Files
Lyrebird/Sources/Lyrebird/Lyrebird.docc/Generators/Envelopes.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

18 KiB
Raw Blame History

Envelopes

@Metadata { @PageKind(article) }

Multi-segment envelope data model and generators shipped with the Lyrebird module.


Envelope

Envelope is the data model consumed by EnvelopeGen. It is a pure value — it holds levels, durations, and curve shapes but produces no audio on its own.

// Explicit per-segment durations
Envelope(levels: [0, 1, 0.5, 0], durations: [0.01, 0.3, 0.2], curves: [-4.0, 0, -4.0])

// Equal-duration segments
Envelope(levels: [0, 1, 0], duration: 1.0, curves: [.sine, .sine])
  • levels: N+1 values — the first is the start level, each subsequent value is the target of the next segment.
  • durations and curves: N values each. Under-specified arrays are padded to exactly N in init; over-specified arrays are trimmed. The RT thread never sees an out-of-bounds index.
  • totalDuration is pre-computed at init — safe to read from any thread.
  • loopNode: optional 0-based segment index. When set and gate > 0, EnvelopeGen loops back to the start of that segment each time it finishes. When gate drops to ≤ 0, the loop exits and the envelope continues from loopNode + 1 through to completion. Must be strictly less than releaseNode − 1 when both are set (i.e. strictly before the segment whose end lands on the hold level — releaseNode is a level index, loopNode is a segment index); an invalid value is clamped to nil at init.
  • releaseNode: optional 0-based level index (SuperCollider-style — refers to an entry in levels). When set, EnvelopeGen holds at levels[releaseNode] while gate > 0. When gate drops to ≤ 0, playback resumes from segment releaseNode through the remaining segments. Valid range 1 ... levels.count - 1; out-of-range values are clamped to nil at init.
  • Gate permanent-latch: once gate goes ≤ 0, both loop and release-hold are permanently disabled for that generator instance. The envelope runs to completion even if gate later returns to > 0.

Use Envelope/valueAtTime(_:) to query the envelope shape at any time offset without advancing generator state (useful for visualisation or debugging).


EnvelopeCurve

EnvelopeCurve controls the interpolation shape of one segment. Pass named cases, numeric literals, or a mix:

// Named curves
curves: [.sine, .exponential, .welch]

// Numeric literals — parametric exponential curve
curves: [-4.0, 0, 4.0]

// Mixed
curves: [.sine, -4.0, .step]

Named Curves

Case Formula Shape Use when
.lin start + range × pos Straight ramp — same as 0 Default; constant-rate change
.exponential start × (end/start)^pos True exponential — stays near start then accelerates Perceived-loudness fades; both levels must be non-zero and the same sign — use 0.0001 as a minimum absolute level (e.g. levels: [0.0001, 1, 0.0001]); falls back to linear if either level is zero
.sine start + range × (1 − cos(π·pos)) / 2 Slow at both ends, fast in the middle Smooth attack/release with no click
.welch rising: start + range × sin(π/2·pos) / falling: × (1 − cos(π/2·pos)) Convex up when rising, concave when falling Natural-feeling bows and swells
.step end (constant) Immediately snaps to end level, holds for the segment duration Percussion gate; instant-on before a timed hold
.hold start (constant) Holds start level for the full duration, then snaps to end Sustain plateau before a release; pair with .step for gate shapes
.squared start + range × pos² Quadratic ease-in — slow start, accelerating Gentle attack build-up
.cubed start + range × pos³ Cubic ease-in — even slower start Stronger ease-in than .squared

.step vs .hold: both are "instant + hold" but from opposite ends of the segment. .step snaps to the end level immediately then holds; .hold holds the start level then snaps to end at the segment boundary. Combine them for step-and-hold patterns: curves: [.step, .hold, .lin] → jump to 1, hold for a duration, then ramp down.

Parametric Curve (numeric literal)

Formula: start + range × (1 − exp(c·pos)) / (1 − exp(c))

Value Shape Typical use
0 (or |c| < 0.001) Linear Same as .lin
c < 0 Fast start, slow end — output rises above the linear path Natural ADSR attack/decay. Typical value: −4.
c > 0 Slow start, fast end — output stays below the linear path Build-up or swell effects

The larger the magnitude, the more extreme the curve. Values in the range ±2 to ±8 cover most musical needs.

RT Performance

All curves avoid trig per sample on the RT thread:

Curve(s) RT cost per sample
.lin, numeric literal One multiply
.exponential One multiply (ratio stepping)
.sine, .welch Two multiplies + two adds (digital oscillator); one cos/sin call per segment, not per sample
.squared, .cubed, .step, .hold Pure arithmetic — one or two multiplies

EnvelopeGen.Audio / EnvelopeGen.Control

EnvelopeGen/Audio evaluates one envelope sample per output sample — use this for amplitude envelopes and any case where per-sample shape accuracy matters.

EnvelopeGen/Control advances the envelope by count samples each block (timing is identical to EnvelopeGen/Audio) and fills the output buffer with a linear ramp to the block's target level. Intra-block shape detail is lost; use Audio-rate when that matters.

let osc: OscSin.Audio = OscSin.Audio(freq: 440.0)
let env = Envelope(levels: [0, 1, 0.001], durations: [0.01, 0.5], curves: [.sine, .exponential])

// Audio-rate amplitude envelope. Constructed inside Synthesizer.build() with
// doneAction: .freeNode → self-registers with autoFreeOnDone; the engine removes
// the synth once the envelope completes. Outside build() call autoFreeOnDone(ampEnv)
// explicitly, or poll ampEnv.needsFree.
let ampEnv = EnvelopeGen.Audio(envelope: env, doneAction: .freeNode)

// Control-rate modulator (filter cutoff, pitch, etc.)
let filtEnv = EnvelopeGen.Control(envelope: env)
let filter  = RBJLowPass.Audio(input: osc, freq: filtEnv * 2000.0 + 200.0, q: 0.707)

// levelScale / levelBias: output = level × scale + bias
let scaledEnv = EnvelopeGen.Audio(envelope: env,
                                  levelScale: 2.0 as Double,
                                  levelBias:  -1.0 as Double)

// timeScale: stretches each segment's duration. Same shape, twice as long.
let slowEnv = EnvelopeGen.Audio(envelope: env, timeScale: 2.0 as Double)
_ = (ampEnv, filter, scaledEnv, slowEnv)

Parameters:

  • envelope — the Envelope value describing levels, durations, and curves.
  • levelScale — multiplied into every output sample (default 1.0). Any ValidGeneratorInput.
  • levelBias — added after scale (default 0.0). Any ValidGeneratorInput.
  • timeScale — multiplies each segment's duration before sample-count conversion (default 1.0). Any ValidGeneratorInput. Read once per block; applied at the next segment entry, so the segment currently in progress is not re-timed mid-flight. Negative values clamp to 0 (snaps the affected segment to its end level).
  • doneAction — action taken when the last segment completes (see table below).

Gate parameter (gate):

Pass any ValidGeneratorInput at init (default 1.0). The gate is read once per block (block-constant) — changes take effect on the next block boundary. Pass a ParameterNode backed by a @LiveParam to change it at runtime from a Synthesizer.

Gate interacts with two optional Envelope fields:

  • releaseNode — level index (SuperCollider-style). The generator holds at levels[releaseNode] while gate > 0. When gate drops to ≤ 0, playback resumes from segment releaseNode through the remaining segments.
  • loopNode — when the generator finishes that segment, it jumps back to its start and replays it while gate > 0. When gate drops to ≤ 0, the loop exits and playback continues through the remaining segments.

Permanent-latch rule: once gate goes ≤ 0, both the loop and the release-hold are permanently bypassed for the lifetime of that generator instance. The envelope runs to completion even if gate later returns to > 0. This prevents retriggering from floating-point noise or re-use of a gate signal.

Pass a ParameterNode ($liveparam) to control gate at runtime from a Synthesizer:

final class MySynth: SynthesizerBase {
    @LiveParam var gate: Double = 1.0   // held open by default

    override func build() {
        let adsr = Envelope(
            levels:      [0, 1, 0.7, 0],
            durations:   [0.01, 0.1, 0.5],
            curves:      [.sine, -4.0, -4.0],
            releaseNode: 2                     // hold at sustain (0.7) after decay
        )
        let envGen = EnvelopeGen.Audio(envelope: adsr, gate: $gate, doneAction: .freeNode)
        output(bus: 0, source: envGen * osc)
    }
}

synth.gate = 0.0  // RT-safe — releases envelope on next block

Done actions:

Value Behaviour
.nothing Freeze at final level
.freeNode Freeze and set needsFree = true
.loop Restart from the beginning

needsFree uses a releasing atomic store on the RT thread and an acquiring load on the public accessor. Read it from a non-RT context (main thread or scheduling loop) after processBlock returns — never act on it from inside the RT callback.


Common Patterns

ADSR with gate

// Attack (seg 0), Decay (seg 1), Release (seg 2).
// releaseNode=2 (level index — levels[2]=0.7) → holds at sustain level until gate drops.
// Pass a ParameterNode from a @LiveParam so the gate can be updated at runtime.
let adsr = Envelope(
    levels:      [0, 1, 0.7, 0],
    durations:   [0.01, 0.1, 0.5],
    curves:      [.sine, -4.0, -4.0],
    releaseNode: 2
)
// Constant gate — holds at sustain, never releases (useful as a one-shot trigger):
let envGen = EnvelopeGen.Audio(envelope: adsr, gate: 1.0 as Double, doneAction: .freeNode)

// Or wire a @LiveParam for runtime release:
// let envGen = EnvelopeGen.Audio(envelope: adsr, gate: $gate, doneAction: .freeNode)
// synth.gate = 0.0  // triggers release

ADSR with looping sustain

// Attack (seg 0), SustainLoop (seg 1), Release (seg 2).
// loopNode=1: loops seg 1 while gate > 0.
// releaseNode=3 (level index — levels[3]=0): the hold landing point is the final
//   level. Since gate=0 also triggered the loop exit, the hold is bypassed entirely
//   and seg 2 plays straight through to completion.
let adsr = Envelope(
    levels:      [0, 1, 0.8, 0],
    durations:   [0.01, 0.2, 0.4],
    curves:      [.sine, .sine, -4.0],
    loopNode:    1,
    releaseNode: 3
)
// synth.gate = 1.0 → loops seg 1 (sustain shape)
// synth.gate = 0.0 → exits loop, plays release, done

ADSR without gate (static shape)

// Attack: sinusoidal in, Decay: fast-start parametric, Sustain: hold, Release: exp
let adsr = Envelope(
    levels:    [0,    1,    0.7,   0.7,  0],
    durations: [0.01, 0.1,  0.0,   0.4,  0.2],
    curves:    [.sine, -4.0, .step, .hold, .exponential]
)

Step and hold

// Jump immediately to 1, hold for 0.5 s, then linear release
let gate = Envelope(levels: [0, 1, 1, 0], durations: [0, 0.5, 0.2], curves: [.step, .hold, .lin])

Looping LFO shape

let lfo = Envelope(levels: [0, 1, 0], duration: 2.0, curves: [.sine, .sine])
let gen = EnvelopeGen.Audio(envelope: lfo, doneAction: .loop)

EnvelopePoll.Audio / EnvelopePoll.Control

EnvelopePoll/Audio and EnvelopePoll/Control evaluate the envelope shape at an arbitrary time value without advancing any playback state. loopNode and releaseNode are ignored — the lookup is stateless and purely based on the time input.

Use this when you want to map a time signal to an envelope shape rather than play it:

  • Driving with a Phasor for a continuously looping shape (without doneAction: .loop)
  • Scrubbing the envelope position at control rate for LFO-style modulation
  • Querying the same Envelope from multiple generators independently
// Audio-rate scrub: Phasor drives time across the full envelope duration
let env  = Envelope(levels: [0, 1, 0], durations: [0.5, 0.5], curves: [.sine, .sine])
let t    = Phasor.Audio(freq: 1.0) * env.totalDuration   // 0…1 s per cycle
let poll = EnvelopePoll.Audio(envelope: env, time: t)

// Control-rate filter sweep shaped by an envelope
let cutoff = EnvelopePoll.Control(
    envelope: Envelope(levels: [200, 2000, 200], durations: [1.0, 1.0], curves: [.sine, .sine]),
    time: Line.Control(start: 0, end: 2.0, dur: 2.0)
)
let filt = RBJLowPass.Audio(input: osc, freq: cutoff, q: 0.707)

Time input resolution:

  • EnvelopePoll.Audio — if time is an AudioGenerator, valueAtTime is called per sample using that generator's output buffer. Scalar, ControlGenerator, or Closure inputs are block-constant (evaluated once per block).
  • EnvelopePoll.Control — time is always read once per block via floatValue; the output ramps linearly from the previous block's value to the current lookup result.

RT note: when time is audio-rate, curves .sine, .welch, .exponential, and parametric .custom call trig / exp once per sample on the RT thread. This is the unavoidable cost of random-access lookup. With block-constant time, all curves evaluate at most once per block regardless of type.

Parameters (same as EnvelopeGen):

  • envelope — the Envelope value to query.
  • time — any ValidGeneratorInput; audio-rate inputs trigger per-sample dispatch.
  • levelScale / levelBias — applied after lookup: output = valueAtTime(t) × scale + bias.

Runtime Envelope Swap

Both EnvelopeGen and EnvelopePoll support swapping the Envelope after construction via setEnvelope(_:). Call this on the main thread at any time — the new shape is delivered to the RT thread lock-free and takes effect at the start of the next audio block.

// Create a synth with an initial envelope
let initial = Envelope(levels: [0, 1, 0], durations: [0.01, 0.5], curves: [.sine, .exponential])
let envGen  = EnvelopeGen.Audio(envelope: initial, doneAction: .freeNode)

// Later — from the main thread, swap to a new shape without restarting the synth
let brighter = Envelope(levels: [0, 1, 0], durations: [0.005, 0.2], curves: [.sine, -4.0])
envGen.setEnvelope(brighter)

Playback state on swap: currentSegment and samplePos are preserved (in-place semantics). If the new envelope has fewer segments than currentSegment, the generator clamps to the last available segment and resets samplePos to 0. The _released latch is not cleared — if the gate has already been released, the new envelope still runs to completion without re-arming loop or hold.

// EnvelopePoll: same API, no playback state involved
let poll = EnvelopePoll.Audio(envelope: initial, time: phasor)
poll.setEnvelope(brighter)   // takes effect next block

Segment limit: setEnvelope accepts envelopes with up to EnvelopePacket.maxSegments (32) segments. Envelopes with more segments cannot be set at runtime; use a new synthesizer node instead.


Single-segment ramps: Line, ExponentialLine, RateRamp

Three lightweight Control-rate ramp generators for the common case of a single straight or geometric ramp. Faster to type and read than a two-level Envelope, and equivalent under the hood to the corresponding EnvelopeGen.Control configuration.

Line.Control

Linear ramp from start to end over dur seconds. Reaches end at the last sample of the block that crosses dur, then dispatches doneAction.

let fade = Line.Control(start: 1.0, end: 0.0, dur: 2.0, doneAction: .freeNode)
let osc  = OscSin.Audio(freq: 440.0) * fade
// After processBlock: if fade.needsFree { engine.remove(synth) }

ExponentialLine.Control

Exponential (geometric) ramp — interpolated in log space so the perceived rate of change is constant. Init traps if start and end cross zero or either is zero — there is no zero-crossing path in log space.

let pitch = ExponentialLine.Control(start: 100.0, end: 1000.0, dur: 1.0)
let osc   = OscSin.Audio(freq: pitch)

For a fade through silence, use Line/Control (linear) or an EnvelopeGen with a .exponential curve and a non-zero floor (e.g. 0.0001).

RateRamp.Control

Open-ended accumulator — initialises to start and grows by rate units per second indefinitely. A ≤0 → >0 rising edge on trigger resets the accumulator to the current value of start. There is no done action; the generator runs for the lifetime of its node.

rate is sampled once per audio block (block-constant; reads through any ParameterNode ramp endpoint). start is sampled at the first audio block (to seed the accumulator) and at every trigger edge — modulating it between edges has no effect on output.

// Saw-style ramp at 1 Hz, reset by an audible trigger.
let trig = Impulse.Control(freq: 1.0)
let ramp = RateRamp.Control(trigger: trig, rate: 1.0)
let cutoff = ramp * 1000.0 + 200.0

Modelled on SuperCollider's Sweep UGen, with an added modulatable start value.

Done actions (Line / ExponentialLine)

Same DoneAction enum used by EnvelopeGen. RateRamp/Control does not accept a done action — it is open-ended by design.

Value Behaviour
.nothing Freeze at end
.freeNode Freeze at end and set needsFree = true
.loop Reset and run from start again — discontinuous restart at the block boundary