# 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` 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 { private var buffer: [T?] private let capacity: Int // must be power of 2 private let writeIdx = Atomic(0) private let readIdx = Atomic(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, 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..` 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..