Files
Lyrebird/docs/engine/multi-core.md
T
2026-06-01 18:27:40 -07:00

6.9 KiB
Raw Blame History

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

  • segmentSerial in SynthesisEngine is Atomic<UInt64>. Write is a single releasing wrappingAdd before concurrent evaluation; reads in concurrent workers use an acquiring load.
  • SynthGraph carries an optional ScratchBuses? reference (_scratchBuses). Non-nil when evaluating inside a ParallelGroup child.
  • Out.Audio._computeSamples calls graph.addSamplesToAudioBus(...) which routes to ScratchBuses.accumulate(...) (scratch path) or engine.addToAudioBus(...) (normal path).
  • SynthesizerBase.evaluate forwards _scratchBuses when constructing localGraph, so the full downstream generator DAG writes to the same scratch slot.
  • Each ScratchBuses instance owns a conversionScratch: [Float] for vDSP_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 Generator instance between two children races on _segmentSerial/_cachedResult. Each child must own its DAG exclusively.
  • Control bus writes: Out.Control is not scratch-buffered. Same-index writes from concurrent children race.
  • Nested ParallelGroups: an inner group's merge pass writes directly to engine.audioBuses, bypassing the outer group's scratch.
  • Dynamic child mutation: children are snapshotted into childrenSnapshot in build(). 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 SynthesizerBase instance binds to exactly one SynthesisEngine for 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 matching processBlock cycle.
  • Cross-engine sharing throws EngineAddError.boundToOtherEngine(current:prior:) — both UUIDs are reported.
  • Same-engine re-add without an intervening remove throws EngineAddError.doubleAdd(engine:).
  • 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.