v2.4.1 docs: promote the event system to its own EventPatterns topic

Extract the 2.4.0 event system from RoutineTask into a dedicated
EventPatterns DocC article and surface it on the landing page, so the
EventPattern / MonoEventPattern / ParallelEventPattern / EventConductor
family is its own topic. Docs-only; folded into the v2.4.1 tag.
This commit is contained in:
2026-12-03 13:46:19 -08:00
parent ec72bd3a4c
commit 1368deb8b1
4 changed files with 165 additions and 119 deletions
@@ -0,0 +1,152 @@
# Event Patterns
@Metadata {
@PageKind(article)
}
Declarative, event-driven playback: bind value patterns to a voice's parameters and let Lyrebird schedule each note's start and release.
## Overview
``EventPattern`` is the heart of Lyrebird's event-driven playback: it binds named value ``Pattern``s to a voice's `@LiveParam` parameters and plays them as a dur-driven stream of voices, so you do not hand-roll a spawn loop. Binding is **typed** — a `ReferenceWritableKeyPath` into a concrete voice type, checked at compile time — with no untyped event dictionary and no default-event prototype. The voice owns its amplitude envelope; the pattern owns timing.
Each event pulls one value from every bound pattern plus the duration pattern, makes a voice, writes the values, adds it, and reaps it, then waits the event's duration. The stream ends when the duration pattern or **any** bound pattern is exhausted; `repeats` replays the whole set.
**How a voice ends** follows one rule — the pattern never hard-removes a voice that frees itself. A voice conforming to ``EventGated`` is held open by its gate for the note and note-off'd (gate → `0`) after `sustain`, so its envelope release plays out and frees it; a voice conforming to ``EventSustainAware`` instead builds a fixed-duration self-freeing envelope from the sustain it is handed. In both cases the release is never cut. A voice conforming to neither is removed after `sustain + releaseTail` beats — the only case ``EventPattern/releaseTail(_:)`` affects.
```swift
import LyrebirdSynth
// A voice whose envelope frees it; EventPattern shapes the envelope via setEventSustain.
final class PluckVoice: SynthesizerBase, EventSustainAware {
@LiveParam var freq: Double = 440.0
@LiveParam var amp: Double = 0.2
private var sustain: Double = 0.5
func setEventSustain(seconds: Double) {
sustain = seconds
}
override func build() {
let env: Envelope = Envelope(levels: [0.0, 1.0, 0.0], durations: [0.005, sustain], curves: [0, 0])
let gen: EnvelopeGen.Audio = EnvelopeGen.Audio(envelope: env, doneAction: .freeNode)
output(bus: 0, source: OscSin.Audio(freq: $freq, mul: $amp) * gen)
}
}
func playPluck(on engine: SynthesisEngine) -> 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)
}
```
## Note-off with EventGated
A voice conforming to ``EventGated`` exposes its gate `@LiveParam` as `eventGate`; the pattern opens it on add (default the parameter open so the attack fires) and closes it after `sustain`. Give the voice an `EnvelopeGen` with a gate and a `releaseNode`: it holds at the sustain level while the gate is open, plays its release when the gate closes, and frees itself via `doneAction: .freeNode`. Nothing truncates the release, and there is no `releaseTail` to tune.
```swift
import LyrebirdSynth
// A gated voice: the gate holds it open; EventPattern closes it at the note's sustain.
final class GatedVoice: SynthesizerBase, EventGated {
@LiveParam var freq: Double = 440.0
@LiveParam var amp: Double = 0.2
@LiveParam var gate: Double = 1.0 // open by default so the attack fires on add
var eventGate: ParameterNode { $gate }
override func build() {
// releaseNode: 1 holds at levels[1] while gate > 0; gate → 0 plays segment 1 (release).
let env: Envelope = Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.01, 0.3],
curves: [.welch, .welch],
releaseNode: 1
)
let gen: EnvelopeGen.Audio = EnvelopeGen.Audio(envelope: env, gate: $gate, doneAction: .freeNode)
output(bus: 0, source: OscSin.Audio(freq: $freq, mul: $amp) * gen)
}
}
func playGated(on engine: SynthesisEngine) -> EventPatternHandle {
EventPattern(make: { GatedVoice() })
.bind(\.freq, .sequence([440.0, 550.0, 660.0]))
.dur(.sequence([0.25, 0.25, 0.5]))
.legato(0.8)
.tempo(132.0)
.play(on: engine)
}
```
When a voice conforms to **both** ``EventGated`` and ``EventSustainAware``, the gate wins: `setEventSustain` is skipped so the two release paths never fire together.
## Monophonic and parallel
``MonoEventPattern`` reuses **one** persistent voice, updating its parameters per event instead of spawning a new voice. A voice conforming to ``EventRetriggerable`` is re-struck on every event after the first (per-event articulation); when it also conforms to ``EventSustainAware``, its sustain is set before each `retrigger()`. A persistent ``EventGated`` voice is held open across the stream and note-off'd once, at the end.
``ParallelEventPattern`` plays several patterns at once. It holds a heterogeneous set of children — any mix of ``EventPattern``, ``MonoEventPattern`` and nested `ParallelEventPattern`s (anything conforming to ``EventPatternPlayable``) — and returns one ``EventPatternHandle`` that stops or awaits them all. The children share no common clock; same-tempo children begin within thread-start latency of each other and are not re-synchronised afterwards. ``ParallelEventPattern/add(_:)`` adds a child that enters with the group; ``ParallelEventPattern/addAfter(beats:eventPattern:)`` staggers a child a fixed number of beats into the shared start grid. All children must be composed before `play` — the group is a fire-once start. To push patterns in **live**, after playback has begun, use ``EventConductor`` instead.
```swift
func playTogether(on engine: SynthesisEngine) -> EventPatternHandle {
let bass: EventPattern<PluckVoice> = EventPattern(make: { PluckVoice() })
.bind(\.freq, .sequence([110.0, 110.0, 165.0, 110.0]))
.dur(.sequence([1.0]))
let lead: EventPattern<PluckVoice> = EventPattern(make: { PluckVoice() })
.bind(\.freq, .sequence([440.0, 550.0, 660.0]))
.dur(.sequence([0.5]))
return ParallelEventPattern([bass, lead]).play(on: engine)
}
```
Playback runs on a background `LyrebirdTask`; voice construction and `@LiveParam` writes hop to the main thread. The returned ``EventPatternHandle`` stops playback (``EventPatternHandle/stop()``), reports whether anything is still playing (``EventPatternHandle/isPlaying``), or blocks until a finite pattern finishes (``EventPatternHandle/waitUntilComplete(releasePadding:)``).
## Live insertion — EventConductor
Where ``ParallelEventPattern`` composes every child up front and fires once, ``EventConductor`` keeps a background clock running and accepts patterns **while it plays**, from any thread — a UI button, an OSC handler, a MIDI callback. Each enters quantised to the shared beat grid.
```swift
let conductor: EventConductor = EventConductor(tempo: 128.0)
conductor.start(on: engine)
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
bassPart.stop() // … and later stops the bass alone
```
``EventConductor/add(_:quantize:)`` enqueues under a lock and returns an ``EventConductorHandle`` at once; the conductor's own task starts due patterns on the main thread. ``EventConductorHandle/stop()`` stops that one part — cancelling it if still pending, stopping it if already playing — without disturbing the others, which is what the conductor's own ``EventConductor/stop()`` does. ``EventQuantum`` names the entry boundary — ``EventQuantum/now``, ``EventQuantum/nextBeat``, ``EventQuantum/nextMultiple(ofBeats:)``, ``EventQuantum/atBeat(_:)``, ``EventQuantum/afterBeats(_:)``. The clock quantises only each pattern's **entry**; once started a pattern keeps its own relative timing at its own tempo, so patterns may be polytempo. For finite content, ``EventConductor/waitUntilIdle(releasePadding:)`` blocks until nothing is pending and no child is still playing, after which the caller typically calls ``EventConductor/stop()``.
## Topics
### Patterns
- ``EventPattern``
- ``MonoEventPattern``
- ``ParallelEventPattern``
### Live ensemble
- ``EventConductor``
- ``EventConductorHandle``
- ``EventQuantum``
### Voice conformances
- ``EventGated``
- ``EventSustainAware``
- ``EventRetriggerable``
- ``EventPatternPlayable``
### Handles
- ``EventPatternHandle``
## See Also
- <doc:RoutineTask>
- <doc:Scheduling>
- <doc:PolyphonicVoices>
@@ -152,6 +152,10 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass
- ``TriggerEvent``
- ``TriggerHandlerToken``
### Event Patterns
- <doc:EventPatterns>
### Score and Event Sequencing
- <doc:ScoreSystem>
+7 -117
View File
@@ -480,126 +480,16 @@ bass.start(engine: engine)
## Event-driven patterns
``EventPattern`` is the heart of Lyrebird's event-driven playback: it binds named value ``Pattern``s to a voice's `@LiveParam` parameters and plays them as a dur-driven stream of voices, so you do not hand-roll the spawn loop above. Binding is **typed** — a `ReferenceWritableKeyPath` into a concrete voice type, checked at compile time — with no untyped event dictionary and no default-event prototype. The voice owns its amplitude envelope; the pattern owns timing.
Each event pulls one value from every bound pattern plus the duration pattern, makes a voice, writes the values, adds it, and reaps it, then waits the event's duration. The stream ends when the duration pattern or **any** bound pattern is exhausted; `repeats` replays the whole set.
**How a voice ends** follows one rule — the pattern never hard-removes a voice that frees itself. A voice conforming to ``EventGated`` is held open by its gate for the note and note-off'd (gate → `0`) after `sustain`, so its envelope release plays out and frees it; a voice conforming to ``EventSustainAware`` instead builds a fixed-duration self-freeing envelope from the sustain it is handed. In both cases the release is never cut. A voice conforming to neither is removed after `sustain + releaseTail` beats — the only case ``EventPattern/releaseTail(_:)`` affects.
```swift
import LyrebirdSynth
// A voice whose envelope frees it; EventPattern shapes the envelope via setEventSustain.
final class PluckVoice: SynthesizerBase, EventSustainAware {
@LiveParam var freq: Double = 440.0
@LiveParam var amp: Double = 0.2
private var sustain: Double = 0.5
func setEventSustain(seconds: Double) {
sustain = seconds
}
override func build() {
let env: Envelope = Envelope(levels: [0.0, 1.0, 0.0], durations: [0.005, sustain], curves: [0, 0])
let gen: EnvelopeGen.Audio = EnvelopeGen.Audio(envelope: env, doneAction: .freeNode)
output(bus: 0, source: OscSin.Audio(freq: $freq, mul: $amp) * gen)
}
}
func playPluck(on engine: SynthesisEngine) -> 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)
}
```
### Note-off with EventGated
A voice conforming to ``EventGated`` exposes its gate `@LiveParam` as `eventGate`; the pattern opens it on add (default the parameter open so the attack fires) and closes it after `sustain`. Give the voice an `EnvelopeGen` with a gate and a `releaseNode`: it holds at the sustain level while the gate is open, plays its release when the gate closes, and frees itself via `doneAction: .freeNode`. Nothing truncates the release, and there is no `releaseTail` to tune.
```swift
import LyrebirdSynth
// A gated voice: the gate holds it open; EventPattern closes it at the note's sustain.
final class GatedVoice: SynthesizerBase, EventGated {
@LiveParam var freq: Double = 440.0
@LiveParam var amp: Double = 0.2
@LiveParam var gate: Double = 1.0 // open by default so the attack fires on add
var eventGate: ParameterNode { $gate }
override func build() {
// releaseNode: 1 holds at levels[1] while gate > 0; gate → 0 plays segment 1 (release).
let env: Envelope = Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.01, 0.3],
curves: [.welch, .welch],
releaseNode: 1
)
let gen: EnvelopeGen.Audio = EnvelopeGen.Audio(envelope: env, gate: $gate, doneAction: .freeNode)
output(bus: 0, source: OscSin.Audio(freq: $freq, mul: $amp) * gen)
}
}
func playGated(on engine: SynthesisEngine) -> EventPatternHandle {
EventPattern(make: { GatedVoice() })
.bind(\.freq, .sequence([440.0, 550.0, 660.0]))
.dur(.sequence([0.25, 0.25, 0.5]))
.legato(0.8)
.tempo(132.0)
.play(on: engine)
}
```
### Monophonic and parallel
``MonoEventPattern`` reuses **one** persistent voice, updating its parameters per event instead of spawning a new voice. A voice conforming to ``EventRetriggerable`` is re-struck on every event after the first (per-event articulation); when it also conforms to ``EventSustainAware``, its sustain is set before each `retrigger()`. A persistent ``EventGated`` voice is held open across the stream and note-off'd once, at the end.
``ParallelEventPattern`` plays several patterns at once. It holds a heterogeneous set of children — any mix of ``EventPattern``, ``MonoEventPattern`` and nested `ParallelEventPattern`s (anything conforming to ``EventPatternPlayable``) — and returns one ``EventPatternHandle`` that stops or awaits them all. The children share no common clock; same-tempo children begin within thread-start latency of each other and are not re-synchronised afterwards. ``ParallelEventPattern/add(_:)`` adds a child that enters with the group; ``ParallelEventPattern/addAfter(beats:eventPattern:)`` staggers a child a fixed number of beats into the shared start grid. All children must be composed before `play` — the group is a fire-once start. To push patterns in **live**, after playback has begun, use ``EventConductor`` instead.
```swift
func playTogether(on engine: SynthesisEngine) -> EventPatternHandle {
let bass: EventPattern<PluckVoice> = EventPattern(make: { PluckVoice() })
.bind(\.freq, .sequence([110.0, 110.0, 165.0, 110.0]))
.dur(.sequence([1.0]))
let lead: EventPattern<PluckVoice> = EventPattern(make: { PluckVoice() })
.bind(\.freq, .sequence([440.0, 550.0, 660.0]))
.dur(.sequence([0.5]))
return ParallelEventPattern([bass, lead]).play(on: engine)
}
```
Playback runs on a background `LyrebirdTask`; voice construction and `@LiveParam` writes hop to the main thread. The returned ``EventPatternHandle`` stops playback (``EventPatternHandle/stop()``), reports whether anything is still playing (``EventPatternHandle/isPlaying``), or blocks until a finite pattern finishes (``EventPatternHandle/waitUntilComplete(releasePadding:)``).
### Live insertion — EventConductor
Where ``ParallelEventPattern`` composes every child up front and fires once, ``EventConductor`` keeps a background clock running and accepts patterns **while it plays**, from any thread — a UI button, an OSC handler, a MIDI callback. Each enters quantised to the shared beat grid.
```swift
let conductor: EventConductor = EventConductor(tempo: 128.0)
conductor.start(on: engine)
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
bassPart.stop() // … and later stops the bass alone
```
``EventConductor/add(_:quantize:)`` enqueues under a lock and returns an ``EventConductorHandle`` at once; the conductor's own task starts due patterns on the main thread. ``EventConductorHandle/stop()`` stops that one part — cancelling it if still pending, stopping it if already playing — without disturbing the others, which is what the conductor's own ``EventConductor/stop()`` does. ``EventQuantum`` names the entry boundary — ``EventQuantum/now``, ``EventQuantum/nextBeat``, ``EventQuantum/nextMultiple(ofBeats:)``, ``EventQuantum/atBeat(_:)``, ``EventQuantum/afterBeats(_:)``. The clock quantises only each pattern's **entry**; once started a pattern keeps its own relative timing at its own tempo, so patterns may be polytempo. For finite content, ``EventConductor/waitUntilIdle(releasePadding:)`` blocks until nothing is pending and no child is still playing, after which the caller typically calls ``EventConductor/stop()``.
Bind value ``Pattern``s to a voice's `@LiveParam`s and let Lyrebird schedule each
note's start and release — ``EventPattern`` for one voice per event,
``MonoEventPattern`` for a reused voice, ``ParallelEventPattern`` to fire several
together, and ``EventConductor`` to push parts in live while the clock runs. These
build on the routine/clock machinery above; see <doc:EventPatterns> for the full
guide and examples.
## See Also
- ``EventPattern``
- ``MonoEventPattern``
- ``ParallelEventPattern``
- ``EventConductor``
- ``EventConductorHandle``
- ``EventQuantum``
- ``EventGated``
- ``EventSustainAware``
- <doc:EventPatterns>
- ``LyrebirdClock``
- ``ValueComputable``
- <doc:Scheduling>