Consolidated release: the cross-platform Linux port (engine, generators, CLI, REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive. See RELEASES.md and LINUX_README.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
7.5 KiB
Multi-Core Audio
Two supported patterns for spreading synthesis work across CPU cores.
ParallelGroup
ParallelGroup is a Synthesizer node that evaluates its children concurrently via DispatchQueue.concurrentPerform. Each child writes into a pre-allocated per-child scratch copy of engine.audioBuses. After the concurrent barrier, all scratch slots are summed into the real buses via vDSP_vadd.
Architecture
segmentSerialinSynthesisEngineisAtomic<UInt64>. Write is a single releasingwrappingAddbefore concurrent evaluation; reads in concurrent workers use an acquiring load.SynthGraphcarries an optionalScratchBuses?reference (_scratchBuses). Non-nil when evaluating inside aParallelGroupchild.Out.Audio._computeSamplescallsgraph.addSamplesToAudioBus(...)which routes toScratchBuses.accumulate(...)(scratch path) orengine.addToAudioBus(...)(normal path).SynthesizerBase.evaluateforwards_scratchBuseswhen constructinglocalGraph, so the full downstream generator DAG writes to the same scratch slot.- Each
ScratchBusesinstance owns aconversionScratch: [Float]forvDSP_vdpsp(Double→Float), avoiding races on the engine's_busAccumulateScratch.
Clear and merge use busOffset
ScratchBuses.clearDirtyBuses(offset:count:) zeroes only the segment's sample range, and only for buses any child wrote since the last clear (tracked in a per-slot dirty: [Bool] mask updated inside accumulate). After clearing, the mask is reset; children's writes during this segment re-populate it; the merge pass then reads the mask and skips vDSP_vadd on buses left untouched. With the default 128 audio buses and a child that writes to two of them (a typical stereo voice), this drops both the clear and merge passes from 128 vDSP calls per child per segment down to 2. The merge pass still reads srcBase.advanced(by: offset) and writes to dstBase.advanced(by: offset), correctly handling sub-block segments.
Limitations
- Cross-child generator fan-out: sharing a
Generatorinstance between two children races on_segmentSerial/_cachedResult. Each child must own its DAG exclusively. - Control bus writes:
Out.Controlis not scratch-buffered. Same-index writes from concurrent children race. - Nested
ParallelGroups: an inner group's merge pass writes directly toengine.audioBuses, bypassing the outer group's scratch. - Dynamic child mutation: children are snapshotted into
childrenSnapshotinbuild(). Mutating the child list while the group is active is a data race.
Memory cost
numChildren × numAudioBuses × blockSize × sizeof(Float) per group, plus one blockSize-Float conversion scratch per child. Allocated in build() (off RT); never resized.
Multiple Engine Instances
Each SynthesisEngine is fully independent: separate audioBuses, controlBuses, sharedTables, segmentSerial, root Group, scheduling queues, and AudioDriver. Two engines on separate threads use two cores with no shared state.
Device constraint: Core Audio grants exclusive AUHAL ownership per output device. Two engines cannot both drive the same hardware output simultaneously. This pattern is suited to NRT rendering (one engine per output file) or separate output devices.
No code changes are required — this works with the existing API. The EngineHost facade is the blessed entry point for multi-engine use (creation-owning, role-based, NRT pool, lifecycle serialisation). Single-engine code stays on the direct SynthesisEngine() constructor unchanged.
Object ownership rules
Two engines do not magically share object graphs. Runtime binding checks enforce one-engine ownership at the points where a synth or buffer crosses the engine boundary.
Synthesizer
- One
SynthesizerBaseinstance binds to exactly oneSynthesisEnginefor the period it lives in that engine's node tree. - Bound on
engine.add(_:)/engine.add(_:position:)/engine.schedule(_:at:)/engine.schedule(_:after:)via a single-shot atomic compare-exchange. - Cleared on
engine.remove(_:)after the matchingprocessBlockcycle. - Cross-engine sharing throws
EngineAddError.boundToOtherEngine(current:prior:)— both UUIDs are reported. - Same-engine re-add without an intervening
removethrowsEngineAddError.doubleAdd(engine:). engine.stop()also releases the exclusive binding for every non-persistent synth the engine was hosting — including synths nested inside drainedGroupsubtrees (notParallelGroupchildren, which are never bound individually). Becausestop()has already halted the RT thread before this unbind pass runs, a stop-then-re-add of the same instance — to the same engine or a different one — needs no interveningprocessBlock, unlike theremove(_:)path. Seesynthesis-engine.md§stop()node-tree teardown contract.- Pattern for "the same synth, on two engines": construct a fresh instance per engine. Synth construction is cheap; the build closure is the canonical place to express the graph.
LyrebirdBuffer
LyrebirdBuffer has an opt-in two-tier binding API. Single-engine code does not need to touch it — the default behaviour matches the legacy unbound state and the existing tear-free language-side write model is preserved.
| Tier | API | Semantics |
|---|---|---|
| Exclusive | try buffer.bindExclusive(to: engine) + buffer.unbindExclusive(from: engine) |
Single-engine ownership. Throws EngineAddError.boundToOtherEngine if any read-only holder or a different exclusive engine holds the buffer. |
| Read-only share | try buffer.bindReadOnly(to: engine) + buffer.unbindReadOnly(from: engine) |
Any number of engines may hold read-only shares concurrently. Throws EngineAddError.boundToOtherEngine if an exclusive engine holds the buffer. Refcount-based — the refcount does not track per-engine identity. |
The tiers are mutually exclusive: bindReadOnly fails when an exclusive bind is in force, and bindExclusive fails when the read-only refcount is non-zero.
Read-only invariant. Callers holding a read-only share must not invoke setValue, setRangeValues, clear, fill*, or invalidate. This is documented but not runtime-enforced — existing mutation API stays unguarded to preserve the legacy tear-free single-engine write model. Audit at the binding site.
Canonical cross-engine wavetable share pattern:
let wavetable: LyrebirdBuffer = LyrebirdBuffer(count: 4096)
wavetable.fillSine() // mutate while unbound
try wavetable.bindReadOnly(to: engineA)
try wavetable.bindReadOnly(to: engineB)
// both engines read the same wavetable concurrently …
wavetable.unbindReadOnly(from: engineA)
wavetable.unbindReadOnly(from: engineB)
Lifecycle coordination
Process-wide EngineLifecycleCoordinator (internal singleton) tracks every live engine via WeakEngineRef keyed by SynthesisEngine.identifier. The coordinator's withLifecycleLock(_:) is the chokepoint intended to wrap engine.start() / engine.stop() calls so that concurrent start/stop across two engines cannot interleave on the freeWorker.sync teardown drain. The EngineHost uses this lock in startAll / stopAll; direct-ctor callers that drive their own multi-engine lifecycle should serialise start/stop on the caller side, or migrate to the host.
See also: docs/engine/multi-engine-host.md for the role-based, creation-owning EngineHost facade including the NRT pool API.