Files
Lyrebird/Sources/Lyrebird/Lyrebird.docc/NodeTree.md
T
josh 560724d116 v1.3.0 release: graceful-release fix, quickstart template + demo, documentation accuracy pass
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated
  synths were hard-freed instead of released).
- New: quickstart project template + LyrebirdQuickstartDemo.
- Docs: every example typechecked or provably illustrative (426->542); ~20
  wrong-API examples fixed; root docs brought under the compile guard.
- Fixed: NRT/Score demo Package.swift build from terminal again.

See RELEASES.md for details.
2026-07-17 14:05:01 -07:00

12 KiB

Node Tree and Group Actions

@Metadata { @PageKind(article) }

Add, remove, and arrange Synthesizer nodes in the SynthesisEngine signal graph.

Tree Structure

SynthesisEngine
└── rootGroup  (Group, persistent)
    ├── [pre-main nodes]        ← .before(engine.mainGroup)
    ├── mainGroup  (Group, persistent)   ← default engine.add(_:) target
    │   ├── Synthesizer         ← newest-added evaluates first
    │   └── Synthesizer
    └── [post-main nodes]       ← .after(engine.mainGroup)

rootGroup is the engine's root Group. mainGroup is a persistent child of rootGroup and the default target for engine.add(_:). Both groups are created at engine init and never freed.

engine.add(_:) uses head-insertion — the most-recently-added node evaluates first inside mainGroup. Group itself conforms to Synthesizer, so groups can be nested to any depth.

Defining a Synthesizer

Subclass SynthesizerBase and override build(). Register Out.Audio (or Out.Control) generators with addOutputGenerator — or use the shorthand helpers output(bus:source:) and controlOutput(bus:source:).

// Example — your synthesizer, defined by subclassing SynthesizerBase
final class MySynth: SynthesizerBase {
    @LiveParam var freq: Double = 440.0
    @LiveParam var amp:  Double = 0.5

    override func build() {
        let osc: OscSin.Audio = OscSin.Audio(freq: $freq, phase: 0.0)
        output(bus: 0, source: osc * $amp)
    }
}

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)

let tone: MySynth = MySynth()
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

// Start tone2 at exactly sample 44100 (1 second at 44.1 kHz)
let tone2: MySynth = MySynth()
try engine.schedule(tone2, at: 44100)

When the scheduled sample falls within the current block window, the engine adds the node mid-block via sub-block splitting, giving a sample-accurate onset.

After a relative duration in seconds

let tone3: MySynth = MySynth()
try engine.schedule(tone3, after: 2.0)   // 2 seconds from now

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

let tone: MySynth = MySynth()
try engine.add(tone)

engine.remove(tone)

At an absolute sample time

let tone2: MySynth = MySynth()
try engine.schedule(tone2, at: 44100)

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.

Schedule paired add and remove

let note: MySynth = MySynth()
let startTime: SampleTime = engine.currentTime + engine.seconds(0.5)
let stopTime: SampleTime  = startTime + engine.seconds(1.0)

try engine.schedule(note, at: startTime)
engine.remove(note,   at: stopTime)

Both events enqueue to the same pendingQueue and are sorted by target time within each block.

Updating Parameters While Running

Update from the main thread at any time after the node is added. Two equivalent routes:

final class ParamSynth: SynthesizerBase {
    @LiveParam var freq: Double = 440.0
    @LiveParam var amp:  Double = 0.5
    override func build() {
        output(bus: 0, source: OscSin.Audio(freq: $freq) * $amp)
    }
}

let engine: SynthesisEngine = SynthesisEngine(
    blockSize: 512, sampleRate: 44100, numOutputChannels: 2,
    numInputChannels: 0, driver: OfflineDriver())
let tone: ParamSynth = ParamSynth()
try engine.add(tone)

tone.freq = 880.0                              // typed direct write
try? tone.updateParameter("amp", value: 0.3)   // by-name (e.g. from OSC)

Both routes write the same atomic. The RT audio thread picks up the new value at the start of the next (sub-)block via an acquiring atomic load, then linearly ramps to it. See doc:ParameterInputs for the full mechanism (including sub-block ramping when controlBlockSize < blockSize).

Nested Groups

Nesting groups controls evaluation order without tracking individual nodes.

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

let instruments: Group = Group()
try engine.add(instruments)

let bass: MySynth = MySynth()
try engine.add(bass, position: .tail(of: instruments))   // append

let lead: MySynth = MySynth()
try engine.add(lead, position: .head(of: instruments))   // prepend — runs before bass

let pad: MySynth = MySynth()
try engine.add(pad, position: .after(bass))              // insert after bass in its group
NodePosition Behaviour
.tail(of: group) Append to end of group
.head(of: group) Prepend to front of group
.before(target) Insert before target in whatever group contains it (O(n) recursive search)
.after(target) Insert after target in whatever group contains it (O(n) recursive search)

.before and .after fall back to mainGroup head insertion if the target is not found.

Global pre/post processing

Use engine.mainGroup as a position anchor for global processing nodes:

// Run before all instruments (e.g. input limiter on live input bus)
try engine.add(MySynth(), position: .before(engine.mainGroup))

// Default instrument add — lands in mainGroup
try engine.add(MySynth())

// Run after all instruments (e.g. ambisonic decoder, master reverb)
try engine.add(MySynth(), position: .after(engine.mainGroup))

Group Lifecycle

Every Synthesizer has two lifecycle methods:

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:

Group.release(engine:)

Releases all direct children, then self-frees when the group empties:

  1. Calls release(engine:) on each child. If a child throws .noGate, calls free(engine:) on it immediately.
  2. Starts a 0.1 s polling timer that watches group.count (atomically). When count reaches 0, calls group.free(engine:).
let instruments: Group = Group()
try engine.add(instruments)
try engine.add(MySynth(), position: .tail(of: instruments))

instruments.release(engine: engine)
// All gated children begin release phase.
// When the last one finishes and is removed, instruments self-frees.

Group.free(engine:)

Immediately tears down the group and all its children — no envelope release:

let instruments: Group = Group()
try engine.add(instruments)
try engine.add(MySynth(), position: .tail(of: instruments))

instruments.free(engine: engine)
// On next block: all children enqueued to freeQueue, group removed from tree.

Group.count

group.count is backed by an Atomic<Int> and can be read safely from any thread. The release timer uses this to determine when the group is empty.

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.

// Example — DrumSynth and ReverbEffect are user-defined SynthesizerBase subclasses
// Node A: writes to bus 4 (effects send)
class DrumSynth: SynthesizerBase {
    override func build() {
        let drum = WhiteNoise.Audio() * 0.8
        output(bus: 0, source: drum)   // dry output
        output(bus: 4, source: drum)   // parallel send to bus 4
    }
}

// Node B: reads from bus 4 — must appear AFTER DrumSynth in the tree
class ReverbEffect: SynthesizerBase {
    override func build() {
        let wet = input(bus: 4)
        output(bus: 0, source: wet * 0.4)
    }
}

let drums  = DrumSynth()
let reverb = ReverbEffect()

try engine.add(drums)   // evaluated first → bus 4 populated
try engine.add(reverb)  // 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 and post the removal:

// Example — PianoNote is a user-defined SynthesizerBase subclass
final class PianoNote: SynthesizerBase {
    let env: EnvelopeGen.Audio

    override 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 = PianoNote()
try engine.add(note)

// Poll from main thread (e.g. timer or display-link callback):
if note.env.needsFree {
    engine.remove(note)
}

Do not call engine.remove from within the RT audio callback.

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.

final class Voice: SynthesizerBase {
    @LiveParam var freq: Double = 440.0
    @LiveParam var gate: Double = 0.0
    override func build() {
        output(bus: 0, source: OscSin.Audio(freq: $freq) * $gate * 0.2)
    }
}

let group: Group = Group()
try engine.add(group)

let pool: VoicePool = try VoicePool(
    voiceCount: 8, group: group, engine: engine,
    stealStrategy: .oldest
) { Voice() }

let voice: Voice = pool.noteOn(note: 60)   // allocate or steal
voice.freq = midiToHz(60)
voice.gate = 1.0

pool.noteOff(note: 60)              // mark free; gate down yourself

See doc:PolyphonicVoices for full usage, steal strategies, MIDI wiring, and routine integration.

Thread Safety Summary

Operation Thread Notes
engine.add / engine.schedule Main build() and PreparedNode allocation happen here
engine.remove Main Pre-retains the synth ref before enqueueing
updateParameter Main Enqueues to per-synth SPSCQueue; applied next block
VoicePool methods Main Language-side only; no RT involvement
Group.addToTail / remove RT (audio) Called inside applyEvent — 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.