Files
Lyrebird/docs/tooling/routine-task.md
T

24 KiB
Raw Blame History

LyrebirdRoutine, LyrebirdTask, and Pattern

Algorithmic event scheduling on background threads. Non-RT — drives high-level events (add/remove synths, change @LiveParam values) from sequential code with timed waits.


Pattern<T>

Demand-rate value sequence. Not thread-safe; use within a single Routine/Task.

let freqs = Pattern.sequence([440.0, 550.0, 880.0], repeats: 2)
while let f = freqs.next() { ... }   // iterates twice, then next() returns nil
freqs.reset()                         // restart from beginning
Property/Method Description
next() -> T? Return current value and advance. nil when exhausted or values is empty.
reset() Restart from first value; clear cycle count.
isExhausted true after repeats full cycles. Always false when repeats == -1.

repeats: -1 (default) = infinite loop.

Pattern Factory Reference

All variants below are constructed by static factory methods on Pattern<T>. Every variant returns a Pattern<T> (or Pattern<[T]> for tuple) backed by a module-internal engine. next() / reset() / isExhausted behave uniformly. Numeric factories require T == Double and live on extension Pattern where T == Double; the rest are generic.

Atomic value sources — generic T

Factory Behaviour
Pattern.sequence(_:repeats:offset:) Cycle through array repeats times. -1 infinite. offset shifts only the first pass — emission opens at values[offset] (wraps modulo count) and runs to the array end, then later cycles run full from index 0.
Pattern.shuffle(_:repeats:seed:) Fisher-Yates permute once at init, then cycle. Same permutation replays on reset. (SC Pshuf)
Pattern.nonRepeatingRandom(_:repeats:seed:) Random pick avoiding same index as previous. Documented index-vs-value caveat for duplicate-value pools. (SC Pxrand)
Pattern.weightedRandom(_:weights:repeats:seed:) Pick proportional to weight. Init preconditions: equal count, finite non-negative weights, positive sum. (SC Pwrand)
Pattern.closure(_:) Wrap () -> T?. Latches once nil is returned. Reset clears latch but cannot reset closure-internal state. (SC Pfunc)

Atomic value sources — numeric Pattern<Double>

Factory Behaviour
Pattern.series(start:step:length:) Arithmetic series. length == -1 infinite. (SC Pseries)
Pattern.geometric(start:ratio:length:) Geometric series. (SC Pgeom)
Pattern.uniformRandom(low:high:length:seed:) Uniform random in [low, high]. (SC Pwhite)
Pattern.brownian(low:high:step:start:length:seed:) Clamped random walk. start defaults to midpoint. (SC Pbrown)
Pattern.gaussian(mean:stdDev:length:seed:) Gaussian (Box-Muller). (SC Pgauss)
Pattern.cauchy(location:scale:length:seed:) Cauchy (inverse-CDF). (SC Pcauchy)
Pattern.beta(alpha:beta:length:seed:) Beta(α, β) in [0, 1] (two-Gamma). (SC Pbeta)

Length / range modifiers — generic T, wrap any Pattern<T>

Factory Behaviour
Pattern.repeating(_:count:) Replay upstream count times with reset() between cycles. -1 infinite. (SC Pn)
Pattern.limit(_:count:) Emit at most count items returned. count >= 0 precondition. (SC Pfin)
Pattern.drop(_:count:) Skip first count upstream values lazily. count >= 0 precondition. (SC Pdrop)
Pattern.stutter(_:count:) For each upstream value, emit n times where n is the next value from a Pattern<Int>. (SC Pstutter)

Multi-pattern composition — generic T

Factory Behaviour
Pattern.switching(_:index:) One value per index draw; out-of-range index latches. (SC Pswitch1)
Pattern.concatenate(_:) Sequential play; advance when active sub-pattern returns nil.
Pattern.roundRobin(_:) One value per pattern in rotation; dead slots skipped. (SC Ppatlace)
Pattern.tuple(_:) Returns Pattern<[T]>. Zips children into size-stable arrays. Latches on any child nil.
Pattern.interleave(_:repeats:) SC Place. Each outer cycle emits one value per sub-list; shorter sub-lists wrap modulo own length. Empty sub-lists silently dropped. repeats == -1 infinite.

Map / filter / reject — generic T

Factory Behaviour
Pattern.map(_:_:) Wraps Pattern<U> with (U) -> T transform. Result element type can differ. (SC Pcollect)
Pattern.filter(_:where:) Keep upstream values where predicate is true. Spin caveat for never-matching infinite source. (SC Pselect)
Pattern.reject(_:where:) Inverse of filter. Routes the same engine with a negated predicate. (SC Preject)

Numeric transforms — Pattern<Double>

Factory Behaviour
Pattern.accumulate(_:initial:) Running sum from initial. (SC Paccum)
Pattern.difference(_:) First value verbatim, subsequent = x[n] - x[n-1]. (SC Pdiff)
Pattern.wrap(_:low:high:) Wrap into half-open [low, high) via floor-modulo with FP-boundary post-clamp. Precondition high > low. (SC Pwrap)
Pattern.clip(_:low:high:) Clamp to [low, high]. Precondition high >= low. (SC Pclip)
Pattern.round(_:step:) Round to nearest multiple of step, ties away from zero. Precondition step > 0. (SC Pround)
Pattern.smooth(_:coefficient:) One-pole exponential smoother y[n] = c·y[n-1] + (1-c)·x[n]. Coefficient clamped to [0, 1]. First sample passes through. (SC Psmooth)

Composition example

// Repeat (cycle through a switch of two sub-patterns picked by an index pattern) 4 times.
let composite: Pattern<Double> = Pattern.repeating(
    Pattern.switching(
        [Pattern.series(start: 0, step: 1, length: 4),
         Pattern.uniformRandom(low: 0, high: 1, length: 4)],
        index: Pattern.sequence([0, 1, 0, 1])
    ),
    count: 4
)

The same factories on the demand side are implemented as separate DemandGenerator types (DemandSeries, DemandShuffle, DemandSwitch, etc.) wrapping the matching Pattern engines — see docs/stdlib/generators.md § Demand-rate.


EventPattern — event-driven playback

EventPattern is the heart of Lyrebird's event-driven playback: it binds named value Patterns to a voice's parameters and plays them as a timed stream of voices. Each event pulls one value from every bound pattern plus the duration pattern, makes a fresh voice, writes the pulled values into its parameters, adds it to the engine, and reaps it (see Lifecycle below) — then waits the event's duration before the next event.

final class PluckVoice: SynthesizerBase, EventSustainAware {
    @LiveParam var freq: Double = 440.0
    @LiveParam var amp:  Double = 0.2
    private var sustainSeconds: Double = 1.0

    func setEventSustain(seconds: Double) { sustainSeconds = seconds }

    override func build() {
        // An envelope sized to `sustainSeconds` that frees the voice when it finishes
        // (`.freeNode` → SynthesizerBase auto-frees when the envelope completes).
        let env: EnvelopeGen.Audio = EnvelopeGen.Audio(
            envelope: Envelope(levels: [0, 1, 0], durations: [0.01, sustainSeconds], curves: [0, 0]),
            doneAction: .freeNode
        )
        output(bus: 0, source: OscSin.Audio(freq: $freq) * $amp * env)
    }
}

let handle: EventPatternHandle = EventPattern(make: { PluckVoice() })
    .bind(\.freq, .sequence([440.0, 550.0, 660.0]))
    .bind(\.amp,  .uniformRandom(low: 0.1, high: 0.4))
    .dur(.sequence([0.25, 0.25, 0.5]))
    .legato(0.9)
    .tempo(132.0)
    .play(on: engine)

Design

  • Typed binding, not an event dictionary. A binding is a ReferenceWritableKeyPath into a concrete voice type (\.freq), checked at compile time. There is no untyped event dictionary.
  • No default-event prototype. There is no name-to-name conversion chain (degree → note → freq, dB → amp) and no sustain/legato prototype math. The voice owns its envelope; the pattern owns timing. Pass the values you actually want in the units the voice expects.
  • Binding key paths must be formed on the main actor (a @LiveParam is main-actor-isolated). Ordinary setup code already runs there; this only matters for off-main test code.

Lifecycle

Per event (in beats): delta is pulled from the dur pattern, sustain = delta * legato. The voice is added, then reaped by one of three paths:

  • EventGated — the voice exposes its gate @LiveParam as eventGate. The pattern opens the gate on add (default the parameter open so the attack fires) and schedules a note-off (gate → 0) sustain beats later, via a non-blocking, overlap-safe ctx.set(_:to:afterBeats:) — a legato above 1.0 overlaps successive voices. The voice's gated EnvelopeGen (releaseNode + doneAction: .freeNode) plays its release and frees itself. The pattern never hard-removes it.
  • EventSustainAware — the voice is handed sustain in seconds just before being added, so it shapes a fixed-duration self-freeing envelope. Also never hard-removed.
  • Plain (neither protocol) — the voice is scheduled for removal sustain + releaseTail beats later (ctx.remove(afterBeats:)). This is the only path releaseTail affects.

The stream ends when the dur pattern or any bound pattern is exhausted; .repeats(n) replays the whole bound set n times (resetting the patterns between). On stop(), outstanding gate note-offs are fired immediately so gated voices release and self-free rather than hanging open.

Monophonic and parallel

  • MonoEventPattern reuses a single persistent voice: one voice is made and added once, its parameters updated per event, and torn down when the stream ends or when the handle is stopped. A voice conforming to EventRetriggerable is re-struck (retrigger()) on every event after the first — per-event articulation; a voice that does not conform plays continuously with its parameters gliding per event. When the voice is also EventSustainAware, its sustain is set before each retrigger(). An EventGated voice is held open across the whole stream and note-off'd once at teardown (gate → 0, release plays, self-frees); a non-gated voice is removed after releaseTail beats.
  • ParallelEventPattern plays several patterns at once: it holds any mix of EventPattern and MonoEventPattern children (EventPatternPlayable) and starts each on its own task back to back. The children share no common clock — same-tempo children begin within thread-start latency of each other and are not re-synchronised afterwards (small drift can accumulate over long runs); different tempos run polytemporally. add(_:) adds a child that enters with the group; addAfter(beats:eventPattern:) staggers a child's entry a fixed number of beats into the group's start grid (the child simply waits that lead-in before its first event). It returns one EventPatternHandle whose stop() stops every child and whose waitUntilComplete(releasePadding:) returns once all finite children finish. The group is a fire-once start: compose every child before play. For live, beat-quantised insertion after playback has begun (a UI button, an OSC or MIDI callback), use EventConductor instead — see below.

EventConductor — live, clock-driven ensemble

ParallelEventPattern composes its children up front and fires once. EventConductor keeps a background clock running and lets you push patterns in while it plays, from any thread:

let conductor = EventConductor(tempo: 128.0)
conductor.start(on: engine)
let drumsPart = conductor.add(drums, quantize: .now)       // start the groove now
// … later, from a GUI button / OSC / MIDI callback, on any thread …
let bassPart = conductor.add(bass, quantize: .nextMultiple(ofBeats: 4))   // drops in on the next bar
// … later still …
bassPart.stop()                                            // stops the bass alone; the drums play on
  • add(_:quantize:) is thread-safe — call it from a UI, OSC or MIDI handler on any thread. It enqueues under a lock and returns an EventConductorHandle at once; the conductor's own task drains the queue each poll (~10 ms) and starts due patterns on the main thread (voice construction is main-actor-isolated). Defaults to .nextBeat.
  • The returned EventConductorHandle stops one part: stop() cancels it if still pending (no voice is built) or stops it if already playing (its gated voices release), leaving the other parts running. isPlaying reports pending-or-playing. This is the per-part counterpart to the conductor's own stop(), which stops everything. Perfect for a toggle button per part.
  • EventQuantum names the entry boundary: .now, .nextBeat, .nextMultiple(ofBeats:) (the next bar/grid line), .atBeat(_:) (absolute), .afterBeats(_:) (a relative lead-in, the direct analogue of ParallelEventPattern.addAfter).
  • The clock quantises only each pattern's entry. A resolved pattern is held until the conductor's clock reaches its target beat, then started — so entry aligns to the conductor's grid within the poll granularity (~10 ms), independent of the pattern's own tempo. Once started, a pattern runs its own relative wait(beats:) chain at its own tempo — exactly as under EventPattern/ParallelEventPattern — so patterns can be polytempo, and the conductor does not re-align their individual events afterwards.
  • stop() halts the clock and every pattern it started (idempotent; further add is ignored). isRunning, hasActiveChildren, and currentBeat are thread-safe reads. For finite content, waitUntilIdle(releasePadding:) blocks until nothing is pending and no child is still playing, then waits out the release tails — add the patterns, waitUntilIdle, then stop().

Playback runs on a background LyrebirdTask; voice construction and parameter writes hop to the main thread. The returned EventPatternHandle has stop(), isPlaying, and waitUntilComplete(releasePadding:) — the latter blocks until every finite pattern finishes, then waits an extra releasePadding seconds so the last voices' envelope release tails ring out before a caller (a CLI demo, an offline render) tears the engine down. A long-lived app keeps the engine running and leaves releasePadding at its 0 default.


LyrebirdRoutine

Runs a closure once on a dedicated background thread (Thread, .userInitiated QoS).

let routine = LyrebirdRoutine { ctx in
    let freqs = Pattern.sequence([440.0, 550.0, 660.0])
    while let freq = freqs.next() {
        let tone = SineTone(); tone.freq = freq
        ctx.add(tone)
        try ctx.wait(seconds: 0.5)
        ctx.remove(tone)
        try ctx.wait(seconds: 0.1)
    }
}
routine.start(engine: engine)
// ... later:
routine.stop()

States

idle → (start) → running → (body returns / stop) → stopped
stopped → (reset) → idle

API

Method Description
start(engine:) Launch background thread. No-op if not .idle.
stop() Signal stop. Next ctx.wait() throws LyrebirdRoutineError.stopped.
reset() Signal stop and block until thread finishes. Resets to .idle for restart.

LyrebirdTask

Like LyrebirdRoutine with pause() / resume(). Identical body signature.

let task = LyrebirdTask { ctx in
    while true {
        ctx.add(nextEvent())
        try ctx.wait(seconds: 0.25)
    }
}
task.start(engine: engine)
task.pause()    // freeze; thread sleeps inside ctx.wait()
task.resume()   // continue from where it left off
task.stop()

States

idle → running → paused → running → stopped
Method Description
pause() Suspend inside next ctx.wait(). Sets state .paused.
resume() Broadcast on internal condition; resumes ctx.wait(). Sets state .running.
stop() / reset() Same as LyrebirdRoutine.

LyrebirdRoutineContext

Passed to the body closure. Provides:

Timed waits

try ctx.wait(seconds: 0.5)            // sleep ~0.5s; polls stop/pause every 10ms
try ctx.waitUntil(sampleTime: t)      // block until engine.currentTime >= t

Both throw LyrebirdRoutineError.stopped when stop() is called. Let the error propagate or catch and rethrow to unwind cleanly.

Engine calls

All dispatched to the main thread via DispatchQueue.main.async to preserve the pendingQueue single-producer invariant.

ctx.add(synth)
ctx.schedule(synth, at: sampleTime)
ctx.schedule(synth, after: 2.0)       // seconds
ctx.remove(synth)
ctx.remove(synth, at: sampleTime)

Live parameters

Change a running synth's @LiveParam from the body. Unlike the engine calls above, a ParameterNode write goes straight to its lock-free atomic — no main-thread hop — so it runs inline on the routine's own thread; the RT thread picks it up at the next block.

@UIParam (UIParamNode) is not a valid target: its value is @Observable-tracked and main-thread-only, so it can't be written from the routine's background thread. ctx.set / ctx.ramp take a ParameterNode; update @UIParam from the main thread.

ctx.set(param, to: 8.0)                 // step: jump to a value
try ctx.ramp(param, to: 0.5, seconds: 3)  // glide: smooth sweep over 3 s, then continue
try ctx.ramp(param, to: 0.5, beats: 2)    // same, in beats at the current tempo

ctx.ramp blocks the body for its duration — like wait — and lands exactly on the target. It steps the scalar at the 10 ms poll granularity; the ParameterNode's own per-block linear interpolation blends the steps into a continuous glide on the RT thread (no node source is installed, so a later ctx.set still takes effect immediately).

param is the projected node, captured on the main actor first. The synth is @MainActor-isolated, so its @LiveParam property and $-projection can't be reached from the background body. Capture the (Sendable) node once at setup, then drive it from the body — this is the idiomatic Swift-6 shape:

// runDemo() / setup — @MainActor context
let reverbSynth = GVerbTest(sampleRate: sr)
let reverbTime  = reverbSynth.$reverbTime        // ParameterNode — Sendable, captured once

LyrebirdTask.run(engine: engine) { ctx in         // @Sendable body — background thread
    ctx.add(reverbSynth)
    try ctx.wait(beats: 2)
    ctx.set(reverbTime, to: 8.0)                  // long tail
    try ctx.ramp(reverbTime, to: 0.5, beats: 2)   // then glide down
    ctx.remove(reverbSynth)
}

The background thread is the point: the body is sequential, blocking code — add → wait → set → ramp → remove reads top-to-bottom like a score — while the audio and the main thread run undisturbed. wait/ramp sleep this thread, never the RT thread.

No-capture alternative. A synth that is driven mostly from routines can skip @LiveParam and expose the node directly as a nonisolated let ParameterNode, which is reachable from the background with no capture — trading the plain-Double value sugar and the $-projection:

@MainActor final class GVerbTest: SynthesizerBase {
    nonisolated let reverbTime = ParameterNode(3.0)
    override func build() { output(bus: 0, source: GVerb.Audio(/* … */, reverbTime: reverbTime)) }
}
// then, straight from the body — no capture line:
ctx.set(reverbSynth.reverbTime, to: 8.0)

Error handling

let routine = LyrebirdRoutine { ctx in
    do {
        while true {
            try ctx.wait(seconds: 0.25)
            // ... produce events ...
        }
    } catch LyrebirdRoutineError.stopped {
        // cleanup if needed
    }
    // body returns → state = .stopped
}

Uncaught LyrebirdRoutineError.stopped is silently swallowed by the Routine/Task harness — it always signals a clean stop, not a crash.


Thread model

  • One Thread per Routine/Task. Thread is created on start(), destroyed when body returns.
  • stop() is non-blocking. reset() blocks the calling thread until the body exits.
  • Do not call reset() from inside the body closure.
  • Multiple routines run concurrently and independently.

Actor isolation

The body is @Sendable and runs off the main thread; SynthesizerBase is @MainActor. So:

To do this from a body Use Cost
Construct a synth ctx.onMain { MySynth(...) } Synchronous main hop — absorbed by wait's drift compensation. Keep it short; needs a serviced main thread (see below).
Add / schedule / remove ctx.add / ctx.schedule / ctx.remove Async hop to main (build() runs there)
Change a parameter ctx.set(node, to:) with $param captured on main None — lock-free atomic write, inline on the body's thread

Direct property writes (synth.freq = 880) and projected-node access (synth.$freq) are main-isolated and unavailable from a body — capture the node on main first.

ctx.onMain is what lets the number and parameters of synths depend on the body's own logic, instead of pre-allocating every synth outside the body and capturing it.

ctx.onMain requires a serviced main thread. It hops synchronously with no timeout, so it blocks the body forever if nothing drains the main queue. A GUI run loop services it, as does a caller parked on waitUntilComplete() / LyrebirdTask.run (both pump the main run loop for exactly this reason). The trap: task.start(engine:) followed by blocking main on a bare Thread.sleep or semaphore — ctx.add would silently queue, but onMain hangs.

Full model — what is main-bound and why, pre- vs post-publication, and why SynthesizerBase.init cannot simply be made nonisolated (a committed regression fixture enforces it) — is in ARCHITECTURE.md §9.2.


LyrebirdClock

Named shared clock that multiple routines and tasks can align to without per-routine drift.

The drift problem

Two routines calling ctx.wait(beats: 1) in independent loops accumulate OS scheduler jitter independently and drift apart within seconds. ctx.waitUntil(sampleTime:) on a shared sample-time grid never drifts.

// WRONG — drifts
let a = LyrebirdRoutine { ctx in
    while true { ctx.add(Kick()); try ctx.wait(beats: 1) }
}
let b = LyrebirdRoutine { ctx in
    while true { ctx.add(Bass()); try ctx.wait(beats: 1) }
}

// RIGHT — locked to same grid
let clock = LyrebirdClock(engine: engine, bpm: 120.0)
let a = LyrebirdRoutine { ctx in
    while true {
        try ctx.waitUntil(sampleTime: clock.nextBeat())
        ctx.add(Kick())
    }
}
let b = LyrebirdRoutine { ctx in
    while true {
        try ctx.waitUntil(sampleTime: clock.nextBeat())
        ctx.add(Bass())
    }
}

API

let clock = LyrebirdClock(engine: engine, bpm: 120.0)
Property / Method Type Description
epoch SampleTime Engine sample time at clock creation.
bpm Double (get/set) Tempo. Setter accumulates beats elapsed before the change — beat count is continuous.
currentBeat Double Beats elapsed since epoch, accumulated across tempo changes.
sampleTime(beat:) SampleTime Convert beat number → sample time. May return a past sample time.
nextBeat(after:) SampleTime Sample time of the next whole beat after beat (or currentBeat if nil). Exclusive: nextBeat(after: 4.0) returns beat 5.

Tempo changes

// Beat count is continuous across bpm changes
clock.bpm = 90.0   // _beatOffset accumulates beats since last change

sampleTime(beat:) is only accurate within the current tempo segment — beats since the last bpm change. Past-segment queries return mathematically extrapolated values, not a reconstruction of the prior tempo.

Multi-voice example

let clock = LyrebirdClock(engine: engine, bpm: 120.0)

// Kick on every beat
let kick = LyrebirdRoutine { ctx in
    while true {
        try ctx.waitUntil(sampleTime: clock.nextBeat())
        ctx.add(KickDrum())
    }
}

// Bass on every other beat (offset by 0.5)
let bass = LyrebirdRoutine { ctx in
    while true {
        try ctx.waitUntil(sampleTime: clock.sampleTime(beat: floor(clock.currentBeat) + 1.5))
        ctx.add(BassSynth())
    }
}

kick.start(engine: engine)
bass.start(engine: engine)

Thread safety

LyrebirdClock is Sendable. Multiple routines may call currentBeat, sampleTime(beat:), and nextBeat(after:) concurrently. Only one thread should write bpm.

Following an external MIDI clock

To drive LyrebirdClock from incoming MIDI Clock (0xF8) messages, use MIDIClockFollower. See docs/tooling/midi-clock-sync.md for the full wiring guide.