Files
Lyrebird/Sources/Lyrebird/Process/LyrebirdEventList.swift
T

1453 lines
68 KiB
Swift

// LyrebirdEventList.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
// MARK: - Named constants for timeline precision
/// Number of decimal places used when rounding timeline entry offsets.
/// `4` provides 0.1 ms resolution — matches ``stemSecondsDecimalPlaces`` for
/// consistency with stem filenames.
private let timelineOffsetDecimalPlaces: Int = 4
/// Multiplier used to round a `Double` offset to ``timelineOffsetDecimalPlaces`` places.
/// `10 ^ 4 = 10 000`.
private let timelineOffsetRoundingFactor: Double = 10_000.0
// MARK: - Internal master routing synthesizer
/// Internal synthesizer that applies a lag-smoothed master amplitude to the
/// EventList's user-supplied `bus` **in place** via `ReplaceOut`.
///
/// Reads N channels from `bus` via `In.Audio`, multiplies by the lag-smoothed
/// scalar `amp` (mono-broadcast across all N source channels via the
/// `BinaryOpGenerator` channel-aware policy), and overwrites the same N buses
/// via a single `ReplaceOut.Audio`. The fan-out cache ensures the multiply
/// runs once per channel per block; the bus write is a `vDSP_vdpsp` per
/// channel into the engine bus slice.
///
/// Placed inside `_masterGroup` (sibling-after the process group). Any pre/post
/// master FX added via ``LyrebirdEventList/preMasterGroup`` /
/// ``LyrebirdEventList/postMasterGroup`` run respectively before and after
/// this synth. See `docs/engine/eventlist-routing-design.md` for the full
/// design.
final class EventListMasterSynth: SynthesizerBase {
@LiveParam var amp: Double = 1.0
@LiveParam var ampLag: Double = 0.1
let bus: AudioBus
init(
bus: AudioBus,
initialAmp: Double,
initialAmpLag: Double
) {
self.bus = bus
super.init()
self.amp = initialAmp
self.ampLag = initialAmpLag
}
override func build() {
let smoothAmp: Lag.Audio = Lag.Audio(input: $amp, time: $ampLag)
// In.Audio on an AudioBus reads `bus.channelCount` consecutive buses.
// BinaryOpGenerator broadcasts the mono `smoothAmp` across all channels
// of `inSig`, producing an N-channel scaled signal in one pass.
// ReplaceOut.Audio with an AudioBus target fans the N-channel source
// across `bus.channelCount` consecutive buses, overwriting each.
let inSig: In.Audio = In.Audio(bus: bus)
let scaled: BinaryOpGenerator = inSig * smoothAmp
replaceOutput(bus: bus, source: scaled)
}
}
// MARK: - LyrebirdEventList
/// An ordered list of ``LyrebirdEvent``s that plays sequentially, with a shared
/// master routing bus and lag-smoothed master amplitude.
///
/// `LyrebirdEventList` is the Lyrebird equivalent of SuperCollider's `ProcEvents`.
/// It owns a group of ``LyrebirdProcess`` instances, provides a shared master input
/// bus so all processes mix through a single amplitude-controlled output, and
/// tracks the timeline of fired events.
///
/// ## Lifecycle
///
/// 1. Construct with an ordered array of ``LyrebirdEvent``s and optional
/// `initProcess` / `killProcess`.
/// 2. Call ``next()`` or ``play(eventIndex:)`` to fire events.
/// 3. Each `next()` increments ``index``. Past the last event, ``nextEvent``
/// returns `nil`.
/// 4. Call ``releaseAll()`` to gracefully release all running processes, or
/// ``killAll()`` to immediately free everything.
/// 5. ``reset()`` calls ``killAll()`` and resets ``index`` to `0`.
///
/// ## First-event side effects
///
/// On the very first event after init or reset:
/// - ``startStamp`` is captured (absolute seconds since Unix epoch).
/// - The master amplitude synth is spawned.
/// - `initProcess` (if non-nil) is played.
///
/// ## Caller-owned synth lifecycle — re-add gotcha
///
/// The EventList manages its **own** nodes (master synth, master/process groups,
/// each ``LyrebirdProcess``'s private group) correctly across reset / kill — they
/// are recreated fresh on the next play, so they never collide. But if your
/// `initProcess` (or an ``onKillAll`` hook) **adds caller-owned synths that
/// outlive a single process** — e.g. a body that calls `engine.add(myInputSynth)`
/// for synths you keep references to and reuse — those instances are yours to
/// cycle, and you must respect the engine's re-add rule:
///
/// > `engine.remove` / `free` / `Group.free` only *enqueue* removal. The synth's
/// > engine binding clears one ``SynthesisEngine/processBlock(inputSamples:)``
/// > later, when the RT thread drains the free queue. Re-adding the **same
/// > instance** before that drain throws `EngineAddError.doubleAdd`
/// > ("allow at least one processBlock before re-adding the same instance").
///
/// ``reset()`` / ``killAll()`` free everything on the main thread *synchronously*,
/// so the moment they return the list looks fully torn down — but caller-owned
/// instances are still bound for one more block. A skip-ahead-then-restart, or a
/// second `killAll`, can re-fire your add path inside that window and trip the
/// guard. Two safe patterns:
///
/// 1. **Split persistent from per-performance.** Add session-lifetime synths once
/// (outside the EventList's play cycle, freed at engine stop); only re-add the
/// short-lived ones, and **build fresh instances** for each re-add rather than
/// re-adding the same object.
/// 2. **Re-create on re-add.** If a synth must be re-added every first event, make
/// a new instance each time — a fresh instance has a clear binding and is never
/// inside the one-block window.
///
/// See the Process System article's "Persisting Captured Input Buffers" section
/// for a worked example.
///
/// ## Master routing
///
/// All wrapped processes route their output to a shared master input bus. A
/// `EventListMasterSynth` reads from that bus, applies a lag-smoothed master
/// amplitude, and writes to the hardware output bus (bus `0`).
///
/// ## End-of-performance hook (``onKillAll``)
///
/// ``onKillAll`` fires synchronously at the top of ``killAll()`` (and from
/// ``reset()``, which calls `killAll` internally). Use it to run
/// performance-scoped cleanup — most commonly, to dump session
/// ``LyrebirdBuffer``s captured during the performance to disk before the
/// next one begins. The hook does not fire from ``releaseAll()`` or from a
/// natural end-of-events drain. See the "Persisting Captured Input Buffers"
/// subsection of the Process System article for the recommended pattern.
///
/// - Parameters:
/// - id: Identifier string for this EventList. Must be unique within a session.
/// - events: Ordered array of events to play.
/// - engine: The synthesis engine.
/// - amp: Initial master amplitude `[0.0, 1.0]`. Defaults to `1.0`.
/// - ampLag: Lag time in seconds for master amplitude changes. Defaults to `0.1`.
/// - bus: Shared master bus the EventList scales in place.
/// - initProcess: Optional process played on the first event. `nil` = none.
/// - killProcess: Optional process played when ``killAll()`` is called. `nil` = none.
public final class LyrebirdEventList: @unchecked Sendable {
// @unchecked Sendable: most mutable state (_index, _startDate, _isRunning,
// _masterSynth, _masterGroup, _isReplaying, _isPlayingTimeline,
// _timelineRoutine) is accessed from the main thread only (via the public
// API which documents main-thread-only usage). The async body tasks of owned
// processes access _eventListStartProvider (a closure) which reads
// _startDate — this is safe because _startDate is written once (first
// event) before any body tasks read it, using the same wall-clock pattern as
// LyrebirdProcessContext._eventListStart.
// Timeline routines dispatch play(eventIndex:) back to the main thread via
// DispatchQueue.main.async, preserving the main-thread-only invariant.
//
// _timeline is the one exception: it is read from background body tasks via
// `fireTimes(forEvent:)` / `firstFireTime(forEvent:)`. All five mutation
// sites (`_appendTimelineEntry`, `clearTimeline`, `setTimeline`,
// `loadTimeline`, `reset`) and both cross-thread readers acquire
// `_timelineLock`. The bare `timeline` public getter and `saveTimeline` /
// `playTimeline` read `_timeline` without the lock; those are main-thread-
// only per their docs and run on the same thread as the mutators.
// MARK: - Identity
/// Unique identifier for this EventList. Assigned to all owned processes as
/// `_eventListID`.
public let id: String
// MARK: - Configuration (immutable after init)
private let _events: [LyrebirdEvent]
private let _engine: SynthesisEngine
private let _initialAmp: Double
private let _ampLag: Double
/// The shared master bus the EventList monitors and scales in place.
/// Channel count derived as `_bus.channelCount`.
private let _bus: AudioBus
/// Optional process fired exactly once on the first event. It is **not**
/// auto-released by any event in ``_events``; it runs for the entire
/// EventList session and is only stopped by ``releaseAll()`` (graceful) or
/// ``killAll()`` (immediate). See the public ``init(id:events:engine:amp:ampLag:bus:initProcess:killProcess:)`` doc block.
private let _initProcess: LyrebirdProcess?
private let _killProcess: LyrebirdProcess?
/// Flat list of all processes owned by this EventList (events + init + kill).
private let _allProcesses: [LyrebirdProcess]
// MARK: - Runtime state (main-thread only)
/// The group containing all process private groups. Processes are added here.
public private(set) var group: Group
/// The group containing pre-master FX, the master synth, and post-master FX.
/// Placed after `group` in the root. Internal order is
/// `_preMasterGroup` → `_masterSynth` → `_postMasterGroup`.
private var _masterGroup: Group
/// Sub-group inside `_masterGroup` that runs **before** the master synth.
/// Caller adds decoders / pre-master FX here via ``addPreMaster(_:)`` or by
/// reading ``preMasterGroup`` directly. These synths read the unscaled
/// process output and can write to the EventList's `bus` (which the master
/// synth then scales) or to any other bus.
private var _preMasterGroup: Group
/// Sub-group inside `_masterGroup` that runs **after** the master synth.
/// Caller adds limiters / mastering FX / tap recorders here via
/// ``addPostMaster(_:)`` or by reading ``postMasterGroup`` directly. These
/// synths see the post-amp signal.
private var _postMasterGroup: Group
private var _masterSynth: EventListMasterSynth?
/// `true` between the moment `killAll()` commits to a master teardown and
/// the moment `_teardownMaster()` finishes. Used to short-circuit
/// redundant `killAll()` calls so the kill process is not re-launched and
/// `_teardownMaster()` is not invoked twice. Necessary because
/// `LyrebirdProcess` rearms to idle after teardown — the previous
/// `kp.isRunning` guard is no longer sufficient.
private var _teardownMasterPending: Bool = false
private var _startDate: Date?
/// Engine sample time captured alongside `_startDate` on the first event.
/// Used by ``LyrebirdProcess/_eventListStartSampleTimeProvider`` to compute
/// stem filename offsets via sample-accurate arithmetic instead of wall-clock
/// time — this is correct under both real-time and NRT playback.
private var _startSampleTime: SampleTime?
// MARK: - Playback state
private var _index: Int = 0
private var _isRunning: Bool = false
// MARK: - Recording state (main-thread only)
/// Non-nil while recording is enabled. Set by ``record(directory:format:)``
/// and cleared by ``stopRecord()``.
private var _recordingDirectory: URL?
private var _recordingFormat: AudioFileFormat = .wavFloat32
private var _isRecording: Bool = false
// MARK: - Timeline state (main-thread only)
/// Live-captured timeline entries. Appended by ``play(eventIndex:)`` (unless
/// ``_isReplaying`` is `true`). Replaced by ``loadTimeline(from:)`` /
/// ``setTimeline(_:)``. Cleared by ``clearTimeline()`` and ``reset()``.
private var _timeline: [LyrebirdTimelineEntry] = []
/// `true` once the very first live-capture entry has been appended. Used by
/// ``_appendTimelineEntry`` to distinguish the origin event (which always gets
/// `offset == 0.0`) from subsequent events (which compute elapsed time from
/// `_startDate`). Reset only by ``reset()`` — `clearTimeline()` does NOT reset
/// this so that events fired after `clearTimeline()` correctly report elapsed time
/// since the first event rather than `0.0`.
private var _timelineOriginSet: Bool = false
/// `true` while a ``playTimeline(clock:)`` replay is in progress. Suppresses
/// capture inside ``play(eventIndex:)`` so that replayed events do not
/// double-append entries.
private var _isReplaying: Bool = false
/// `true` from when ``playTimeline(clock:)`` begins scheduling until the last
/// entry fires (or ``stopTimelinePlayback()`` is called).
private var _isPlayingTimeline: Bool = false
/// Internal routine that drives timeline playback. Retained so
/// ``stopTimelinePlayback()`` can signal it.
private var _timelineRoutine: LyrebirdRoutine?
/// Lock protecting cross-thread reads of `_timeline` (e.g. from a
/// `LyrebirdProcess` body closure on a background task). All `_timeline`
/// mutations (`_appendTimelineEntry`, `clearTimeline`, `setTimeline`,
/// `loadTimeline`, `reset`) acquire this lock; the cross-thread readers
/// `fireTimes(forEvent:)` and `firstFireTime(forEvent:)` also acquire it.
/// The main-thread-only `timeline` accessor and timeline-replay paths do
/// not — they already run on the same thread as the mutators.
private let _timelineLock: NSLock = NSLock()
// MARK: - Callbacks
/// Called after each event fires, with the zero-based event index that was played.
public var onEvent: ((Int) -> Void)?
/// Called synchronously at the top of ``killAll()`` **before** any process
/// kill or master teardown begins. Use this hook to run end-of-performance
/// work that needs to observe the just-finished state of the event list and
/// any user-owned resources (input capture buffers, custom node-tree
/// branches, telemetry, etc.).
///
/// Typical use: launch a background task that writes session ``LyrebirdBuffer``s
/// to disk before the next performance begins. See the "Persisting Captured
/// Input Buffers" subsection of the Process System article for the
/// recommended pattern.
///
/// Runs on the same thread that invoked ``killAll()`` (main thread by
/// convention). Exceptions thrown from the closure are not caught — keep
/// the body straight-line.
public var onKillAll: (() -> Void)?
// MARK: - Init
/// Creates a `LyrebirdEventList`.
///
/// All processes in `events`, `initProcess`, and `killProcess` are claimed by
/// this EventList. A process can only belong to one EventList; constructing a
/// second EventList with the same process instance traps with
/// ``LyrebirdProcessError/processAlreadyOwned(processID:ownerID:)``.
///
/// - Parameters:
/// - id: Unique identifier for this EventList.
/// - events: Ordered array of ``LyrebirdEvent``s.
/// - engine: The synthesis engine.
/// - amp: Initial master amplitude. Range `[0.0, 1.0]`. Defaults to `1.0`.
/// - ampLag: Lag time in seconds for master amplitude smoothing. Defaults to `0.1`.
/// - bus: The shared master bus the EventList monitors and scales **in place**.
/// Contained ``LyrebirdProcess`` instances keep their own ``LyrebirdProcess``
/// `procOut` — the caller is responsible for designing process factories whose
/// `procOut` writes to this `bus` (otherwise the master amp control has no
/// effect on that process). Channel count is taken from `bus.channelCount`.
/// See `docs/engine/eventlist-routing-design.md` for the in-place scaling
/// design rationale.
/// - initProcess: Optional process fired exactly once when the first event
/// plays. It is **not** auto-released by any event in `events`. It runs
/// for the entire EventList session and is only released when the caller
/// invokes ``releaseAll()`` (graceful release through its envelope's
/// `releaseNode`) or ``killAll()`` (immediate kill). To make it
/// self-terminate, give its envelope a finite total duration with no
/// `releaseNode`-gated sustain segment. `nil` = none.
/// - killProcess: Optional process fired when ``killAll()`` is called. `nil` = none.
public init(
id: String,
events: [LyrebirdEvent],
engine: SynthesisEngine,
amp: Double = 1.0,
ampLag: Double = 0.1,
bus: AudioBus = AudioBus(index: 0, channelCount: 2),
initProcess: LyrebirdProcess? = nil,
killProcess: LyrebirdProcess? = nil
) throws {
self.id = id
_events = events
_engine = engine
_initialAmp = amp
_ampLag = ampLag
_bus = bus
_initProcess = initProcess
_killProcess = killProcess
// Collect all processes for ownership assignment and iteration.
var allProcs: [LyrebirdProcess] = []
for event: LyrebirdEvent in events {
allProcs.append(contentsOf: event.starts)
allProcs.append(contentsOf: event.releases)
}
if let ip: LyrebirdProcess = initProcess { allProcs.append(ip) }
if let kp: LyrebirdProcess = killProcess { allProcs.append(kp) }
// Deduplicate (a process may appear in both starts and releases arrays).
var seen: Set<ObjectIdentifier> = Set<ObjectIdentifier>()
_allProcesses = allProcs.filter { seen.insert(ObjectIdentifier($0)).inserted }
// Build all groups before claiming ownership so fatalError fires before
// any engine state is mutated. `_masterGroup` holds, in order,
// `_preMasterGroup` → master synth → `_postMasterGroup`.
let processGroup: Group = Group()
let masterGroup: Group = Group()
let preMasterGroup: Group = Group()
let postMasterGroup: Group = Group()
group = processGroup
_masterGroup = masterGroup
_preMasterGroup = preMasterGroup
_postMasterGroup = postMasterGroup
// Claim ownership of all processes — throw on duplicate ownership.
let ownID: ObjectIdentifier = ObjectIdentifier(self)
for proc: LyrebirdProcess in _allProcesses {
if let existingID: ObjectIdentifier = proc._eventListID, existingID != ownID {
// Converted from fatalError. The caller (which
// may be a plugin host or REPL) now sees a recoverable error
// rather than crashing.
throw LyrebirdProcessError.processAlreadyOwned(
processID: proc.id,
ownerID: id
)
}
proc._eventListID = ownID
proc._eventListStartProvider = { [weak self] in self?._startDate }
proc._eventListStartSampleTimeProvider = { [weak self] in self?._startSampleTime }
proc._owningEventList = self
}
}
// MARK: - Public state
/// Master amplitude, lag-smoothed.
///
/// Writing ramps to the new value over `ampLag` seconds.
@MainActor public var amp: Double {
get { _masterSynth?.$amp.value ?? _initialAmp }
set { _masterSynth?.amp = newValue }
}
/// Sub-group inside the master group that evaluates **before** the master
/// amp synth. Add decoders, sends, or any pre-master FX here. These synths
/// see the **unscaled** process output; the master synth then scales the
/// EventList's `bus` in place via ReplaceOut.
///
/// Lifetime: synths added here are freed when the EventList tears down
/// (`releaseAll()` natural end, `killAll()`, or `reset()`). Each playback
/// session re-allocates a fresh group object, so synth references obtained
/// here are valid for one session only — after teardown the next session's
/// `_firstEventSetup` builds a new empty group.
///
/// Calling ``addPreMaster(_:)`` is valid at any point after the
/// `LyrebirdEventList` is initialised. Before the first event fires the
/// engine has not yet added `_preMasterGroup` to the node tree, so the
/// child-add lands in `engine`'s pending queue alongside the group-add
/// itself; the queue's FIFO discipline guarantees the parent group is
/// inserted into the tree before any child-add is applied.
public var preMasterGroup: Group { _preMasterGroup }
/// Sub-group inside the master group that evaluates **after** the master
/// amp synth. Add limiters, mastering FX, or tap recorders here. These
/// synths see the **post-amp** signal on the EventList's `bus`.
///
/// Lifetime: same as ``preMasterGroup``.
public var postMasterGroup: Group { _postMasterGroup }
/// Convenience for adding a pre-master FX synth at the tail of
/// ``preMasterGroup``. Equivalent to
/// `engine.add(synth, position: .tail(of: preMasterGroup))`.
///
/// Order of evaluation within `preMasterGroup` matches insertion order.
///
/// Safe to call from a `LyrebirdProcess.body` closure (`initProcess` or any
/// event-driven process body) at any time, including before the first event
/// fires. The synth's lifetime is bounded by `_masterGroup.free()` in
/// `_teardownMaster()` — it is automatically released on EventList
/// teardown.
@MainActor public func addPreMaster(_ synth: any Synthesizer) throws {
try _engine.add(synth, position: .tail(of: _preMasterGroup))
}
/// Convenience for adding a post-master FX synth at the tail of
/// ``postMasterGroup``. Same timing and lifetime guarantees as
/// ``addPreMaster(_:)``.
@MainActor public func addPostMaster(_ synth: any Synthesizer) throws {
try _engine.add(synth, position: .tail(of: _postMasterGroup))
}
/// Current playback index. Setting this value does not auto-release any running
/// processes — it simply moves the playhead for the next ``next()`` call.
public var index: Int {
get { _index }
set { _index = newValue }
}
/// Index of the last event that was played, or `nil` before the first play.
public private(set) var currentEvent: Int?
/// Index of the next event to play (= ``index``), or `nil` if past the end.
public var nextEvent: Int? {
_index < _events.count ? _index : nil
}
/// Read-only access to the events that were passed at construction time.
///
/// Useful for UI layers that want to display per-event metadata
/// (e.g. the process IDs in `events[currentEvent].starts`).
public var events: [LyrebirdEvent] { _events }
/// Number of events in the list. Equivalent to `events.count`.
public var eventCount: Int { _events.count }
/// All processes claimed by this EventList — the union of every event's
/// `starts` and `releases`, plus `initProcess` and `killProcess` if set.
/// Deduplicated by identity.
///
/// Useful for UI layers that want to enumerate running processes
/// (e.g. show a per-process control strip while playback advances).
public var allProcesses: [LyrebirdProcess] { _allProcesses }
/// Absolute time (seconds since Unix epoch) at which the first event was fired.
/// `nil` before the first play and after ``reset()``.
public private(set) var startStamp: Double?
/// `true` after the first event is fired; `false` after ``reset()`` or ``killAll()``.
public private(set) var isRunning: Bool = false
// MARK: - Recording state (public read-only)
/// `true` while stem recording is enabled.
///
/// Processes started after ``record(directory:format:)`` is called receive a
/// ``DiskOut/Audio`` generator that writes their route-bus signal to disk.
/// Processes already running when recording is enabled do **not** start
/// recording retroactively — only new `play(engine:)` calls after `record(directory:format:)` are
/// captured.
///
/// Recording is automatically stopped by ``stopRecord()``, ``reset()``, or
/// ``killAll()``.
public var isRecording: Bool { _isRecording }
/// Directory to which stem files are written, or `nil` when not recording.
public var recordDirectory: URL? { _recordingDirectory }
/// Container-and-encoding format used for stem files.
///
/// Defaults to ``AudioFileFormat/wavFloat32``. Set via ``record(directory:format:)``.
public var recordFormat: AudioFileFormat { _recordingFormat }
// MARK: - Playback
/// Play the event at the current ``index`` and increment the index.
///
/// No-op when ``nextEvent`` is `nil` (past the end).
@MainActor public func next() {
guard _index < _events.count else { return }
let idx: Int = _index
_index += 1
play(eventIndex: idx)
}
/// Play the event at the specified index without changing ``index``.
///
/// Out-of-range indices are silently ignored.
///
/// - Parameter eventIndex: Zero-based index into the events array.
@MainActor public func play(eventIndex: Int) {
guard eventIndex >= 0, eventIndex < _events.count else { return }
// Capture engine.currentTime ONCE at the top of the call so every
// sample-time read inside this event references the same origin.
// Without this, the background driver thread (in RT or test-driver
// scenarios) can advance `engine.currentTime` between
// `_firstEventSetup` setting `_startSampleTime` and `proc._play`
// reading its own `playSampleTime`, producing a stem-filename
// offset that disagrees with the timeline-entry offset by ~one
// engine block.
let originSampleTime: SampleTime = _engine.currentTime
// First-event side effects.
// `_firstEventSetup` now throws on
// engine.add failures and fully unwinds successful partial adds
// before re-throwing. Catch + post to `LyrebirdMessageCenter`
// and return — `isRunning` stays `false` because the setup
// deferred all instance-state writes until the full add
// sequence succeeded.
if !isRunning {
do {
try _firstEventSetup(at: originSampleTime)
} catch {
let listID: String = String(describing: ObjectIdentifier(self))
Task { @MainActor in
LyrebirdMessageCenter.shared.post(
.error,
"LyrebirdEventList \(listID) first-event setup failed: \(error)",
source: "LyrebirdEventList.play"
)
}
return
}
}
let event: LyrebirdEvent = _events[eventIndex]
currentEvent = eventIndex
// Release listed processes first, then start new ones.
for proc: LyrebirdProcess in event.releases {
if proc.isRunning && !proc.isReleasing {
proc.release()
}
}
for proc: LyrebirdProcess in event.starts {
// Inject recording config immediately before _play so the process
// can construct its stem filename and spawn DiskOut if recording is active.
if _isRecording, let dir: URL = _recordingDirectory {
proc._recordingConfig = ProcessRecordingConfig(
directory: dir,
format: _recordingFormat,
sanitisedEventListID: sanitisedForFilename(id),
sampleRate: _engine.sampleRate
)
} else {
proc._recordingConfig = nil
}
// Process writes to its own declared `procOut`. EventList scales the
// user-supplied `_bus` in place via the master synth.
// _play throws only for the cross-EventList target case; init
// pre-validates ownership so that condition cannot fire here.
// Use `try?` to be defensive — if a user mutates `_target` after
// EventList init, the error is silently dropped rather than
// crashing the timeline runner.
try? proc._play(
engine: _engine,
parentGroup: group,
playSampleTimeOverride: originSampleTime
)
}
// Timeline capture — append an entry unless we are in a replay pass.
if !_isReplaying {
_appendTimelineEntry(eventIndex: eventIndex, event: event)
}
onEvent?(eventIndex)
}
// MARK: - Release / kill / reset
/// Release every currently-running process gracefully.
///
/// Calls ``LyrebirdProcess/release(reltime:)`` on each running, non-releasing
/// process. Does not advance ``index``.
@MainActor public func releaseAll() {
for proc: LyrebirdProcess in _allProcesses {
if proc.isRunning && !proc.isReleasing {
proc.release()
}
}
}
/// Immediately kill every process, free the master synth and bus, and reset
/// running state.
///
/// After `killAll()`:
/// - ``isRunning`` is `false`.
/// - ``startStamp`` is `nil`.
/// - ``index`` is unchanged.
///
/// When `killProcess` is non-nil, it is played and master teardown is deferred
/// until after the kill process finishes naturally (its `onFinished` triggers
/// `_teardownMaster()`). This ensures the kill process's envelope has time to
/// run before the parent group is freed. Teardown is therefore **not** guaranteed
/// to be synchronous when a kill process is configured — callers that need a
/// synchronous guarantee should use ``reset()`` instead of ``killAll()``.
///
/// **End-of-performance hook**: ``onKillAll`` (if set) fires synchronously
/// at the top of this method, before any process kill or master teardown
/// begins. Use it to dump session ``LyrebirdBuffer``s to disk or run any
/// other performance-scoped cleanup. See the "Persisting Captured Input
/// Buffers" subsection of the Process System article.
@MainActor public func killAll() {
// Fire the end-of-performance hook before any teardown so callers can
// observe the live state (buffers, node tree) one last time.
onKillAll?()
// Guard against double-call while a master teardown is already in flight.
// `_teardownMasterPending` covers both the in-flight kill process case
// and the brief window between the kill process finishing and the
// deferred `_teardownMaster()` poll firing. (Process state alone is no
// longer a reliable signal — processes rearm to idle after teardown.)
if _teardownMasterPending {
for proc: LyrebirdProcess in _allProcesses where proc !== _killProcess {
if proc.isRunning {
proc._group = nil // prevent double-free from _teardown
proc.kill()
}
}
isRunning = false
_startDate = nil
_startSampleTime = nil
startStamp = nil
return
}
// Kill all owned processes (excluding the kill process itself, which we
// may be about to start and should run to its own natural completion).
//
// IMPORTANT: Nil out each process's _group reference BEFORE calling
// _teardownMaster(), which will call group.free() recursively freeing all
// process private groups. This prevents the process's async _teardown
// callback from posting a duplicate groupFree event for the same
// already-freed private group.
for proc: LyrebirdProcess in _allProcesses where proc !== _killProcess {
if proc.isRunning {
proc._group = nil // prevent double-free from _teardown
proc.kill()
}
}
if let kp: LyrebirdProcess = _killProcess, !kp.isRunning {
_teardownMasterPending = true
// Play the kill process and defer master teardown until it finishes.
// The kill process runs its own _teardown (freeing its private _group)
// via its onFinished callback before the master teardown frees the
// parent group — so no dangling _group reference can occur.
// Kill process writes to its own declared procOut.
try? kp._play(
engine: _engine,
parentGroup: group
)
// Chain onto the kill process's onFinished: fire _teardownMaster after
// the kill process completes its own teardown.
// Note: _onFinished is a stored let on LyrebirdProcess. Instead of
// mutating the kill process's callback (which is immutable), we use a
// separate watcher approach: re-use the kill process's _eventListStartProvider
// callback slot is not appropriate here. The clean path is to observe
// onFinished via a DispatchQueue poll from a one-shot block. Since the
// kill process calls _onFinished?() at the end of its own _teardown(), we
// wrap _teardownMaster() in a closure that fires on main after the kill
// process transitions to done and its _teardown() chain is complete.
// We do this via a weak-capture polling block dispatched on .main with
// a very short poll interval (10 ms) — same pattern as the watcher timer.
let killProcRef: LyrebirdProcess = kp
let engineRef: SynthesisEngine = _engine
// Capture a flag to ensure teardown fires exactly once even if killAll()
// is called again (guarded by the isRunning check at the top of killAll).
_scheduleDeferredMasterTeardown(killProc: killProcRef, engine: engineRef)
} else {
// No kill process (or already past idle) — tear down immediately.
_teardownMasterPending = true
_teardownMaster()
}
isRunning = false
_startDate = nil
_startSampleTime = nil
startStamp = nil
}
/// Poll until `killProc` finishes, then tear down the master on the main thread.
/// Uses a DispatchQueue delayed dispatch cascade to avoid blocking the caller.
@MainActor private func _scheduleDeferredMasterTeardown(
killProc: LyrebirdProcess,
engine: SynthesisEngine
) {
// Poll interval: 10 ms — matches the watcher timer interval in LyrebirdProcess.
let killProcPollIntervalMs: Int = 10
@MainActor func poll() {
if killProc.isRunning {
// Still running — re-arm.
DispatchQueue.main.asyncAfter(
deadline: .now() + .milliseconds(killProcPollIntervalMs)
) { MainActor.assumeIsolated { poll() } }
} else {
// Kill process done — tear down master now.
self._teardownMaster()
}
}
DispatchQueue.main.asyncAfter(
deadline: .now() + .milliseconds(killProcPollIntervalMs)
) { MainActor.assumeIsolated { poll() } }
}
/// Kill everything, reset ``index`` to `0`, clear recording state, clear the
/// timeline, and restore the initial amplitude.
///
/// After `reset()`:
/// - ``isRunning`` is `false`.
/// - ``startStamp`` is `nil`.
/// - ``index`` is `0`.
/// - ``currentEvent`` is `nil`.
/// - ``isRecording`` is `false`.
/// - ``timeline`` is empty.
///
/// Any in-progress ``playTimeline(clock:)`` is stopped before the reset.
/// Processes that were recording continue to flush their in-flight DiskOut
/// buffers to disk until their teardown completes.
@MainActor public func reset() {
stopTimelinePlayback()
killAll()
stopRecord()
_timelineLock.lock()
_timeline.removeAll()
_timelineLock.unlock()
_timelineOriginSet = false
_index = 0
currentEvent = nil
}
// MARK: - Recording
/// Enable stem recording for all processes started after this call.
///
/// Each new ``LyrebirdProcess/play(engine:)`` invocation creates a dedicated
/// ``DiskOut/Audio`` instance that taps the process's private route bus and
/// writes to a file in `directory`.
///
/// **Filename scheme** (deterministic, lex-sortable):
/// ```
/// <directory>/<eventListID>_<offset>_<processID>_<playIndex>.<ext>
/// ```
/// where `<offset>` is formatted as `%07.4f` seconds (zero-padded to 7 integer
/// digits, 4 decimal places) since the first event fired.
///
/// **Late-start support**: calling `record(directory:format:)` after the first
/// event has already fired is valid. Processes that are already running do
/// **not** start recording retroactively; only new `play(engine:)` calls after this
/// point produce stem files.
///
/// **Concurrent recording sessions**: calling `record(directory:format:)` again
/// while already recording changes the directory and format for future processes;
/// processes already recording continue with their original settings.
///
/// **Persisting captured input ``LyrebirdBuffer``s alongside stems**: stem
/// recording covers per-process output via ``DiskOut/Audio``. Pieces that
/// also accumulate live input into a ``LyrebirdBuffer`` (e.g. a
/// `RecordBuffer.Audio` tap) should write those buffers to disk
/// per-performance via ``onKillAll`` rather than at engine stop. The
/// canonical pattern — free input synths inside the hook, launch a
/// background task that captures strong buffer refs, then clear + rebuild
/// for the next performance — is documented in the "Persisting Captured
/// Input Buffers" subsection of the Process System article.
///
/// - Parameters:
/// - directory: Directory in which stem files are created. Created
/// eagerly (including intermediate directories) before this call returns.
/// A failure to create the directory is logged but does not throw — recording
/// will simply fail silently when the first process attempts to write.
/// - format: Container and PCM encoding. Defaults to ``AudioFileFormat/wavFloat32``.
/// Must be a PCM or RF64 format — compressed formats (`.aacHigh` / `.aacMedium`
/// / `.alac`) are **rejected** (stems stream through ``DiskOut/Audio``, which is
/// PCM/RF64 only); passing one logs a warning and leaves recording disabled.
public func record(
directory: URL,
format: AudioFileFormat = .wavFloat32
) {
// Stems are written by DiskOut, which streams PCM/RF64 only — a compressed
// format would make every per-process DiskOut.init throw and recording fail
// silently. Reject it up front with a clear message and do not enable
// recording (render offline for compressed output).
guard !format.isCompressed else {
print("[LyrebirdEventList '\(id)'] Compressed formats (AAC/ALAC) are not "
+ "supported for stem recording — DiskOut streams PCM/RF64 only. "
+ "Recording NOT enabled. Use a PCM/RF64 format for stems, or render "
+ "offline (LyrebirdBuffer.write / NRTDriver) for AAC/ALAC.")
return
}
// Eagerly create the directory so the contract "directory exists when the
// first process plays" is guaranteed regardless of whether any event fires.
do {
try FileManager.default.createDirectory(
at: directory,
withIntermediateDirectories: true
)
} catch {
print("[LyrebirdEventList '\(id)'] Could not create recording directory '\(directory.path)': \(error)")
}
_recordingDirectory = directory
_recordingFormat = format
_isRecording = true
}
/// Disable stem recording for all processes started after this call.
///
/// Processes that are already recording continue until their natural teardown,
/// which closes the ``DiskOut/Audio`` cleanly and flushes all buffered frames
/// to disk. No in-flight recording is interrupted.
///
/// After `stopRecord()`, ``isRecording`` returns `false` and
/// ``recordDirectory`` returns `nil`.
///
/// **Format persistence**: `stopRecord()` does not reset ``recordFormat``. The
/// format value set by the most recent ``record(directory:format:)`` call persists
/// across stop/restart cycles. This is intentional — calling `record()` again
/// with no explicit `format:` argument continues using the previous format.
public func stopRecord() {
_isRecording = false
_recordingDirectory = nil
}
// MARK: - Timeline (public API)
/// The live-captured performance timeline.
///
/// Each entry in this array corresponds to one ``play(eventIndex:)`` (or
/// ``next()``) invocation during a live performance. The first entry always
/// has ``LyrebirdTimelineEntry/offset`` `== 0.0`. Entries are in chronological
/// order (ascending offset).
///
/// The array is **not** populated during ``playTimeline(clock:)`` replay — the
/// `_isReplaying` flag suppresses capture so entries are not doubled.
///
/// Cleared by ``reset()`` and ``clearTimeline()``. Replaced wholesale by
/// ``loadTimeline(from:)`` and ``setTimeline(_:)``.
///
/// - Important: Main-thread only. This accessor reads `_timeline` without
/// acquiring `_timelineLock`; callers on a background body task must use
/// ``fireTimes(forEvent:)`` or ``firstFireTime(forEvent:)`` instead.
public var timeline: [LyrebirdTimelineEntry] { _timeline }
/// Save the current timeline to `url` as a pretty-printed, sorted-keys JSON file.
///
/// The file contains a top-level JSON array of ``LyrebirdTimelineEntry`` objects.
/// Key ordering is alphabetical (`JSONEncoder.OutputFormatting.sortedKeys`).
///
/// - Parameter url: Destination file URL. Parent directories must already exist
/// (`FileManager` is not called on the caller's behalf here).
/// - Throws: `EncodingError` if JSON serialization fails, or file-system errors
/// from `Data.write(to:options:)`.
public func saveTimeline(to url: URL) throws {
let encoder: JSONEncoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data: Data = try encoder.encode(_timeline)
try data.write(to: url, options: .atomic)
}
/// Load a previously-saved timeline from `url`, replacing the current
/// ``timeline``.
///
/// Validates that every entry's ``LyrebirdTimelineEntry/eventIndex`` is within
/// `0..<events.count`. The first failing entry throws
/// ``LyrebirdTimelineError/eventIndexOutOfRange(entryOffset:eventIndex:)``
/// and the existing timeline is **not** replaced.
///
/// - Parameter url: A JSON file previously written by ``saveTimeline(to:)``.
/// - Throws: `DecodingError` if the file cannot be parsed, file-system errors
/// from `Data(contentsOf:)`, or ``LyrebirdTimelineError`` on validation failure.
public func loadTimeline(from url: URL) throws {
let data: Data = try Data(contentsOf: url)
let decoder: JSONDecoder = JSONDecoder()
let entries: [LyrebirdTimelineEntry] = try decoder.decode([LyrebirdTimelineEntry].self, from: data)
try _validateEntries(entries)
_timelineLock.lock()
_timeline = entries
_timelineLock.unlock()
}
/// Replace the current timeline with `entries` directly (for tests and
/// programmatic use).
///
/// Validates that every entry's ``LyrebirdTimelineEntry/eventIndex`` is within
/// `0..<events.count`. Throws ``LyrebirdTimelineError`` on the first failing
/// entry without modifying the existing timeline.
///
/// - Parameter entries: Replacement timeline entries.
/// - Throws: ``LyrebirdTimelineError/eventIndexOutOfRange(entryOffset:eventIndex:)``
/// if any entry's event index is out of range.
public func setTimeline(_ entries: [LyrebirdTimelineEntry]) throws {
try _validateEntries(entries)
_timelineLock.lock()
_timeline = entries
_timelineLock.unlock()
}
/// Empty the timeline without affecting running processes or recording state.
///
/// Independent of ``reset()`` — does not kill processes or stop recording.
public func clearTimeline() {
_timelineLock.lock()
_timeline.removeAll()
_timelineLock.unlock()
}
/// Schedule playback of the captured ``timeline`` against `clock`.
///
/// Entries are sorted by offset before scheduling (defensive against JSON
/// round-trip reordering) and dispatched via a ``LyrebirdRoutine`` background
/// thread. Each entry fires ``play(eventIndex:)`` at the recorded offset
/// relative to `clock`-now.
///
/// Capture is suppressed during replay (`_isReplaying == true`) so entries do
/// not double-append to the timeline. The timeline array itself is unchanged
/// after playback.
///
/// Sets ``isPlayingTimeline`` to `true` at start; flips it to `false` after the
/// last entry fires or ``stopTimelinePlayback()`` is called.
///
/// - Parameter clock: The ``LyrebirdClock`` that drives replay timing. Its
/// `bpm` value is not modified by this call. Offset seconds are converted to
/// sample-accurate ``SampleTime`` values via the clock's engine.
public func playTimeline(clock: LyrebirdClock) {
// Stop any prior playback before starting fresh.
_stopAndJoinTimelineRoutine()
guard !_timeline.isEmpty else { return }
// Sort entries defensively — JSON round-trip should preserve order, but
// we make it explicit.
let sorted: [LyrebirdTimelineEntry] = _timeline.sorted { $0.offset < $1.offset }
let engine: SynthesisEngine = _engine
_isPlayingTimeline = true
_isReplaying = true
// Extract Sendable values before the closure to avoid capturing non-Sendable types.
let sampleRate: Double = engine.sampleRate
// Capture the origin sample time at this moment (on the main thread), but use a
// Sendable-safe mechanism to communicate it into the Sendable routine closure.
// We read engine.currentTime here (synchronous, atomic) and pass it as a captured
// let constant — closer in time to when the routine thread actually starts than
// if we had captured it earlier in playTimeline() before sorted/guard checks.
let originSampleTime: SampleTime = engine.currentTime
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
for entry: LyrebirdTimelineEntry in sorted {
// Target sample time = origin + offset in samples.
let targetSample: SampleTime = originSampleTime + SampleTime((entry.offset * sampleRate).rounded())
try ctx.waitUntil(sampleTime: targetSample)
// Fire on main thread — play(eventIndex:) is main-thread-only.
DispatchQueue.main.async { [weak self] in
self?.play(eventIndex: entry.eventIndex)
}
}
// All entries have fired (or the routine was stopped).
// Flags are cleared synchronously by _stopAndJoinTimelineRoutine() — no
// trailing async dispatch needed here, which avoids a race where a new
// playTimeline() call starts before the previous trailing block fires.
}
_timelineRoutine = routine
routine.start(engine: engine)
}
/// Cancel timeline playback.
///
/// Signals the internal routine to stop. Already-fired events remain played.
/// Sets ``isPlayingTimeline`` to `false`.
///
/// No-op if timeline playback is not active.
public func stopTimelinePlayback() {
_stopAndJoinTimelineRoutine()
_isPlayingTimeline = false
_isReplaying = false
}
/// `true` from the start of ``playTimeline(clock:)`` until all entries have
/// fired or ``stopTimelinePlayback()`` is called.
public var isPlayingTimeline: Bool { _isPlayingTimeline }
// MARK: - Private helpers (timeline)
/// Build and append a ``LyrebirdTimelineEntry`` for `eventIndex`.
///
/// Computes the offset as `(now - _startDate)` rounded to 4 decimal places.
///
/// The very first entry ever appended in a play session always gets `offset == 0.0`
/// regardless of when this method is called relative to `_startDate`. After that,
/// all subsequent entries compute the true elapsed time from `_startDate`, even if
/// the timeline was cleared via ``clearTimeline()`` mid-performance.
///
/// This is controlled by `_timelineOriginSet`, which is set on the first append and
/// only cleared by ``reset()`` (not by ``clearTimeline()``). This ensures that a
/// third event fired after `clearTimeline()` reports the correct elapsed time since
/// the first event, not `0.0` (which was the pre-fix bug).
private func _appendTimelineEntry(eventIndex: Int, event: LyrebirdEvent) {
let rawOffset: Double
if !_timelineOriginSet {
// This is the very first entry — by definition the timeline origin.
rawOffset = 0.0
_timelineOriginSet = true
} else if let start: Date = _startDate {
let elapsed: TimeInterval = Date().timeIntervalSince(start)
// Round to timelineOffsetDecimalPlaces decimal places.
rawOffset = (elapsed * timelineOffsetRoundingFactor).rounded() / timelineOffsetRoundingFactor
} else {
// _startDate is nil unexpectedly — fall back to 0.0 defensively.
rawOffset = 0.0
}
let entry: LyrebirdTimelineEntry = LyrebirdTimelineEntry(
offset: rawOffset,
eventIndex: eventIndex,
startedProcessIDs: event.starts.map { $0.id },
releasedProcessIDs: event.releases.map { $0.id }
)
_timelineLock.lock()
_timeline.append(entry)
_timelineLock.unlock()
}
/// All offsets (seconds since the first event fired) at which `eventIndex`
/// was played. Returns an empty array if the event has not yet fired or
/// `eventIndex` is out of range.
///
/// Thread-safe: may be called from a `LyrebirdProcess` body closure
/// (background task) or `onRelease` callback.
public func fireTimes(forEvent eventIndex: Int) -> [Double] {
_timelineLock.lock()
defer { _timelineLock.unlock() }
return _timeline
.filter { $0.eventIndex == eventIndex }
.map(\.offset)
}
/// The first offset at which `eventIndex` was played, or `nil` if it has
/// not yet fired (or is out of range).
///
/// Thread-safe: may be called from a `LyrebirdProcess` body closure
/// (background task) or `onRelease` callback.
public func firstFireTime(forEvent eventIndex: Int) -> Double? {
_timelineLock.lock()
defer { _timelineLock.unlock() }
return _timeline.first { $0.eventIndex == eventIndex }?.offset
}
/// Validate that every entry's `eventIndex` is within `0..<_events.count`.
/// Throws on the first violation without mutating `_timeline`.
private func _validateEntries(_ entries: [LyrebirdTimelineEntry]) throws {
for entry: LyrebirdTimelineEntry in entries {
guard entry.eventIndex >= 0 && entry.eventIndex < _events.count else {
throw LyrebirdTimelineError.eventIndexOutOfRange(
entryOffset: entry.offset,
eventIndex: entry.eventIndex
)
}
}
}
/// Stop and synchronously join the timeline routine (if any).
/// Resets `_timelineRoutine` to `nil` and clears both `_isPlayingTimeline` and
/// `_isReplaying` synchronously on the calling (main) thread. This prevents a
/// race where a new ``playTimeline(clock:)`` call sets the flags to `true` before
/// a trailing `DispatchQueue.main.async` from the old routine fires and resets
/// them back to `false`.
private func _stopAndJoinTimelineRoutine() {
guard let routine: LyrebirdRoutine = _timelineRoutine else { return }
_timelineRoutine = nil
routine.reset() // signals stop + blocks until the thread exits
// Clear flags here — the routine body no longer dispatches a trailing async
// reset, so this is the single place that clears them.
_isPlayingTimeline = false
_isReplaying = false
}
// MARK: - Private helpers (engine lifecycle)
/// Spawn groups and master synth, fire initProcess.
/// Called exactly once per play session (first event after init/reset).
///
/// - Parameter originSampleTime: Engine sample time captured by
/// ``play(eventIndex:)`` at the top of its call. Stored verbatim as
/// `_startSampleTime` so the first event's stem-filename offset
/// (which reads `playSampleTime - _startSampleTime`) is exactly
/// zero when both reads share the same origin.
@MainActor private func _firstEventSetup(at originSampleTime: SampleTime) throws {
// Defer mutating instance state (isRunning / dates) until ALL
// engine.add calls have succeeded. A mid-sequence throw would
// otherwise leave the EventList with isRunning=true and
// partially-applied side effects, and the caller would have to
// do a fresh reset() to recover.
//
// Track every successful add into `committed`. On throw, walk
// `committed` in reverse and engine.remove each — fully unwinding
// the partial setup so a retry leaves no orphan nodes in the
// engine's node tree. The retained-ref pre-allocation inside
// engine.remove is bounded; failure-during-rollback is logged
// but does not re-throw (the caller already saw a structured
// error from the original throw).
// The shared master bus is caller-supplied (`_bus`). No allocation here.
// EventList neither owns the bus nor frees it during teardown.
// Ordering note: the five `_engine.add` calls in this method all land
// in the engine's pending queue with equal `targetTime`. The engine's
// queue uses a stable insertion sort, so FIFO order is preserved — the
// resulting node-tree evaluation order matches the call order here
// (process group → preMaster → masterSynth → postMaster). Re-ordering
// these `add` calls changes evaluation order; do not reorder lightly.
var committed: [any Synthesizer] = []
committed.reserveCapacity(5)
let masterSynth: EventListMasterSynth = EventListMasterSynth(
bus: _bus,
initialAmp: _initialAmp,
initialAmpLag: _ampLag
)
do {
// Add the process group at the head of mainGroup so all EventList
// work sits inside the engine's canonical main bus and respects any
// nodes the caller has placed `.before` / `.after` mainGroup as
// pre/post-main FX.
try _engine.add(group, position: .head(of: _engine.mainGroup))
committed.append(group)
// Add the master group immediately after the process group so the
// master synth always evaluates after all route synths.
try _engine.add(_masterGroup, position: .after(group))
committed.append(_masterGroup)
// Build the master group's internal node order:
// _preMasterGroup → masterSynth → _postMasterGroup
// Pre-master FX (decoders, sends) read the unscaled process output.
// Post-master FX (limiters, recorders) see the post-amp signal.
try _engine.add(_preMasterGroup, position: .head(of: _masterGroup))
committed.append(_preMasterGroup)
// Create and add the master synth at the tail (currently after the
// pre group). Scales `_bus` in place via ReplaceOut.
try _engine.add(masterSynth, position: .tail(of: _masterGroup))
committed.append(masterSynth)
// Post group goes at the new tail — after the master synth.
try _engine.add(_postMasterGroup, position: .tail(of: _masterGroup))
committed.append(_postMasterGroup)
} catch {
// Rollback: remove every node that successfully landed, in
// reverse order. `engine.remove` returns Bool (not throws);
// false on pendingQueueFull is logged but does not block the
// rollback chain — at worst the leaked node will be cleaned
// up by `_teardownMaster` on the next reset().
for synth: any Synthesizer in committed.reversed() {
if !_engine.remove(synth) {
let listID: String = String(describing: ObjectIdentifier(self))
Task { @MainActor in
LyrebirdMessageCenter.shared.post(
.warning,
"LyrebirdEventList \(listID) rollback: " +
"engine.remove failed for partially-added node " +
"(pendingQueue full); will be cleaned up by reset().",
source: "LyrebirdEventList._firstEventSetup"
)
}
}
}
// `_masterSynth` was already nil at entry (instance-state
// writes are deferred until the do-block succeeds). No
// assignment needed here.
throw error
}
// All adds succeeded — commit instance state.
_masterSynth = masterSynth
isRunning = true
_startDate = Date()
_startSampleTime = originSampleTime
startStamp = _startDate?.timeIntervalSince1970
// TODO: master file capture (Step deferred) — record the mixed master bus
// to a single output file alongside the per-process stems. This requires
// a DiskOut tap reading `_bus` after the master synth evaluates, placed
// in the master group at .tail(of: _masterGroup) position after the master synth.
// Update the start provider for all processes now that _startDate is set.
// (The closure already captures [weak self], so it will return the live date.)
// Fire initProcess if one was provided. Writes to its own declared procOut.
if let ip: LyrebirdProcess = _initProcess, !ip.isRunning {
try? ip._play(
engine: _engine,
parentGroup: group
)
}
}
// MARK: - buildFromFile static factory
/// Construct a ``LyrebirdEventList`` from one or more performance log files.
///
/// Each file at `paths` must be a JSON array of ``LyrebirdTimelineEntry`` objects
/// (the format produced by ``saveTimeline(to:)``). Entries from all files are
/// concatenated, sorted by `offset`, and grouped by `tolerance`. Within each
/// tolerance group, process IDs are used to mint fresh ``LyrebirdProcess`` instances
/// via the supplied factory closures.
///
/// ## Minting and ID deduplication
///
/// For every occurrence of a `baseID` in a `startedProcessIDs` list, the factory
/// `processFactories[baseID]` is called with a minted ID of the form
/// `"<baseID>_<counter>"` where `counter` starts at `0` on the first occurrence
/// and increments with every subsequent occurrence across the entire EventList.
/// For example, `"bell"` appearing three times across all events yields processes
/// `"bell_0"`, `"bell_1"`, and `"bell_2"`.
///
/// Releases resolve to the most-recently-minted instance for that base ID.
///
/// ## Tolerance grouping
///
/// Entries whose `offset` values fall within `tolerance` seconds of the previous
/// group's offset are merged into that group. A `tolerance` of `0.0` produces a
/// separate event for every entry. Groups whose merged `starts` and `releases`
/// are both empty are skipped.
///
/// ## Edge cases
///
/// - Empty files contribute zero entries and are silently ignored.
/// - `eventIndex` values in the loaded entries are ignored — only `offset`,
/// `startedProcessIDs`, and `releasedProcessIDs` are consumed.
/// - Duplicate `baseID` values within the same entry's `startedProcessIDs` are
/// each minted separately (the counter increments per occurrence, not per group).
///
/// - Parameters:
/// - id: Unique identifier for the resulting ``LyrebirdEventList``.
/// - engine: The synthesis engine.
/// - processFactories: Dictionary mapping base process IDs to factory closures.
/// Each closure receives the minted ID string and must return a fresh
/// ``LyrebirdProcess`` configured with that ID.
/// - tolerance: Maximum gap in seconds between two entries for them to be merged
/// into the same event. Must be `≥ 0`.
/// - paths: URLs of JSON timeline files to read. Must be non-empty.
/// - amp: Initial master amplitude `[0.0, 1.0]`. Defaults to `1.0`.
/// - ampLag: Lag time in seconds for master amplitude changes. Defaults to `0.1`.
/// - bus: Shared master bus the EventList monitors and scales in place.
/// - initProcess: Optional process played on the first event. `nil` = none.
/// - killProcess: Optional process played when ``killAll()`` is called.
/// `nil` = none.
/// - Returns: A fully constructed ``LyrebirdEventList`` ready for playback.
/// - Throws: ``LyrebirdProcessError/buildFromFileNoInput`` when `paths` is empty,
/// ``LyrebirdProcessError/invalidTolerance(value:)`` when `tolerance < 0`,
/// ``LyrebirdProcessError/unknownProcessFactory(baseID:)`` when an entry
/// references a base ID absent from `processFactories`, or
/// ``LyrebirdProcessError/releaseBeforeStart(baseID:)`` when a release entry
/// references a base ID that has never been started.
public static func buildFromFile(
id: String,
engine: SynthesisEngine,
processFactories: [String: (_ mintedID: String) -> LyrebirdProcess],
tolerance: Double,
paths: [URL],
amp: Double = 1.0,
ampLag: Double = 0.1,
bus: AudioBus = AudioBus(index: 0, channelCount: 2),
initProcess: LyrebirdProcess? = nil,
killProcess: LyrebirdProcess? = nil
) throws -> LyrebirdEventList {
// Validate inputs before any I/O.
guard !paths.isEmpty else {
throw LyrebirdProcessError.buildFromFileNoInput
}
guard tolerance >= 0.0 else {
throw LyrebirdProcessError.invalidTolerance(value: tolerance)
}
// Step 1 — Read and flatten all files.
var allEntries: [LyrebirdTimelineEntry] = []
let decoder: JSONDecoder = JSONDecoder()
for path: URL in paths {
let data: Data = try Data(contentsOf: path)
let entries: [LyrebirdTimelineEntry] = try decoder.decode([LyrebirdTimelineEntry].self, from: data)
allEntries.append(contentsOf: entries)
}
// Step 2 — Sort by offset ascending.
allEntries.sort { $0.offset < $1.offset }
// Step 3 — Tolerance grouping.
// Each group is (groupOffset, starts: [String], releases: [String]).
var groupedEvents: [(offset: Double, starts: [String], releases: [String])] = []
for entry: LyrebirdTimelineEntry in allEntries {
if groupedEvents.isEmpty ||
(entry.offset - groupedEvents[groupedEvents.count - 1].offset) > tolerance {
// Start a new group.
groupedEvents.append((
offset: entry.offset,
starts: entry.startedProcessIDs,
releases: entry.releasedProcessIDs
))
} else {
// Merge into the last group (append, no de-dupe).
let lastIndex: Int = groupedEvents.count - 1
groupedEvents[lastIndex].starts.append(contentsOf: entry.startedProcessIDs)
groupedEvents[lastIndex].releases.append(contentsOf: entry.releasedProcessIDs)
}
}
// Step 4 — Mint processes and build LyrebirdEvent array.
// incDict: counter per base ID (0 on first occurrence).
var incDict: [String: Int] = [:]
// latestMintedByBase: most-recently-minted process per base ID.
var latestMintedByBase: [String: LyrebirdProcess] = [:]
var events: [LyrebirdEvent] = []
for group: (offset: Double, starts: [String], releases: [String]) in groupedEvents {
// Skip empty groups (both starts and releases are empty).
if group.starts.isEmpty && group.releases.isEmpty { continue }
// Build starts — mint a fresh process per occurrence of each baseID.
var starts: [LyrebirdProcess] = []
for baseID: String in group.starts {
guard let factory: (String) -> LyrebirdProcess = processFactories[baseID] else {
throw LyrebirdProcessError.unknownProcessFactory(baseID: baseID)
}
let counter: Int = incDict[baseID] ?? 0
let mintedID: String = "\(baseID)_\(counter)"
incDict[baseID] = counter + 1
let process: LyrebirdProcess = factory(mintedID)
starts.append(process)
latestMintedByBase[baseID] = process
}
// Build releases — resolve to most-recently-minted instance per baseID.
var releases: [LyrebirdProcess] = []
for baseID: String in group.releases {
guard let process: LyrebirdProcess = latestMintedByBase[baseID] else {
throw LyrebirdProcessError.releaseBeforeStart(baseID: baseID)
}
releases.append(process)
}
events.append(LyrebirdEvent(starts: starts, releases: releases))
}
// Step 5 — Construct and return the EventList.
return try LyrebirdEventList(
id: id,
events: events,
engine: engine,
amp: amp,
ampLag: ampLag,
bus: bus,
initProcess: initProcess,
killProcess: killProcess
)
}
/// Free the master synth and both groups. The master `_bus` is caller-owned
/// and is NOT released here.
@MainActor private func _teardownMaster() {
if let synth: EventListMasterSynth = _masterSynth {
// engine.remove routes through pendingQueue (SPSCQueue, lock-free) — RT-safe
// to call from the main thread.
_engine.remove(synth)
_masterSynth = nil
}
// Freeing `_masterGroup` cascades to free `_preMasterGroup`, the master
// synth, and `_postMasterGroup` — and any synths the caller added to
// the pre/post groups. Those caller-added synths therefore have a
// lifetime bounded by the EventList session.
_masterGroup.free(engine: _engine)
group.free(engine: _engine)
// Replace the freed groups with fresh ones so the EventList can be played again
// after reset() without requiring a new EventList instance.
//
// `addPreMaster(_:)` / `addPostMaster(_:)` calls made between teardown
// and the next `_firstEventSetup` enqueue child-adds against the new
// (still-detached) `_preMasterGroup` / `_postMasterGroup`. Group's
// linked-list mutations operate on the group itself; the parent
// connection happens when `_firstEventSetup` attaches `_masterGroup` to
// `mainGroup`. The detached children come along with their parent at
// that point, so order between caller-side `addPreMaster` and the
// subsequent `_firstEventSetup` doesn't change observable behaviour.
group = Group()
_masterGroup = Group()
_preMasterGroup = Group()
_postMasterGroup = Group()
// Teardown done — allow future `killAll()` calls to commit again.
_teardownMasterPending = false
}
}