Files
Lyrebird/Sources/Lyrebird/AudioDrivers/AUv3Driver.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

515 lines
23 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// AUv3Driver.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if canImport(AudioToolbox)
import Foundation
import AudioToolbox
import AVFoundation
/// `AudioDriver` for AUv3 plugin contexts where the host calls the engine's
/// render path via `internalRenderBlock`. Supports both single-bus AUs and
/// multi-bus AUs (aux output + sidechain input).
///
/// **Single-bus path** (default): one output bus consuming
/// `engine.numOutputChannels` engine buses, optionally one input bus
/// consuming `engine.numInputChannels` engine buses. Used when the AU never
/// calls ``configureBusMap(outputBusChannelCounts:inputBusChannelCounts:)``.
///
/// **Multi-bus path**: ``LyrebirdAudioUnit`` calls ``configureBusMap(outputBusChannelCounts:inputBusChannelCounts:)``
/// before `engine.start()` to declare per-AU-bus channel counts. The driver
/// then maintains per-output-bus ring buffers and per-input-bus host ABL
/// pull buffers. `render(outputBusNumber:...)` reads from the matching ring;
/// `_fillInputStagingFromHost` calls `pullInputBlock` once per input bus per
/// engine block.
///
/// On each `render` call the driver advances the engine in fixed
/// `blockSize`-frame steps via `engine.processBlock(inputSamples:)`,
/// distributes engine output buses across the per-bus rings, and pops the
/// requested `frameCount` frames into the host's `AudioBufferList`. Inherent
/// latency is one engine block (≈5.8 ms at 256-sample blocks / 44.1 kHz).
///
/// All RT-thread state is pre-allocated in `setup`. The render path performs
/// no Swift allocation, no locks, and no ARC retain/release traffic on the
/// engine reference (held via `Unmanaged`).
public final class AUv3Driver: AudioDriver {
// MARK: - Configuration
/// Maximum frames the host may request per render call. Used to size each
/// per-output-bus ring. Set by `LyrebirdAudioUnit.allocateRenderResources`
/// before `engine.start()` triggers `setup(engine:)`. Changing this after
/// `setup` has no effect until the next `setup` call.
public var maxFramesToRender: Int
/// Unmanaged engine reference. Set in `setup(engine:)`, cleared in `stop`.
private var _engineRef: Unmanaged<SynthesisEngine>?
/// Cached engine block size, set in `setup`.
private var _blockSize: Int = 0
/// Cached engine output channel count (sum across all AU output busses).
private var _numOutputChannels: Int = 0
/// Cached engine input channel count (sum across all AU input busses).
private var _numInputChannels: Int = 0
// MARK: - Per-bus map
/// Channel count per AU output bus. Set by ``configureBusMap(outputBusChannelCounts:inputBusChannelCounts:)`` (or
/// derived from engine.numOutputChannels in `setup` for single-bus
/// back-compat).
private var _outputBusChannelCounts: [Int] = []
/// Engine bus index (relative to `engine.audioBuses[0]`) where each AU
/// output bus's channel 0 lives. `_outputBusOffsets[busIndex] +
/// channelOffset` resolves to an absolute engine bus index.
private var _outputBusOffsets: [Int] = []
/// Channel count per AU input bus.
private var _inputBusChannelCounts: [Int] = []
/// Engine bus index where each AU input bus's channel 0 lives. Already
/// absolute (i.e. offset by `numOutputChannels`).
private var _inputBusOffsets: [Int] = []
/// One ring per AU output bus. Sized `2 × max(maxFramesToRender, blockSize)`
/// per channel.
private var _outputRings: [AUv3RingBuffer] = []
/// One pre-allocated AudioBufferList per AU input bus, used to receive
/// the host's `pullInputBlock` output before copying into engine input
/// buses.
private var _hostInputABLs: [UnsafeMutablePointer<AudioBufferList>] = []
/// Per-input-bus contiguous Float backing pointed to by `_hostInputABLs`.
private var _hostInputBackings: [UnsafeMutablePointer<Float>] = []
/// Per-input-bus float backing capacity (in floats).
private var _hostInputBackingFloatCounts: [Int] = []
/// Pre-allocated scratch array of per-channel `Float*` pointers used by
/// `render(...)` to call `ring.read(into:channelCount:count:)`. Sized
/// to the largest output bus's channel count so any bus's render call
/// can be served.
private var _channelPtrScratch: UnsafeMutablePointer<UnsafeMutablePointer<Float>>?
private var _channelPtrScratchCapacity: Int = 0
/// Pre-allocated engine input staging passed to
/// `engine.processBlock(inputSamples:)` once per block when running as an
/// effect AU. Sized `[totalInputChannels][blockSize]`.
private var _inputStagingBuffers: [[Float]] = []
/// Pre-allocated empty input array for instrument-mode AUs.
private let _emptyInput: [[Float]] = []
// MARK: - Init
/// - Parameter maxFramesToRender: Upper bound on `frameCount` the host
/// may request per render call.
public init(maxFramesToRender: Int = auv3DriverDefaultMaxFramesToRender) {
precondition(maxFramesToRender > 0, "maxFramesToRender must be positive")
self.maxFramesToRender = maxFramesToRender
// AUv3 hosts may instantiate the driver before the host process owns
// a SynthesisEngine (e.g. AU-validation passes that exercise render
// without a full engine setup). Force RT-thread-identity TLS key
// initialisation here so the first render callback's
// `markCurrentThreadAsRT()` is a single pthread_setspecific, not
// an `pthread_key_create` on the RT thread.
RTThreadIdentity.warmUp()
}
deinit {
_channelPtrScratch?.deallocate()
for abl: UnsafeMutablePointer<AudioBufferList> in _hostInputABLs {
UnsafeMutableRawPointer(abl).deallocate()
}
for c: Int in 0..<_hostInputBackings.count {
_hostInputBackings[c].deinitialize(count: _hostInputBackingFloatCounts[c])
_hostInputBackings[c].deallocate()
}
}
// MARK: - Bus map configuration
/// Declare per-bus channel counts before `engine.start()` triggers
/// `setup(engine:)`. The driver allocates one output ring per output bus
/// and one input ABL per input bus during `setup`.
///
/// **Bus → engine offset mapping.** Output bus `i` occupies engine bus
/// indices `[Σ counts[0..<i], Σ counts[0..<i+1])`. Input bus `i`
/// occupies engine bus indices `[numOutputChannels + Σ inputCounts[0..<i],
/// numOutputChannels + Σ inputCounts[0..<i+1])`.
///
/// Called by `LyrebirdAudioUnit.allocateRenderResources` before
/// `engine.start()`. If never called, `setup(engine:)` derives a
/// single-bus configuration from `engine.numOutputChannels` /
/// `engine.numInputChannels` for backward compatibility.
///
/// - Parameters:
/// - outputBusChannelCounts: Per-output-bus channel counts. Must sum
/// to `engine.numOutputChannels`. Must contain at least one entry.
/// - inputBusChannelCounts: Per-input-bus channel counts. Empty for
/// instrument AUs. Must sum to `engine.numInputChannels` when
/// non-empty.
public func configureBusMap(
outputBusChannelCounts: [Int],
inputBusChannelCounts: [Int]
) {
precondition(!outputBusChannelCounts.isEmpty,
"AUv3Driver: at least one output bus required")
_outputBusChannelCounts = outputBusChannelCounts
_inputBusChannelCounts = inputBusChannelCounts
var off: Int = 0
var outOffsets: [Int] = []
outOffsets.reserveCapacity(outputBusChannelCounts.count)
for n: Int in outputBusChannelCounts {
outOffsets.append(off)
off += n
}
_outputBusOffsets = outOffsets
// Input offsets start at numOutputChannels — resolved in setup once
// engine.numOutputChannels is known. Store the running sum here.
var inOff: Int = 0
var inOffsets: [Int] = []
inOffsets.reserveCapacity(inputBusChannelCounts.count)
for n: Int in inputBusChannelCounts {
inOffsets.append(inOff)
inOff += n
}
_inputBusOffsets = inOffsets
}
// MARK: - AudioDriver
public func setup(engine: SynthesisEngine) throws {
_engineRef = Unmanaged.passUnretained(engine)
_blockSize = engine.blockSize
_numOutputChannels = engine.numOutputChannels
_numInputChannels = engine.numInputChannels
// Single-bus back-compat: if no map configured, derive from engine.
if _outputBusChannelCounts.isEmpty {
_outputBusChannelCounts = [engine.numOutputChannels]
_outputBusOffsets = [0]
}
if _inputBusChannelCounts.isEmpty {
if engine.numInputChannels > 0 {
_inputBusChannelCounts = [engine.numInputChannels]
_inputBusOffsets = [0]
}
}
// Translate stored input offsets into absolute engine bus indices.
// The map was stored relative to the start of the input area.
for i: Int in 0..<_inputBusOffsets.count {
_inputBusOffsets[i] = engine.numOutputChannels + _inputBusOffsets[i]
}
// Per-bus rings double-buffer the engine output so the host can pull
// a bus N times for every M engine advances without the ring
// saturating mid-render. The `auv3RingBufferHeadroomFactor` constant
// controls how much over-headroom each bus carries vs. the larger of
// `maxFramesToRender` and the engine `blockSize`.
let ringCapacity: Int = auv3RingBufferHeadroomFactor * max(maxFramesToRender, engine.blockSize)
_outputRings = []
_outputRings.reserveCapacity(_outputBusChannelCounts.count)
var maxBusChannels: Int = 0
for nch: Int in _outputBusChannelCounts {
_outputRings.append(AUv3RingBuffer(channelCount: nch, capacity: ringCapacity))
if nch > maxBusChannels { maxBusChannels = nch }
}
// Channel-pointer scratch sized to the largest output bus so any bus's
// render call can stage its destination pointers in one shot.
if _channelPtrScratchCapacity < maxBusChannels {
_channelPtrScratch?.deallocate()
let buf: UnsafeMutablePointer<UnsafeMutablePointer<Float>> = UnsafeMutablePointer<UnsafeMutablePointer<Float>>.allocate(
capacity: maxBusChannels
)
_channelPtrScratch = buf
_channelPtrScratchCapacity = maxBusChannels
}
// Engine input staging — one row per engine input channel.
if engine.numInputChannels > 0 {
_inputStagingBuffers = [[Float]](
repeating: [Float](repeating: 0, count: engine.blockSize),
count: engine.numInputChannels
)
} else {
_inputStagingBuffers = []
}
// Allocate one host-input ABL per input bus.
_deallocateHostInputABLs()
for nch: Int in _inputBusChannelCounts {
_allocateHostInputABL(channels: nch, framesPerChannel: engine.blockSize)
}
}
private func _allocateHostInputABL(channels: Int, framesPerChannel: Int) {
let ablBytes: Int = AudioBufferList.sizeInBytes(maximumBuffers: channels)
let ablRaw: UnsafeMutableRawPointer = UnsafeMutableRawPointer.allocate(
byteCount: ablBytes,
alignment: MemoryLayout<AudioBufferList>.alignment
)
let ablPtr: UnsafeMutablePointer<AudioBufferList> = ablRaw.assumingMemoryBound(to: AudioBufferList.self)
let floatsTotal: Int = channels * framesPerChannel
let backing: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: floatsTotal)
backing.initialize(repeating: 0, count: floatsTotal)
let abl: UnsafeMutableAudioBufferListPointer = UnsafeMutableAudioBufferListPointer(ablPtr)
abl.unsafeMutablePointer.pointee.mNumberBuffers = UInt32(channels)
let byteSize: UInt32 = UInt32(framesPerChannel) * lyrebirdBytesPerSample
for c: Int in 0..<channels {
abl[c] = AudioBuffer(
mNumberChannels: 1,
mDataByteSize: byteSize,
mData: UnsafeMutableRawPointer(backing.advanced(by: c * framesPerChannel))
)
}
_hostInputABLs.append(ablPtr)
_hostInputBackings.append(backing)
_hostInputBackingFloatCounts.append(floatsTotal)
}
private func _deallocateHostInputABLs() {
for abl: UnsafeMutablePointer<AudioBufferList> in _hostInputABLs {
UnsafeMutableRawPointer(abl).deallocate()
}
for c: Int in 0..<_hostInputBackings.count {
_hostInputBackings[c].deinitialize(count: _hostInputBackingFloatCounts[c])
_hostInputBackings[c].deallocate()
}
_hostInputABLs = []
_hostInputBackings = []
_hostInputBackingFloatCounts = []
}
public func start() throws {
// No-op: AU host drives rendering via `render(...)`.
}
public func stop() {
_engineRef = nil
for ring: AUv3RingBuffer in _outputRings { ring.reset() }
}
public var suggestedControlBlockSize: Int? { lyrebirdDefaultControlBlockSize }
// MARK: - Host render entry point
/// Pulls `frameCount` frames into the host's output `AudioBufferList` for
/// the AU output bus identified by `outputBusNumber`.
///
/// **RT-thread.** Called from `LyrebirdAudioUnit.internalRenderBlock` on
/// the AU host's audio thread. Allocation-free; engine reference is
/// taken via `Unmanaged.takeUnretainedValue()` (no ARC traffic).
///
/// - Parameters:
/// - frameCount: Number of frames the host wants per channel.
/// - outputBusNumber: Which declared AU output bus the host is asking
/// for. Multi-bus AUs receive one render call per bus per cycle.
/// - outputData: AU host's output `AudioBufferList` for the specified
/// bus. Each buffer is a non-interleaved Float32 channel.
/// - timestamp: Host-supplied `AudioTimeStamp` passed through to
/// `pullInput` for effect-AU input. Ignored for instrument-AUs.
/// - pullInput: Host's `AURenderPullInputBlock` (or `nil` for
/// instrument-AUs). The driver calls it once per input bus per
/// engine block.
/// - Returns: `noErr` on success; `kAudioUnitErr_Uninitialized` if
/// `setup` has not been called; `kAudioUnitErr_TooManyFramesToProcess`
/// if `frameCount` exceeds `maxFramesToRender`;
/// `kAudioUnitErr_InvalidParameterValue` if the AU bus number is out
/// of range or the host's ABL is malformed; the host's status code
/// if `pullInput` fails for an effect-AU.
public func render(
frameCount: Int,
outputBusNumber: Int = 0,
outputData: UnsafeMutablePointer<AudioBufferList>,
timestamp: UnsafePointer<AudioTimeStamp>? = nil,
pullInput: AURenderPullInputBlock? = nil
) -> AUAudioUnitStatus {
RTThreadIdentity.markCurrentThreadAsRT()
guard let engineRef: Unmanaged<SynthesisEngine> = _engineRef,
let scratch: UnsafeMutablePointer<UnsafeMutablePointer<Float>> = _channelPtrScratch else {
return kAudioUnitErr_Uninitialized
}
guard frameCount <= maxFramesToRender else {
return kAudioUnitErr_TooManyFramesToProcess
}
guard outputBusNumber >= 0,
outputBusNumber < _outputRings.count else {
return kAudioUnitErr_InvalidParameterValue
}
let engine: SynthesisEngine = engineRef.takeUnretainedValue()
let isEffectAU: Bool = _numInputChannels > 0
let busRing: AUv3RingBuffer = _outputRings[outputBusNumber]
// Advance engine until the requested bus's ring holds enough frames.
// Engine output is distributed across all per-bus rings on every
// block — buses that aren't being pulled this cycle accumulate
// samples for their next render call.
while busRing.availableToRead < frameCount {
if isEffectAU {
let status: AUAudioUnitStatus = _fillInputStagingFromHost(
timestamp: timestamp,
pullInput: pullInput
)
if status != noErr { return status }
engine.processBlock(inputSamples: _inputStagingBuffers)
} else {
engine.processBlock(inputSamples: _emptyInput)
}
_distributeEngineOutputToRings(engine: engine)
}
// Pop into the host's AudioBufferList for this bus.
let abl: UnsafeMutableAudioBufferListPointer = UnsafeMutableAudioBufferListPointer(outputData)
let busChannels: Int = _outputBusChannelCounts[outputBusNumber]
let copyChannels: Int = min(abl.count, busChannels)
for c: Int in 0..<copyChannels {
guard let raw: UnsafeMutableRawPointer = abl[c].mData else {
return kAudioUnitErr_InvalidParameterValue
}
scratch[c] = raw.assumingMemoryBound(to: Float.self)
}
if copyChannels > 0 {
busRing.read(into: scratch, channelCount: copyChannels, count: frameCount)
}
let byteSize: UInt32 = UInt32(frameCount) * lyrebirdBytesPerSample
for c: Int in 0..<abl.count {
abl[c].mDataByteSize = byteSize
}
return noErr
}
/// Pushes one engine block's worth of output into every per-AU-bus ring,
/// drawing the matching channel slice from `engine.audioBuses` at the
/// configured offsets.
///
/// **Saturation policy.** The AU spec does not require hosts to render
/// every output bus on every cycle — a host may pull bus 0 ten times
/// while leaving bus 1 idle. In that case bus 1's ring would saturate
/// after `capacity / blockSize` engine advances. To avoid a precondition
/// crash on the RT thread we drop the oldest block from any ring that
/// cannot accept the new frames: the ring is reset before the write,
/// so the abandoned bus always holds the freshest block available when
/// the host eventually pulls it. Documented behaviour: hosts that
/// neglect a bus for `> 2× capacity / blockSize` cycles will hear a
/// discontinuity in that bus when they next pull it. Typical hosts
/// pull all declared buses synchronously and never trigger this path.
private func _distributeEngineOutputToRings(engine: SynthesisEngine) {
for busIndex: Int in 0..<_outputRings.count {
let ring: AUv3RingBuffer = _outputRings[busIndex]
let offset: Int = _outputBusOffsets[busIndex]
let channelCount: Int = _outputBusChannelCounts[busIndex]
if ring.availableToWrite < _blockSize {
ring.reset()
}
ring.write(
fromAudioBuses: engine.audioBuses,
sourceBusOffset: offset,
channelCount: channelCount,
count: _blockSize
)
}
}
/// Pulls one engine block of input from the host. For multi-input-bus
/// AUs, calls `pullInput` once per declared input bus and copies the
/// host samples into the matching slice of `_inputStagingBuffers`.
/// If `pullInput` is nil (host did not provide a pull block), the
/// staging buffers are zero-filled.
private func _fillInputStagingFromHost(
timestamp: UnsafePointer<AudioTimeStamp>?,
pullInput: AURenderPullInputBlock?
) -> AUAudioUnitStatus {
guard let pullInput: AURenderPullInputBlock else {
// No host input available — feed silence so the engine still
// advances.
for c: Int in 0..<_inputStagingBuffers.count {
_inputStagingBuffers[c].withUnsafeMutableBufferPointer { buf in
guard let base: UnsafeMutablePointer<Float> = buf.baseAddress else { return }
for i: Int in 0..<_blockSize { base[i] = 0 }
}
}
return noErr
}
let frames: AUAudioFrameCount = AUAudioFrameCount(_blockSize)
var stagingCursor: Int = 0
for busIndex: Int in 0..<_inputBusChannelCounts.count {
let busChannels: Int = _inputBusChannelCounts[busIndex]
let inputABL: UnsafeMutablePointer<AudioBufferList> = _hostInputABLs[busIndex]
var flags: AudioUnitRenderActionFlags = []
let status: AUAudioUnitStatus
if let ts: UnsafePointer<AudioTimeStamp> = timestamp {
status = pullInput(&flags, ts, frames, busIndex, inputABL)
} else {
var defaultTs: AudioTimeStamp = AudioTimeStamp()
status = withUnsafePointer(to: &defaultTs) { tsPtr in
pullInput(&flags, tsPtr, frames, busIndex, inputABL)
}
}
if status != noErr { return status }
let abl: UnsafeMutableAudioBufferListPointer = UnsafeMutableAudioBufferListPointer(inputABL)
let copyChannels: Int = min(abl.count, busChannels)
for c: Int in 0..<copyChannels {
guard let raw: UnsafeMutableRawPointer = abl[c].mData else { continue }
let src: UnsafeMutablePointer<Float> = raw.assumingMemoryBound(to: Float.self)
let stagingIdx: Int = stagingCursor + c
guard stagingIdx < _inputStagingBuffers.count else { break }
_inputStagingBuffers[stagingIdx].withUnsafeMutableBufferPointer { buf in
guard let dst: UnsafeMutablePointer<Float> = buf.baseAddress else { return }
for i: Int in 0..<_blockSize { dst[i] = src[i] }
}
}
// Zero any extra staging channels the host didn't fill for this bus.
for c: Int in copyChannels..<busChannels {
let stagingIdx: Int = stagingCursor + c
guard stagingIdx < _inputStagingBuffers.count else { break }
_inputStagingBuffers[stagingIdx].withUnsafeMutableBufferPointer { buf in
guard let base: UnsafeMutablePointer<Float> = buf.baseAddress else { return }
for i: Int in 0..<_blockSize { base[i] = 0 }
}
}
stagingCursor += busChannels
}
return noErr
}
/// Engine reference exposed for testing.
internal var _engineForTesting: SynthesisEngine? {
_engineRef?.takeUnretainedValue()
}
/// First output ring exposed for testing.
internal var _ringForTesting: AUv3RingBuffer? { _outputRings.first }
/// Per-output-bus rings exposed for testing.
internal var _outputRingsForTesting: [AUv3RingBuffer] { _outputRings }
/// Engine bus offset map exposed for testing.
internal var _outputBusOffsetsForTesting: [Int] { _outputBusOffsets }
internal var _inputBusOffsetsForTesting: [Int] { _inputBusOffsets }
}
/// Default `maximumFramesToRender` for AUv3 plugin contexts.
public let auv3DriverDefaultMaxFramesToRender: Int = 1024
/// Headroom multiplier applied to each per-bus output ring buffer's
/// capacity. A factor of `2` lets the engine produce one block of output
/// for a bus while the host is mid-pull on another bus without saturating
/// the ring. Larger values give more slack for hosts that pull busses
/// asynchronously at the cost of memory.
public let auv3RingBufferHeadroomFactor: Int = 2
#endif