1.0.0 release
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
// EngineAddError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Errors thrown from `SynthesisEngine.add(_:)` and
|
||||
/// `SynthesisEngine.add(_:position:)`. Replaces the legacy
|
||||
/// `Bool`-returning signature with structured diagnostics.
|
||||
///
|
||||
/// Cases
|
||||
/// =====
|
||||
/// - `boundToOtherEngine` — the synth is already bound to a different
|
||||
/// `SynthesisEngine`. Cross-engine sharing is illegal because every
|
||||
/// engine owns its own `_segmentSerial` / `_cachedResult` cache state,
|
||||
/// and concurrent evaluation across engines would race on those caches.
|
||||
/// To re-use a synth pattern across engines, build a fresh instance per
|
||||
/// engine (the cheap default), or — for read-only `LyrebirdBuffer` assets
|
||||
/// that need to be shared — use `LyrebirdBuffer.bindReadOnly(to:)`.
|
||||
/// - `doubleAdd` — the synth is already bound to this engine. Re-adding
|
||||
/// while still active in the node tree would race `rebuildGraph()` on
|
||||
/// the main thread with `evaluate()` iterating `outputGenerators` on the
|
||||
/// RT thread. Always `engine.remove(synth)` and allow at least one
|
||||
/// `processBlock` to pass before re-adding the same instance.
|
||||
/// - `pendingQueueFull` — the engine's `pendingQueue` SPSC queue is full;
|
||||
/// the add event could not be enqueued. Indicates the caller is adding
|
||||
/// nodes faster than the RT thread is draining them. Reduce add cadence
|
||||
/// or increase `eventQueueCapacity` at engine init.
|
||||
/// - `rebuildFailed` — `SynthesizerBase.rebuildGraph()` threw while
|
||||
/// constructing the synth's generator DAG. Wraps the underlying error
|
||||
/// verbatim. Inspect `underlying` for the user-side build failure.
|
||||
public enum EngineAddError: Error, CustomStringConvertible {
|
||||
|
||||
/// The synthesizer (or buffer) is already bound to a different engine.
|
||||
/// `current` identifies the engine whose `add(_:)` / `bindExclusive`
|
||||
/// / `bindReadOnly` was just called. `prior` is the engine that
|
||||
/// already owns the resource, when resolvable via the
|
||||
/// `EngineLifecycleCoordinator` registry.
|
||||
///
|
||||
/// `prior` is `Optional` because two edge cases produce an
|
||||
/// unresolved prior identity:
|
||||
/// 1. The owning engine has already deinited but did not unbind
|
||||
/// the synth/buffer first — the raw pointer in the binding
|
||||
/// atomic is dangling. The registry lookup returns no match.
|
||||
/// 2. A read-only refcount tier is in force on a buffer — the
|
||||
/// refcount tier deliberately does not track per-engine
|
||||
/// identity, so the prior holder is unknown by design.
|
||||
case boundToOtherEngine(current: UUID, prior: UUID?)
|
||||
|
||||
/// The synthesizer is already active in this engine's node tree.
|
||||
case doubleAdd(engine: UUID)
|
||||
|
||||
/// The engine's `pendingQueue` was full when the add event was posted.
|
||||
case pendingQueueFull
|
||||
|
||||
/// `SynthesizerBase.rebuildGraph()` threw while building the DAG.
|
||||
case rebuildFailed(underlying: any Error)
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .boundToOtherEngine(let current, let prior):
|
||||
let priorDesc: String = prior.map { "engine \($0)" }
|
||||
?? "an unknown prior engine (deinited without unbind, or read-only refcount tier)"
|
||||
return "Resource is already bound to \(priorDesc); " +
|
||||
"attempted bind to engine \(current). One Synthesizer / exclusive " +
|
||||
"buffer may only be bound to one engine at a time. Build a fresh " +
|
||||
"instance per engine, or use LyrebirdBuffer.bindReadOnly for " +
|
||||
"cross-engine wavetable sharing."
|
||||
case .doubleAdd(let engine):
|
||||
return "Synthesizer is already active in engine \(engine). " +
|
||||
"Call engine.remove(synth) and allow at least one processBlock " +
|
||||
"before re-adding the same instance."
|
||||
case .pendingQueueFull:
|
||||
return "Engine pendingQueue is full — add event dropped. " +
|
||||
"Reduce add cadence or increase eventQueueCapacity at engine init."
|
||||
case .rebuildFailed(let underlying):
|
||||
return "Synthesizer.rebuildGraph() failed: \(underlying)"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,550 @@
|
||||
// EngineHost.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Creation-owning facade for multi-engine `SynthesisEngine` workloads.
|
||||
///
|
||||
/// Use `EngineHost` when a process needs **two or more**
|
||||
/// `SynthesisEngine` instances. Single-engine code continues to use the
|
||||
/// direct `SynthesisEngine` constructor unchanged — the host adds nothing
|
||||
/// for the N = 1 case beyond what the
|
||||
/// `EngineLifecycleCoordinator` already provides.
|
||||
///
|
||||
/// Three responsibilities
|
||||
/// ======================
|
||||
/// 1. **Engine creation under role uniqueness.** `makeEngine(role:config:)`
|
||||
/// constructs a `SynthesisEngine` with the provided config and
|
||||
/// associates it with a `EngineHostRole`. Roles cannot
|
||||
/// repeat. `.rtOutput(deviceID:)` shares the role-equality check
|
||||
/// (deviceID is part of the role's `Hashable` key), so two engines
|
||||
/// cannot drive the same AUHAL output.
|
||||
///
|
||||
/// 2. **Lifecycle coordination.** `startAll()` and `stopAll()` snapshot
|
||||
/// the registered engines under the host's lock and iterate WITHOUT
|
||||
/// holding the lock, so concurrent host accessors are not blocked
|
||||
/// while individual engines start or stop. Iteration order is
|
||||
/// dictionary-natural (not deterministic) — callers that require a
|
||||
/// specific order should drive engines individually via
|
||||
/// `engine(for:)`. `startAll()` rolls back on partial failure. Each
|
||||
/// engine's own `EngineLifecycleCoordinator` registration stays
|
||||
/// untouched — the host composes above it.
|
||||
///
|
||||
/// 3. **Lookup and adoption.** `engine(for:)` resolves a role to its
|
||||
/// live engine. `adopt(existing:)` registers an
|
||||
/// externally-constructed engine under a host role for the cases
|
||||
/// where direct-ctor + lifecycle-host hybrid is preferred (test
|
||||
/// fixtures, migration).
|
||||
///
|
||||
/// NRT batch render
|
||||
/// ================
|
||||
/// `renderConcurrent(jobs:)` ships as a separate API on
|
||||
/// the same host. See its own doc on the method.
|
||||
///
|
||||
/// Thread safety
|
||||
/// =============
|
||||
/// All public methods acquire `_lock` (`NSLock`). Holds are short —
|
||||
/// dictionary mutation only. Marked `@unchecked Sendable` because the
|
||||
/// dictionaries are protected by the lock.
|
||||
///
|
||||
/// Single-engine compatibility
|
||||
/// ===========================
|
||||
/// The host does **not** intercept `SynthesisEngine.init` for engines
|
||||
/// constructed directly (without the host). Single-engine users see no
|
||||
/// change. The `EngineLifecycleCoordinator` registers every
|
||||
/// engine in the process; the host queries the same coordinator on
|
||||
/// `adopt(existing:)`.
|
||||
public final class EngineHost: @unchecked Sendable {
|
||||
|
||||
/// Nanoseconds-per-second conversion factor for
|
||||
/// `DispatchTime.uptimeNanoseconds`-derived elapsed measurements
|
||||
/// inside the NRT pool. Local to the host because
|
||||
/// `SynthesisEngine.nanosecondsPerSecond` is `private` and
|
||||
/// promoting it would change an ABI surface for a single internal
|
||||
/// consumer.
|
||||
private static let nanosecondsPerSecond: Double = 1_000_000_000.0
|
||||
|
||||
/// Internal lock protecting `_engines` and `_devicesByRole`. Held by
|
||||
/// every public method. Non-reentrant — public methods must not
|
||||
/// nest. (`startAll()` does not call `register` / `unregister`
|
||||
/// itself, so there is no transitive re-entry risk through the
|
||||
/// `EngineLifecycleCoordinator` lock.)
|
||||
private let _lock: NSLock = NSLock()
|
||||
|
||||
/// Role → engine map. The host holds strong references, so engines
|
||||
/// constructed via `makeEngine` live for the host's lifetime unless
|
||||
/// removed via a future `release(role:)` API.
|
||||
private var _engines: [EngineHostRole: SynthesisEngine] = [:]
|
||||
|
||||
/// Reverse map: engine identifier → role. Lets `adopt(existing:)`
|
||||
/// detect that an engine is already registered and return its role.
|
||||
/// Also used internally for `role(for:)` queries.
|
||||
private var _rolesByEngine: [UUID: EngineHostRole] = [:]
|
||||
|
||||
// Note: no `_claimedDevices: Set<UInt32>` is
|
||||
// needed to enforce AUHAL device exclusivity — `.rtOutput(deviceID:)`
|
||||
// is a `Hashable` enum case, so two registrations with the same
|
||||
// deviceID are already caught by the `_engines[role]` collision
|
||||
// check (yielding `.duplicateRole`). The
|
||||
// companion `EngineHostError.duplicateDevice` case was dropped — it had
|
||||
// no producer and forced every exhaustive consumer switch to handle
|
||||
// dead code. Re-add the Set + case together if a future role shape
|
||||
// ever cross-cuts deviceID under a different surrounding enum case.
|
||||
|
||||
public init() {}
|
||||
|
||||
// MARK: - Creation (197.1)
|
||||
|
||||
/// Construct a fresh `SynthesisEngine` using `config` and register
|
||||
/// it under `role`. The returned engine is owned by the host (held
|
||||
/// strongly until process exit or — in a future API — release).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - role: Role identifier. Must be distinct from any role
|
||||
/// already registered with this host.
|
||||
/// - config: Engine construction parameters.
|
||||
/// - Returns: The newly constructed engine. The caller may keep a
|
||||
/// reference but the host's strong reference is the primary
|
||||
/// owner.
|
||||
/// - Throws:
|
||||
/// - `EngineHostError.duplicateRole(role)` — `role` already
|
||||
/// registered with this host. For `.rtOutput(deviceID:)`, same
|
||||
/// deviceID surfaces here too (deviceID is part of the role's
|
||||
/// `Hashable` key).
|
||||
@discardableResult
|
||||
public func makeEngine(
|
||||
role: EngineHostRole,
|
||||
config: SynthesisEngineConfig
|
||||
) throws -> SynthesisEngine {
|
||||
// Pre-validate role uniqueness under the
|
||||
// host lock, then RELEASE the lock before calling
|
||||
// `SynthesisEngine.init`. The engine ctor reaches into
|
||||
// `EngineLifecycleCoordinator.shared.register(self)` which
|
||||
// acquires the coordinator's NSLock — holding host._lock at
|
||||
// that point creates a host→coordinator nested-lock acquisition
|
||||
// order. Any future caller that wraps `makeEngine` inside
|
||||
// `EngineLifecycleCoordinator.withLifecycleLock(_:)` would
|
||||
// deadlock against the non-reentrant coordinator lock. Two
|
||||
// separate critical sections eliminate the nest.
|
||||
//
|
||||
// Race window between the pre-check and the post-construction
|
||||
// commit: a concurrent makeEngine on a *different* thread
|
||||
// could grab the same role between our pre-check and our
|
||||
// post-construction commit. The post-check repeats validation
|
||||
// under the lock so the second caller throws `.duplicateRole`
|
||||
// and we trap the now-orphan engine via Swift ARC (it goes
|
||||
// out of scope when this function returns the error). No
|
||||
// engine leak, no duplicate registration.
|
||||
// Scoped pre-check using `defer` so a
|
||||
// throwing `_validateRoleUnlocked` cannot leave the lock held.
|
||||
// (Bare `_lock.unlock()` after the throw point would leak the
|
||||
// lock and permanently deadlock the host instance.)
|
||||
try { () throws -> Void in
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
try _validateRoleUnlocked(role)
|
||||
}()
|
||||
|
||||
// TODO(phase-future, F11): SynthesisEngine.init is non-throwing
|
||||
// today. If a future change ever makes it throwing (the
|
||||
// reserved `EngineAddError.rebuildFailed` case is
|
||||
// the most likely producer), wrap this construction in
|
||||
// `do/catch` so a throwing init does not bypass the
|
||||
// post-construction commit step. The pre-validate-then-construct
|
||||
// pattern below relies on the construction completing without
|
||||
// throwing.
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: config.blockSize,
|
||||
controlBlockSize: config.controlBlockSize,
|
||||
sampleRate: config.sampleRate,
|
||||
numOutputChannels: config.numOutputChannels,
|
||||
numInputChannels: config.numInputChannels,
|
||||
numAudioBuses: config.numAudioBuses,
|
||||
numControlBuses: config.numControlBuses,
|
||||
eventQueueCapacity: config.eventQueueCapacity,
|
||||
driver: config.driver
|
||||
)
|
||||
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
try _validateRoleUnlocked(role)
|
||||
_registerUnlocked(engine: engine, role: role)
|
||||
return engine
|
||||
}
|
||||
|
||||
// MARK: - Lookup (197.3)
|
||||
|
||||
/// Resolve `role` to its registered engine, or `nil` if no engine
|
||||
/// is registered under that role.
|
||||
public func engine(for role: EngineHostRole) -> SynthesisEngine? {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
return _engines[role]
|
||||
}
|
||||
|
||||
/// Resolve a `SynthesisEngine` back to the role under which it was
|
||||
/// registered, or `nil` if the engine is not host-managed.
|
||||
public func role(for engine: SynthesisEngine) -> EngineHostRole? {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
return _rolesByEngine[engine.identifier]
|
||||
}
|
||||
|
||||
/// Snapshot of all host-registered engines, in no defined order.
|
||||
public var engines: [SynthesisEngine] {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
return Array(_engines.values)
|
||||
}
|
||||
|
||||
/// Snapshot of all host-registered roles, in no defined order.
|
||||
public var roles: [EngineHostRole] {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
return Array(_engines.keys)
|
||||
}
|
||||
|
||||
/// Number of host-registered engines.
|
||||
public var engineCount: Int {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
return _engines.count
|
||||
}
|
||||
|
||||
// MARK: - Lifecycle (197.3)
|
||||
|
||||
/// Start every host-registered engine. Engines start sequentially
|
||||
/// from a snapshot taken under the host's lock; the lock is
|
||||
/// **released before any `engine.start()` is invoked**, so
|
||||
/// concurrent host accessors (`engine(for:)`, `engineCount`,
|
||||
/// other `makeEngine` / `adopt` callers) are not blocked during
|
||||
/// the start sequence. If any engine throws during start, every
|
||||
/// successfully-started engine is rolled back with `stop()`
|
||||
/// before re-throwing the failure (wrapped in
|
||||
/// `EngineHostError.startFailed`).
|
||||
///
|
||||
/// **Snapshot race window.** A `makeEngine` / `adopt` that
|
||||
/// commits between the snapshot and the loop end will leave its
|
||||
/// engine unstarted by this `startAll` call. Callers that need
|
||||
/// "every registered engine is started, even ones added during
|
||||
/// startAll" should call `startAll()` once after all registrations
|
||||
/// complete, or serialise registration and startup on the caller
|
||||
/// side.
|
||||
///
|
||||
/// Iteration order over `_engines` is dictionary-natural and not
|
||||
/// stable. If a caller needs a specific start ordering, register
|
||||
/// the engines first and then call `engine(for:)` to drive them
|
||||
/// individually.
|
||||
public func startAll() throws {
|
||||
// Snapshot the engine list under the
|
||||
// host lock, then iterate WITHOUT holding the lock. `engine.start()`
|
||||
// performs blocking driver init (`CoreAudioDriver.setup` calls
|
||||
// into AUHAL) and can take tens of milliseconds; holding host
|
||||
// ._lock across the full sequence serialises every concurrent
|
||||
// host accessor (engine(for:), engineCount, etc.) for the
|
||||
// entire start duration.
|
||||
_lock.lock()
|
||||
let snapshot: [SynthesisEngine] = Array(_engines.values)
|
||||
_lock.unlock()
|
||||
|
||||
var started: [SynthesisEngine] = []
|
||||
started.reserveCapacity(snapshot.count)
|
||||
// Capture the failing engine directly inside the loop's catch
|
||||
// — the previous draft re-iterated `_engines.values` to find
|
||||
// it by elimination, which relied on Swift Dictionary
|
||||
// iteration order being stable between two separate
|
||||
// iterations (not guaranteed by the language).
|
||||
for engine: SynthesisEngine in snapshot {
|
||||
do {
|
||||
try engine.start()
|
||||
started.append(engine)
|
||||
} catch {
|
||||
// Rollback: stop every engine we successfully started.
|
||||
for prior: SynthesisEngine in started.reversed() {
|
||||
prior.stop()
|
||||
}
|
||||
throw EngineHostError.startFailed(
|
||||
engine: engine.identifier,
|
||||
underlying: error
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop every host-registered engine. Reverse of `startAll()`.
|
||||
/// `engine.stop()` is documented as safe to call when already
|
||||
/// stopped, so a partial `startAll` followed by `stopAll` is a
|
||||
/// no-op for the never-started engines.
|
||||
///
|
||||
/// Same snapshot-and-iterate-unlocked pattern as `startAll`; same
|
||||
/// snapshot-race window — an engine registered concurrently after
|
||||
/// the snapshot is captured will not be stopped by this call.
|
||||
public func stopAll() {
|
||||
// Snapshot then iterate unlocked. Same
|
||||
// rationale as `startAll` — engine.stop() runs `freeWorker.sync`
|
||||
// + `_autoFreeWorker.sync` synchronous drains that take tens
|
||||
// of milliseconds for a real RT engine.
|
||||
_lock.lock()
|
||||
let snapshot: [SynthesisEngine] = Array(_engines.values)
|
||||
_lock.unlock()
|
||||
|
||||
for engine: SynthesisEngine in snapshot {
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Adoption (197.5)
|
||||
|
||||
/// Register an externally-constructed `SynthesisEngine` with this
|
||||
/// host under `role`. Escape hatch for test fixtures and migration
|
||||
/// from direct-ctor codepaths. The engine must already be live
|
||||
/// (its `init` must have completed, which means it is in the
|
||||
/// `EngineLifecycleCoordinator` registry).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - existing: A live `SynthesisEngine` instance to bring under
|
||||
/// host management.
|
||||
/// - role: Role to register the engine under.
|
||||
/// - Throws:
|
||||
/// - `EngineHostError.duplicateRole(role)` — `role` is
|
||||
/// already in use. For `.rtOutput(deviceID:)`, same deviceID
|
||||
/// surfaces here too.
|
||||
/// - `EngineHostError.adoptRejected(engine:reason:)` —
|
||||
/// `existing` is not visible in the lifecycle registry (likely
|
||||
/// deinit-in-progress or constructed via a private API the
|
||||
/// host cannot verify).
|
||||
public func adopt(
|
||||
existing: SynthesisEngine,
|
||||
role: EngineHostRole
|
||||
) throws {
|
||||
// Query the coordinator OUTSIDE the host
|
||||
// lock to avoid the host→coordinator nested lock acquisition
|
||||
// that would deadlock if a caller wraps `adopt` inside
|
||||
// `EngineLifecycleCoordinator.withLifecycleLock`. The TOCTOU
|
||||
// gap (the engine could deinit between the liveness check and
|
||||
// the commit) is acceptable — the worst outcome is `adopt`
|
||||
// succeeds on an engine that has since deinited, which the
|
||||
// host's weak observation would notice through the
|
||||
// EngineLifecycleCoordinator registry as it ages out.
|
||||
let coordinatorEngines: [SynthesisEngine] = EngineLifecycleCoordinator.shared.engines
|
||||
let isLive: Bool = coordinatorEngines.contains { $0 === existing }
|
||||
guard isLive else {
|
||||
throw EngineHostError.adoptRejected(
|
||||
engine: existing.identifier,
|
||||
reason: "Engine not visible in EngineLifecycleCoordinator " +
|
||||
"(deinited, mid-deinit, or constructed via an unsupported path)"
|
||||
)
|
||||
}
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
try _validateRoleUnlocked(role)
|
||||
_registerUnlocked(engine: existing, role: role)
|
||||
}
|
||||
|
||||
// MARK: - NRT batch render (197.4)
|
||||
|
||||
/// Render a batch of `NRTJob` values concurrently and stream
|
||||
/// completion records as each job finishes.
|
||||
///
|
||||
/// Each job spins up its own `SynthesisEngine` with an
|
||||
/// `NRTDriver` — engines are **not** registered with the host's
|
||||
/// role map. They live for the duration of one render and deinit
|
||||
/// when the render task returns. `EngineLifecycleCoordinator`
|
||||
/// handles automatic registry cleanup.
|
||||
///
|
||||
/// Concurrency
|
||||
/// ===========
|
||||
/// At most `maxConcurrent` jobs run simultaneously. The default
|
||||
/// matches `ProcessInfo.processInfo.activeProcessorCount`. Each
|
||||
/// in-flight job runs on its own background `Task` with no
|
||||
/// cross-job state sharing — the binding guarantees enforce
|
||||
/// the isolation at the engine level.
|
||||
///
|
||||
/// Failure semantics
|
||||
/// =================
|
||||
/// If one job throws, the stream propagates the throw to the
|
||||
/// caller's `for try await`. In-flight jobs continue until they
|
||||
/// finish (or their own task is cancelled by the caller). The
|
||||
/// stream is single-shot — once it ends (clean finish or throw),
|
||||
/// no further results arrive.
|
||||
///
|
||||
/// Output order
|
||||
/// ============
|
||||
/// Results stream in **completion order**, not input order. Use
|
||||
/// `NRTResult.jobIndex` to correlate back to the input array.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - jobs: Job descriptors to render. Empty array yields a
|
||||
/// stream that finishes immediately with no results.
|
||||
/// - maxConcurrent: Maximum number of jobs running at once.
|
||||
/// Clamped to `[1, jobs.count]`.
|
||||
/// - Returns: An `AsyncThrowingStream<NRTResult, Error>`. Iterate
|
||||
/// via `for try await result in stream`.
|
||||
public func renderConcurrent(
|
||||
jobs: [NRTJob],
|
||||
maxConcurrent: Int = ProcessInfo.processInfo.activeProcessorCount
|
||||
) -> AsyncThrowingStream<NRTResult, Error> {
|
||||
return AsyncThrowingStream<NRTResult, Error> { continuation in
|
||||
// Empty input → immediate clean finish, no tasks spawned.
|
||||
guard !jobs.isEmpty else {
|
||||
continuation.finish()
|
||||
return
|
||||
}
|
||||
|
||||
let cap: Int = max(1, min(maxConcurrent, jobs.count))
|
||||
|
||||
// Driver task: orchestrates a TaskGroup with bounded
|
||||
// concurrency. `withThrowingTaskGroup` cannot escape its
|
||||
// closure, so the orchestration runs inside a Swift `Task`
|
||||
// that feeds the continuation.
|
||||
let task: Task<Void, Never> = Task {
|
||||
do {
|
||||
try await withThrowingTaskGroup(of: NRTResult.self) { group in
|
||||
var nextJobIndex: Int = 0
|
||||
// Seed up to `cap` initial jobs. Use
|
||||
// `addTaskUnlessCancelled` so a cancelled outer
|
||||
// Task does not spawn additional renders.
|
||||
while nextJobIndex < cap {
|
||||
let index: Int = nextJobIndex
|
||||
let job: NRTJob = jobs[index]
|
||||
_ = group.addTaskUnlessCancelled {
|
||||
try EngineHost._executeJob(job: job, jobIndex: index)
|
||||
}
|
||||
nextJobIndex += 1
|
||||
}
|
||||
// Stream completions; refill from queue.
|
||||
for try await result: NRTResult in group {
|
||||
continuation.yield(result)
|
||||
if nextJobIndex < jobs.count {
|
||||
let index: Int = nextJobIndex
|
||||
let job: NRTJob = jobs[index]
|
||||
_ = group.addTaskUnlessCancelled {
|
||||
try EngineHost._executeJob(job: job, jobIndex: index)
|
||||
}
|
||||
nextJobIndex += 1
|
||||
}
|
||||
}
|
||||
continuation.finish()
|
||||
}
|
||||
} catch let cancellation as CancellationError {
|
||||
// Two distinct sources produce a
|
||||
// `CancellationError` reaching this catch:
|
||||
//
|
||||
// 1. Caller broke the for-await → `onTermination`
|
||||
// → `task.cancel()` → `withThrowingTaskGroup`'s
|
||||
// for-await throws cooperative-cancel. The
|
||||
// outer Task's `isCancelled` is true in this
|
||||
// case. Finish cleanly.
|
||||
//
|
||||
// 2. A user's `build` closure threw
|
||||
// `CancellationError` deliberately → propagated
|
||||
// through `_executeJob` → child task failed →
|
||||
// group rethrew the first child error. The
|
||||
// outer Task is NOT cancelled. Propagate as a
|
||||
// stream throw so the caller sees the job
|
||||
// failure (rethrowing the caught instance
|
||||
// preserves any future payload).
|
||||
//
|
||||
// `Task.isCancelled` discriminates correctly
|
||||
// because it reads the outer driver-Task's own
|
||||
// cancellation state.
|
||||
if Task.isCancelled {
|
||||
continuation.finish()
|
||||
} else {
|
||||
continuation.finish(throwing: cancellation)
|
||||
}
|
||||
} catch {
|
||||
continuation.finish(throwing: error)
|
||||
}
|
||||
}
|
||||
|
||||
// Cancellation handler: stream caller breaks the for-await
|
||||
// → continuation terminates → driver task gets cancelled.
|
||||
// Cancellation suppresses scheduling of queued jobs (Task
|
||||
// cancellation gates `group.addTask` in the refill path).
|
||||
// In-flight `_executeJob` calls run to completion because
|
||||
// `engine.start()` is a synchronous render with no
|
||||
// cooperative-cancellation checks.
|
||||
// `onTermination` fires for both `.finished` and
|
||||
// `.cancelled` reasons. Cancelling a task that has already
|
||||
// finished is a no-op, so the unconditional cancel here
|
||||
// is correct even on the normal-finish path.
|
||||
continuation.onTermination = { @Sendable _ in
|
||||
task.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute one NRT job synchronously: construct a fresh
|
||||
/// `SynthesisEngine` with an `NRTDriver`, invoke `job.build` to
|
||||
/// populate the graph, then `engine.start()` to render (the NRT
|
||||
/// driver renders synchronously inside `start()`). Returns the
|
||||
/// `NRTResult` on completion.
|
||||
///
|
||||
/// Runs on a background `Task` — not the main thread. The engine
|
||||
/// is constructed, used, and deallocated entirely within this
|
||||
/// function's stack frame.
|
||||
private static func _executeJob(
|
||||
job: NRTJob,
|
||||
jobIndex: Int
|
||||
) throws -> NRTResult {
|
||||
let driver: NRTDriver = NRTDriver(
|
||||
outputURL: job.outputURL,
|
||||
duration: job.duration,
|
||||
inputURL: job.inputURL,
|
||||
inputStartOffset: job.inputStartOffset
|
||||
)
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: job.blockSize,
|
||||
sampleRate: job.sampleRate,
|
||||
numOutputChannels: job.numOutputChannels,
|
||||
numInputChannels: job.numInputChannels,
|
||||
driver: driver
|
||||
)
|
||||
// Caller's build closure adds synthesizers before start —
|
||||
// NRTDriver renders synchronously inside start().
|
||||
try job.build(engine)
|
||||
// Monotonic clock for elapsed timing.
|
||||
// `Date().timeIntervalSince(...)` is wall-clock and susceptible
|
||||
// to NTP / system-clock adjustments mid-render.
|
||||
let startNs: UInt64 = DispatchTime.now().uptimeNanoseconds
|
||||
// Ensure engine.stop() runs even if
|
||||
// engine.start() throws — without this, an NRTDriver render
|
||||
// that returns with isRunning still true would let the engine
|
||||
// deinit in the running state, skipping the freeQueue drain
|
||||
// and other teardown bookkeeping.
|
||||
defer { engine.stop() }
|
||||
try engine.start()
|
||||
let endNs: UInt64 = DispatchTime.now().uptimeNanoseconds
|
||||
let elapsed: Double = Double(endNs - startNs) / EngineHost.nanosecondsPerSecond
|
||||
return NRTResult(
|
||||
outputURL: job.outputURL,
|
||||
jobIndex: jobIndex,
|
||||
elapsed: elapsed
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Internal helpers
|
||||
|
||||
/// Validate that `role` can be registered now. Caller must hold
|
||||
/// `_lock`. `.rtOutput(deviceID:)` same-device collisions surface
|
||||
/// here as `.duplicateRole` because the deviceID is part of the
|
||||
/// role's `Hashable` key.
|
||||
private func _validateRoleUnlocked(_ role: EngineHostRole) throws {
|
||||
if _engines[role] != nil {
|
||||
throw EngineHostError.duplicateRole(role)
|
||||
}
|
||||
}
|
||||
|
||||
/// Commit a role registration. Caller must hold `_lock`.
|
||||
private func _registerUnlocked(
|
||||
engine: SynthesisEngine,
|
||||
role: EngineHostRole
|
||||
) {
|
||||
_engines[role] = engine
|
||||
_rolesByEngine[engine.identifier] = role
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// EngineHostError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Errors thrown from `EngineHost` API.
|
||||
public enum EngineHostError: Error, CustomStringConvertible {
|
||||
|
||||
/// Two registrations attempted under the same `EngineHostRole`.
|
||||
/// Use a distinct role (e.g. bump the `nrtRender(slot:)` index, or
|
||||
/// promote to `.custom(String)`).
|
||||
case duplicateRole(EngineHostRole)
|
||||
|
||||
// The `.duplicateDevice(UInt32)` case was removed.
|
||||
// `.rtOutput(deviceID:)` carries the deviceID inside the role's
|
||||
// Hashable key, so same-device registration surfaces as
|
||||
// `.duplicateRole`. The dedicated case had no producer in current
|
||||
// code and forced every exhaustive consumer switch to handle dead
|
||||
// code. Re-add if a future role shape ever cross-cuts deviceID
|
||||
// under a different surrounding enum case.
|
||||
|
||||
/// `host.startAll()` encountered an underlying `engine.start()`
|
||||
/// failure on one of the registered engines. The error chain
|
||||
/// includes the failing engine's identifier and the wrapped
|
||||
/// underlying error.
|
||||
case startFailed(engine: UUID, underlying: any Error)
|
||||
|
||||
/// `host.adopt(existing:)` rejected an engine because its
|
||||
/// `EngineLifecycleCoordinator` registration cannot be assumed
|
||||
/// (the engine has already deinited or was constructed via a path
|
||||
/// the host cannot verify).
|
||||
case adoptRejected(engine: UUID, reason: String)
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .duplicateRole(let role):
|
||||
return "EngineHost: duplicate registration for role \(role). " +
|
||||
"Use a distinct role identifier."
|
||||
case .startFailed(let engine, let underlying):
|
||||
return "EngineHost: startAll() failed at engine \(engine): \(underlying)"
|
||||
case .adoptRejected(let engine, let reason):
|
||||
return "EngineHost: adopt(existing:) rejected engine \(engine): \(reason)"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// EngineHostRole.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Role identifier for engines registered with `EngineHost`.
|
||||
/// Roles serve two purposes:
|
||||
///
|
||||
/// 1. **Lookup key** — `host.engine(for: role)` resolves a role back to
|
||||
/// its `SynthesisEngine` instance.
|
||||
/// 2. **Exclusivity constraint** — duplicate registrations under the
|
||||
/// same role throw `EngineHostError.duplicateRole`. For
|
||||
/// `.rtOutput(deviceID:)`, same-deviceID collisions surface through
|
||||
/// the same `.duplicateRole` path because `deviceID` is part of the
|
||||
/// role's `Hashable` key — the role-equality check covers macOS
|
||||
/// AUHAL exclusive-device contract enforcement directly.
|
||||
///
|
||||
/// Use `.custom(String)` as an escape hatch when no built-in case
|
||||
/// captures the intent (e.g. a debugging-only side engine, or a
|
||||
/// roadmap-specific role not yet a first-class case).
|
||||
public enum EngineHostRole: Hashable, Sendable {
|
||||
|
||||
/// Non-realtime render slot, identified by an integer slot number.
|
||||
/// Typical use: NRT batch render via `host.renderConcurrent(jobs:)`
|
||||
/// places each `NRTJob` on a distinct `.nrtRender(slot:)` role.
|
||||
case nrtRender(slot: Int)
|
||||
|
||||
/// Realtime audio output bound to a specific hardware output device.
|
||||
///
|
||||
/// **macOS.** `deviceID` is the raw `UInt32` form of
|
||||
/// `CoreAudio.AudioDeviceID`. AUHAL grants exclusive ownership per
|
||||
/// output device, so the host's role-keyed uniqueness check
|
||||
/// (`.duplicateRole` on a second registration with the same
|
||||
/// `deviceID`) is genuine AUHAL exclusivity enforcement.
|
||||
///
|
||||
/// **iOS.** `deviceID` is **host-bookkeeping only**. RemoteIO does
|
||||
/// not address individual hardware devices — `AVAudioSession`
|
||||
/// routing chooses the active route at the session layer, and
|
||||
/// AUHAL exclusivity is meaningless under that model. Pass `0` for
|
||||
/// the default iOS route, or any caller-defined unique value if
|
||||
/// you want to keep multiple `.rtOutput` registrations distinct
|
||||
/// for host-internal purposes. For non-output engines on iOS
|
||||
/// (analysis, decoder side-chains), prefer `.auxiliary(name:)` —
|
||||
/// the `.rtOutput` role does not give you anything the auxiliary
|
||||
/// role doesn't on iOS.
|
||||
///
|
||||
/// **Uniqueness contract.** The host throws
|
||||
/// `EngineHostError.duplicateRole` if a second
|
||||
/// `.rtOutput(deviceID:)` with the same `deviceID` is registered —
|
||||
/// two `.rtOutput` roles with identical `deviceID` are the same
|
||||
/// `Hashable` role key, so the role-equality check covers
|
||||
/// same-device collision directly.
|
||||
case rtOutput(deviceID: UInt32)
|
||||
|
||||
/// Auxiliary engine, identified by a free-form name. Useful for
|
||||
/// analysis-only side engines (FFT capture, scope tap), parallel
|
||||
/// decoder chains (ATK ambisonic decode separate from the main
|
||||
/// mix), or any non-output engine that should still be lifecycle-
|
||||
/// managed by the host.
|
||||
case auxiliary(name: String)
|
||||
|
||||
/// Free-form custom role. Escape hatch for use cases not covered
|
||||
/// by the built-in cases. Uniqueness is determined entirely by the
|
||||
/// `String` payload; the host treats `.custom("X")` as distinct
|
||||
/// from `.auxiliary(name: "X")`.
|
||||
case custom(String)
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
// EngineLifecycleCoordinator.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Process-wide registry of live `SynthesisEngine` instances, keyed by
|
||||
/// `SynthesisEngine.identifier`. Module-internal singleton.
|
||||
///
|
||||
/// Purpose
|
||||
/// =======
|
||||
/// 1. **Engine lookup by identifier** — `EngineAddError.boundToOtherEngine`
|
||||
/// carries `current` and `prior` UUIDs; the registry lets diagnostics and
|
||||
/// the multi-engine host (`EngineHost`) resolve a UUID
|
||||
/// back to the actual `SynthesisEngine` instance.
|
||||
/// 2. **Cross-engine lifecycle serialisation** — `withLifecycleLock(_:)` is
|
||||
/// intended to wrap `engine.start()` / `engine.stop()` so concurrent
|
||||
/// start/stop calls across two `SynthesisEngine` instances cannot
|
||||
/// interleave in the `freeWorker.sync` teardown drain (suspected behind
|
||||
/// the deferred parallel-`swift test` crash; see
|
||||
/// `memory/project_parallel_test_crash.md`). Lock is held only across
|
||||
/// main-thread lifecycle calls — RT thread never touches it.
|
||||
/// 3. **Diagnostics** — `count` and `engines` let tests + the host facade
|
||||
/// detect "more than one engine in process" cases that should go through
|
||||
/// `EngineHost`.
|
||||
///
|
||||
/// Thread safety
|
||||
/// =============
|
||||
/// All public methods acquire `_lock` (an `NSLock`). Holds are short — dict
|
||||
/// mutation only — except `withLifecycleLock(_:)`, which is called by
|
||||
/// engine start/stop on the main thread and is expected to hold across the
|
||||
/// full lifecycle transition. No method is callable from the RT audio
|
||||
/// thread; the coordinator is a non-RT-safe construct.
|
||||
///
|
||||
/// Memory model
|
||||
/// ============
|
||||
/// Registry stores `WeakEngineRef` so the coordinator never keeps engines
|
||||
/// alive past their natural reference-counted lifetime. Engines call
|
||||
/// `unregister(_:)` in their `deinit` to evict the dictionary slot
|
||||
/// proactively — without this, slot stays in the dict with a nil weak
|
||||
/// payload until the next `prune()` call. `unregister(_:)` is therefore an
|
||||
/// optimisation, not a correctness requirement.
|
||||
internal final class EngineLifecycleCoordinator: @unchecked Sendable {
|
||||
|
||||
/// Process-wide singleton. The registry is intentionally global —
|
||||
/// engine identity is a process-level concern. Tests must accept that
|
||||
/// instances created in one test case are visible from another until
|
||||
/// they deinit; engine `deinit` evicts the slot. Real tests using the
|
||||
/// coordinator (regression test, host tests)
|
||||
/// should not rely on a globally empty starting state.
|
||||
internal static let shared: EngineLifecycleCoordinator = EngineLifecycleCoordinator()
|
||||
|
||||
/// Internal lock protecting `_engines` mutation and held by
|
||||
/// `withLifecycleLock(_:)` for the duration of engine start/stop.
|
||||
/// `NSLock` is recursion-unsafe; do not nest `withLifecycleLock`.
|
||||
private let _lock: NSLock = NSLock()
|
||||
|
||||
/// Weak references to live engines, keyed by `SynthesisEngine.identifier`.
|
||||
/// Slots whose `engine` property has gone `nil` are pruned lazily on the
|
||||
/// next `register` / `unregister` / `prune` call.
|
||||
private var _engines: [UUID: WeakEngineRef] = [:]
|
||||
|
||||
/// Private to enforce singleton access via ``shared``.
|
||||
private init() {}
|
||||
|
||||
// MARK: - Registration
|
||||
|
||||
/// Add `engine` to the registry. Called from `SynthesisEngine.init`
|
||||
/// after the `identifier` property is assigned. Idempotent on the same
|
||||
/// UUID — re-registering with the same key replaces the weak slot.
|
||||
///
|
||||
/// - Parameter engine: The engine to register. Held weakly.
|
||||
internal func register(_ engine: SynthesisEngine) {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
_engines[engine.identifier] = WeakEngineRef(engine: engine)
|
||||
}
|
||||
|
||||
/// Remove the registry slot for `identifier`. Called from
|
||||
/// `SynthesisEngine.deinit`. Safe to call on a UUID that is not present
|
||||
/// (no-op).
|
||||
///
|
||||
/// - Parameter identifier: The engine identifier to evict.
|
||||
internal func unregister(_ identifier: UUID) {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
_engines.removeValue(forKey: identifier)
|
||||
}
|
||||
|
||||
/// Resolve `identifier` to its live engine, or `nil` if no live engine
|
||||
/// is registered under that key. Used by `EngineAddError` diagnostics
|
||||
/// to print engine details by UUID.
|
||||
///
|
||||
/// - Parameter identifier: The engine identifier to look up.
|
||||
/// - Returns: The live `SynthesisEngine`, or `nil` if absent / deinited.
|
||||
internal func engine(for identifier: UUID) -> SynthesisEngine? {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
return _engines[identifier]?.engine
|
||||
}
|
||||
|
||||
/// Number of live engines currently registered. Counts only slots whose
|
||||
/// weak reference is still resolvable. Used by tests and the
|
||||
/// host facade for "multi-engine detected" diagnostics.
|
||||
internal var count: Int {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
return _engines.values.reduce(0) { $0 + ($1.engine == nil ? 0 : 1) }
|
||||
}
|
||||
|
||||
/// Snapshot of all live engines. Returned as a fresh array to avoid
|
||||
/// holding the lock across caller iteration. Dead weak slots are
|
||||
/// skipped (not returned).
|
||||
internal var engines: [SynthesisEngine] {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
return _engines.values.compactMap { $0.engine }
|
||||
}
|
||||
|
||||
/// Evict registry slots whose weak engine has deinited. Normally
|
||||
/// unnecessary because `SynthesisEngine.deinit` calls `unregister`, but
|
||||
/// kept as a safety valve for unit tests that drop engines on a thread
|
||||
/// that races with the registry lock. Not called automatically.
|
||||
internal func prune() {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
// Collect dead keys first, then remove. Mutating a Dictionary
|
||||
// while iterating it via `for ... in` is undefined behaviour in
|
||||
// Swift — the iterator is not guaranteed stable under
|
||||
// concurrent modification of the underlying storage.
|
||||
let deadKeys: [UUID] = _engines.compactMap { (key, ref) in
|
||||
ref.engine == nil ? key : nil
|
||||
}
|
||||
for key: UUID in deadKeys {
|
||||
_engines.removeValue(forKey: key)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Lifecycle lock
|
||||
|
||||
/// Acquire the lifecycle lock for the duration of `body`. Intended to
|
||||
/// wrap `SynthesisEngine.start()` and `SynthesisEngine.stop()` so that
|
||||
/// concurrent start/stop calls across engines serialise their
|
||||
/// teardown drains (`freeWorker.sync` + `parameterSourceKillQueue` +
|
||||
/// `bufferSwapKillQueue`). Caller must run on the main thread; the RT
|
||||
/// audio thread must never call into the coordinator.
|
||||
///
|
||||
/// `NSLock` is non-reentrant — `withLifecycleLock` calls must not nest.
|
||||
/// If start() ever needs to call stop() on another engine (or
|
||||
/// vice-versa), the engine API must release the outer lock first.
|
||||
///
|
||||
/// **Transitive re-entry warning.** `_lock` also guards
|
||||
/// `register(_:)` and `unregister(_:)`. If `body` triggers any code
|
||||
/// path that constructs or destroys a `SynthesisEngine` (e.g. a
|
||||
/// closure that creates a temporary engine, or releases the last
|
||||
/// strong reference to one), the resulting `register` / `unregister`
|
||||
/// call will deadlock on the same NSLock.
|
||||
/// `EngineHost` enforces the no-engine-lifecycle-inside-body
|
||||
/// contract by owning all engine ctors/dtors itself.
|
||||
///
|
||||
/// - Parameter body: Closure executed under the lifecycle lock.
|
||||
/// - Returns: The return value of `body`.
|
||||
/// - Throws: Re-throws whatever `body` throws.
|
||||
internal func withLifecycleLock<T>(_ body: () throws -> T) rethrows -> T {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
return try body()
|
||||
}
|
||||
}
|
||||
|
||||
/// Weak reference wrapper for the engine registry. Keeps the engine
|
||||
/// dictionary value-type at the cost of one indirection. Cannot be a
|
||||
/// `weak var` directly because dictionaries require their values to be
|
||||
/// stable types, and Swift's `weak` modifier only applies to property
|
||||
/// declarations.
|
||||
internal struct WeakEngineRef {
|
||||
weak var engine: SynthesisEngine?
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// NRTJob.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// One unit of work for `EngineHost.renderConcurrent(jobs:)`.
|
||||
///
|
||||
/// Each job carries the parameters needed to spin up a fresh
|
||||
/// `SynthesisEngine` with an `NRTDriver`, build the synthesis graph,
|
||||
/// and render to a destination file.
|
||||
///
|
||||
/// **Engine isolation.** Each job constructs its own `SynthesisEngine`
|
||||
/// — engines are never shared across jobs. The binding
|
||||
/// system guarantees that `Synthesizer` instances added to one job's
|
||||
/// engine cannot leak into another job's engine. Build a fresh
|
||||
/// graph inside `build` per job; do not capture and reuse synthesizer
|
||||
/// instances across jobs.
|
||||
///
|
||||
/// **No host registration.** Pool jobs do not register their engines
|
||||
/// in the host's role registry. The engine's lifetime is bounded by
|
||||
/// the `render` closure body — it deinits when the closure returns,
|
||||
/// at which point `EngineLifecycleCoordinator.shared.unregister(...)`
|
||||
/// fires automatically.
|
||||
public struct NRTJob: Sendable {
|
||||
|
||||
/// Destination file URL the rendered audio writes to. CAF format
|
||||
/// per `NRTDriver`'s contract; the file is created by the driver
|
||||
/// at `engine.start()` time.
|
||||
public let outputURL: URL
|
||||
|
||||
/// Render duration in seconds. Maps to `NRTDriver.init(duration:)`.
|
||||
public let duration: Double
|
||||
|
||||
/// Audio render block size in samples. Defaults to 512 — matches
|
||||
/// `lyrebirdDefaultResultBufferSize` and the engine-level cap.
|
||||
public let blockSize: Int
|
||||
|
||||
/// Sample rate in Hz.
|
||||
public let sampleRate: Double
|
||||
|
||||
/// Number of hardware output channels. Typical: 2 for stereo, 4
|
||||
/// for quad NRT batch.
|
||||
public let numOutputChannels: Int
|
||||
|
||||
/// Number of hardware input channels the engine reserves. The NRT
|
||||
/// driver clamps the input file's channel count against this value
|
||||
/// at render time, so jobs that read fewer channels than the file
|
||||
/// contains receive only the first `numInputChannels` channels; jobs
|
||||
/// that reserve more than the file provides receive silence on the
|
||||
/// excess channels. Pass `0` for pure synthesis jobs (the default);
|
||||
/// pass the channel count you want exposed to the synth graph when
|
||||
/// `inputURL` is set.
|
||||
public let numInputChannels: Int
|
||||
|
||||
/// Optional source input file URL passed through to
|
||||
/// `NRTDriver(inputURL:)`. `nil` for pure synthesis jobs. To
|
||||
/// actually receive samples from the input file, `numInputChannels`
|
||||
/// must be ≥ 1 — the host passes `numInputChannels` straight
|
||||
/// through to `SynthesisEngine.init`, and the driver clamps file
|
||||
/// channels against it.
|
||||
public let inputURL: URL?
|
||||
|
||||
/// Seconds to skip into `inputURL` before render begins.
|
||||
public let inputStartOffset: Double
|
||||
|
||||
/// Closure invoked once per render with the fresh engine. Add
|
||||
/// synthesizers via `engine.add(_:)` here, *before* the host
|
||||
/// calls `engine.start()`. The closure may throw — a throw
|
||||
/// propagates via the `AsyncThrowingStream` returned from
|
||||
/// `renderConcurrent`.
|
||||
///
|
||||
/// **Threading.** The closure runs on a background `Task` executor
|
||||
/// — not the main thread. If your build logic needs to touch
|
||||
/// `@MainActor`-isolated state (e.g. an `@Observable` parameter
|
||||
/// tree owned by the UI), capture only the value-typed parameters
|
||||
/// into the closure and read them inside, or pre-build a
|
||||
/// `@Sendable` snapshot before assembling the job list.
|
||||
///
|
||||
/// `@Sendable` so the host can dispatch the closure onto a
|
||||
/// background task.
|
||||
public let build: @Sendable (SynthesisEngine) throws -> Void
|
||||
|
||||
public init(
|
||||
outputURL: URL,
|
||||
duration: Double,
|
||||
blockSize: Int = lyrebirdDefaultResultBufferSize,
|
||||
sampleRate: Double = lyrebirdDefaultSampleRate,
|
||||
numOutputChannels: Int = 2,
|
||||
numInputChannels: Int = 0,
|
||||
inputURL: URL? = nil,
|
||||
inputStartOffset: Double = 0.0,
|
||||
build: @escaping @Sendable (SynthesisEngine) throws -> Void
|
||||
) {
|
||||
self.outputURL = outputURL
|
||||
self.duration = duration
|
||||
self.blockSize = blockSize
|
||||
self.sampleRate = sampleRate
|
||||
self.numOutputChannels = numOutputChannels
|
||||
self.numInputChannels = numInputChannels
|
||||
self.inputURL = inputURL
|
||||
self.inputStartOffset = inputStartOffset
|
||||
self.build = build
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// NRTResult.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Completion record for one `NRTJob` rendered by
|
||||
/// `EngineHost.renderConcurrent(jobs:)`.
|
||||
///
|
||||
/// Yielded by the `AsyncThrowingStream` returned from
|
||||
/// `renderConcurrent` — one `NRTResult` per successful job. Failures
|
||||
/// are reported via the stream's throw path, not as an error field on
|
||||
/// `NRTResult`, so every yielded value represents a successful render.
|
||||
public struct NRTResult: Sendable {
|
||||
|
||||
/// Output file URL the render wrote to. Mirrors `NRTJob.outputURL`.
|
||||
public let outputURL: URL
|
||||
|
||||
/// Index of the job in the input array passed to
|
||||
/// `renderConcurrent(jobs:)`. Lets callers correlate stream output
|
||||
/// back to the original job list (results stream in completion
|
||||
/// order, not input order, since job durations differ).
|
||||
public let jobIndex: Int
|
||||
|
||||
/// Wall-clock duration of the render in seconds, measured from
|
||||
/// `engine.start()` entry to return. Useful for comparing
|
||||
/// render-time vs render-duration ratios across jobs.
|
||||
public let elapsed: Double
|
||||
|
||||
public init(
|
||||
outputURL: URL,
|
||||
jobIndex: Int,
|
||||
elapsed: Double
|
||||
) {
|
||||
self.outputURL = outputURL
|
||||
self.jobIndex = jobIndex
|
||||
self.elapsed = elapsed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// RTThreadIdentity.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
|
||||
/// Identifies whether the calling thread is currently inside an audio driver's
|
||||
/// render callback.
|
||||
///
|
||||
/// Used by DEBUG-only asserts in non-RT-safe APIs (e.g. ``ValueComputable``)
|
||||
/// to trap when those APIs are mistakenly called from the RT thread.
|
||||
///
|
||||
/// Mechanism: each RT driver's `render(...)` entry point calls
|
||||
/// ``markCurrentThreadAsRT()`` on first invocation. The marker is stored in
|
||||
/// pthread thread-local storage via `pthread_setspecific` — an O(1) pointer
|
||||
/// write that is allocation-free and signal-safe.
|
||||
///
|
||||
/// In release builds the marker is still set (one pointer write per render
|
||||
/// callback entry — negligible cost) but is never read, so the work is
|
||||
/// effectively dead-stripped if linkers elect to remove the assert call
|
||||
/// sites. Set-once-per-thread optimisation (skipping the `setspecific` when
|
||||
/// the slot is already marked) is intentional to keep the per-callback cost
|
||||
/// at one TLS pointer read in the steady state.
|
||||
internal enum RTThreadIdentity {
|
||||
|
||||
// MARK: - pthread TLS key
|
||||
|
||||
/// Sentinel bit pattern stored in the TLS slot to mark "this is an RT
|
||||
/// thread". Stored as `UInt` (Sendable) and bridged to the pointer type
|
||||
/// expected by `pthread_setspecific` / `pthread_getspecific` at use sites.
|
||||
/// Any non-zero bit pattern works; `1` is distinct from any real heap
|
||||
/// address.
|
||||
private static let _markerBitPattern: UInt = 1
|
||||
|
||||
/// pthread TLS key. Created lazily on first access — always from a
|
||||
/// non-RT call site (engine init / driver setup) because
|
||||
/// ``warmUp()`` is invoked there. RT call sites read this after the
|
||||
/// warm-up, so `pthread_key_create` never runs on the RT thread.
|
||||
///
|
||||
/// `nonisolated(unsafe)` because `pthread_key_t` (a `CUnsignedInt` on
|
||||
/// Darwin) is a trivially-Sendable scalar; the strict-concurrency
|
||||
/// checker can't see through the C typealias. The key is written exactly
|
||||
/// once during the lazy init closure (synchronised by Swift's static-let
|
||||
/// guarantee) and read-only thereafter.
|
||||
private static let _key: pthread_key_t = {
|
||||
var key: pthread_key_t = 0
|
||||
let status: Int32 = pthread_key_create(&key, nil)
|
||||
precondition(status == 0, "pthread_key_create failed with status \(status)")
|
||||
return key
|
||||
}()
|
||||
|
||||
// MARK: - API
|
||||
|
||||
/// Force lazy initialisation of the TLS key from a known non-RT call
|
||||
/// site (engine init / driver setup). Avoids a first-touch allocation on
|
||||
/// the RT thread.
|
||||
internal static func warmUp() {
|
||||
_ = _key
|
||||
}
|
||||
|
||||
/// Mark the calling thread as an RT render thread. Idempotent — safe to
|
||||
/// call on every render callback entry; only writes the TLS slot when it
|
||||
/// isn't already marked.
|
||||
///
|
||||
/// RT-safe: at most one `pthread_setspecific` call per thread, otherwise
|
||||
/// a single TLS pointer comparison. No allocation, no locking.
|
||||
internal static func markCurrentThreadAsRT() {
|
||||
let sentinel: UnsafeMutableRawPointer? = UnsafeMutableRawPointer(bitPattern: _markerBitPattern)
|
||||
if pthread_getspecific(_key) != sentinel {
|
||||
pthread_setspecific(_key, sentinel)
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` if the calling thread has been marked as an RT render thread.
|
||||
///
|
||||
/// Read-only fast path: single TLS pointer comparison. Safe to call from
|
||||
/// any thread.
|
||||
internal static var isCurrentThreadRT: Bool {
|
||||
let sentinel: UnsafeMutableRawPointer? = UnsafeMutableRawPointer(bitPattern: _markerBitPattern)
|
||||
return pthread_getspecific(_key) == sentinel
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DEBUG assert helper
|
||||
|
||||
#if DEBUG
|
||||
/// Trap when invoked from the RT render thread. Used by non-RT-safe APIs
|
||||
/// (``ValueComputable`` conformers, language-side helpers) to catch misuse
|
||||
/// at first call during development.
|
||||
///
|
||||
/// Release builds compile this away entirely — no code, no symbol.
|
||||
///
|
||||
/// The DEBUG branch keeps the abort message a `StaticString` literal so the
|
||||
/// trap path does not heap-allocate before terminating. The call-site
|
||||
/// function name is preserved through the `preconditionFailure` file/line
|
||||
/// parameters (`#file` / `#line` default arguments captured automatically),
|
||||
/// which the Swift runtime prints alongside the message — that's where the
|
||||
/// caller identity surfaces in the crash log. Constructing
|
||||
/// `"\(caller) called on RT thread..."` would allocate a `String` on the
|
||||
/// RT thread, which is itself a CLAUDE.md hard violation.
|
||||
internal func _lyrebirdAssertNotOnRTThread() {
|
||||
if RTThreadIdentity.isCurrentThreadRT {
|
||||
preconditionFailure("Non-RT API called on RT audio render thread. See ValueComputable.md for guidance.")
|
||||
}
|
||||
}
|
||||
#else
|
||||
internal func _lyrebirdAssertNotOnRTThread() {}
|
||||
#endif
|
||||
@@ -0,0 +1,197 @@
|
||||
// RetainQueue.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Type-safe wrapper around `SPSCQueue<Unmanaged<AnyObject>>` for the
|
||||
/// Synthesizer / PreparedNode free-queue pattern.
|
||||
///
|
||||
/// Motivation
|
||||
/// ==========
|
||||
/// The pattern `_ = freeQueue.enqueue(Unmanaged.passRetained(x as AnyObject))`
|
||||
/// appears at every RT-side enqueue site in `SynthesisEngine.applyEvent`.
|
||||
/// Each site has the same three correctness invariants:
|
||||
/// 1. `Unmanaged.passRetained` must run before the enqueue (RT-safe — just an
|
||||
/// atomic refcount bump, no allocation).
|
||||
/// 2. On enqueue success, exactly one `release()` must follow on the
|
||||
/// drain side.
|
||||
/// 3. On enqueue failure (queue full), no `release()` may run on the RT
|
||||
/// thread (ARC deallocation is non-RT-safe). The retained ref leaks
|
||||
/// until process exit; the leak is documented as graceful overflow
|
||||
/// degradation, not a crash.
|
||||
///
|
||||
/// `RetainQueue<T>` centralises these invariants. It exposes:
|
||||
/// - `enqueue(_:)` — RT-safe enqueue. Silent leak on overflow. Used by
|
||||
/// `applyEvent` on the audio render thread.
|
||||
/// - `enqueueBalanced(_:)` — Non-RT enqueue. On overflow, balances the
|
||||
/// retain with a synchronous `release()`. Used by main-thread code
|
||||
/// paths (`engine.remove(_:at:)` pre-retain) where the silent-leak
|
||||
/// degradation is not appropriate.
|
||||
/// - `dequeue()` — Returns `Unmanaged<T>?`. Caller invokes `release()`
|
||||
/// after touching the strongly-typed underlying object. Called by
|
||||
/// the background `freeWorker` drain.
|
||||
///
|
||||
/// RT vs non-RT enqueue
|
||||
/// ====================
|
||||
/// Use `enqueue(_:)` only on the audio render thread. The silent-leak
|
||||
/// overflow path is the canonical RT-safe degradation under burst load —
|
||||
/// `release()` is not safe to call from the RT thread (could cascade
|
||||
/// through ARC into arbitrary `deinit` code, which can allocate / take
|
||||
/// locks / call out to unbounded user code). Size the underlying SPSC
|
||||
/// queue capacity at engine init time generously enough that overflow
|
||||
/// is a misconfiguration signal, not steady-state behaviour.
|
||||
///
|
||||
/// Use `enqueueBalanced(_:)` from main-thread code paths where the
|
||||
/// caller pre-retains a synth for handoff (e.g. `remove(_:at:)`
|
||||
/// enqueues an `Unmanaged` carried inside a `ScheduledEvent`). If that
|
||||
/// outer enqueue fails, the caller has already paid the retain and the
|
||||
/// balanced release closes the loop. Calling `enqueueBalanced` from the
|
||||
/// RT thread is a CLAUDE.md hard-rule violation.
|
||||
///
|
||||
/// Type safety
|
||||
/// ===========
|
||||
/// The generic parameter `T` is the underlying object type the caller is
|
||||
/// retaining. The stored representation is `Unmanaged<AnyObject>` to
|
||||
/// keep the wire type identical to the legacy `SPSCQueue<Unmanaged<AnyObject>>`
|
||||
/// (so freeQueue can hold a heterogeneous mix of `Synthesizer`,
|
||||
/// `PreparedNode`, `Group`, etc.). `dequeue()` returns `Unmanaged<T>` so
|
||||
/// the drain side can call `release()` with the concrete type — though in
|
||||
/// the freeQueue case, callers pass `AnyObject` and the type-erased
|
||||
/// release is what they want.
|
||||
///
|
||||
/// Future direction
|
||||
/// ================
|
||||
/// Per the open question flagged when this queue was introduced, if multi-engine
|
||||
/// processes ever start hitting queue overflow in steady state (rather
|
||||
/// than as misconfiguration), candidate fixes are:
|
||||
/// - Bump the per-engine queue capacity at init time.
|
||||
/// - Add a second-chance overflow buffer that the main-thread drain
|
||||
/// can absorb without RT thread involvement.
|
||||
/// - Promote the enqueue API to return a sentinel "overflowed" state
|
||||
/// instead of a bare `Bool` so callers can record metrics.
|
||||
/// None ship in 196.5; the current shape preserves byte-for-byte
|
||||
/// behaviour with the legacy code while typing the surface.
|
||||
internal struct RetainQueue<T: AnyObject> {
|
||||
|
||||
/// Underlying SPSC queue. The element type stays `Unmanaged<AnyObject>`
|
||||
/// to match the legacy freeQueue wire shape; the typed wrapper layers
|
||||
/// `T` on top via casts at the API boundary.
|
||||
private let _queue: SPSCQueue<Unmanaged<AnyObject>>
|
||||
|
||||
/// Construct a `RetainQueue` with `capacity` slots. The capacity is
|
||||
/// forwarded directly to `SPSCQueue.init`, which preconditions on
|
||||
/// power-of-two capacities.
|
||||
///
|
||||
/// - Parameter capacity: Number of pre-allocated slots. Must be a
|
||||
/// power of two.
|
||||
internal init(capacity: Int) {
|
||||
self._queue = SPSCQueue<Unmanaged<AnyObject>>(capacity: capacity)
|
||||
}
|
||||
|
||||
/// Number of pre-allocated slots in the underlying SPSC queue.
|
||||
internal var capacity: Int { _queue.capacity }
|
||||
|
||||
/// **RT-safe** enqueue. Retains `object` (atomic refcount bump only —
|
||||
/// no allocation) and posts the retained reference to the queue. On
|
||||
/// overflow, the retained reference is silently dropped (leaks until
|
||||
/// process exit). Use from the audio render thread only when the
|
||||
/// silent-leak degradation is acceptable.
|
||||
///
|
||||
/// - Parameter object: The object to retain and enqueue.
|
||||
/// - Returns: `true` on successful enqueue, `false` on overflow.
|
||||
/// Callers that need to know about overflow can record a counter
|
||||
/// off the discarded return value.
|
||||
@discardableResult
|
||||
internal func enqueue(_ object: T) -> Bool {
|
||||
let retained: Unmanaged<AnyObject> = Unmanaged.passRetained(object as AnyObject)
|
||||
let inserted: Bool = _queue.enqueue(retained)
|
||||
// RT-safety: on overflow, cannot call retained.release() — ARC
|
||||
// deallocation cascades are non-RT-safe. The retain leaks.
|
||||
return inserted
|
||||
}
|
||||
|
||||
/// **Non-RT** enqueue. Retains `object` and posts the retained
|
||||
/// reference; on overflow, balances the retain with a synchronous
|
||||
/// `release()` so the object's refcount returns to its pre-call
|
||||
/// value. Use from main-thread code paths where the silent-leak
|
||||
/// degradation is not appropriate.
|
||||
///
|
||||
/// Calling this from the audio render thread is a CLAUDE.md hard-rule
|
||||
/// violation — `release()` can run user `deinit` which may allocate
|
||||
/// or block.
|
||||
///
|
||||
/// - Parameter object: The object to retain and enqueue.
|
||||
/// - Returns: `true` on successful enqueue, `false` on overflow.
|
||||
@discardableResult
|
||||
internal func enqueueBalanced(_ object: T) -> Bool {
|
||||
let retained: Unmanaged<AnyObject> = Unmanaged.passRetained(object as AnyObject)
|
||||
let inserted: Bool = _queue.enqueue(retained)
|
||||
if !inserted {
|
||||
retained.release()
|
||||
}
|
||||
return inserted
|
||||
}
|
||||
|
||||
/// **RT-safe** enqueue accepting a pre-retained `Unmanaged<AnyObject>`
|
||||
/// rather than a strong reference. Used by `SynthesisEngine.applyEvent`
|
||||
/// to re-enqueue the pre-retained `ScheduledEvent.remove` payload and
|
||||
/// the `.groupFree` orphan-group fallback.
|
||||
///
|
||||
/// The caller has already paid the retain; this method just moves
|
||||
/// the reference into the queue. On overflow, the reference is
|
||||
/// **silently dropped** — the retain count stays at +1 permanently
|
||||
/// (leaks until process exit). `release()` cannot run on the RT
|
||||
/// thread (cascades through arbitrary `deinit` code), so silent
|
||||
/// leak is the only RT-safe degradation. Matches the legacy
|
||||
/// `_ = freeQueue.enqueue(ref)` behaviour byte-for-byte.
|
||||
///
|
||||
/// Use ``enqueuePreretainedBalanced(_:)`` if calling from the main
|
||||
/// thread (where `release()` is safe to balance the refcount).
|
||||
///
|
||||
/// - Parameter retainedRef: A pre-retained `Unmanaged` reference. The
|
||||
/// caller transfers ownership of the +1 to the queue.
|
||||
/// - Returns: `true` on successful enqueue, `false` on overflow.
|
||||
@discardableResult
|
||||
internal func enqueuePreretained(_ retainedRef: Unmanaged<AnyObject>) -> Bool {
|
||||
return _queue.enqueue(retainedRef)
|
||||
}
|
||||
|
||||
/// **Non-RT** variant of ``enqueuePreretained(_:)`` that balances the
|
||||
/// refcount on overflow via a synchronous `release()`. Use from
|
||||
/// main-thread code paths (e.g. an `engine.remove(_:at:)` re-entry
|
||||
/// path that has pre-retained the synth and needs the refcount to
|
||||
/// balance if `pendingQueue` is full).
|
||||
///
|
||||
/// Calling from the RT thread is a CLAUDE.md hard-rule violation —
|
||||
/// `release()` is non-RT-safe.
|
||||
///
|
||||
/// - Parameter retainedRef: A pre-retained `Unmanaged` reference.
|
||||
/// - Returns: `true` on successful enqueue, `false` on overflow
|
||||
/// (in which case the refcount has been balanced by `release()`).
|
||||
@discardableResult
|
||||
internal func enqueuePreretainedBalanced(_ retainedRef: Unmanaged<AnyObject>) -> Bool {
|
||||
let inserted: Bool = _queue.enqueue(retainedRef)
|
||||
if !inserted {
|
||||
retainedRef.release()
|
||||
}
|
||||
return inserted
|
||||
}
|
||||
|
||||
/// Dequeue one retained reference, or `nil` if the queue is empty.
|
||||
/// The returned `Unmanaged<T>` carries the +1 retain count; caller
|
||||
/// must invoke `release()` exactly once to balance.
|
||||
///
|
||||
/// Type-cast via `Unmanaged<T>.fromOpaque(toOpaque())` — the
|
||||
/// underlying queue stores `Unmanaged<AnyObject>`, but the typed
|
||||
/// `T` parameter lets the caller release with the correct concrete
|
||||
/// type if needed. For the freeQueue case where `T = AnyObject`
|
||||
/// and callers only care about `release()`, this is identical to a
|
||||
/// direct dequeue.
|
||||
///
|
||||
/// - Returns: The next retained reference, or `nil` if empty.
|
||||
internal func dequeue() -> Unmanaged<T>? {
|
||||
guard let any: Unmanaged<AnyObject> = _queue.dequeue() else { return nil }
|
||||
return Unmanaged<T>.fromOpaque(any.toOpaque())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// SPSCQueue.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Synchronization
|
||||
|
||||
/// Single-Producer Single-Consumer lock-free ring buffer.
|
||||
/// Capacity must be an exact power of two (e.g. 256, 512, 1024).
|
||||
/// No allocation after init; safe to use on the RT audio thread (consumer side).
|
||||
public final class SPSCQueue<T>: @unchecked Sendable {
|
||||
|
||||
private var buffer: [T?]
|
||||
private let mask: Int
|
||||
// Unbounded monotonic counters; actual index = value & mask
|
||||
private let writeIdx: Atomic<Int> = Atomic<Int>(0)
|
||||
private let readIdx: Atomic<Int> = Atomic<Int>(0)
|
||||
|
||||
/// The actual number of slots in the queue. Always a power of two.
|
||||
public var capacity: Int { mask + 1 }
|
||||
|
||||
public init(capacity: Int) {
|
||||
precondition(
|
||||
capacity > 0 && capacity & (capacity - 1) == 0,
|
||||
"SPSCQueue capacity \(capacity) must be a power of two (e.g. 256, 512, 1024)."
|
||||
)
|
||||
self.mask = capacity - 1
|
||||
self.buffer = [T?](repeating: nil, count: capacity)
|
||||
}
|
||||
|
||||
/// Enqueue a value. Called from the producer thread only.
|
||||
/// Returns false if the queue is full.
|
||||
@discardableResult
|
||||
public func enqueue(_ value: T) -> Bool {
|
||||
let write: Int = writeIdx.load(ordering: .relaxed)
|
||||
let read: Int = readIdx.load(ordering: .acquiring)
|
||||
let capacity: Int = mask + 1
|
||||
guard write - read < capacity else { return false }
|
||||
buffer[write & mask] = value
|
||||
writeIdx.store(write + 1, ordering: .releasing)
|
||||
return true
|
||||
}
|
||||
|
||||
/// Dequeue a value. Called from the consumer thread only.
|
||||
/// Returns nil if the queue is empty.
|
||||
///
|
||||
/// The slot is cleared to `nil` after the value is read so the queue does not retain
|
||||
/// any strong references beyond what the consumer holds. Without this, a class-typed
|
||||
/// `T` (or an enum case carrying class payloads — e.g. `ScheduledEvent` holding
|
||||
/// `Synthesizer` / `PreparedNode`) would keep its previous occupant alive in the ring
|
||||
/// slot until the next `enqueue` happens to wrap to the same index, which under sparse
|
||||
/// traffic with `eventQueueCapacity = 1024` could be thousands of blocks. The extra
|
||||
/// ARC release on the consumer thread is intentional and accepted: when the consumer
|
||||
/// is the RT audio thread, the class payload would be released anyway via the returned
|
||||
/// `value` going out of scope shortly after dequeue.
|
||||
public func dequeue() -> T? {
|
||||
let read: Int = readIdx.load(ordering: .relaxed)
|
||||
let write: Int = writeIdx.load(ordering: .acquiring)
|
||||
guard read < write else { return nil }
|
||||
let value: T? = buffer[read & mask]
|
||||
buffer[read & mask] = nil
|
||||
readIdx.store(read + 1, ordering: .releasing)
|
||||
return value
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// SampleTime.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Monotonic sample counter. Updated each block by the engine.
|
||||
public typealias SampleTime = Int64
|
||||
@@ -0,0 +1,42 @@
|
||||
// ScheduledEvent.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// An event that the main thread posts into the pending queue for the RT thread to apply.
|
||||
///
|
||||
/// RT-safety contract:
|
||||
/// - `.add`: carries a `PreparedNode` whose `build()`/`rebuildGraph()` has already been called
|
||||
/// and whose linked-list node has already been heap-allocated — both on the scheduling thread.
|
||||
/// The RT thread only wires pointer references; no allocation occurs in `applyEvent`.
|
||||
/// - `.remove`: carries a pre-retained `Unmanaged<AnyObject>` ref taken on the scheduling
|
||||
/// thread. The RT thread enqueues it directly to `freeQueue` without calling `passRetained`.
|
||||
/// - `.addNode`: like `.add` but carries an explicit `NodePosition` describing where in the
|
||||
/// tree to insert the node. Always applied immediately (targetTime = 0).
|
||||
/// - `.groupFree`: tears down a Group and all its children on the RT thread. The optional
|
||||
/// `parentGroup` is used as a fast-path for removal; falls back to recursive rootGroup search.
|
||||
///
|
||||
/// Parameter updates are NOT routed through `ScheduledEvent`. They are atomic stores to
|
||||
/// the projected `ParameterNode` / `UIParamNode` of an `@LiveParam` / `@UIParam` property —
|
||||
/// the RT thread picks up the new value at the start of the next (sub-)block via an
|
||||
/// acquiring atomic load inside `_computeSamples`.
|
||||
///
|
||||
/// `@unchecked Sendable` because the Synthesizer references are managed exclusively by the
|
||||
/// scheduling contract: allocated on main, freed on the background drain thread.
|
||||
internal enum ScheduledEvent: @unchecked Sendable {
|
||||
case add(PreparedNode, at: SampleTime)
|
||||
case remove(any Synthesizer, retainedRef: Unmanaged<AnyObject>, at: SampleTime)
|
||||
case addNode(PreparedNode, NodePosition, at: SampleTime)
|
||||
case groupFree(Group, parentGroup: Group?, at: SampleTime)
|
||||
|
||||
/// The sample time at which this event should be applied.
|
||||
internal var targetTime: SampleTime {
|
||||
switch self {
|
||||
case .add(_, let t): return t
|
||||
case .remove(_, _, let t): return t
|
||||
case .addNode(_, _, let t): return t
|
||||
case .groupFree(_, _, let t): return t
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,93 @@
|
||||
// SynthesisEngineConfig.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Carrier type for the `SynthesisEngine.init` parameter list, used by
|
||||
/// `EngineHost.makeEngine(role:config:)` so callers can pass a
|
||||
/// single value-typed configuration rather than threading every engine
|
||||
/// init parameter through the host API.
|
||||
///
|
||||
/// All fields mirror the underlying `SynthesisEngine.init` signature
|
||||
/// one-for-one. Defaults match the engine init's documented defaults
|
||||
/// (e.g. `numAudioBuses = lyrebirdDefaultNumAudioBuses`,
|
||||
/// `eventQueueCapacity = lyrebirdDefaultEventQueueCapacity`).
|
||||
///
|
||||
/// Use this type only when constructing engines via
|
||||
/// `EngineHost`. The direct `SynthesisEngine.init` constructor
|
||||
/// continues to take individual parameters and is unaffected.
|
||||
///
|
||||
/// Not `Sendable` because `driver: AudioDriver` is a class without a
|
||||
/// Sendable conformance guarantee — drivers are RT-thread-aware types
|
||||
/// that typically conform via `@unchecked Sendable` per their own
|
||||
/// contracts. Construct the config on the thread that calls
|
||||
/// `EngineHost.makeEngine` — the host's `makeEngine` carries no
|
||||
/// actor isolation, so passing a `SynthesisEngineConfig` from a
|
||||
/// background queue into `makeEngine` is the caller's responsibility
|
||||
/// to keep race-free (the driver field is the only non-value member,
|
||||
/// and drivers are designed to be transferred by ownership at construction
|
||||
/// time).
|
||||
public struct SynthesisEngineConfig {
|
||||
|
||||
/// Audio render block size in samples. Must be `<=
|
||||
/// lyrebirdDefaultResultBufferSize` (512). Power-of-two not
|
||||
/// required (validated against the `eventQueueCapacity` power-of-two
|
||||
/// rule separately).
|
||||
public let blockSize: Int
|
||||
|
||||
/// Optional control-rate sub-block size. `nil` defers to the
|
||||
/// driver's `suggestedControlBlockSize`; if the driver also returns
|
||||
/// `nil`, the engine runs at full-block control rate.
|
||||
public let controlBlockSize: Int?
|
||||
|
||||
/// Sample rate in Hz. `SynthesisEngine.setSampleRate(_:)` can change
|
||||
/// this later while the engine is stopped.
|
||||
public let sampleRate: Double
|
||||
|
||||
/// Number of hardware output channels reserved at bus indices
|
||||
/// `0..<numOutputChannels`.
|
||||
public let numOutputChannels: Int
|
||||
|
||||
/// Number of hardware input channels reserved at bus indices
|
||||
/// `numOutputChannels..<numOutputChannels+numInputChannels`.
|
||||
public let numInputChannels: Int
|
||||
|
||||
/// Total audio bus count. Defaults to `lyrebirdDefaultNumAudioBuses`.
|
||||
public let numAudioBuses: Int
|
||||
|
||||
/// Total control bus count. Defaults to `lyrebirdDefaultNumControlBuses`.
|
||||
public let numControlBuses: Int
|
||||
|
||||
/// SPSC pending-queue capacity. Must be power-of-two. Defaults to
|
||||
/// `lyrebirdDefaultEventQueueCapacity`.
|
||||
public let eventQueueCapacity: Int
|
||||
|
||||
/// Audio driver instance. Held by the engine via `let driver` after
|
||||
/// `init`. Caller transfers ownership at construction time.
|
||||
public let driver: AudioDriver
|
||||
|
||||
public init(
|
||||
blockSize: Int,
|
||||
controlBlockSize: Int? = nil,
|
||||
sampleRate: Double,
|
||||
numOutputChannels: Int,
|
||||
numInputChannels: Int,
|
||||
numAudioBuses: Int = lyrebirdDefaultNumAudioBuses,
|
||||
numControlBuses: Int = lyrebirdDefaultNumControlBuses,
|
||||
eventQueueCapacity: Int = lyrebirdDefaultEventQueueCapacity,
|
||||
driver: AudioDriver
|
||||
) {
|
||||
self.blockSize = blockSize
|
||||
self.controlBlockSize = controlBlockSize
|
||||
self.sampleRate = sampleRate
|
||||
self.numOutputChannels = numOutputChannels
|
||||
self.numInputChannels = numInputChannels
|
||||
self.numAudioBuses = numAudioBuses
|
||||
self.numControlBuses = numControlBuses
|
||||
self.eventQueueCapacity = eventQueueCapacity
|
||||
self.driver = driver
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// SynthesisEngineConfigError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Errors thrown by ``SynthesisEngine`` config setters that mutate pre-run
|
||||
/// parameters (sample rate, channel counts).
|
||||
///
|
||||
/// All setters are non-RT, main-thread-safe, and require the engine to be
|
||||
/// stopped — see ``SynthesisEngine/setSampleRate(_:)`` and friends.
|
||||
public enum SynthesisEngineConfigError: Error, Sendable {
|
||||
/// The setter was called while ``SynthesisEngine/isRunning`` is `true`.
|
||||
/// Configuration may only be changed when the engine is idle or stopped.
|
||||
case engineIsRunning
|
||||
/// The supplied value failed validation (e.g. non-positive sample rate,
|
||||
/// negative input channel count, zero output channel count). The associated
|
||||
/// string identifies the parameter and the rule that was violated.
|
||||
case invalidValue(String)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// SynthesisEngineListener.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Receives lifecycle state transitions from a ``SynthesisEngine``.
|
||||
///
|
||||
/// Attach via ``SynthesisEngine/addSynthesisEngineListener(_:)``; the engine holds a
|
||||
/// weak reference and auto-prunes deallocated listeners on subsequent fan-outs. Detach
|
||||
/// explicitly with ``SynthesisEngine/removeSynthesisEngineListener(_:)``.
|
||||
///
|
||||
/// Callbacks fire on the thread that invoked ``SynthesisEngine/start()`` or
|
||||
/// ``SynthesisEngine/stop()`` — typically the main thread for GUI-driven apps.
|
||||
/// Listeners that mutate SwiftUI `@Published` state can do so directly.
|
||||
///
|
||||
/// ```swift
|
||||
/// final class StatusModel: ObservableObject, SynthesisEngineListener {
|
||||
/// @Published var label = "Idle"
|
||||
/// func synthesisEngine(_ engine: SynthesisEngine,
|
||||
/// didChangeState state: SynthesisEngineState) {
|
||||
/// switch state {
|
||||
/// case .idle: label = "Idle"
|
||||
/// case .starting: label = "Starting…"
|
||||
/// case .started: label = "Running"
|
||||
/// case .startFailed(let err): label = "Failed: \(err)"
|
||||
/// case .tearingDown: label = "Stopping…"
|
||||
/// case .stopped: label = "Stopped"
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
public protocol SynthesisEngineListener: AnyObject {
|
||||
/// Invoked whenever the engine transitions between ``SynthesisEngineState`` cases.
|
||||
func synthesisEngine(
|
||||
_ engine: SynthesisEngine,
|
||||
didChangeState state: SynthesisEngineState
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// SynthesisEngineState.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Lifecycle state of a ``SynthesisEngine``.
|
||||
///
|
||||
/// Transitions are fired by ``SynthesisEngine`` to every attached
|
||||
/// ``SynthesisEngineListener`` on the same thread that called ``SynthesisEngine/start()``
|
||||
/// or ``SynthesisEngine/stop()`` — typically the main thread.
|
||||
///
|
||||
/// Typical sequences:
|
||||
/// - Successful run: `.idle` → `.starting` → `.started` → `.tearingDown` → `.stopped`
|
||||
/// - Failed start: `.idle` → `.starting` → `.startFailed(err)` → `.idle`
|
||||
///
|
||||
/// `startFailed` carries the error thrown by the underlying driver. After the failure
|
||||
/// callback fans out, the engine transitions back to `.idle` so a subsequent call to
|
||||
/// ``SynthesisEngine/start()`` produces a fresh `.starting` event.
|
||||
public enum SynthesisEngineState: Sendable {
|
||||
/// Post-init, fully stopped, or recovered from a failed start.
|
||||
case idle
|
||||
/// ``SynthesisEngine/start()`` entered; driver setup has not yet completed.
|
||||
case starting
|
||||
/// Driver started successfully; ``SynthesisEngine/isRunning`` is `true`.
|
||||
case started
|
||||
/// Driver setup or start threw. Carries the thrown error.
|
||||
case startFailed(Error)
|
||||
/// ``SynthesisEngine/stop()`` entered; driver teardown in progress.
|
||||
case tearingDown
|
||||
/// ``SynthesisEngine/stop()`` complete; all queues drained.
|
||||
case stopped
|
||||
}
|
||||
Reference in New Issue
Block a user