320 lines
12 KiB
Markdown
320 lines
12 KiB
Markdown
# 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.
|
||
|
||
```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 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**
|
||
|
||
```swift
|
||
// 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.
|
||
|
||
---
|
||
|
||
## LyrebirdRoutine
|
||
|
||
Runs a closure **once** on a dedicated background thread (`Thread`, `.userInitiated` QoS).
|
||
|
||
```swift
|
||
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.
|
||
|
||
```swift
|
||
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
|
||
|
||
```swift
|
||
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.
|
||
|
||
```swift
|
||
ctx.add(synth)
|
||
ctx.schedule(synth, at: sampleTime)
|
||
ctx.schedule(synth, after: 2.0) // seconds
|
||
ctx.remove(synth)
|
||
ctx.remove(synth, at: sampleTime)
|
||
```
|
||
|
||
---
|
||
|
||
## 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
|
||
}
|
||
// 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.
|
||
|
||
---
|
||
|
||
## 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.
|
||
|
||
```swift
|
||
// 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
|
||
|
||
```swift
|
||
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
|
||
|
||
```swift
|
||
// 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
|
||
|
||
```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 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.
|