560724d116
- 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.
389 lines
16 KiB
Markdown
389 lines
16 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)
|
||
```
|
||
|
||
### 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.
|
||
|
||
```swift
|
||
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:
|
||
|
||
```swift
|
||
// 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:
|
||
|
||
```swift
|
||
@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
|
||
|
||
```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.
|
||
|
||
### 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.
|
||
|
||
```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.
|