Files
Lyrebird/docs/engine/core-audio-driver.md
T
2026-06-01 18:27:40 -07:00

9.3 KiB
Raw Blame History

CoreAudioDriver — Pending Fixes

Sources/Lyrebird/AudioDrivers/CoreAudioDriver.swift


Blocking Issues (must fix before next merge to main)

1. print() on the RT thread — lines 764–767

// CURRENT (broken)
if renderStatus != noErr && debugBlockCount < 3 {
    print("ERROR: AudioUnitRender failed with status \(renderStatus)")
    debugBlockCount += 1
}

Fix: Replace with an Atomic<Int32> that stores the last error code. The main thread can inspect it later (e.g. in a debug accessor), but the RT thread never allocates or calls print.

// After the property declarations:
private let _lastInputRenderError = Atomic<Int32>(noErr)

// In render():
if renderStatus != noErr {
    _lastInputRenderError.store(renderStatus, ordering: .relaxed)
}

Remove debugBlockCount entirely.


2. Non-atomic isInitialized — data race between start()/stop() and render()

// CURRENT (broken)
private var isInitialized: Bool = false   // plain Bool — no ordering guarantee

start() and stop() run on the main thread; render() reads isInitialized on the RT thread. This is an unsynchronised read/write pair — undefined behaviour under Swift's memory model.

Fix:

private let _isInitialized = Atomic<Bool>(false)
  • start(): _isInitialized.store(true, ordering: .releasing) (after AudioUnitInitialize)
  • stop(): _isInitialized.store(false, ordering: .releasing)
  • render(): _isInitialized.load(ordering: .acquiring)
  • deinit: _isInitialized.store(false, ordering: .releasing) before unit disposal

3. Per-sample input copy loop — unnecessary overhead

// CURRENT
for i in 0..<frameCount {
    inputStagingBuffers[ch][i] = rawPtr[i]
}

Fix: Replace with memcpy. The raw pointer and staging buffer are already Float arrays of the correct size.

inputStagingBuffers[ch].withUnsafeMutableBufferPointer { dst in
    guard let base = dst.baseAddress else { return }
    memcpy(base, rawPtr, frameCount * MemoryLayout<Float>.size)
}

Non-Blocking Issues (clean-up, no correctness impact today)

4. Remove all print() / DEBUG: / ERROR: calls from setup()

There are approximately 30 print() calls throughout setup() that were scaffolding. They allocate String instances and should be removed entirely. If diagnostics are needed in the future, use os_log with .debug level (compile-time stripped in release builds).


5. Replace string-matching device selection with transport-type query

The current "last resort" device scan (lines 326–467) uses fragile string matching:

nameLower.contains("built-in")
nameLower.contains("macbook")
nameLower.contains("teams")   // blocklist
nameLower.contains("zoom")    // blocklist

This breaks under non-English locales and any device whose name doesn't match the expected patterns.

Fix: Query kAudioDevicePropertyTransportType and compare against kAudioDeviceTransportTypeBuiltIn. No string allocation, locale-independent.

private func deviceTransportType(_ deviceID: AudioDeviceID) -> UInt32 {
    var transportType: UInt32 = 0
    var size = UInt32(MemoryLayout<UInt32>.size)
    var addr = AudioObjectPropertyAddress(
        mSelector: kAudioDevicePropertyTransportType,
        mScope: kAudioObjectPropertyScopeGlobal,
        mElement: kAudioObjectPropertyElementMain
    )
    AudioObjectGetPropertyData(deviceID, &addr, 0, nil, &size, &transportType)
    return transportType
}

Device selection order (replaces the current chain of if/else blocks):

  1. defaultOutputID == defaultInputID → use directly (ideal: USB headset, aggregate already set in system prefs)
  2. defaultOutputID has ≥ numInputChannels input channels → use it
  3. defaultInputID has ≥ numOutputChannels output channels → use it
  4. Enumerate all devices; pick the first with transportType == kAudioDeviceTransportTypeBuiltIn that has both input and output → findBuiltInDuplexDevice()
  5. Fall through to aggregate device creation (see §6)

6. Programmatic Aggregate Device creation

When no single device satisfies full-duplex requirements (step 5 above falls through), create a private CoreAudio Aggregate Device rather than throwing an error.

New error cases to add to CoreAudioError:

case aggregateDeviceCreationFailed(OSStatus)
case microphoneAccessDenied

New stored properties:

private var aggregateDeviceID: AudioDeviceID = AudioDeviceID(kAudioObjectUnknown)
private var coreAudioPluginID: AudioObjectID = AudioObjectID(kAudioObjectUnknown)

Step A — find the CoreAudio HAL plugin object:

private func findCoreAudioPluginID() -> AudioObjectID {
    // Uses AudioValueTranslation to resolve bundle ID → AudioObjectID
    let bundleID = "com.apple.audio.CoreAudio" as CFString
    var pluginID = AudioObjectID(kAudioObjectUnknown)
    var translation = AudioValueTranslation(
        mInputData: UnsafeMutableRawPointer(mutating: &bundleID as AnyObject as! UnsafeRawPointer),
        mInputDataSize: UInt32(MemoryLayout<CFString>.size),
        mOutputData: &pluginID,
        mOutputDataSize: UInt32(MemoryLayout<AudioObjectID>.size)
    )
    var addr = AudioObjectPropertyAddress(
        mSelector: kAudioHardwarePropertyPlugInForBundleID,
        mScope: kAudioObjectPropertyScopeGlobal,
        mElement: kAudioObjectPropertyElementMain
    )
    var size = UInt32(MemoryLayout<AudioValueTranslation>.size)
    AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &addr, 0, nil, &size, &translation)
    return pluginID
}

Step B — create the aggregate:

private func makeAggregateDevice(
    outputDeviceID: AudioDeviceID,
    inputDeviceID: AudioDeviceID
) throws -> AudioDeviceID {
    coreAudioPluginID = findCoreAudioPluginID()
    guard coreAudioPluginID != kAudioObjectUnknown else {
        throw CoreAudioError.aggregateDeviceCreationFailed(noErr)
    }

    // Get UIDs for both devices
    let outputUID = try deviceUID(outputDeviceID)
    let inputUID  = try deviceUID(inputDeviceID)

    // Build the composition dictionary
    // 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,
        kAudioAggregateDeviceMasterSubDeviceKey: outputUID,
        kAudioAggregateDeviceIsPrivateKey:     1,   // auto-destroyed when plugin releases it
        kAudioAggregateDeviceIsStackedKey:     0,
    ]

    var newDeviceID = AudioDeviceID(kAudioObjectUnknown)
    var addr = AudioObjectPropertyAddress(
        mSelector: kAudioPlugInCreateAggregateDevice,
        mScope: kAudioObjectPropertyScopeGlobal,
        mElement: kAudioObjectPropertyElementMain
    )
    let qualifier = aggDesc as CFDictionary
    var size = UInt32(MemoryLayout<AudioDeviceID>.size)
    let status = AudioObjectGetPropertyData(
        coreAudioPluginID, &addr,
        UInt32(MemoryLayout<CFDictionary>.size), [qualifier] as AnyObject,
        &size, &newDeviceID
    )
    guard status == noErr else { throw CoreAudioError.aggregateDeviceCreationFailed(status) }
    aggregateDeviceID = newDeviceID
    return newDeviceID
}

Step C — destroy on stop() and deinit:

private func destroyAggregateDevice() {
    guard aggregateDeviceID != AudioDeviceID(kAudioObjectUnknown),
          coreAudioPluginID != AudioObjectID(kAudioObjectUnknown) else { return }
    var addr = AudioObjectPropertyAddress(
        mSelector: kAudioPlugInDestroyAggregateDevice,
        mScope: kAudioObjectPropertyScopeGlobal,
        mElement: kAudioObjectPropertyElementMain
    )
    var deviceID = aggregateDeviceID
    var size = UInt32(MemoryLayout<AudioDeviceID>.size)
    AudioObjectSetPropertyData(coreAudioPluginID, &addr, 0, nil, size, &deviceID)
    aggregateDeviceID = AudioDeviceID(kAudioObjectUnknown)
}

Call destroyAggregateDevice() at the top of stop() (before AudioOutputUnitStop) and in deinit.


7. Named constant for bytes-per-sample

The literal 4 appears in six AudioStreamBasicDescription initialisers.

private let lyrebirdBytesPerSample: UInt32 = 4   // 32-bit float = 4 bytes

8. Microphone permission — throw instead of print

// CURRENT
} else if authStatus == .denied || authStatus == .restricted {
    print("ERROR: Microphone access denied...")
}

Fix: Throw CoreAudioError.microphoneAccessDenied so the caller can surface it to the user.


Implementation Order

  1. Fix §1 (_lastInputRenderError + remove debugBlockCount) — blocking RT issue
  2. Fix §2 (_isInitialized → Atomic<Bool>) — blocking data race
  3. Fix §3 (memcpy) — trivial, same block
  4. Fix §8 (throw on mic denied) — small change, clear error contract
  5. Fix §7 (named constant) — cosmetic, do while touching ASBD initialisers
  6. Fix §4 (remove all print() from setup())
  7. Fix §5 (transport-type device selection)
  8. Fix §6 (aggregate device creation) — largest change; implement last

Run /lyrebird_review after all eight steps are complete.