287 lines
14 KiB
Markdown
287 lines
14 KiB
Markdown
# SynthesisEngine
|
||
|
||
The central object that owns Core Audio I/O and drives the signal graph.
|
||
|
||
## Initialization
|
||
|
||
```swift
|
||
SynthesisEngine(
|
||
blockSize: Int, // samples per render callback (e.g. 512)
|
||
sampleRate: Double, // e.g. 44100, 48000
|
||
numOutputChannels: Int, // hardware output channels (e.g. 2)
|
||
numInputChannels: Int, // hardware input channels (e.g. 2)
|
||
numAudioBuses: Int, // default 128
|
||
numControlBuses: Int // default 4096
|
||
)
|
||
```
|
||
|
||
`SynthesisEngine.init` also allocates and fills `sharedTables` (see below) on the calling
|
||
(non-RT) thread, so shared tables are ready before the first render callback.
|
||
|
||
## Shared Lookup Tables
|
||
|
||
```swift
|
||
engine.sharedTables.sineTable // LyrebirdBuffer — 32768-sample sine wave
|
||
engine.sharedTables.hanningTable // LyrebirdBuffer — 32768-sample Hanning window
|
||
```
|
||
|
||
`sharedTables` is a `public let SharedTables` instance created in `init`. All tables
|
||
use `lyrebirdDefaultTableSize` (32768) samples. Tables are never invalidated during the
|
||
engine's lifetime — generators that read from shared tables do not need to check `isValid`.
|
||
|
||
Access from generators via `graph.engine.sharedTables.sineTable` inside `calculatedSamples`.
|
||
The table reference should be cached as an ivar at `init` time (like `OscSin` does) to avoid
|
||
any per-block property traversal on the RT thread.
|
||
|
||
### User-allocated buffers (`LyrebirdBuffer`)
|
||
|
||
```swift
|
||
let buf = LyrebirdBuffer(count: lyrebirdDefaultTableSize) // allocate off RT thread
|
||
buf.fillSine() // fill before scheduling
|
||
let osc = OscTable.Audio(table: buf, freq: 440.0)
|
||
try engine.add(mySynth) // buf now in RT use — do not fill again
|
||
|
||
// Later, on the main thread:
|
||
buf.invalidate() // RT thread sees isValid == false, outputs silence
|
||
engine.remove(mySynth) // ARC releases buf when synth is freed via freeQueue
|
||
```
|
||
|
||
- Fill methods (`fill(with:)`, `fill(using:)`, `fillSine()`, `fillHanning()`) must be called
|
||
**before** the buffer enters RT use. Calling them while a generator holds the buffer in a
|
||
running engine is an unsynchronized data race.
|
||
- `invalidate()` is RT-safe (releasing atomic store). The RT thread reads `isValid` with an
|
||
acquiring load before accessing samples.
|
||
|
||
## Core Audio Setup (AUHAL)
|
||
|
||
Use `kAudioUnitSubType_HALOutput` — **not** `DefaultOutput`. Only `HALOutput` supports full-duplex I/O (both input and output on the same unit). `DefaultOutput` does not support input and will fail with `-10879` when `EnableIO` is requested on the input element.
|
||
|
||
```swift
|
||
var outputUnit: AudioComponentInstance
|
||
|
||
// 1. Find the HAL output audio component (supports full duplex)
|
||
var desc = AudioComponentDescription(
|
||
componentType: kAudioUnitType_Output,
|
||
componentSubType: kAudioUnitSubType_HALOutput, // NOT DefaultOutput
|
||
componentManufacturer: kAudioUnitManufacturer_Apple,
|
||
componentFlags: 0, componentFlagsMask: 0
|
||
)
|
||
let component = AudioComponentFindNext(nil, &desc)
|
||
AudioComponentInstanceNew(component, &outputUnit)
|
||
|
||
// 2. Enable output on element 0 (required for HALOutput — not automatic)
|
||
var enableOutput: UInt32 = 1
|
||
AudioUnitSetProperty(outputUnit,
|
||
kAudioOutputUnitProperty_EnableIO,
|
||
kAudioUnitScope_Output, 0,
|
||
&enableOutput, UInt32(MemoryLayout<UInt32>.size))
|
||
|
||
// 3. Enable input on element 1
|
||
var enableInput: UInt32 = 1
|
||
AudioUnitSetProperty(outputUnit,
|
||
kAudioOutputUnitProperty_EnableIO,
|
||
kAudioUnitScope_Input, 1,
|
||
&enableInput, UInt32(MemoryLayout<UInt32>.size))
|
||
|
||
// 4. Set stream format (match engine sampleRate, numOutputChannels)
|
||
// Apply to output scope element 0 and input scope element 1
|
||
|
||
// 5. Set max frames per slice
|
||
var maxFrames = UInt32(blockSize)
|
||
AudioUnitSetProperty(outputUnit,
|
||
kAudioUnitProperty_MaximumFramesPerSlice,
|
||
kAudioUnitScope_Global, 0,
|
||
&maxFrames, UInt32(MemoryLayout<UInt32>.size))
|
||
|
||
// 6. Install render callback
|
||
var callbackStruct = AURenderCallbackStruct(
|
||
inputProc: lyrebirdRenderCallback, // module-level @convention(c) free function
|
||
inputProcRefCon: Unmanaged.passUnretained(self).toOpaque()
|
||
)
|
||
AudioUnitSetProperty(outputUnit,
|
||
kAudioUnitProperty_SetRenderCallback,
|
||
kAudioUnitScope_Input, 0,
|
||
&callbackStruct, UInt32(MemoryLayout<AURenderCallbackStruct>.size))
|
||
|
||
// 7. Initialize and start
|
||
AudioUnitInitialize(outputUnit)
|
||
AudioOutputUnitStart(outputUnit)
|
||
```
|
||
|
||
Input staging buffers (one `AudioBufferList` per input channel) are pre-allocated during `setup()` — **never** in the render callback.
|
||
|
||
### Microphone Permission
|
||
|
||
When `numInputChannels > 0`, the host process needs explicit OS permission before AUHAL delivers non-zero input frames. System requirement, not Lyrebird-specific — applies to every Lyrebird host (CLI tool, SwiftUI app, scaffolded Xcode project, AUv3 host).
|
||
|
||
Templates do **not** pre-wire microphone capability because most pieces are output-only and would otherwise trigger a permission prompt on every first run for no reason. The project owner adds it when needed:
|
||
|
||
- **macOS** — add `NSMicrophoneUsageDescription` (string explaining the use) to the target's `Info.plist`. Sandboxed apps additionally need `com.apple.security.device.audio-input` in the `.entitlements`. A plain `swift run` CLI tool inherits Terminal's TCC grant: the user accepts the prompt for Terminal once and subsequent CLI runs from that shell get input.
|
||
- **iOS** — add `NSMicrophoneUsageDescription` to `Info.plist`, **and** set the `AVAudioSession` category to `.playAndRecord` (not `.playback`, which is output-only and returns zero-filled input regardless of `numInputChannels`).
|
||
|
||
Until the user grants permission the input buses stay zero-filled. Failure mode is silent: an `In` generator returns silence, a `ScopeCapture` tap on input buses draws a flat line, no error is thrown by the driver. (TODO #8 in [`core-audio-driver.md`](core-audio-driver.md) — surface `CoreAudioError.microphoneAccessDenied` instead of silently logging.) See [`project-system.md`](../tooling/project-system.md) for per-template specifics on where these fields live in scaffolded projects.
|
||
|
||
## Render Callback
|
||
|
||
Runs on the **real-time audio thread**. Must not allocate, lock, or block.
|
||
|
||
The callback is a module-level `@convention(c)` free function (`lyrebirdRenderCallback`). It recovers the engine via `Unmanaged.fromOpaque(inRefCon).takeUnretainedValue()`.
|
||
|
||
```swift
|
||
// Pseudocode — actual implementation in CoreAudioDriver.swift
|
||
func lyrebirdRenderCallback(...) -> OSStatus {
|
||
// 1. Read hardware input via AudioUnitRender on element 1
|
||
// (into pre-allocated staging buffers — no allocation here)
|
||
// 2. Build [[Float]] view over staging buffers
|
||
// 3. engine.processBlock(inputSamples:)
|
||
// → zeros audio buses, copies input, evaluates node tree
|
||
// 4. memcpy audioBuses[0..<numOutputChannels] → ioData AudioBufferList
|
||
return noErr
|
||
}
|
||
```
|
||
|
||
`processBlock` returns `Void` — callers read `engine.audioBuses[]` directly after the call. This avoids any allocation on the RT thread.
|
||
|
||
Each call to `processBlock` may invoke `evaluateSegment` one or more times (once per
|
||
sub-block when scheduled events split the block). `evaluateSegment` constructs a
|
||
`SynthGraph` value to pass into `rootGroup.evaluate`. The `SynthGraph` needs a
|
||
`_parameterTable` reference even at the root level (before any `SynthesizerBase.evaluate`
|
||
replaces it with the synth's own table). To avoid a `ParameterTable()` heap allocation on
|
||
every `evaluateSegment` call, `SynthesisEngine` pre-allocates a single empty
|
||
`_emptyParameterTable` in `init` and passes it via the internal
|
||
`SynthGraph(engine:busOffset:parameterTable:)` init. The empty table's `inputs` dictionary
|
||
is never written to after construction; `SynthesizerBase.evaluate` always overwrites
|
||
`_parameterTable` with the per-synthesizer table before any generator reads it.
|
||
|
||
## Lock-Free Graph Mutation
|
||
|
||
- Main thread builds a new node tree snapshot
|
||
- Posts it via a lock-free queue (e.g. single-producer single-consumer ring buffer) or `OSAtomicCompareAndSwap` on a pointer
|
||
- RT callback reads the current pointer atomically at the top of each block
|
||
- No locks, no `DispatchQueue` on the RT thread
|
||
|
||
## Lifecycle
|
||
|
||
```swift
|
||
try engine.start() // allocates bus memory, calls driver.setup() + driver.start()
|
||
engine.stop() // calls driver.stop(), sets isRunning = false
|
||
```
|
||
|
||
`start()` is idempotent — calling it when already running is a no-op. `stop()` is safe to call multiple times.
|
||
|
||
Bus memory (`audioBuses`, `controlBuses`) is allocated in `start()` and is empty before start. After `stop()`, the existing bus arrays remain in memory but are not updated further.
|
||
|
||
## Engine Identity
|
||
|
||
Every `SynthesisEngine` carries a process-unique `identifier: UUID`, assigned at `init` and immutable for the engine's lifetime. The identifier surfaces in:
|
||
|
||
- `EngineAddError.boundToOtherEngine(current: UUID, prior: UUID)` and `.doubleAdd(engine: UUID)` diagnostics.
|
||
- The internal `EngineLifecycleCoordinator` registry, which holds weak references to every live engine keyed by `identifier`. The coordinator is the registration target for the `EngineHost` facade and the lookup source for translating raw engine pointers back to UUIDs in binding error messages.
|
||
|
||
## Ownership Binding (`engine.add` throws)
|
||
|
||
`engine.add(_:)`, `engine.add(_:position:)`, `engine.schedule(_:at:)`, and `engine.schedule(_:after:)` are throwing methods:
|
||
|
||
```swift
|
||
public func add(_ synth: any Synthesizer) throws
|
||
public func add(_ synth: any Synthesizer, position: NodePosition) throws
|
||
public func schedule(_ synth: any Synthesizer, at time: SampleTime) throws
|
||
public func schedule(_ synth: any Synthesizer, after seconds: Double) throws
|
||
```
|
||
|
||
All four throw `EngineAddError`:
|
||
|
||
| Case | When |
|
||
|------|------|
|
||
| `.boundToOtherEngine(current:prior:)` | Synth is already bound to a different `SynthesisEngine`. Build a fresh instance per engine; one Synthesizer instance is bound to one engine for its lifetime. |
|
||
| `.doubleAdd(engine:)` | Synth is already active in this engine's node tree. Call `engine.remove(synth)` and allow at least one `processBlock` before re-adding the same instance. |
|
||
| `.pendingQueueFull` | The engine's `pendingQueue` SPSC queue was full when the add event was posted. Reduce add cadence or increase `eventQueueCapacity` at engine init. |
|
||
| `.rebuildFailed(underlying:)` | Reserved for future use — `rebuildGraph()` does not throw in the current implementation. Listed for forward compatibility. |
|
||
|
||
Internally, every add path calls `synth._bind(to: self)` before any RT-visible side effect. `_bind` is a single-shot acquire-release `compareExchange` on `SynthesizerBase._engineBinding: Atomic<UInt>` storing the raw bit pattern of an `UnsafeMutableRawPointer` to the bound engine. Zero RT cost — the binding atomic is read only on the main thread during add. `remove(_:)` synchronously calls `_unbind` on successful enqueue so a subsequent re-add (after one `processBlock`) does not collide with `.doubleAdd`.
|
||
|
||
`Group` instances are not bound — they are persistent node-tree fixtures and do not subclass `SynthesizerBase`.
|
||
|
||
`LyrebirdBuffer` has an opt-in two-tier binding API for cross-engine sharing — see [Multi-Core Audio § Multiple Engines](multi-core.md) and the `EngineHost` doc.
|
||
|
||
## CPU Statistics
|
||
|
||
`SynthesisEngine` tracks real-time CPU load and exposes two thread-safe read properties:
|
||
|
||
```swift
|
||
engine.averageCPU // Double — exponential moving average (α=0.1) of load per block
|
||
engine.peakCPU // Double — peak load since last reset (auto-resets every 5 s)
|
||
```
|
||
|
||
Both express load as a fraction of one nominal block duration: `0.0` = idle, `1.0` = full block
|
||
consumed, `> 1.0` = over budget (xruns likely). Manual reset:
|
||
|
||
```swift
|
||
engine.resetPeakCPU() // releases to 0.0 immediately; timer also fires every 5 s
|
||
```
|
||
|
||
**Threading:** both properties use `Atomic<UInt64>.load(ordering: .relaxed)` — safe to read from
|
||
any thread at any time. The RT callback writes via releasing atomic stores on every `processBlock`
|
||
call. The automatic reset fires on a background `DispatchQueue` (the same `lyrebird.free` worker
|
||
used for deallocation).
|
||
|
||
**LyrebirdStatusView** (in `LyrebirdUI`) wraps these properties in a compact embeddable SwiftUI
|
||
view that polls at 10 Hz and renders color-coded bars — see [GUI System](../ui/gui-system.md).
|
||
|
||
## Scope Tap (ScopeCapture)
|
||
|
||
`ScopeCapture` is an optional real-time audio bus tap that feeds a double-buffered
|
||
ring to the UI for oscilloscope display.
|
||
|
||
```swift
|
||
let scope = ScopeCapture(buses: [0, 1], bufferSize: 2048)
|
||
engine.scopeTap = scope // set before start()
|
||
try engine.start()
|
||
|
||
// In a SwiftUI view:
|
||
LyrebirdScopeView(capture: scope)
|
||
.frame(height: 120)
|
||
```
|
||
|
||
**How it works:**
|
||
|
||
- `ScopeCapture` holds two ping-pong `[[Float]]` buffers (each `bufferSize` samples
|
||
per channel). The RT thread writes into the "back" buffer; when it fills, it atomically
|
||
swaps front/back. The main thread calls `snapshot()` to get a deep copy of the most
|
||
recently completed front buffer.
|
||
- `SynthesisEngine` caches the tap as `Unmanaged<ScopeCapture>` at `start()` time
|
||
(in `_rtScopeTap`) to avoid ARC retain/release on the RT thread. Set `scopeTap` before
|
||
calling `start()` — changes after `start()` are not picked up.
|
||
- At the end of each `processBlock`, the engine calls `_rtScopeTap?.takeUnretainedValue().write(...)`.
|
||
No allocation occurs on the RT path: `write` uses `withUnsafeMutableBufferPointer` +
|
||
`assign(from:count:)` for raw pointer copies.
|
||
|
||
**RT safety invariants:**
|
||
|
||
- CoW sharing from `[Float](repeating:)` init is broken in `ScopeCapture.init`
|
||
via `withUnsafeMutableBufferPointer { _ in }` on every inner buffer before the RT thread starts.
|
||
- `snapshot()` copies via `Array($0)` from `UnsafeBufferPointer` — does not increase the
|
||
CoW refcount of the internal front buffer; RT writes to the back buffer never CoW-allocate.
|
||
- `bufferSize` must be ≥ the engine's `blockSize`. Enforced by `precondition` in `write()`.
|
||
|
||
```swift
|
||
// ScopeCapture init
|
||
public init(buses: [Int], bufferSize: Int = 2048)
|
||
|
||
// Called from processBlock (RT thread) — no allocation
|
||
public func write(audioBuses: [[Float]], count: Int)
|
||
|
||
// Called from main thread — returns a deep copy
|
||
public func snapshot() -> [[Float]] // [channelIndex][sampleIndex]
|
||
```
|
||
|
||
See `Sources/Lyrebird/Capture/ScopeCapture.swift` and `LyrebirdScopeView` in
|
||
`docs/ui/gui-system.md`.
|
||
|
||
## Threading Rules
|
||
|
||
| Thread | Allowed | Not Allowed |
|
||
|---|---|---|
|
||
| RT callback | Read bus memory, evaluate generators, atomic pointer reads, `Unmanaged.takeUnretainedValue()` | Allocate memory, take locks, call Swift runtime, print, ARC retain/release |
|
||
| Main thread | Allocate, lock, build graphs, post to lock-free queue, `scope.snapshot()` | Write directly to bus memory during a running callback |
|