1.0.0 release
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
# Bus System
|
||||
|
||||
Pre-allocated at `SynthesisEngine.start()`. Never resized at runtime.
|
||||
|
||||
## Memory Layout
|
||||
|
||||
```swift
|
||||
// Audio buses: 2D array, [busIndex][sampleIndex]
|
||||
var audioBuses: [[Float]] // [numAudioBuses][blockSize]
|
||||
|
||||
// Control buses: 1D array, one value per bus
|
||||
var controlBuses: [Float] // [numControlBuses]
|
||||
```
|
||||
|
||||
## Reserved Bus Layout
|
||||
|
||||
```
|
||||
Audio buses:
|
||||
0 ..< numOutputChannels → hardware output
|
||||
numOutputChannels ..< numOutputChannels + numInputChannels → hardware input
|
||||
numOutputChannels + numInputChannels ..< numAudioBuses → user buses
|
||||
|
||||
Control buses:
|
||||
0 ..< numControlBuses → all user-addressable (none reserved)
|
||||
```
|
||||
|
||||
## Per-Cycle Semantics
|
||||
|
||||
At the top of each render callback:
|
||||
1. **Zero all audio buses** — `audioBuses[i] = [Float](repeating: 0, count: blockSize)`
|
||||
2. **Copy hardware input** — write input samples into the reserved input buses
|
||||
3. **Retain control buses** — no zeroing; values persist until overwritten
|
||||
|
||||
At the bottom of each render callback:
|
||||
4. **Copy output buses to hardware** — read buses 0..<numOutputChannels into the AudioBufferList
|
||||
|
||||
## `In` Generator
|
||||
|
||||
Reads from one or more consecutive buses. The channel count is fixed at init — no RT allocation.
|
||||
|
||||
```swift
|
||||
// Single-channel (default)
|
||||
In.Audio(bus: 5) // 1-channel generator
|
||||
In.Control(bus: 10) // 1-channel, interpolated ramp
|
||||
|
||||
// Multi-channel — reads N consecutive buses, returns N channels
|
||||
In.Audio(bus: 4, channels: 3) // reads audioBuses[4], [5], [6]
|
||||
In.Control(bus: 10, channels: 2) // reads controlBuses[10] and [11]
|
||||
|
||||
// AudioBus object — channel count comes from the allocation
|
||||
In.Audio(bus: myAudioBus) // channels == myAudioBus.channelCount
|
||||
```
|
||||
|
||||
`floatValue` always returns the value of the first channel (bus index). Each `In.Control`
|
||||
channel maintains its own ramp state (`previousOutputValue` exposes channel 0).
|
||||
|
||||
## `Out` Generator
|
||||
|
||||
Accumulates into a bus. Uses `+=` so multiple Synthesizers writing to the same bus mix.
|
||||
|
||||
```swift
|
||||
// Audio rate — mono source writes one bus
|
||||
for i in 0..<blockSize {
|
||||
engine.audioBuses[busIndex][i] += inputBlock[i]
|
||||
}
|
||||
|
||||
// Control rate
|
||||
engine.controlBuses[busIndex] += inputValue
|
||||
```
|
||||
|
||||
### Multi-channel `Out`
|
||||
|
||||
When the source returns N channels, `Out` writes channel `ch` to `bus + ch`:
|
||||
|
||||
```swift
|
||||
// Stereo source (e.g. Pan2, GeneratorArray of 2) writes buses 0 and 1:
|
||||
Out.Audio(bus: 0, source: Pan2(input: osc, pan: 0.0))
|
||||
```
|
||||
|
||||
Mono sources are unaffected — they return one channel and write only `bus`.
|
||||
|
||||
## Multi-channel Expansion
|
||||
|
||||
`GeneratorArray` wraps N generators and returns an N-channel `[[LyrebirdFloat]]`.
|
||||
Create one with the `expand()` helper in `build()`:
|
||||
|
||||
```swift
|
||||
let oscs = expand([440.0, 880.0]) { OscSin.Audio(freq: $0) }
|
||||
output(bus: 0, source: oscs) // bus 0 = 440 Hz, bus 1 = 880 Hz
|
||||
```
|
||||
|
||||
Read N consecutive buses with `input(bus:channels:)`:
|
||||
|
||||
```swift
|
||||
output(bus: 0, source: input(bus: 2, channels: 2) * 0.5)
|
||||
```
|
||||
|
||||
See `docs/stdlib/multichannel.md` for the full MCE guide.
|
||||
|
||||
## Bus Allocator
|
||||
|
||||
`SynthesisEngine.busAllocator` manages user buses so you don't track raw integers manually.
|
||||
Hardware output/input buses are pre-reserved at init; allocation starts from the first free
|
||||
bus after them.
|
||||
|
||||
```swift
|
||||
// Allocate a stereo user bus
|
||||
let stereo = try engine.busAllocator.allocateAudioBus(channelCount: 2)
|
||||
let ctrl = try engine.busAllocator.allocateControlBus()
|
||||
|
||||
// Use with convenience inits on In / Out
|
||||
let reader = In.Audio(bus: stereo) // reads stereo.index (channel 0)
|
||||
let multi = In.Audio.multi(bus: stereo) // GeneratorArray — both channels
|
||||
let writer = Out.Audio(source: someSignal, bus: stereo) // clamped to stereo.channelCount
|
||||
let ctrlIn = In.Control(bus: ctrl)
|
||||
|
||||
// Return when done
|
||||
engine.busAllocator.releaseAudioBus(stereo)
|
||||
engine.busAllocator.releaseControlBus(ctrl)
|
||||
```
|
||||
|
||||
**Thread safety:** `BusAllocator` is protected by an internal `NSLock`; safe from any
|
||||
language-side thread. Never call from the RT audio thread.
|
||||
|
||||
**`BusAllocatorError.noFreeBus(channelCount:)`** — thrown when no contiguous block of the
|
||||
requested size is available.
|
||||
|
||||
### `AudioBus` and `ControlBus`
|
||||
|
||||
Plain value types. Pass directly to `In.Audio(bus:)`, `In.Audio.multi(bus:)`,
|
||||
`Out.Audio(source:bus:)`, `In.Control(bus:)`, and `Out.Control(source:bus:)`. They are not
|
||||
`ValidGeneratorInput` — for bus reading use the `In` generator wrappers.
|
||||
|
||||
## Defaults
|
||||
|
||||
| Parameter | Default |
|
||||
|---|---|
|
||||
| `numAudioBuses` | 128 |
|
||||
| `numControlBuses` | 4096 |
|
||||
| `blockSize` | Configurable at init (e.g. 512) |
|
||||
@@ -0,0 +1,281 @@
|
||||
# CoreAudioDriver — Pending Fixes
|
||||
|
||||
`Sources/Lyrebird/AudioDrivers/CoreAudioDriver.swift`
|
||||
|
||||
---
|
||||
|
||||
## Blocking Issues (must fix before next merge to `main`)
|
||||
|
||||
### 1. `print()` on the RT thread — lines 764–767
|
||||
|
||||
```swift
|
||||
// CURRENT (broken)
|
||||
if renderStatus != noErr && debugBlockCount < 3 {
|
||||
print("ERROR: AudioUnitRender failed with status \(renderStatus)")
|
||||
debugBlockCount += 1
|
||||
}
|
||||
```
|
||||
|
||||
**Fix:** Replace with an `Atomic<Int32>` that stores the last error code. The main thread can
|
||||
inspect it later (e.g. in a debug accessor), but the RT thread never allocates or calls `print`.
|
||||
|
||||
```swift
|
||||
// After the property declarations:
|
||||
private let _lastInputRenderError = Atomic<Int32>(noErr)
|
||||
|
||||
// In render():
|
||||
if renderStatus != noErr {
|
||||
_lastInputRenderError.store(renderStatus, ordering: .relaxed)
|
||||
}
|
||||
```
|
||||
|
||||
Remove `debugBlockCount` entirely.
|
||||
|
||||
---
|
||||
|
||||
### 2. Non-atomic `isInitialized` — data race between `start()`/`stop()` and `render()`
|
||||
|
||||
```swift
|
||||
// CURRENT (broken)
|
||||
private var isInitialized: Bool = false // plain Bool — no ordering guarantee
|
||||
```
|
||||
|
||||
`start()` and `stop()` run on the main thread; `render()` reads `isInitialized` on the RT thread.
|
||||
This is an unsynchronised read/write pair — undefined behaviour under Swift's memory model.
|
||||
|
||||
**Fix:**
|
||||
|
||||
```swift
|
||||
private let _isInitialized = Atomic<Bool>(false)
|
||||
```
|
||||
|
||||
- `start()`: `_isInitialized.store(true, ordering: .releasing)` (after `AudioUnitInitialize`)
|
||||
- `stop()`: `_isInitialized.store(false, ordering: .releasing)`
|
||||
- `render()`: `_isInitialized.load(ordering: .acquiring)`
|
||||
- `deinit`: `_isInitialized.store(false, ordering: .releasing)` before unit disposal
|
||||
|
||||
---
|
||||
|
||||
### 3. Per-sample input copy loop — unnecessary overhead
|
||||
|
||||
```swift
|
||||
// CURRENT
|
||||
for i in 0..<frameCount {
|
||||
inputStagingBuffers[ch][i] = rawPtr[i]
|
||||
}
|
||||
```
|
||||
|
||||
**Fix:** Replace with `memcpy`. The raw pointer and staging buffer are already Float arrays of
|
||||
the correct size.
|
||||
|
||||
```swift
|
||||
inputStagingBuffers[ch].withUnsafeMutableBufferPointer { dst in
|
||||
guard let base = dst.baseAddress else { return }
|
||||
memcpy(base, rawPtr, frameCount * MemoryLayout<Float>.size)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Non-Blocking Issues (clean-up, no correctness impact today)
|
||||
|
||||
### 4. Remove all `print()` / `DEBUG:` / `ERROR:` calls from `setup()`
|
||||
|
||||
There are approximately 30 `print()` calls throughout `setup()` that were scaffolding. They
|
||||
allocate `String` instances and should be removed entirely. If diagnostics are needed in the
|
||||
future, use `os_log` with `.debug` level (compile-time stripped in release builds).
|
||||
|
||||
---
|
||||
|
||||
### 5. Replace string-matching device selection with transport-type query
|
||||
|
||||
The current "last resort" device scan (lines 326–467) uses fragile string matching:
|
||||
|
||||
```swift
|
||||
nameLower.contains("built-in")
|
||||
nameLower.contains("macbook")
|
||||
nameLower.contains("teams") // blocklist
|
||||
nameLower.contains("zoom") // blocklist
|
||||
```
|
||||
|
||||
This breaks under non-English locales and any device whose name doesn't match the expected
|
||||
patterns.
|
||||
|
||||
**Fix:** Query `kAudioDevicePropertyTransportType` and compare against
|
||||
`kAudioDeviceTransportTypeBuiltIn`. No string allocation, locale-independent.
|
||||
|
||||
```swift
|
||||
private func deviceTransportType(_ deviceID: AudioDeviceID) -> UInt32 {
|
||||
var transportType: UInt32 = 0
|
||||
var size = UInt32(MemoryLayout<UInt32>.size)
|
||||
var addr = AudioObjectPropertyAddress(
|
||||
mSelector: kAudioDevicePropertyTransportType,
|
||||
mScope: kAudioObjectPropertyScopeGlobal,
|
||||
mElement: kAudioObjectPropertyElementMain
|
||||
)
|
||||
AudioObjectGetPropertyData(deviceID, &addr, 0, nil, &size, &transportType)
|
||||
return transportType
|
||||
}
|
||||
```
|
||||
|
||||
**Device selection order** (replaces the current chain of `if/else` blocks):
|
||||
|
||||
1. `defaultOutputID == defaultInputID` → use directly (ideal: USB headset, aggregate already set in system prefs)
|
||||
2. `defaultOutputID` has ≥ `numInputChannels` input channels → use it
|
||||
3. `defaultInputID` has ≥ `numOutputChannels` output channels → use it
|
||||
4. Enumerate all devices; pick the first with `transportType == kAudioDeviceTransportTypeBuiltIn` that has both input and output → `findBuiltInDuplexDevice()`
|
||||
5. Fall through to aggregate device creation (see §6)
|
||||
|
||||
---
|
||||
|
||||
### 6. Programmatic Aggregate Device creation
|
||||
|
||||
When no single device satisfies full-duplex requirements (step 5 above falls through), create a
|
||||
private CoreAudio Aggregate Device rather than throwing an error.
|
||||
|
||||
**New error cases to add to `CoreAudioError`:**
|
||||
|
||||
```swift
|
||||
case aggregateDeviceCreationFailed(OSStatus)
|
||||
case microphoneAccessDenied
|
||||
```
|
||||
|
||||
**New stored properties:**
|
||||
|
||||
```swift
|
||||
private var aggregateDeviceID: AudioDeviceID = AudioDeviceID(kAudioObjectUnknown)
|
||||
private var coreAudioPluginID: AudioObjectID = AudioObjectID(kAudioObjectUnknown)
|
||||
```
|
||||
|
||||
**Step A — find the CoreAudio HAL plugin object:**
|
||||
|
||||
```swift
|
||||
private func findCoreAudioPluginID() -> AudioObjectID {
|
||||
// Uses AudioValueTranslation to resolve bundle ID → AudioObjectID
|
||||
let bundleID = "com.apple.audio.CoreAudio" as CFString
|
||||
var pluginID = AudioObjectID(kAudioObjectUnknown)
|
||||
var translation = AudioValueTranslation(
|
||||
mInputData: UnsafeMutableRawPointer(mutating: &bundleID as AnyObject as! UnsafeRawPointer),
|
||||
mInputDataSize: UInt32(MemoryLayout<CFString>.size),
|
||||
mOutputData: &pluginID,
|
||||
mOutputDataSize: UInt32(MemoryLayout<AudioObjectID>.size)
|
||||
)
|
||||
var addr = AudioObjectPropertyAddress(
|
||||
mSelector: kAudioHardwarePropertyPlugInForBundleID,
|
||||
mScope: kAudioObjectPropertyScopeGlobal,
|
||||
mElement: kAudioObjectPropertyElementMain
|
||||
)
|
||||
var size = UInt32(MemoryLayout<AudioValueTranslation>.size)
|
||||
AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &addr, 0, nil, &size, &translation)
|
||||
return pluginID
|
||||
}
|
||||
```
|
||||
|
||||
**Step B — create the aggregate:**
|
||||
|
||||
```swift
|
||||
private func makeAggregateDevice(
|
||||
outputDeviceID: AudioDeviceID,
|
||||
inputDeviceID: AudioDeviceID
|
||||
) throws -> AudioDeviceID {
|
||||
coreAudioPluginID = findCoreAudioPluginID()
|
||||
guard coreAudioPluginID != kAudioObjectUnknown else {
|
||||
throw CoreAudioError.aggregateDeviceCreationFailed(noErr)
|
||||
}
|
||||
|
||||
// Get UIDs for both devices
|
||||
let outputUID = try deviceUID(outputDeviceID)
|
||||
let inputUID = try deviceUID(inputDeviceID)
|
||||
|
||||
// Build the composition dictionary
|
||||
// Output device is master (drives the clock)
|
||||
let subDeviceList: [CFDictionary] = [
|
||||
[kAudioSubDeviceUIDKey: outputUID] as CFDictionary,
|
||||
[kAudioSubDeviceUIDKey: inputUID] as CFDictionary,
|
||||
]
|
||||
let aggDesc: [String: Any] = [
|
||||
kAudioAggregateDeviceNameKey: "LyrebirdAggregate",
|
||||
kAudioAggregateDeviceUIDKey: "com.lyrebird.aggregate.\(UUID().uuidString)",
|
||||
kAudioAggregateDeviceSubDeviceListKey: subDeviceList,
|
||||
kAudioAggregateDeviceMasterSubDeviceKey: outputUID,
|
||||
kAudioAggregateDeviceIsPrivateKey: 1, // auto-destroyed when plugin releases it
|
||||
kAudioAggregateDeviceIsStackedKey: 0,
|
||||
]
|
||||
|
||||
var newDeviceID = AudioDeviceID(kAudioObjectUnknown)
|
||||
var addr = AudioObjectPropertyAddress(
|
||||
mSelector: kAudioPlugInCreateAggregateDevice,
|
||||
mScope: kAudioObjectPropertyScopeGlobal,
|
||||
mElement: kAudioObjectPropertyElementMain
|
||||
)
|
||||
let qualifier = aggDesc as CFDictionary
|
||||
var size = UInt32(MemoryLayout<AudioDeviceID>.size)
|
||||
let status = AudioObjectGetPropertyData(
|
||||
coreAudioPluginID, &addr,
|
||||
UInt32(MemoryLayout<CFDictionary>.size), [qualifier] as AnyObject,
|
||||
&size, &newDeviceID
|
||||
)
|
||||
guard status == noErr else { throw CoreAudioError.aggregateDeviceCreationFailed(status) }
|
||||
aggregateDeviceID = newDeviceID
|
||||
return newDeviceID
|
||||
}
|
||||
```
|
||||
|
||||
**Step C — destroy on `stop()` and `deinit`:**
|
||||
|
||||
```swift
|
||||
private func destroyAggregateDevice() {
|
||||
guard aggregateDeviceID != AudioDeviceID(kAudioObjectUnknown),
|
||||
coreAudioPluginID != AudioObjectID(kAudioObjectUnknown) else { return }
|
||||
var addr = AudioObjectPropertyAddress(
|
||||
mSelector: kAudioPlugInDestroyAggregateDevice,
|
||||
mScope: kAudioObjectPropertyScopeGlobal,
|
||||
mElement: kAudioObjectPropertyElementMain
|
||||
)
|
||||
var deviceID = aggregateDeviceID
|
||||
var size = UInt32(MemoryLayout<AudioDeviceID>.size)
|
||||
AudioObjectSetPropertyData(coreAudioPluginID, &addr, 0, nil, size, &deviceID)
|
||||
aggregateDeviceID = AudioDeviceID(kAudioObjectUnknown)
|
||||
}
|
||||
```
|
||||
|
||||
Call `destroyAggregateDevice()` at the top of `stop()` (before `AudioOutputUnitStop`) and in
|
||||
`deinit`.
|
||||
|
||||
---
|
||||
|
||||
### 7. Named constant for bytes-per-sample
|
||||
|
||||
The literal `4` appears in six `AudioStreamBasicDescription` initialisers.
|
||||
|
||||
```swift
|
||||
private let lyrebirdBytesPerSample: UInt32 = 4 // 32-bit float = 4 bytes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 8. Microphone permission — throw instead of print
|
||||
|
||||
```swift
|
||||
// CURRENT
|
||||
} else if authStatus == .denied || authStatus == .restricted {
|
||||
print("ERROR: Microphone access denied...")
|
||||
}
|
||||
```
|
||||
|
||||
**Fix:** Throw `CoreAudioError.microphoneAccessDenied` so the caller can surface it to the user.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Order
|
||||
|
||||
1. Fix §1 (`_lastInputRenderError` + remove `debugBlockCount`) — blocking RT issue
|
||||
2. Fix §2 (`_isInitialized` → `Atomic<Bool>`) — blocking data race
|
||||
3. Fix §3 (`memcpy`) — trivial, same block
|
||||
4. Fix §8 (throw on mic denied) — small change, clear error contract
|
||||
5. Fix §7 (named constant) — cosmetic, do while touching ASBD initialisers
|
||||
6. Fix §4 (remove all `print()` from `setup()`)
|
||||
7. Fix §5 (transport-type device selection)
|
||||
8. Fix §6 (aggregate device creation) — largest change; implement last
|
||||
|
||||
Run `/lyrebird_review` after all eight steps are complete.
|
||||
@@ -0,0 +1,232 @@
|
||||
# LyrebirdEventList Routing Design
|
||||
|
||||
## The Bug (pre-Phase X)
|
||||
|
||||
`LyrebirdEventList` allocated its own private `_masterBus` and, when starting any
|
||||
contained `LyrebirdProcess`, passed `procOutOverride: masterBus` to
|
||||
`LyrebirdProcess._play`. This **silently discarded** whatever `procOut` the
|
||||
process factory had configured.
|
||||
|
||||
`EventListMasterSynth` then read from `_masterBus`, applied a lag-smoothed master
|
||||
amplitude, and wrote to **hardcoded `outBusIndex: 0`** (hardware out).
|
||||
|
||||
### Symptom
|
||||
|
||||
A process configured with `procOut: ambisonicRoutingBus` (intending to feed an
|
||||
`AmbisonicDecoder` placed `.after(engine.mainGroup)`) had its B-format output
|
||||
re-routed to `_masterBus` instead of `ambisonicRoutingBus`. The downstream
|
||||
decoder read silence. The master synth then wrote raw, un-decoded B-format
|
||||
directly to hardware buses 0..N-1.
|
||||
|
||||
For a quad setup with `masterChannels: 4`, the user saw raw W/X/Y/Z components
|
||||
on hardware outputs 0/1/2/3 — three "loud" channels and a flat Z (elevation = 0)
|
||||
— with no spatialization at all. With the default `masterChannels: 2`, the W/X
|
||||
components landed on hw 0/1 and the decoder again ran on silence.
|
||||
|
||||
### Why It Was Designed That Way
|
||||
|
||||
Early `LyrebirdEventList` used a single shared master bus to mix all owned
|
||||
processes through one amplitude control, modelled after the trivial stereo
|
||||
case where every process writes mono/stereo straight to hardware out and the
|
||||
master synth applies a global volume. The override made wiring "just work" for
|
||||
that case but is incompatible with any process that needs to feed an effect
|
||||
chain (ambisonic decode, reverb send, sidechain, multi-bus stem, etc.).
|
||||
|
||||
## The Fix
|
||||
|
||||
Two coupled changes:
|
||||
|
||||
1. **Drop `procOutOverride`.** All three `_play` call sites in
|
||||
`LyrebirdEventList` (`playEvent`, `initProcess` first-event setup,
|
||||
`killProcess` teardown) pass `procOutOverride: nil`; the parameter itself
|
||||
has been removed from `LyrebirdProcess._play`. The process writes to its
|
||||
own declared `procOut`.
|
||||
|
||||
2. **Make the EventList's master bus user-supplied.** `LyrebirdEventList.init`
|
||||
now takes a `bus: AudioBus` parameter (replacing `masterChannels: Int`).
|
||||
Channel count is derived from `bus.channelCount`. No private bus is
|
||||
allocated.
|
||||
|
||||
3. **Master synth applies amp in-place via `ReplaceOut`.**
|
||||
`EventListMasterSynth.build()` reads N channels of `bus`, multiplies by
|
||||
the lag-smoothed `amp` (mono-broadcast via `BinaryOpGenerator`'s
|
||||
channel-aware policy), and overwrites the same N buses via a single
|
||||
`ReplaceOut.Audio`:
|
||||
|
||||
let inSig = In.Audio(bus: bus) // reads bus.channelCount channels
|
||||
let scaled = inSig * smoothAmp // N-channel × 1-channel → N
|
||||
replaceOutput(bus: bus, source: scaled) // overwrites bus.channelCount buses
|
||||
|
||||
The master synth lives in `_masterGroup`, which is added as a sibling
|
||||
immediately after the process group (`.after(group)`). Both groups sit
|
||||
inside `engine.mainGroup` (at `.head`). The result is:
|
||||
|
||||
mainGroup
|
||||
├── group (event-list process group, head)
|
||||
│ └── processes write to their own procOut (e.g. ambisonicRoutingBus)
|
||||
└── _masterGroup
|
||||
├── _preMasterGroup (caller-FX, e.g. AmbisonicDecoder)
|
||||
├── EventListMasterSynth (In * amp → ReplaceOut, in place)
|
||||
└── _postMasterGroup (caller-FX, e.g. limiter, tap recorder)
|
||||
[optional consumer placed `.after(engine.mainGroup)` reads scaled `bus`]
|
||||
|
||||
Order is sufficient because Lyrebird's signal-flow runs the head group
|
||||
first, then `_masterGroup` (so master sees the fully-written `bus`), and
|
||||
then any node placed `.after(mainGroup)`.
|
||||
|
||||
## Caller Responsibilities
|
||||
|
||||
- The caller is responsible for ensuring the `bus` passed to
|
||||
`LyrebirdEventList` is the bus their `LyrebirdProcess` factories actually
|
||||
write to (`procOut:` matches `bus:`). Otherwise the master amp control has
|
||||
no effect on that process.
|
||||
- If the caller wants no amp scaling, pass `amp: 1.0` (ReplaceOut multiplies
|
||||
by 1 — effective passthrough).
|
||||
- The hardware-out path is no longer hardcoded. The caller can place any
|
||||
number of effects/decoders/recorders between the EventList's bus and the
|
||||
hardware output, simply by adding synths at appropriate positions in the
|
||||
node tree — or use ``LyrebirdEventList/addPreMaster(_:)`` /
|
||||
``LyrebirdEventList/addPostMaster(_:)`` (see below).
|
||||
|
||||
## Historical Note — The Delta-Add Predecessor
|
||||
|
||||
The first cut of this refactor (before `ReplaceOut` existed) applied amp via
|
||||
an additive trick on top of `Out.Audio`:
|
||||
|
||||
bus[ch] = bus[ch] + bus[ch] * (amp - 1)
|
||||
= bus[ch] * amp
|
||||
|
||||
Cute but indirect — required a comment to be readable, and only generalised to
|
||||
scalar amp scaling. `ReplaceOut.Audio` superseded it: same per-sample cost
|
||||
(1 mul + 1 store vs 1 mul + 1 add), clearer semantics, and a primitive the
|
||||
codebase can reuse for any read-transform-replace pattern (bus-level limiters,
|
||||
master recorders, decoders that take ownership of hw-out buses).
|
||||
|
||||
## Why Not Pattern B (User Multiplies Amp In Their Chain)?
|
||||
|
||||
Considered: drop the master synth entirely, expose `amp` only as an
|
||||
`@LiveParam` for the caller to wire into their own decoder/effect chain.
|
||||
Rejected because the most common case (process writes to hardware out, single
|
||||
event list) still benefits from a zero-config master amp. The current design
|
||||
preserves drop-in convenience for the simple case while removing the override
|
||||
that broke chained-effect cases.
|
||||
|
||||
## ReplaceOut Refactor
|
||||
|
||||
`ReplaceOut.Audio` / `ReplaceOut.Control` are first-class **overwrite** bus
|
||||
write primitives parallel to `Out.Audio` / `Out.Control`. The master synth now
|
||||
reads N channels of the EventList's `bus`, multiplies by the lag-smoothed
|
||||
amp (mono-broadcast via the `BinaryOpGenerator` channel-aware policy), and
|
||||
overwrites the same N buses via a single `ReplaceOut.Audio` call.
|
||||
|
||||
### ReplaceOut semantics
|
||||
|
||||
- Overwrites the target bus, wiping any prior writes in the current block's
|
||||
`[offset, offset + count)` range.
|
||||
- Multi-channel sources fan out to consecutive buses, just like `Out.Audio`.
|
||||
- Inside a `ParallelGroup`, ReplaceOut routes through
|
||||
`ScratchBuses.replace`, which only overwrites *this child's scratch
|
||||
contribution*. Other siblings' parallel writes and any pre-existing
|
||||
engine-bus content are unaffected. Outside a `ParallelGroup`, ReplaceOut
|
||||
routes through `SynthesisEngine.setAudioBus`, which scrubs the engine bus
|
||||
directly.
|
||||
- Engine plumb: `engine.setAudioBus(_:offset:samples:count:)` writes the
|
||||
bus slice via `vDSP_vdpsp` (Double → Float) directly into the bus
|
||||
pointer; no accumulate scratch needed.
|
||||
- `SynthesizerBase.replaceOutput(bus:source:)` mirrors
|
||||
`SynthesizerBase.output(bus:source:)` — auto-registers via
|
||||
`RootRegistering`.
|
||||
|
||||
### Trade-offs vs delta-add
|
||||
|
||||
| Aspect | Delta-add | ReplaceOut |
|
||||
|--------|-----------|------------|
|
||||
| Cost per sample | 1 mul + 1 add | 1 mul + 1 store |
|
||||
| Per-channel passes | N (manual loop) | 1 (multi-channel source fans out) |
|
||||
| Readability | Trick comment required | Direct read/scale/replace |
|
||||
| Generalises | Specific to amp scaling | Any read-transform-replace pattern |
|
||||
| Foot-guns | None | Wipes prior writes — node-tree order critical |
|
||||
|
||||
The cost is essentially equal at the per-sample level; ReplaceOut wins on
|
||||
clarity and on enabling additional patterns (bus-level limiters, master
|
||||
recorders, decoders that take ownership of hw-out buses).
|
||||
|
||||
## Pre/Post-Master Groups
|
||||
|
||||
EventList exposes two insertion groups inside `_masterGroup`:
|
||||
|
||||
```
|
||||
mainGroup
|
||||
├── group (process group, head)
|
||||
│ └── processes write to their declared procOut
|
||||
└── _masterGroup
|
||||
├── _preMasterGroup ← caller adds decoders / pre-master FX
|
||||
├── EventListMasterSynth ← reads bus, scales by amp, overwrites bus
|
||||
└── _postMasterGroup ← caller adds limiters / mastering FX
|
||||
```
|
||||
|
||||
Public API:
|
||||
|
||||
```swift
|
||||
public var preMasterGroup: Group { _preMasterGroup }
|
||||
public var postMasterGroup: Group { _postMasterGroup }
|
||||
public func addPreMaster(_ synth: any Synthesizer)
|
||||
public func addPostMaster(_ synth: any Synthesizer)
|
||||
```
|
||||
|
||||
### Use cases
|
||||
|
||||
- **Ambisonic / multi-speaker decode**: factory writes B-format to a
|
||||
routing bus; pre-master decoder reads the routing bus, decodes, writes
|
||||
speaker feeds to the EventList's `bus`. Master synth then scales the
|
||||
speaker feeds. Post-master synth can apply a limiter to the scaled feed.
|
||||
- **Bus-level sidechain**: pre-master compressor reads control input,
|
||||
reduces bus content before master amp.
|
||||
- **Master recorder / tap**: post-master `DiskOut` records the final
|
||||
scaled signal alongside per-process stems.
|
||||
|
||||
### Lifecycle
|
||||
|
||||
- `_preMasterGroup` and `_postMasterGroup` are constructed in
|
||||
`LyrebirdEventList.init` and added to the engine in `_firstEventSetup`.
|
||||
- Synths added via `addPreMaster` / `addPostMaster` are children of those
|
||||
groups, so they are freed when `_masterGroup.free()` runs in
|
||||
`_teardownMaster()` (which happens on `killAll`, on natural envelope
|
||||
end-of-list, or on `reset()`).
|
||||
- After teardown the EventList re-allocates fresh empty pre/post groups so
|
||||
subsequent playback sessions start from a clean slate.
|
||||
|
||||
### Ordering guarantees
|
||||
|
||||
Group children evaluate in insertion order. `_firstEventSetup` adds, in
|
||||
sequence:
|
||||
|
||||
1. `_preMasterGroup` at `.head(of: _masterGroup)`
|
||||
2. `EventListMasterSynth` at `.tail(of: _masterGroup)` (now second)
|
||||
3. `_postMasterGroup` at `.tail(of: _masterGroup)` (now third)
|
||||
|
||||
So evaluation order within `_masterGroup` is strictly pre → master → post.
|
||||
Synths added later via `addPreMaster` / `addPostMaster` are appended to
|
||||
their respective sub-group's tail; their relative order matches insertion
|
||||
order.
|
||||
|
||||
## Migration
|
||||
|
||||
`LyrebirdEventList.init` signature change is breaking. Callers must replace
|
||||
|
||||
masterChannels: 2
|
||||
|
||||
with
|
||||
|
||||
bus: <theirAudioBus>
|
||||
|
||||
The `buildFromFile` static factory and recording-related code follow the same
|
||||
substitution.
|
||||
|
||||
For callers that previously relied on the default master-to-hw-out routing
|
||||
with `masterChannels: 2`: construct `let outBus = AudioBus(index: 0,
|
||||
channelCount: 2)` and pass `bus: outBus`. Each process should also have its
|
||||
`procOut` set to the same bus (most factories default to `procOut: 0`, which
|
||||
matches). The `bus:` parameter retains a default of
|
||||
`AudioBus(index: 0, channelCount: 2)` so call sites that omit it compile
|
||||
unchanged.
|
||||
@@ -0,0 +1,89 @@
|
||||
# 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 `ParallelGroup`s:** 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:**
|
||||
|
||||
```swift
|
||||
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`](multi-engine-host.md) for the role-based, creation-owning `EngineHost` facade including the NRT pool API.
|
||||
@@ -0,0 +1,317 @@
|
||||
# EngineHost — Multi-Engine Facade
|
||||
|
||||
Creation-owning facade for processes that need **two or more** `SynthesisEngine` instances.
|
||||
|
||||
Single-engine code does **not** use the host. Direct `SynthesisEngine()` construction remains the supported path for N = 1. The host adds nothing for the single-engine case that the `EngineLifecycleCoordinator` registry does not already provide.
|
||||
|
||||
---
|
||||
|
||||
## When to use the host
|
||||
|
||||
- **NRT batch render** — render N audio files in parallel, one engine per file. Use `renderConcurrent(jobs:)`.
|
||||
- **Multi-device RT output** — drive two separate audio devices (e.g. headphone + main + sub) from one process, one engine per AUHAL device.
|
||||
- **Auxiliary engines** — analysis-only side engines, decoder side-chains, scope taps that should be lifecycle-managed with the rest of the process.
|
||||
- **Test fixtures** — wrap a small set of engines for unified start/stop in integration tests.
|
||||
|
||||
If your process uses one engine throughout, do not introduce the host. The direct constructor + binding APIs cover the single-engine case.
|
||||
|
||||
---
|
||||
|
||||
## Role-based registration
|
||||
|
||||
Every engine the host manages carries a `EngineHostRole`:
|
||||
|
||||
```swift
|
||||
public enum EngineHostRole: Hashable, Sendable {
|
||||
case nrtRender(slot: Int)
|
||||
case rtOutput(deviceID: UInt32)
|
||||
case auxiliary(name: String)
|
||||
case custom(String)
|
||||
}
|
||||
```
|
||||
|
||||
| Case | Purpose | Uniqueness enforcement |
|
||||
|---|---|---|
|
||||
| `.nrtRender(slot:)` | NRT batch render slot | Role-identity (slot index) |
|
||||
| `.rtOutput(deviceID:)` | Realtime AUHAL output | Role-identity + per-device |
|
||||
| `.auxiliary(name:)` | Non-output engine | Role-identity (name string) |
|
||||
| `.custom(String)` | Escape hatch | Role-identity (string) |
|
||||
|
||||
The host throws `EngineHostError.duplicateRole(role)` on any second registration under the same role. For `.rtOutput(deviceID:)`, same deviceID implies the same role (deviceID is part of the role's `Hashable` key), so duplicate device registration surfaces as `.duplicateRole`. AUHAL grants exclusive ownership per output device on macOS — the host's role-keyed registry enforces this at the API. (There is no separate `.duplicateDevice` enum case — it would be unreachable given the role-keyed design; re-add one only if a future role shape ever cross-cuts deviceID under a different surrounding case.)
|
||||
|
||||
**`.rtOutput.deviceID` semantics.** On macOS the `UInt32` is the raw bit pattern of `CoreAudio.AudioDeviceID`. On iOS the type carries no native meaning (RemoteIO does not address individual hardware devices — `AVAudioSession` routes are chosen at the session layer). Pass `0` for the default iOS route, or any caller-defined unique value if you want host-level uniqueness checks against other RT engines.
|
||||
|
||||
---
|
||||
|
||||
## Creation: `makeEngine(role:config:)`
|
||||
|
||||
```swift
|
||||
let host = EngineHost()
|
||||
let cfg = SynthesisEngineConfig(
|
||||
blockSize: 256,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
let engine = try host.makeEngine(role: .rtOutput(deviceID: 0), config: cfg)
|
||||
```
|
||||
|
||||
`SynthesisEngineConfig` mirrors `SynthesisEngine.init` one-for-one with the same defaults. It is a value-typed carrier so callers don't thread eight parameters through every `makeEngine` call.
|
||||
|
||||
The returned engine is held strongly by the host. Caller may keep its own reference but the host's strong reference is the primary owner.
|
||||
|
||||
---
|
||||
|
||||
## Lookup
|
||||
|
||||
```swift
|
||||
let engine: SynthesisEngine? = host.engine(for: .nrtRender(slot: 0))
|
||||
let role: EngineHostRole? = host.role(for: someEngine)
|
||||
|
||||
let all: [SynthesisEngine] = host.engines // snapshot, unordered
|
||||
let allRoles: [EngineHostRole] = host.roles
|
||||
let n: Int = host.engineCount
|
||||
```
|
||||
|
||||
All accessors hold the host's internal `NSLock` briefly; snapshots return arrays so callers can iterate without holding any lock.
|
||||
|
||||
---
|
||||
|
||||
## Lifecycle: `startAll()` / `stopAll()`
|
||||
|
||||
```swift
|
||||
try host.startAll()
|
||||
defer { host.stopAll() }
|
||||
```
|
||||
|
||||
`startAll()` walks the registered engines from a snapshot taken under the host's lock, then calls `engine.start()` on each **outside the lock**. Concurrent host accessors (`engine(for:)`, `engineCount`, other `makeEngine` / `adopt` callers) are not blocked during the start sequence. Iteration order over the role dictionary is not stable; if your scenario requires a specific start ordering, register engines and start them explicitly via `engine(for:)`.
|
||||
|
||||
**Snapshot race window.** A `makeEngine` / `adopt` that commits between the snapshot and the loop end will leave its engine unstarted by this `startAll` call. Call `startAll()` once after all registrations complete, or serialise registration and startup on the caller side.
|
||||
|
||||
**Rollback on failure.** If one engine throws during start, every previously-started engine is rolled back with `engine.stop()` before the host throws `EngineHostError.startFailed(engine:underlying:)`. Partial start states are not exposed to the caller.
|
||||
|
||||
`stopAll()` is the reverse — `engine.stop()` is idempotent so calling `stopAll()` on a never-started or partially-started host is safe.
|
||||
|
||||
---
|
||||
|
||||
## Adoption: `adopt(existing:role:)`
|
||||
|
||||
Escape hatch for **migration** scenarios (existing direct-ctor code wanting to opt into host lifecycle without re-construction) and **test fixtures** (an engine constructed by a test helper that needs host registration after the fact):
|
||||
|
||||
```swift
|
||||
let engine = SynthesisEngine(blockSize: 256, sampleRate: 44100,
|
||||
numOutputChannels: 2, numInputChannels: 0,
|
||||
driver: someDriver)
|
||||
try host.adopt(existing: engine, role: .custom("imported"))
|
||||
```
|
||||
|
||||
The host verifies the engine is visible in `EngineLifecycleCoordinator.shared.engines` before accepting — guards against passing a deinit-in-progress engine or one constructed via an unsupported path. Throws `EngineHostError.adoptRejected(engine:reason:)` if the verification fails.
|
||||
|
||||
After adoption the engine is indistinguishable from a `makeEngine`-constructed engine: same role-keyed lookup, same `startAll`/`stopAll` participation.
|
||||
|
||||
---
|
||||
|
||||
## NRT batch render: `renderConcurrent(jobs:maxConcurrent:)`
|
||||
|
||||
The blessed entry point for "render N audio files in parallel."
|
||||
|
||||
```swift
|
||||
let host = EngineHost()
|
||||
let jobs: [NRTJob] = mixes.enumerated().map { i, mix in
|
||||
NRTJob(
|
||||
outputURL: outDir.appendingPathComponent("mix_\(i).caf"),
|
||||
duration: 4.0,
|
||||
blockSize: 512,
|
||||
sampleRate: 48000,
|
||||
numOutputChannels: 2
|
||||
) { engine in
|
||||
try engine.add(mix.makeRouteSynth())
|
||||
}
|
||||
}
|
||||
|
||||
for try await result in host.renderConcurrent(jobs: jobs, maxConcurrent: 4) {
|
||||
print("rendered \(result.outputURL.lastPathComponent) in \(result.elapsed) s")
|
||||
}
|
||||
```
|
||||
|
||||
### Job descriptors
|
||||
|
||||
`NRTJob` is a `Sendable` value carrying everything needed to spin up one engine and render one file:
|
||||
|
||||
| Field | Purpose |
|
||||
|---|---|
|
||||
| `outputURL: URL` | Destination CAF file |
|
||||
| `duration: Double` | Render duration in seconds |
|
||||
| `blockSize: Int` | Engine block size (defaults to `lyrebirdDefaultResultBufferSize = 512`) |
|
||||
| `sampleRate: Double` | Engine sample rate |
|
||||
| `numOutputChannels: Int` | 2 / 4 / 8 channel render |
|
||||
| `inputURL: URL?` | Optional source file for processing jobs |
|
||||
| `inputStartOffset: Double` | Seconds to skip into `inputURL` |
|
||||
| `build: @Sendable (SynthesisEngine) throws -> Void` | Closure adding synths before render |
|
||||
|
||||
The `build` closure runs on the background `Task` executing the job — it must be `@Sendable` (no captures of non-Sendable state, no mutation of shared mutable references). Engine binding enforces that synthesizers added to one job's engine cannot leak into another job's engine.
|
||||
|
||||
### Completion records
|
||||
|
||||
`NRTResult` is yielded per successful render:
|
||||
|
||||
```swift
|
||||
public struct NRTResult: Sendable {
|
||||
public let outputURL: URL
|
||||
public let jobIndex: Int // correlation back to input array
|
||||
public let elapsed: Double // wall-clock seconds
|
||||
}
|
||||
```
|
||||
|
||||
**Results stream in completion order, not input order.** Use `jobIndex` to correlate results back to the original job list.
|
||||
|
||||
### Concurrency
|
||||
|
||||
`maxConcurrent` defaults to `ProcessInfo.processInfo.activeProcessorCount` and is clamped to `[1, jobs.count]`. The host drives a `withThrowingTaskGroup` with a seed-and-refill pattern: initial `maxConcurrent` jobs spawn; each completion triggers spawn of the next queued job until the input is exhausted.
|
||||
|
||||
### Failure semantics
|
||||
|
||||
If any job throws (from its `build` closure, from `engine.start()`, or from the `NRTDriver`), the throw propagates via the `AsyncThrowingStream`'s throw path. Iterate with `for try await`:
|
||||
|
||||
```swift
|
||||
do {
|
||||
for try await result in host.renderConcurrent(jobs: jobs) { … }
|
||||
} catch let error as DeliberateBuildFailure {
|
||||
// handle
|
||||
}
|
||||
```
|
||||
|
||||
Behaviour on throw:
|
||||
- The throwing job's error propagates through the AsyncThrowingStream.
|
||||
- `withThrowingTaskGroup` cancels the remaining child tasks when the body's `for try await` rethrows, and the refill loop's `addTaskUnlessCancelled` no longer spawns queued jobs.
|
||||
- Cancellation propagates only as a flag — child tasks check `Task.isCancelled` cooperatively. `_executeJob` calls `engine.start()` which renders synchronously without cancellation checks, so any in-flight render runs to completion regardless of cancellation. Their results are discarded (the stream is finished by the time they return).
|
||||
|
||||
The stream is single-shot — once it finishes (clean end or throw), no further results arrive.
|
||||
|
||||
### Pool engines are not host-registered
|
||||
|
||||
NRT pool jobs spin up their engines **inline** — they are not registered in the host's role map. The engine lives for the duration of one render and deinits when the executing function returns. `EngineLifecycleCoordinator`'s auto register/unregister still applies.
|
||||
|
||||
This means:
|
||||
- `host.engines` does **not** include pool jobs (the host's role map and the pool are independent facilities).
|
||||
- Cancelling the stream cancels the underlying Task; in-flight engines stop naturally as their `engine.start()` returns.
|
||||
|
||||
---
|
||||
|
||||
## Drawbacks (acknowledged)
|
||||
|
||||
1. **New top-level public type.** API-stability commitment. If the role enum gains new cases (e.g. `.scope`, `.midiClock`) in a future phase, those additions are non-breaking — but renaming/removing cases is a major version bump.
|
||||
2. **God-object risk.** The host is deliberately scoped to lifecycle + ownership registry + NRT pool. Routing stays in the bus system; scheduling stays per-engine; MIDI / OSC stay unchanged. Avoid expanding the host's responsibilities.
|
||||
3. **Adoption optional.** Multi-engine bug reports without a host present require triage of "do you have an `EngineHost`?" as the first question.
|
||||
|
||||
---
|
||||
|
||||
## Drawbacks of NOT using the host
|
||||
|
||||
If you spin up two engines manually (direct `SynthesisEngine()` × 2) without a host, you lose:
|
||||
|
||||
- Role-keyed uniqueness check — nothing prevents two engines from binding to the same AUHAL device until the second one's `start()` fails at the driver layer.
|
||||
- `startAll` / `stopAll` rollback semantics — you must hand-roll the partial-start cleanup.
|
||||
- The `renderConcurrent` NRT pool API.
|
||||
|
||||
The `EngineLifecycleCoordinator` still tracks the engines, and binding errors still surface — but the convenience layer is missing.
|
||||
|
||||
---
|
||||
|
||||
## Caveats and footguns
|
||||
|
||||
Non-blocking findings that affect users of the host.
|
||||
|
||||
### NRT pool memory cost on high-core systems
|
||||
|
||||
`renderConcurrent`'s default `maxConcurrent: ProcessInfo.processInfo.activeProcessorCount` × per-engine working set can be large.
|
||||
|
||||
Per-engine memory at a glance (steady state):
|
||||
|
||||
| Component | Size |
|
||||
|---|---|
|
||||
| `audioBuses` | `numAudioBuses × blockSize × sizeof(Float)` |
|
||||
| `controlBuses` | `numControlBuses × sizeof(Float)` |
|
||||
| `_busAccumulateScratch` | `blockSize × sizeof(Float)` |
|
||||
| `ScratchBuses` (per `ParallelGroup` child) | `numChildren × numAudioBuses × blockSize × sizeof(Float)` |
|
||||
| Generator output buffers (per generator) | `lyrebirdDefaultResultBufferSize × numChannels × sizeof(Double)` |
|
||||
|
||||
On an M3 Max (16 cores) running stereo 48kHz with `numAudioBuses = 128`, `blockSize = 512`, the bus alone is ~2.5 MB × 16 ≈ 40 MB before any synth graph. iOS / memory-constrained Mac can OOM under the default cap.
|
||||
|
||||
**Mitigation.** Cap `maxConcurrent` to `min(4, activeProcessorCount)` on mobile / shared-memory targets, or size the cap to your render-time budget × per-render working set on desktop. Set explicitly:
|
||||
|
||||
```swift
|
||||
let cap = max(1, ProcessInfo.processInfo.activeProcessorCount - 2)
|
||||
for try await result in host.renderConcurrent(jobs: jobs, maxConcurrent: cap) { … }
|
||||
```
|
||||
|
||||
### In-flight NRT jobs continue writing to disk after stream cancellation
|
||||
|
||||
`engine.start()` renders synchronously without cooperative-cancellation checks. Caller break → in-flight renders run to completion → CAF files land on disk → results are discarded by the closed `for try await` loop. Users expect "cancellation = no files left behind."
|
||||
|
||||
**Mitigation.** Track the expected output URLs on the caller side; on cancellation, walk the set and delete any URLs that did not receive a corresponding `NRTResult`:
|
||||
|
||||
```swift
|
||||
var pending: Set<URL> = Set(jobs.map(\.outputURL))
|
||||
do {
|
||||
for try await result in host.renderConcurrent(jobs: jobs) {
|
||||
pending.remove(result.outputURL)
|
||||
if shouldCancel { break }
|
||||
}
|
||||
} catch { … }
|
||||
// `pending` now contains URLs for jobs that either never ran, or ran
|
||||
// and landed on disk after the loop broke. Either case is cleanup.
|
||||
for url in pending {
|
||||
try? FileManager.default.removeItem(at: url)
|
||||
}
|
||||
```
|
||||
|
||||
### Cross-job synth-instance sharing trips engine binding
|
||||
|
||||
If you share a `Synthesizer` instance across `NRTJob.build` closures (captured by a job-list-building loop without re-construction), the first job binds the synth to its engine via the `_engineBinding` CAS. Subsequent jobs then throw `EngineAddError.boundToOtherEngine` — surprising because the first engine is "gone" from the caller's perspective.
|
||||
|
||||
The binding atomic survives the first engine's `deinit`. Either:
|
||||
|
||||
- An explicit `engine.remove(synth)` on the bound engine clears the binding (but pool engines deinit when `_executeJob` returns — there is no opportunity for a caller-side `remove`).
|
||||
- A subsequent `_bind` on a different engine triggers the stale-pointer recovery path. The recovery is bounded by a documented address-reuse known limit — if Swift's allocator places the new engine at the freed engine's exact address, the new bind misclassifies as `.doubleAdd`. See `Tests/LyrebirdTests/MultiEngineRegressionTests.swift::bindRecoversFromStaleEnginePointer` for the test that exercises this.
|
||||
|
||||
**Mitigation.** Construct fresh synth instances **inside** the `build` closure, not in the outer job-list-building scope:
|
||||
|
||||
```swift
|
||||
// WRONG — synth is captured once and bound to job 0's engine.
|
||||
let synth = MySynth()
|
||||
let jobs = (0..<4).map { i in
|
||||
NRTJob(...) { engine in try engine.add(synth) }
|
||||
}
|
||||
|
||||
// RIGHT — each build closure constructs its own synth.
|
||||
let jobs = (0..<4).map { i in
|
||||
NRTJob(...) { engine in try engine.add(MySynth()) }
|
||||
}
|
||||
```
|
||||
|
||||
### Cooperative thread pool starvation on long renders
|
||||
|
||||
`_executeJob` runs a synchronous NRT render on a regular `Task` → occupies one cooperative-pool slot for the full render duration. With `maxConcurrent` = `activeProcessorCount`, the entire Swift global executor is parked for the render. Other async work in the same process stalls until at least one render completes and frees a slot.
|
||||
|
||||
**Mitigation (user-side).** Cap `maxConcurrent` below `activeProcessorCount` to leave headroom:
|
||||
|
||||
```swift
|
||||
let cap = max(1, ProcessInfo.processInfo.activeProcessorCount - 2)
|
||||
```
|
||||
|
||||
**Mitigation (future host change, deferred).** Dispatch `_executeJob` onto a dedicated `DispatchQueue.global(qos: .userInitiated)` and bridge to the `Task` via continuation. Decouples renders from the cooperative pool entirely. Tracked as a future change.
|
||||
|
||||
### `adopt(existing:role:)` TOCTOU is benign
|
||||
|
||||
`adopt` verifies the engine is live via `EngineLifecycleCoordinator.shared.engines` outside the host lock, then commits the registration under the host lock. The engine could deinit between the two — but Swift ARC guarantees the engine stays alive once the host's strong reference is acquired at commit time. The original strong-ref holder racing `deinit` either had a strong ref the whole time (no deinit) or already lost the ref by the time the coordinator's weak ref was non-nil at check time (engine cannot have started `deinit` while a strong ref existed).
|
||||
|
||||
**No user mitigation required** — the race is benign by ARC semantics. Surfaced here so users do not assume `adopt` needs external locking.
|
||||
|
||||
## See also
|
||||
|
||||
- `docs/engine/synthesis-engine.md` § Engine Identity, Ownership Binding
|
||||
- `docs/engine/multi-core.md` § Multiple Engine Instances, Object ownership rules
|
||||
- `Tests/LyrebirdTests/EngineHostTests.swift` — 14 host-coverage tests
|
||||
- `Tests/LyrebirdTests/MultiEngineRegressionTests.swift::twoEnginesViaHostUniformityContract` — host-variant of the two-engine concurrent regression test, proves the host-driven path produces the same observable behaviour as direct-ctor
|
||||
@@ -0,0 +1,223 @@
|
||||
# Scheduling & Event Timing
|
||||
|
||||
## Design Goals
|
||||
|
||||
- Synthesizers are fully allocated **before** entering the signal tree — the RT thread never allocates
|
||||
- Events are scheduled with a `SampleTime` target — 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
|
||||
|
||||
```swift
|
||||
typealias SampleTime = Int64 // monotonic sample counter, updated each block
|
||||
```
|
||||
|
||||
The engine exposes:
|
||||
```swift
|
||||
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.
|
||||
|
||||
```swift
|
||||
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
|
||||
|
||||
```swift
|
||||
// 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)
|
||||
|
||||
```swift
|
||||
// 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`:
|
||||
|
||||
```swift
|
||||
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:
|
||||
|
||||
```swift
|
||||
// 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 to `freeQueue`
|
||||
- A background `DispatchQueue` drains `freeQueue` and 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
|
||||
|
||||
```swift
|
||||
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`:
|
||||
|
||||
```swift
|
||||
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)`.
|
||||
@@ -0,0 +1,286 @@
|
||||
# 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 |
|
||||
Reference in New Issue
Block a user