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.
244 lines
11 KiB
Markdown
244 lines
11 KiB
Markdown
# Scheduling & Event Timing
|
||
|
||
## Design Goals
|
||
|
||
- Synthesizers are fully allocated **before** entering the signal tree — the RT thread never allocates
|
||
- Events are scheduled with a `SampleTime` target — sample-accurate start within a block
|
||
- Freed Synthesizers are deallocated **after** leaving the signal tree — the RT thread never frees
|
||
- Freeing is block-accurate (synth runs to end of block, then removed) — inaudible because envelopes decay to zero
|
||
|
||
## SampleTime
|
||
|
||
```swift
|
||
typealias SampleTime = Int64 // monotonic sample counter, updated each block
|
||
```
|
||
|
||
The engine exposes:
|
||
```swift
|
||
engine.currentTime // SampleTime at the start of the current (or most recent) block
|
||
engine.seconds(_ d: Double) -> SampleTime // convenience: d * sampleRate
|
||
```
|
||
|
||
## Three Lock-Free Queues
|
||
|
||
```
|
||
Main thread RT audio thread Background thread
|
||
─────────── ─────────────── ─────────────────
|
||
allocate Synthesizer
|
||
schedule(synth, at: T) → [pendingQueue] → insert at sample T
|
||
evaluate tree
|
||
done synths → [freeQueue] → ARC release (deinit)
|
||
|
||
update param at T → [paramQueue] → apply at sample T
|
||
```
|
||
|
||
All three are `SPSCQueue<T>` instances — single-producer/single-consumer ring buffers using `Synchronization.Atomic` (requires macOS 15+).
|
||
|
||
## SPSCQueue
|
||
|
||
Fixed-capacity ring buffer. Capacity set at engine init (default 1024 per queue). No allocation after init.
|
||
|
||
```swift
|
||
import Synchronization
|
||
|
||
final class SPSCQueue<T> {
|
||
private var buffer: [T?]
|
||
private let capacity: Int // must be power of 2
|
||
private let writeIdx = Atomic<Int>(0)
|
||
private let readIdx = Atomic<Int>(0)
|
||
|
||
init(capacity: Int) { ... } // capacity MUST be a power of two — precondition, not rounded
|
||
|
||
// Called from producer (main thread) only
|
||
func enqueue(_ value: T) -> Bool
|
||
|
||
// Called from consumer (RT thread) only
|
||
func dequeue() -> T?
|
||
}
|
||
```
|
||
|
||
## ScheduledEvent
|
||
|
||
```swift
|
||
// Internal — the pointer-only payload handed to the RT thread. Synth/node
|
||
// allocation and retain happen on the main thread before enqueue.
|
||
internal enum ScheduledEvent {
|
||
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)
|
||
}
|
||
```
|
||
|
||
Parameter updates are **not** queue events — they are atomic stores on
|
||
`@LiveParam` / `@UIParam` properties, picked up by the RT thread on the next
|
||
(sub-)block. See below.
|
||
|
||
## Scheduling API (SynthesisEngine)
|
||
|
||
```swift
|
||
// Schedule a synth to start at an absolute sample time
|
||
try engine.schedule(synth, at: engine.currentTime + engine.seconds(2.0))
|
||
|
||
// Convenience: seconds from now
|
||
try engine.schedule(synth, after: 2.0)
|
||
|
||
// Immediately (next block boundary)
|
||
try engine.add(synth) // or: try engine.schedule(synth, at: engine.currentTime)
|
||
|
||
// Update a parameter — atomic store on a @LiveParam, no scheduling API
|
||
synth.freq = 880.0 // applied on the next (sub-)block
|
||
|
||
// Remove a synth at a future time (returns Bool — non-throwing)
|
||
engine.remove(synth, at: engine.currentTime + engine.seconds(4.0))
|
||
```
|
||
|
||
## processBlock — Sub-block Splitting
|
||
|
||
Each block, events whose `targetTime` falls within `[currentTime, currentTime + blockSize)` are applied mid-block at the correct sample offset. This gives sample-accurate start times.
|
||
|
||
```
|
||
currentBlockStart = engine.currentTime
|
||
|
||
1. Zero audio buses, copy hardware input to input buses
|
||
2. Drain pendingQueue → collect events in [currentBlockStart, currentBlockStart + blockSize)
|
||
Sort by targetTime
|
||
3. Evaluate in segments:
|
||
cursor = 0
|
||
for each event E at offset = E.targetTime - currentBlockStart:
|
||
if offset > cursor:
|
||
tree.evaluate(count: offset - cursor, busOffset: cursor)
|
||
applyEvent(E) ← pointer-only: add/remove node, update parameter
|
||
cursor = offset
|
||
tree.evaluate(count: blockSize - cursor, busOffset: cursor)
|
||
4. Collect synths with doneAction == .freeNode → post Unmanaged refs to freeQueue
|
||
5. currentTime += blockSize
|
||
```
|
||
|
||
Events scheduled before `currentBlockStart` (i.e., in the past) are applied immediately at `offset = 0`.
|
||
|
||
## Per-Block Event Budget — `maxEventsPerBlock`
|
||
|
||
Step 2's drain and the future-event **carry-over** are both hard-capped so the RT thread never reallocates its staging arrays mid-render. The cap is `maxEventsPerBlock`, a `SynthesisEngine.init` parameter (default `lyrebirdDefaultMaxEventsPerBlock = 256`, a power of two is *not* required — only `> 0`). Also settable via `SynthesisEngineConfig` / `EngineHost`.
|
||
|
||
It bounds **two** things per block:
|
||
|
||
- **Events firing this block** — how many `targetTime ∈ [blockStart, blockEnd)` events apply in one block.
|
||
- **Look-ahead depth** — how many future-dated events the engine carries across a block boundary. Events scheduled further out than the current block sit in a `carryOverEvents` buffer capped at the same value; anything beyond it is **dropped**, not deferred.
|
||
|
||
This is the ceiling that governs whether a large batch of pre-scheduled events survives — **not** `eventQueueCapacity` (which only bounds the SPSC ring's in-flight occupancy). The two are independent: `maxEventsPerBlock` may legitimately exceed `eventQueueCapacity`, because carry-over accumulates across blocks (e.g. under a just-in-time NRT feed) while the ring only ever holds a per-drain burst.
|
||
|
||
### When events are dropped
|
||
|
||
Dropping is silent to the audio path but instrumented off the RT thread:
|
||
|
||
- **`engine.perBlockEventDropCount: UInt64`** — monotonic count of events dropped for exceeding the cap since start (or since `resetPerBlockEventDropCount()`). Distinct from `pendingQueueDroppedCount` (which counts main-thread *enqueue* failures against `eventQueueCapacity`).
|
||
- **Console warning** — a one-line `[Lyrebird] Warning: … exceeded maxEventsPerBlock …` is printed at most once per drain interval. The RT thread only sets a relaxed counter + a `.releasing` latch (no allocation / lock / `print`); a non-RT drain (`freeWorker` timer, `stop()`, and the end of `NRTDriver.start()`) prints and clears the latch.
|
||
|
||
Raising the cap costs only pre-allocated staging memory (three arrays × `maxEventsPerBlock` `ScheduledEvent`s), reserved once in `start()` — no RT cost. Alternatively, keep the cap and **spread scheduling over time** (e.g. a JIT feed driven by a `TriggerListener` in NRT) so no single block's onset density or look-ahead exceeds the budget.
|
||
|
||
## Generator Interface — count Parameter
|
||
|
||
Because segments are variable length, generators produce `count` samples rather than always `blockSize`:
|
||
|
||
```swift
|
||
protocol Generator {
|
||
func calculatedSamples(graph: SynthGraph, count: Int) -> [[Double]]
|
||
}
|
||
```
|
||
|
||
Stateful generators (phase accumulators, filter memory, delay write heads) advance by exactly `count` samples per call. This ensures correct timing even when a block is split.
|
||
|
||
## Out Generator — busOffset
|
||
|
||
The `Out` generator writes into the bus at the correct position:
|
||
|
||
```swift
|
||
// Audio rate Out — writes count samples starting at busOffset
|
||
for i in 0..<count {
|
||
engine.audioBuses[busIndex][busOffset + i] += inputBlock[i]
|
||
}
|
||
```
|
||
|
||
For segments before a new synth is inserted, the new synth's `Out` has not yet run — those bus positions remain zero (or whatever prior synths wrote).
|
||
|
||
## Block-Accurate Freeing
|
||
|
||
When a generator signals `doneAction: .freeNode`, the Synthesizer is flagged during the current block's evaluation. After the block is fully evaluated:
|
||
- The Synthesizer is removed from the signal tree (pointer update only)
|
||
- An `Unmanaged<any Synthesizer>` reference is posted to `freeQueue`
|
||
- A background `DispatchQueue` drains `freeQueue` and calls `.release()` — ARC deinit runs off RT
|
||
|
||
The synth runs to the natural end of the block. Since envelopes decay to zero before signalling done, there is no audible click.
|
||
|
||
## Memory Safety Invariants
|
||
|
||
| Thread | May do | Must not do |
|
||
|---|---|---|
|
||
| Main / REPL | Allocate Synthesizer, post to pendingQueue, read currentTime | Write directly to signal tree |
|
||
| RT callback | Read/write bus memory, evaluate generators, atomic index reads | Allocate, deallocate, lock, block |
|
||
| Background | Drain freeQueue, call ARC release, read/write non-RT state | Post to pendingQueue from multiple threads simultaneously |
|
||
|
||
## Non-Real-Time (NRT) Rendering
|
||
|
||
NRT rendering shares the entire scheduling stack — `SampleTime`, `SPSCQueue`, `ScheduledEvent`, sub-block splitting — with no engine changes. The only difference is the driver.
|
||
|
||
### NRTDriver
|
||
|
||
```swift
|
||
NRTDriver(outputURL: URL, duration: Double)
|
||
```
|
||
|
||
`start()` runs a tight synchronous loop:
|
||
|
||
```
|
||
while currentTime < totalSamples:
|
||
engine.processBlock(inputSamples: silence)
|
||
append audioBuses[0..<numOutputChannels] to output file
|
||
// currentTime advances inside processBlock
|
||
```
|
||
|
||
After the loop, the output file is finalised and `stop()` is called automatically. `start()` blocks until rendering is complete — appropriate for scripts and score workflows.
|
||
|
||
Output is written via `ExtAudioFile` (AudioToolbox) as AIFF or WAV. No additional framework dependencies beyond what `CoreAudioDriver` already uses.
|
||
|
||
### Score Pattern
|
||
|
||
Pre-schedule all events before calling `start()`. The pending queue holds them until the engine clock reaches each event's `SampleTime`:
|
||
|
||
```swift
|
||
let engine = SynthesisEngine(
|
||
blockSize: 512, sampleRate: 44100,
|
||
numOutputChannels: 2, numInputChannels: 0,
|
||
driver: NRTDriver(outputURL: url, duration: 10.0)
|
||
)
|
||
|
||
// Schedule the score
|
||
try engine.schedule(pad, at: 0)
|
||
try engine.schedule(kick, at: engine.seconds(0.0))
|
||
try engine.schedule(kick, at: engine.seconds(0.5))
|
||
try engine.schedule(kick, at: engine.seconds(1.0))
|
||
engine.remove(pad, at: engine.seconds(8.0)) // returns Bool — non-throwing
|
||
|
||
try engine.start() // renders synchronously, writes file, returns when done
|
||
```
|
||
|
||
### Termination
|
||
|
||
**Initial implementation: fixed duration.** The caller specifies total render length at `NRTDriver` init. The loop runs for exactly `ceil(duration * sampleRate / blockSize)` blocks.
|
||
|
||
**Stretch goal (future):** Event-driven termination — stop when the pending queue is empty *and* the node tree is empty (all synths have freed themselves). This enables rendering a score of unknown length without specifying duration upfront.
|
||
|
||
### NRT vs OfflineDriver
|
||
|
||
| Driver | Purpose |
|
||
|---|---|
|
||
| `OfflineDriver` | Tests — no-op, no output, `processBlock` called manually |
|
||
| `NRTDriver` | Score rendering — drives engine, writes audio file |
|
||
|
||
`OfflineDriver` remains the right choice for unit tests because it gives full control: call `processBlock` directly, inspect `audioBuses[]` immediately.
|
||
|
||
## macOS Version Note
|
||
|
||
`Synchronization.Atomic` requires macOS 15+. The package platform target is `.macOS(.v15)`.
|