8.6 KiB
Scheduling & Event Timing
Design Goals
- Synthesizers are fully allocated before entering the signal tree — the RT thread never allocates
- Events are scheduled with a
SampleTimetarget — 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
typealias SampleTime = Int64 // monotonic sample counter, updated each block
The engine exposes:
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.
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 rounded up to next power of 2
// Called from producer (main thread) only
func enqueue(_ value: T) -> Bool
// Called from consumer (RT thread) only
func dequeue() -> T?
}
ScheduledEvent
// 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)
// 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.
Generator Interface — count Parameter
Because segments are variable length, generators produce count samples rather than always blockSize:
protocol Generator {
func calculatedSamples(graph: SynthGraph, count: Int) -> [[LyrebirdFloat]]
}
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:
// 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 tofreeQueue - A background
DispatchQueuedrainsfreeQueueand 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
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:
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).