v2.4.0 release: event patterns + live event conductor
This commit is contained in:
@@ -478,8 +478,128 @@ bass.start(engine: engine)
|
||||
|
||||
``LyrebirdClock`` is `Sendable`. Multiple routines may read `currentBeat`, `sampleTime(beat:)`, and `nextBeat(after:)` concurrently. Only one thread should write `bpm`.
|
||||
|
||||
## 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()``.
|
||||
|
||||
## See Also
|
||||
|
||||
- ``EventPattern``
|
||||
- ``MonoEventPattern``
|
||||
- ``ParallelEventPattern``
|
||||
- ``EventConductor``
|
||||
- ``EventConductorHandle``
|
||||
- ``EventQuantum``
|
||||
- ``EventGated``
|
||||
- ``EventSustainAware``
|
||||
- ``LyrebirdClock``
|
||||
- ``ValueComputable``
|
||||
- <doc:Scheduling>
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// EventBinding.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// One `keyPath → Pattern` binding inside an ``EventPattern``.
|
||||
///
|
||||
/// Pairs a writable key path into a voice's `@LiveParam` (`\.freq`, `\.amp`, …) with the
|
||||
/// `Pattern<Double>` that drives it. On each event the pattern yields one value, written to
|
||||
/// the voice through the key path before the voice is added to the engine.
|
||||
///
|
||||
/// The key path targets a `@LiveParam`-backed `Double`, whose setter is an RT-safe atomic
|
||||
/// store, so the write is picked up by the render thread on the next block.
|
||||
///
|
||||
/// Internal — callers build bindings through ``EventPattern/bind(_:_:)``. Accessed only on
|
||||
/// the main thread, inside the pattern's per-event `onMain` hop (single consumer).
|
||||
internal struct EventBinding<V: Synthesizer> {
|
||||
|
||||
/// Writable key path into the voice's `@LiveParam Double` parameter.
|
||||
let keyPath: ReferenceWritableKeyPath<V, Double>
|
||||
|
||||
/// Value source for this parameter. One value is pulled per event via ``nextValue()``.
|
||||
let pattern: Pattern<Double>
|
||||
|
||||
/// Pulls the next value for this binding without touching a voice.
|
||||
///
|
||||
/// - Returns: The next value, or `nil` if the pattern is exhausted — which ends the whole
|
||||
/// event stream (any exhausted input ends it).
|
||||
/// Pulling before making a voice avoids constructing a voice that is then discarded.
|
||||
@MainActor func nextValue() -> Double? {
|
||||
pattern.next()
|
||||
}
|
||||
|
||||
/// Writes a previously pulled value into `voice` through the key path.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: The value to write.
|
||||
/// - voice: The voice whose parameter is being set.
|
||||
@MainActor func write(_ value: Double, to voice: V) {
|
||||
voice[keyPath: keyPath] = value
|
||||
}
|
||||
|
||||
/// Returns the pattern to its initial state (used when an ``EventPattern`` repeats).
|
||||
func reset() {
|
||||
pattern.reset()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
// EventConductor.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Synchronization
|
||||
|
||||
/// Poll granularity of the conductor's driving task, in seconds. Matches the routine context's
|
||||
/// own poll cadence, so a quantised entry lands within roughly this of its beat boundary.
|
||||
private let eventConductorPollSeconds: Double = 0.01
|
||||
|
||||
/// A running, clock-driven ensemble you push event patterns into **live** — from a UI button, an
|
||||
/// OSC handler, a MIDI callback, any thread — each entering quantised to a shared beat grid.
|
||||
///
|
||||
/// Where ``ParallelEventPattern`` is a fire-once group (every child composed before `play`), an
|
||||
/// `EventConductor` keeps a background clock running and accepts ``add(_:quantize:)`` at any time
|
||||
/// from any thread. Each added pattern begins on the boundary named by its ``EventQuantum`` — the
|
||||
/// next beat, the next bar, an absolute beat, or a relative lead-in — so a pattern triggered from
|
||||
/// a control surface drops into the groove on the beat rather than the instant the control fired.
|
||||
///
|
||||
/// ```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
|
||||
/// // … later still …
|
||||
/// bassPart.stop() // stops the bass alone; the drums play on
|
||||
/// ```
|
||||
///
|
||||
/// ## What the clock governs
|
||||
///
|
||||
/// The shared clock quantises only each pattern's **entry**, and it does so against the
|
||||
/// conductor's own beat grid: a resolved pattern is held until the conductor's clock reaches its
|
||||
/// target beat, then started immediately. Entry therefore aligns to the conductor's grid within
|
||||
/// the poll granularity (~`eventConductorPollSeconds`), **independent of the pattern's own tempo**.
|
||||
/// Once started, a pattern runs its own relative `wait(beats:)` chain at its own tempo, exactly as
|
||||
/// it would under ``EventPattern`` or ``ParallelEventPattern`` — so patterns can be polytempo, and
|
||||
/// the conductor does not re-align their individual events after entry.
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// ``add(_:quantize:)`` is safe to call from any thread: it enqueues under a lock and returns an
|
||||
/// ``EventConductorHandle`` at once. The conductor's own background task drains the queue each poll
|
||||
/// and starts due patterns on the main thread (voice construction is main-actor-isolated). Call
|
||||
/// ``EventConductorHandle/stop()`` on that handle to stop one part alone; ``stop()`` on the
|
||||
/// conductor stops them all. ``stop()``, ``isRunning``, ``hasActiveChildren`` and ``currentBeat``
|
||||
/// are likewise thread-safe. A pattern whose start is in flight when ``stop()`` is called is
|
||||
/// stopped as soon as it has entered, so nothing outlives the conductor.
|
||||
///
|
||||
/// ## Lifecycle
|
||||
///
|
||||
/// The conductor runs until ``stop()``. For finite content, ``waitUntilIdle(releasePadding:)``
|
||||
/// blocks until nothing is pending and no child is still playing (pumping the main run loop so the
|
||||
/// dispatched starts land), after which the caller typically calls ``stop()``.
|
||||
///
|
||||
/// - SeeAlso: ``EventConductorHandle``, ``EventQuantum``, ``ParallelEventPattern``, ``EventPatternPlayable``, ``EventPattern``
|
||||
public final class EventConductor: @unchecked Sendable {
|
||||
|
||||
/// Conductor lifecycle phase.
|
||||
private enum Phase {
|
||||
case idle // created, not yet started
|
||||
case running // driving task live
|
||||
case stopped // stopped; ignores further adds
|
||||
}
|
||||
|
||||
/// Guards every mutable field below. Held only for short, lock-local work — never across the
|
||||
/// main-thread hop that starts a child.
|
||||
private let _lock: NSLock = NSLock()
|
||||
|
||||
private var _phase: Phase = .idle
|
||||
|
||||
/// Patterns added but not yet resolved against the clock, each with the quantum that places it
|
||||
/// and the ``EventConductorHandle`` returned to the caller.
|
||||
private var _inbox: [(part: EventConductorHandle, pattern: any EventPatternPlayable, quantize: EventQuantum)] = []
|
||||
|
||||
/// Resolved patterns awaiting their target beat. Each poll, those whose target beat has arrived
|
||||
/// are started; the rest stay here. Resolving against the conductor's clock (not a per-pattern
|
||||
/// lead-in) is what makes entry tempo-independent.
|
||||
private var _pending: [(part: EventConductorHandle, pattern: any EventPatternPlayable, targetBeat: Double)] = []
|
||||
|
||||
/// Count of patterns selected to start this poll but whose entry has not yet been recorded — a
|
||||
/// pattern is never invisible to ``waitUntilIdle(releasePadding:)`` in the gap between selection
|
||||
/// and the main-thread start.
|
||||
private var _starting: Int = 0
|
||||
|
||||
/// Parts that have entered (or are entering). Finished parts are pruned lazily on append and on
|
||||
/// ``hasActiveChildren`` so a long-running conductor does not accumulate them without bound.
|
||||
private var _active: [EventConductorHandle] = []
|
||||
|
||||
/// The engine, captured at ``start(on:)``. Immutable once running.
|
||||
private var _engine: SynthesisEngine?
|
||||
|
||||
/// The background driving task. Immutable once running.
|
||||
private var _task: LyrebirdTask?
|
||||
|
||||
/// The conductor clock's latest beat position, as `Double` bit pattern, updated each poll.
|
||||
/// Read lock-free by ``currentBeat``.
|
||||
private let _currentBeatBits: Atomic<UInt64> = Atomic<UInt64>(0)
|
||||
|
||||
/// Playback tempo in beats per minute. Set at init before ``start(on:)``.
|
||||
private let _tempo: Double
|
||||
|
||||
/// Creates a conductor at `tempo` BPM. Add patterns with ``add(_:quantize:)`` before or after
|
||||
/// ``start(on:)``.
|
||||
///
|
||||
/// - Parameter tempo: Beats per minute. Must be positive. Defaults to `120.0`.
|
||||
public init(tempo: Double = 120.0) {
|
||||
precondition(tempo > 0 && tempo.isFinite, "tempo must be positive and finite")
|
||||
_tempo = tempo
|
||||
}
|
||||
|
||||
// MARK: - Control
|
||||
|
||||
/// Starts the conductor's clock on `engine`. No-op if already started.
|
||||
///
|
||||
/// Any patterns already queued by ``add(_:quantize:)`` are serviced on the first poll, relative
|
||||
/// to beat `0`.
|
||||
///
|
||||
/// - Parameter engine: Engine the patterns' voices are added to.
|
||||
@MainActor public func start(on engine: SynthesisEngine) {
|
||||
_lock.lock()
|
||||
guard _phase == .idle else {
|
||||
_lock.unlock()
|
||||
return
|
||||
}
|
||||
_phase = .running
|
||||
_engine = engine
|
||||
let task: LyrebirdTask = LyrebirdTask { [self] ctx in
|
||||
try _run(ctx: ctx)
|
||||
}
|
||||
_task = task
|
||||
_lock.unlock()
|
||||
task.start(engine: engine)
|
||||
}
|
||||
|
||||
/// Enqueues `pattern` to enter at the boundary named by `quantize`, returning a handle that
|
||||
/// stops that pattern alone. Thread-safe — call from a UI, OSC or MIDI callback on any thread.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pattern: The pattern to start — an ``EventPattern``, ``MonoEventPattern`` or
|
||||
/// ``ParallelEventPattern``.
|
||||
/// - quantize: When it should enter, against the conductor's clock. Defaults to
|
||||
/// ``EventQuantum/nextBeat``.
|
||||
/// - Returns: An ``EventConductorHandle`` for this part. ``EventConductorHandle/stop()`` cancels
|
||||
/// it if still pending, or stops it if already playing, without disturbing the other parts.
|
||||
/// After ``stop()`` the returned handle is already cancelled (its ``EventConductorHandle/isPlaying``
|
||||
/// is `false`) and the pattern is never started.
|
||||
@discardableResult
|
||||
public func add(
|
||||
_ pattern: any EventPatternPlayable,
|
||||
quantize: EventQuantum = .nextBeat
|
||||
) -> EventConductorHandle {
|
||||
// Validate on the caller's thread so a bad quantum traps at the call site, not later on
|
||||
// the conductor's background task.
|
||||
quantize.validate()
|
||||
let part: EventConductorHandle = EventConductorHandle()
|
||||
_lock.lock()
|
||||
if _phase != .stopped {
|
||||
_inbox.append((part, pattern, quantize))
|
||||
} else {
|
||||
part.markCancelledBeforeEntry()
|
||||
}
|
||||
_lock.unlock()
|
||||
return part
|
||||
}
|
||||
|
||||
/// Stops the conductor and every pattern it started. Idempotent; no further ``add(_:quantize:)``
|
||||
/// is honoured afterwards. A pattern whose start is in flight is stopped as soon as it enters.
|
||||
public func stop() {
|
||||
_lock.lock()
|
||||
_phase = .stopped
|
||||
let task: LyrebirdTask? = _task
|
||||
// Cancel everything still pending so its handle reports stopped and it never enters.
|
||||
for item: (part: EventConductorHandle, pattern: any EventPatternPlayable, quantize: EventQuantum) in _inbox {
|
||||
item.part.markCancelledBeforeEntry()
|
||||
}
|
||||
for item: (part: EventConductorHandle, pattern: any EventPatternPlayable, targetBeat: Double) in _pending {
|
||||
item.part.markCancelledBeforeEntry()
|
||||
}
|
||||
let active: [EventConductorHandle] = _active
|
||||
_inbox.removeAll(keepingCapacity: false)
|
||||
_pending.removeAll(keepingCapacity: false)
|
||||
_active.removeAll(keepingCapacity: false)
|
||||
_lock.unlock()
|
||||
task?.stop()
|
||||
for part: EventConductorHandle in active {
|
||||
part.stop()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - State
|
||||
|
||||
/// `true` while the conductor's clock is running (started and not stopped).
|
||||
public var isRunning: Bool {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
return _phase == .running
|
||||
}
|
||||
|
||||
/// `true` while any pattern the conductor started is still playing. Prunes finished handles as
|
||||
/// a side effect.
|
||||
public var hasActiveChildren: Bool {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
_active.removeAll { !$0.isPlaying }
|
||||
return !_active.isEmpty
|
||||
}
|
||||
|
||||
/// The conductor clock's current beat position (`0` before ``start(on:)``). Updated each poll,
|
||||
/// so it is accurate to within the poll granularity.
|
||||
public var currentBeat: Double {
|
||||
Double(bitPattern: _currentBeatBits.load(ordering: .relaxed))
|
||||
}
|
||||
|
||||
/// Blocks the calling thread until nothing is pending and no started pattern is still playing,
|
||||
/// then waits an extra `releasePadding` seconds for release tails to ring out.
|
||||
///
|
||||
/// Intended for finite content, and only after ``start(on:)``: add the patterns, `waitUntilIdle`,
|
||||
/// then ``stop()``. On the main thread it pumps the run loop so the conductor's dispatched starts
|
||||
/// land; off-main it polls. Returns immediately if the conductor is stopped or not yet started
|
||||
/// (before ``start(on:)`` nothing can drain, so do not call it then). If patterns may still be
|
||||
/// added later (a live performance), do not call this — drive ``stop()`` directly instead.
|
||||
///
|
||||
/// - Parameter releasePadding: Extra seconds to wait after the last pattern finishes. Negative
|
||||
/// values are clamped to `0`. Defaults to `0`.
|
||||
public func waitUntilIdle(releasePadding: Double = 0) {
|
||||
while true {
|
||||
_lock.lock()
|
||||
let idle: Bool = _phase != .running
|
||||
|| (_inbox.isEmpty && _pending.isEmpty && _starting == 0
|
||||
&& !_active.contains { $0.isPlaying })
|
||||
_lock.unlock()
|
||||
if idle { break }
|
||||
_tick(seconds: eventConductorPollSeconds)
|
||||
}
|
||||
let padding: Double = max(0.0, releasePadding)
|
||||
guard padding > 0 else { return }
|
||||
_tick(seconds: padding)
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
/// The conductor's driving-task body: set tempo, then poll — servicing the inbox and
|
||||
/// publishing the beat position — until stopped.
|
||||
private func _run(ctx: LyrebirdRoutineContext) throws {
|
||||
ctx.tempo = _tempo
|
||||
while true {
|
||||
_serviceInbox(ctx: ctx)
|
||||
_currentBeatBits.store(ctx.currentBeat.bitPattern, ordering: .relaxed)
|
||||
try ctx.wait(seconds: eventConductorPollSeconds)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves newly-added patterns against the clock, then starts every pending pattern whose
|
||||
/// target beat has arrived — on the main thread, with no lead-in. Runs on the conductor's task
|
||||
/// thread.
|
||||
private func _serviceInbox(ctx: LyrebirdRoutineContext) {
|
||||
let beatNow: Double = ctx.currentBeat
|
||||
|
||||
_lock.lock()
|
||||
guard _phase == .running, let engine: SynthesisEngine = _engine else {
|
||||
_lock.unlock()
|
||||
return
|
||||
}
|
||||
// Resolve inbox → pending against the current beat.
|
||||
for item: (part: EventConductorHandle, pattern: any EventPatternPlayable, quantize: EventQuantum) in _inbox {
|
||||
_pending.append((item.part, item.pattern, item.quantize.targetBeat(from: beatNow)))
|
||||
}
|
||||
_inbox.removeAll(keepingCapacity: true)
|
||||
// Select the pending parts whose boundary has arrived; keep the rest.
|
||||
guard !_pending.isEmpty else {
|
||||
_lock.unlock()
|
||||
return
|
||||
}
|
||||
var due: [(part: EventConductorHandle, pattern: any EventPatternPlayable)] = []
|
||||
var stillPending: [(part: EventConductorHandle, pattern: any EventPatternPlayable, targetBeat: Double)] = []
|
||||
for item: (part: EventConductorHandle, pattern: any EventPatternPlayable, targetBeat: Double) in _pending {
|
||||
if item.targetBeat <= beatNow {
|
||||
due.append((item.part, item.pattern))
|
||||
} else {
|
||||
stillPending.append(item)
|
||||
}
|
||||
}
|
||||
_pending = stillPending
|
||||
// Track the due parts in `_active` now, under the same lock that removed them from
|
||||
// `_pending`. A due part is therefore never invisible to ``stop()`` in the gap before its
|
||||
// start hop: if ``stop()`` lands during the hop it snapshots and stops the part, and the
|
||||
// `attach` below then stops the just-started pattern.
|
||||
if !due.isEmpty {
|
||||
_active.removeAll { !$0.isPlaying }
|
||||
for item: (part: EventConductorHandle, pattern: any EventPatternPlayable) in due {
|
||||
_active.append(item.part)
|
||||
}
|
||||
}
|
||||
_starting += due.count
|
||||
_lock.unlock()
|
||||
|
||||
for item: (part: EventConductorHandle, pattern: any EventPatternPlayable) in due {
|
||||
_lock.lock()
|
||||
let runningBeforeHop: Bool = _phase == .running
|
||||
_lock.unlock()
|
||||
// Skip if the conductor stopped or the caller cancelled this part before it entered —
|
||||
// no voice is built. The part stays in `_active` but reports `isPlaying == false`, so it
|
||||
// is pruned on the next selection or ``hasActiveChildren`` read.
|
||||
guard runningBeforeHop, !item.part.isCancelled else {
|
||||
item.part.markCancelledBeforeEntry()
|
||||
_lock.lock()
|
||||
_starting -= 1
|
||||
_lock.unlock()
|
||||
continue
|
||||
}
|
||||
|
||||
let args: StartArgs = StartArgs(engine: engine, pattern: item.pattern)
|
||||
let handle: EventPatternHandle = ctx.onMain {
|
||||
args.pattern.play(on: args.engine)
|
||||
}
|
||||
|
||||
// Hand over the real handle. `attach` stops it at once if the part was cancelled during
|
||||
// the hop — by the caller's ``EventConductorHandle/stop()`` or by ``stop()``'s snapshot.
|
||||
item.part.attach(handle)
|
||||
_lock.lock()
|
||||
_starting -= 1
|
||||
_lock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
/// One wait step for ``waitUntilIdle(releasePadding:)`` — pump the main run loop when on main so
|
||||
/// dispatched starts run, else a plain sleep.
|
||||
private func _tick(seconds: Double) {
|
||||
if Thread.isMainThread {
|
||||
RunLoop.current.run(until: Date().addingTimeInterval(seconds))
|
||||
} else {
|
||||
Thread.sleep(forTimeInterval: seconds)
|
||||
}
|
||||
}
|
||||
|
||||
/// Cross-thread carrier so the `@Sendable` task body can hand the (non-`Sendable`) engine and
|
||||
/// pattern to the synchronous main-thread hop. The hop is a full barrier; the two threads never
|
||||
/// touch an instance concurrently.
|
||||
private struct StartArgs: @unchecked Sendable {
|
||||
let engine: SynthesisEngine
|
||||
let pattern: any EventPatternPlayable
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// EventConductorHandle.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A stoppable reference to one pattern handed to an ``EventConductor`` through
|
||||
/// ``EventConductor/add(_:quantize:)``.
|
||||
///
|
||||
/// Returned the instant you add a pattern — before it has entered. Because the conductor holds a
|
||||
/// pattern until its quantised beat arrives, the underlying ``EventPatternHandle`` does not exist
|
||||
/// yet, so this handle stands in for it. ``stop()`` works in either phase: before entry it cancels
|
||||
/// the pending start (the pattern never enters, no voice is built); after entry it stops the
|
||||
/// started pattern, so its gated voices release. Stopping one part this way leaves every other part
|
||||
/// the conductor is running untouched — unlike ``EventConductor/stop()``, which stops them all.
|
||||
///
|
||||
/// Thread-safe: ``stop()`` and ``isPlaying`` may be called from any thread (a UI button, an OSC or
|
||||
/// MIDI callback).
|
||||
///
|
||||
/// - SeeAlso: ``EventConductor``, ``EventPatternHandle``
|
||||
public final class EventConductorHandle: @unchecked Sendable {
|
||||
|
||||
private let _lock: NSLock = NSLock()
|
||||
|
||||
/// The real handle, set by the conductor once the pattern has entered. `nil` while pending.
|
||||
private var _real: EventPatternHandle?
|
||||
|
||||
/// `true` once ``stop()`` has been called (in either phase) or the conductor cancelled the
|
||||
/// pending start. Before entry this tells the conductor to skip starting the pattern.
|
||||
private var _cancelled: Bool = false
|
||||
|
||||
internal init() {}
|
||||
|
||||
/// `true` while this part is pending entry or still playing; `false` once it has finished, been
|
||||
/// stopped, or been cancelled before entry.
|
||||
public var isPlaying: Bool {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
if let real: EventPatternHandle = _real {
|
||||
return real.isPlaying
|
||||
}
|
||||
// Not yet entered: still pending (so "playing") unless it was cancelled.
|
||||
return !_cancelled
|
||||
}
|
||||
|
||||
/// Stops this part only. Before the pattern enters, cancels its pending start; after entry,
|
||||
/// stops the started pattern so its gated voices release. Idempotent; safe from any thread.
|
||||
public func stop() {
|
||||
_lock.lock()
|
||||
_cancelled = true
|
||||
let real: EventPatternHandle? = _real
|
||||
_lock.unlock()
|
||||
real?.stop()
|
||||
}
|
||||
|
||||
/// `true` if the part has been stopped or cancelled — the conductor reads this before entry to
|
||||
/// skip the start.
|
||||
internal var isCancelled: Bool {
|
||||
_lock.lock()
|
||||
defer { _lock.unlock() }
|
||||
return _cancelled
|
||||
}
|
||||
|
||||
/// Called by the conductor when the pattern enters, handing over the real handle. If the part
|
||||
/// was stopped while still pending, the just-started pattern is stopped at once.
|
||||
internal func attach(_ real: EventPatternHandle) {
|
||||
_lock.lock()
|
||||
_real = real
|
||||
let cancelled: Bool = _cancelled
|
||||
_lock.unlock()
|
||||
if cancelled {
|
||||
real.stop()
|
||||
}
|
||||
}
|
||||
|
||||
/// Called by the conductor when a pending part will never enter — the conductor stopped, or the
|
||||
/// part's beat was reached after it had been cancelled. Marks it finished so ``isPlaying``
|
||||
/// reports `false`.
|
||||
internal func markCancelledBeforeEntry() {
|
||||
_lock.lock()
|
||||
_cancelled = true
|
||||
_lock.unlock()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// EventGated.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Opt-in refinement a voice adopts so an event pattern can drive its **gate** — a gate-driven
|
||||
/// note-on/note-off model.
|
||||
///
|
||||
/// An ``EventGated`` voice exposes the gate `ParameterNode` projected from one of its
|
||||
/// `@LiveParam` properties (`$gate`). The event pattern opens the gate when the voice is added
|
||||
/// (so the attack fires) and closes it — sets it to `0` — when the note's sustain elapses. The
|
||||
/// voice's own `EnvelopeGen` does the rest: give it `gate: $gate` and an `Envelope` with a
|
||||
/// `releaseNode`, so it holds at the sustain level while the gate is open and plays its release
|
||||
/// segment when the gate closes, then frees itself via `doneAction: .freeNode`. Nothing truncates
|
||||
/// the release — the pattern supplies the gate and the note's sustain, and the voice's own envelope
|
||||
/// owns the release.
|
||||
///
|
||||
/// ```swift
|
||||
/// final class PluckVoice: SynthesizerBase, EventGated {
|
||||
/// @LiveParam var freq: Double = 440.0
|
||||
/// @LiveParam var amp: Double = 0.2
|
||||
/// @LiveParam var gate: Double = 1.0 // defaults OPEN so the attack fires on add
|
||||
///
|
||||
/// var eventGate: ParameterNode { $gate }
|
||||
///
|
||||
/// override func build() {
|
||||
/// let env: Envelope = Envelope(
|
||||
/// levels: [0.0, 1.0, 0.0],
|
||||
/// durations: [0.01, 0.3],
|
||||
/// curves: [.welch, .welch],
|
||||
/// releaseNode: 1 // hold at levels[1] while gate > 0
|
||||
/// )
|
||||
/// let shaped: EnvelopeGen.Audio = EnvelopeGen.Audio(
|
||||
/// envelope: env, gate: $gate, doneAction: .freeNode
|
||||
/// )
|
||||
/// output(bus: 0, source: OscSin.Audio(freq: $freq, mul: $amp) * shaped)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Conformance is optional and is an alternative to ``EventSustainAware``. A gated voice is driven
|
||||
/// by its gate (held open for the note, closed at `sustain`); a sustain-aware voice instead builds
|
||||
/// a fixed-duration self-timed envelope from a `sustain`-in-seconds hand-off. Either way an event
|
||||
/// pattern never hard-removes the voice — it trusts the voice to free itself via `doneAction`. A
|
||||
/// voice conforming to **neither** is removed by the pattern after `sustain + releaseTail` beats.
|
||||
///
|
||||
/// - SeeAlso: ``EventSustainAware``, ``EventPattern``, ``MonoEventPattern``
|
||||
public protocol EventGated: Synthesizer {
|
||||
|
||||
/// The gate parameter node — project a `@LiveParam` with `$`, e.g. `$gate`.
|
||||
///
|
||||
/// Read on the main actor. Default the backing parameter **open** (`≥ 1.0`) so the voice's
|
||||
/// attack fires the moment it is added. The event pattern sets it to `0` when the note's
|
||||
/// sustain elapses, driving the voice's `EnvelopeGen` release.
|
||||
@MainActor var eventGate: ParameterNode { get }
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
// EventPattern.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Default fraction of each event's duration for which a voice sounds.
|
||||
private let eventPatternDefaultLegato: Double = 0.9
|
||||
|
||||
/// Default playback tempo in beats per minute.
|
||||
private let eventPatternDefaultTempo: Double = 120.0
|
||||
|
||||
/// The heart of Lyrebird's event-driven playback: binds named value ``Pattern``s to a voice's
|
||||
/// `@LiveParam` 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 — then waits the event's duration before the next event. The stream ends when the
|
||||
/// duration pattern or **any** bound pattern is exhausted (any exhausted input ends it),
|
||||
/// optionally repeating the whole bound set.
|
||||
///
|
||||
/// **How a voice ends** follows one rule: the voice owns its envelope; the pattern owns
|
||||
/// timing. A voice conforming to ``EventGated`` is held open by its gate for the note and gets a
|
||||
/// note-off (gate → `0`) after `sustain` beats, 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 pattern never hard-removes the voice — it
|
||||
/// trusts `doneAction`, so the release is never cut. A voice conforming to neither is removed after
|
||||
/// `sustain + releaseTail` beats (see ``releaseTail(_:)``).
|
||||
///
|
||||
/// Binding is **typed**: a `ReferenceWritableKeyPath` into a concrete voice type, checked at
|
||||
/// compile time. There is no untyped event dictionary and no default-event prototype — you pass
|
||||
/// the values you actually want, in the units the voice expects.
|
||||
///
|
||||
/// ```swift
|
||||
/// final class PluckVoice: SynthesizerBase, EventSustainAware {
|
||||
/// @LiveParam var freq: Double = 440.0
|
||||
/// @LiveParam var amp: Double = 0.2
|
||||
/// // … build() wires an envelope that frees the voice; setEventSustain shapes it …
|
||||
/// }
|
||||
///
|
||||
/// 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)
|
||||
/// ```
|
||||
///
|
||||
/// Playback runs on a background `LyrebirdTask`; voice construction and parameter writes hop
|
||||
/// to the main thread (`@LiveParam` and `SynthesizerBase` are main-actor-isolated). The
|
||||
/// returned ``EventPatternHandle`` stops playback or waits for a finite stream to finish.
|
||||
///
|
||||
/// Not thread-safe: configure (`bind`/`dur`/…) before `play`, and drive a single `play` at a
|
||||
/// time. Its patterns are pulled by exactly one playback task.
|
||||
///
|
||||
/// - SeeAlso: ``EventGated``, ``EventSustainAware``, ``EventPatternHandle``, ``Pattern``
|
||||
public final class EventPattern<V: Synthesizer>: @unchecked Sendable {
|
||||
|
||||
/// Factory for a fresh voice per event. Called on the main thread.
|
||||
private let _make: @MainActor () -> V
|
||||
|
||||
/// `keyPath → Pattern` bindings, applied in order each event.
|
||||
private var _bindings: [EventBinding<V>] = []
|
||||
|
||||
/// Duration (delta) pattern in beats. Defaults to an infinite stream of `1.0`.
|
||||
private var _durPattern: Pattern<Double> = Pattern<Double>.sequence([1.0])
|
||||
|
||||
/// Fraction of each duration a voice sustains (`sustain = delta * legato`).
|
||||
private var _legato: Double = eventPatternDefaultLegato
|
||||
|
||||
/// Extra beats of grace after `sustain` before a **plain** voice is removed, so its envelope
|
||||
/// release tail is not hard-cut. Unused by ``EventGated`` / ``EventSustainAware`` voices, which
|
||||
/// free themselves.
|
||||
private var _releaseTail: Double = 0.0
|
||||
|
||||
/// Number of times to play the whole bound set (resetting between). `1` = once.
|
||||
private var _repeats: Int = 1
|
||||
|
||||
/// Playback tempo in beats per minute.
|
||||
private var _tempo: Double = eventPatternDefaultTempo
|
||||
|
||||
/// Creates an event pattern.
|
||||
///
|
||||
/// - Parameter make: Factory returning a fresh voice for each event. Runs on the main
|
||||
/// thread. Construct and return a new instance — do not reuse one across events (see
|
||||
/// `MonoEventPattern` for single-voice reuse).
|
||||
public init(make: @escaping @MainActor () -> V) {
|
||||
_make = make
|
||||
}
|
||||
|
||||
// MARK: - Builder
|
||||
|
||||
/// Binds a voice parameter to a value pattern.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - keyPath: Writable key path into a `@LiveParam Double` on the voice (`\.freq`).
|
||||
/// - pattern: Value source; one value is pulled per event.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func bind(
|
||||
_ keyPath: ReferenceWritableKeyPath<V, Double>,
|
||||
_ pattern: Pattern<Double>
|
||||
) -> Self {
|
||||
_bindings.append(EventBinding(keyPath: keyPath, pattern: pattern))
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets the duration (delta) pattern, in beats. One value is pulled per event; the stream
|
||||
/// ends if it is exhausted.
|
||||
///
|
||||
/// - Parameter pattern: Beats-per-event value source.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func dur(_ pattern: Pattern<Double>) -> Self {
|
||||
_durPattern = pattern
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets the legato factor: a voice sustains for `delta * legato` beats. Values above `1.0`
|
||||
/// overlap successive voices.
|
||||
///
|
||||
/// - Parameter value: Sustain fraction of each duration. Must be `≥ 0`. Defaults to `0.9`.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func legato(_ value: Double) -> Self {
|
||||
precondition(value >= 0, "legato must be non-negative")
|
||||
_legato = value
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets extra beats of grace after `sustain` before a **plain** voice is removed, so its
|
||||
/// envelope release tail is not cut short.
|
||||
///
|
||||
/// Affects only voices that conform to **neither** ``EventGated`` nor ``EventSustainAware`` —
|
||||
/// those free themselves (gate release or a self-timed envelope) and are never hard-removed, so
|
||||
/// this value does nothing for them.
|
||||
///
|
||||
/// - Parameter beats: Grace in beats. Defaults to `0.0`.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func releaseTail(_ beats: Double) -> Self {
|
||||
_releaseTail = beats
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets how many times to play the whole bound set (resetting all patterns between).
|
||||
///
|
||||
/// - Parameter count: Number of passes. `1` plays once; pass `Int.max` for effectively
|
||||
/// endless playback. Values below `1` play nothing.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func repeats(_ count: Int) -> Self {
|
||||
_repeats = count
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets the playback tempo.
|
||||
///
|
||||
/// - Parameter bpm: Beats per minute. Must be positive. Defaults to `120.0`.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func tempo(_ bpm: Double) -> Self {
|
||||
precondition(bpm > 0, "tempo must be positive")
|
||||
_tempo = bpm
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - Play
|
||||
|
||||
/// Starts playback on a background task after an optional lead-in, and returns a handle to
|
||||
/// control it.
|
||||
///
|
||||
/// Snapshots the current configuration into an `EventStream` **before** starting the
|
||||
/// task, so later builder calls cannot race with the running stream.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: Engine the voices are added to.
|
||||
/// - beats: Lead-in before the first event, in beats at this pattern's tempo. `0` starts
|
||||
/// immediately. The task is live (waiting) for the lead-in, so `stop()` works during it.
|
||||
/// - Returns: A handle to stop playback or await a finite stream.
|
||||
@discardableResult
|
||||
@MainActor public func play(
|
||||
on engine: SynthesisEngine,
|
||||
startAfterBeats beats: Double
|
||||
) -> EventPatternHandle {
|
||||
let task: LyrebirdTask = makeTask(stream: makeEventStream(), startOffsetBeats: beats)
|
||||
task.start(engine: engine)
|
||||
return EventPatternHandle(tasks: [task])
|
||||
}
|
||||
|
||||
/// Builds a fresh `EventStream` from the current configuration. Each call returns an
|
||||
/// independent stream (patterns are shared by reference, so reuse is single-consumer).
|
||||
@MainActor internal func makeEventStream() -> EventStream<V> {
|
||||
EventStream(
|
||||
make: _make,
|
||||
bindings: _bindings,
|
||||
durPattern: _durPattern,
|
||||
legato: _legato,
|
||||
repeats: _repeats,
|
||||
tempo: _tempo
|
||||
)
|
||||
}
|
||||
|
||||
/// Builds the driving task for a pre-snapshot `stream`, without starting it. The body
|
||||
/// captures the snapshot, not `self`, so builder mutation after `play` cannot affect it.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - stream: The pre-snapshot event stream to drive.
|
||||
/// - startOffsetBeats: Lead-in in beats before the first event (`0` = none).
|
||||
@MainActor internal func makeTask(
|
||||
stream: EventStream<V>,
|
||||
startOffsetBeats: Double
|
||||
) -> LyrebirdTask {
|
||||
let tempoBPM: Double = _tempo
|
||||
let releaseTailBeats: Double = _releaseTail
|
||||
return LyrebirdTask { ctx in
|
||||
ctx.tempo = tempoBPM
|
||||
do {
|
||||
// Lead-in: wait before the first event so a staggered child enters on the group's
|
||||
// shared start grid. The task is live (waiting) throughout, so stop() still works.
|
||||
if startOffsetBeats > 0 {
|
||||
try ctx.wait(beats: startOffsetBeats)
|
||||
}
|
||||
while let event: ResolvedEvent = ctx.onMain({ stream.nextResolved() }) {
|
||||
ctx.add(event.voice)
|
||||
if let gate: ParameterNode = event.gate {
|
||||
// Gate note-off: the gate is already open (the voice defaults it open, so the
|
||||
// attack fires on add); close it after `sustain` so the voice's envelope
|
||||
// release plays out and frees it. Non-blocking and overlap-safe, so a
|
||||
// legato > 1 voice's note-off lands after the next voice has already begun.
|
||||
ctx.set(gate, to: 0.0, afterBeats: event.sustain)
|
||||
} else if !event.selfFreeing {
|
||||
// Plain voice (neither EventGated nor EventSustainAware): it will not free
|
||||
// itself, so reap it after its tail. This is the only path releaseTail affects.
|
||||
ctx.remove(event.voice, afterBeats: event.sustain + releaseTailBeats)
|
||||
}
|
||||
// EventSustainAware (selfFreeing, no gate): trust its self-timed, self-freeing
|
||||
// envelope — no removal, so the release is never hard-cut.
|
||||
try ctx.wait(beats: event.delta)
|
||||
}
|
||||
// Finite stream done: let the final voices' gate-closes fire at their proper times
|
||||
// before the body returns, so trailing note-offs are not dropped.
|
||||
try ctx.waitForScheduledSets()
|
||||
} catch LyrebirdRoutineError.stopped {
|
||||
// Stopped mid-stream: close every outstanding gate now so its voice releases and
|
||||
// self-frees, rather than hanging at the sustain level.
|
||||
ctx._flushScheduledSets()
|
||||
throw LyrebirdRoutineError.stopped
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension EventPattern: EventPatternPlayable {}
|
||||
@@ -0,0 +1,93 @@
|
||||
// EventPatternHandle.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A running event pattern — ``EventPattern``, ``MonoEventPattern`` or ``ParallelEventPattern`` —
|
||||
/// returned by `play(...)`.
|
||||
///
|
||||
/// Holds the background `LyrebirdTask`(s) driving the pattern. Use it to stop playback, ask
|
||||
/// whether anything is still playing, or block until a finite pattern finishes.
|
||||
///
|
||||
/// ```swift
|
||||
/// let handle: EventPatternHandle = pattern.play(on: engine)
|
||||
/// // … later …
|
||||
/// handle.stop()
|
||||
/// ```
|
||||
public final class EventPatternHandle: @unchecked Sendable {
|
||||
|
||||
/// The background tasks driving playback. One for a single ``EventPattern``; several for a
|
||||
/// `ParallelEventPattern`.
|
||||
private let _tasks: [LyrebirdTask]
|
||||
|
||||
/// Wraps the tasks driving an event pattern.
|
||||
///
|
||||
/// - Parameter tasks: The started `LyrebirdTask`(s). Must be non-empty.
|
||||
internal init(tasks: [LyrebirdTask]) {
|
||||
precondition(!tasks.isEmpty, "EventPatternHandle requires at least one task")
|
||||
_tasks = tasks
|
||||
}
|
||||
|
||||
/// Merges several single-pattern handles into one that controls them all — used by
|
||||
/// ``ParallelEventPattern`` so stopping or awaiting the parent covers every child.
|
||||
///
|
||||
/// - Parameter handles: The child handles. Must be non-empty.
|
||||
internal convenience init(merging handles: [EventPatternHandle]) {
|
||||
self.init(tasks: handles.flatMap { $0._tasks })
|
||||
}
|
||||
|
||||
/// `true` while any driving task is still live — running or paused (a paused task has not
|
||||
/// finished and may resume).
|
||||
public var isPlaying: Bool {
|
||||
_tasks.contains { $0.state == .running || $0.state == .paused }
|
||||
}
|
||||
|
||||
/// Stops playback: no further events are spawned. Already-added voices are reaped as they
|
||||
/// would be at a normal stream end — outstanding gate note-offs fire immediately so
|
||||
/// ``EventGated`` voices release and self-free, self-timed ``EventSustainAware`` voices free
|
||||
/// themselves, and plain voices keep their scheduled removal. A ``MonoEventPattern``'s
|
||||
/// persistent voice is gate-closed if ``EventGated``, otherwise removed after its `releaseTail`.
|
||||
/// Idempotent.
|
||||
public func stop() {
|
||||
for task: LyrebirdTask in _tasks {
|
||||
task.stop()
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocks the calling thread until every driving task has finished, then waits an additional
|
||||
/// `releasePadding` seconds.
|
||||
///
|
||||
/// Only returns for a finite pattern (one whose value patterns exhaust, or after ``stop()``).
|
||||
///
|
||||
/// The pattern's task finishes at the **final note-off** — but a voice's envelope release plays
|
||||
/// on after that, on the audio thread. A caller that tears the engine down the instant this
|
||||
/// returns (a CLI demo, an offline render) would cut that tail, clicking the last note. Pass
|
||||
/// `releasePadding` equal to (or a little above) the voices' longest release so the tail rings
|
||||
/// out first. A long-lived app keeps the engine running and the tail decays naturally, so the
|
||||
/// default `0` is right there.
|
||||
///
|
||||
/// Pumps the main run loop while waiting — through the padding too — so main-dispatched engine
|
||||
/// edits (a voice's `doneAction` self-free, say) still land. Never call from a context that
|
||||
/// must stay responsive.
|
||||
///
|
||||
/// - Parameter releasePadding: Extra seconds to wait after the pattern completes, for release
|
||||
/// tails to ring out. Negative values are clamped to `0`. Defaults to `0`.
|
||||
public func waitUntilComplete(releasePadding: Double = 0) {
|
||||
for task: LyrebirdTask in _tasks {
|
||||
task.waitUntilComplete()
|
||||
}
|
||||
let padding: Double = max(0.0, releasePadding)
|
||||
guard padding > 0 else { return }
|
||||
// On the main thread, keep the run loop serviced so dispatched engine ops still drain while
|
||||
// the tail rings; off-main (e.g. a test thread) a plain sleep suffices — the audio decays
|
||||
// on the RT thread regardless.
|
||||
if Thread.isMainThread {
|
||||
RunLoop.current.run(until: Date().addingTimeInterval(padding))
|
||||
} else {
|
||||
Thread.sleep(forTimeInterval: padding)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// EventPatternPlayable.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// A configured event pattern that can be started on an engine, returning a handle.
|
||||
///
|
||||
/// Both ``EventPattern`` (polyphonic) and ``MonoEventPattern`` (monophonic) conform, so a
|
||||
/// ``ParallelEventPattern`` can hold a heterogeneous set of children (`[any EventPatternPlayable]`)
|
||||
/// and start them together.
|
||||
///
|
||||
/// - SeeAlso: ``EventPattern``, ``MonoEventPattern``, ``ParallelEventPattern``
|
||||
public protocol EventPatternPlayable {
|
||||
|
||||
/// Starts playback on a background task after an optional lead-in, and returns a handle.
|
||||
///
|
||||
/// The driving task is live for the whole lead-in (it is simply waiting), so the returned
|
||||
/// handle reports ``EventPatternHandle/isPlaying`` and honours ``EventPatternHandle/stop()``
|
||||
/// during it. The handle must wrap at least one task, even when the configured stream yields
|
||||
/// no events, so that ``ParallelEventPattern`` can merge children's handles unconditionally.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: Engine the voices are added to.
|
||||
/// - beats: Lead-in before the first event, in beats at the pattern's own tempo. `0` starts
|
||||
/// immediately. ``ParallelEventPattern`` uses it to stagger a child's entry on the group's
|
||||
/// shared start grid (see ``ParallelEventPattern/addAfter(beats:eventPattern:)``).
|
||||
/// - Returns: A handle to stop playback or await a finite stream.
|
||||
@MainActor func play(on engine: SynthesisEngine, startAfterBeats beats: Double) -> EventPatternHandle
|
||||
}
|
||||
|
||||
public extension EventPatternPlayable {
|
||||
|
||||
/// Starts playback immediately — no lead-in. Equivalent to `play(on:startAfterBeats: 0)`.
|
||||
///
|
||||
/// - Parameter engine: Engine the voices are added to.
|
||||
/// - Returns: A handle to stop playback or await a finite stream.
|
||||
@discardableResult
|
||||
@MainActor func play(on engine: SynthesisEngine) -> EventPatternHandle {
|
||||
play(on: engine, startAfterBeats: 0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// EventQuantum.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// When a pattern handed to an ``EventConductor`` should begin, expressed against the conductor's
|
||||
/// shared beat clock.
|
||||
///
|
||||
/// A conductor quantises only the **entry** of each pattern: the first event lands on the chosen
|
||||
/// boundary, after which the pattern runs its own relative timing at its own tempo. The conductor
|
||||
/// resolves the quantum to a target beat on its own clock and holds the pattern until that beat
|
||||
/// arrives, then starts it immediately — so entry aligns to the conductor's grid regardless of the
|
||||
/// pattern's own tempo.
|
||||
///
|
||||
/// - SeeAlso: ``EventConductor``
|
||||
public enum EventQuantum: Sendable {
|
||||
|
||||
/// Begin at the next service tick — effectively immediately (within the conductor's poll
|
||||
/// granularity), with no grid alignment.
|
||||
case now
|
||||
|
||||
/// Begin on the next whole beat strictly after now.
|
||||
case nextBeat
|
||||
|
||||
/// Begin on the next multiple of `ofBeats` strictly after now — e.g. `4.0` is the next bar in
|
||||
/// 4/4, `2.0` the next half-bar. Must be positive.
|
||||
case nextMultiple(ofBeats: Double)
|
||||
|
||||
/// Begin at an absolute beat on the conductor's timeline. A beat already in the past is due
|
||||
/// immediately and starts at the next service tick.
|
||||
case atBeat(Double)
|
||||
|
||||
/// Begin `ofBeats` beats from now — a relative lead-in. The direct analogue of
|
||||
/// ``ParallelEventPattern/addAfter(beats:eventPattern:)``. A negative value starts now.
|
||||
case afterBeats(Double)
|
||||
|
||||
/// Traps if the quantum carries an invalid parameter. Called by ``EventConductor/add(_:quantize:)``
|
||||
/// on the caller's thread so a bad value surfaces at the call site, not later on the conductor's
|
||||
/// background task. ``targetBeat(from:)`` keeps its own check as a backstop.
|
||||
internal func validate() {
|
||||
switch self {
|
||||
case .now, .nextBeat:
|
||||
break
|
||||
case .nextMultiple(let ofBeats):
|
||||
precondition(ofBeats > 0 && ofBeats.isFinite, "nextMultiple ofBeats must be positive and finite")
|
||||
case .atBeat(let beat):
|
||||
precondition(beat.isFinite, "atBeat must be finite")
|
||||
case .afterBeats(let ofBeats):
|
||||
precondition(ofBeats.isFinite, "afterBeats must be finite")
|
||||
}
|
||||
}
|
||||
|
||||
/// The target beat this quantum resolves to, given the conductor's current beat position.
|
||||
///
|
||||
/// - Parameter beatNow: The conductor clock's current beat at service time.
|
||||
/// - Returns: The beat at which the pattern should enter. The conductor holds the pattern until
|
||||
/// its clock reaches this beat, then starts it.
|
||||
internal func targetBeat(from beatNow: Double) -> Double {
|
||||
switch self {
|
||||
case .now:
|
||||
return beatNow
|
||||
case .nextBeat:
|
||||
return beatNow.rounded(.down) + 1.0
|
||||
case .nextMultiple(let ofBeats):
|
||||
precondition(ofBeats > 0, "nextMultiple ofBeats must be positive")
|
||||
return ((beatNow / ofBeats).rounded(.down) + 1.0) * ofBeats
|
||||
case .atBeat(let beat):
|
||||
return beat
|
||||
case .afterBeats(let ofBeats):
|
||||
return beatNow + max(0.0, ofBeats)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// EventRetriggerable.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Opt-in articulation hook for the single reused voice of a ``MonoEventPattern``.
|
||||
///
|
||||
/// A ``MonoEventPattern`` holds one voice and updates its parameters per event. By default the
|
||||
/// voice is not re-struck between events — it plays continuously with its parameters gliding. A
|
||||
/// voice that conforms to `EventRetriggerable` additionally re-articulates — closing and reopening
|
||||
/// its envelope — on each event after the first: ``MonoEventPattern`` calls ``retrigger()`` on
|
||||
/// every event *after* the first (the first is articulated by `build()` when the voice is added),
|
||||
/// so the voice can restart its amplitude envelope for a fresh attack.
|
||||
///
|
||||
/// Conformance is optional. A ``MonoEventPattern`` voice that does not conform simply has its
|
||||
/// parameters updated each event with no re-articulation.
|
||||
///
|
||||
/// - SeeAlso: ``MonoEventPattern``, ``EventSustainAware``
|
||||
public protocol EventRetriggerable: Synthesizer {
|
||||
|
||||
/// Re-articulates the voice for a new event — typically restarting its amplitude envelope.
|
||||
///
|
||||
/// Called on the main actor, once per event after the first, before the event's duration is
|
||||
/// waited out. When the voice also conforms to ``EventSustainAware``, its
|
||||
/// ``EventSustainAware/setEventSustain(seconds:)`` is called *before* `retrigger()`, so an
|
||||
/// envelope restarted here is already sized to this event's sustain.
|
||||
@MainActor func retrigger()
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// EventStream.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Minutes-to-seconds divisor for the beats→seconds conversion. Module scope (shared by the
|
||||
/// event-stream variants) because a `static` stored property is not allowed on a generic type.
|
||||
internal let eventStreamSecondsPerMinute: Double = 60.0
|
||||
|
||||
/// The pure per-event pull logic shared by ``EventPattern`` and its variants.
|
||||
///
|
||||
/// An `EventStream` holds the voice factory, the key-path bindings, and the duration pattern,
|
||||
/// and yields one resolved event at a time via ``next()``: it makes a voice, writes every
|
||||
/// bound parameter, hands the voice its sustain, and returns it with the event's timing.
|
||||
/// Exhaustion of the duration pattern or **any** binding ends the current pass; `repeats`
|
||||
/// replays the whole bound set (resetting the patterns between).
|
||||
///
|
||||
/// This type owns no threads and touches no engine — it is the deterministic core that the
|
||||
/// background playback loop drives through `ctx.onMain`. Keeping it separate makes the event
|
||||
/// logic directly unit-testable on the main actor, and lets `MonoEventPattern` /
|
||||
/// `ParallelEventPattern` reuse it.
|
||||
///
|
||||
/// Not thread-safe: pulled by exactly one consumer, on the main actor.
|
||||
///
|
||||
/// `@unchecked Sendable`: the playback loop runs on a background task that *holds* the stream
|
||||
/// reference but only ever calls ``next()`` inside a `ctx.onMain` hop — every access to the
|
||||
/// stream's mutable state happens on the main actor. The reference crosses the actor boundary;
|
||||
/// the state it guards does not.
|
||||
internal final class EventStream<V: Synthesizer>: @unchecked Sendable {
|
||||
|
||||
/// One resolved event: the configured voice, its timing (in beats), and how it is reaped.
|
||||
struct Event {
|
||||
let voice: V
|
||||
let delta: Double
|
||||
let sustain: Double
|
||||
/// The voice's gate node when it conforms to ``EventGated``, else `nil`. The playback loop
|
||||
/// opens it at add and schedules it to `0` after `sustain` beats (gate note-off).
|
||||
let gate: ParameterNode?
|
||||
/// `true` when the voice frees itself (``EventGated`` or ``EventSustainAware``), so the
|
||||
/// loop must **not** hard-remove it; `false` for a plain voice, which is removed after
|
||||
/// `sustain + releaseTail`.
|
||||
let selfFreeing: Bool
|
||||
}
|
||||
|
||||
private let _make: @MainActor () -> V
|
||||
private let _bindings: [EventBinding<V>]
|
||||
private let _durPattern: Pattern<Double>
|
||||
private let _legato: Double
|
||||
private let _tempo: Double
|
||||
private var _repeatsLeft: Int
|
||||
|
||||
/// - Parameters:
|
||||
/// - make: Voice factory, called once per event on the main actor.
|
||||
/// - bindings: Key-path/pattern bindings applied in order each event.
|
||||
/// - durPattern: Duration (delta) pattern in beats.
|
||||
/// - legato: Sustain fraction of each duration (`sustain = delta * legato`).
|
||||
/// - repeats: Number of passes over the whole bound set (`1` = once).
|
||||
/// - tempo: Tempo in BPM, used to convert sustain beats to seconds.
|
||||
init(
|
||||
make: @escaping @MainActor () -> V,
|
||||
bindings: [EventBinding<V>],
|
||||
durPattern: Pattern<Double>,
|
||||
legato: Double,
|
||||
repeats: Int,
|
||||
tempo: Double
|
||||
) {
|
||||
_make = make
|
||||
_bindings = bindings
|
||||
_durPattern = durPattern
|
||||
_legato = legato
|
||||
_tempo = tempo
|
||||
_repeatsLeft = repeats
|
||||
}
|
||||
|
||||
/// Tracks whether the current pass yielded any event, so a pass that produces nothing
|
||||
/// ends the stream instead of looping (guards against an empty pattern with a huge
|
||||
/// `repeats`, which would otherwise spin on the main actor).
|
||||
private var _producedThisPass: Bool = false
|
||||
|
||||
/// Returns the next resolved event, or `nil` when the stream is fully exhausted (all
|
||||
/// passes complete, a pattern ran out on the final pass, or a whole pass produced nothing).
|
||||
@MainActor func next() -> Event? {
|
||||
while _repeatsLeft > 0 {
|
||||
if let event: Event = pullOne() {
|
||||
_producedThisPass = true
|
||||
return event
|
||||
}
|
||||
// Current pass exhausted. A pass that yielded nothing ends the stream — otherwise
|
||||
// an empty pattern with a large `repeats` would loop with no progress.
|
||||
if !_producedThisPass { return nil }
|
||||
_repeatsLeft -= 1
|
||||
if _repeatsLeft > 0 {
|
||||
resetPatterns()
|
||||
_producedThisPass = false
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Pulls one event from the current pass, or `nil` if a pattern is exhausted.
|
||||
///
|
||||
/// Binding values are pulled **before** the voice is made, so an exhausted pattern does
|
||||
/// not leave a constructed-then-discarded voice.
|
||||
@MainActor private func pullOne() -> Event? {
|
||||
guard let delta: Double = _durPattern.next() else { return nil }
|
||||
var values: [Double] = []
|
||||
values.reserveCapacity(_bindings.count)
|
||||
for binding: EventBinding<V> in _bindings {
|
||||
guard let value: Double = binding.nextValue() else { return nil }
|
||||
values.append(value)
|
||||
}
|
||||
let voice: V = _make()
|
||||
for (binding, value): (EventBinding<V>, Double) in zip(_bindings, values) {
|
||||
binding.write(value, to: voice)
|
||||
}
|
||||
// `EventPattern.legato(_:)` preconditions `legato >= 0`; `max(0, …)` keeps the
|
||||
// `setEventSustain` "always ≥ 0" contract defensively for any other construction path.
|
||||
let sustain: Double = max(0.0, delta * _legato)
|
||||
let secondsPerBeat: Double = eventStreamSecondsPerMinute / _tempo
|
||||
let gated: EventGated? = voice as? EventGated
|
||||
let gateNode: ParameterNode? = gated?.eventGate
|
||||
// Gate wins: when a voice is gated, the pattern's scheduled gate note-off drives its
|
||||
// release, so a voice that is *also* `EventSustainAware` is not self-timed as well — the two
|
||||
// release mechanisms never both fire. A non-gated sustain-aware voice self-times as before.
|
||||
let aware: EventSustainAware? = (gated == nil) ? (voice as? EventSustainAware) : nil
|
||||
aware?.setEventSustain(seconds: sustain * secondsPerBeat)
|
||||
// A gated or sustain-aware voice frees itself (gate release / self-timed envelope +
|
||||
// `doneAction`); the loop must not hard-remove it. A plain voice has neither and is reaped.
|
||||
let selfFreeing: Bool = gated != nil || aware != nil
|
||||
return Event(
|
||||
voice: voice,
|
||||
delta: delta,
|
||||
sustain: sustain,
|
||||
gate: gateNode,
|
||||
selfFreeing: selfFreeing
|
||||
)
|
||||
}
|
||||
|
||||
/// Resolves the next event and erases its voice type for the background playback loop, so the
|
||||
/// `@Sendable` task body never names the generic `V`. See ``ResolvedEvent``.
|
||||
@MainActor func nextResolved() -> ResolvedEvent? {
|
||||
guard let e: Event = next() else { return nil }
|
||||
return ResolvedEvent(
|
||||
voice: e.voice,
|
||||
delta: e.delta,
|
||||
sustain: e.sustain,
|
||||
gate: e.gate,
|
||||
selfFreeing: e.selfFreeing
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the duration and all bound patterns to their initial state.
|
||||
@MainActor private func resetPatterns() {
|
||||
_durPattern.reset()
|
||||
for binding: EventBinding<V> in _bindings {
|
||||
binding.reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// EventSustainAware.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Opt-in refinement a voice adopts so an event pattern can tell it how long the current note
|
||||
/// should sound.
|
||||
///
|
||||
/// An event pattern binds parameter values and handles each voice's removal, but it does not
|
||||
/// own the voice's amplitude envelope — the voice does. A voice that conforms to
|
||||
/// `EventSustainAware` is handed the computed sustain (in seconds) for each event, so it can
|
||||
/// shape or trigger a fixed-duration, self-freeing envelope that matches the pattern's timing.
|
||||
/// This keeps the division of labour central to the event-driven system: the pattern owns timing
|
||||
/// and merely supplies the note's sustain; the voice owns its envelope.
|
||||
///
|
||||
/// Conformance is optional. A voice that does not conform still plays — ``EventPattern`` simply
|
||||
/// removes it after `sustain + releaseTail` beats with no envelope hand-off.
|
||||
///
|
||||
/// `EventSustainAware` and ``EventGated`` are **alternative** release mechanisms — a self-timed
|
||||
/// envelope versus a pattern-driven gate note-off. A voice may conform to both, but the **gate
|
||||
/// wins**: when a voice is also ``EventGated``, the pattern drives release through the gate and
|
||||
/// does *not* call ``setEventSustain(seconds:)``, so the two never both fire. `setEventSustain`
|
||||
/// is therefore only invoked on a voice that is not gated.
|
||||
///
|
||||
/// - SeeAlso: ``EventPattern``, ``MonoEventPattern``, ``EventGated``
|
||||
public protocol EventSustainAware: Synthesizer {
|
||||
|
||||
/// Informs the voice how long this note should sustain, in seconds.
|
||||
///
|
||||
/// Called on the main thread. ``EventPattern`` calls it once per voice, just before the
|
||||
/// voice is added to the engine. ``MonoEventPattern`` calls it once per event — before each
|
||||
/// `retrigger()` — on the single persistent voice, so it may already be in the engine. The
|
||||
/// voice typically uses this to configure a fixed-duration envelope whose `doneAction` frees
|
||||
/// or re-articulates it, so it terminates on its own schedule.
|
||||
///
|
||||
/// - Parameter seconds: Note duration in seconds (`sustain` beats converted at the
|
||||
/// pattern's tempo). Always `≥ 0`.
|
||||
@MainActor func setEventSustain(seconds: Double)
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
// MonoEventPattern.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Default fraction of each event's duration for which the voice sounds.
|
||||
private let monoEventPatternDefaultLegato: Double = 0.9
|
||||
|
||||
/// Default playback tempo in beats per minute.
|
||||
private let monoEventPatternDefaultTempo: Double = 120.0
|
||||
|
||||
/// The monophonic event-driven player: binds named value ``Pattern``s to **one persistent
|
||||
/// voice**, updating its parameters per event instead of spawning a new voice each time.
|
||||
///
|
||||
/// The voice is made once (on the main thread) and added to the engine once. Each event pulls
|
||||
/// one value from every bound pattern plus the duration pattern, writes them into the voice's
|
||||
/// `@LiveParam` parameters, optionally re-articulates the voice (``EventRetriggerable``), then
|
||||
/// waits the event's duration. The stream ends when the duration pattern or **any** bound
|
||||
/// pattern is exhausted (the same rule as ``EventPattern``), optionally repeating the whole
|
||||
/// bound set. When the stream ends **or** playback is stopped, a voice conforming to ``EventGated``
|
||||
/// gets a note-off (its gate is closed) so its envelope release plays out and frees it; any other
|
||||
/// voice is removed after ``releaseTail(_:)`` beats.
|
||||
///
|
||||
/// A voice conforming to ``EventRetriggerable`` is re-struck (``EventRetriggerable/retrigger()``)
|
||||
/// on every event after the first — per-event articulation. A voice that does not conform plays
|
||||
/// continuously with its parameters gliding per event — no re-strike.
|
||||
///
|
||||
/// > Important: unlike ``EventPattern``, the voice here is **persistent** — added once and reused
|
||||
/// > for every event. Give it a sustaining envelope that holds across events. The cleanest shape is
|
||||
/// > an ``EventGated`` voice: a gated `EnvelopeGen` with a `releaseNode` holds open while the gate
|
||||
/// > is up and frees via `doneAction: .freeNode` only when the gate closes at stream end, and
|
||||
/// > ``EventRetriggerable/retrigger()`` re-strikes it per event. What you must **not** give it is an
|
||||
/// > *ungated* one-shot self-freeing envelope: a voice that frees itself after the first event's
|
||||
/// > sustain is gone before the next event, and the stream falls silent. Those belong with
|
||||
/// > ``EventPattern``, which spawns a fresh voice per event.
|
||||
///
|
||||
/// ```swift
|
||||
/// let handle: EventPatternHandle = MonoEventPattern(make: { LeadVoice() })
|
||||
/// .bind(\.freq, .sequence([440.0, 550.0, 660.0]))
|
||||
/// .dur(.sequence([0.25, 0.25, 0.5]))
|
||||
/// .tempo(132.0)
|
||||
/// .play(on: engine)
|
||||
/// ```
|
||||
///
|
||||
/// Playback runs on a background `LyrebirdTask`; voice construction and parameter writes hop to
|
||||
/// the main thread. The returned ``EventPatternHandle`` stops playback or waits for a finite
|
||||
/// stream to finish.
|
||||
///
|
||||
/// Not thread-safe: configure (`bind`/`dur`/…) before `play`, and drive a single `play` at a
|
||||
/// time. Its patterns are pulled by exactly one playback task.
|
||||
///
|
||||
/// - SeeAlso: ``EventPattern``, ``EventGated``, ``EventRetriggerable``, ``EventSustainAware``, ``EventPatternHandle``
|
||||
public final class MonoEventPattern<V: Synthesizer>: @unchecked Sendable {
|
||||
|
||||
/// Factory for the single persistent voice. Called once, on the main thread.
|
||||
private let _make: @MainActor () -> V
|
||||
|
||||
/// `keyPath → Pattern` bindings, applied in order each event.
|
||||
private var _bindings: [EventBinding<V>] = []
|
||||
|
||||
/// Duration (delta) pattern in beats. Defaults to an infinite stream of `1.0`.
|
||||
private var _durPattern: Pattern<Double> = Pattern<Double>.sequence([1.0])
|
||||
|
||||
/// Fraction of each duration the voice sustains (`sustain = delta * legato`), handed to a
|
||||
/// voice conforming to ``EventSustainAware``.
|
||||
private var _legato: Double = monoEventPatternDefaultLegato
|
||||
|
||||
/// Extra beats of grace after the final event before a **non-gated** voice is removed, so its
|
||||
/// release tail is not hard-cut. Unused by an ``EventGated`` voice, which is note-off'd via its
|
||||
/// gate and frees itself.
|
||||
private var _releaseTail: Double = 0.0
|
||||
|
||||
/// Number of times to play the whole bound set (resetting between). `1` = once.
|
||||
private var _repeats: Int = 1
|
||||
|
||||
/// Playback tempo in beats per minute.
|
||||
private var _tempo: Double = monoEventPatternDefaultTempo
|
||||
|
||||
/// Creates a monophonic event pattern.
|
||||
///
|
||||
/// - Parameter make: Factory returning the single persistent voice, made once on the main
|
||||
/// thread. For a fresh voice per event, use ``EventPattern`` instead.
|
||||
public init(make: @escaping @MainActor () -> V) {
|
||||
_make = make
|
||||
}
|
||||
|
||||
// MARK: - Builder
|
||||
|
||||
/// Binds a voice parameter to a value pattern.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - keyPath: Writable key path into a `@LiveParam Double` on the voice (`\.freq`).
|
||||
/// - pattern: Value source; one value is pulled per event.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func bind(
|
||||
_ keyPath: ReferenceWritableKeyPath<V, Double>,
|
||||
_ pattern: Pattern<Double>
|
||||
) -> Self {
|
||||
_bindings.append(EventBinding(keyPath: keyPath, pattern: pattern))
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets the duration (delta) pattern, in beats. One value is pulled per event; the stream
|
||||
/// ends if it is exhausted.
|
||||
///
|
||||
/// - Parameter pattern: Beats-per-event value source.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func dur(_ pattern: Pattern<Double>) -> Self {
|
||||
_durPattern = pattern
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets the legato factor: the sustain handed to an ``EventSustainAware`` voice is
|
||||
/// `delta * legato` beats.
|
||||
///
|
||||
/// - Parameter value: Sustain fraction of each duration. Must be `≥ 0`. Defaults to `0.9`.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func legato(_ value: Double) -> Self {
|
||||
precondition(value >= 0, "legato must be non-negative")
|
||||
_legato = value
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets extra beats of grace after the final event before a **non-gated** voice is removed, so
|
||||
/// its envelope release tail is not cut short.
|
||||
///
|
||||
/// Unused by an ``EventGated`` voice: that voice is note-off'd via its gate at stream end and
|
||||
/// frees itself, so its release is never hard-cut regardless of this value.
|
||||
///
|
||||
/// - Parameter beats: Grace in beats. Defaults to `0.0`.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func releaseTail(_ beats: Double) -> Self {
|
||||
_releaseTail = beats
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets how many times to play the whole bound set (resetting all patterns between).
|
||||
///
|
||||
/// - Parameter count: Number of passes. `1` plays once; pass `Int.max` for effectively
|
||||
/// endless playback. Values below `1` play nothing.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func repeats(_ count: Int) -> Self {
|
||||
_repeats = count
|
||||
return self
|
||||
}
|
||||
|
||||
/// Sets the playback tempo.
|
||||
///
|
||||
/// - Parameter bpm: Beats per minute. Must be positive. Defaults to `120.0`.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func tempo(_ bpm: Double) -> Self {
|
||||
precondition(bpm > 0, "tempo must be positive")
|
||||
_tempo = bpm
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - Play
|
||||
|
||||
/// Starts playback on a background task and returns a handle to control it.
|
||||
///
|
||||
/// Makes the persistent voice and snapshots the current configuration into a
|
||||
/// `MonoEventStream` **before** starting the task, so later builder calls cannot race with
|
||||
/// the running stream.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: Engine the voice is added to.
|
||||
/// - beats: Lead-in before the first event, in beats at this pattern's tempo. `0` starts
|
||||
/// immediately. The task is live (waiting) for the lead-in, so `stop()` works during it.
|
||||
/// - Returns: A handle to stop playback or await a finite stream.
|
||||
@discardableResult
|
||||
@MainActor public func play(
|
||||
on engine: SynthesisEngine,
|
||||
startAfterBeats beats: Double
|
||||
) -> EventPatternHandle {
|
||||
let task: LyrebirdTask = makeTask(stream: makeEventStream(), startOffsetBeats: beats)
|
||||
task.start(engine: engine)
|
||||
return EventPatternHandle(tasks: [task])
|
||||
}
|
||||
|
||||
/// Makes the persistent voice and builds a fresh `MonoEventStream` from the current
|
||||
/// configuration. Each call makes an independent voice and stream (patterns are shared by
|
||||
/// reference, so reuse is single-consumer).
|
||||
@MainActor internal func makeEventStream() -> MonoEventStream<V> {
|
||||
MonoEventStream(
|
||||
voice: _make(),
|
||||
bindings: _bindings,
|
||||
durPattern: _durPattern,
|
||||
legato: _legato,
|
||||
repeats: _repeats,
|
||||
tempo: _tempo
|
||||
)
|
||||
}
|
||||
|
||||
/// Builds the driving task for a pre-snapshot `stream`, without starting it. The body
|
||||
/// captures the snapshot, not `self`, so builder mutation after `play` cannot affect it.
|
||||
/// The voice is added on the first event and removed once the stream ends.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - stream: The pre-snapshot event stream to drive.
|
||||
/// - startOffsetBeats: Lead-in in beats before the first event (`0` = none).
|
||||
@MainActor internal func makeTask(
|
||||
stream: MonoEventStream<V>,
|
||||
startOffsetBeats: Double
|
||||
) -> LyrebirdTask {
|
||||
let tempoBPM: Double = _tempo
|
||||
let releaseTailBeats: Double = _releaseTail
|
||||
return LyrebirdTask { ctx in
|
||||
ctx.tempo = tempoBPM
|
||||
// Lead-in before the first event (0 = none). Thrown `stopped` here skips straight to
|
||||
// the defer, which leaks nothing — the voice has not been added yet.
|
||||
if startOffsetBeats > 0 {
|
||||
try ctx.wait(beats: startOffsetBeats)
|
||||
}
|
||||
// The voice is carried on each event (type-erased to `any Synthesizer`) rather than
|
||||
// captured from outside the `@Sendable` body — the body must not name the non-Sendable
|
||||
// generic `V`. It is the same instance every event.
|
||||
var addedVoice: (any Synthesizer)? = nil
|
||||
// The persistent voice's gate node, captured on the first event when it is EventGated.
|
||||
var gateNode: ParameterNode? = nil
|
||||
// Tear the voice down when the body exits — on normal completion *and* when `stop()`
|
||||
// makes `ctx.wait` throw `LyrebirdRoutineError.stopped`. A trailing statement after
|
||||
// the loop would be skipped on the throw, leaking the persistent voice.
|
||||
defer {
|
||||
if let gate: ParameterNode = gateNode {
|
||||
// Gated voice: close the gate so its envelope release plays out and frees it
|
||||
// (no hard-remove, so the release is not cut). Atomic store, safe on this thread.
|
||||
gate.value = 0.0
|
||||
} else if let voice: any Synthesizer = addedVoice {
|
||||
// Non-gated voice: reap after its tail.
|
||||
ctx.remove(voice, afterBeats: releaseTailBeats)
|
||||
}
|
||||
}
|
||||
while let event: ResolvedEvent = ctx.onMain({ stream.nextResolved() }) {
|
||||
if addedVoice == nil {
|
||||
ctx.add(event.voice)
|
||||
addedVoice = event.voice
|
||||
gateNode = event.gate
|
||||
}
|
||||
try ctx.wait(beats: event.delta)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension MonoEventPattern: EventPatternPlayable {}
|
||||
@@ -0,0 +1,157 @@
|
||||
// MonoEventStream.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// The pure per-event pull logic for ``MonoEventPattern`` — the single-voice counterpart of
|
||||
/// `EventStream`.
|
||||
///
|
||||
/// Unlike `EventStream`, which makes a fresh voice per event, a `MonoEventStream` writes each
|
||||
/// event's values into **one persistent voice** (created once, before playback). ``next()``
|
||||
/// pulls one value from the duration pattern and every binding, writes them into the voice,
|
||||
/// re-articulates the voice on each event after the first (when it conforms to
|
||||
/// ``EventRetriggerable``), hands it the event sustain (when it conforms to
|
||||
/// ``EventSustainAware``), and returns the event timing. Exhaustion of the duration pattern or
|
||||
/// **any** binding ends the current pass; `repeats` replays the whole bound set.
|
||||
///
|
||||
/// This type owns no threads and touches no engine — it is the deterministic core the
|
||||
/// background playback loop drives through `ctx.onMain`, directly unit-testable on the main
|
||||
/// actor. The repeat/exhaustion bookkeeping mirrors `EventStream`; the only difference is that
|
||||
/// values are written into the reused voice rather than a freshly made one.
|
||||
///
|
||||
/// Not thread-safe: pulled by exactly one consumer, on the main actor.
|
||||
///
|
||||
/// `@unchecked Sendable`: the playback loop runs on a background task that *holds* the stream
|
||||
/// reference but only ever calls ``next()`` inside a `ctx.onMain` hop — every access to the
|
||||
/// stream's mutable state (and to the voice) happens on the main actor. The reference crosses
|
||||
/// the actor boundary; the state it guards does not.
|
||||
internal final class MonoEventStream<V: Synthesizer>: @unchecked Sendable {
|
||||
|
||||
/// One resolved event: the persistent voice (the same instance every event) and the beats to
|
||||
/// wait before the next event. The voice is carried here so the playback loop can add/remove
|
||||
/// it without capturing a non-`Sendable` value across the task boundary. Sustain is applied
|
||||
/// to the voice inside ``next()`` (via `setEventSustain`), so it is not carried out.
|
||||
struct Event {
|
||||
let voice: V
|
||||
let delta: Double
|
||||
/// The persistent voice's gate node when it conforms to ``EventGated``, else `nil`. The
|
||||
/// same node every event (one persistent voice); the playback loop reads it once, on the
|
||||
/// first event, to drive the end-of-stream note-off.
|
||||
let gate: ParameterNode?
|
||||
}
|
||||
|
||||
/// The single persistent voice every event writes into.
|
||||
let voice: V
|
||||
|
||||
private let _bindings: [EventBinding<V>]
|
||||
private let _durPattern: Pattern<Double>
|
||||
private let _legato: Double
|
||||
private let _tempo: Double
|
||||
private var _repeatsLeft: Int
|
||||
|
||||
/// `false` until the first event has been produced, so re-articulation is skipped on the
|
||||
/// first event (the voice's `build()` articulates it when it is added).
|
||||
private var _hasArticulated: Bool = false
|
||||
|
||||
/// Tracks whether the current pass yielded any event, so a pass that produces nothing ends
|
||||
/// the stream instead of looping (guards an empty pattern with a huge `repeats`).
|
||||
private var _producedThisPass: Bool = false
|
||||
|
||||
/// - Parameters:
|
||||
/// - voice: The persistent voice every event writes into. Created on the main actor.
|
||||
/// - bindings: Key-path/pattern bindings applied in order each event.
|
||||
/// - durPattern: Duration (delta) pattern in beats.
|
||||
/// - legato: Sustain fraction of each duration (`sustain = delta * legato`).
|
||||
/// - repeats: Number of passes over the whole bound set (`1` = once).
|
||||
/// - tempo: Tempo in BPM, used to convert sustain beats to seconds.
|
||||
init(
|
||||
voice: V,
|
||||
bindings: [EventBinding<V>],
|
||||
durPattern: Pattern<Double>,
|
||||
legato: Double,
|
||||
repeats: Int,
|
||||
tempo: Double
|
||||
) {
|
||||
self.voice = voice
|
||||
_bindings = bindings
|
||||
_durPattern = durPattern
|
||||
_legato = legato
|
||||
_tempo = tempo
|
||||
_repeatsLeft = repeats
|
||||
}
|
||||
|
||||
/// Returns the next resolved event, or `nil` when the stream is fully exhausted (all passes
|
||||
/// complete, a pattern ran out on the final pass, or a whole pass produced nothing).
|
||||
@MainActor func next() -> Event? {
|
||||
while _repeatsLeft > 0 {
|
||||
if let event: Event = pullOne() {
|
||||
_producedThisPass = true
|
||||
return event
|
||||
}
|
||||
if !_producedThisPass { return nil }
|
||||
_repeatsLeft -= 1
|
||||
if _repeatsLeft > 0 {
|
||||
resetPatterns()
|
||||
_producedThisPass = false
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Pulls one event from the current pass and writes it into the persistent voice, or `nil`
|
||||
/// if a pattern is exhausted. Values are pulled **before** they are written, so an exhausted
|
||||
/// pattern leaves the voice's parameters untouched for that aborted event.
|
||||
@MainActor private func pullOne() -> Event? {
|
||||
guard let delta: Double = _durPattern.next() else { return nil }
|
||||
var values: [Double] = []
|
||||
values.reserveCapacity(_bindings.count)
|
||||
for binding: EventBinding<V> in _bindings {
|
||||
guard let value: Double = binding.nextValue() else { return nil }
|
||||
values.append(value)
|
||||
}
|
||||
for (binding, value): (EventBinding<V>, Double) in zip(_bindings, values) {
|
||||
binding.write(value, to: voice)
|
||||
}
|
||||
let sustain: Double = max(0.0, delta * _legato)
|
||||
let secondsPerBeat: Double = eventStreamSecondsPerMinute / _tempo
|
||||
let gateNode: ParameterNode? = (voice as? EventGated)?.eventGate
|
||||
// Gate wins: a gated voice releases via its gate note-off, so it is not also self-timed even
|
||||
// if it conforms to `EventSustainAware`. For a non-gated sustain-aware voice, hand over this
|
||||
// event's sustain *before* re-articulating, so a voice that sizes its restarted envelope to
|
||||
// the sustain uses this event's value, not the previous one's.
|
||||
if gateNode == nil, let aware: EventSustainAware = voice as? EventSustainAware {
|
||||
aware.setEventSustain(seconds: sustain * secondsPerBeat)
|
||||
}
|
||||
// Re-articulate every event after the first; the first is articulated by `build()` when
|
||||
// the voice is added to the engine.
|
||||
if _hasArticulated, let retriggerable: EventRetriggerable = voice as? EventRetriggerable {
|
||||
retriggerable.retrigger()
|
||||
}
|
||||
_hasArticulated = true
|
||||
return Event(voice: voice, delta: delta, gate: gateNode)
|
||||
}
|
||||
|
||||
/// Resolves the next event and erases its voice type for the background playback loop, so the
|
||||
/// `@Sendable` task body never names the generic `V`. Mono uses only `voice`, `delta` and
|
||||
/// `gate`; `sustain` is already applied to the voice inside ``next()`` and `selfFreeing` is
|
||||
/// unused here. See ``ResolvedEvent``.
|
||||
@MainActor func nextResolved() -> ResolvedEvent? {
|
||||
guard let e: Event = next() else { return nil }
|
||||
return ResolvedEvent(
|
||||
voice: e.voice,
|
||||
delta: e.delta,
|
||||
sustain: 0.0,
|
||||
gate: e.gate,
|
||||
selfFreeing: false
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns the duration and all bound patterns to their initial state.
|
||||
@MainActor private func resetPatterns() {
|
||||
_durPattern.reset()
|
||||
for binding: EventBinding<V> in _bindings {
|
||||
binding.reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// ParallelEventPattern.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Plays several event patterns at once — Lyrebird's parallel event-driven player.
|
||||
///
|
||||
/// Holds a set of children — any mix of ``EventPattern``, ``MonoEventPattern`` and even nested
|
||||
/// `ParallelEventPattern`s (anything conforming to ``EventPatternPlayable``) — and starts each
|
||||
/// on its own background `LyrebirdTask` when `play(on:)` is called. The children are started back to back on the
|
||||
/// main thread and share **no common clock**: each runs its own tempo and its own relative
|
||||
/// `wait(beats:)` chain. Children with the same tempo begin within thread-start latency of each
|
||||
/// other (sub-millisecond in practice) but are not re-synchronised afterwards, so small
|
||||
/// per-event timing drift can accumulate over long runs; children with different tempos run
|
||||
/// polytemporally. The returned ``EventPatternHandle`` controls them all at once:
|
||||
/// ``EventPatternHandle/stop()`` stops every child, ``EventPatternHandle/isPlaying`` is `true`
|
||||
/// while any child is still live, and ``EventPatternHandle/waitUntilComplete(releasePadding:)``
|
||||
/// returns once all finite children have finished.
|
||||
///
|
||||
/// A child added with ``addAfter(beats:eventPattern:)`` enters a fixed number of beats into the
|
||||
/// group's timeline: because every child is launched from the one `play` call and shares that
|
||||
/// start instant, the lead-in staggers its entry on the group's start grid. This is a static,
|
||||
/// composed-before-`play` stagger — see *Not thread-safe* below for why live insertion is not
|
||||
/// supported here.
|
||||
///
|
||||
/// ```swift
|
||||
/// let lead: MonoEventPattern<LeadVoice> = MonoEventPattern(make: { LeadVoice() })
|
||||
/// .bind(\.freq, .sequence([440.0, 550.0, 660.0]))
|
||||
/// .dur(.sequence([0.5]))
|
||||
///
|
||||
/// let bass: EventPattern<BassVoice> = EventPattern(make: { BassVoice() })
|
||||
/// .bind(\.freq, .sequence([55.0, 55.0, 82.5, 55.0]))
|
||||
/// .dur(.sequence([1.0]))
|
||||
///
|
||||
/// let handle: EventPatternHandle = ParallelEventPattern()
|
||||
/// .add(lead) // enters with the group
|
||||
/// .addAfter(beats: 2.0, eventPattern: bass) // enters two beats in
|
||||
/// .play(on: engine)
|
||||
/// ```
|
||||
///
|
||||
/// Not thread-safe: compose all children (`add` / `addAfter`) before `play`, and drive a single
|
||||
/// `play` at a time. Each child's patterns are pulled by exactly one playback task. There is no
|
||||
/// supported way to add a child **after** `play` — the group is a fire-once start, not a live,
|
||||
/// beat-quantised conductor you push patterns into from a UI, OSC or MIDI callback.
|
||||
///
|
||||
/// - SeeAlso: ``EventPatternPlayable``, ``EventPattern``, ``MonoEventPattern``, ``EventPatternHandle``
|
||||
public final class ParallelEventPattern: @unchecked Sendable {
|
||||
|
||||
/// The child patterns played in parallel, in the order added, each with the beats of lead-in
|
||||
/// before it enters (`0` = starts with the group).
|
||||
private var _children: [(offset: Double, child: any EventPatternPlayable)]
|
||||
|
||||
/// Creates a parallel pattern with no children. Add them with ``add(_:)`` or
|
||||
/// ``addAfter(beats:eventPattern:)``.
|
||||
public init() {
|
||||
_children = []
|
||||
}
|
||||
|
||||
/// Creates a parallel pattern over the given children, all entering with the group.
|
||||
///
|
||||
/// - Parameter children: The patterns to play at once.
|
||||
public init(_ children: [any EventPatternPlayable]) {
|
||||
_children = children.map { (0.0, $0) }
|
||||
}
|
||||
|
||||
/// Appends a child pattern that enters with the group.
|
||||
///
|
||||
/// - Parameter child: The pattern to play alongside the others.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func add(_ child: any EventPatternPlayable) -> Self {
|
||||
_children.append((0.0, child))
|
||||
return self
|
||||
}
|
||||
|
||||
/// Appends a child pattern that enters `beats` beats after the group starts.
|
||||
///
|
||||
/// All children are launched together when ``play(on:startAfterBeats:)`` is called and share
|
||||
/// that one start instant; `beats` is a lead-in the child waits out (at its own tempo) before
|
||||
/// its first event, so a child added with `addAfter(beats: 2)` enters two beats into the
|
||||
/// group's timeline. This is a **fixed, pre-`play` stagger** — not a live, beat-quantised
|
||||
/// insertion while the group is already running.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - beats: Lead-in before the child's first event, in beats at the child's tempo. Must be
|
||||
/// `≥ 0`.
|
||||
/// - eventPattern: The pattern to play, entering after the lead-in.
|
||||
/// - Returns: `self`, for chaining.
|
||||
@discardableResult
|
||||
public func addAfter(beats: Double, eventPattern: any EventPatternPlayable) -> Self {
|
||||
precondition(beats >= 0 && beats.isFinite, "addAfter beats must be non-negative and finite")
|
||||
_children.append((beats, eventPattern))
|
||||
return self
|
||||
}
|
||||
|
||||
/// Starts every child on `engine` and returns one handle controlling them all.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: Engine the children's voices are added to.
|
||||
/// - beats: Lead-in applied to the whole group before any child enters, in beats. Each
|
||||
/// child's own ``addAfter(beats:eventPattern:)`` offset is added on top. `0` starts now.
|
||||
/// - Returns: A handle whose ``EventPatternHandle/stop()`` stops every child and whose
|
||||
/// ``EventPatternHandle/waitUntilComplete(releasePadding:)`` returns once all finite children
|
||||
/// finish.
|
||||
/// - Precondition: at least one child has been added; an empty pattern traps.
|
||||
@discardableResult
|
||||
@MainActor public func play(
|
||||
on engine: SynthesisEngine,
|
||||
startAfterBeats beats: Double
|
||||
) -> EventPatternHandle {
|
||||
precondition(!_children.isEmpty, "ParallelEventPattern requires at least one child")
|
||||
let handles: [EventPatternHandle] = _children.map {
|
||||
$0.child.play(on: engine, startAfterBeats: beats + $0.offset)
|
||||
}
|
||||
return EventPatternHandle(merging: handles)
|
||||
}
|
||||
}
|
||||
|
||||
// A ParallelEventPattern is itself playable, so one may be nested as a child of another
|
||||
// (nested parallel groups). Its merged handle already wraps at least one task.
|
||||
extension ParallelEventPattern: EventPatternPlayable {}
|
||||
@@ -0,0 +1,36 @@
|
||||
// ResolvedEvent.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// A type-erased view of one resolved event, handed to the background playback loop.
|
||||
///
|
||||
/// The playback loops in ``EventPattern`` and ``MonoEventPattern`` run inside a `@Sendable`
|
||||
/// `LyrebirdTask` body. Naming the generic voice type `V` there — for example annotating an
|
||||
/// `EventStream<V>.Event` binding, or an `addedVoice: V?` — captures the non-`Sendable` metatype
|
||||
/// `V.Type` in that isolated closure, which Swift's concurrency checking flags. `ResolvedEvent`
|
||||
/// erases the voice to `any Synthesizer`, so the loop never mentions `V`: the stream (captured as
|
||||
/// an instance, which is safe) resolves each event on the main actor and hands back this
|
||||
/// non-generic value, which carries everything the loop needs.
|
||||
///
|
||||
/// `MonoEventPattern` uses only `voice`, `delta` and `gate`; `sustain` and `selfFreeing` are
|
||||
/// meaningful only to the polyphonic ``EventPattern`` reaping paths.
|
||||
struct ResolvedEvent {
|
||||
|
||||
/// The configured voice, type-erased.
|
||||
let voice: any Synthesizer
|
||||
|
||||
/// Beats to wait before the next event.
|
||||
let delta: Double
|
||||
|
||||
/// Beats the voice sounds (`delta * legato`). Drives the `EventGated` note-off time.
|
||||
let sustain: Double
|
||||
|
||||
/// The voice's gate node when it conforms to `EventGated`, else `nil`.
|
||||
let gate: ParameterNode?
|
||||
|
||||
/// `true` when the voice frees itself (`EventGated` or `EventSustainAware`), so it is not
|
||||
/// hard-removed.
|
||||
let selfFreeing: Bool
|
||||
}
|
||||
@@ -64,6 +64,11 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
|
||||
// `elapsedSamples` value at the most recent tempo change.
|
||||
private var _sampleTempoChangeSamples: SampleTime = 0
|
||||
|
||||
// Pending non-blocking parameter writes, each due at a `now`-timeline timestamp. Accessed
|
||||
// only on the body's own thread (like `tempo`), so no lock is needed — the array crosses no
|
||||
// thread boundary. The `param.value` writes it performs are themselves atomic and RT-safe.
|
||||
private var _scheduledSets: [_ScheduledSet] = []
|
||||
|
||||
internal init(
|
||||
engine: SynthesisEngine,
|
||||
control: RoutineControl
|
||||
@@ -345,6 +350,89 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
|
||||
param.value = value
|
||||
}
|
||||
|
||||
/// Schedules `param` to be set to `value` after `seconds`, **without blocking** the body.
|
||||
///
|
||||
/// Unlike ``set(_:to:)`` (which writes immediately) and ``ramp(_:to:seconds:)`` (which blocks
|
||||
/// for the glide), this records a one-shot future write and returns at once — so the body can
|
||||
/// start the next event while earlier writes are still pending. Several scheduled writes
|
||||
/// coexist and fire independently, which is what lets overlapping voices (legato `> 1`) each
|
||||
/// get their own note-off.
|
||||
///
|
||||
/// The write is serviced on this context's own timeline: due writes fire during any
|
||||
/// ``wait(seconds:)`` / ``wait(beats:)`` and during ``waitForScheduledSets()``, at the ~10 ms
|
||||
/// poll granularity. Pause time (`LyrebirdTask.pause()`) is excluded — a pause defers a pending
|
||||
/// write by the pause duration — and a stop abandons pending writes unless the body first calls
|
||||
/// ``waitForScheduledSets()`` (drain at their proper times) or the internal flush (fire now).
|
||||
///
|
||||
/// The target time is captured relative to the current ``now``; a non-positive `seconds` makes
|
||||
/// the write due at the next service.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - param: The `@LiveParam` node — `synth.$someLiveParam`. (`@UIParam` is not accepted —
|
||||
/// see ``set(_:to:)``.)
|
||||
/// - value: The value to write when the delay elapses.
|
||||
/// - seconds: Delay from now, in seconds.
|
||||
public func set(
|
||||
_ param: ParameterNode,
|
||||
to value: Double,
|
||||
after seconds: Double
|
||||
) {
|
||||
_scheduledSets.append(_ScheduledSet(fireAtNow: now + max(0.0, seconds), param: param, value: value))
|
||||
}
|
||||
|
||||
/// Schedules `param` to be set to `value` after `beats` beats at the current ``tempo``.
|
||||
/// See ``set(_:to:after:)``.
|
||||
public func set(
|
||||
_ param: ParameterNode,
|
||||
to value: Double,
|
||||
afterBeats beats: Double
|
||||
) {
|
||||
set(param, to: value, after: beats * 60.0 / tempo)
|
||||
}
|
||||
|
||||
/// Blocks until every write scheduled by ``set(_:to:after:)`` / ``set(_:to:afterBeats:)`` has
|
||||
/// fired at its proper time. Used at the end of a finite stream so trailing writes (a final
|
||||
/// voice's note-off, say) are not dropped when the body returns.
|
||||
///
|
||||
/// Throws `LyrebirdRoutineError.stopped` if the owning routine is stopped while draining.
|
||||
public func waitForScheduledSets() throws {
|
||||
while !_scheduledSets.isEmpty {
|
||||
if control.shouldStop.load(ordering: .relaxed) { throw LyrebirdRoutineError.stopped }
|
||||
let earliest: Double = _scheduledSets.reduce(Double.greatestFiniteMagnitude) {
|
||||
Swift.min($0, $1.fireAtNow)
|
||||
}
|
||||
let remaining: Double = earliest - now
|
||||
// `_sleepUntil` services due writes each poll, so sleeping to `earliest` fires it;
|
||||
// a non-positive remaining falls through to an immediate service on the next pass.
|
||||
_nextWakeTime = try _sleepUntil(Date().addingTimeInterval(max(0.0, remaining)))
|
||||
_serviceScheduledSets()
|
||||
}
|
||||
}
|
||||
|
||||
/// Fires every pending scheduled write immediately, regardless of its due time, and clears the
|
||||
/// list. Used on stop so outstanding gates close (voices release and self-free) rather than
|
||||
/// hanging at their sustain level.
|
||||
internal func _flushScheduledSets() {
|
||||
for s: _ScheduledSet in _scheduledSets { s.param.value = s.value }
|
||||
_scheduledSets.removeAll(keepingCapacity: false)
|
||||
}
|
||||
|
||||
/// Fires any scheduled writes whose due time has arrived, in schedule order, and drops them.
|
||||
/// Called from the wait poll loop — a no-op when nothing is pending.
|
||||
private func _serviceScheduledSets() {
|
||||
guard !_scheduledSets.isEmpty else { return }
|
||||
let t: Double = now
|
||||
var i: Int = 0
|
||||
while i < _scheduledSets.count {
|
||||
if _scheduledSets[i].fireAtNow <= t {
|
||||
let s: _ScheduledSet = _scheduledSets.remove(at: i)
|
||||
s.param.value = s.value
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Glides a live parameter from its current value to `target` over `seconds`, then lands exactly
|
||||
/// on `target`. **Blocks** the routine/task body for the duration — like ``wait(seconds:)``, so it
|
||||
/// sequences naturally with the body's other timed events.
|
||||
@@ -415,6 +503,9 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
|
||||
_pauseAccumulated += pauseDuration
|
||||
_pauseAccumulatedSamples += _engine.currentTime - pauseStartSamples
|
||||
}
|
||||
// Fire any parameter writes scheduled via `set(_:to:after:)` whose due time has
|
||||
// arrived. Placed before the remaining-time check so the final wake still services.
|
||||
_serviceScheduledSets()
|
||||
let remaining: TimeInterval = adjustedTarget.timeIntervalSince(Date())
|
||||
if remaining <= 0 { break }
|
||||
Thread.sleep(forTimeInterval: min(LyrebirdRoutineContext.pollIntervalSeconds, remaining))
|
||||
@@ -440,6 +531,14 @@ public final class LyrebirdRoutineContext: @unchecked Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// One pending non-blocking parameter write: the value to store, the node to store it into, and
|
||||
/// the `now`-timeline timestamp at which it becomes due. Lives only on the body thread.
|
||||
private struct _ScheduledSet {
|
||||
let fireAtNow: Double
|
||||
let param: ParameterNode
|
||||
let value: Double
|
||||
}
|
||||
|
||||
/// One-shot carrier that returns a (possibly non-`Sendable`) value from a synchronous
|
||||
/// main-thread hop in ``LyrebirdRoutineContext/onMain(_:)``.
|
||||
///
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// The current Lyrebird framework and CLI version.
|
||||
public let lyrebirdVersion: String = "2.3.0"
|
||||
public let lyrebirdVersion: String = "2.4.0"
|
||||
|
||||
/// The banner printed when the interactive shell or REPL session starts.
|
||||
public let welcomeBanner: String = """
|
||||
|
||||
Reference in New Issue
Block a user