Files
Lyrebird/Sources/Lyrebird/Lyrebird.docc/ParameterInputs.md
T
josh 24ea32e47c v2.2.0 release: live-parameter ramp origin primed at synth add
A @UIParam/@LiveParam value assigned after construction but before the first render
is now delivered flat on the first block instead of ramping from the property-
declaration default (fixes e.g. a NoiseGate restored from saved rig state latching
open and ignoring its threshold). Backed by a new internal-facing
LiveParameterValue._primeRampOrigin() (default no-op, source-compatible); live
changes after start still ramp. See RELEASES.md for the full behavior-change note.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-03 12:25:29 -08:00

14 KiB
Raw Blame History

Parameter Inputs

@Metadata { @PageKind(article) }

How to choose between @LiveParam, @UIParam, direct generator wiring, and the trigger / envelope / buffer paths when feeding values into a synthesizer.

Overview

Every value flowing into a generator is any ValidGeneratorInput. The interesting question is how the value gets there — three mechanisms cover the live-update case, plus a small handful of dedicated paths for non-Double cases (triggers, envelopes, buffers).

Default rule:

Live Double parameter from the main thread → @LiveParam. Add @UIParam instead when SwiftUI controls bind to it. Anything else → see the table below.

Decision matrix

Need Use Threading Smoothing
Double scalar mutated post-init from main thread @LiveParam atomic store per-(sub-)block linear ramp
Double scalar with a UI binding @UIParam (Lyrebird) atomic + @Observable per-(sub-)block linear ramp
Audio-rate / control-rate signal wire Generator directly RT graph per the source
Compile-time constant pass Double literal n/a none
RT→main edge event SendTrigger + TriggerListener SPSC trigger queue n/a
Envelope swap EnvelopeGen.setEnvelope(_:) (EnvelopePacket) SPSC packet queue in-place segment
Buffer / wavetable dedicated swap on holding generator atomic ref handoff n/a
NRT / offline render LyrebirdMessageContext(nrtEngine:) inline same as RT

@LiveParam

final class SineTone: SynthesizerBase {
    @LiveParam var freq: Double = 440.0
    @LiveParam var gate: Double = 1.0

    // Fixed at construction — not updateable post-init
    private let amp: Double
    private let envelope: Envelope

    init(amp: Double = 0.2, envelope: Envelope) {
        self.amp = amp
        self.envelope = envelope
        super.init()
    }

    override func build() {
        let osc = OscSin.Audio(freq: $freq)
        let env = EnvelopeGen.Control(envelope: envelope, gate: $gate, doneAction: .freeNode)
        output(bus: 0, source: osc * amp * env)
    }
}

// Envelope with a sustain hold: attack → decay → hold at 0.6 until gate closes → release
let env  = Envelope(levels: [0, 1, 0.6, 0], durations: [0.01, 0.1, 0.3], curves: [.lin, .lin, .lin], releaseNode: 2)
let tone = SineTone(amp: 0.3, envelope: env)

tone.freq = 880.0                                    // typed direct write
try? tone.updateParameter("freq", value: 880.0)      // by-name (e.g. from OSC)
// gate starts at 1.0 — envelope runs attack/decay then holds at sustain level
tone.gate = 0.0                                      // close gate — release segment runs; node frees itself when done

The projected value ($name) is a ParameterNode — a ControlGenerator backed by an Atomic<UInt64>. Wire it directly into any input that accepts any ValidGeneratorInput.

Threading model

Main thread writes are releasing atomic stores. The RT thread issues an acquiring load at the start of each (sub-)block inside _computeSamples and produces a linear ramp from the previous block's last value to the new target. No locks, no allocation, no blocking.

Auto-registration

SynthesizerBase discovers @LiveParam (and @UIParam) properties via Mirror reflection at the end of rebuildGraph(). The property name (with the leading _ of property-wrapper backing storage stripped) becomes the parameter key for updateParameter and LyrebirdMessageContext/set(_:to:on:). No declareParameter call is needed.

Auto-registration also primes each parameter's ramp origin to its current value (before the RT thread sees the node), so a value assigned between construction and the synth's first render — for example restoring saved state onto a freshly built synth — is delivered flat on the first block, not as a ramp up from the property-declaration default. Changes made after the synth is running still ramp as usual.

Block-rate vs sub-block-rate ramping

When controlBlockSize == blockSize (the engine default), the framework calls _computeSamples once per audio block, producing one ramp segment of length blockSize. When controlBlockSize < blockSize, the framework calls _computeSamples K = blockSize / controlBlockSize times per audio block, each call re-loading the atomic and producing one ramp segment of length controlBlockSize. Total work is identical in both modes; the sub-block path simply offers finer granularity for fast main-thread updates.

Limitations

  • Double only. No Int, Bool, or enum. For triggers / gates use SendTrigger; for non-numeric state, rebuild the graph.
  • Always ramps. No stepped variant. If you need an instantaneous step, pass a Double literal directly into the generator init.
  • Main-thread setter only. The RT thread must not write value. Use SendTrigger if the RT side needs to signal main.
  • One value per ParameterNode. Vector / multi-channel parameters need multiple @LiveParams or a wired-in generator.
  • No persistence. Save / restore presets externally — @LiveParam carries no serialisation hook.

Mixing @LiveParam with init-time constants

A Double passed at init becomes a fixed ConstantGeneratorInput wired permanently into the graph. Use this for values that are set once per instance and never change — oscillator base frequency, a fixed gain stage, a filter Q that belongs to the instrument design rather than live performance.

final class DetunedTone: SynthesizerBase {
    // Fixed at construction time — not updateable post-init
    private let baseFreq: Double

    // Live-updateable after construction
    @LiveParam var detune: Double = 0.0
    @LiveParam var amp:    Double = 0.2

    init(baseFreq: Double) {
        self.baseFreq = baseFreq
        super.init()
    }

    override func build() {
        // baseFreq is a Double literal in the graph — zero overhead, no ParameterNode
        // $detune is a ParameterNode — atomic load + per-block ramp
        let osc = OscSin.Audio(freq: baseFreq + $detune)
        output(bus: 0, source: osc * $amp)
    }
}

Instantiation passes the fixed value; live parameters use direct property assignment or updateParameter afterward:

let tone = DetunedTone(baseFreq: 440.0)
engine.defaultGroup.add(tone)
try engine.start()

tone.detune = 7.0     // atomic store, ramped on RT thread next block
tone.amp    = 0.4

The rule of thumb: if the value conceptually belongs to the instrument (tuning root, number of voices, buffer reference) pass it at init. If it belongs to performance (pitch bend, amplitude, filter sweep) use @LiveParam.

@UIParam

A strict superset of @LiveParam, defined in core Lyrebird; the UI controls that bind to it live in the cross-platform LyrebirdUI module (SwiftUI on Apple, SwiftOpenUI/GTK4 on Linux):

import LyrebirdSynth   // @UIParam
import LyrebirdUI      // ParameterSlider (Apple)

final class MySynth: SynthesizerBase {
    @UIParam var frequency: Double = 440.0

    override func build() {
        output(bus: 0, source: OscSin.Audio(freq: $frequency))
    }
}

ParameterSlider("Frequency", node: synth.$frequency, range: 20...20_000)
synth.frequency = 880.0     // updates atomic + triggers SwiftUI re-render

Same RT delivery as @LiveParam (per-(sub-)block ramp via UIParamNode → ParameterNode) plus an @Observable value for SwiftUI binding.

Direct generator wiring

If a value is generated on the RT side (LFO, envelope, bus read, math), there is no parameter — pass the Generator straight into the init slot:

let lfo  = OscSin.Control(freq: 5.0, mul: 10.0)        // ±10 Hz vibrato
let osc  = OscSin.Audio(freq: $freq + lfo)             // @LiveParam carrier + LFO
output(bus: 0, source: osc * $amp)

@LiveParam and direct generator wiring compose freely — the operator and + / * overloads work on any mix.

External by-name updates

LyrebirdMessageContext exposes LyrebirdMessageContext/set(_:to:on:) for OSC / MIDI handlers that receive parameter names as String:

osc.addHandler("/synth/freq") { msg, ctx in
    if let value = msg.argument(0)?.doubleValue {
        try? ctx.set("freq", to: value, on: synth)
    }
}

Internally this calls synth.updateParameter("freq", value: value), which looks up the projected ParameterNode / UIParamNode by name (Mirror-populated at build() time) and issues an atomic store.

Triggers, envelopes, buffers

These cases are not handled by @LiveParam:

  • Edge triggers / gates — use SendTrigger to detect ≤0→>0 crossings on the RT thread and post events to a TriggerListener handler. See SendTrigger.
  • Envelope swap — EnvelopeGen exposes a hot-swap path via an SPSC queue of EnvelopePacket value types. Useful for live shape changes without rebuilding the synth.
  • Buffer / wavetable swap — generators that hold a LyrebirdBuffer provide a dedicated reference setter that performs an atomic handoff.

Live source-swap

Runtime source-swap lets you replace the generator wired into a @LiveParam slot without stopping the synthesizer. The transition is sample-accurate to the next audio block boundary and never drops audio.

Motivation

Without source-swap, moving a parameter from a static scalar to an LFO requires rebuilding the entire synth — which causes an audible gap. Source-swap eliminates that gap: you assign a new generator at any time and the audio thread picks it up at the next block boundary.

final class SineTone: SynthesizerBase {
    @LiveParam var freq: Double = 440.0
    @LiveParam var amp:  Double = 0.2

    override func build() {
        output(bus: 0, source: OscSin.Audio(freq: $freq, mul: $amp))
    }
}

let tone = SineTone()
try engine.add(tone)
tone.freq = 440.0   // start at 440 Hz via scalar

// Live-swap: now driven by an LFO sweeping 340–540 Hz at 0.5 Hz
tone.$freq.source = LFSawtooth.Control(freq: 0.5, mul: 100, add: 440)

// Revert to scalar — ramps back from the LFO's last output toward 440
tone.$freq.source = nil

API surface

Three equivalent write paths:

Path When to use
synth.$freq.source = lfo Interactive use — direct projected-value access.
synth.$freq.setSource(lfo, crossfadeBlocks: 4) When a soft crossfade is needed.
synth.setSource(synth.$freq, to: lfo) Generic / programmatic code holding the ParameterNode as a variable.

All three paths are equivalent when crossfadeBlocks is 0 (the default). Prefer the first form for interactive / live-coding use.

Lifecycle of old sources

The previous source generator is released on a background thread, away from the audio thread, via the engine's parameterSourceKillQueue. This is automatic — no manual cleanup is required. The source property getter returns the last value assigned on the main thread; it is eventually consistent with the audio thread's current slot within one audio block.

Crossfade

When crossfadeBlocks > 0, the audio thread linearly mixes the old and new source outputs over the specified number of blocks before releasing the old source:

// 4-block crossfade ≈ 23 ms at 44.1 kHz / 256-sample block
tone.$freq.setSource(newLFO, crossfadeBlocks: 4)
  • crossfadeBlocks = 0 (default) — hard swap at the next block boundary.
  • A new swap issued while a crossfade is in progress immediately kills the in-progress old source and starts a fresh crossfade.
  • Maximum value: parameterNodeMaxCrossfadeBlocks (1024 blocks ≈ 6 s at a 256-sample block).

Threading rules

  • Main thread only. The source setter and setSource(_:crossfadeBlocks:) are main-thread-only. They enqueue a SourcePacket onto a per-parameter SPSC queue; the setter never blocks.
  • The audio thread drains the queue at the start of each block — no locks, no allocation.
  • Scalar writes (synth.freq = value) remain valid while a source is active. The scalar is stored atomically and resumes control once source = nil is assigned.

Limits

Limit Value Notes
Per-parameter SPSC queue capacity 4 pending swaps Overflow traps (programmer error — 4 swaps per block is already pathological).
Shared kill-queue capacity 256 old sources Overflow degrades gracefully: the dropped reference leaks one generator instance; a console warning is printed.
Maximum crossfade length parameterNodeMaxCrossfadeBlocks = 1024 blocks Enforced by precondition on the main thread.

Known limitation — source generator parameters

The source generator's own parameters (e.g. the freq of a wired LFSawtooth.Control) are fixed at construction time. They are not reachable via synth.updateParameter("freq", value:) because updateParameter targets parameters registered on synth via Mirror reflection. To change a source generator's parameters at runtime, keep a direct reference and update it through its own typed property accessor, or swap in a newly constructed source generator.

Decision tree

  1. Is the value computed on the RT thread? → wire as a Generator.
  2. Is the value a Double mutated from the main thread?
    • With SwiftUI binding → @UIParam.
    • Without → @LiveParam.
  3. Should a parameter switch dynamically between scalar and generator sources? → live source-swap.
  4. Is the value an edge / trigger event? → SendTrigger.
  5. Is the value an envelope shape? → EnvelopeGen.setEnvelope(_:).
  6. Is the value a buffer? → buffer-swap setter on the holding generator.

Topics

See also