LyrebirdRandom scalar distribution sampling (seedable value type + shared Random) with DistributionKind.sample dispatcher. Live Scratch editor: rename to LyrebirdScratch, App Support artifact staging, Format Code (⌥⌘F), Render to File (⌥⌘R offline CAF), line-number gutter, manual completion, Foundation in snippets, scroll-jump fix, scheduling/NRT docs.
16 KiB
Temporal Demand Generators
@Metadata { @PageKind(article) }
Time-aware value generation for both the language thread (TemporalStream) and the
real-time synthesis thread (TimedDemand).
Overview
The temporal demand system generates values from statistical distributions or algorithmic walks where the distribution parameters themselves evolve over time. The elapsed time since the first value request is passed to each parameter, so a pitch tendency can start narrow and widen over 10 seconds, or a Brownian walk can gradually freeze to a still point.
There are two sides to the system with a clean interface boundary:
| Side | Types | Thread | Use when |
|---|---|---|---|
| Language | TemporalStream + TemporalTendency / TemporalBrownian / TemporalSequence … |
Background (Routine/Task) | Scheduling events: ctx.add(), @LiveParam, MIDI, OSC |
| Synthesis | TimedDemand.Audio/Control + DemandTemporalTendency / DemandTemporalBrownian |
RT audio thread | Audio-rate or control-rate S&H signal generation |
Both sides share the same DistributionKind enum and the same mathematical sampling functions.
The only difference is that the language side allows closures (TemporalParameter.closure);
the RT side restricts to .value and .envelope only (RTTemporalParameter).
Language Side — TemporalStream
TemporalParameter
The parameter type for all language-side temporal algorithms. Resolves to a Double given
elapsed time and a call counter.
// Fixed value — never changes
let fixed: TemporalParameter = .value(440.0)
// Evolves over time — read from Envelope at elapsed seconds
let rising: TemporalParameter = .envelope(
Envelope(levels: [220, 880], durations: [10.0], curves: [.lin])
)
// Computed per call — closure receives (elapsedSeconds, callCount)
let custom: TemporalParameter = .closure { elapsed, count in
220.0 * pow(2.0, elapsed / 10.0) // exponential ramp
}
Important:
.closureis language-side only. Never pass aTemporalParameter.closureto an RT generator. UseRTTemporalParameterfor synthesis-side code.
TemporalAlgorithm
The pluggable strategy protocol. All built-in algorithms conform to it:
| Type | Behaviour |
|---|---|
TemporalTendency |
Samples a statistical distribution. Parameters evolve with elapsed time. |
TemporalBrownian |
Stateful random walk within time-varying bounds. |
TemporalSequence |
Steps through a [TemporalParameter] list. Each item can be a value, envelope, or closure. |
TemporalRandomPick |
Picks uniformly from a [TemporalParameter] list on each call. |
TemporalMarkov |
Weighted Markov chain. Each state yields a value; transitions select the next state by probability. |
TemporalClosure |
(elapsed, counter, rng) -> Double — fully custom logic. |
TemporalStream
Wraps any TemporalAlgorithm and adds timing (wall-clock seconds or LyrebirdClock beats),
a PRNG seeded at construction, and an optional repeats limit.
// Wall-clock seconds — elapsed time measured in seconds since first next()
let stream = TemporalStream(
TemporalTendency(
distribution: .gauss,
parX: .value(50.0), // stddev
parY: .envelope(Envelope(levels: [220, 880], durations: [30.0])) // mean drifts
)
)
while let pitch = stream.next() {
// pitch is drawn from Gaussian(stddev=50, mean=220..880 over 30s)
}
// Beat-clock — elapsed time measured in beats of a LyrebirdClock
let clock = LyrebirdClock(engine: engine, bpm: 120.0)
let beatStream = TemporalStream(
TemporalBrownian(lo: .value(200), hi: .value(800), stepSize: .value(40)),
clock: clock
)
Calling next()
next() returns Double?. On the first call it captures the current time as t₀; subsequent
calls compute elapsed time from t₀. Returns nil when the algorithm is exhausted.
stream.reset() // resets counter, t₀, and algorithm internal state to start fresh
stream.isExhausted // true when the algorithm has returned nil
TemporalTendency (language side)
Samples any of the 16 statistical distributions. All four parameter slots accept
TemporalParameter:
// Uniform distribution, fixed bounds
let uniform = TemporalTendency(
distribution: .uniform,
parX: .value(0.0), // lo
parY: .value(1.0) // hi
)
// Gaussian pitch tendency with widening spread over time
let spreading = TemporalTendency(
distribution: .gauss,
parX: .envelope(Envelope(levels: [10, 200], durations: [20.0])), // dev widens
parY: .value(440.0) // mean stays at A4
)
// Beta distribution with closure-driven shape
let shaped = TemporalTendency(
distribution: .betaRand,
parX: .value(0.0), // lo
parY: .value(1.0), // hi
parA: .closure { _, count in Double(count % 5) + 1 }, // lowProb cycles
parB: .value(2.0)
)
Distribution parameter mapping:
| Distribution | parX | parY | parA | parB |
|---|---|---|---|---|
.uniform |
lo | hi | — | — |
.lpRand / .hpRand / .meanRand |
lo | hi | — | — |
.expRand |
lo (> 0) | hi (> 0) | — | — |
.exponential |
density | — | — | — |
.gamma |
mode | — | — | — |
.gauss |
dev | mean | — | — |
.laplace / .alaplace / .hcos / .logistic / .arcsin |
dispersion | — | — | — |
.poisson |
mean | — | — | — |
.betaRand |
lo | hi | lowProb (α) | highProb (β) |
.cauchy |
mean | spread | posOnly (> 0 = true) | — |
TemporalBrownian (language side)
Stateful random walk. Bounds and step size are TemporalParameter, so the walk can gradually
narrow its range or reduce its step size as time progresses.
// Walk starts at 440, constrained to [200, 800], step ±50
let walk = TemporalBrownian(
lo: .value(200), hi: .value(800), stepSize: .value(50)
)
// Walk converges: step shrinks from 100 to 0.1 over 30 seconds
let converging = TemporalBrownian(
lo: .value(200),
hi: .value(800),
stepSize: .envelope(Envelope(levels: [100, 0.1], durations: [30.0])),
start: 440.0 // explicit starting position; nil = auto-centre
)
TemporalSequence (language side)
Steps through a list of TemporalParameter values. Each item can evolve with time.
// Fixed pitches — classic Pattern replacement
let seq = TemporalSequence(values: [
.value(261.63),
.value(293.66),
.value(329.63),
.value(349.23)
], repeats: -1) // infinite cycle
// Pitches that drift upward over the sequence
let drifting = TemporalSequence(values: [
.envelope(Envelope(levels: [261, 440], durations: [60])),
.envelope(Envelope(levels: [293, 550], durations: [60])),
.envelope(Envelope(levels: [329, 660], durations: [60]))
])
TemporalMarkov (language side)
Weighted Markov chain. Each state holds a TemporalParameter value and a list of weighted
outgoing transitions to other states. On each next() call the chain yields the current
state's value, then selects the next state by sampling the weighted transition distribution.
// Simple three-state melody chain
let stateA = TemporalMarkov.State(
value: .value(440.0), // A4
transitions: [
.init(to: 0, weight: 1), // stay at A (weight 1)
.init(to: 1, weight: 2), // go to B (weight 2 — twice as likely)
]
)
let stateB = TemporalMarkov.State(
value: .value(550.0), // C#5
transitions: [
.init(to: 0, weight: 1),
.init(to: 2, weight: 1),
]
)
let stateC = TemporalMarkov.State(
value: .value(660.0), // E5
transitions: [
.init(to: 1, weight: 1),
.init(to: 0, weight: 1),
]
)
let markov = TemporalMarkov(states: [stateA, stateB, stateC], initialState: 0)
let stream = TemporalStream(markov, seed: 99)
let routine = LyrebirdRoutine { ctx in
while let freq = stream.next() {
let synth = MySynth(); synth.freq = freq
ctx.add(synth)
try ctx.wait(beats: 1.0)
ctx.remove(synth)
}
}
Key properties:
- Weights are relative —
[1, 2, 1]is equivalent to[0.25, 0.5, 0.25]. - Out-of-range
toindices are clamped at call time. - Cumulative weights are pre-computed at
init—next()is allocation-free. - A state with an empty
transitionsarray stays in place forever (absorbing state). - State values are
TemporalParameter— they can be.envelope(...)to evolve over time. initialStatedefaults to0; clamped to[0, stateCount-1].
// Time-varying state values — pitch rises over 30 s per state
let rising = TemporalMarkov.State(
value: .envelope(Envelope(levels: [220, 440], durations: [30.0])),
transitions: [.init(to: 1, weight: 1), .init(to: 0, weight: 1)]
)
Language-side recipe: pitch tendency in a Routine
let engine: SynthesisEngine = ...
let stream = TemporalStream(
TemporalTendency(
distribution: .gauss,
parX: .value(30.0), // stddev ±30 Hz
parY: .envelope(
Envelope(levels: [220.0, 880.0], durations: [20.0], curves: [.exp])
) // mean rises exponentially over 20 s
),
seed: 42
)
let routine = LyrebirdRoutine { ctx in
while let freq = stream.next() {
let synth = MySynth(); synth.freq = freq
ctx.add(synth)
try ctx.wait(beats: 0.5)
ctx.remove(synth)
try ctx.wait(beats: 0.1)
}
}
routine.start(engine: engine)
Synthesis Side — TimedDemand
RTTemporalParameter
The RT-safe subset of TemporalParameter. Sendable. Only .value and .envelope are allowed —
closures are absent because they must never execute on the audio render thread.
let fixed: RTTemporalParameter = .value(440.0)
let evolving: RTTemporalParameter = .envelope(
Envelope(levels: [200, 800], durations: [30.0])
)
TimedDemandGenerator
Protocol extending DemandGenerator. Concrete implementations receive elapsed seconds and a
call counter on each pull.
public protocol TimedDemandGenerator: DemandGenerator {
func nextValue(elapsedSeconds: Double, counter: Int) -> Double?
}
The nextValue() bridge (from DemandGenerator) always passes elapsed = 0, counter = 0.
Use TimedDemand.Audio/Control to get accurate timing; use bare Demand.Audio/Control only
when temporal evolution is not needed.
TimedDemand.Audio and TimedDemand.Control
Drop-in replacements for Demand.Audio/Control that pass timing context to the demand source.
- Audio: sample-accurate. Each ≤0→>0 trigger edge computes elapsed time as
(currentTime + sampleOffset - startTime) / sampleRate. - Control: one pull per audio block (first rising edge wins). Same elapsed computation applied to the sample position of the trigger within the block.
let walk = DemandTemporalBrownian(lo: .value(200), hi: .value(800), stepSize: .value(50))
// Control-rate — one new pitch per trigger
let pitchSeq = TimedDemand.Control(
trig: Impulse.Control(freq: 2), // 2 triggers per second
demand: walk
)
addOutputGenerator(Out.Audio(bus: 0, source: OscSin.Audio(freq: pitchSeq)))
Reset — send a rising edge to reset: to restart elapsed time and counter from zero:
let d = TimedDemand.Audio(trig: trigGen, reset: resetGen, demand: tendency)
DemandTemporalTendency
RT-safe demand generator sampling from any of the 16 DistributionKind variants.
Parameters are RTTemporalParameter — evolves automatically as elapsed time increases
between triggers.
// Gaussian pitch — stddev fixed, mean rises over 20 s
let tendency = DemandTemporalTendency(
distribution: .gauss,
parX: .value(30.0), // stddev
parY: .envelope(Envelope(levels: [220, 880], durations: [20.0])),
seed: 42
)
let pitchSeq = TimedDemand.Control(
trig: Impulse.Control(freq: 4),
demand: tendency
)
// Uniform pan position, range narrows over 10 s
let narrowing = DemandTemporalTendency(
distribution: .uniform,
parX: .envelope(Envelope(levels: [-1.0, -0.1], durations: [10.0])), // lo
parY: .envelope(Envelope(levels: [1.0, 0.1], durations: [10.0])) // hi
)
repeats — pass repeats: N to exhaust after N pulls; -1 (default) = infinite.
DemandTemporalBrownian
RT-safe random walk. Bounds and step size are RTTemporalParameter.
// Walk within [200, 800], step ±50 Hz, auto-starts at midpoint
let walk = DemandTemporalBrownian(lo: .value(200), hi: .value(800), stepSize: .value(50))
// Step shrinks from 100 → 1 Hz over 30 s — walk converges
let converging = DemandTemporalBrownian(
lo: .value(200),
hi: .value(800),
stepSize: .envelope(Envelope(levels: [100, 1], durations: [30.0])),
start: 440.0 // explicit start; omit to auto-centre on first pull
)
let pitchSeq = TimedDemand.Control(trig: Impulse.Control(freq: 2), demand: converging)
Inverted bounds (lo > hi) are handled gracefully — bounds are swapped internally.
Synthesis-side recipe: evolving Gaussian pitch walk
// Pitch tendency: mean drifts from 220 Hz → 880 Hz over 60 s; stddev fixed at 40 Hz
let tendency = DemandTemporalTendency(
distribution: .gauss,
parX: .value(40.0),
parY: .envelope(Envelope(levels: [220, 880], durations: [60.0], curves: [.exp])),
seed: 1234
)
// Two voices with different seeds and rates — both share one DemandTemporalTendency each
class MelodyVoice: SynthesizerBase {
override func build() {
let trig = Impulse.Control(freq: 3.0)
let pitch = TimedDemand.Control(trig: trig, demand: tendency)
let env = EnvelopeGen.Audio(
envelope: Envelope(levels: [0, 1, 0], durations: [0.05, 0.2]),
gate: trig
)
let sig = OscSin.Audio(freq: pitch) * env
addOutputGenerator(Out.Audio(bus: 0, source: sig))
}
}
Comparing Language Side and Synthesis Side
Language (TemporalStream) |
Synthesis (TimedDemand) |
|
|---|---|---|
| Thread | Background (Routine/Task) | RT audio thread |
| Elapsed time source | ContinuousClock or LyrebirdClock beats |
Engine sample counter |
| Parameter types | TemporalParameter (value/envelope/closure) |
RTTemporalParameter (value/envelope only) |
| Output use | @LiveParam, ctx.add(synth), MIDI, OSC |
ValidGeneratorInput — frequency, amplitude, etc. |
| Trigger model | stream.next() called manually |
≤0→>0 trigger signal edge |
| Exhaustion | repeats then nil |
repeats then holds last value |
| Reset | stream.reset() |
Rising edge on reset: input |
Use the language side when the value drives event scheduling — choosing which synth to instantiate, what note to play, when to remove a voice.
Use the synthesis side when the value drives a signal parameter directly — the filter cutoff, oscillator frequency, or amplitude of an already-running synthesizer.
Previewing Distributions
Both TemporalStream and the RT demand sources expose batch collection helpers for
generating preview arrays on the language side.
Collect from TemporalStream
let stream = TemporalStream(
TemporalTendency(distribution: .gauss, parX: .value(0.5), parY: .value(0.0)),
seed: 42
)
let points = stream.collect(200) // 200 Gaussian samples
LyrebirdScatterView(points).padding()
Collect from DemandTemporalTendency
let tendency = DemandTemporalTendency(distribution: .betaRand,
parX: .value(0), parY: .value(1),
parA: .value(2), parB: .value(5),
seed: 42)
let data = tendency.samples(count: 300, timespan: 0)
LyrebirdScatterView(data, pointColor: .orange)
Collect from DemandTemporalBrownian
let walk = DemandTemporalBrownian(lo: .value(-1), hi: .value(1),
stepSize: .value(0.1), seed: 1)
LyrebirdScatterView(walk.samples(count: 100), pointColor: .green)
Pass timespan: 0 to snapshot all values at elapsedSeconds = 0. Pass a non-zero
timespan to exercise time-varying envelope parameters across the sampled window.
See Also
TimedDemandDemandTemporalTendencyDemandTemporalBrownianTemporalStreamTemporalMarkovRTTemporalParameterTemporalParameterDistributionKind- doc:Noise
- doc:RandomAndJitter
- doc:RoutineTask