# 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: 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.