8eb64f883f
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
553 lines
24 KiB
Swift
553 lines
24 KiB
Swift
// 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,
|
|
maxEventsPerBlock: config.maxEventsPerBlock,
|
|
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,
|
|
format: job.format,
|
|
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
|
|
}
|
|
}
|