# 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.size)) // 3. Enable input on element 1 var enableInput: UInt32 = 1 AudioUnitSetProperty(outputUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableInput, UInt32(MemoryLayout.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.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.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..` 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.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` 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 |