560724d116
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated synths were hard-freed instead of released). - New: quickstart project template + LyrebirdQuickstartDemo. - Docs: every example typechecked or provably illustrative (426->542); ~20 wrong-API examples fixed; root docs brought under the compile guard. - Fixed: NRT/Score demo Package.swift build from terminal again. See RELEASES.md for details.
331 lines
29 KiB
Markdown
331 lines
29 KiB
Markdown
# Lyrebird — Architecture
|
||
|
||
A technical tour of how Lyrebird runs audio: the thread model, how the non-real-time world talks to the real-time render callback without locks, how a block is split for sample-accurate scheduling, how bus memory is managed, and how work fans out across cores. The audience is engineers who want to answer "how does this actually work?" and "how would I do *X*?" — not a getting-started guide (see [`README.md`](README.md)) and not an API reference (see `docs/`).
|
||
|
||
The single organizing principle: **the real-time audio thread never allocates, never locks, never blocks.** Every design decision below follows from that constraint.
|
||
|
||
---
|
||
|
||
## 1. The thread model
|
||
|
||
Lyrebird is a single-process framework. At runtime there are up to four kinds of execution context. Knowing which thread you are on tells you what you are allowed to do.
|
||
|
||
### 1.1 The real-time (RT) audio thread
|
||
|
||
This is the Core Audio render callback, invoked by the OS audio HAL every `blockSize` samples at real-time scheduling priority. On macOS the callback is driven by an AUHAL unit (`kAudioUnitSubType_HALOutput`, chosen over `DefaultOutput` because it supports full-duplex input + output); on iOS by RemoteIO. The callback path is:
|
||
|
||
```
|
||
HAL → lyrebirdRenderCallback → CoreAudioDriver.render() → SynthesisEngine.processBlock()
|
||
```
|
||
|
||
Everything reachable from `processBlock()` runs under the RT contract:
|
||
|
||
- **No allocation** — no `Array`/`String`/object creation, no implicit Copy-on-Write reallocs.
|
||
- **No locks** — no `Mutex`, `NSLock`, `DispatchSemaphore`, no `os_unfair_lock`.
|
||
- **No blocking** — no file/network I/O, no `DispatchQueue.async`, no waiting on another thread.
|
||
- **No ARC churn** — no `retain`/`release` on hot paths; cached references are held via `Unmanaged`.
|
||
- **No `print` / no dynamic casts** — no Foundation logging, no `as?`/`is` runtime type checks (inputs are classified once at `init`).
|
||
|
||
The RT thread is the **single writer** of: the engine's audio bus memory, `_currentTime`, the segment serial, and the CPU-load statistics. Everyone else reads those through atomics.
|
||
|
||
### 1.2 The main / non-RT thread
|
||
|
||
This is wherever you call the public API: `engine.add(_:)`, `engine.schedule(_:)`, `engine.remove(_:)`, and parameter mutations. It is allowed to do everything the RT thread cannot. Its job is to do all the expensive work — allocate synthesizers, run `build()` to construct the generator DAG, retain references — *before* handing a fully-prepared, pointer-only payload to the RT thread through a lock-free queue. SwiftUI `@Published` updates, file loading, and locks all live here.
|
||
|
||
### 1.3 The deferred-deallocation worker
|
||
|
||
When a synth is removed, its memory must not be freed on the RT thread (ARC dealloc can take locks and walk arbitrary deinit chains). Instead the RT thread hands the retained reference to a background queue — `DispatchQueue(label: "lyrebird.free", qos: .background)` — which drains a free-queue on a timer and calls `Unmanaged.release()` off the hot path. ARC deinit therefore always fires on a non-RT thread.
|
||
|
||
### 1.4 ParallelGroup worker threads
|
||
|
||
When a `ParallelGroup` evaluates more than one child, it dispatches the children across cores via `DispatchQueue.concurrentPerform`. Those worker invocations run *as part of* one `processBlock()` call — they are RT-priority work and inherit the full RT contract. They are not a long-lived pool you manage; `concurrentPerform` joins before the block returns. (See §7.)
|
||
|
||
### 1.5 The NRT (offline) render thread
|
||
|
||
`NRTDriver` is a passive driver: instead of an audio device callback, it runs a tight loop calling `engine.processBlock()` as fast as possible until the requested duration is filled, writing each block to a CAF file via `ExtAudioFile`. The *same* `processBlock` and the *same* scheduling stack run — there is no separate offline code path — but there is no hardware clock, so it renders faster than real time. The RT contract still holds inside `processBlock`, but the driver loop around it is ordinary code.
|
||
|
||
---
|
||
|
||
## 2. Non-RT → RT communication: the lock-free handoff
|
||
|
||
The central problem: the main thread wants to add/remove/retune voices, but cannot take a lock that the RT thread might wait on, and the RT thread cannot allocate or block. The solution is a set of **single-producer / single-consumer (SPSC) lock-free ring queues** plus a strict rule that all allocation happens on the producer side.
|
||
|
||
### 2.1 SPSCQueue
|
||
|
||
`SPSCQueue<T>` (in `Sources/Lyrebird/Engine/SPSCQueue.swift`) is the shared primitive. It is a fixed-size ring buffer (`[T?]`, capacity rounded to a power of two) with two atomic, unbounded, monotonically-increasing counters from the `Synchronization` module:
|
||
|
||
- `writeIdx: Atomic<Int>` — advanced by the producer with a **releasing** store on enqueue.
|
||
- `readIdx: Atomic<Int>` — advanced by the consumer with an **acquiring** load on dequeue.
|
||
|
||
The real slot is `counter & mask`. Occupancy is `writeIdx - readIdx`. The release/acquire pairing establishes a happens-before edge: everything the producer wrote into the slot is visible to the consumer once it observes the new `writeIdx`. No lock is ever taken. Because the capacity is fixed and the buffer is allocated up front, enqueue/dequeue never allocate.
|
||
|
||
`Synchronization.Atomic` is why the platform floor is **macOS 15 / iOS 18** — earlier OSes lack it.
|
||
|
||
### 2.2 The queues
|
||
|
||
| Queue | Direction | Carries | Notes |
|
||
|---|---|---|---|
|
||
| `pendingQueue` | main → RT | `ScheduledEvent` (add/remove/param/groupFree) | Default capacity 1024 (power-of-2). Enqueue returns `Bool`; on full, the event drops and `pendingQueueDroppedCount` increments so the caller can detect a burst overflow. |
|
||
| `freeQueue` | RT → free-worker | `Unmanaged<AnyObject>` | Pre-retained on main thread; released on the background worker. |
|
||
| `parameterSourceKillQueue` | RT → main | pointer to a replaced parameter source | Old `@LiveParam`/`@UIParam` source freed off-RT after a swap. |
|
||
| `bufferSwapKillQueue` | RT → main | pointer to a replaced `LyrebirdBuffer` | Old buffer freed off-RT after a hot-swap. |
|
||
| `triggerQueue` | RT → listener | `TriggerEvent` | RT-side trigger notifications surfaced to non-RT listeners. |
|
||
|
||
The design pattern is identical across all of them: **whoever can allocate does the allocation; the queue moves only pointers / pre-built values.**
|
||
|
||
### 2.3 ScheduledEvent — a pointer-only payload
|
||
|
||
The work the RT thread does to apply an event is deliberately trivial: re-link a node into the tree, or store a parameter value. All the heavy lifting (allocating the synth, calling `build()`, constructing the `PreparedNode`, retaining it) happens on the main thread *before* the event is enqueued. The enum captures exactly the pre-built state needed:
|
||
|
||
- `.add(PreparedNode, at: SampleTime)` — node already built and retained.
|
||
- `.addNode(PreparedNode, NodePosition, at: SampleTime)` — same, with an explicit tree position.
|
||
- `.remove(Synthesizer, retainedRef: Unmanaged, at: SampleTime)` — the synth is retained via `Unmanaged.passRetained()` on the main thread so the RT thread can hand it to `freeQueue` without touching ARC.
|
||
- `.groupFree(Group, parentGroup: Group?, at: SampleTime)` — frees a whole subtree.
|
||
|
||
### 2.4 Binding: single-shot atomic compare-exchange
|
||
|
||
A synthesizer may belong to exactly one engine at a time. This is enforced not with a lock but with a single-shot CAS on `SynthesizerBase._engineBinding: Atomic<UInt>`, which stores the engine pointer's bit pattern:
|
||
|
||
```
|
||
compareExchange(expected: 0, desired: enginePtrBits, ordering: .acquiringAndReleasing)
|
||
```
|
||
|
||
If the slot was already non-zero, the synth is bound elsewhere → `engine.add` throws `EngineAddError.boundToOtherEngine(current:prior:)` (or `.doubleAdd` if it is the *same* engine without an intervening `remove`). The errors map raw pointers back to human-readable `SynthesisEngine.identifier: UUID` values via a process-wide `EngineLifecycleCoordinator` registry (weakly holding every live engine). There is bounded stale-pointer recovery (max 2 passes): if the previously-bound engine has since deinit'd, the binding is cleared and the CAS retried.
|
||
|
||
`LyrebirdBuffer` extends this to a **two-tier** model for cross-engine sharing: `bindExclusive` (CAS on `_exclusiveEngine`, one engine, fails if any read-only holder) vs. `bindReadOnly` (refcounted via `_readOnlyRefCount: Atomic<Int>`, N engines, fails if an exclusive holder exists). The two tiers are mutually exclusive at any instant. Single-engine code needs none of this — an unbound buffer just works.
|
||
|
||
---
|
||
|
||
## 3. The render callback flow
|
||
|
||
`SynthesisEngine.processBlock()` is the heart of the system. One invocation produces one hardware block. In order:
|
||
|
||
1. **Mark RT identity** — `RTThreadIdentity.markCurrentThreadAsRT()` sets a thread-local flag so `DEBUG` assertions elsewhere can trap RT-illegal calls.
|
||
2. **Flush denormals** — `fesetenv()` enables flush-to-zero so denormal floats don't tank CPU.
|
||
3. **Zero the audio buses** — `vDSP_vclr()` clears audio bus memory for the block. (Control buses are *not* zeroed — they persist.)
|
||
4. **Copy hardware input** — incoming mic/line samples are `memcpy`'d into the reserved input buses. Never via Swift array assignment (which could trigger a CoW dealloc on the RT thread).
|
||
5. **Drain `pendingQueue`** and split the block at event boundaries (§4).
|
||
6. **Evaluate each segment** in order via `evaluateSegment(count:busOffset:)`.
|
||
7. **Advance `_currentTime`** by `blockSize` with a releasing atomic store.
|
||
8. **Update CPU stats** (EMA, relaxed atomics — best-effort).
|
||
9. **Write the scope tap** if an oscilloscope capture is attached.
|
||
10. **Apply the master gain ramp** — interpolated from the previous block's gain to the current target so volume/mute changes never click.
|
||
|
||
`blockSize` is capped at **512** (`lyrebirdDefaultResultBufferSize`) because every generator's output buffer is pre-allocated to exactly that size — there is no grow path on the RT thread.
|
||
|
||
---
|
||
|
||
## 4. Sample-accurate scheduling: block splitting
|
||
|
||
Audio is processed in blocks, but musical events must land on exact samples. Lyrebird reconciles the two by **splitting a block into segments at event boundaries** and evaluating each segment independently.
|
||
|
||
Time is `SampleTime` (`Int64`), a monotonic sample counter incremented by `blockSize` each block, written only by the RT thread and read elsewhere via atomic load. A `ScheduledEvent` carries an absolute `targetTime`.
|
||
|
||
Within one `processBlock`, with `blockStart = currentTime` and `blockEnd = blockStart + blockSize`:
|
||
|
||
```
|
||
1. Collect events whose targetTime ∈ [blockStart, blockEnd) from pendingQueue
|
||
(plus any carried over from a previous block).
|
||
2. Sort by targetTime — allocation-free insertion sort.
|
||
3. cursor = 0
|
||
for each event E, at offset = E.targetTime - blockStart:
|
||
if offset > cursor:
|
||
evaluateSegment(count: offset - cursor, busOffset: cursor) // render up to the event
|
||
applyEvent(E) // pointer-only: link/unlink node, or store a parameter
|
||
cursor = offset
|
||
evaluateSegment(count: blockSize - cursor, busOffset: cursor) // render the tail
|
||
4. currentTime += blockSize
|
||
```
|
||
|
||
So a synth scheduled at sample offset 137 of a 512-sample block causes the block to render as `[0..137)`, then the synth links in, then `[137..512)` renders with it active — and its `Out` generator begins writing at exactly `busOffset = 137`. Events in the past clamp to the block start; a hard cap of **256 events per block** bounds worst-case work (excess defers/drops).
|
||
|
||
`evaluateSegment` bumps `_atomicSegmentSerial` (releasing store), builds a `SynthGraph` around a pre-allocated empty parameter table (no per-segment alloc), and calls `rootGroup.evaluate(graph:count:)`. Crucially, generators render `count` samples — *not* always `blockSize` — and advance their internal state (oscillator phase, filter history, delay write heads) by exactly `count`. This is why a generator's `_computeSamples` must use `count`, never `engine.blockSize`: it may be called several times within a single block.
|
||
|
||
---
|
||
|
||
## 5. Bus memory
|
||
|
||
Buses are the only shared signal medium between nodes, and all of their memory is pre-allocated at `start()` and never resized.
|
||
|
||
- `audioBuses: [[Float]]` — shape `[numAudioBuses][blockSize]`.
|
||
- `controlBuses: [Float]` — shape `[numControlBuses]` (one ramp-target value per control bus).
|
||
|
||
Layout reserves the low audio buses for hardware:
|
||
|
||
```
|
||
[0 .. numOutputChannels) → hardware output (memcpy'd to the device)
|
||
[numOutputChannels .. +numInputChannels) → hardware input (filled from the device)
|
||
[numOutputChannels+numInputChannels .. numAudioBuses) → user buses
|
||
```
|
||
|
||
Per-block semantics differ by type:
|
||
|
||
- **Audio buses** are zeroed each block, written by `Out.Audio` with `+=` (so multiple voices on one bus mix naturally), and read by `In.Audio`.
|
||
- **Control buses** are *not* zeroed; a value persists until overwritten, carrying a single per-block ramp target.
|
||
|
||
"How would I route one synth into another?" → write to a user audio bus with `Out.Audio(bus: N, ...)` and read it with `In.Audio(bus: N)` in a downstream synth placed later in the node tree. Evaluation order (the node tree, head-to-tail) determines who sees whose output within a block.
|
||
|
||
### 5.1 ScratchBuses (parallel isolation)
|
||
|
||
When work is parallelized, concurrent children cannot all `+=` into the same shared engine bus without racing. Each `ParallelGroup` child therefore renders into its own pre-allocated `ScratchBuses` (same shape as the engine buses, plus a per-bus **dirty mask**). After the parallel barrier, a sequential merge pass sums each *dirty* scratch bus into the engine buses with `vDSP_vadd`. The dirty mask is the key optimization: a typical stereo voice touches 2 buses, so the merge does ~2 vector-adds instead of scanning all `numAudioBuses`.
|
||
|
||
---
|
||
|
||
## 6. How RT-safety is actually enforced
|
||
|
||
The contract in §1.1 is upheld by four mechanisms, not by hope:
|
||
|
||
1. **Pre-allocation everywhere.** Engine buses and parameter tables in `start()`; per-child `ScratchBuses` in `ParallelGroup.build()`; every generator's `_result` buffer (512 doubles) in `GeneratorBase.init()`. The RT thread only ever reads/writes into storage that already exists. `SynthesisEngine.init` rejects `blockSize > 512`.
|
||
2. **Atomics-only synchronization.** All cross-thread state is a `Synchronization.Atomic<T>`. Memory ordering is deliberate: releasing stores publish, acquiring loads consume, relaxed loads are used only for best-effort stats. There are no mutexes anywhere on the signal path.
|
||
3. **`Unmanaged` for cached references.** The engine caches things like the scope-tap target as `Unmanaged` so the RT thread can reach them without an ARC retain/release. Removal uses `Unmanaged.passRetained()` on the main thread and `Unmanaged.release()` on the free-worker — the RT thread only *moves* the pointer.
|
||
4. **Thread-local debug asserts.** The `RTThreadIdentity` TLS flag lets RT-illegal entry points (e.g. running a user `ValueComputable` closure) assert in `DEBUG`. The flag's key is warmed up off-RT in `CoreAudioDriver.init()` so even the first lookup doesn't allocate on the audio thread.
|
||
|
||
This is the lens for "would this be RT-safe?": if your code, reachable from a generator's `_computeSamples` or `calculatedSamples`, would allocate, lock, log, or touch ARC, it belongs on the main thread or behind a queue — not in the render path. The catalog of helpers in `docs/protocols/writing-generators.md` §13 exists precisely so generator authors never have to hand-roll RT-unsafe boilerplate.
|
||
|
||
---
|
||
|
||
## 7. Multi-core: ParallelGroup
|
||
|
||
`ParallelGroup` is a `Synthesizer` that evaluates its children concurrently to use more than one core for a heavy graph. Its lifecycle inside one segment:
|
||
|
||
```swift
|
||
// 1. Clear each child's scratch buses over the segment's sample range.
|
||
for slot in scratchSlots { slot.clearDirtyBuses(offset: offset, count: count) }
|
||
|
||
// 2. Evaluate.
|
||
if children.count == 1 {
|
||
// Fast path: skip the dispatch entirely, render inline.
|
||
children[0].evaluate(graph: SynthGraph(..., scratchBuses: slots[0]), count: count)
|
||
} else {
|
||
DispatchQueue.concurrentPerform(iterations: children.count) { i in
|
||
// Each i renders into its own scratchSlots[i] — no shared write target, no race.
|
||
children[i].evaluate(graph: SynthGraph(..., scratchBuses: scratchSlots[i]), count: count)
|
||
}
|
||
}
|
||
|
||
// 3. Barrier has passed. Merge dirty scratch buses into the engine buses.
|
||
for slot in scratchSlots {
|
||
for bus where slot.dirty[bus] { vDSP_vadd(slot.buses[bus], engine.audioBuses[bus], ...) }
|
||
}
|
||
```
|
||
|
||
Correctness rests on isolation and the segment serial:
|
||
|
||
- **Isolation** — each worker writes only its own `ScratchBuses`, so concurrent `Out.Audio` writes never collide. The merge is sequential.
|
||
- **`_atomicSegmentSerial`** — incremented once (releasing) before the parallel region; workers read it (acquiring). Generator result caches key on this serial, so a stale cache from a previous segment is never reused inside a concurrent worker.
|
||
|
||
Constraints that fall out of the model — useful when answering "why doesn't *X* work in parallel?":
|
||
|
||
- **No cross-child fan-out.** Sharing one generator instance between two children races on its cache. Build a copy per child.
|
||
- **Control-bus writes aren't scratch-isolated.** Two children writing the same control bus race.
|
||
- **No nested ParallelGroups.** An inner merge would bypass the outer scratch.
|
||
- **Children are fixed at `build()`.** Adding/removing children while active is undefined.
|
||
|
||
The single-child inline fast path matters: dispatching `concurrentPerform` for one child would cost more in scheduler overhead than it saves.
|
||
|
||
---
|
||
|
||
## 8. Multiple engines: EngineHost and NRT batch rendering
|
||
|
||
A process can run several engines — e.g. one real-time output plus a pool of offline renderers. `EngineHost` is the facade that owns them, keyed by an `EngineHostRole` (`.rtOutput(deviceID:)`, `.nrtRender(slot:)`, `.auxiliary(name:)`, `.custom(_)`). It enforces role uniqueness — a second engine claiming the same `.rtOutput(deviceID:)` throws `.duplicateRole`, because AUHAL output devices are exclusive.
|
||
|
||
`startAll()` / `stopAll()` are transactional: engines are snapshotted under a (non-RT) lock, started without the lock, and if any one throws, the already-started engines are rolled back with `stop()` so the caller never sees a partial-start state.
|
||
|
||
For offline batch work, `renderConcurrent(jobs:maxConcurrent:)` spawns short-lived engines on Swift `Task`s (not host-registered), defaulting `maxConcurrent` to `activeProcessorCount`. It uses a seed-and-refill pattern: launch the first `maxConcurrent` jobs, and each completion launches the next queued one. The first failure propagates and cancels the rest. (Caveat: an in-flight render may keep writing its CAF after the stream closes — orphan files are the caller's to clean up.)
|
||
|
||
Cross-engine object sharing is governed by the binding rules in §2.4. The full ownership matrix lives in `docs/engine/multi-engine-host.md` and `docs/engine/multi-core.md`.
|
||
|
||
---
|
||
|
||
## 9. Synthesizer lifecycle, end to end
|
||
|
||
Putting the pieces together — what `engine.add(synth)` actually does:
|
||
|
||
1. **(main)** Allocate the synth.
|
||
2. **(main)** `synth._bind(to: engine)` via the single-shot CAS (§2.4).
|
||
3. **(main)** `synth.build()` — construct the generator DAG, allocate every buffer.
|
||
4. **(main)** Wrap in a `PreparedNode`, retain it, enqueue `.add(node, at: time)` onto `pendingQueue`.
|
||
5. **(RT)** `processBlock` drains the event at the scheduled offset and links the node into the tree — pointer-only, no allocation (§4).
|
||
6. **(RT)** The synth renders from the next segment onward.
|
||
|
||
And `engine.remove(synth)`:
|
||
|
||
1. **(main)** `Unmanaged.passRetained(synth)` → `.remove(synth, retainedRef:, at:)` enqueued.
|
||
2. **(RT)** Unlink the node from the tree, push `retainedRef` to `freeQueue`, clear the binding CAS. No ARC, no dealloc on the RT thread.
|
||
3. **(free-worker)** Drain `freeQueue`, `Unmanaged.release()` → ARC deinit fires off-RT.
|
||
|
||
`remove` returns `Bool` (it unbinds synchronously on successful enqueue), but there is a documented one-`processBlock` window between `remove` and a re-`add` of the same instance — the RT thread needs a block to actually unlink it. If `freeQueue` overflows, the framework logs one warning and leaks that single reference rather than risk the RT thread; a leaked voice is preferable to an audio dropout or crash.
|
||
|
||
### 9.1 Actor isolation of the lifecycle
|
||
|
||
The Swift-concurrency isolation of `Synthesizer` is split along exactly the thread boundary above:
|
||
|
||
- **Language side is `@MainActor`.** `SynthesizerBase` is a `@MainActor` class, and the `Synthesizer` protocol declares `build()`, `release(engine:)`, `free(engine:)` as `@MainActor` requirements. Steps 1–4 of the add path (allocate → build → enqueue) and the `engine.add` / `schedule` / `add(position:)` entry points are therefore main-actor-isolated. This is what lets a consumer building under Xcode 26's `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` default subclass `SynthesizerBase` and override `build()` with **no** concurrency annotations — the consumer's MainActor default now matches the base instead of conflicting with a nonisolated override. (`engine.remove` stays nonisolated — it unbinds via atomics and enqueues a pointer-only event; `_bind` / `_unbind` are nonisolated for the same reason.)
|
||
|
||
- **`SynthesizerBase` declares `release(engine:)` / `free(engine:)` as `open` members, not just protocol conformances.** The `Synthesizer` extension supplies defaults for both, but a protocol-extension default is bound **statically** at the conformance — `SynthesizerBase`'s. Were the base to declare no member of its own, a subclass could not `override` them at all, and a subclass method declared without `override` would be invisible to every caller holding an `any Synthesizer`: the call would reach the extension default and throw `.noGate`. That matters because the callers that drive the lifecycle are exactly those existential ones — `Group.release` cascades to children as `any Synthesizer`, freeing any child that throws `.noGate`, so a gated subclass would be hard-freed and its envelope release phase skipped. Declaring both as `open` class members makes the witness a class method, so the call dispatches through the vtable and subclass overrides run. Pinned by `SynthesizerReleaseDispatchTests`.
|
||
|
||
- **The RT entry point is `nonisolated`.** `evaluate(graph:count:)` is `nonisolated final` so the render callback (steps 5–6) reaches it with **no actor hop**. It reads exactly two stored properties cross-thread — `parameterTable` (immutable `let`) and `outputGenerators` (written in `build()` on main, read on RT) — both marked `nonisolated(unsafe)`. Their safety rests entirely on the happens-before edge established by the SPSC `pendingQueue` (§2.1): the RT thread cannot observe the node until it dequeues the `.add` event, which the producer enqueued *after* `build()` fully returned on main. No new runtime synchronisation is introduced by the isolation annotations.
|
||
|
||
- **`Group` / `ParallelGroup` stay nonisolated.** They satisfy the `@MainActor` `build`/`release`/`free` requirements with less-isolated (nonisolated) witnesses, keeping their RT-owned linked-list / snapshot state reachable from the render thread. `Group.release` installs its self-free poll timer through a `nonisolated` helper so the utility-queue handler does not inherit `@MainActor` (which would trap when it fires off-main).
|
||
|
||
- **Internal controllers that drive the node tree are `@MainActor`** where they touch the language side: `LyrebirdProcess` (`play`/`_play`/`release`/`amp`/teardown), `LyrebirdEventList` (`play(eventIndex:)`/`next`/`releaseAll`/`killAll`/`reset`/master teardown), `VoicePool.init`, `ParallelGroup.add`. Cross-thread reads that pre-existed the change (e.g. the auto-free watcher reading `EnvelopeGen.needsFree`, `EventList.fireTimes` from process body tasks) are preserved via `nonisolated(unsafe)` on the specific fields they touch.
|
||
|
||
The guarantee is locked by the committed `RegressionFixtures/MainActorConsumer` package, which compiles an unannotated `SynthesizerBase` subclass under `.swiftLanguageMode(.v6)` + `-default-isolation MainActor`.
|
||
|
||
### 9.2 Working with the isolation from a routine or task
|
||
|
||
A `LyrebirdRoutine` / `LyrebirdTask` body is `@Sendable` and runs on its own background thread. `SynthesizerBase` is `@MainActor`. Those two facts drive every ergonomic question below, so it is worth being precise about **what is actually main-bound, and why**:
|
||
|
||
| Step | Main-bound? | Why |
|
||
|---|---|---|
|
||
| `init` (allocate the synth) | **Yes** — but for an *ergonomic* reason, not an RT one | See "Why `init` is not `nonisolated`" below |
|
||
| `build()` (construct the DAG) | **Yes — load-bearing** | Must complete-before the `.add` enqueue; that is the happens-before edge the RT thread relies on (§9.1) |
|
||
| `engine.add` / `schedule` | **Yes — load-bearing** | `pendingQueue` is SPSC: exactly one producer |
|
||
| `engine.remove` | No | Unbinds via atomics, enqueues a pointer-only event |
|
||
| Writing a `@LiveParam` | No — but the *property* is main-isolated | The value itself crosses via a lock-free atomic (see "Mutating parameters") |
|
||
| `evaluate()` (RT) | No — `nonisolated final` | The render callback must reach it with no actor hop |
|
||
|
||
**Constructing a synth inside a body — `ctx.onMain`.** Because a body cannot touch `@MainActor` state directly, the historical idiom was to pre-allocate every synth *outside* the body and capture it (the `BufferDemos` pattern). That forces the set of synths to be known in advance. ``LyrebirdRoutineContext/onMain(_:)`` removes the restriction — it runs a main-actor closure, blocks the body until it returns, and hands the (possibly non-`Sendable`) result back:
|
||
|
||
```swift
|
||
LyrebirdTask.run(engine: engine) { ctx in
|
||
while ctx.now < 10.0 {
|
||
let grain: Grain = ctx.onMain { Grain(startPos: nextPos(), rate: nextRate()) }
|
||
ctx.add(grain) // async hop; grain self-frees via its envelope
|
||
try ctx.wait(seconds: 0.05) // drift-compensated as usual
|
||
}
|
||
}
|
||
```
|
||
|
||
The hop is synchronous, so its cost counts as work between `wait` calls — which `wait(seconds:)` already compensates for by shortening the next sleep. Keep the closure short (build one synth, not a batch): it blocks both the body and the main thread. Note `build()` does **not** run inside `onMain` — it runs later, on main, inside `ctx.add`'s dispatched `engine.add`.
|
||
|
||
`onMain` **requires a serviced main thread**, and this is the one way to misuse it. `ctx.add` is fire-and-forget (`DispatchQueue.main.async`) and merely delays if main is busy; `onMain` hops synchronously with no timeout, so if main is never serviced it blocks the body forever with no diagnostic. A GUI run loop services it; so does a CLI parked on `waitUntilComplete()` / `LyrebirdTask.run`, which pump the main run loop for exactly this reason. The trap is `task.start(engine:)` followed by blocking main on something that is not a run loop (a bare `Thread.sleep`, a semaphore wait) — park on `waitUntilComplete()` instead. Re-entering the caller's own thread is *not* a hazard: `lyrebirdRunMainActorMutation` branches on `Thread.isMainThread` and runs the closure inline when already on main, so `onMain` is self-deadlock-free whichever thread calls it.
|
||
|
||
**Mutating parameters — `ctx.set`, not property writes.** Construction is *pre-publication*: the synth is thread-local, unshared, and the RT thread cannot reach it, which is what makes hopping to main for it a pure formality. A parameter write is *post-publication*: the synth is live in the tree and the RT thread reads it every block. Safety there comes from `ParameterNode`'s atomic — **not** from isolation. So capture the projected node on main once, then drive it from the body:
|
||
|
||
```swift
|
||
let cutoff: ParameterNode = filter.$cutoff // captured on main
|
||
LyrebirdTask.run(engine: engine) { ctx in
|
||
ctx.set(cutoff, to: 1200) // releasing atomic store — no dispatch
|
||
}
|
||
```
|
||
|
||
`ctx.set` is **not** a main hop: unlike `ctx.add`, it writes the atomic inline on the body's own thread. The only cost is the one-line capture. (`synth.cutoff = 1200` and `synth.$cutoff` are both main-isolated — the property inherits the class's isolation even though `LiveParam` itself is a plain, atomic-backed struct.)
|
||
|
||
**Why `init` is not `nonisolated`.** It looks free — the base `init()` is empty, `build()` is not called from it, and a fresh synth is unshared. It is not free. Under `-default-isolation MainActor` a consumer subclass that declares no init gets an *implicit `@MainActor init()`*, which would then override a `nonisolated` base init and fail with `different actor isolation from nonisolated overridden declaration` — breaking every unannotated consumer, i.e. exactly the §9.1 guarantee. The main test suite cannot catch this (it does not build under that flag); `RegressionFixtures/MainActorConsumer` is the only thing that does. **If you are tempted to relax the isolation on `SynthesizerBase.init`, build that fixture first.** `ctx.onMain` exists precisely because it buys the same ergonomics additively, with no isolation change.
|
||
|
||
---
|
||
|
||
## Where to go deeper
|
||
|
||
| Topic | Doc |
|
||
|---|---|
|
||
| Engine internals, render pass | `docs/engine/synthesis-engine.md` |
|
||
| Core Audio / AUHAL driver | `docs/engine/core-audio-driver.md` |
|
||
| Sample-accurate scheduling | `docs/engine/scheduling.md` |
|
||
| Bus memory / In / Out | `docs/engine/bus-system.md` |
|
||
| ParallelGroup / multi-core | `docs/engine/multi-core.md` |
|
||
| EngineHost / NRT batch pool | `docs/engine/multi-engine-host.md` |
|
||
| Signal evaluation order | `docs/signal-flow/signal-flow.md` |
|
||
| Writing RT-safe generators (helper catalog §13) | `docs/protocols/writing-generators.md` |
|