Files
Lyrebird/Sources/Lyrebird/Engine/SynthesisEngine.swift
T
josh 844dc4d9cd v2.1.0 release: Swift 6.4 modernization
Typed throws across the closed-error-set APIs (OSC, MIDI, engine add/schedule,
bus/config/parameter, and the WAV/RF64/Spectral file codecs — source-compatible
narrowing, new .ioFailure cases), plus internal hardening: NSLock-guarded
scheduling/MIDI state moved to Mutex<State>, and the Spectral/FFT scratch owners
moved to a ~Copyable RTScratchBuffer RAII buffer. No API or behavioral change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 19:54:59 -07:00

2007 lines
99 KiB
Swift

// SynthesisEngine.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdDSP
import Foundation
import Synchronization
/// The central hub of the Lyrebird audio engine.
///
/// `SynthesisEngine` owns the audio bus memory, the scheduling queue, the fan-out cache
/// serial, and the root `Group` of the signal graph. It drives the graph once per block
/// via `processBlock`, which is called by the `AudioDriver` from the Core Audio RT thread.
///
/// `Synthesizer` instances are added via `add(_:)` or `schedule(_:at:)` and removed via
/// `remove(_:)` or `remove(_:at:)`. Adding and removing communicates with the RT thread
/// through an `SPSCQueue` — no locks, no allocation on the render path.
///
/// **Typical setup**:
/// ```swift
/// let driver = CoreAudioDriver()
/// let engine = SynthesisEngine(
/// blockSize: 512,
/// sampleRate: 44100,
/// numOutputChannels: 2,
/// numInputChannels: 0,
/// driver: driver
/// )
/// try engine.start()
/// try engine.add(MySynth())
/// // … audio running …
/// engine.stop()
/// ```
///
/// **Thread safety** — `processBlock` runs on the Core Audio RT thread; never call it directly
/// while the engine is running. `add(_:)` / `schedule(_:at:)` are `@MainActor`-isolated: the
/// `pendingQueue` is single-producer, so every enqueue must come from the main thread.
/// `remove(_:)` is `nonisolated` — it unbinds via atomics and enqueues a pointer-only event, so
/// it is callable from any non-RT thread. From a `LyrebirdRoutine` / `LyrebirdTask` body, go
/// through the context (``LyrebirdRoutineContext/add(_:)``, which dispatches to main) rather
/// than calling the engine directly. See `ARCHITECTURE.md` §1 and §9.
///
/// **Deliberately NOT `Sendable`.** This was evaluated and rejected on purpose:
/// - *Checked* `Sendable` is infeasible — the engine holds mutable per-block RT
/// state (node tree, bus memory, block cursors) whose safety comes from the
/// architecture (single-producer `pendingQueue`, atomics, the render-callback
/// happens-before barrier), not from the type system. Those fields cannot be
/// made Sendable-clean without dismantling the RT design.
/// - *`@unchecked`* `Sendable` would be a blanket "safe to share across threads"
/// assertion that is only true for *specific* access patterns (main-thread
/// mutation via the queue; RT-thread reads in `processBlock`) and false for
/// others (mutating config while running, or touching the engine from the RT
/// thread). Declaring it would erase the compiler friction that currently
/// forces each genuine cross-thread transfer to be spelled `nonisolated(unsafe)`
/// at the call site — and those few sites (e.g. `LyrebirdAudioUnit` config
/// hand-off, a UI closure capture) are a *feature*: each is a visible, reviewed
/// "verified safe here" marker on the most concurrency-sensitive object in the
/// system.
///
/// The cost of staying non-Sendable is tiny (a handful of `nonisolated(unsafe)`
/// captures) and the benefit is real (no false safety guarantee, every transfer
/// stays auditable). Classes that hold an engine reference therefore remain
/// `@unchecked Sendable` themselves, keeping their own mutable state in a `Mutex`
/// and naming the engine reference as the sole hand-verified item. Do not add a
/// `Sendable` conformance here without re-opening that trade-off.
public final class SynthesisEngine {
/// Process-unique identity. Used by the engine ownership-binding system
/// (`SynthesizerBase._engineBinding`, `LyrebirdBuffer` cross-engine
/// share refcounts) to name engines in errors and by
/// `EngineLifecycleCoordinator` as a registry key. Assigned at `init`,
/// never changes. Equality-compared by `UUID` value, not identity.
public let identifier: UUID = UUID()
public let blockSize: Int
/// Number of samples per control-rate sub-block.
/// ControlGenerators compute one new value per control block and interpolate across it.
/// Must be a power of two and a divisor of blockSize. Defaults to blockSize (no sub-blocking).
public let controlBlockSize: Int
/// Target sample rate in Hz. Mutable only while the engine is stopped
/// (`isRunning == false`); use ``setSampleRate(_:)`` to change at runtime.
/// The audio driver re-reads this value during `setup(engine:)` on the next
/// `start()` and negotiates the hardware rate from it.
public private(set) var sampleRate: Double
/// Number of hardware output channels reserved on bus indices `0..<numOutputChannels`.
/// Mutable only while the engine is stopped — use ``setNumOutputChannels(_:)``.
public private(set) var numOutputChannels: Int
/// Number of hardware input channels reserved on bus indices
/// `numOutputChannels..<numOutputChannels+numInputChannels`.
/// Mutable only while the engine is stopped — use ``setNumInputChannels(_:)``.
public private(set) var numInputChannels: Int
public let numAudioBuses: Int
/// Per-AU-input-bus engine bus offset map. Index `busIndex` returns the
/// engine `audioBuses` index where AU input bus `busIndex`'s channel 0
/// lives. Populated by ``AUv3Driver/setup(engine:)`` for multi-input-bus
/// AUs. Default `[numOutputChannels]` for single-input-bus AUs and `[]`
/// for instruments / non-AU engines — `AUInput/Audio` reads this map at
/// render time to resolve `busIndex` → engine bus.
public internal(set) var auInputBusOffsets: [Int] = []
/// Per-AU-output-bus engine bus offset map. Index `busIndex` returns the
/// engine `audioBuses` index where AU output bus `busIndex`'s channel 0
/// lives. Populated by ``AUv3Driver/setup(engine:)`` for multi-output-bus
/// AUs. Default `[0]` for single-output-bus AUs and `[]` for non-AU
/// engines. Currently informational — `Out.Audio` already writes by
/// explicit bus index — but exposed so subclasses or AU-aware helpers
/// can consult it.
public internal(set) var auOutputBusOffsets: [Int] = []
public let numControlBuses: Int
/// Language-side bus allocator. Pre-reserves hardware output and input audio buses.
/// Never call allocation/release methods from the RT audio thread.
public let busAllocator: BusAllocator
public private(set) var isRunning: Bool = false
/// Monotonic sample counter. Written only by processBlock (RT thread) via atomic store;
/// read by the main thread via atomic load. Using Atomic<SampleTime> eliminates the data
/// race that a plain `var` would create between schedule(after:) and processBlock.
private let _currentTime: Atomic<SampleTime> = Atomic<SampleTime>(0)
/// Public read-only accessor — atomic relaxed load, safe from any thread.
public var currentTime: SampleTime { _currentTime.load(ordering: .relaxed) }
/// `currentTime` captured at the most recent `start()` call. Basis for `elapsedSamples`.
/// 0 before the first start. Updated each time `start()` succeeds; not reset by `stop()`
/// so that an `elapsedSeconds` read between stop and next start is well-defined (returns
/// time elapsed during the previous run).
private let _startSampleTime: Atomic<SampleTime> = Atomic<SampleTime>(0)
/// Sample count since the most recent `start()` call.
/// Safe to read from any thread (atomic loads).
///
/// Returns `currentTime - startSampleTime`. While the engine is stopped, this freezes at
/// the value reached during the previous run. Before the first `start()`, returns 0.
public var elapsedSamples: SampleTime {
currentTime - _startSampleTime.load(ordering: .relaxed)
}
/// Wall-clock seconds since the most recent `start()` call, derived from
/// `elapsedSamples / sampleRate`. Sample-accurate — does not include OS scheduler jitter.
/// Safe to read from any thread.
public var elapsedSeconds: Double {
Double(elapsedSamples) / sampleRate
}
/// Exponential moving average of CPU load per block (0.0 = idle, 1.0 = full block used).
/// Safe to read from any thread.
public var averageCPU: Double {
Double(bitPattern: _atomicAverageCPUBits.load(ordering: .relaxed))
}
/// Peak CPU load observed since the last resetPeakCPU() call.
/// Safe to read from any thread.
public var peakCPU: Double {
Double(bitPattern: _atomicPeakCPUBits.load(ordering: .relaxed))
}
/// Reset peak CPU to 0.0. Safe to call from the main thread.
public func resetPeakCPU() {
_atomicPeakCPUBits.store((0.0).bitPattern, ordering: .releasing)
}
/// Pre-allocated audio bus memory: [busIndex][sampleIndex]
/// Zeroed at the start of each processBlock call.
/// `internal(set)` is FOR TESTS ONLY — production code must use addToAudioBus(_:at:value:).
/// Direct subscript assignment bypasses bounds checks and should never appear in non-test paths.
public internal(set) var audioBuses: [[Float]] = []
/// Scratch Float buffer for Double→Float conversion in the batch bus-accumulation path.
/// Pre-allocated to blockSize in start(); written and read only on the RT thread.
private var _busAccumulateScratch: [Float] = []
/// Pre-allocated control bus memory: [busIndex]
/// Retained (not zeroed) across processBlock calls.
/// `internal(set)` is FOR TESTS ONLY — production code must use addToControlBus(_:value:).
public internal(set) var controlBuses: [Float] = []
private let driver: AudioDriver
// MARK: - Scheduling
/// Hard cap on events processed per block. The staging arrays are reserved to this capacity
/// in start(); if more events arrive, excess events are silently dropped rather than
/// triggering a realloc on the RT thread.
///
/// Bounds both the number of events firing within one block and the future-event
/// look-ahead carried across block boundaries (`carryOverEvents`). Set at `init` from
/// the `maxEventsPerBlock` parameter; immutable thereafter, so the RT thread reads it
/// as a plain `let` with no synchronisation. Default `lyrebirdDefaultMaxEventsPerBlock`.
public let maxEventsPerBlock: Int
/// Lock-free queue for events posted by the main thread, drained by the RT thread.
/// Capacity is set at init time and must be a power of two.
internal let pendingQueue: SPSCQueue<ScheduledEvent>
/// Monotonic counter of `add` / `schedule` / `remove` calls that returned `false`
/// because the pending queue was full. Useful for detecting when the engine is
/// being asked to handle bursts that exceed `eventQueueCapacity`. Read from any
/// thread via `pendingQueueDroppedCount`. Reset to zero by calling
/// `resetPendingQueueDroppedCount()` from the main thread.
private let _droppedCount: Atomic<UInt64> = Atomic<UInt64>(0)
/// Number of scheduling events dropped because the pending queue was full since
/// the engine started (or since the last call to `resetPendingQueueDroppedCount()`).
/// A non-zero value indicates that callers exceeded `eventQueueCapacity` — increase
/// it at engine init time, or batch / throttle scheduling on the caller side.
public var pendingQueueDroppedCount: UInt64 {
_droppedCount.load(ordering: .acquiring)
}
/// Resets the pending-queue drop counter to zero. Main-thread-only; called from any
/// language-side thread.
public func resetPendingQueueDroppedCount() {
_droppedCount.store(0, ordering: .releasing)
}
/// Records a drop. Internal helper used by the `add` / `schedule` / `remove`
/// `@discardableResult Bool` paths.
@inline(__always)
internal func _recordPendingQueueDrop() {
_droppedCount.wrappingAdd(1, ordering: .relaxed)
}
/// Monotonic counter of scheduling events dropped by the RT thread because a single
/// block's event budget (`maxEventsPerBlock`) was exceeded — either too many events
/// fired in one block or the future-event look-ahead overflowed. Distinct from
/// `pendingQueueDroppedCount`, which counts main-thread enqueue failures. Read from
/// any thread; reset with `resetPerBlockEventDropCount()`.
private let _perBlockEventDroppedCount: Atomic<UInt64> = Atomic<UInt64>(0)
/// Latch set by the RT thread when it drops at least one event for exceeding
/// `maxEventsPerBlock`. A non-RT drain (`drainPerBlockEventDropWarning()`) checks,
/// prints a one-line console warning, and clears it — so the warning is emitted at
/// most once per drain interval regardless of how many events were dropped.
private let _perBlockEventDropped: Atomic<Bool> = Atomic<Bool>(false)
/// Number of scheduling events the RT thread dropped because `maxEventsPerBlock` was
/// exceeded since the engine started (or since the last `resetPerBlockEventDropCount()`).
/// A non-zero value means a block's onset density or future look-ahead exceeded the cap —
/// raise `maxEventsPerBlock` at engine init, or throttle scheduling on the caller side.
public var perBlockEventDropCount: UInt64 {
_perBlockEventDroppedCount.load(ordering: .acquiring)
}
/// Resets the per-block event-drop counter to zero. Call from any non-RT thread.
public func resetPerBlockEventDropCount() {
_perBlockEventDroppedCount.store(0, ordering: .releasing)
}
/// Records a per-block event-budget drop. RT-safe: two atomic ops, no allocation,
/// no locking, no string construction. Called from `processBlock`'s event-drain loop
/// when a staging array is already at `maxEventsPerBlock`.
///
/// The counter increment is `.relaxed`; the latch store is `.releasing` so it
/// synchronizes-with the drain's `.acquiring` CAS in `drainPerBlockEventDropWarning()`.
/// That release/acquire edge guarantees the drain thread, once it observes the latch
/// set, also sees the counter increment that precedes it in program order — so the
/// printed drop count is never stale.
@inline(__always)
private func _recordPerBlockEventDrop() {
_perBlockEventDroppedCount.wrappingAdd(1, ordering: .relaxed)
_perBlockEventDropped.store(true, ordering: .releasing)
}
/// Checks the per-block event-drop latch and, if set, prints a one-line console
/// warning naming `maxEventsPerBlock` and the cumulative drop count, then clears the
/// latch. Non-RT only — shares the `freeWorker`/stop drain sites with the kill-queue
/// overflow warning so no RT-thread `print` is ever attempted.
internal func drainPerBlockEventDropWarning() {
guard _perBlockEventDropped.compareExchange(
expected: true,
desired: false,
successOrdering: .acquiring,
failureOrdering: .relaxed
).exchanged else { return }
let dropped: UInt64 = _perBlockEventDroppedCount.load(ordering: .relaxed)
print("[Lyrebird] Warning: scheduling events dropped — a block exceeded "
+ "maxEventsPerBlock (\(maxEventsPerBlock)); \(dropped) event(s) dropped so far. "
+ "Raise maxEventsPerBlock at engine init, or throttle/spread scheduling.")
}
/// Update the synth/group counters by `delta` (typically `+1` or `-1`).
/// Called from `applyEvent` on the RT thread — uses relaxed atomic adds (no allocation,
/// no locks, no runtime type checks). The `isGroup` flag is read from `PreparedNode`,
/// classified off-RT at node construction.
@inline(__always)
private func _bumpNodeCount(isGroup: Bool, delta: Int) {
if isGroup {
_groupCount.wrappingAdd(delta, ordering: .relaxed)
} else {
_synthesizerCount.wrappingAdd(delta, ordering: .relaxed)
}
}
/// Lock-free queue for Synthesizer instances to be released off the RT thread.
/// RT thread posts retained refs via the `enqueue` helper; background
/// worker calls `release()` on what `dequeue` returns. Populated when
/// removing nodes from the signal graph. Capacity matches pendingQueue
/// (set at init time).
///
/// The typed `RetainQueue<AnyObject>` wrapper replaces the
/// legacy `SPSCQueue<Unmanaged<AnyObject>>` exposure. The wrapper
/// centralises the `Unmanaged.passRetained` + overflow-handling
/// invariants — see `RetainQueue.swift` for the RT-safe vs
/// non-RT-safe enqueue contract.
internal let freeQueue: RetainQueue<AnyObject>
// MARK: - Parameter-source kill queue
/// Fixed capacity for the parameter-source kill queue. Power of two.
///
/// 256 slots accommodate aggressive source-swap bursts: at 44100/512 (~11.6 ms/block)
/// the main-thread drain runs every ~5 ms (shared with `freeQueue`), so at most ~1
/// block of back-pressure accumulates under normal load. 256 gives headroom for 256
/// un-drained old generators before overflow degrades gracefully.
private static let parameterSourceKillQueueCapacity: Int = 256
/// Lock-free queue carrying raw retained pointers to old source generators that must
/// be ARC-released on the main thread.
///
/// **Lifetime contract:**
/// - RT thread: enqueues via `ParameterNode._pushToKillQueue(ptr:engine:)`. Each pointer
/// was produced by `Unmanaged.passRetained(...).toOpaque()` on the RT thread when an
/// old `_sourceSlot` was displaced. No allocation, no lock.
/// - Main thread: drains via `drainParameterSourceKillQueue()`. Each pointer is consumed
/// by `Unmanaged<AnyObject>.fromOpaque(ptr).release()`, which fires ARC dealloc safely
/// away from the audio thread.
///
/// **Overflow policy (graceful degradation):** If the queue is full the RT thread drops
/// the pointer and sets `_killQueueOverflowed`. The main-thread drain checks that flag
/// and prints a one-line console warning. The leaked reference is one generator instance;
/// this is strictly preferable to crashing the engine. See `ParameterNode._pushToKillQueue`.
internal let parameterSourceKillQueue: SPSCQueue<UnsafeRawPointer>
/// Set to `true` by the RT thread when `parameterSourceKillQueue` was full and a pointer
/// was dropped. Cleared by `drainParameterSourceKillQueue()` after it prints the warning.
/// `Atomic<Bool>` so the RT write and main-thread read are both data-race-free.
internal let _killQueueOverflowed: Atomic<Bool> = Atomic(false)
/// Capacity for `bufferSwapKillQueue`. Same sizing rationale as
/// `parameterSourceKillQueue`: 256 slots accommodate aggressive buffer-swap bursts
/// before main-thread drain degrades gracefully via `_killQueueOverflowed`.
private static let bufferSwapKillQueueCapacity: Int = 256
/// Lock-free queue carrying raw retained pointers to old `LyrebirdBuffer` instances
/// that must be ARC-released on a non-RT thread.
///
/// **Lifetime contract:**
/// - RT thread: enqueues from `RTBufferSlot.load(graph:)` when it dequeues a pending
/// swap and displaces the previously installed buffer. Each pointer was produced
/// by `Unmanaged<LyrebirdBuffer>.passRetained(...).toOpaque()` on the non-RT
/// thread that called `RTBufferSlot.swap(_:engine:)`. No allocation, no lock.
/// - Main thread: drains via the same timer that drains `parameterSourceKillQueue`.
/// Each pointer is consumed by `Unmanaged<LyrebirdBuffer>.fromOpaque(ptr).release()`,
/// firing ARC dealloc safely off the audio thread.
///
/// **Overflow policy (graceful degradation):** If the queue is full the RT thread
/// drops the pointer and sets `_killQueueOverflowed` (shared with the parameter-source
/// kill queue — both overflows mean the same thing: main-thread drain fell behind).
/// The leaked reference is one `LyrebirdBuffer` instance.
internal let bufferSwapKillQueue: SPSCQueue<UnsafeRawPointer>
// MARK: - Trigger notification channel (RT → TriggerListener)
/// Fixed capacity for the trigger event queue. Power of two; separate from
/// `eventQueueCapacity` because trigger density is independent of scheduling load.
/// 1024 gives headroom for multiple simultaneous `SendTrigger.Audio` generators at
/// `blockSize=512` (max single-generator density is 256 edges/block for alternating signals).
private static let triggerQueueCapacity: Int = 1024
/// Lock-free queue: RT thread enqueues `TriggerEvent`s; the `TriggerListener`
/// drains it via a `DispatchSourceUserDataAdd` (RT mode) or `_drainSync` (NRT mode).
internal let triggerQueue: SPSCQueue<TriggerEvent>
/// Weak reference to the attached listener. Main-thread only — never read from the RT thread.
/// The RT thread uses `_rtTriggerSignalFn` (cached at `start()`) instead.
internal weak var _triggerListener: TriggerListener?
/// RT-cached signal closure. Captures the listener's `DispatchSourceUserDataAdd` directly,
/// so `_postTrigger` never reads any mutable listener-owned state from the RT thread.
/// Set in `start()` (before RT begins), cleared in `stop()` (after RT ends).
private var _rtTriggerSignalFn: (() -> Void)?
/// Attach a `TriggerListener` to receive trigger events from `SendTrigger`
/// generators. The engine holds a weak reference; the caller retains ownership.
///
internal func _attachTriggerListener(_ listener: TriggerListener) {
_triggerListener = listener
}
internal func _detachTriggerListener(_ listener: TriggerListener) {
if _triggerListener === listener { _triggerListener = nil }
}
// MARK: - State listeners (main-thread only)
/// Box that weakly references a `SynthesisEngineListener` so the engine never
/// retains caller-owned listener objects.
private struct _ListenerBox {
weak var listener: SynthesisEngineListener?
}
/// Attached state listeners. Mutated and iterated on the main thread only —
/// `start()` / `stop()` / `add*` / `remove*` share the same threading contract.
private var _stateListeners: [_ListenerBox] = []
/// Most recent ``SynthesisEngineState`` transition fired to listeners.
///
/// Main-thread only — written by `start()` / `stop()` (which are documented
/// main-thread-safe) and consistent only when read from the same thread.
/// SwiftUI listeners that mutate `@Published` state in their callback can
/// read this property directly from the same callback.
public private(set) var currentState: SynthesisEngineState = .idle
/// Attach a listener that receives lifecycle state transitions.
///
/// The engine holds a weak reference — the caller retains ownership. Dead listeners
/// are pruned automatically on each fan-out. Safe to call before or after `start()`.
public func addSynthesisEngineListener(_ listener: SynthesisEngineListener) {
_stateListeners.removeAll { $0.listener == nil || $0.listener === listener }
_stateListeners.append(_ListenerBox(listener: listener))
}
/// Detach a previously attached listener.
public func removeSynthesisEngineListener(_ listener: SynthesisEngineListener) {
_stateListeners.removeAll { $0.listener == nil || $0.listener === listener }
}
/// Update `currentState` and fan out to attached listeners. Main-thread only.
private func _setState(_ newState: SynthesisEngineState) {
currentState = newState
_stateListeners.removeAll { $0.listener == nil }
for box: SynthesisEngine._ListenerBox in _stateListeners {
box.listener?.synthesisEngine(self, didChangeState: newState)
}
}
/// Post a trigger event from the RT audio thread.
///
/// Called exclusively by `SendTrigger` generators inside `_computeSamples`.
/// Enqueues into the lock-free `triggerQueue` (no allocation, no blocking), then
/// calls the pre-cached signal closure which calls `DispatchSourceUserDataAdd.add(data:)` —
/// async-signal-safe, non-blocking.
///
/// Signals only when the enqueue succeeds — drops silently if the queue is full.
internal func _postTrigger(_ event: TriggerEvent) {
if triggerQueue.enqueue(event) {
_rtTriggerSignalFn?()
}
}
/// Background DispatchQueue that drains freeQueue, keeping ARC deallocs off the RT thread.
private let freeWorker: DispatchQueue = DispatchQueue(label: "lyrebird.free", qos: .background)
/// Timer that periodically triggers the freeQueue drain. Cancelled in stop().
private var freeQueueTimer: DispatchSourceTimer?
/// Timer that resets peakCPU on a fixed interval. Cancelled in stop().
private var _peakResetTimer: DispatchSourceTimer?
private static let peakCPUResetIntervalSeconds: Double = 5.0
// MARK: - Auto-free watcher (synths opting in via autoFreeOnDone)
/// Entry in the auto-free registry. Weak `synth` so a manually-removed
/// or otherwise dropped synth clears its own slot without intervention;
/// `probe` is held strongly only as long as the synth itself retains
/// it via the generator DAG (the registry has no obligation to keep
/// either alive).
private struct _AutoFreeEntry {
weak var synth: SynthesizerBase?
weak var probe: (any DoneActionWatchable)?
}
private let _autoFreeLock: NSLock = NSLock()
private var _autoFreeEntries: [_AutoFreeEntry] = []
private var _autoFreeTimer: DispatchSourceTimer?
/// Polling cadence for the auto-free watcher in milliseconds. Matches
/// the `LyrebirdProcess` watcher cadence so envelope-driven self-frees
/// are observed within ~10 ms of their RT-side flip.
private static let autoFreePollIntervalMs: Int = 10
/// Background queue the auto-free watcher runs on. Reads atomic
/// `needsFree` and dispatches `engine.remove(synth)` to the main
/// thread.
private let _autoFreeWorker: DispatchQueue = DispatchQueue(
label: "lyrebird.autofree",
qos: .utility
)
/// Register `synth` in the auto-free watcher if it has opted in via
/// ``SynthesizerBase/autoFreeOnDone(_:)``. Cheap downcast + flag check
/// — silently skips synths without a probe and non-`SynthesizerBase`
/// nodes (e.g. raw `Group` / `ParallelGroup`).
private func _registerAutoFreeIfAny(_ synth: any Synthesizer) {
guard let base: SynthesizerBase = synth as? SynthesizerBase,
base._autoFreeProbe != nil else { return }
_registerAutoFree(base)
}
/// Symmetric counterpart to ``_registerAutoFreeIfAny(_:)`` — drops the
/// synth from the watcher when the user calls `engine.remove` manually
/// before the envelope's `needsFree` flips.
private func _unregisterAutoFreeIfAny(_ synth: any Synthesizer) {
guard let base: SynthesizerBase = synth as? SynthesizerBase else { return }
_unregisterAutoFree(base)
}
/// Register `synth` in the auto-free watcher. No-op when the synth has
/// no auto-free probe attached. Idempotent — adding the same synth
/// twice keeps a single entry.
internal func _registerAutoFree(_ synth: SynthesizerBase) {
guard let probe: any DoneActionWatchable = synth._autoFreeProbe else { return }
_autoFreeLock.lock()
defer { _autoFreeLock.unlock() }
for entry: _AutoFreeEntry in _autoFreeEntries where entry.synth === synth {
return
}
_autoFreeEntries.append(_AutoFreeEntry(synth: synth, probe: probe))
_startAutoFreeTimerIfNeeded_locked()
}
/// Drop `synth` from the auto-free watcher. Called by `engine.remove`
/// so manual removal supersedes the watcher.
internal func _unregisterAutoFree(_ synth: SynthesizerBase) {
_autoFreeLock.lock()
defer { _autoFreeLock.unlock() }
_autoFreeEntries.removeAll { $0.synth === synth || $0.synth == nil || $0.probe == nil }
if _autoFreeEntries.isEmpty {
_autoFreeTimer?.cancel()
_autoFreeTimer = nil
}
}
/// Start the shared auto-free timer if at least one entry is registered.
/// Must be called with `_autoFreeLock` held.
private func _startAutoFreeTimerIfNeeded_locked() {
guard _autoFreeTimer == nil else { return }
let timer: any DispatchSourceTimer = DispatchSource.makeTimerSource(queue: _autoFreeWorker)
timer.schedule(
deadline: .now() + .milliseconds(SynthesisEngine.autoFreePollIntervalMs),
repeating: .milliseconds(SynthesisEngine.autoFreePollIntervalMs),
leeway: .milliseconds(SynthesisEngine.autoFreePollIntervalMs)
)
timer.setEventHandler { [weak self] in
self?._tickAutoFreeWatcher()
}
_autoFreeTimer = timer
timer.resume()
}
/// One auto-free tick — snapshots the registry, walks it without
/// holding the lock during the `needsFree` reads, then dispatches any
/// removals to the main thread.
private func _tickAutoFreeWatcher() {
_autoFreeLock.lock()
let snapshot: [_AutoFreeEntry] = _autoFreeEntries
_autoFreeLock.unlock()
var toFree: [SynthesizerBase] = []
var deadEntryFound: Bool = false
for entry: _AutoFreeEntry in snapshot {
guard let synth: SynthesizerBase = entry.synth,
let probe: any DoneActionWatchable = entry.probe else {
deadEntryFound = true
continue
}
if probe.needsFree {
toFree.append(synth)
}
}
// Always re-acquire the lock to (a) sweep dead entries and (b)
// remove `toFree` synths from the registry BEFORE dispatching to
// main. Without the pre-dispatch removal, subsequent 10 ms ticks
// would re-observe `needsFree == true` and enqueue duplicate
// `engine.remove(synth)` calls — the second one corrupts the
// node-tree mirror (didRemove on an already-removed node).
if deadEntryFound || !toFree.isEmpty {
_autoFreeLock.lock()
_autoFreeEntries.removeAll { entry in
if entry.synth == nil || entry.probe == nil { return true }
if let s: SynthesizerBase = entry.synth,
toFree.contains(where: { $0 === s }) {
return true
}
return false
}
if _autoFreeEntries.isEmpty {
_autoFreeTimer?.cancel()
_autoFreeTimer = nil
}
_autoFreeLock.unlock()
}
guard !toFree.isEmpty else { return }
let args: _AutoFreeRemovalArgs = _AutoFreeRemovalArgs(engine: self, synths: toFree)
DispatchQueue.main.async {
// Race guard: `stop()` writes `isRunning = false` and then drains
// the utility queue via `_autoFreeWorker.sync {}`. A tick already
// past its `sync {}` window can still land its main-queue dispatch
// here AFTER `stop()` returns. Skipping the remove avoids enqueueing
// a `.remove` event into `pendingQueue` that the now-idle RT thread
// would never drain — which would leak the retained synth ref.
guard args.engine.isRunning else { return }
for synth: SynthesizerBase in args.synths {
_ = args.engine.remove(synth)
}
}
}
/// Events that arrived too early for the previous block and must be reconsidered next block.
/// `internal` (not `private`) so `@testable` test code can assert the drain in `stop()` cleared it.
internal var carryOverEvents: [ScheduledEvent] = []
/// Events that belong to the current block window [blockStart, blockEnd).
/// `internal` for the same `@testable` rationale as `carryOverEvents`.
internal var thisBlockEvents: [ScheduledEvent] = []
/// Events from pendingQueue / carryOver that are still in the future after this block.
/// `internal` for the same `@testable` rationale as `carryOverEvents`.
internal var nextCarryOver: [ScheduledEvent] = []
/// Internal hook retained for scheduling tests that verify segment boundaries.
/// Set by tests to observe segment calls. Real graph evaluation (rootGroup.evaluate) runs
/// first; this fires afterwards so existing scheduling tests continue to pass.
internal var _segmentEvaluator: ((Int, Int) -> Void)?
// MARK: - Shared lookup tables
/// Pre-computed lookup tables (sine, Hanning window, etc.) shared by all generators.
///
/// Allocated and filled in `init` on the calling (non-RT) thread. Generators access
/// these via `graph.engine.sharedTables` inside `calculatedSamples`. Tables are never
/// freed during the engine's lifetime, so generators reading shared tables do not need
/// to check `isValid`.
public let sharedTables: SharedTables
/// Pre-allocated empty `ParameterTable` used by `evaluateSegment` when constructing
/// the root `SynthGraph` context on the RT thread.
///
/// `evaluateSegment` builds an initial `SynthGraph` whose `_parameterTable` is never
/// read by the signal graph — each `SynthesizerBase.evaluate` overwrites it with the
/// synthesizer's own table via the internal `SynthGraph(engine:busOffset:parameterTable:)`
/// init. Reusing a single pre-allocated empty table eliminates the per-block
/// `ParameterTable()` heap allocation that the public `SynthGraph.init` would otherwise
/// trigger on every `processBlock` call.
private let _emptyParameterTable: ParameterTable = ParameterTable()
/// Monotonically-incrementing segment counter used by the generator fan-out cache.
///
/// Incremented once at the top of every `evaluateSegment` call via `_advanceSegmentSerial`.
/// Each `Generator.calculatedSamples` reads `segmentSerial` and compares against its
/// stored `_segmentSerial`: a match means the generator was already evaluated this segment
/// and the cached `_cachedResult` is returned; a mismatch triggers `_computeSamples`.
///
/// Stored as `Atomic<UInt64>` so that `ParallelGroup` can read the serial from multiple
/// worker threads concurrently without a data race. The single write always happens before
/// the concurrent evaluation section (releasing store), and reads within concurrent workers
/// use acquiring loads to establish the happens-before edge.
///
/// Starts at `1` so generators initialised with `_segmentSerial = 0` always miss on
/// their first call.
private let _atomicSegmentSerial: Atomic<UInt64> = Atomic<UInt64>(1)
/// Acquiring load of the segment serial — safe to call from any thread.
///
/// Exposed as `@_spi(LyrebirdExtensions)` so out-of-tree extension packages can build
/// their own test helpers that simulate block-boundary advancement (the standard
/// `advanceBlock` helper pattern). Not part of the stable public API.
@_spi(LyrebirdExtensions)
public var segmentSerial: UInt64 { _atomicSegmentSerial.load(ordering: .acquiring) }
/// Increment the segment serial. Called once per `evaluateSegment` (before any concurrent
/// evaluation begins) and by tests via `advanceBlock`.
///
/// Uses a single wrapping-add with releasing semantics so all parallel readers in a
/// subsequent `concurrentPerform` see the updated value via their acquiring loads.
///
/// Exposed as `@_spi(LyrebirdExtensions)` so out-of-tree extension packages can build
/// their own `advanceBlock` test helper. Not part of the stable public API.
@_spi(LyrebirdExtensions)
public func advanceSegmentSerial() {
_atomicSegmentSerial.wrappingAdd(1, ordering: .releasing)
}
// MARK: - CPU statistics
private static let cpuEMAAlpha: Double = 0.1
private static let nanosecondsPerSecond: Double = 1_000_000_000.0
private static let freeQueueDrainIntervalMs: Int = 5
/// Precomputed: mach ticks → nanoseconds. Computed once at init from mach_timebase_info.
private let _machTicksToNs: Double
/// Precomputed: nominal block duration in nanoseconds = (blockSize / sampleRate) * 1e9.
/// Recomputed whenever ``setSampleRate(_:)`` is called (engine must be stopped).
private var _blockDurationNs: Double
/// EMA state — RT-private. Written and read only on the RT thread; no atomic needed.
private var _cpuEMA: Double = 0.0
private var _cpuEMAInitialized: Bool = false
/// Cross-thread CPU stats using Double.bitPattern in UInt64 atomics (same pattern as ParameterNode).
/// RT thread writes (.releasing), main thread reads (.relaxed).
private let _atomicAverageCPUBits: Atomic<UInt64> = Atomic<UInt64>((0.0).bitPattern)
private let _atomicPeakCPUBits: Atomic<UInt64> = Atomic<UInt64>((0.0).bitPattern)
/// Cross-thread node counts. Written by the RT thread inside `applyEvent` (one
/// add/remove per event, classified via `PreparedNode.isGroup`); read from any
/// thread via `synthesizerCount` / `groupCount`. `synthesizerCount` counts leaf
/// `Synthesizer` instances; `groupCount` counts `Group` and `ParallelGroup` containers
/// added to the engine (the implicit `rootGroup` is not counted).
private let _synthesizerCount: Atomic<Int> = Atomic<Int>(0)
private let _groupCount: Atomic<Int> = Atomic<Int>(0)
/// Number of leaf `Synthesizer` instances currently active in the engine's node tree.
/// Excludes `Group` and `ParallelGroup` containers.
///
/// Count maintained by `applyEvent` on the RT thread. Direct adds and removes
/// track exactly; `.groupFree` walks the entire freed subtree and decrements
/// counts for every descendant synth (at any depth), so nested-group hierarchies
/// settle the counter correctly when their root is freed.
public var synthesizerCount: Int { _synthesizerCount.load(ordering: .relaxed) }
/// Number of `Group` and `ParallelGroup` containers currently active in the node tree.
/// Excludes the implicit `rootGroup` and `mainGroup` — only counts groups explicitly added via
/// `add(_:)` / `schedule(_:at:)` / `add(_:position:)`.
///
/// Same recursion semantics as `synthesizerCount` — `.groupFree` decrements the
/// counter for every nested group in the freed subtree, not just direct children.
public var groupCount: Int { _groupCount.load(ordering: .relaxed) }
// MARK: - Master output gain / mute
/// Atomic backing store for ``masterGain`` — `Double.bitPattern` packed into a
/// `UInt64`. Mirrors the CPU-bits atomic pattern; relaxed orderings are sufficient
/// because RT-thread reads and main-thread writes are both monotonic scalars.
private let _masterGainBits: Atomic<UInt64> = Atomic<UInt64>((1.0).bitPattern)
/// Atomic mute flag. Read on the RT thread; written on the main thread.
private let _muteFlag: Atomic<Bool> = Atomic<Bool>(false)
/// RT-thread-only: the master gain value applied at the end of the *previous*
/// `processBlock`. Used as the ramp-in level for the current block so a sudden
/// slider move or mute toggle is interpolated to its target over one block
/// rather than producing a step discontinuity.
private var _previousAppliedGain: Float = 1.0
/// Linear amplitude scaler applied to every hardware output channel
/// (`audioBuses[0..<numOutputChannels]`) at the end of each `processBlock`.
///
/// Defaults to `1.0` (unity). `0.0` is silence. Values greater than `1.0` boost
/// — no internal clamp. UI sliders should expose a bounded range
/// (a dB-tapered slider is the canonical surface).
///
/// Changes are interpolated over one audio block via a linear ramp from the
/// previous applied gain to the new target — no click on sudden moves.
///
/// Thread-safe (atomic load/store). Independent of ``isMuted`` — both are
/// applied multiplicatively (`effective = isMuted ? 0 : masterGain`).
public var masterGain: Double {
get { Double(bitPattern: _masterGainBits.load(ordering: .relaxed)) }
set {
// Silently reject non-finite values — a stray NaN would propagate through
// `vDSP_vrampmul` and poison the output buffer for every subsequent block.
// No magnitude clamp: callers may set any finite scalar (including > 1).
guard newValue.isFinite else { return }
_masterGainBits.store(newValue.bitPattern, ordering: .relaxed)
}
}
/// When `true`, the engine zeroes every hardware output channel after graph
/// evaluation each block. The signal graph still evaluates (synths advance,
/// scope taps still capture pre-mute audio) — only the final write to the
/// driver is silenced.
///
/// The transition is interpolated over one block via the same ramp used by
/// ``masterGain``, so toggling mute does not click.
///
/// Thread-safe (atomic load/store).
public var isMuted: Bool {
get { _muteFlag.load(ordering: .relaxed) }
set { _muteFlag.store(newValue, ordering: .relaxed) }
}
// MARK: - Scope tap
/// Optional audio bus capture tap. Set before calling `start()`.
///
/// At the end of each `processBlock`, the engine calls `write(audioBuses:count:)` on the
/// tap using a pre-retained `Unmanaged` reference cached at `start()` time. Avoid changing
/// this property after `start()` — the RT thread reads `_rtScopeTap`, not `scopeTap`, and
/// they would diverge.
public var scopeTap: ScopeCapture?
/// Unmanaged reference cached at `start()` from `scopeTap`. Used on the RT thread to avoid
/// the ARC retain/release that `ScopeCapture?` optional chaining would impose.
/// Written only in `start()` / `stop()` (non-RT); read only in `processBlock()` (RT).
/// These calls cannot overlap, so no synchronisation is required.
private var _rtScopeTap: Unmanaged<ScopeCapture>?
// MARK: - Node tree
/// The root of the signal graph node tree. Contains `mainGroup` plus any user-installed
/// pre-main / post-main nodes added via `.before(engine.mainGroup)` / `.after(engine.mainGroup)`.
/// Reads are safe from any thread (Group is RT-owned for writes).
/// Persistent — created at init, never freed.
public private(set) var rootGroup: Group = Group(persistent: true)
/// The default target for `engine.add(_:)`. Persistent — created at init, never freed.
///
/// Instruments and synths added via `engine.add(_:)` or `engine.schedule(_:at:)` land
/// at the head of `mainGroup` (newest-first order). `mainGroup` is the sole initial child
/// of `rootGroup`.
///
/// Use `.before(engine.mainGroup)` to install global pre-processing nodes (e.g. input
/// limiters) that evaluate before the instrument graph. Use `.after(engine.mainGroup)` to
/// install global post-processing nodes (e.g. ambisonic decoders, master reverb) that
/// evaluate after. These insertions go into `rootGroup` immediately before or after
/// `mainGroup`'s slot.
///
/// ```swift
/// // Pre-processing: runs before all instruments
/// try engine.add(InputLimiter(), position: .before(engine.mainGroup))
///
/// // Default instrument add — lands in mainGroup
/// try engine.add(MySynth())
///
/// // Post-processing: runs after all instruments
/// try engine.add(MasterReverb(), position: .after(engine.mainGroup))
/// ```
public let mainGroup: Group = Group(persistent: true)
/// Main-thread mirror of the node tree.
///
/// Updated **after a successful** language-side `add` / `schedule` /
/// `remove` enqueue, plus on `Group.free(engine:)`. The mirror is
/// skipped on queue overflow so its view stays consistent with the RT
/// thread's view (the dropped event never lands). Reads
/// `mirror.snapshot` from any SwiftUI view to display the current
/// tree. Documented limitations live on ``NodeTreeMirror``.
public let nodeTreeMirror: NodeTreeMirror
// MARK: - Init
public init(
blockSize: Int,
controlBlockSize: Int? = nil,
sampleRate: Double,
numOutputChannels: Int,
numInputChannels: Int,
numAudioBuses: Int = lyrebirdDefaultNumAudioBuses,
numControlBuses: Int = lyrebirdDefaultNumControlBuses,
eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity,
maxEventsPerBlock: Int = lyrebirdDefaultMaxEventsPerBlock,
driver: AudioDriver
) {
// Initialise RT-thread identity TLS key from this known non-RT call
// site. Avoids first-touch allocation when the RT render callback
// later calls `RTThreadIdentity.markCurrentThreadAsRT()`.
RTThreadIdentity.warmUp()
precondition(
blockSize <= lyrebirdDefaultResultBufferSize,
"blockSize \(blockSize) exceeds the maximum supported by built-in generators " +
"(\(lyrebirdDefaultResultBufferSize)). Increase lyrebirdDefaultResultBufferSize " +
"or pre-allocate generator output buffers to a larger size."
)
precondition(
eventQueueCapacity > 0 && eventQueueCapacity & (eventQueueCapacity - 1) == 0,
"eventQueueCapacity \(eventQueueCapacity) must be a power of two (e.g. 256, 512, 1024, 2048)."
)
precondition(
maxEventsPerBlock > 0,
"maxEventsPerBlock \(maxEventsPerBlock) must be positive."
)
// Resolution order: explicit caller value → driver suggestion → full block (no sub-blocking).
// Explicit values are validated strictly. Driver suggestions that don't fit blockSize are
// silently ignored (fall back to full-block mode) so small-blockSize test engines don't crash.
let resolvedControlBlockSize: Int
let driverSuggestion: Int? = driver.suggestedControlBlockSize
if let explicit: Int = controlBlockSize {
precondition(
explicit > 0 && explicit & (explicit - 1) == 0,
"controlBlockSize \(explicit) must be a power of two."
)
precondition(
blockSize % explicit == 0,
"controlBlockSize \(explicit) must divide blockSize \(blockSize) evenly."
)
resolvedControlBlockSize = explicit
} else if let suggested: Int = driverSuggestion,
suggested > 0, suggested & (suggested - 1) == 0, blockSize % suggested == 0 {
resolvedControlBlockSize = suggested
} else {
if let suggested: Int = driverSuggestion {
print("[Lyrebird] Warning: suggestedControlBlockSize \(suggested) is not a power-of-two divisor of blockSize \(blockSize) — ignoring, using full-block control rate")
}
resolvedControlBlockSize = blockSize
}
self.blockSize = blockSize
self.controlBlockSize = resolvedControlBlockSize
self.sampleRate = sampleRate
self.numOutputChannels = numOutputChannels
self.numInputChannels = numInputChannels
self.numAudioBuses = numAudioBuses
self.numControlBuses = numControlBuses
self.maxEventsPerBlock = maxEventsPerBlock
self.busAllocator = BusAllocator(
numAudioBuses: numAudioBuses,
numControlBuses: numControlBuses,
numOutputChannels: numOutputChannels,
numInputChannels: numInputChannels
)
self.driver = driver
self.sharedTables = SharedTables()
self.pendingQueue = SPSCQueue<ScheduledEvent>(capacity: eventQueueCapacity)
self.freeQueue = RetainQueue<AnyObject>(capacity: eventQueueCapacity)
self.triggerQueue = SPSCQueue<TriggerEvent>(capacity: SynthesisEngine.triggerQueueCapacity)
self.parameterSourceKillQueue = SPSCQueue<UnsafeRawPointer>(
capacity: SynthesisEngine.parameterSourceKillQueueCapacity
)
self.bufferSwapKillQueue = SPSCQueue<UnsafeRawPointer>(
capacity: SynthesisEngine.bufferSwapKillQueueCapacity
)
_machTicksToNs = LyrebirdMonotonicClock.ticksToNanos
_blockDurationNs = (Double(blockSize) / sampleRate) * SynthesisEngine.nanosecondsPerSecond
// Install mainGroup as the sole initial child of rootGroup. This runs pre-start on the
// calling thread — the RT thread has not started yet, so direct linked-list mutation
// is safe here without going through pendingQueue.
//
// mainGroup is a structural peer of rootGroup — both are persistent and neither is
// counted in `engine.groupCount` (which tracks only user-added nodes). No counter bump.
//
// Bypass prepareNode — Group has no signal graph of its own. Call mainGroup.build()
// explicitly so the install path stays correct if Group ever grows build-time setup.
// Direct PreparedNode construction is safe here because we are pre-start, off-RT.
mainGroup.build()
let mainGroupNode: PreparedNode = PreparedNode(mainGroup)
rootGroup.addToTail(mainGroupNode)
// Seed the main-thread node-tree mirror with rootGroup → mainGroup.
// Every subsequent add / remove / Group.free is reflected here.
self.nodeTreeMirror = NodeTreeMirror(
rootGroup: rootGroup,
mainGroup: mainGroup
)
// Register with the process-wide engine registry.
// The coordinator holds a weak reference, so this does not extend
// the engine's lifetime past its natural ARC scope. The matching
// `unregister` call in `deinit` evicts the slot proactively.
EngineLifecycleCoordinator.shared.register(self)
}
deinit {
// Evict the registry slot for this engine's identifier. The
// coordinator holds a weak reference, so the slot would prune
// lazily anyway, but explicit eviction keeps the dictionary tight
// for long-running processes that create and discard many engines
// (NRT batch render under `EngineHost`).
EngineLifecycleCoordinator.shared.unregister(identifier)
}
// MARK: - Pre-run configuration
/// Update the target sample rate.
///
/// The driver re-reads `engine.sampleRate` during `setup(engine:)` on the next
/// `start()`. Recomputes the internal block-duration constant used for CPU
/// statistics.
///
/// **Caveat — pre-built generators:** filter coefficients, oversampler
/// tables, delay lengths and other generator state computed at construction
/// time from the previous sample rate are **not** invalidated. Synths
/// added to the engine before this call will keep their original
/// coefficients and will detune / mis-tune after the rate change. Re-add
/// affected synths (or rebuild the graph) after changing the rate.
///
/// - Parameter rate: New sample rate in Hz. Must be finite and `> 0`.
/// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` if the engine is
/// currently running; ``SynthesisEngineConfigError/invalidValue(_:)`` if
/// `rate` is non-finite or `<= 0`.
public func setSampleRate(_ rate: Double) throws(SynthesisEngineConfigError) {
guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning }
guard rate.isFinite, rate > 0 else {
throw SynthesisEngineConfigError.invalidValue(
"sampleRate must be a finite value > 0, got \(rate)"
)
}
guard rate != sampleRate else { return }
sampleRate = rate
_blockDurationNs = (Double(blockSize) / rate) * SynthesisEngine.nanosecondsPerSecond
}
/// Update the number of hardware output channels.
///
/// Bus slots `0..<numOutputChannels` are reserved for hardware outputs by the
/// bus allocator. Changing this count invalidates any prior bus allocations
/// (the free list is reset).
///
/// - Parameter count: New output channel count. Must be `>= 1` and fit within
/// `numAudioBuses`.
/// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` /
/// ``SynthesisEngineConfigError/invalidValue(_:)``.
public func setNumOutputChannels(_ count: Int) throws(SynthesisEngineConfigError) {
guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning }
guard count >= 1 else {
throw SynthesisEngineConfigError.invalidValue(
"numOutputChannels must be >= 1, got \(count)"
)
}
guard count + numInputChannels <= numAudioBuses else {
throw SynthesisEngineConfigError.invalidValue(
"numOutputChannels (\(count)) + numInputChannels (\(numInputChannels)) " +
"exceeds numAudioBuses (\(numAudioBuses))"
)
}
guard count != numOutputChannels else { return }
numOutputChannels = count
busAllocator._reconfigureHardwareReservation(
numOutputChannels: count,
numInputChannels: numInputChannels
)
}
/// Update the number of hardware input channels.
///
/// Bus slots `numOutputChannels..<numOutputChannels+numInputChannels` are
/// reserved for hardware inputs. Changing this count invalidates any prior
/// bus allocations (the free list is reset).
///
/// - Parameter count: New input channel count. Must be `>= 0` and fit within
/// `numAudioBuses` together with `numOutputChannels`.
/// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` /
/// ``SynthesisEngineConfigError/invalidValue(_:)``.
public func setNumInputChannels(_ count: Int) throws(SynthesisEngineConfigError) {
guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning }
guard count >= 0 else {
throw SynthesisEngineConfigError.invalidValue(
"numInputChannels must be >= 0, got \(count)"
)
}
guard numOutputChannels + count <= numAudioBuses else {
throw SynthesisEngineConfigError.invalidValue(
"numOutputChannels (\(numOutputChannels)) + numInputChannels (\(count)) " +
"exceeds numAudioBuses (\(numAudioBuses))"
)
}
guard count != numInputChannels else { return }
numInputChannels = count
busAllocator._reconfigureHardwareReservation(
numOutputChannels: numOutputChannels,
numInputChannels: count
)
}
// MARK: - Lifecycle
public func start() throws {
guard !isRunning else { return }
// Deferred: the lifecycle lock was
// initially wired here to head off the suspected interleave
// behind the deferred parallel-`swift test` crash. Empirically,
// holding the lock across `freeWorker.sync` teardown in stop()
// (and the matching scope in start()) destabilises the
// existing test suite — multiple full-suite runs SIGABRT/SIGSEGV
// on retain-race patterns that were dormant under the prior
// un-locked sequence. The lock infrastructure stays in place
// (`EngineLifecycleCoordinator.withLifecycleLock`) for
// `EngineHost` to own at a higher level (host-scoped
// start/stop coordination rather than per-engine).
_setState(.starting)
_startSampleTime.store(_currentTime.load(ordering: .relaxed), ordering: .releasing)
_cpuEMAInitialized = false
_atomicAverageCPUBits.store((0.0).bitPattern, ordering: .releasing)
_atomicPeakCPUBits.store((0.0).bitPattern, ordering: .releasing)
audioBuses = [[Float]](
repeating: [Float](repeating: 0, count: blockSize),
count: numAudioBuses
)
// Seed the master-gain ramp so the first block after each `start()` has a
// matched `from`/`to` (no spurious ramp from a stale value left over by
// the previous run, e.g. a `stop()` while muted).
_previousAppliedGain = _muteFlag.load(ordering: .relaxed)
? 0.0
: Float(Double(bitPattern: _masterGainBits.load(ordering: .relaxed)))
controlBuses = [Float](repeating: 0, count: numControlBuses)
_busAccumulateScratch = [Float](repeating: 0, count: blockSize)
// Pre-allocate staging arrays to the hard cap — no RT realloc as long as
// events-per-block stays within maxEventsPerBlock (excess are dropped).
carryOverEvents.reserveCapacity(maxEventsPerBlock)
thisBlockEvents.reserveCapacity(maxEventsPerBlock)
nextCarryOver.reserveCapacity(maxEventsPerBlock)
// Force eager initialization of module-level `let` constants used by RBJ filters.
// Swift module-level lets are protected by swift_once on first access; touching them
// here guarantees that path runs off the RT thread before the first render callback.
_ = rbjLn2Half
_ = rbjMaxFreqFraction
_ = pan2AngleScale
_ = panNHalfPi
_ = ambi1WScale
_ = granularPanAngleScale
_ = fmGrainTableSizeDivTwoPi
// Cache scope tap as Unmanaged so the RT thread never incurs an ARC retain/release.
_rtScopeTap = scopeTap.map { .passUnretained($0) }
// Cache the trigger listener and its dispatch-source signal closure for RT use.
// The closure captures the dispatch source directly — no mutable listener state
// is read on the RT thread. Must be set before driver.start() so the RT thread
// sees a stable non-nil value from its first block.
if let listener: TriggerListener = _triggerListener {
_rtTriggerSignalFn = listener._prepareRTSignal()
}
do {
try driver.setup(engine: self)
try driver.start()
} catch {
_setState(.startFailed(error))
_setState(.idle)
throw error
}
isRunning = true
startFreeQueueDrain()
startPeakResetTimer()
_setState(.started)
}
public func stop() {
guard isRunning else { return }
// Deferred: see start() for the
// rationale on why the lifecycle lock is not wired here.
_setState(.tearingDown)
driver.stop()
isRunning = false
_rtScopeTap = nil
// Clear RT trigger cache after driver.stop() — RT thread is no longer running.
_rtTriggerSignalFn = nil
// Cancel the background timer and perform a final synchronous drain to release
// any remaining Synthesizer references before the engine is considered stopped.
freeQueueTimer?.cancel()
freeQueueTimer = nil
_peakResetTimer?.cancel()
_peakResetTimer = nil
_autoFreeLock.lock()
_autoFreeTimer?.cancel()
_autoFreeTimer = nil
_autoFreeEntries.removeAll()
_autoFreeLock.unlock()
// Drain any in-flight `_tickAutoFreeWatcher` that started before the
// cancel landed. Without this barrier a late tick could dispatch
// `engine.remove(synth)` to main AFTER `stop()` returns, enqueuing a
// `.remove` event whose retained ref the now-stopped RT thread
// never drains — an ARC leak of the synth reference.
_autoFreeWorker.sync { }
// Tear down all non-persistent nodes from the linked-list tree (must
// happen before the freeWorker drain so any retained refs from in-flight
// `.remove` events still in the pending queue get released cleanly).
_drainAllNonPersistentNodes()
freeWorker.sync {
while let ref: Unmanaged<AnyObject> = self.freeQueue.dequeue() {
ref.release()
}
self.drainParameterSourceKillQueue()
self.drainBufferSwapKillQueue()
self.drainPerBlockEventDropWarning()
}
_setState(.stopped)
}
/// Tear down every non-persistent node in the engine's tree so a subsequent
/// `start()` begins from the same `rootGroup → mainGroup` baseline as a
/// fresh `SynthesisEngine`. Called from `stop()` after `driver.stop()` has
/// returned (RT thread is no longer running, so direct linked-list mutation
/// is safe).
///
/// Steps:
/// 1. Drain `pendingQueue` of any events that never reached `applyEvent`,
/// releasing `.remove` events' retained refs to balance ARC.
/// 2. `mainGroup._drainNodes` drops every direct child, unbinding each
/// drained synth (and every synth nested inside a drained `Group`
/// subtree) from `self` via `_unbindNodeAndDescendants(_:)` before ARC
/// cascades through the nested `PreparedNode` chains to release the
/// entire subtree.
/// 3. Walk `rootGroup` and preserve only the `PreparedNode` that wraps
/// `mainGroup`. All other direct children (`.before(mainGroup)` /
/// `.after(mainGroup)` installations) are unlinked and unbound the
/// same way.
/// 4. Reset `_synthesizerCount` / `_groupCount` to zero.
/// 5. Reseed `nodeTreeMirror` so SwiftUI observers see the empty baseline.
///
/// Unbinding here (rather than leaving it to ARC) is what lets a caller
/// re-`add` the same synth instance — to this engine or a different one —
/// immediately after `stop()` returns, with no `EngineAddError.doubleAdd`
/// and no "wait one processBlock" constraint (unlike `remove(_:)`, whose
/// unbind races the RT thread and therefore documents that wait). `stop()`
/// has already halted the RT thread via `driver.stop()`, so there is no
/// such race here.
private func _drainAllNonPersistentNodes() {
// 1. Pending queue (events posted by main but never dequeued by the RT
// thread). `.remove` carries an `Unmanaged.passRetained` ref that
// must be released to balance ARC; the other cases carry strong
// refs that ARC drops with the local enum copy.
while let event: ScheduledEvent = pendingQueue.dequeue() {
if case .remove(_, let ref, _) = event {
ref.release()
}
}
// 2. `carryOverEvents` — RT-side staging buffer holding events whose
// `targetTime` is past `blockEnd` (e.g. a future-dated remove). A
// `.remove` parked here owns an `Unmanaged.passRetained` ref that
// would leak if stop() landed first. Release each `.remove`'s ref
// and clear the buffer.
//
// `thisBlockEvents` and `nextCarryOver` are NOT drained:
// `thisBlockEvents` holds events that were already applied this
// block — their refs were routed to `freeQueue` by `applyEvent`
// and will be released by the freeWorker drain below. Touching
// them here would double-release the same `Unmanaged` ref →
// crash. `nextCarryOver` is the working buffer the block-end swap
// copies into `carryOverEvents`; its content is a duplicate of
// `carryOverEvents`'s and is wiped at the top of the next block,
// so any release here would also double-fire.
_releaseRemoveRefs(in: &carryOverEvents)
// 3. mainGroup direct children — unbind each drained synth (and its
// nested-Group descendants), then let ARC cascade release the
// subtree as before.
mainGroup._drainNodes { n in self._unbindNodeAndDescendants(n) }
// 4. rootGroup: preserve only the mainGroup PreparedNode; unbind and
// unlink everything else.
_drainRootKeepingMainGroup()
// 5. Counters and mirror.
_synthesizerCount.store(0, ordering: .relaxed)
_groupCount.store(0, ordering: .relaxed)
nodeTreeMirror.reset(rootGroup: rootGroup, mainGroup: mainGroup)
}
/// Unbind `node.synth` from `self` (no-op if `node.synth` is not a
/// `SynthesizerBase`, or is already unbound), then recurse into a nested
/// `Group`'s children so every synth in a drained subtree is fully
/// detached — not just the top-level node the caller drained.
///
/// `ParallelGroup` children are intentionally not descended into: they are
/// added via `ParallelGroup.add(_:)` rather than `engine.add(_:)`, so they
/// were never individually bound in the first place (only the enclosing
/// `ParallelGroup` synth — which is not a `SynthesizerBase` either — was
/// ever passed to `engine.add`). Same opaque-`ParallelGroup` convention as
/// `Group.removeRecursive` / `Group._walkSubtreeForCountDecrement`.
///
/// Called only from `stop()`'s teardown path, after `driver.stop()` has
/// returned — main thread, RT thread not running, safe to call `_unbind`.
private func _unbindNodeAndDescendants(_ node: PreparedNode) {
(node.synth as? SynthesizerBase)?._unbind(from: self)
guard let nested: Group = node.groupRef else { return }
var child: PreparedNode? = nested.head
while let n: PreparedNode = child {
_unbindNodeAndDescendants(n)
child = n.next
}
}
/// Walk `buf` and release any `.remove` event's `Unmanaged.passRetained`
/// ref, then clear the array keeping its reserved capacity. Used during
/// `stop()` teardown to balance ARC on events that were staged on the RT
/// side but never applied.
private func _releaseRemoveRefs(in buf: inout [ScheduledEvent]) {
for event: ScheduledEvent in buf {
if case .remove(_, let ref, _) = event {
ref.release()
}
}
buf.removeAll(keepingCapacity: true)
}
/// Walk `rootGroup`'s linked list, preserve only the `PreparedNode` whose
/// `synth === mainGroup`, and unlink everything else. Pre/post-main user
/// nodes (installed via `.before(mainGroup)` / `.after(mainGroup)`) are
/// unbound (see `_unbindNodeAndDescendants(_:)`) and dropped; their refs
/// release via ARC as the enclosing scope ends. `mainGroup` itself is left
/// untouched — never unbound (it is not a `SynthesizerBase` to begin with)
/// and never unlinked.
private func _drainRootKeepingMainGroup() {
var mainNode: PreparedNode? = nil
var node: PreparedNode? = rootGroup.head
while let n: PreparedNode = node {
let next: PreparedNode? = n.next
n.next = nil
n.prev = nil
if n.synth === mainGroup {
mainNode = n
} else {
_unbindNodeAndDescendants(n)
}
node = next
}
guard let mn: PreparedNode = mainNode else {
// Invariant: rootGroup always holds mainGroup's PreparedNode as a
// direct child while the engine is alive. Reaching this branch
// means the linked list was corrupted somewhere upstream.
preconditionFailure(
"SynthesisEngine.stop: rootGroup is missing its mainGroup PreparedNode — engine state corrupted"
)
}
rootGroup.head = mn
rootGroup.tail = mn
rootGroup._atomicCount.store(1, ordering: .relaxed)
}
// MARK: - Bus write accessors (module-internal — used by Out/ControlOut generators)
/// Accumulate a Float value into an audio bus sample. Called by Out generators.
internal func addToAudioBus(
_ bus: Int,
at index: Int,
value: Float
) {
assert(bus >= 0 && bus < numAudioBuses,
"addToAudioBus: bus \(bus) out of range [0, \(numAudioBuses))")
assert(index >= 0 && index < audioBuses[bus].count,
"addToAudioBus: index \(index) out of range for bus \(bus) (size \(audioBuses[bus].count))")
audioBuses[bus][index] += value
}
/// Batch-accumulate `count` Double samples into an audio bus starting at `offset`.
/// Converts Double→Float via vDSP_vdpsp, then adds to the bus via vDSP_vadd.
/// Called only from the RT thread; uses the pre-allocated _busAccumulateScratch buffer.
internal func addToAudioBus(
_ bus: Int,
offset: Int,
samples: [Double],
count: Int
) {
assert(bus >= 0 && bus < numAudioBuses,
"addToAudioBus: bus \(bus) out of range [0, \(numAudioBuses))")
assert(offset + count <= audioBuses[bus].count,
"addToAudioBus: offset \(offset) + count \(count) exceeds bus \(bus) size")
samples.withUnsafeBufferPointer { src in
guard let srcBase: UnsafePointer<Double> = src.baseAddress else { return }
_busAccumulateScratch.withUnsafeMutableBufferPointer { scratch in
guard let scratchBase: UnsafeMutablePointer<Float> = scratch.baseAddress else { return }
vDSP_vdpsp(srcBase, 1, scratchBase, 1, vDSP_Length(count))
audioBuses[bus].withUnsafeMutableBufferPointer { dst in
guard let dstBase: UnsafeMutablePointer<Float> = dst.baseAddress else { return }
vDSP_vadd(scratchBase, 1,
dstBase.advanced(by: offset), 1,
dstBase.advanced(by: offset), 1,
vDSP_Length(count))
}
}
}
}
/// Batch-overwrite `count` Double samples into an audio bus starting at `offset`.
/// Converts Double→Float via vDSP_vdpsp and writes directly to the bus (no accumulate).
/// Called by `ReplaceOut.Audio` from the RT thread.
///
/// - Important: This **wipes** any prior writes to `audioBuses[bus]` in the
/// `[offset, offset + count)` range. Use only when the calling synth intends
/// to take ownership of the target bus content for the remainder of the block.
internal func setAudioBus(
_ bus: Int,
offset: Int,
samples: [Double],
count: Int
) {
assert(bus >= 0 && bus < numAudioBuses,
"setAudioBus: bus \(bus) out of range [0, \(numAudioBuses))")
assert(offset + count <= audioBuses[bus].count,
"setAudioBus: offset \(offset) + count \(count) exceeds bus \(bus) size")
samples.withUnsafeBufferPointer { src in
guard let srcBase: UnsafePointer<Double> = src.baseAddress else { return }
audioBuses[bus].withUnsafeMutableBufferPointer { dst in
guard let dstBase: UnsafeMutablePointer<Float> = dst.baseAddress else { return }
// Convert Double → Float directly into the bus slice. No scratch needed.
vDSP_vdpsp(srcBase, 1, dstBase.advanced(by: offset), 1, vDSP_Length(count))
}
}
}
/// Accumulate a Float value into a control bus. Called by ControlOut generators.
internal func addToControlBus(
_ bus: Int,
value: Float
) {
assert(bus >= 0 && bus < numControlBuses,
"addToControlBus: bus \(bus) out of range [0, \(numControlBuses))")
controlBuses[bus] += value
}
/// Overwrite a control bus sample. Called by `ReplaceOut.Control`. Wipes any
/// prior write in the current block.
internal func setControlBus(
_ bus: Int,
value: Float
) {
assert(bus >= 0 && bus < numControlBuses,
"setControlBus: bus \(bus) out of range [0, \(numControlBuses))")
controlBuses[bus] = value
}
// MARK: - Convenience
/// Convert a duration in seconds to a SampleTime delta.
public func seconds(_ d: Double) -> SampleTime {
SampleTime(d * sampleRate)
}
// MARK: - Scheduling API
/// Schedule a synthesizer to be added at an absolute sample time.
///
/// Builds the generator DAG and pre-allocates the linked-list node on the calling
/// (main) thread. The RT thread only wires pointer references in applyEvent —
/// no allocation occurs during processBlock.
///
/// - Important: Do not schedule the same instance while it is still active in the
/// node tree. `rebuildGraph()` is called here on the calling thread; if the synth
/// is concurrently being evaluated on the RT thread, output generators will race.
/// - Throws:
/// - `EngineAddError.doubleAdd` — synth is already bound to this engine.
/// - `EngineAddError.boundToOtherEngine` — synth is bound to a different engine.
/// - `EngineAddError.pendingQueueFull` — pendingQueue was full; the event was
/// dropped and the binding (if just acquired) released. Callers can react by
/// retrying after a future block, increasing `eventQueueCapacity` at engine
/// init time, or surfacing a UI-level back-off.
@MainActor public func schedule(
_ synth: any Synthesizer,
at time: SampleTime
) throws(EngineAddError) {
precondition(
synth !== rootGroup && synth !== mainGroup,
"Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer"
)
// Claim ownership before any RT-visible side effect.
let base: SynthesizerBase? = synth as? SynthesizerBase
try base?._bind(to: self)
let enqueued: Bool = pendingQueue.enqueue(prepareAddEvent(synth, at: time))
guard enqueued else {
base?._unbind(from: self)
_recordPendingQueueDrop()
throw EngineAddError.pendingQueueFull
}
nodeTreeMirror.didAdd(synth, position: .head(of: mainGroup))
_registerAutoFreeIfAny(synth)
}
/// Schedule a synthesizer to be added after a relative duration in seconds.
/// Reads currentTime via atomic load — safe to call from the main thread while
/// the engine is running. Builds the generator DAG on the calling thread.
/// - Throws:
/// - `EngineAddError.doubleAdd` — synth is already bound to this engine.
/// - `EngineAddError.boundToOtherEngine` — synth is bound to a different engine.
/// - `EngineAddError.pendingQueueFull` — pendingQueue was full; the event was
/// dropped and the binding (if just acquired) released.
@MainActor public func schedule(
_ synth: any Synthesizer,
after seconds: Double
) throws(EngineAddError) {
precondition(
synth !== rootGroup && synth !== mainGroup,
"Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer"
)
// Claim ownership before any RT-visible side effect.
let base: SynthesizerBase? = synth as? SynthesizerBase
try base?._bind(to: self)
let time: SampleTime = _currentTime.load(ordering: .relaxed) + self.seconds(seconds)
let enqueued: Bool = pendingQueue.enqueue(prepareAddEvent(synth, at: time))
guard enqueued else {
base?._unbind(from: self)
_recordPendingQueueDrop()
throw EngineAddError.pendingQueueFull
}
nodeTreeMirror.didAdd(synth, position: .head(of: mainGroup))
_registerAutoFreeIfAny(synth)
}
/// Schedule a synthesizer to be removed at an absolute sample time.
///
/// Pre-retains the synthesizer on the calling (main) thread so the RT thread
/// can enqueue the retained reference to `freeQueue` without calling `passRetained`
/// during processBlock.
///
/// Persistent groups (`rootGroup`, `mainGroup`) are silently ignored — they are
/// structural engine fixtures and must remain alive for the engine's lifetime.
/// This check runs language-side (no RT penalty).
/// - Returns: `true` on enqueue; `false` if the pending queue was full (in which
/// case the pre-retained reference is released immediately to balance ARC), or
/// if the synthesizer is a persistent group (logs a warning and returns false).
@discardableResult
public func remove(
_ synth: any Synthesizer,
at time: SampleTime
) -> Bool {
// Language-side guard — `as?` is safe here (non-RT path).
if let group: Group = synth as? Group, group._persistent {
print("[Lyrebird] Warning: ignoring remove() of persistent Group")
return false
}
let ref: Unmanaged<AnyObject> = Unmanaged.passRetained(synth as AnyObject)
let enqueued: Bool = pendingQueue.enqueue(.remove(synth, retainedRef: ref, at: time))
if enqueued {
nodeTreeMirror.didRemove(synth)
_unregisterAutoFreeIfAny(synth)
// Release ownership binding synchronously on
// successful enqueue. The RT thread has not yet processed the
// `.remove` event at this point — the documented
// `remove → wait one processBlock → re-add` constraint (see
// SynthesizerBase class doc) protects against the
// rebuildGraph-vs-evaluate race that predates the
// binding system. The early unbind here only releases the
// ownership atomic so a properly-delayed re-add does not throw
// `.doubleAdd`. Calling remove + immediate re-add without
// waiting one block remains undefined behaviour exactly as
// before; the binding CAS does not protect against the
// underlying RT race.
(synth as? SynthesizerBase)?._unbind(from: self)
} else {
ref.release()
_recordPendingQueueDrop()
}
return enqueued
}
/// Add a synthesizer to `mainGroup` immediately (at the current sample time).
/// Equivalent to `schedule(_:at:currentTime)`. The synthesizer lands at the head of
/// `mainGroup` — newest-first order. Safe to call from the main thread.
/// - Throws: `EngineAddError` — see `schedule(_:at:)` for cases.
@MainActor public func add(_ synth: any Synthesizer) throws(EngineAddError) {
try schedule(synth, at: currentTime)
}
/// Add a synthesizer at the specified position in the node tree.
///
/// Builds the generator DAG on the calling thread and posts an `.addNode` event.
/// The RT thread applies the insertion at the next block boundary or segment split.
///
/// - Parameter synth: The synthesizer to add.
/// - Parameter position: Where to insert the node. Use `.head(of:)` / `.tail(of:)` for
/// group-relative insertion, or `.before(_:)` / `.after(_:)` for sibling-relative
/// insertion (linear O(n) tree search; falls back to `mainGroup` head on miss).
/// - Throws: `EngineAddError` — see `schedule(_:at:)` for cases.
@MainActor public func add(
_ synth: any Synthesizer,
position: NodePosition
) throws(EngineAddError) {
precondition(
synth !== rootGroup && synth !== mainGroup,
"Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer"
)
// Claim ownership before any RT-visible side effect.
let base: SynthesizerBase? = synth as? SynthesizerBase
try base?._bind(to: self)
let node: PreparedNode = prepareNode(synth)
let enqueued: Bool = pendingQueue.enqueue(.addNode(node, position, at: currentTime))
guard enqueued else {
base?._unbind(from: self)
_recordPendingQueueDrop()
throw EngineAddError.pendingQueueFull
}
nodeTreeMirror.didAdd(synth, position: position)
_registerAutoFreeIfAny(synth)
}
/// Remove a synthesizer from the node tree immediately (at the current sample time).
/// Equivalent to remove(_:at:currentTime). Safe to call from the main thread.
/// - Returns: `true` on enqueue; `false` if the pending queue was full.
@discardableResult
public func remove(_ synth: any Synthesizer) -> Bool {
remove(synth, at: currentTime)
}
// MARK: - processBlock
/// Process one block of audio.
/// Called by the Core Audio render callback and directly by tests / NRTDriver.
public func processBlock(inputSamples: [[Float]]) {
let blockStartTick: UInt64 = LyrebirdMonotonicClock.ticks()
// 1. Zero all audio buses (control buses are never zeroed — they persist)
for i: Int in 0..<audioBuses.count {
audioBuses[i].withUnsafeMutableBufferPointer { buf in
guard let bufBase: UnsafeMutablePointer<Float> = buf.baseAddress else { return }
vDSP_vclr(bufBase, 1, vDSP_Length(buf.count))
}
}
// 2. Copy hardware input into reserved input buses.
// Element-wise copy into the pre-allocated inner [Float] — array assignment
// would swap the buffer reference, releasing the pre-allocated storage on
// the RT thread (ARC dec) and triggering CoW on the next block when the
// shared storage is mutated via withUnsafeMutableBufferPointer.
//
// Index-based loop over both `inputSamples` and `audioBuses` to avoid the
// `let samples = inputSamples[ch]` ARC retain on the inner `[Float]` that
// a `for (ch, samples) in inputSamples.enumerated()` form would introduce.
let inputBusStart: Int = numOutputChannels
let inputBusCap: Int = Swift.max(0, audioBuses.count - inputBusStart)
let inputCount: Int = Swift.min(inputSamples.count, inputBusCap)
for ch: Int in 0..<inputCount {
let busIdx: Int = inputBusStart + ch
audioBuses[busIdx].withUnsafeMutableBufferPointer { dst in
// `audioBuses` inner `[Float]` storage is uniquely owned post-`start()`:
// it's allocated here in step 1 (see `audioBuses = [[Float]](...)` in
// `start()`), the only writes are this element-wise copy + per-block
// `vDSP_vclr` zero-fill above, and the only reads are via
// `withUnsafeBufferPointer` (no `let busSlice = audioBuses[i]` aliasing).
// The withUnsafeMutableBufferPointer uniqueness check therefore never
// triggers a CoW heap allocation on the RT thread.
guard let dstBase: UnsafeMutablePointer<Float> = dst.baseAddress else { return }
// Tolerate partial input blocks (iOS first-frame underrun, mid-stream
// sample-rate / bus reconfigure): copy what's available, zero the tail.
// Oversize sources are silently clamped to `dst.count` — pre-allocated
// bus geometry is the source of truth; an oversize hardware buffer is
// a host-side misconfig that should not crash the RT thread.
inputSamples[ch].withUnsafeBufferPointer { src in
guard let srcBase: UnsafePointer<Float> = src.baseAddress else { return }
// Step 1 above already zero-filled this entire bus, so a partial
// src.count < dst.count source leaves the tail at zero without an
// additional `vDSP_vclr` here.
let copyCount: Int = Swift.min(src.count, dst.count)
dstBase.update(from: srcBase, count: copyCount)
}
}
}
// 3. Scheduling — sub-block splitting
// Read clock atomically; only processBlock writes it (RT thread single-writer).
let blockStart: SampleTime = _currentTime.load(ordering: .relaxed)
let blockEnd: SampleTime = blockStart + SampleTime(blockSize)
let cap: Int = maxEventsPerBlock
thisBlockEvents.removeAll(keepingCapacity: true)
nextCarryOver.removeAll(keepingCapacity: true)
// Drain carry-over from previous block — hard-capped to avoid RT realloc.
for event: ScheduledEvent in carryOverEvents {
if event.targetTime < blockEnd {
if thisBlockEvents.count < cap { thisBlockEvents.append(event) }
else { _recordPerBlockEventDrop() }
} else {
if nextCarryOver.count < cap { nextCarryOver.append(event) }
else { _recordPerBlockEventDrop() }
}
}
// Drain pending queue — stop once both arrays are at the cap.
while thisBlockEvents.count < cap || nextCarryOver.count < cap,
let event: ScheduledEvent = pendingQueue.dequeue() {
if event.targetTime < blockEnd {
if thisBlockEvents.count < cap { thisBlockEvents.append(event) }
else { _recordPerBlockEventDrop() }
} else {
if nextCarryOver.count < cap { nextCarryOver.append(event) }
else { _recordPerBlockEventDrop() }
}
}
// Swap nextCarryOver → carryOverEvents without realloc.
carryOverEvents.removeAll(keepingCapacity: true)
for event: ScheduledEvent in nextCarryOver { carryOverEvents.append(event) }
// Swap-based insertion sort — allocation-free; no ARC count ever hits zero
// mid-sort because swapAt never leaves an element without at least one owner.
// stride(from:to:by:) is used rather than a Range literal so that an empty
// thisBlockEvents array (count == 0 → stride from 1 to 0) produces no iterations
// rather than the fatal "lowerBound > upperBound" trap a Range would cause.
for i: Int in stride(from: 1, to: thisBlockEvents.count, by: 1) {
var j: Int = i
while j > 0 && thisBlockEvents[j - 1].targetTime > thisBlockEvents[j].targetTime {
thisBlockEvents.swapAt(j - 1, j)
j -= 1
}
}
// Walk events and evaluate segments
var cursor: SampleTime = 0
for event: ScheduledEvent in thisBlockEvents {
// Past events clamp to offset 0
let offset: SampleTime = max(SampleTime(0), event.targetTime - blockStart)
if offset > cursor {
evaluateSegment(count: Int(offset - cursor), busOffset: Int(cursor))
cursor = offset
}
applyEvent(event)
}
// Final segment to end of block
if cursor < SampleTime(blockSize) {
evaluateSegment(count: Int(SampleTime(blockSize) - cursor), busOffset: Int(cursor))
}
// 4. Advance clock — releasing store so main-thread loads see the new value.
_currentTime.store(blockStart + SampleTime(blockSize), ordering: .releasing)
// 5. CPU usage statistics — RT-private EMA + atomic publish.
let elapsedNs: Double = Double(LyrebirdMonotonicClock.ticks() &- blockStartTick) * _machTicksToNs
let cpuLoad: Double = elapsedNs / _blockDurationNs
if _cpuEMAInitialized {
_cpuEMA = SynthesisEngine.cpuEMAAlpha * cpuLoad + (1.0 - SynthesisEngine.cpuEMAAlpha) * _cpuEMA
} else {
_cpuEMA = cpuLoad
_cpuEMAInitialized = true
}
_atomicAverageCPUBits.store(_cpuEMA.bitPattern, ordering: .releasing)
let storedPeak: Double = Double(bitPattern: _atomicPeakCPUBits.load(ordering: .relaxed))
if cpuLoad > storedPeak {
_atomicPeakCPUBits.store(cpuLoad.bitPattern, ordering: .releasing)
}
// 6. Scope capture — push rendered block into the tap ring (no allocation, no ARC).
// _rtScopeTap is Unmanaged: takeUnretainedValue() does not retain/release.
// Tap sees pre-master-gain audio so the scope stays useful even when isMuted == true.
_rtScopeTap?.takeUnretainedValue().write(audioBuses: audioBuses, count: blockSize)
// 7. Master gain / mute — linear ramp across the block from the previously applied
// gain to the current target. Applied only to hardware output channels.
let muted: Bool = _muteFlag.load(ordering: .relaxed)
let targetGain: Float = muted
? 0.0
: Float(Double(bitPattern: _masterGainBits.load(ordering: .relaxed)))
applyMasterGainRamp(
from: _previousAppliedGain,
to: targetGain,
count: blockSize
)
_previousAppliedGain = targetGain
}
/// RT-thread helper: multiply each hardware output channel in-place by a linear
/// ramp from `from` → `to` over `count` samples. No allocation.
///
/// Uses `vDSP_vrampmul` per output channel. `vDSP_vrampmul` mutates its
/// `*start` argument in-place (documented API contract — the start value
/// advances past the ramp's end so a consecutive call can continue the
/// ramp). Each channel must therefore re-seed its own local `start` copy,
/// otherwise channels beyond the first would multiply by a flat `~to`
/// instead of the intended ramp.
private func applyMasterGainRamp(from: Float, to: Float, count: Int) {
guard count > 0, numOutputChannels > 0 else { return }
let n: vDSP_Length = vDSP_Length(count)
if from == to {
// No transition — apply a constant scalar (or skip entirely for unity).
if from == 1.0 { return }
var gain: Float = from
for ch: Int in 0..<numOutputChannels {
guard ch < audioBuses.count else { break }
audioBuses[ch].withUnsafeMutableBufferPointer { buf in
guard let base: UnsafeMutablePointer<Float> = buf.baseAddress else { return }
vDSP_vsmul(base, 1, &gain, base, 1, n)
}
}
return
}
var step: Float = (to - from) / Float(count)
for ch: Int in 0..<numOutputChannels {
guard ch < audioBuses.count else { break }
// Per-channel local copy — `vDSP_vrampmul` mutates `*start` so a shared
// `var start` would be advanced after channel 0 and the remaining
// channels would ramp from the wrong starting point.
var start: Float = from
audioBuses[ch].withUnsafeMutableBufferPointer { buf in
guard let base: UnsafeMutablePointer<Float> = buf.baseAddress else { return }
vDSP_vrampmul(base, 1, &start, &step, base, 1, n)
}
}
}
// MARK: - Private helpers
/// Evaluate `count` samples starting at `busOffset` within the current block.
/// Drives the root group (real graph evaluation), then fires the test hook if set.
private func evaluateSegment(
count: Int,
busOffset: Int
) {
// Advance the fan-out cache serial before constructing the graph. Every generator
// evaluated within this call will read the updated serial from graph.engine.segmentSerial.
// ControlGenerators with controlBlockSize < count self-subdivide inside calculatedSamples.
advanceSegmentSerial()
let graph: SynthGraph = SynthGraph(engine: self, busOffset: busOffset,
parameterTable: _emptyParameterTable)
rootGroup.evaluate(graph: graph, count: count)
_segmentEvaluator?(count, busOffset)
}
/// Apply a scheduled event to the signal graph (called on the RT thread).
///
/// RT-safety invariants:
/// - `.add`: graph already built; node already allocated — only pointer wiring here.
/// - `.remove`: synth ref pre-retained on main thread; this method only enqueues refs
/// to freeQueue — no `passRetained` calls on the RT thread.
/// - `.addNode`: like `.add` but uses `NodePosition` for placement; falls back to
/// `mainGroup` head if a `.before`/`.after` target is not found.
/// - `.groupFree`: drains all children to `freeQueue`, removes group from tree.
private func applyEvent(_ event: ScheduledEvent) {
switch event {
case .add(let node, _):
mainGroup.addToHead(node)
_bumpNodeCount(isGroup: node.isGroup, delta: 1)
case .remove(let synth, let ref, _):
if let removedNode: PreparedNode = rootGroup.removeRecursive(synth) {
_bumpNodeCount(isGroup: removedNode.isGroup, delta: -1)
freeQueue.enqueuePreretained(ref)
freeQueue.enqueue(removedNode)
} else {
freeQueue.enqueuePreretained(ref)
}
case .addNode(let node, let position, _):
switch position {
case .head(of: let group):
group.addToHead(node)
case .tail(of: let group):
group.addToTail(node)
case .before(let target):
if !rootGroup.addBefore(node, target: target) {
mainGroup.addToHead(node)
}
case .after(let target):
if !rootGroup.addAfter(node, target: target) {
mainGroup.addToHead(node)
}
}
_bumpNodeCount(isGroup: node.isGroup, delta: 1)
case .groupFree(let group, let parentGroup, _):
// Persistent groups (rootGroup, mainGroup) must never be freed — suppress entirely.
// The `_persistent` flag is a plain Bool set once at init and never written on the
// RT thread, so this read is safe (no concurrent mutation).
if group._persistent { return }
// Remove group from its parent FIRST. Use the provided parent as fast-path;
// fall back to recursive rootGroup search if parentGroup is nil.
//
// If the group is no longer reachable from `rootGroup` (e.g. `engine.stop()`
// already drained the tree via `_drainAllNonPersistentNodes` and reset
// node counters to zero, then this `.groupFree` event lands post-stop in
// `pendingQueue` and is applied by a subsequent `start()`), the
// subtree-walk + child-drain bookkeeping below would double-decrement
// counters past zero. Treat the not-in-tree case as a no-op for
// bookkeeping; just ARC-release the group reference.
let removedNode: PreparedNode?
if let parent: Group = parentGroup {
removedNode = parent.remove(group)
} else {
removedNode = rootGroup.removeRecursive(group)
}
guard let rn: PreparedNode = removedNode else {
freeQueue.enqueue(group)
return
}
// Settle node-count bookkeeping for every descendant in the subtree.
// The drain loop below only sees direct children; nested groups
// (grandchildren and below) are released off-RT via the ARC cascade
// through `freeQueue` and never reach `applyEvent` themselves, so their
// counter decrements must happen here. Pure read-only walk — does not
// touch linked-list state. Uses `PreparedNode.isGroup` / `.groupRef`
// (classified off-RT at init) so no `as?` runs on the RT thread.
group._walkSubtreeForCountDecrement { isGroup in
_bumpNodeCount(isGroup: isGroup, delta: -1)
}
// Drain all direct children to freeQueue. Nested group synths are ARC-owned by
// their PreparedNodes; releasing those PreparedNodes cascades deallocation off-RT.
// Counter decrements for these children were handled by the subtree walk above.
group._drainNodes { n in
freeQueue.enqueue(n.synth as AnyObject)
freeQueue.enqueue(n)
}
_bumpNodeCount(isGroup: rn.isGroup, delta: -1)
freeQueue.enqueue(rn)
freeQueue.enqueue(group)
}
}
// MARK: - Private scheduling helpers
/// Build the generator DAG and pre-allocate the linked-list `PreparedNode`.
/// All allocation and `build()`/`rebuildGraph()` happen here on the calling thread;
/// the RT thread never allocates in `applyEvent`.
/// `@MainActor`: invokes `build()` / `rebuildGraph()` (the `@MainActor` language-side
/// add surface). The node-tree add path runs on the main thread by
/// contract (it also touches `nodeTreeMirror`, observed by SwiftUI).
@MainActor private func prepareNode(_ synth: any Synthesizer) -> PreparedNode {
if let base: SynthesizerBase = synth as? SynthesizerBase {
base.rebuildGraph()
} else {
synth.build()
}
return PreparedNode(synth)
}
/// Build the generator DAG, pre-allocate the linked-list node, and wrap in a `.add` event.
@MainActor private func prepareAddEvent(
_ synth: any Synthesizer,
at time: SampleTime
) -> ScheduledEvent {
.add(prepareNode(synth), at: time)
}
// MARK: - Free queue drain
/// Starts a background timer that periodically drains `freeQueue` and
/// `parameterSourceKillQueue`, releasing objects via ARC off the RT thread.
/// The 5 ms poll interval is a safe default; even at 44100/512 (~11.6 ms per block)
/// this drains within one block period.
private func startFreeQueueDrain() {
let timer: any DispatchSourceTimer = DispatchSource.makeTimerSource(queue: freeWorker)
timer.schedule(deadline: .now(), repeating: .milliseconds(SynthesisEngine.freeQueueDrainIntervalMs))
timer.setEventHandler { [weak self] in
guard let self: SynthesisEngine else { return }
while let ref: Unmanaged<AnyObject> = self.freeQueue.dequeue() {
ref.release()
}
self.drainParameterSourceKillQueue()
self.drainBufferSwapKillQueue()
self.drainPerBlockEventDropWarning()
}
timer.resume()
freeQueueTimer = timer
}
/// Drains `bufferSwapKillQueue`, releasing `LyrebirdBuffer` references previously
/// retained on a non-RT thread (in `RTBufferSlot.swap`) and displaced by the RT
/// thread inside `RTBufferSlot.load(graph:)`. ARC dealloc fires here on the
/// `freeWorker` thread (or wherever this method is called from), never on the
/// RT audio thread.
@discardableResult
internal func drainBufferSwapKillQueue() -> Int {
var count: Int = 0
while let ptr: UnsafeRawPointer = bufferSwapKillQueue.dequeue() {
Unmanaged<LyrebirdBuffer>.fromOpaque(ptr).release()
count += 1
}
return count
}
// MARK: - Parameter-source kill queue drain
/// Drains the parameter-source kill queue, releasing old source generators via ARC.
///
/// Call from the main thread (or any non-RT thread). Each pointer in the queue was
/// produced by `Unmanaged.passRetained(GeneratorBox(...)).toOpaque()` on the RT
/// thread when an old `_sourceSlot` was displaced. `Unmanaged<GeneratorBox>
/// .fromOpaque(_:).release()` deinits the box here, and the box's stored
/// `generator` property in turn fires its own final ARC release as part of the
/// box's destruction — all on the main thread, away from the audio thread.
///
/// Also checks `_killQueueOverflowed` and prints a one-line console warning if the
/// kill queue was full at any point since the last drain. The flag is cleared after
/// the warning is printed.
///
/// - Returns: Number of generator references released in this call. Useful for
/// telemetry and test assertions.
@discardableResult
internal func drainParameterSourceKillQueue() -> Int {
var count: Int = 0
while let ptr: UnsafeRawPointer = parameterSourceKillQueue.dequeue() {
Unmanaged<GeneratorBox>.fromOpaque(ptr).release()
count += 1
}
// Check and clear the overflow flag.
if _killQueueOverflowed.compareExchange(
expected: true,
desired: false,
successOrdering: .acquiring,
failureOrdering: .relaxed
).exchanged {
print("[Lyrebird] Warning: parameterSourceKillQueue overflowed — one or more old "
+ "source generators may have leaked. Reduce source-swap burst rate or "
+ "increase parameterSourceKillQueueCapacity.")
}
return count
}
private func startPeakResetTimer() {
let interval: Double = SynthesisEngine.peakCPUResetIntervalSeconds
let timer: any DispatchSourceTimer = DispatchSource.makeTimerSource(queue: freeWorker)
timer.schedule(deadline: .now() + interval, repeating: interval)
timer.setEventHandler { [weak self] in
self?.resetPeakCPU()
}
timer.resume()
_peakResetTimer = timer
}
}
/// Cross-thread carrier for the auto-free watcher's `engine.remove(synth)`
/// hop to the main thread. `@unchecked Sendable` mirrors the
/// `ContextAddArgs` / `GroupFreeArgs` idiom — the captured engine and
/// synth references are only touched on the main thread once the dispatch
/// fires.
private struct _AutoFreeRemovalArgs: @unchecked Sendable {
let engine: SynthesisEngine
let synths: [SynthesizerBase]
}