v2.4.0 release: event patterns + live event conductor
This commit is contained in:
@@ -104,6 +104,83 @@ The same factories on the demand side are implemented as separate `DemandGenerat
|
||||
|
||||
---
|
||||
|
||||
## EventPattern — event-driven playback
|
||||
|
||||
`EventPattern` is the heart of Lyrebird's event-driven playback: it binds named value `Pattern`s 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.
|
||||
|
||||
```swift
|
||||
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:
|
||||
|
||||
```swift
|
||||
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).
|
||||
|
||||
Reference in New Issue
Block a user