1.0.0 release
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
// TriggerEvent.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// A trigger notification posted by the RT audio thread.
|
||||
///
|
||||
/// Value type with no reference fields — bitwise-copied into `SPSCQueue<TriggerEvent>`
|
||||
/// with no ARC traffic or allocation on the RT thread.
|
||||
///
|
||||
/// `sampleTime` is the absolute engine sample counter at the start of the block in which
|
||||
/// the ≤0→>0 edge was detected. `value` carries the instantaneous value of the `SendTrigger`
|
||||
/// value input at the crossing frame.
|
||||
public struct TriggerEvent: Sendable {
|
||||
/// Trigger ID declared on the `SendTrigger` generator. Handlers filter by this value.
|
||||
public let id: Int32
|
||||
/// Value input sampled at the moment of the ≤0→>0 crossing.
|
||||
public let value: Double
|
||||
/// Absolute engine sample time of the block start containing the trigger edge.
|
||||
public let sampleTime: SampleTime
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// TriggerHandlerToken.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Opaque token returned by `TriggerListener.addHandler(id:_:)`.
|
||||
/// Pass to `removeHandler(_:)` to unregister.
|
||||
public struct TriggerHandlerToken: Sendable, Equatable {
|
||||
let id: UInt64
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
// TriggerListener.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Synchronization
|
||||
|
||||
/// Receives trigger notifications posted by `SendTrigger` generators on the RT audio thread.
|
||||
///
|
||||
/// `TriggerListener` mirrors the `MIDI` / `OSCServer` pattern:
|
||||
/// register handlers via `addHandler(id:_:)`, receive `TriggerEvent` + `LyrebirdMessageContext`
|
||||
/// in each handler, and remove handlers via `removeHandler(_:)`.
|
||||
///
|
||||
/// **Setup (RT mode):**
|
||||
/// ```swift
|
||||
/// let listener = TriggerListener(engine: engine) // auto-attaches to engine
|
||||
///
|
||||
/// let token = listener.addHandler(id: 1) { event, ctx in
|
||||
/// ctx.add(MySynth())
|
||||
/// }
|
||||
/// listener.start()
|
||||
/// engine.start() // caches RT signal closure; must come after listener.start()
|
||||
/// // … later …
|
||||
/// engine.stop() // clears RT cache; RT thread stops
|
||||
/// listener.detach() // cancels dispatch source and removes from engine
|
||||
/// listener.removeHandler(token)
|
||||
/// ```
|
||||
///
|
||||
/// **Setup (NRT mode):**
|
||||
/// ```swift
|
||||
/// let driver = NRTDriver(outputURL: url, duration: 5.0)
|
||||
/// let listener = TriggerListener(engine: engine) // auto-attaches
|
||||
/// driver.triggerListener = listener
|
||||
/// // Do NOT call listener.start() for NRT — _drainSync is the sole consumer.
|
||||
/// ```
|
||||
///
|
||||
/// Handlers execute on the `lyrebird.trigger` background queue in RT mode, or inline
|
||||
/// during `NRTDriver.start()` in NRT mode. The `LyrebirdMessageContext` passed to handlers
|
||||
/// dispatches engine mutations to the main thread (RT) or inline (NRT).
|
||||
public final class TriggerListener: @unchecked Sendable {
|
||||
// Sendable invariant: `handlers` is serialised by `lock` for all reads and writes;
|
||||
// `nextTokenID` is `Atomic`. All other stored state is immutable `let` references.
|
||||
|
||||
private let engine: SynthesisEngine
|
||||
|
||||
private let lock: NSLock = NSLock()
|
||||
private var handlers: [(token: TriggerHandlerToken, id: Int32?,
|
||||
onEvent: @Sendable (TriggerEvent, LyrebirdMessageContext) -> Void)] = []
|
||||
private let nextTokenID: Atomic<UInt64> = Atomic<UInt64>(0)
|
||||
|
||||
private let handlerQueue: DispatchQueue = DispatchQueue(label: "lyrebird.trigger", qos: .userInteractive)
|
||||
|
||||
/// Dispatch source that wakes `handlerQueue` when `engine._postTrigger` is called.
|
||||
/// Created and activated in `start()`; cancelled in `stop()`.
|
||||
private var source: DispatchSourceUserDataAdd?
|
||||
|
||||
/// Creates a listener and immediately attaches it to `engine`.
|
||||
/// No separate `engine.attachTriggerListener` call is needed.
|
||||
public init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
engine._attachTriggerListener(self)
|
||||
}
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
/// Remove this listener from the engine and cancel any active dispatch source.
|
||||
/// Call after `engine.stop()` — the RT thread must have stopped before the
|
||||
/// engine's cached RT signal closure is invalidated.
|
||||
public func detach() {
|
||||
stop()
|
||||
engine._detachTriggerListener(self)
|
||||
}
|
||||
|
||||
/// Activate the `DispatchSourceUserDataAdd` that wakes the handler queue when
|
||||
/// the RT thread posts a trigger. Must be called before `engine.start()` so that
|
||||
/// `engine.start()` can cache the signal closure via `_prepareRTSignal()`.
|
||||
///
|
||||
/// Not required for NRT use — `NRTDriver` calls `_drainSync` directly.
|
||||
public func start() {
|
||||
guard source == nil else { return }
|
||||
let src: any DispatchSourceUserDataAdd = DispatchSource.makeUserDataAddSource(queue: handlerQueue)
|
||||
src.setEventHandler { [weak self] in
|
||||
self?._drain()
|
||||
}
|
||||
src.resume()
|
||||
source = src
|
||||
}
|
||||
|
||||
/// Cancel the dispatch source. Call after `engine.stop()` — the RT thread must be
|
||||
/// stopped before this clears the source the engine cached in `_rtTriggerSignalFn`.
|
||||
public func stop() {
|
||||
source?.cancel()
|
||||
source = nil
|
||||
}
|
||||
|
||||
// MARK: - Handler registration
|
||||
|
||||
/// Register a handler that fires when a `SendTrigger` generator with the given `id`
|
||||
/// detects a ≤0→>0 edge. Handlers execute on the `lyrebird.trigger` background queue
|
||||
/// in RT mode, or inline during `NRTDriver.start()` in NRT mode.
|
||||
///
|
||||
/// ```swift
|
||||
/// let token = listener.addHandler(id: 1) { event, ctx in
|
||||
/// let synth = MySynth()
|
||||
/// synth.freq = event.value * 880.0
|
||||
/// ctx.add(synth)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - id: Trigger ID to listen for. Pass `nil` to receive all trigger IDs (wildcard).
|
||||
/// - onEvent: Closure invoked with the `TriggerEvent` and a `LyrebirdMessageContext`.
|
||||
/// - Returns: Token for later removal via `removeHandler(_:)`.
|
||||
@discardableResult
|
||||
public func addHandler(
|
||||
id: Int32? = nil,
|
||||
_ onEvent: @Sendable @escaping (TriggerEvent, LyrebirdMessageContext) -> Void
|
||||
) -> TriggerHandlerToken {
|
||||
let rawID: UInt64 = nextTokenID.add(1, ordering: .acquiringAndReleasing).newValue
|
||||
let token: TriggerHandlerToken = TriggerHandlerToken(id: rawID)
|
||||
lock.withLock { handlers.append((token, id, onEvent)) }
|
||||
return token
|
||||
}
|
||||
|
||||
/// Remove the handler identified by `token`. Thread-safe; safe to call from any queue.
|
||||
public func removeHandler(_ token: TriggerHandlerToken) {
|
||||
lock.withLock { handlers.removeAll { $0.token == token } }
|
||||
}
|
||||
|
||||
// MARK: - Internal: RT signal closure preparation
|
||||
|
||||
/// Called by `SynthesisEngine.start()` on the main thread, before `driver.start()`.
|
||||
/// Returns a closure that the engine caches for RT use — the closure captures the
|
||||
/// dispatch source directly, so the RT thread never reads any mutable listener state.
|
||||
///
|
||||
/// Returns `nil` (as a no-op closure) if `start()` was not called before the engine started.
|
||||
internal func _prepareRTSignal() -> () -> Void {
|
||||
guard let src: any DispatchSourceUserDataAdd = source else { return {} }
|
||||
return { src.add(data: 1) }
|
||||
}
|
||||
|
||||
// MARK: - Internal: drain
|
||||
|
||||
/// Drain `engine.triggerQueue` and dispatch matching handlers.
|
||||
/// Called by the dispatch source event handler in RT mode.
|
||||
private func _drain() {
|
||||
let ctx: LyrebirdMessageContext = LyrebirdMessageContext(engine: engine)
|
||||
_dispatchEvents(ctx: ctx)
|
||||
}
|
||||
|
||||
/// Synchronous drain for NRT use. Called by `NRTDriver` after each `processBlock`.
|
||||
///
|
||||
/// Uses `LyrebirdMessageContext(nrtEngine:)` so `ctx.add(synth)` enqueues directly
|
||||
/// to `pendingQueue` without a `DispatchQueue.main.async` hop, allowing the synth
|
||||
/// to be activated in the very next `processBlock` call.
|
||||
///
|
||||
/// - Precondition: `start()` must NOT have been called on this listener. In NRT mode
|
||||
/// `_drainSync` is the sole consumer of `triggerQueue`. Calling `start()` creates
|
||||
/// a second consumer on the handler queue, violating the SPSC contract.
|
||||
internal func _drainSync() {
|
||||
precondition(source == nil,
|
||||
"TriggerListener: do not call start() on a listener used with NRTDriver. " +
|
||||
"_drainSync is the sole triggerQueue consumer in NRT mode; calling start() " +
|
||||
"creates a second consumer on the handler queue, violating the SPSC contract.")
|
||||
let ctx: LyrebirdMessageContext = LyrebirdMessageContext(nrtEngine: engine)
|
||||
_dispatchEvents(ctx: ctx)
|
||||
}
|
||||
|
||||
private func _dispatchEvents(ctx: LyrebirdMessageContext) {
|
||||
let snapshot: [(token: TriggerHandlerToken, id: Int32?, onEvent: @Sendable (TriggerEvent, LyrebirdMessageContext) -> Void)] = lock.withLock { handlers }
|
||||
while let event: TriggerEvent = engine.triggerQueue.dequeue() {
|
||||
for entry: (token: TriggerHandlerToken, id: Int32?, onEvent: @Sendable (TriggerEvent, LyrebirdMessageContext) -> Void) in snapshot where entry.id == nil || entry.id == event.id {
|
||||
entry.onEvent(event, ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user