158 lines
7.3 KiB
Swift
158 lines
7.3 KiB
Swift
// 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()
|
|
}
|
|
}
|
|
}
|