// LyrebirdAudioUnit.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation import AVFoundation import AudioToolbox import Synchronization /// Default placeholder sample rate used by `LyrebirdAudioUnit` before the host /// commits a rate via `allocateRenderResources`. The AU exposes this on its /// output bus's initial `AVAudioFormat`; the host re-negotiates if it wants a /// different rate. public let lyrebirdAUDefaultSampleRate: Double = 44100.0 /// Default name for the single-bus output bus when a `LyrebirdAudioUnit` /// subclass does not override ``LyrebirdAudioUnit/lyrebirdOutputBusses``. public let lyrebirdAUDefaultOutputBusName: String = "Output" /// Default name for the single-bus input bus when a `LyrebirdAudioUnit` /// subclass does not override ``LyrebirdAudioUnit/lyrebirdInputBusses`` /// and `lyrebirdInputChannels > 0`. public let lyrebirdAUDefaultInputBusName: String = "Input" /// Open AU base class that bridges a `SynthesizerBase` subclass and a /// `SynthesisEngine` into an `AUAudioUnit` the host can host. /// /// **Subclass pattern.** Override `makeSynthesizer()` to return your synth /// instance, optionally override `parameterMetadata()` to attach `min` / `max` / /// `unit` hints to your `@LiveParam` slots, and that is enough for a working /// instrument plugin: /// /// ```swift /// public final class MyFMSynthAudioUnit: LyrebirdAudioUnit { /// public override class func makeSynthesizer() -> SynthesizerBase { /// MyFMSynth() /// } /// public override class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] { /// [ /// "freq": .init(min: 20, max: 8000, unit: .hertz), /// "amp": .init(min: 0, max: 1, unit: .linearGain), /// "modIndex": .init(min: 0, max: 4), /// ] /// } /// } /// ``` /// /// **Effect AUs.** Override `lyrebirdInputChannels` to return a positive value /// to declare an input bus and receive host audio. The synth's `build()` reads /// from the host input via ``AUInput``: /// /// ```swift /// override func build() { /// let inputLeft = AUInput.Audio(channel: 0) /// let inputRight = AUInput.Audio(channel: 1) /// let wet = FreeVerb.Audio(input: inputLeft + inputRight) * $wetMix /// output(bus: 0, source: wet[0] + inputLeft * (1 - $wetMix)) /// output(bus: 1, source: wet[1] + inputRight * (1 - $wetMix)) /// } /// ``` /// /// **MIDI input.** Set `midiHandler` to a closure that receives /// ``MIDIMessage`` events parsed from the AU host's render-event chain. Default /// is `nil` (silently ignored). For voice-pool integration use /// ``LyrebirdAUVoicePoolBinding`` to wire `noteOn` / `noteOff` to a /// `VoicePool` instance. /// /// **Presets.** Override `factoryPresets()` to return a list of named presets /// the host can offer in its preset menu. Read / write `currentPreset` to apply /// or materialise a preset. /// /// **Lifecycle.** The synth is constructed once during `init`; its `@LiveParam` /// slots are inspected to build the AU parameter tree. The engine is constructed /// in `allocateRenderResources` so it can adopt the host-negotiated sample rate, /// and torn down in `deallocateRenderResources`. open class LyrebirdAudioUnit: AUAudioUnit { // MARK: - Subclass hooks /// Required override. Construct and return the synthesizer instance that this /// AU should host. /// /// `@MainActor`: the override constructs a `@MainActor` `SynthesizerBase` /// subclass, so the factory must be main-actor-isolated for a consumer building under /// the MainActor-default mode to override it with no concurrency annotations — the same /// rationale as `SynthesizerBase.build()`. Invoked from `init` on the host's main thread. @MainActor open class func makeSynthesizer() -> SynthesizerBase { fatalError("LyrebirdAudioUnit subclasses must override `makeSynthesizer()`") } /// Optional override. Returns per-parameter metadata (min/max/unit/display name) /// keyed by `@LiveParam` property name. open class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] { [:] } /// Engine block size. Defaults to `lyrebirdAUDefaultBlockSize` (256). Must be a /// power of two ≤ `lyrebirdDefaultResultBufferSize` (512). open class var lyrebirdBlockSize: Int { lyrebirdAUDefaultBlockSize } /// Output channel count for a single-output-bus AU. Defaults to `2` /// (stereo). Ignored when ``lyrebirdOutputBusses`` is overridden to /// declare more than one bus. open class var lyrebirdOutputChannels: Int { 2 } /// Input channel count for a single-input-bus effect AU. Defaults to /// `0` (instrument AU — no input bus). Ignored when /// ``lyrebirdInputBusses`` is overridden to declare a non-empty list. open class var lyrebirdInputChannels: Int { 0 } /// Output bus declarations. Defaults to a single bus named "Output" /// with ``lyrebirdOutputChannels`` channels — the canonical single-bus /// shape. Override to declare multiple output busses (FX sends, stem /// outs, etc.). /// /// ```swift /// public override class var lyrebirdOutputBusses: [LyrebirdAUBusSpec] { /// [ /// .init(name: "Main", channelCount: 2), /// .init(name: "FX Send", channelCount: 2), /// ] /// } /// ``` /// /// Engine bus layout: bus 0 occupies engine channels /// `[0, busses[0].channelCount)`, bus 1 occupies /// `[busses[0].channelCount, busses[0].channelCount + /// busses[1].channelCount)`, etc. Synthesizer `build()` continues to /// use `output(bus: N, source:)` with the absolute engine bus index; /// helpers / docs explain the mapping per subclass. open class var lyrebirdOutputBusses: [LyrebirdAUBusSpec] { [LyrebirdAUBusSpec(name: lyrebirdAUDefaultOutputBusName, channelCount: lyrebirdOutputChannels)] } /// Input bus declarations. Defaults to a single bus named "Input" /// with ``lyrebirdInputChannels`` channels when /// `lyrebirdInputChannels > 0`, otherwise an empty array (instrument). /// Override to declare multiple input busses — typically main + /// sidechain. /// /// ```swift /// public override class var lyrebirdInputBusses: [LyrebirdAUBusSpec] { /// [ /// .init(name: "Main In", channelCount: 2), /// .init(name: "Sidechain", channelCount: 2), /// ] /// } /// ``` /// /// ``AUInput/Audio/init(busIndex:channel:)`` reads from a specific AU /// input bus regardless of bus order. open class var lyrebirdInputBusses: [LyrebirdAUBusSpec] { lyrebirdInputChannels > 0 ? [LyrebirdAUBusSpec(name: lyrebirdAUDefaultInputBusName, channelCount: lyrebirdInputChannels)] : [] } /// Initial `maximumFramesToRender`. Host may override this via the /// `maximumFramesToRender` setter before `allocateRenderResources`. open class var lyrebirdMaxFramesToRender: AUAudioFrameCount { AUAudioFrameCount(auv3DriverDefaultMaxFramesToRender) } /// Optional override. Returns factory presets the host can show in its preset /// menu. Each entry's `parameters` dictionary is applied via the same path /// `fullState` setter uses — scalar `@LiveParam` values map directly. Source /// slots are restored if the parameter is registered via /// ``LyrebirdAUPresetSourceRegistry``. /// /// Default returns an empty array (no factory presets). open class func factoryPresetsForLyrebird() -> [LyrebirdAUFactoryPreset] { [] } // MARK: - Public state /// The synthesizer hosted by this AU. Lifetime matches the AU itself. public final let synthesizer: SynthesizerBase /// AUv3 driver — passive, host-driven render path. public final let driver: AUv3Driver /// Currently active synthesis engine. `nil` until `allocateRenderResources` /// is called; re-created each cycle to adopt the host's sample rate. public final private(set) var engine: SynthesisEngine? /// MIDI dispatch callback invoked from the render thread for every /// `AURenderEvent` of type `.MIDI` in the host's event chain. **The /// closure runs on the audio thread** — it must obey all RT rules (no /// allocation, no locks, no `print`). Typical use: bridge to a /// ``LyrebirdAUVoicePoolBinding`` via an SPSC queue or CoreMIDI loop /// (see the voice-pool-binding docs for the bridging patterns). /// /// **Threading.** Set on the main thread. The setter writes through an /// `Atomic` pointer (acquire/release ordering) so the render /// thread observes a fully-initialised closure or no closure at all — /// never a torn read. The previous handler box (if any) is released on /// the main thread when the setter returns. public final var midiHandler: ((MIDIMessage, AUEventSampleTime) -> Void)? { get { _midiHandlerStorage.currentHandler() } set { _midiHandlerStorage.setHandler(newValue) } } // MARK: - AU base-class overrides (storage) private let _parameterTree: AUParameterTree private let _parameterNodes: [AUParameterAddress: any LiveParameterValue] private let _outputBuses: [AUAudioUnitBus] private let _inputBuses: [AUAudioUnitBus] private let _outputBusSpecs: [LyrebirdAUBusSpec] private let _inputBusSpecs: [LyrebirdAUBusSpec] private let _outputBusOffsets: [Int] private let _inputBusOffsets: [Int] private var _outputBusArrayBacking: AUAudioUnitBusArray? private var _inputBusArrayBacking: AUAudioUnitBusArray? private let _renderBlock: AUInternalRenderBlock private let _blockSize: Int private let _totalOutputChannels: Int private let _totalInputChannels: Int private let _midiHandlerStorage: _MIDIHandlerStorage // MARK: - Init public override init( componentDescription: AudioComponentDescription, options: AudioComponentInstantiationOptions = [] ) throws { // 1. Resolve subclass configuration. // `makeSynthesizer()` is `@MainActor` (it builds a `@MainActor` synth); `AUAudioUnit` // instances are created by the host on the main thread, so `assumeIsolated` is valid. let synth: SynthesizerBase = MainActor.assumeIsolated { Self.makeSynthesizer() } let blockSize: Int = Self.lyrebirdBlockSize let outputBusSpecs: [LyrebirdAUBusSpec] = Self.lyrebirdOutputBusses let inputBusSpecs: [LyrebirdAUBusSpec] = Self.lyrebirdInputBusses precondition( blockSize > 0 && (blockSize & (blockSize - 1)) == 0, "lyrebirdBlockSize \(blockSize) must be a power of two" ) precondition( blockSize <= lyrebirdDefaultResultBufferSize, "lyrebirdBlockSize \(blockSize) exceeds lyrebirdDefaultResultBufferSize \(lyrebirdDefaultResultBufferSize)" ) precondition(!outputBusSpecs.isEmpty, "lyrebirdOutputBusses must declare at least one output bus") // Sum channels + build per-bus engine offset maps. Output busses // occupy engine bus indices [0, totalOutput). Input busses occupy // [totalOutput, totalOutput + totalInput). var totalOutputChannels: Int = 0 var outputBusOffsets: [Int] = [] outputBusOffsets.reserveCapacity(outputBusSpecs.count) for spec: LyrebirdAUBusSpec in outputBusSpecs { outputBusOffsets.append(totalOutputChannels) totalOutputChannels += spec.channelCount } var totalInputChannels: Int = 0 var inputBusOffsets: [Int] = [] inputBusOffsets.reserveCapacity(inputBusSpecs.count) for spec: LyrebirdAUBusSpec in inputBusSpecs { inputBusOffsets.append(totalOutputChannels + totalInputChannels) totalInputChannels += spec.channelCount } let driver: AUv3Driver = AUv3Driver(maxFramesToRender: Int(Self.lyrebirdMaxFramesToRender)) // 2. Build the parameter tree before super.init. The @LiveParam wrappers // on `synth` exist as soon as the synth is constructed; no engine // interaction is required for Mirror discovery. let (tree, nodes) = LyrebirdAUParameterMapping.buildParameterTree( for: synth, metadata: Self.parameterMetadata() ) // 3. Build one AUAudioUnitBus per output spec. var outputBuses: [AUAudioUnitBus] = [] outputBuses.reserveCapacity(outputBusSpecs.count) for spec: LyrebirdAUBusSpec in outputBusSpecs { guard let format: AVAudioFormat = AVAudioFormat( standardFormatWithSampleRate: lyrebirdAUDefaultSampleRate, channels: AVAudioChannelCount(spec.channelCount) ) else { throw LyrebirdAudioUnitError.invalidStreamFormat } let bus: AUAudioUnitBus = try AUAudioUnitBus(format: format) bus.maximumChannelCount = AVAudioChannelCount(spec.channelCount) outputBuses.append(bus) } // 4. Build one AUAudioUnitBus per input spec (empty for instruments). var inputBuses: [AUAudioUnitBus] = [] inputBuses.reserveCapacity(inputBusSpecs.count) for spec: LyrebirdAUBusSpec in inputBusSpecs { guard let format: AVAudioFormat = AVAudioFormat( standardFormatWithSampleRate: lyrebirdAUDefaultSampleRate, channels: AVAudioChannelCount(spec.channelCount) ) else { throw LyrebirdAudioUnitError.invalidStreamFormat } let bus: AUAudioUnitBus = try AUAudioUnitBus(format: format) bus.maximumChannelCount = AVAudioChannelCount(spec.channelCount) inputBuses.append(bus) } // 5. Construct the RT render block before super.init. Captures the driver // via Unmanaged so the closure performs no ARC retain/release on the // audio thread. let midiStorage: _MIDIHandlerStorage = _MIDIHandlerStorage() let driverRef: Unmanaged = Unmanaged.passUnretained(driver) let renderBlock: AUInternalRenderBlock = { (_, timestamp, frameCount, outputBusNumber, outputData, eventsHead, pullInput) -> AUAudioUnitStatus in let driver: AUv3Driver = driverRef.takeUnretainedValue() let handler: ((MIDIMessage, AUEventSampleTime) -> Void)? = midiStorage.currentHandler() LyrebirdAudioUnit._dispatchMIDIEvents( eventsHead: eventsHead, handler: handler ) return driver.render( frameCount: Int(frameCount), outputBusNumber: outputBusNumber, outputData: outputData, timestamp: timestamp, pullInput: pullInput ) } // 6. Assign stored properties. self.synthesizer = synth self.driver = driver self._parameterTree = tree self._parameterNodes = nodes self._outputBuses = outputBuses self._inputBuses = inputBuses self._outputBusSpecs = outputBusSpecs self._inputBusSpecs = inputBusSpecs self._outputBusOffsets = outputBusOffsets self._inputBusOffsets = inputBusOffsets self._renderBlock = renderBlock self._blockSize = blockSize self._totalOutputChannels = totalOutputChannels self._totalInputChannels = totalInputChannels self._midiHandlerStorage = midiStorage try super.init(componentDescription: componentDescription, options: options) // 7. Now `self` is valid — wire AU bus arrays and parameter observers. self._outputBusArrayBacking = AUAudioUnitBusArray( audioUnit: self, busType: .output, busses: outputBuses ) self._inputBusArrayBacking = AUAudioUnitBusArray( audioUnit: self, busType: .input, busses: inputBuses ) // Parameter observers: bridge host writes/reads to the LiveParameterValue node. let nodesCopy: [AUParameterAddress : any LiveParameterValue] = nodes tree.implementorValueObserver = { param, value in guard let node: any LiveParameterValue = nodesCopy[param.address] else { return } node._writeAtomicValue(Double(value)) } tree.implementorValueProvider = { param in guard let node: any LiveParameterValue = nodesCopy[param.address] else { return param.value } return AUValue(node.value) } tree.implementorStringFromValueCallback = { param, valuePtr in let v: AUValue = valuePtr?.pointee ?? param.value return String(format: "%.3f", v) } self.maximumFramesToRender = Self.lyrebirdMaxFramesToRender } // MARK: - AUAudioUnit overrides public override var parameterTree: AUParameterTree? { get { _parameterTree } set { /* read-only — Lyrebird owns the tree */ } } public override var inputBusses: AUAudioUnitBusArray { guard let buses: AUAudioUnitBusArray = _inputBusArrayBacking else { // Apple's KVO machinery can query this from inside `super.init` // before our post-super wiring runs. Degrade // gracefully instead of `fatalError` to avoid killing the // plugin host process. The real backing is installed before // any actual render begins (allocateRenderResources / start), // so an empty stub here is harmless. assertionFailure("inputBusses queried before LyrebirdAudioUnit.init completed — returning empty placeholder") return AUAudioUnitBusArray(audioUnit: self, busType: .input, busses: []) } return buses } public override var outputBusses: AUAudioUnitBusArray { guard let buses: AUAudioUnitBusArray = _outputBusArrayBacking else { // Same rationale as inputBusses. assertionFailure("outputBusses queried before LyrebirdAudioUnit.init completed — returning empty placeholder") return AUAudioUnitBusArray(audioUnit: self, busType: .output, busses: []) } return buses } public override var internalRenderBlock: AUInternalRenderBlock { _renderBlock } public override var latency: TimeInterval { 0 } public override var tailTime: TimeInterval { 0 } // MARK: - Resource lifecycle public override func allocateRenderResources() throws { try super.allocateRenderResources() if let existing: SynthesisEngine = engine { _ = existing.remove(synthesizer) existing.stop() engine = nil } // Use output bus 0's sample rate as the canonical rate. Multi-bus // AUs require all busses to share a sample rate per the AU spec; // hosts negotiate one rate at allocate time. let sampleRate: Double = _outputBuses[0].format.sampleRate guard sampleRate > 0 else { throw LyrebirdAudioUnitError.outputBusNotConfigured } driver.maxFramesToRender = Int(maximumFramesToRender) driver.configureBusMap( outputBusChannelCounts: _outputBusSpecs.map(\.channelCount), inputBusChannelCounts: _inputBusSpecs.map(\.channelCount) ) let newEngine: SynthesisEngine = SynthesisEngine( blockSize: _blockSize, sampleRate: sampleRate, numOutputChannels: _totalOutputChannels, numInputChannels: _totalInputChannels, driver: driver ) newEngine.auOutputBusOffsets = _outputBusOffsets newEngine.auInputBusOffsets = _inputBusOffsets try newEngine.start() // `engine.add` is `@MainActor`. `allocateRenderResources()` overrides // `AUAudioUnit`'s nonisolated declaration, so this method cannot itself be // `@MainActor`. AU hosts usually call render-resource allocation on the main thread, // but the contract does not guarantee it — the bridge runs the add inline when on // main and hops synchronously otherwise, so an off-main host (e.g. auval) does not // trap. The `nonisolated(unsafe)` local transfers the non-`Sendable` engine into the // bridge closure without tripping region-isolation's sending check (the same value is // reused below at `engine = newEngine`). `synthesizer` is `Sendable` (`SynthesizerBase` // is `@MainActor` ⇒ implicitly Sendable), so it needs no such annotation. nonisolated(unsafe) let engineToConfigure: SynthesisEngine = newEngine let synthToAdd: SynthesizerBase = synthesizer try lyrebirdRunMainActorMutation { try engineToConfigure.add(synthToAdd) } engine = newEngine } public override func deallocateRenderResources() { if let existing: SynthesisEngine = engine { _ = existing.remove(synthesizer) existing.stop() engine = nil } super.deallocateRenderResources() } // MARK: - Factory presets public override var factoryPresets: [AUAudioUnitPreset]? { Self.factoryPresetsForLyrebird().enumerated().map { idx, preset in let auPreset: AUAudioUnitPreset = AUAudioUnitPreset() auPreset.number = idx auPreset.name = preset.name return auPreset } } /// Host calls this when the user selects a preset from the preset menu, or /// programmatically. Setting to `nil` is a no-op (no "user preset" /// concept here). public override var currentPreset: AUAudioUnitPreset? { get { _currentPreset } set { _currentPreset = newValue guard let newValue: AUAudioUnitPreset, newValue.number >= 0 else { return } let presets: [LyrebirdAUFactoryPreset] = Self.factoryPresetsForLyrebird() guard newValue.number < presets.count else { return } applyFactoryPreset(presets[newValue.number]) } } private var _currentPreset: AUAudioUnitPreset? /// Apply a factory preset: write scalar values and (re)wire source slots. /// Called both from the `currentPreset` setter and during `fullState` /// restore when the saved dictionary includes source-slot entries. public final func applyFactoryPreset(_ preset: LyrebirdAUFactoryPreset) { // Scalar values. for entry: LyrebirdAUParameterEntry in LyrebirdAUParameterMapping.discoverLiveParameters(of: synthesizer) { if let value: AUValue = preset.scalarValues[entry.name] { entry.node._writeAtomicValue(Double(value)) if let param: AUParameter = _parameterTree.parameter(withAddress: entry.address) { param.value = value } } } // Source slots. for (name, descriptor) in preset.sourceSlots { guard let entry: LyrebirdAUParameterEntry = LyrebirdAUParameterMapping .discoverLiveParameters(of: synthesizer) .first(where: { $0.name == name }) else { continue } let generator: (any Generator)? = LyrebirdAUPresetSourceRegistry.makeGenerator(from: descriptor) if let parameterNode: ParameterNode = entry.node as? ParameterNode { parameterNode.source = generator } } } // MARK: - State save / restore /// Encodes scalar `@LiveParam` values + source-slot generators (where the /// source conforms to ``LyrebirdAUPresetCodable``) under /// ``lyrebirdAUFullStateKey``. /// /// **Scalar slots** are always saved. **Source slots** are saved only when /// the generator currently wired into a `ParameterNode.source` registered /// with ``LyrebirdAUPresetSourceRegistry`` via its `presetTypeID`. Unknown /// generators are silently skipped — restoring will revert that slot to its /// scalar target. public override var fullState: [String: Any]? { get { var dict: [String : Any] = super.fullState ?? [:] var scalars: [String: AUValue] = [:] var sources: [String: [String: AUValue]] = [:] var sourceTypes: [String: String] = [:] for entry: LyrebirdAUParameterEntry in LyrebirdAUParameterMapping.discoverLiveParameters(of: synthesizer) { scalars[entry.name] = AUValue(entry.node.value) if let parameterNode: ParameterNode = entry.node as? ParameterNode, let activeSource: any Generator = parameterNode.source, let codable: any LyrebirdAUPresetCodable = activeSource as? LyrebirdAUPresetCodable { sources[entry.name] = codable.presetEncodedParameters sourceTypes[entry.name] = type(of: codable).presetTypeID } } var payload: [String: Any] = [ lyrebirdAUFullStateScalarKey: scalars, ] if !sources.isEmpty { payload[lyrebirdAUFullStateSourcesKey] = sources payload[lyrebirdAUFullStateSourceTypesKey] = sourceTypes } dict[lyrebirdAUFullStateKey] = payload return dict } set { super.fullState = newValue guard let raw: [String : Any] = newValue?[lyrebirdAUFullStateKey] as? [String: Any] else { // Legacy 104a payload — scalar-only, value-only dictionary. if let legacyScalars: [String : AUValue] = newValue?[lyrebirdAUFullStateKey] as? [String: AUValue] { _restoreScalars(legacyScalars) } return } if let scalars: [String : AUValue] = raw[lyrebirdAUFullStateScalarKey] as? [String: AUValue] { _restoreScalars(scalars) } if let sources: [String : [String : AUValue]] = raw[lyrebirdAUFullStateSourcesKey] as? [String: [String: AUValue]], let sourceTypes: [String : String] = raw[lyrebirdAUFullStateSourceTypesKey] as? [String: String] { _restoreSources(parameters: sources, types: sourceTypes) } } } private func _restoreScalars(_ scalars: [String: AUValue]) { for entry: LyrebirdAUParameterEntry in LyrebirdAUParameterMapping.discoverLiveParameters(of: synthesizer) { guard let value: AUValue = scalars[entry.name] else { continue } entry.node._writeAtomicValue(Double(value)) if let param: AUParameter = _parameterTree.parameter(withAddress: entry.address) { param.value = value } } } private func _restoreSources( parameters: [String: [String: AUValue]], types: [String: String] ) { for entry: LyrebirdAUParameterEntry in LyrebirdAUParameterMapping.discoverLiveParameters(of: synthesizer) { guard let typeID: String = types[entry.name], let params: [String : AUValue] = parameters[entry.name] else { continue } let descriptor: LyrebirdAUPresetSourceDescriptor = LyrebirdAUPresetSourceDescriptor( typeID: typeID, parameters: params ) let generator: (any Generator)? = LyrebirdAUPresetSourceRegistry.makeGenerator(from: descriptor) if let parameterNode: ParameterNode = entry.node as? ParameterNode { parameterNode.source = generator } } } // MARK: - MIDI event dispatch /// Walks the `AURenderEvent` chain pointed to by `eventsHead`, parses each /// `.MIDI` event into a ``MIDIMessage``, and invokes `handler` with the /// message and its host-supplied sample time. Non-MIDI events are skipped. /// /// **RT-thread.** Called from `internalRenderBlock`; must be allocation-free. static func _dispatchMIDIEvents( eventsHead: UnsafePointer?, handler: ((MIDIMessage, AUEventSampleTime) -> Void)? ) { guard let handler: (MIDIMessage, AUEventSampleTime) -> Void = handler else { return } var current: UnsafePointer? = eventsHead while let eventPtr: UnsafePointer = current { let event: AURenderEvent = eventPtr.pointee let head: AURenderEventHeader = event.head // AURenderEventType raw values: 8 = MIDI, 11 = MIDISysEx. switch head.eventType { case .MIDI: let midi: AUMIDIEvent = event.MIDI // `data` is a tuple of 3 UInt8 — Swift exposes it as a tuple. let status: UInt8 = midi.data.0 let data1: UInt8 = midi.data.1 let data2: UInt8 = midi.data.2 let message: MIDIMessage = MIDIMessage.from( status: status, data1: data1, data2: data2 ) handler(message, head.eventSampleTime) default: break } current = UnsafePointer(head.next) } } } // MARK: - Atomic midi handler storage /// Heap box holding one MIDI handler closure. Atomic pointer swaps publish /// the closure to the RT render thread with acquire/release ordering — the /// render side never sees a torn closure value. Old boxes are released on /// the main thread inside the setter, after the atomic store has retired, /// so the RT thread cannot observe a freed pointer. final class _MIDIHandlerBox { let handler: (MIDIMessage, AUEventSampleTime) -> Void init(_ handler: @escaping (MIDIMessage, AUEventSampleTime) -> Void) { self.handler = handler } } /// Owner-side wrapper around a `Synchronization.Atomic` storing the /// bit pattern of a retained `_MIDIHandlerBox` (or `0` for "no handler"). /// One instance per AU; captured by reference into the render closure. final class _MIDIHandlerStorage { private let _atomic: Atomic = Atomic(0) deinit { // Release the last retained box, if any. let raw: UInt64 = _atomic.exchange(0, ordering: .acquiring) if raw != 0, let ptr: UnsafeRawPointer = UnsafeRawPointer(bitPattern: UInt(raw)) { Unmanaged<_MIDIHandlerBox>.fromOpaque(ptr).release() } } /// RT-side acquiring read. Returns the closure inside the currently- /// retained box, or `nil` if no handler is installed. @inlinable func currentHandler() -> ((MIDIMessage, AUEventSampleTime) -> Void)? { let raw: UInt64 = _atomic.load(ordering: .acquiring) guard raw != 0, let ptr: UnsafeRawPointer = UnsafeRawPointer(bitPattern: UInt(raw)) else { return nil } return Unmanaged<_MIDIHandlerBox>.fromOpaque(ptr) .takeUnretainedValue() .handler } /// Main-thread setter. Builds a new box (if `handler` is non-nil), /// retains it, atomically swaps in the new bit pattern, then releases /// the previous box outside the atomic — so an RT acquiring load races /// either pre-swap (old box, still retained) or post-swap (new box, /// retained). func setHandler(_ handler: ((MIDIMessage, AUEventSampleTime) -> Void)?) { let newRaw: UInt64 if let handler: (MIDIMessage, AUEventSampleTime) -> Void { let box: _MIDIHandlerBox = _MIDIHandlerBox(handler) let unmanaged: Unmanaged<_MIDIHandlerBox> = Unmanaged.passRetained(box) newRaw = UInt64(UInt(bitPattern: unmanaged.toOpaque())) } else { newRaw = 0 } let oldRaw: UInt64 = _atomic.exchange(newRaw, ordering: .acquiringAndReleasing) if oldRaw != 0, let ptr: UnsafeRawPointer = UnsafeRawPointer(bitPattern: UInt(oldRaw)) { Unmanaged<_MIDIHandlerBox>.fromOpaque(ptr).release() } } } /// Engine block size used by `LyrebirdAudioUnit` when subclasses do not override /// `lyrebirdBlockSize`. 256 samples matches the AU community standard. public let lyrebirdAUDefaultBlockSize: Int = 256 /// Namespaced root key under which `LyrebirdAudioUnit` stores its parameter state. public let lyrebirdAUFullStateKey: String = "lyrebird.parameterValues" /// Sub-key inside the root payload that holds the `[String: AUValue]` scalar /// values. public let lyrebirdAUFullStateScalarKey: String = "scalars" /// Sub-key inside the root payload that holds the per-parameter source-slot /// generator parameters: `[paramName: [paramName: AUValue]]`. public let lyrebirdAUFullStateSourcesKey: String = "sources" /// Sub-key inside the root payload that holds the per-parameter source-slot /// generator type IDs: `[paramName: presetTypeID]`. public let lyrebirdAUFullStateSourceTypesKey: String = "sourceTypes"