# Node Tree and Group Actions The Lyrebird signal graph is a tree of `Synthesizer` nodes owned by `SynthesisEngine`. Every node that produces or processes audio lives in this tree; nodes outside the tree are never evaluated. --- ## Tree Structure ``` SynthesisEngine └── rootGroup (Group, persistent) ├── [pre-main nodes] ← .before(engine.mainGroup) — input limiters, gates, etc. ├── mainGroup (Group, persistent) ← default engine.add(_:) target │ ├── Synthesizer ← newest-added evaluates first │ └── Synthesizer └── [post-main nodes] ← .after(engine.mainGroup) — decoders, master reverb ``` `rootGroup` is the engine's root `Group` — a doubly-linked list of child `Synthesizer` nodes evaluated in order. `mainGroup` is a persistent child of `rootGroup` and the default target for `engine.add(_:)`. Both groups are created at engine init and never freed. **Evaluation order within mainGroup:** `engine.add(_:)` uses head-insertion — the most-recently-added node evaluates first. This means if synth B depends on bus output from synth A, add B first and then A. `Group` itself conforms to `Synthesizer`, so groups can be nested to any depth. --- ## Defining a Synthesizer Subclass `SynthesizerBase` and override `build()`. Declare mutable parameters with `@LiveParam`. Register `Out.Audio` (or `Out.Control`) generators with `addOutputGenerator` — or use the shorthand helpers `output(bus:source:)` and `controlOutput(bus:source:)`. ```swift // Example — your synthesizer, defined by subclassing SynthesizerBase final class SineTone: SynthesizerBase { @LiveParam var freq: Double = 440.0 @LiveParam var amp: Double = 0.5 override func build() { let osc = OscSin.Audio(freq: $freq, phase: 0.0) output(bus: 0, source: osc * $amp) // shorthand for addOutputGenerator(Out(...)) } } ``` `build()` runs once on the **main thread** when the node is scheduled. All generator allocation happens here; the RT audio thread only calls `evaluate(graph:count:)`. --- ## Adding Nodes ### Immediately (at current sample time) ```swift let tone = SineTone() try engine.add(tone) ``` `add(_:)` is equivalent to `schedule(_:at: engine.currentTime)`. The engine reads `currentTime` via an atomic load — safe from the main thread. ### At an absolute sample time ```swift // Start tone2 at exactly sample 44100 (1 second at 44.1 kHz) let tone2 = SineTone() try engine.schedule(tone2, at: 44100) ``` The `SampleTime` value is compared to `engine.currentTime` each block. When the scheduled sample falls within the current block window, the engine adds the node mid-block via sub-block splitting, so the onset is sample-accurate. ### After a relative duration in seconds ```swift let tone3 = SineTone() try engine.schedule(tone3, after: 2.0) // 2 seconds from now ``` `schedule(_:after:)` converts the duration to a `SampleTime` delta using `engine.seconds(_:)` and adds it to the current atomic clock. Internally identical to `schedule(_:at:)`. ### How the add path works Before posting the `.add` event, the engine calls `rebuildGraph()` on `SynthesizerBase` instances (which clears then calls `build()`) on the **main thread**. The linked-list `PreparedNode` is also pre-allocated on the main thread. The RT thread in `applyEvent` only wires pointer references — no allocation on the RT thread. --- ## Removing Nodes ### Immediately ```swift engine.remove(tone) ``` ### At an absolute sample time ```swift // Remove tone2 exactly 2 seconds after it was added engine.remove(tone2, at: 44100 + engine.seconds(2.0)) ``` Removed nodes are handed to `freeQueue`, where a background drain thread releases them via ARC — the RT thread never calls `release()` directly. ### Convenience: schedule paired add and remove ```swift let note = SineTone() let startTime = engine.currentTime + engine.seconds(0.5) let stopTime = startTime + engine.seconds(1.0) try engine.schedule(note, at: startTime) engine.remove(note, at: stopTime) ``` Both events enqueue to the same `pendingQueue`. The engine processes them in target-time order within each block. --- ## Updating Parameters While Running Assign `@LiveParam` properties from the main thread at any time after the node is added. Changes cross to the RT thread via an atomic write and produce a per-sample linear ramp on the next block. ```swift tone.freq = 880.0 // no try, no string — RT-safe atomic write tone.amp = 0.3 ``` For external/REPL access by name (e.g. OSC handlers receiving the parameter name as a String), use `try synth.updateParameter("freq", value: 880.0)` — the by-name route writes the same atomic. See `docs/protocols/synthesizer.md`. --- ## Nested Groups Nesting groups controls evaluation order without needing to track individual nodes. Add a `Group` to the engine the same way you add any `Synthesizer`. ```swift let instruments = Group() let effects = Group() try engine.add(instruments) // evaluated before effects try engine.add(effects) ``` > **Evaluation order is global.** Every `Synthesizer` in `instruments` is evaluated before any `Synthesizer` in `effects`. This matters for bus routing: a node writing to a bus must appear earlier in the tree than any node reading from the same bus. --- ## Node Positioning By default `engine.add(_:)` inserts at the head of `mainGroup` (newest-first). Use the `position:` overload to control placement precisely. ### NodePosition cases | Case | Meaning | |------|---------| | `.tail(of: group)` | Append to end of `group` | | `.head(of: group)` | Prepend to front of `group` (evaluated first within that group) | | `.before(target)` | Insert immediately before `target` in whatever group contains it | | `.after(target)` | Insert immediately after `target` in whatever group contains it | ```swift let instruments = Group() try engine.add(instruments) let bass = BassSynth() try engine.add(bass, position: .tail(of: instruments)) // append let lead = LeadSynth() try engine.add(lead, position: .head(of: instruments)) // prepend — runs before bass let pad = PadSynth() try engine.add(pad, position: .after(bass)) // insert after bass ``` `.before` and `.after` search the entire node tree recursively (O(n)). If the target is not found, the node falls back to `mainGroup` head insertion. ### Global pre/post processing Use `engine.mainGroup` as a position anchor to install global processing nodes that run before or after all default-added instruments: ```swift // Evaluate before all instruments (e.g. input limiter on the live input bus) try engine.add(InputLimiter(), position: .before(engine.mainGroup)) // Default instrument — lands in mainGroup try engine.add(MySynth()) // Evaluate after all instruments (e.g. ambisonic decoder, master reverb) try engine.add(MasterReverb(), position: .after(engine.mainGroup)) ``` Multiple `.before(engine.mainGroup)` insertions are ordered so that each new pre-main node appears immediately before `mainGroup` (pushing earlier pre-main nodes further away). The same rule applies for `.after(engine.mainGroup)` insertions. --- ## Group Lifecycle — release and free Every `Synthesizer` has two lifecycle methods: ```swift try synth.release(engine: engine) // graceful: set gate → 0 (throws SynthesizerError.noGate if unsupported) synth.free(engine: engine) // immediate: remove from tree now ``` `Group` provides cascade implementations of both. ### Group.release(engine:) Releases all direct children, then self-frees when the group empties: 1. For each child: call `child.release(engine:)`. If it throws `.noGate`, call `child.free(engine:)` immediately. 2. Starts a 0.1 s repeating timer that reads `group.count` (atomically safe). When count reaches 0, calls `group.free(engine:)`. **Persistent groups** (`rootGroup` and `mainGroup`) are exceptions: `release(engine:)` still cascades to all children, but the group itself never self-frees. The groups remain attached and ready to accept new children after the cascade drains to zero. ```swift let instruments = Group() // … populate instruments with gated synths … try engine.add(instruments) // Later: gracefully release all notes and remove the group when silent. instruments.release(engine: engine) ``` ### Group.free(engine:) Immediately tears down the group and all its children — no envelope release: ```swift instruments.free(engine: engine) // On next block: all children enqueued to freeQueue, group removed from tree. ``` ### Synthesizer.release — user implementation Override `release(engine:)` in synthesizers that have an envelope gate: ```swift final class GatedNote: SynthesizerBase { @LiveParam var gate: Double = 1.0 override func build() { // … gate drives EnvelopeGen … } // Signal envelope to release (gate → 0). override func release(engine: SynthesisEngine) throws { gate = 0.0 // @LiveParam atomic write — no try needed } } ``` Or use the by-name route, which writes the same atomic on the auto-registered `@LiveParam`: ```swift override func release(engine: SynthesisEngine) throws { try updateParameter("gate", value: 0.0) } ``` --- ## Bus-Based Communication Between Nodes Nodes communicate via audio buses (`Out.Audio` / `In.Audio`) or control buses (`Out.Control` / `In.Control`). Bus writes accumulate with `+=` — multiple nodes can write to the same bus and their outputs mix. `In.Audio` and `In.Control` accept an optional `channels:` parameter to read N consecutive buses as a single N-channel generator (channel count fixed at init, no RT allocation): ```swift In.Audio(bus: 4, channels: 2) // reads audioBuses[4] and [5]; returns 2-channel output In.Control(bus: 10, channels: 2) // reads controlBuses[10] and [11]; independent ramps ``` With `BusAllocator`, pass an `AudioBus` directly and channel count is derived automatically: ```swift let stereo = try engine.busAllocator.allocateAudioBus(channelCount: 2) In.Audio(bus: stereo) // reads stereo.index and stereo.index+1 ``` ```swift // Example — DrumSynth and ReverbEffect are user-defined SynthesizerBase subclasses // Node A: writes to bus 4 (an intermediate "effects send" bus) class DrumSynth: SynthesizerBase { override func build() { let drum = WhiteNoise.Audio() * 0.8 output(bus: 0, source: drum) // dry output on bus 0 output(bus: 4, source: drum) // parallel send to bus 4 for an effect } } // Node B: reads from bus 4 and writes to the main output // Must appear AFTER DrumSynth in the tree so bus 4 is populated first. class ReverbEffect: SynthesizerBase { override func build() { let wet = input(bus: 4) // reads what DrumSynth wrote to bus 4 output(bus: 0, source: wet * 0.4) } } let drums = DrumSynth() let reverb = ReverbEffect() try engine.add(drums) // added first → evaluated first → bus 4 populated try engine.add(reverb) // added second → evaluated second → reads populated bus 4 ``` Audio buses are zeroed at the start of every block. Control buses persist across blocks. --- ## Auto-Free with EnvelopeGen When `EnvelopeGen.Audio` or `EnvelopeGen.Control` finishes and its `doneAction` is `.freeNode`, it sets an atomic flag. Poll the flag from a non-RT context (main thread, scheduling loop, or timer) and post the removal: ```swift // Example — PianoNote is a user-defined SynthesizerBase subclass class PianoNote: SynthesizerBase { let env: EnvelopeGen.Audio init() { env = EnvelopeGen.Audio( envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.3], curves: [0, 0]), doneAction: .freeNode ) } override func build() { output(bus: 0, source: env) } } let note = PianoNote() try engine.add(note) // Poll from main thread (e.g. in a display-link callback or timer): if note.env.needsFree { engine.remove(note) } ``` Do not call `engine.remove` from within the RT audio callback — that would post to `pendingQueue` from the RT thread. --- ## Polyphonic Voice Management For instruments that need multiple simultaneous notes, use `VoicePool` instead of managing individual synthesizer instances manually. The pool allocates N voices into a `Group` at init time and handles note-on/note-off assignment and steal arbitration on the main thread. ```swift let group = Group() try engine.add(group) let pool = try VoicePool( voiceCount: 8, group: group, engine: engine, stealStrategy: .oldest ) { MySynth() } let voice = pool.noteOn(note: 60) // allocates or steals voice.freq = midiToHz(60) voice.gate = 1.0 voice.gate = 0.0 pool.noteOff(note: 60) // marks voice free; gate down yourself ``` See `docs/protocols/synthesizer.md` — "Polyphonic Voice Pools" section for steal strategy reference and MIDI wiring. --- ## Thread Safety Summary | Operation | Thread | Notes | |---|---|---| | `engine.add` / `engine.schedule` | Main | `build()` and `PreparedNode` allocation happen here before enqueueing | | `engine.remove` | Main | Pre-retains the synth ref before enqueueing — no RT retain | | `tone.freq = 880.0` (`@LiveParam`) | Main | Releasing `Atomic` store; RT reads with acquiring load | | `updateParameter` (string-key) | Main | Enqueues to per-synth `SPSCQueue`; applied at next block boundary | | `engine.add(_:position:)` | Main | Like `add(_:)` — builds graph, allocates node, posts `.addNode` event | | `VoicePool` methods | Main | Language-side only; no RT involvement | | `synth.release(engine:)` | Main | Language-side only; posts parameter or remove events | | `synth.free(engine:)` | Main | Posts immediate remove / groupFree event | | `Group.addToTail` / `remove` / `addBefore` / `addAfter` | RT (audio) | Called inside `applyEvent` — no allocation, pointer wiring only | | `evaluate(graph:count:)` | RT (audio) | Never add, remove, or allocate here | The key invariant: **every mutation that allocates or retains happens before the event enters `pendingQueue`**. The RT thread only wires pointers and reads atomic values.