Files
Lyrebird/Sources/Lyrebird/Patterns/Events/ParallelEventPattern.swift
T

123 lines
6.1 KiB
Swift

// 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 {}