208 lines
8.7 KiB
Swift
208 lines
8.7 KiB
Swift
// LyrebirdTask.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import Foundation
|
|
@preconcurrency import CoreFoundation
|
|
import Synchronization
|
|
|
|
/// Like `LyrebirdRoutine` with added `pause()` / `resume()` support.
|
|
///
|
|
/// Pause suspends the thread inside `context.wait()`; resume wakes it.
|
|
/// The body closure is identical to `LyrebirdRoutine`.
|
|
///
|
|
/// ```swift
|
|
/// let task = LyrebirdTask { ctx in
|
|
/// while true {
|
|
/// ctx.add(nextSynth())
|
|
/// try ctx.wait(seconds: 0.25)
|
|
/// }
|
|
/// }
|
|
/// task.start(engine: engine)
|
|
/// task.pause() // freeze event stream
|
|
/// task.resume() // continue from where it stopped
|
|
/// task.stop()
|
|
/// ```
|
|
// @unchecked Sendable invariant: `_stateRaw` is `Atomic<UInt8>` (release/acquire);
|
|
// `_body`, `_control`, and the captured engine reference are immutable post-init;
|
|
// pthread join inside `stop()` / `reset()` flushes the body closure before any
|
|
// re-entry. Capture across actor boundaries is therefore safe.
|
|
public final class LyrebirdTask: @unchecked Sendable {
|
|
|
|
public enum State: Sendable { case idle, running, paused, stopped }
|
|
|
|
private static let resetPollInterval: Double = 0.005
|
|
|
|
private let _body: @Sendable (LyrebirdRoutineContext) throws -> Void
|
|
private let _control: RoutineControl = RoutineControl()
|
|
private let _stateRaw: Atomic<UInt8> = Atomic<UInt8>(RoutineStateRaw.idle)
|
|
|
|
public var state: State {
|
|
switch _stateRaw.load(ordering: .relaxed) {
|
|
case RoutineStateRaw.running: return .running
|
|
case RoutineStateRaw.paused: return .paused
|
|
case RoutineStateRaw.stopped: return .stopped
|
|
default: return .idle
|
|
}
|
|
}
|
|
|
|
public init(_ body: @escaping @Sendable (LyrebirdRoutineContext) throws -> Void) {
|
|
_body = body
|
|
}
|
|
|
|
/// Start the task on a new background thread. Returns immediately.
|
|
/// No-op if not in `.idle` state. Thread-safe: uses compare-exchange to prevent
|
|
/// double-start races between concurrent callers.
|
|
public func start(engine: SynthesisEngine) {
|
|
let (exchanged, _) = _stateRaw.compareExchange(
|
|
expected: RoutineStateRaw.idle,
|
|
desired: RoutineStateRaw.running,
|
|
ordering: .acquiringAndReleasing
|
|
)
|
|
guard exchanged else { return }
|
|
|
|
_control.shouldStop.store(false, ordering: .relaxed)
|
|
_control.isPaused.store(false, ordering: .relaxed)
|
|
_control.threadActive.store(true, ordering: .releasing)
|
|
|
|
let ctx: LyrebirdRoutineContext = LyrebirdRoutineContext(engine: engine, control: _control)
|
|
// Intentional retain: Thread retains self so the task stays alive while
|
|
// the body runs. The cycle breaks when the thread exits and releases self.
|
|
let t: Thread = Thread { [self] in
|
|
do {
|
|
try _body(ctx)
|
|
} catch LyrebirdRoutineError.stopped {
|
|
// clean cancellation
|
|
} catch {
|
|
print("[LyrebirdTask] body threw unexpected error: \(error)")
|
|
}
|
|
_stateRaw.store(RoutineStateRaw.stopped, ordering: .releasing)
|
|
_control.threadActive.store(false, ordering: .releasing)
|
|
}
|
|
t.qualityOfService = .userInitiated
|
|
t.start()
|
|
}
|
|
|
|
/// Suspend the task inside the next `context.wait()` call.
|
|
public func pause() {
|
|
guard _stateRaw.load(ordering: .relaxed) == RoutineStateRaw.running else { return }
|
|
_control.isPaused.store(true, ordering: .releasing)
|
|
_stateRaw.store(RoutineStateRaw.paused, ordering: .releasing)
|
|
}
|
|
|
|
/// Resume a paused task.
|
|
public func resume() {
|
|
guard _stateRaw.load(ordering: .relaxed) == RoutineStateRaw.paused else { return }
|
|
_control.isPaused.store(false, ordering: .releasing)
|
|
_stateRaw.store(RoutineStateRaw.running, ordering: .releasing)
|
|
_control.pauseCondition.broadcast()
|
|
}
|
|
|
|
/// Signal the task to stop. The body exits at the next `context.wait()` call.
|
|
public func stop() {
|
|
_control.shouldStop.store(true, ordering: .releasing)
|
|
_control.pauseCondition.broadcast()
|
|
}
|
|
|
|
/// Stop and reset to `.idle`. Blocks until the background thread has finished.
|
|
/// Do not call from inside the body closure.
|
|
public func reset() {
|
|
stop()
|
|
while _control.threadActive.load(ordering: .acquiring) {
|
|
Thread.sleep(forTimeInterval: LyrebirdTask.resetPollInterval)
|
|
}
|
|
_stateRaw.store(RoutineStateRaw.idle, ordering: .releasing)
|
|
}
|
|
|
|
/// Block the calling thread until the task body completes (or stopped).
|
|
///
|
|
/// Required for CLI / non-GUI callers that block their main thread waiting on a
|
|
/// task. `LyrebirdRoutineContext.add`, `remove`, and `schedule` dispatch to
|
|
/// `DispatchQueue.main` so that engine pendingQueue enqueues honor the engine's
|
|
/// single-producer SPSC contract. If the main thread is parked on a plain
|
|
/// `DispatchSemaphore.wait()` while the task body runs on a background thread,
|
|
/// those dispatched main-async blocks never execute — synthesizers never reach
|
|
/// the engine, `Synthesizer.build()` is never called, and no audio is produced.
|
|
///
|
|
/// This method detects the caller's thread:
|
|
/// - **On main**: pumps `CFRunLoopRun` until a background poller observes the
|
|
/// task transitioning out of `.running` and calls `CFRunLoopStop`. Dispatched
|
|
/// main-async blocks from the task body run normally during the pump.
|
|
/// - **Off main**: plain poll on `threadActive` — the main runloop is free to
|
|
/// process dispatched blocks on its own.
|
|
///
|
|
/// Returns immediately if the task is already in a terminal state.
|
|
/// Do not call from inside the body closure.
|
|
///
|
|
/// ## Multiple concurrent tasks
|
|
///
|
|
/// `waitUntilComplete()` only blocks the *calling* thread; task bodies run on
|
|
/// their own background threads, so several tasks can execute concurrently:
|
|
///
|
|
/// ```swift
|
|
/// let t1 = LyrebirdTask { ctx in /* body 1 */ }
|
|
/// let t2 = LyrebirdTask { ctx in /* body 2 */ }
|
|
/// t1.start(engine: engine) // body 1 on background thread A
|
|
/// t2.start(engine: engine) // body 2 on background thread B (concurrent)
|
|
/// t1.waitUntilComplete() // pumps main runloop — dispatched
|
|
/// // ctx.add/remove from BOTH tasks run on main
|
|
/// t2.waitUntilComplete() // fast-path if done; else keep pumping
|
|
/// ```
|
|
///
|
|
/// `LyrebirdTask.run(engine:body:)` is a single-task convenience that combines
|
|
/// start + wait. Because it blocks the calling thread, you cannot issue a
|
|
/// second `.run` from the same thread while the first is still in flight.
|
|
/// For concurrent CLI tasks, call `start(engine:)` on each and chain
|
|
/// `waitUntilComplete()` calls (as above).
|
|
public func waitUntilComplete() {
|
|
if !_control.threadActive.load(ordering: .acquiring) { return }
|
|
|
|
if Thread.isMainThread {
|
|
// CFRunLoop is thread-safe for stop/wakeup calls per Apple docs;
|
|
// the Sendable warning is suppressed via `nonisolated(unsafe)`.
|
|
nonisolated(unsafe) let mainRunLoop: CFRunLoop? = CFRunLoopGetMain()
|
|
DispatchQueue.global().async { [self] in
|
|
while _control.threadActive.load(ordering: .acquiring) {
|
|
Thread.sleep(forTimeInterval: LyrebirdTask.resetPollInterval)
|
|
}
|
|
CFRunLoopStop(mainRunLoop)
|
|
}
|
|
CFRunLoopRun()
|
|
} else {
|
|
while _control.threadActive.load(ordering: .acquiring) {
|
|
Thread.sleep(forTimeInterval: LyrebirdTask.resetPollInterval)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Convenience for blocking CLI / scripting callers: create, start, and block
|
|
/// until the task body completes.
|
|
///
|
|
/// Equivalent to:
|
|
/// ```swift
|
|
/// let task = LyrebirdTask(body)
|
|
/// task.start(engine: engine)
|
|
/// task.waitUntilComplete()
|
|
/// ```
|
|
///
|
|
/// Use this for CLI demos and scripts where the calling thread should block on
|
|
/// task completion. For GUI / interactive contexts where the caller continues
|
|
/// running, use `start(engine:)` directly and (optionally) hold the returned
|
|
/// task to call `pause()` / `resume()` / `stop()`.
|
|
///
|
|
/// Returns the underlying `LyrebirdTask` for callers that need access after
|
|
/// completion (e.g. to inspect `state`).
|
|
@discardableResult
|
|
public static func run(
|
|
engine: SynthesisEngine,
|
|
body: @escaping @Sendable (LyrebirdRoutineContext) throws -> Void
|
|
) -> LyrebirdTask {
|
|
let task: LyrebirdTask = LyrebirdTask(body)
|
|
task.start(engine: engine)
|
|
task.waitUntilComplete()
|
|
return task
|
|
}
|
|
}
|