Files
Lyrebird/Sources/Lyrebird/Lyrebird.docc/RoutineTask.md
T

413 lines
16 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Routines, Tasks, and Patterns
@Metadata {
@PageKind(article)
}
Algorithmic event scheduling on background threads using `LyrebirdRoutine`, `LyrebirdTask`, and `Pattern<T>`.
## Overview
These types drive high-level events — adding/removing synths, changing `@LiveParam` values — from sequential code with timed waits. They run on background threads and are non-RT.
## Pattern\<T\>
A demand-rate value sequence. Not thread-safe; use within a single Routine/Task.
```swift
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. |
| `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
Every `Pattern<T>` variant is constructed via a static factory method on `Pattern<T>` (or `extension Pattern where T == Double` for numeric variants). All variants return a `Pattern<T>` (or `Pattern<[T]>` for `tuple`) backed by a module-internal engine. `next()` / `reset()` / `isExhausted` behave uniformly.
**Atomic value sources — generic `T`**
| Factory | Behaviour |
|---|---|
| ``Pattern/sequence(_:repeats:offset:)`` | Cycle through array `repeats` times. `-1` infinite. `offset` shifts only the first pass — opens at `values[offset]` (wraps modulo count), runs to the array end, then later cycles run full from index 0. |
| ``Pattern/shuffle(_:repeats:seed:)`` | Fisher-Yates permute once at init; cycle. Same permutation replays on reset. SC `Pshuf`. |
| ``Pattern/nonRepeatingRandom(_:repeats:seed:)`` | Random pick avoiding same *index* as previous. 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. 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. 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. 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. Coefficient clamped to `[0, 1]`. First sample passes through. SC `Psmooth`. |
The same factories on the demand side ship as separate `DemandGenerator` types (`DemandSeries`, `DemandShuffle`, `DemandSwitch`, etc.) that wrap the matching Pattern engines — see ``DemandGenerator``.
### euclideanRhythm
Generates a ``Pattern``\<`Bool`\> using the Bjorklund / Euclidean rhythm algorithm. Distributes
`pulses` hits as evenly as possible across `steps` positions. Classic patterns:
| Notation | Parameters | Pattern |
|---|---|---|
| Tresillo (3:8) | `pulses: 3, steps: 8` | `[1,0,0,1,0,0,1,0]` |
| Cinquillo (5:8) | `pulses: 5, steps: 8` | `[1,0,1,1,0,1,1,0]` |
| E(7,16) | `pulses: 7, steps: 16` | typical West African bell pattern |
```swift
let clave = euclideanRhythm(pulses: 3, steps: 8)
// returns an infinite-cycling Pattern<Bool>
let routine = LyrebirdRoutine { ctx in
ctx.tempo = 120.0
while let hit = clave.next() {
if hit { ctx.add(KickDrum()) }
try ctx.wait(beats: 0.5) // 8 steps per bar at 120 BPM
}
}
// With rotation: shift the pattern forward 2 positions
let rotated = euclideanRhythm(pulses: 5, steps: 8, rotation: 2)
```
- `pulses` — hit count. Clamped to `[0, steps]`.
- `steps` — total positions. Must be ≥ 1.
- `rotation` — cyclic shift after distribution. Positive = shift forward. Defaults to `0`.
The returned `Pattern` has `repeats: -1` (infinite). Call `reset()` to restart from step 1.
## LyrebirdRoutine
Runs a closure **once** on a dedicated background thread (`.userInitiated` QoS).
```swift
let routine = LyrebirdRoutine { ctx in
ctx.tempo = 120.0
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(beats: 1.0) // 0.5 s at 120 BPM; compensates for work above
ctx.remove(tone)
try ctx.wait(beats: 0.2)
}
}
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()`.
```swift
let task = LyrebirdTask { ctx in
while true {
ctx.add(nextEvent())
try ctx.wait(seconds: 0.25)
}
}
task.start(engine: engine)
task.pause() // freeze inside next 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 condition; resumes `ctx.wait()`. Sets state `.running`. |
| `stop()` / `reset()` | Same as `LyrebirdRoutine`. |
## LyrebirdRoutineContext
Passed to the body closure. Provides a routine clock, timed waits, and engine calls.
### Routine clock
The context exposes two parallel timelines: a **wall-clock** clock (driven by `Date()`) and a **sample-accurate** clock (driven by `engine.currentTime`).
```swift
// Wall-clock — drift-compensation source for wait(seconds:) / wait(beats:).
ctx.now // elapsed running seconds since routine started (wall clock)
ctx.currentBeat // elapsed beats from wall clock, accumulated across tempo changes
// Sample-accurate — what the audio engine has actually rendered.
ctx.elapsedSamples // SampleTime — engine samples since routine started
ctx.elapsedSeconds // elapsedSamples / engine.sampleRate
ctx.elapsedBeats // elapsed beats from sample time, accumulated across tempo changes
// Engine-relative pass-throughs (independent of when this routine started).
ctx.engineSamples // SynthesisEngine.elapsedSamples — samples since engine.start()
ctx.engineNow // SynthesisEngine.elapsedSeconds — seconds since engine.start()
```
Both clocks exclude pause time (`LyrebirdTask.pause()`) — paused intervals do not advance either timeline, even though `engine.currentTime` keeps incrementing. Tempo changes accumulate correctly in both:
```swift
ctx.tempo = 60.0
try ctx.wait(seconds: 1.0) // ctx.now ≈ 1.0, ctx.currentBeat ≈ 1.0
ctx.tempo = 120.0
try ctx.wait(seconds: 1.0) // ctx.now ≈ 2.0, ctx.currentBeat ≈ 3.0
```
#### When to use which
| Need | Use |
|---|---|
| Drift-compensated work scheduling (you want `wait` to keep an even cadence) | ``LyrebirdRoutineContext/now`` / ``LyrebirdRoutineContext/currentBeat`` |
| "How much audio has the engine rendered since I started?" | ``LyrebirdRoutineContext/elapsedSeconds`` / ``LyrebirdRoutineContext/elapsedBeats`` |
| Sample-accurate scheduling math (`engine.currentTime + offset`) | ``LyrebirdRoutineContext/elapsedSamples`` |
| Logging musical position into a recording | ``LyrebirdRoutineContext/elapsedBeats`` |
| Shared timeline across multiple routines (anchor to engine, not per-routine start) | ``LyrebirdRoutineContext/engineNow`` / ``LyrebirdRoutineContext/engineSamples`` |
`ctx.now` and `ctx.currentBeat` are wall-clock — they include OS scheduler jitter on the routine's background thread (typically ±1 ms). `ctx.elapsedSeconds` and `ctx.elapsedBeats` are sample-accurate but only advance when the engine processes blocks; before the first block they read 0.
### Timed waits
```swift
try ctx.wait(seconds: 0.5) // wait ~0.5 s with drift compensation
try ctx.wait(beats: 1.0) // wait 1 beat at ctx.tempo BPM
try ctx.waitUntil(sampleTime: t) // block until engine.currentTime >= t
```
All three throw `LyrebirdRoutineError.stopped` when `stop()` is called.
### Drift compensation
`wait(seconds:)` and `wait(beats:)` drive off the routine's own clock. If work between waits consumes part of an interval, the sleep is shortened by exactly that amount so the aggregate period holds:
```swift
ctx.tempo = 120.0
while true {
doWork() // variable processing time
try ctx.wait(beats: 1.0) // sleep = 500ms minus time doWork() took
}
```
If work exceeds the full interval, the sleep is skipped and no deficit carries forward. Pause time is excluded from the clock — pausing does not consume the musical timeline.
`waitUntil(sampleTime:)` resets the drift anchor to "now" on exit, so subsequent `wait` calls are anchored from that point.
### Tempo and beat timing
Set `ctx.tempo` (in BPM) to enable beat-relative waits. Default is 120 BPM.
```swift
ctx.tempo = 120.0
try ctx.wait(beats: 1.0) // 0.5 s at 120 BPM (one quarter note)
try ctx.wait(beats: 0.5) // 0.25 s (one eighth note)
try ctx.wait(beats: 4.0) // 2.0 s (one bar of 4/4)
```
Tempo can change at any point — each call reads the current value:
```swift
ctx.tempo = 60.0
try ctx.wait(beats: 1.0) // 1.0 s
ctx.tempo = 120.0
try ctx.wait(beats: 1.0) // 0.5 s — picks up new tempo immediately
```
Conversion: `seconds = beats × 60 / tempo`.
### Engine calls
Dispatched to the main thread via `DispatchQueue.main.async` to preserve the `pendingQueue` single-producer invariant.
```swift
ctx.add(synth)
ctx.schedule(synth, at: sampleTime)
ctx.schedule(synth, after: 2.0) // seconds
ctx.schedule(synth, afterBeats: 2.0) // 2 beats at current tempo
ctx.remove(synth)
ctx.remove(synth, at: sampleTime)
ctx.remove(synth, afterBeats: 4.0) // 4 beats at current tempo
```
## Error Handling
```swift
let routine = LyrebirdRoutine { ctx in
do {
while true {
try ctx.wait(seconds: 0.25)
// produce events
}
} catch LyrebirdRoutineError.stopped {
// cleanup if needed
}
}
```
Uncaught `LyrebirdRoutineError.stopped` is silently swallowed by the harness — it always signals a clean stop, not a crash.
## Thread Model
- One `Thread` per Routine/Task, 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.
## LyrebirdClock
A 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 separately and drift apart within seconds. `ctx.waitUntil(sampleTime:)` on a shared sample-time grid never drifts.
```swift
// WRONG — each routine drifts independently
let a = LyrebirdRoutine { ctx in
while true { ctx.add(Kick()); try ctx.wait(beats: 1) }
}
// RIGHT — both lock to the same sample-time 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
| Property / Method | Description |
|---|---|
| `epoch: SampleTime` | Engine sample time at clock creation. Shared reference point for all routines. |
| `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 if `beat` has already elapsed. |
| `nextBeat(after:) -> SampleTime` | Sample time of the next whole beat boundary after `beat` (or `currentBeat` if nil). `nextBeat(after: 4.0)` returns beat 5 — exclusive. |
### Tempo changes
```swift
let clock = LyrebirdClock(engine: engine, bpm: 120.0)
// Beat count is continuous across bpm changes
clock.bpm = 90.0 // accumulated beats do not jump; only the rate changes forward
```
`sampleTime(beat:)` is only accurate within the current tempo segment — since the last `bpm` change. Only the current tempo mapping is tracked; earlier segments are not reconstructed.
### Multi-voice example
```swift
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 beat 1.5, 2.5, … (every beat offset by half)
let bass = LyrebirdRoutine { ctx in
while true {
let nextHalf = clock.sampleTime(beat: floor(clock.currentBeat) + 1.5)
try ctx.waitUntil(sampleTime: nextHalf)
ctx.add(BassSynth())
}
}
kick.start(engine: engine)
bass.start(engine: engine)
```
### Thread safety
``LyrebirdClock`` is `Sendable`. Multiple routines may read `currentBeat`, `sampleTime(beat:)`, and `nextBeat(after:)` concurrently. Only one thread should write `bpm`.
## See Also
- ``LyrebirdClock``
- <doc:ValueComputable>
- <doc:Scheduling>
- <doc:NodeTree>