1.0.0 release
This commit is contained in:
@@ -0,0 +1,129 @@
|
||||
// AUInput.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Generator that reads audio from the AU host's input bus when running under
|
||||
/// ``LyrebirdAudioUnit`` with `lyrebirdInputChannels > 0`.
|
||||
///
|
||||
/// Effect-AU pattern: the host sends audio to the AU's input bus, Lyrebird
|
||||
/// stages it onto engine input buses `[numOutputChannels, numOutputChannels +
|
||||
/// numInputChannels)`, and `AUInput.Audio(channel:)` reads from those buses.
|
||||
/// The bus index is resolved at render time from `graph.engine.numOutputChannels
|
||||
/// + channel` so the synth's `build()` does not need to know the engine's
|
||||
/// channel layout up front.
|
||||
///
|
||||
/// ```swift
|
||||
/// override func build() {
|
||||
/// let inputLeft = AUInput.Audio(channel: 0)
|
||||
/// let inputRight = AUInput.Audio(channel: 1)
|
||||
/// output(bus: 0, source: inputLeft * 0.5)
|
||||
/// output(bus: 1, source: inputRight * 0.5)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Instrument-only AUs (`lyrebirdInputChannels == 0`) have no input buses and
|
||||
/// reading from `AUInput.Audio` returns silence (defensive zero-fill, no
|
||||
/// out-of-range read).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - busIndex: AU input bus index. `0` is the main input bus; `1` and up
|
||||
/// are sidechain buses declared by a multi-input AU subclass via
|
||||
/// ``LyrebirdAudioUnit/lyrebirdInputBusses``. Single-bus AUs use bus
|
||||
/// `0` exclusively. Out-of-range bus indices return silence rather
|
||||
/// than read past the bus array.
|
||||
/// - channel: Zero-based host input channel index within the selected
|
||||
/// bus. Must satisfy `0 ≤ channel < bus.channelCount` at render time.
|
||||
/// Out-of-range channels return silence.
|
||||
public enum AUInput {
|
||||
|
||||
public final class Audio: GeneratorBase, AudioGenerator {
|
||||
|
||||
/// AU input bus index, 0-based. Multi-bus AUs declare multiple
|
||||
/// input busses via ``LyrebirdAudioUnit/lyrebirdInputBusses``;
|
||||
/// bus 0 is typically the main input, bus 1 the sidechain.
|
||||
/// Single-bus AUs use bus 0.
|
||||
public let busIndex: Int
|
||||
|
||||
/// Host input channel index within the selected bus, 0-based.
|
||||
public let channel: Int
|
||||
|
||||
public override var outputChannelCount: Int { 1 }
|
||||
|
||||
/// - Parameters:
|
||||
/// - busIndex: AU input bus index. `0` is the main input bus; `1`
|
||||
/// and up are sidechain busses declared by the AU subclass.
|
||||
/// - channel: Zero-based channel index within the selected bus.
|
||||
public init(busIndex: Int, channel: Int) {
|
||||
precondition(busIndex >= 0,
|
||||
"AUInput.Audio busIndex must be non-negative")
|
||||
precondition(channel >= 0,
|
||||
"AUInput.Audio channel must be non-negative")
|
||||
self.busIndex = busIndex
|
||||
self.channel = channel
|
||||
super.init()
|
||||
}
|
||||
|
||||
/// Single-bus convenience init. Equivalent to
|
||||
/// `AUInput.Audio(busIndex: 0, channel: channel)`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - channel: Zero-based channel index within input bus 0.
|
||||
public convenience init(channel: Int) {
|
||||
self.init(busIndex: 0, channel: channel)
|
||||
}
|
||||
|
||||
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let engine: SynthesisEngine = graph.engine
|
||||
let offset: Int = graph.busOffset
|
||||
|
||||
// Resolve absolute engine bus index from the AU bus map. The
|
||||
// driver populates `engine.auInputBusOffsets` in `setup`; entry
|
||||
// `i` holds the engine bus index where AU input bus `i`'s
|
||||
// channel 0 lives. Fall back to the legacy single-bus
|
||||
// convention when the map is empty (engine.numOutputChannels +
|
||||
// channel) so existing non-multi-bus call sites keep working.
|
||||
let absoluteBusIdx: Int
|
||||
if busIndex < engine.auInputBusOffsets.count {
|
||||
absoluteBusIdx = engine.auInputBusOffsets[busIndex] + channel
|
||||
} else if busIndex == 0 {
|
||||
absoluteBusIdx = engine.numOutputChannels + channel
|
||||
} else {
|
||||
// Out-of-range bus → silence.
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
for i: Int in 0..<count { base[i] = 0 }
|
||||
}
|
||||
return _result
|
||||
}
|
||||
|
||||
// Defensive bounds: out-of-range bus or engine without inputs →
|
||||
// produce silence rather than read past the bus array.
|
||||
guard absoluteBusIdx >= engine.numOutputChannels,
|
||||
absoluteBusIdx < engine.audioBuses.count,
|
||||
absoluteBusIdx < engine.numOutputChannels + engine.numInputChannels else {
|
||||
_result[0].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Double> = buf.baseAddress else { return }
|
||||
for i: Int in 0..<count { base[i] = 0 }
|
||||
}
|
||||
return _result
|
||||
}
|
||||
// No `let busSlice = ...[absoluteBusIdx]` — that binding triggers an ARC retain
|
||||
// on the inner [Float] storage on the RT thread. Calling `withUnsafeBufferPointer`
|
||||
// directly on the subscript result lets the compiler emit an `_read` borrow access.
|
||||
engine.audioBuses[absoluteBusIdx].withUnsafeBufferPointer { buf in
|
||||
guard let base: UnsafePointer<Float> = buf.baseAddress else { return }
|
||||
// Restore Array's bounds-check semantics that the raw-pointer path drops.
|
||||
precondition(offset + count <= buf.count)
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = Double(base[offset + i])
|
||||
}
|
||||
}
|
||||
return _result
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
// AUv3RingBuffer.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Per-channel circular buffer that decouples Lyrebird's fixed `blockSize` from the
|
||||
/// variable `frameCount` an AUv3 host requests on each `internalRenderBlock` call.
|
||||
///
|
||||
/// `AUv3Driver` advances the engine in fixed `blockSize`-frame steps and pushes each
|
||||
/// block's output buses into the ring; the host then pulls arbitrary `frameCount`
|
||||
/// frames out per render call (typically 64–1024). When the ring runs low the driver
|
||||
/// pulls another engine block, so the inherent latency is at most one engine block.
|
||||
///
|
||||
/// **Thread-safety.** `write` and `read` are both called on the AU render thread
|
||||
/// inside `internalRenderBlock` — never concurrently from different threads. The
|
||||
/// ring is therefore a plain single-threaded circular buffer with no atomics. All
|
||||
/// storage is pre-allocated in `init`; `write` / `read` / `reset` perform no
|
||||
/// allocation and no locking.
|
||||
public final class AUv3RingBuffer {
|
||||
|
||||
/// Channel count this buffer was configured for.
|
||||
public let channelCount: Int
|
||||
|
||||
/// Per-channel capacity in frames (power of two for cheap masking).
|
||||
public let capacity: Int
|
||||
|
||||
/// Bit-mask for the modulo-`capacity` index.
|
||||
@usableFromInline internal let mask: Int
|
||||
|
||||
/// Storage: `[channel][sample]`. Allocated once in `init`.
|
||||
@usableFromInline internal var storage: [[Float]]
|
||||
|
||||
@usableFromInline internal var writeIdx: Int = 0
|
||||
@usableFromInline internal var readIdx: Int = 0
|
||||
|
||||
/// - Parameters:
|
||||
/// - channelCount: Number of audio channels.
|
||||
/// - capacity: Requested per-channel capacity in frames. Rounded up to the next
|
||||
/// power of two so that wrap-around can use a bit-mask.
|
||||
public init(channelCount: Int, capacity: Int) {
|
||||
precondition(channelCount > 0, "channelCount must be positive")
|
||||
precondition(capacity > 0, "capacity must be positive")
|
||||
var c: Int = 1
|
||||
while c < capacity { c <<= 1 }
|
||||
self.channelCount = channelCount
|
||||
self.capacity = c
|
||||
self.mask = c - 1
|
||||
self.storage = [[Float]](
|
||||
repeating: [Float](repeating: 0, count: c),
|
||||
count: channelCount
|
||||
)
|
||||
}
|
||||
|
||||
/// Frames currently available to read.
|
||||
@inlinable public var availableToRead: Int { writeIdx - readIdx }
|
||||
|
||||
/// Free frames available for writing.
|
||||
@inlinable public var availableToWrite: Int { capacity - availableToRead }
|
||||
|
||||
/// Clears the buffer state and zeros all stored samples. Safe to call on the RT
|
||||
/// thread (allocation-free) but typically invoked from `deallocateRenderResources`
|
||||
/// or before changing sample rate.
|
||||
public func reset() {
|
||||
writeIdx = 0
|
||||
readIdx = 0
|
||||
for c: Int in 0..<channelCount {
|
||||
storage[c].withUnsafeMutableBufferPointer { buf in
|
||||
guard let base: UnsafeMutablePointer<Float> = buf.baseAddress else { return }
|
||||
for i: Int in 0..<buf.count { base[i] = 0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Push `count` frames from `sources[sourceBusOffset..<sourceBusOffset +
|
||||
/// pushChannels]` into the ring. `pushChannels` is the minimum of
|
||||
/// `channelCount` (this ring's per-channel storage count) and the
|
||||
/// caller's supplied `channelCount` argument.
|
||||
///
|
||||
/// Used by ``AUv3Driver`` to slice a specific AU output bus out of the
|
||||
/// engine's combined `audioBuses` array on each engine block.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sources: Per-channel source buffers — typically `engine.audioBuses`.
|
||||
/// - sourceBusOffset: Index into `sources` where this bus's channel 0
|
||||
/// lives. Channel `c` of the ring reads `sources[sourceBusOffset + c]`.
|
||||
/// - sourceChannelCount: Number of channels in the source slice. May be ≤
|
||||
/// this ring's `channelCount`; remaining ring channels are left
|
||||
/// unwritten this push (they retain whatever was there before).
|
||||
/// - count: Number of frames to push (≤ `availableToWrite`; ≤ `capacity`).
|
||||
public func write(
|
||||
fromAudioBuses sources: [[Float]],
|
||||
sourceBusOffset: Int,
|
||||
channelCount sourceChannelCount: Int,
|
||||
count: Int
|
||||
) {
|
||||
precondition(count <= availableToWrite,
|
||||
"ring overflow: count \(count) > availableToWrite \(availableToWrite)")
|
||||
precondition(count <= capacity,
|
||||
"count \(count) exceeds capacity \(capacity)")
|
||||
let w: Int = writeIdx & mask
|
||||
let firstChunk: Int = min(count, capacity - w)
|
||||
let secondChunk: Int = count - firstChunk
|
||||
let upper: Int = min(channelCount, sourceChannelCount)
|
||||
for c: Int in 0..<upper {
|
||||
let srcIdx: Int = sourceBusOffset + c
|
||||
guard srcIdx < sources.count else { break }
|
||||
sources[srcIdx].withUnsafeBufferPointer { src in
|
||||
guard let sBase: UnsafePointer<Float> = src.baseAddress else { return }
|
||||
storage[c].withUnsafeMutableBufferPointer { dst in
|
||||
guard let dBase: UnsafeMutablePointer<Float> = dst.baseAddress else { return }
|
||||
for i: Int in 0..<firstChunk { dBase[w + i] = sBase[i] }
|
||||
for i: Int in 0..<secondChunk { dBase[i] = sBase[firstChunk + i] }
|
||||
}
|
||||
}
|
||||
}
|
||||
writeIdx += count
|
||||
}
|
||||
|
||||
/// Push `count` frames from `sources[0..<channelCount]` into the ring.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sources: Per-channel source buffers. Reads from `sources[0..<channelCount]`;
|
||||
/// each channel array must hold at least `count` samples.
|
||||
/// - count: Number of frames to push (≤ `availableToWrite`; ≤ `capacity`).
|
||||
public func write(from sources: [[Float]], count: Int) {
|
||||
precondition(count <= availableToWrite, "ring overflow: count \(count) > availableToWrite \(availableToWrite)")
|
||||
precondition(count <= capacity, "count \(count) exceeds capacity \(capacity)")
|
||||
let w: Int = writeIdx & mask
|
||||
let firstChunk: Int = min(count, capacity - w)
|
||||
let secondChunk: Int = count - firstChunk
|
||||
let upper: Int = min(channelCount, sources.count)
|
||||
for c: Int in 0..<upper {
|
||||
sources[c].withUnsafeBufferPointer { src in
|
||||
guard let sBase: UnsafePointer<Float> = src.baseAddress else { return }
|
||||
storage[c].withUnsafeMutableBufferPointer { dst in
|
||||
guard let dBase: UnsafeMutablePointer<Float> = dst.baseAddress else { return }
|
||||
for i: Int in 0..<firstChunk { dBase[w + i] = sBase[i] }
|
||||
for i: Int in 0..<secondChunk { dBase[i] = sBase[firstChunk + i] }
|
||||
}
|
||||
}
|
||||
}
|
||||
writeIdx += count
|
||||
}
|
||||
|
||||
/// Pop `count` frames into `destinations[0..<channelCount]`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - destinations: Per-channel destination pointers. Each pointer must address
|
||||
/// at least `count` writable floats.
|
||||
/// - destinationChannelCount: Number of channels in `destinations`. May be ≤
|
||||
/// this ring's `channelCount`; reads use `min(channelCount, destinationChannelCount)`.
|
||||
/// - count: Number of frames to pop (≤ `availableToRead`).
|
||||
public func read(
|
||||
into destinations: UnsafeMutablePointer<UnsafeMutablePointer<Float>>,
|
||||
channelCount destinationChannelCount: Int,
|
||||
count: Int
|
||||
) {
|
||||
precondition(count <= availableToRead, "ring underflow: count \(count) > availableToRead \(availableToRead)")
|
||||
let r: Int = readIdx & mask
|
||||
let firstChunk: Int = min(count, capacity - r)
|
||||
let secondChunk: Int = count - firstChunk
|
||||
let nch: Int = min(channelCount, destinationChannelCount)
|
||||
for c: Int in 0..<nch {
|
||||
let dst: UnsafeMutablePointer<Float> = destinations[c]
|
||||
storage[c].withUnsafeBufferPointer { src in
|
||||
guard let sBase: UnsafePointer<Float> = src.baseAddress else { return }
|
||||
for i: Int in 0..<firstChunk { dst[i] = sBase[r + i] }
|
||||
for i: Int in 0..<secondChunk { dst[firstChunk + i] = sBase[i] }
|
||||
}
|
||||
}
|
||||
readIdx += count
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// LyrebirdAUBusSpec.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Declarative bus spec used by ``LyrebirdAudioUnit/lyrebirdOutputBusses`` and
|
||||
/// ``LyrebirdAudioUnit/lyrebirdInputBusses`` to describe an audio bus the
|
||||
/// AU exposes to the host.
|
||||
///
|
||||
/// Subclasses override the class hooks to return an array of these specs;
|
||||
/// the AU base class constructs one `AUAudioUnitBus` per entry, allocates
|
||||
/// engine channels = `Σ channelCount` across output/input specs, and
|
||||
/// maintains a per-bus engine-channel-offset map so `AUv3Driver.render`
|
||||
/// can route the right channel slice to the right host bus.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: Human-readable bus name. Hosts show this in their I/O
|
||||
/// routing UI (e.g. "Main Out", "Aux Send", "Sidechain In").
|
||||
/// - channelCount: Number of audio channels on this bus. Must be ≥ 1.
|
||||
public struct LyrebirdAUBusSpec: Sendable {
|
||||
|
||||
public let name: String
|
||||
public let channelCount: Int
|
||||
|
||||
/// - Parameters:
|
||||
/// - name: Human-readable bus name.
|
||||
/// - channelCount: Number of audio channels on this bus.
|
||||
public init(name: String, channelCount: Int) {
|
||||
precondition(channelCount >= 1,
|
||||
"LyrebirdAUBusSpec: channelCount must be >= 1")
|
||||
self.name = name
|
||||
self.channelCount = channelCount
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// LyrebirdAUFactoryPreset.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
/// One named factory preset that a `LyrebirdAudioUnit` subclass returns from
|
||||
/// `factoryPresetsForLyrebird()`.
|
||||
///
|
||||
/// A preset combines:
|
||||
/// - `name`: human-readable name shown in the host's preset menu.
|
||||
/// - `scalarValues`: per-parameter scalar values keyed by `@LiveParam` /
|
||||
/// `@UIParam` property name.
|
||||
/// - `sourceSlots`: optional per-parameter source-slot generator descriptors.
|
||||
/// Each descriptor's `typeID` must be registered with
|
||||
/// ``LyrebirdAUPresetSourceRegistry`` for the host's preset-load path to
|
||||
/// reconstruct the generator.
|
||||
public struct LyrebirdAUFactoryPreset: Sendable {
|
||||
|
||||
/// Human-readable preset name shown by the host.
|
||||
public let name: String
|
||||
|
||||
/// Per-parameter scalar values keyed by property name.
|
||||
public let scalarValues: [String: AUValue]
|
||||
|
||||
/// Per-parameter source-slot generator descriptors. Only parameters that
|
||||
/// were actively driven by a registered source generator are listed.
|
||||
public let sourceSlots: [String: LyrebirdAUPresetSourceDescriptor]
|
||||
|
||||
public init(
|
||||
name: String,
|
||||
scalarValues: [String: AUValue] = [:],
|
||||
sourceSlots: [String: LyrebirdAUPresetSourceDescriptor] = [:]
|
||||
) {
|
||||
self.name = name
|
||||
self.scalarValues = scalarValues
|
||||
self.sourceSlots = sourceSlots
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// LyrebirdAUParameterEntry.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
/// One discovered `@LiveParam` / `@UIParam` slot on a `SynthesizerBase` subclass,
|
||||
/// paired with the `AUParameterAddress` it will occupy in the AU parameter tree.
|
||||
///
|
||||
/// Produced by ``LyrebirdAUParameterMapping/discoverLiveParameters(of:)``.
|
||||
public struct LyrebirdAUParameterEntry {
|
||||
|
||||
/// Property name with the leading `_` of property-wrapper backing storage
|
||||
/// stripped (`@LiveParam var freq` → `"freq"`).
|
||||
public let name: String
|
||||
|
||||
/// Stable address assigned in declaration order across the entire class
|
||||
/// hierarchy (oldest-superclass first).
|
||||
public let address: AUParameterAddress
|
||||
|
||||
/// The projected `LiveParameterValue` — `ParameterNode` for `@LiveParam`,
|
||||
/// `UIParamNode` for `@UIParam`. Used to read the current scalar (atomic load)
|
||||
/// and to write new values via `_writeAtomicValue`.
|
||||
public let node: any LiveParameterValue
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// LyrebirdAUParameterInfo.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
import AudioToolbox
|
||||
|
||||
/// Per-parameter metadata supplied by a `LyrebirdAudioUnit` subclass to override the
|
||||
/// auto-generated `AUParameter` for an `@LiveParam` slot.
|
||||
///
|
||||
/// `@LiveParam` itself does not carry `min` / `max` / unit information — its
|
||||
/// declaration is just `@LiveParam var freq: Double = 440.0`. To expose meaningful
|
||||
/// bounds and units to AU hosts, override `LyrebirdAudioUnit.parameterMetadata()`
|
||||
/// and return a dictionary keyed by parameter name:
|
||||
///
|
||||
/// ```swift
|
||||
/// 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),
|
||||
/// "modIndex": .init(min: 0, max: 4),
|
||||
/// ]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Names not present in the dictionary fall back to permissive defaults
|
||||
/// (`min: -1e10`, `max: 1e10`, `unit: .generic`).
|
||||
public struct LyrebirdAUParameterInfo: Sendable {
|
||||
|
||||
/// Lower bound exposed to the host as `AUParameter.minValue`. The AU's parameter
|
||||
/// observer enforces this clamp; if the host writes a value outside `[min, max]`
|
||||
/// `AUParameter` itself clamps before invoking the observer.
|
||||
public var minValue: AUValue
|
||||
|
||||
/// Upper bound exposed to the host as `AUParameter.maxValue`.
|
||||
public var maxValue: AUValue
|
||||
|
||||
/// AU-spec unit hint used by the host's UI (knob labels, automation ramp
|
||||
/// interpretation, etc.). Defaults to `.generic`.
|
||||
public var unit: AudioUnitParameterUnit
|
||||
|
||||
/// Human-readable parameter name shown in host UI. Defaults to the property name.
|
||||
public var displayName: String?
|
||||
|
||||
/// AU flags exposed for the parameter. Defaults to readable/writable + ramped.
|
||||
public var flags: AudioUnitParameterOptions
|
||||
|
||||
public init(
|
||||
min: AUValue = -lyrebirdAUParameterDefaultBound,
|
||||
max: AUValue = lyrebirdAUParameterDefaultBound,
|
||||
unit: AudioUnitParameterUnit = .generic,
|
||||
displayName: String? = nil,
|
||||
flags: AudioUnitParameterOptions = lyrebirdAUParameterDefaultFlags
|
||||
) {
|
||||
self.minValue = min
|
||||
self.maxValue = max
|
||||
self.unit = unit
|
||||
self.displayName = displayName
|
||||
self.flags = flags
|
||||
}
|
||||
}
|
||||
|
||||
/// Default unbounded range for `LyrebirdAUParameterInfo` (effectively unbounded for
|
||||
/// any audible parameter). Using a finite value keeps `AUParameter` happy — it does
|
||||
/// not accept `.infinity` as a min/max.
|
||||
public let lyrebirdAUParameterDefaultBound: AUValue = 1.0e10
|
||||
|
||||
/// Default parameter flags: readable + writable + ramping enabled.
|
||||
public let lyrebirdAUParameterDefaultFlags: AudioUnitParameterOptions = [
|
||||
.flag_IsReadable,
|
||||
.flag_IsWritable,
|
||||
.flag_CanRamp,
|
||||
]
|
||||
@@ -0,0 +1,102 @@
|
||||
// LyrebirdAUParameterMapping.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
import AudioToolbox
|
||||
|
||||
/// Builds an `AUParameterTree` from a `SynthesizerBase` subclass by walking its
|
||||
/// `Mirror` for `@LiveParam` / `@UIParam` properties, assigning each one a stable
|
||||
/// `AUParameterAddress`, and creating one `AUParameter` per slot.
|
||||
///
|
||||
/// Mirrors the discovery logic in `SynthesizerBase._autoRegisterLiveParams()`:
|
||||
/// walks the full `superclassMirror` chain (oldest first) so inherited live
|
||||
/// parameters are included in declaration order.
|
||||
///
|
||||
/// **Min / max / unit metadata.** `@LiveParam` itself carries no bounds, so
|
||||
/// subclasses of `LyrebirdAudioUnit` should override `parameterMetadata()` to
|
||||
/// supply `LyrebirdAUParameterInfo` per parameter name. Names absent from the
|
||||
/// dictionary receive permissive defaults.
|
||||
///
|
||||
/// **Threading.** Mirror reflection is main-thread only; do not invoke from the
|
||||
/// audio render thread.
|
||||
public enum LyrebirdAUParameterMapping {
|
||||
|
||||
/// Walks the synthesizer's mirror hierarchy and returns every `@LiveParam` /
|
||||
/// `@UIParam` slot with a stable `AUParameterAddress`.
|
||||
public static func discoverLiveParameters(
|
||||
of synth: SynthesizerBase
|
||||
) -> [LyrebirdAUParameterEntry] {
|
||||
var entries: [LyrebirdAUParameterEntry] = []
|
||||
var address: AUParameterAddress = 0
|
||||
var mirrors: [Mirror] = []
|
||||
var current: Mirror? = Mirror(reflecting: synth)
|
||||
while let m: Mirror = current {
|
||||
mirrors.append(m)
|
||||
current = m.superclassMirror
|
||||
}
|
||||
for mirror: Mirror in mirrors.reversed() {
|
||||
for child: Mirror.Child in mirror.children {
|
||||
guard let label: String = child.label else { continue }
|
||||
let key: String = label.hasPrefix("_") ? String(label.dropFirst()) : label
|
||||
guard let wrapper: any LiveParameterWrapper = child.value as? LiveParameterWrapper else { continue }
|
||||
let projected: any ValidGeneratorInput = wrapper._projectedAsValidInput
|
||||
guard let node: any LiveParameterValue = projected as? LiveParameterValue else { continue }
|
||||
entries.append(
|
||||
LyrebirdAUParameterEntry(name: key, address: address, node: node)
|
||||
)
|
||||
address += 1
|
||||
}
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
/// Builds the AU parameter tree and a reverse-lookup table from address to the
|
||||
/// underlying `LiveParameterValue` node.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - synth: The synthesizer to introspect.
|
||||
/// - metadata: Per-parameter overrides keyed by parameter name. Missing keys
|
||||
/// fall back to `LyrebirdAUParameterInfo()` defaults.
|
||||
/// - Returns: The constructed `AUParameterTree` and a dictionary mapping each
|
||||
/// `AUParameterAddress` to its backing `LiveParameterValue` node. The caller
|
||||
/// uses the dictionary in the AU's `implementorValueObserver` /
|
||||
/// `implementorValueProvider` to bridge host writes/reads to the underlying
|
||||
/// atomic store on each `ParameterNode` / `UIParamNode`.
|
||||
public static func buildParameterTree(
|
||||
for synth: SynthesizerBase,
|
||||
metadata: [String: LyrebirdAUParameterInfo] = [:]
|
||||
) -> (tree: AUParameterTree, nodes: [AUParameterAddress: any LiveParameterValue]) {
|
||||
let entries: [LyrebirdAUParameterEntry] = discoverLiveParameters(of: synth)
|
||||
var auParameters: [AUParameter] = []
|
||||
var nodes: [AUParameterAddress: any LiveParameterValue] = [:]
|
||||
auParameters.reserveCapacity(entries.count)
|
||||
nodes.reserveCapacity(entries.count)
|
||||
for entry: LyrebirdAUParameterEntry in entries {
|
||||
let info: LyrebirdAUParameterInfo = metadata[entry.name] ?? LyrebirdAUParameterInfo()
|
||||
let display: String = info.displayName ?? entry.name
|
||||
let param: AUParameter = AUParameterTree.createParameter(
|
||||
withIdentifier: entry.name,
|
||||
name: display,
|
||||
address: entry.address,
|
||||
min: info.minValue,
|
||||
max: info.maxValue,
|
||||
unit: info.unit,
|
||||
unitName: nil,
|
||||
flags: info.flags,
|
||||
valueStrings: nil,
|
||||
dependentParameters: nil
|
||||
)
|
||||
// Seed from the node's current scalar value (clamped to the declared range).
|
||||
let current: AUValue = AUValue(entry.node.value)
|
||||
param.value = min(max(current, info.minValue), info.maxValue)
|
||||
auParameters.append(param)
|
||||
nodes[entry.address] = entry.node
|
||||
}
|
||||
let tree: AUParameterTree = AUParameterTree.createTree(withChildren: auParameters)
|
||||
return (tree, nodes)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// LyrebirdAUPresetCodable.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
/// Protocol that a `Generator` conforms to so it can be saved into and restored
|
||||
/// from a `LyrebirdAudioUnit.fullState` payload as a `ParameterNode.source` slot.
|
||||
///
|
||||
/// Conformance requires:
|
||||
/// - `static var presetTypeID: String` — stable cross-version identifier used
|
||||
/// to look up the generator's factory in
|
||||
/// ``LyrebirdAUPresetSourceRegistry``.
|
||||
/// - `var presetEncodedParameters: [String: AUValue]` — current parameter
|
||||
/// values that should be saved into the host's preset payload.
|
||||
/// - `static func presetMake(from:) -> any Generator` — factory that
|
||||
/// reconstructs the generator from a saved parameter dictionary. Returning
|
||||
/// a `Generator` (not the concrete type) lets the registry erase types
|
||||
/// uniformly.
|
||||
///
|
||||
/// **Why a custom protocol rather than `Codable`?** AU `fullState` payloads
|
||||
/// are `[String: Any]` of property-list-compatible values (`AUValue`, strings,
|
||||
/// arrays of same). `Codable` would require additional encode/decode plumbing
|
||||
/// to bridge into that representation; `presetEncodedParameters` keeps the
|
||||
/// surface flat and host-friendly.
|
||||
public protocol LyrebirdAUPresetCodable: Generator {
|
||||
|
||||
/// Stable identifier used to look up this type in
|
||||
/// ``LyrebirdAUPresetSourceRegistry`` on restore. Must be unique across
|
||||
/// every type registered in a given AU build.
|
||||
static var presetTypeID: String { get }
|
||||
|
||||
/// Current parameter values to write into the preset. Keys are typically
|
||||
/// the conforming type's `@LiveParam` property names — though that is
|
||||
/// just a convention; the registry's factory closure is responsible for
|
||||
/// the inverse mapping on restore.
|
||||
var presetEncodedParameters: [String: AUValue] { get }
|
||||
|
||||
/// Reconstructs a generator instance from a previously-encoded parameter
|
||||
/// dictionary. Called on the main thread during `fullState` restore.
|
||||
static func presetMake(from parameters: [String: AUValue]) -> any Generator
|
||||
}
|
||||
|
||||
/// Type-erased descriptor used inside `LyrebirdAUFactoryPreset` and
|
||||
/// `fullState` payloads to identify a generator (by `typeID`) plus its
|
||||
/// parameter values.
|
||||
public struct LyrebirdAUPresetSourceDescriptor: Sendable {
|
||||
|
||||
/// Matches a registered `LyrebirdAUPresetCodable.presetTypeID`.
|
||||
public let typeID: String
|
||||
|
||||
/// Parameter values to pass to the type's `presetMake(from:)` factory.
|
||||
public let parameters: [String: AUValue]
|
||||
|
||||
public init(typeID: String, parameters: [String: AUValue] = [:]) {
|
||||
self.typeID = typeID
|
||||
self.parameters = parameters
|
||||
}
|
||||
}
|
||||
|
||||
/// Registry of `LyrebirdAUPresetCodable` types keyed by `presetTypeID`.
|
||||
///
|
||||
/// Subclasses of `LyrebirdAudioUnit` should call ``register(_:)`` once per
|
||||
/// generator type (typically in the subclass's `+initialize` or a static
|
||||
/// `_ = register(...)` side-effect at the AU's first use) before the AU
|
||||
/// instance is created so that `fullState` restore + `factoryPresets` can
|
||||
/// reconstruct source-slot generators by type ID.
|
||||
public enum LyrebirdAUPresetSourceRegistry {
|
||||
|
||||
/// Maps `presetTypeID` to a factory closure that takes a parameter
|
||||
/// dictionary and returns a generator instance. Access is serialised by
|
||||
/// `_lock`; calls happen on the main thread only.
|
||||
nonisolated(unsafe) private static var _factories: [String: (([String: AUValue]) -> any Generator)] = [:]
|
||||
private static let _lock: NSLock = NSLock()
|
||||
|
||||
/// Registers a `LyrebirdAUPresetCodable` type so that its `presetTypeID`
|
||||
/// can be reconstructed by the preset / fullState restore path.
|
||||
public static func register<T: LyrebirdAUPresetCodable>(_ type: T.Type) {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
_factories[T.presetTypeID] = { params in
|
||||
T.presetMake(from: params)
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes a registered type. Primarily for tests.
|
||||
public static func unregister(typeID: String) {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
_factories.removeValue(forKey: typeID)
|
||||
}
|
||||
|
||||
/// Looks up the registered factory for `typeID` and instantiates a
|
||||
/// generator. Returns `nil` if `typeID` is unregistered.
|
||||
public static func makeGenerator(
|
||||
from descriptor: LyrebirdAUPresetSourceDescriptor
|
||||
) -> (any Generator)? {
|
||||
// Dequeue the factory under the lock, then invoke after release —
|
||||
// user-supplied factories may call back into register/unregister
|
||||
// which would deadlock on a non-recursive NSLock.
|
||||
let factory: (([String: AUValue]) -> any Generator)?
|
||||
do {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
factory = _factories[descriptor.typeID]
|
||||
}
|
||||
return factory?(descriptor.parameters)
|
||||
}
|
||||
|
||||
/// Currently registered type IDs, sorted for stable iteration / test
|
||||
/// inspection.
|
||||
public static var registeredTypeIDs: [String] {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
return _factories.keys.sorted()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
// LyrebirdAUVoicePoolBinding.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
/// Convenience adapter wiring ``MIDIMessage`` events into a
|
||||
/// ``VoicePool`` for polyphonic playback.
|
||||
///
|
||||
/// **Threading.** This binding is **main-thread only** — `VoicePool`
|
||||
/// itself is documented as main-thread-only (its internal `_states` array is
|
||||
/// mutated without synchronization, and the `.quietest` / `.lowestAmplitude`
|
||||
/// steal strategies walk `Mirror(reflecting:)`). The binding therefore must
|
||||
/// not be called from the AU host's render thread.
|
||||
///
|
||||
/// To drive voice allocation from `LyrebirdAudioUnit.midiHandler` (which runs
|
||||
/// on the render thread) bridge the events to the main thread first. Two
|
||||
/// established patterns:
|
||||
///
|
||||
/// - **`MIDI` CoreMIDI** — Set up a CoreMIDI source that the AU host
|
||||
/// routes its MIDI to, hook ``MIDI`` 's handler on the main thread,
|
||||
/// and call `binding.handle(message:)` from there.
|
||||
/// - **SPSC queue + main-thread drain** — In `midiHandler` (RT thread)
|
||||
/// enqueue note events onto an `SPSCQueue<MIDIMessage>`. On a main-thread
|
||||
/// tick (e.g. `DispatchSource.makeTimerSource`) drain the queue and call
|
||||
/// `binding.handle(message:sampleTime:)`. This is the pattern used by
|
||||
/// ``TriggerListener`` for engine→language messaging.
|
||||
///
|
||||
/// **Usage.**
|
||||
///
|
||||
/// ```swift
|
||||
/// let pool = try VoicePool<MyVoice>(
|
||||
/// voiceCount: 8,
|
||||
/// group: voiceGroup,
|
||||
/// engine: engine,
|
||||
/// stealStrategy: .oldest,
|
||||
/// factory: { MyVoice() }
|
||||
/// )
|
||||
/// let binding = LyrebirdAUVoicePoolBinding(pool: pool) { voice, note, velocity in
|
||||
/// voice.freq = midiToHz(Double(note))
|
||||
/// voice.amp = velocity
|
||||
/// voice.gate = 1.0
|
||||
/// } noteOff: { voice, _ in
|
||||
/// voice.gate = 0.0
|
||||
/// }
|
||||
/// // From the main thread, after MIDI bridging:
|
||||
/// binding.handle(message: midiMessage, sampleTime: 0)
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pool: The voice pool this binding routes MIDI events into. Allocated
|
||||
/// and owned by the caller.
|
||||
/// - channelFilter: Optional MIDI channel restriction (0-15). `nil` (default)
|
||||
/// accepts events on all channels.
|
||||
/// - noteOnConfigure: Closure called when a note-on is dispatched. Receives
|
||||
/// the allocated voice, MIDI note number (0–127), and normalised velocity
|
||||
/// `[0, 1]`. Main-thread only — typically sets `voice.freq` / `voice.amp`
|
||||
/// / `voice.gate`.
|
||||
/// - noteOffConfigure: Closure called for every voice on a note-off. Default
|
||||
/// no-op; users that drive release via an envelope gate set
|
||||
/// `voice.gate = 0` here. Receives the voice and the released note number.
|
||||
public final class LyrebirdAUVoicePoolBinding<S: SynthesizerBase> {
|
||||
|
||||
/// The voice pool this binding routes MIDI events into.
|
||||
public let pool: VoicePool<S>
|
||||
|
||||
/// Closure called on note-on. Main-thread only.
|
||||
public var noteOnConfigure: (S, Int, Double) -> Void
|
||||
|
||||
/// Closure called on note-off, once per voice. Main-thread only.
|
||||
public var noteOffConfigure: (S, Int) -> Void
|
||||
|
||||
/// Optional MIDI channel filter (0-15). `nil` = accept all channels.
|
||||
public var channelFilter: UInt8?
|
||||
|
||||
/// - Parameters:
|
||||
/// - pool: The voice pool this binding routes MIDI events into.
|
||||
/// - channelFilter: Optional MIDI channel restriction. `nil` = omni.
|
||||
/// - noteOnConfigure: Closure called when a note-on is dispatched.
|
||||
/// - noteOffConfigure: Closure called for every voice on a note-off.
|
||||
public init(
|
||||
pool: VoicePool<S>,
|
||||
channelFilter: UInt8? = nil,
|
||||
noteOn noteOnConfigure: @escaping (S, Int, Double) -> Void,
|
||||
noteOff noteOffConfigure: @escaping (S, Int) -> Void = { _, _ in }
|
||||
) {
|
||||
self.pool = pool
|
||||
self.channelFilter = channelFilter
|
||||
self.noteOnConfigure = noteOnConfigure
|
||||
self.noteOffConfigure = noteOffConfigure
|
||||
}
|
||||
|
||||
/// Dispatch one MIDI message to the voice pool.
|
||||
///
|
||||
/// **Main-thread only.** Do not call from the AU host's render thread —
|
||||
/// see the class-level docs for the bridging patterns.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - message: The MIDI message to dispatch. Currently only `.noteOn` /
|
||||
/// `.noteOff` are handled; other cases (CC, pitch bend, etc.) are
|
||||
/// ignored. Users with custom dispatch needs install their own
|
||||
/// `LyrebirdAudioUnit.midiHandler` that wraps this binding plus the
|
||||
/// extra logic.
|
||||
/// - sampleTime: Host-supplied sample offset within the current render
|
||||
/// block. Currently unused (voices fire at the next block boundary);
|
||||
/// reserved for a future sample-accurate dispatch path.
|
||||
public func handle(message: MIDIMessage, sampleTime: AUEventSampleTime) {
|
||||
_ = sampleTime
|
||||
switch message {
|
||||
case .noteOn(let channel, let note, let velocity):
|
||||
if let filter: UInt8 = channelFilter, channel != filter { return }
|
||||
let voice: S = pool.noteOn(note: Int(note))
|
||||
let normalised: Double = Double(velocity) / Double(midiVelocityMax)
|
||||
noteOnConfigure(voice, Int(note), normalised)
|
||||
case .noteOff(let channel, let note, _):
|
||||
if let filter: UInt8 = channelFilter, channel != filter { return }
|
||||
let intNote: Int = Int(note)
|
||||
pool.noteOff(note: intNote)
|
||||
// Run the configure callback on every voice — safe because
|
||||
// `gate = 0` is idempotent. The pool does not currently expose
|
||||
// a per-voice note query; if/when it does, restrict to voices
|
||||
// whose recorded note matched `intNote`.
|
||||
for voice: S in pool.voices {
|
||||
noteOffConfigure(voice, intNote)
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Maximum MIDI velocity value (`0..=127`). Normalising
|
||||
/// `Double(velocity) / Double(midiVelocityMax)` yields the conventional `[0,1]`
|
||||
/// range used by `@LiveParam` amplitude parameters.
|
||||
public let midiVelocityMax: UInt8 = 127
|
||||
@@ -0,0 +1,705 @@
|
||||
// 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.
|
||||
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<UInt64>` 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.
|
||||
let synth: SynthesizerBase = 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<AUv3Driver> = 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()
|
||||
try newEngine.add(synthesizer)
|
||||
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<AURenderEvent>?,
|
||||
handler: ((MIDIMessage, AUEventSampleTime) -> Void)?
|
||||
) {
|
||||
guard let handler: (MIDIMessage, AUEventSampleTime) -> Void = handler else { return }
|
||||
var current: UnsafePointer<AURenderEvent>? = eventsHead
|
||||
while let eventPtr: UnsafePointer<AURenderEvent> = 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<UInt64>` 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<UInt64> = Atomic<UInt64>(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"
|
||||
@@ -0,0 +1,24 @@
|
||||
// LyrebirdAudioUnitError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Errors thrown by `LyrebirdAudioUnit` during init or `allocateRenderResources`.
|
||||
public enum LyrebirdAudioUnitError: Error {
|
||||
|
||||
/// `AVAudioFormat(standardFormatWithSampleRate:channels:)` returned nil — usually
|
||||
/// caused by an unsupported channel count or non-finite sample rate.
|
||||
case invalidStreamFormat
|
||||
|
||||
/// `allocateRenderResources` was called before the output bus's stream format
|
||||
/// was committed (sample rate or channel count missing).
|
||||
case outputBusNotConfigured
|
||||
|
||||
/// `makeSynthesizer()` returned a synthesizer whose `@LiveParam` discovery
|
||||
/// produced no parameters AND no audio output generators. The AU has nothing
|
||||
/// to render or expose — almost certainly a programming error.
|
||||
case emptySynthesizer
|
||||
}
|
||||
Reference in New Issue
Block a user