fixes for Swift 6 and threading concerns
This commit is contained in:
@@ -81,7 +81,12 @@ open class LyrebirdAudioUnit: AUAudioUnit {
|
||||
|
||||
/// Required override. Construct and return the synthesizer instance that this
|
||||
/// AU should host.
|
||||
open class func makeSynthesizer() -> SynthesizerBase {
|
||||
///
|
||||
/// `@MainActor` (Phase 201): the override constructs a `@MainActor` `SynthesizerBase`
|
||||
/// subclass, so the factory must be main-actor-isolated for a consumer building under
|
||||
/// the MainActor-default mode to override it with no concurrency annotations — the same
|
||||
/// rationale as `SynthesizerBase.build()`. Invoked from `init` on the host's main thread.
|
||||
@MainActor open class func makeSynthesizer() -> SynthesizerBase {
|
||||
fatalError("LyrebirdAudioUnit subclasses must override `makeSynthesizer()`")
|
||||
}
|
||||
|
||||
@@ -222,7 +227,9 @@ open class LyrebirdAudioUnit: AUAudioUnit {
|
||||
) throws {
|
||||
|
||||
// 1. Resolve subclass configuration.
|
||||
let synth: SynthesizerBase = Self.makeSynthesizer()
|
||||
// `makeSynthesizer()` is `@MainActor` (it builds a `@MainActor` synth); `AUAudioUnit`
|
||||
// instances are created by the host on the main thread, so `assumeIsolated` is valid.
|
||||
let synth: SynthesizerBase = MainActor.assumeIsolated { Self.makeSynthesizer() }
|
||||
let blockSize: Int = Self.lyrebirdBlockSize
|
||||
let outputBusSpecs: [LyrebirdAUBusSpec] = Self.lyrebirdOutputBusses
|
||||
let inputBusSpecs: [LyrebirdAUBusSpec] = Self.lyrebirdInputBusses
|
||||
@@ -436,7 +443,18 @@ open class LyrebirdAudioUnit: AUAudioUnit {
|
||||
newEngine.auOutputBusOffsets = _outputBusOffsets
|
||||
newEngine.auInputBusOffsets = _inputBusOffsets
|
||||
try newEngine.start()
|
||||
try newEngine.add(synthesizer)
|
||||
// `engine.add` is `@MainActor` (Phase 201). `allocateRenderResources()` overrides
|
||||
// `AUAudioUnit`'s nonisolated declaration, so this method cannot itself be
|
||||
// `@MainActor`. AU hosts usually call render-resource allocation on the main thread,
|
||||
// but the contract does not guarantee it — the bridge runs the add inline when on
|
||||
// main and hops synchronously otherwise, so an off-main host (e.g. auval) does not
|
||||
// trap. The `nonisolated(unsafe)` local transfers the non-`Sendable` engine into the
|
||||
// bridge closure without tripping region-isolation's sending check (the same value is
|
||||
// reused below at `engine = newEngine`). `synthesizer` is `Sendable` (`SynthesizerBase`
|
||||
// is `@MainActor` ⇒ implicitly Sendable), so it needs no such annotation.
|
||||
nonisolated(unsafe) let engineToConfigure: SynthesisEngine = newEngine
|
||||
let synthToAdd: SynthesizerBase = synthesizer
|
||||
try lyrebirdRunMainActorMutation { try engineToConfigure.add(synthToAdd) }
|
||||
engine = newEngine
|
||||
}
|
||||
|
||||
|
||||
@@ -267,7 +267,7 @@ public extension LyrebirdBuffer {
|
||||
///
|
||||
/// For session-end dumps from a ``LyrebirdEventList`` teardown, see the
|
||||
/// "Persisting Captured Input Buffers" subsection of the Process System
|
||||
/// article (DocC: ``ProcessSystem``) — it covers the background-task
|
||||
/// article (DocC: <doc:ProcessSystem>) — it covers the background-task
|
||||
/// pattern (captures strong buffer refs, gated on the next session via
|
||||
/// `await`) that lets large buffers (4 × ~460 MB) flush to disk without
|
||||
/// blocking the UI and without doubling peak memory on rapid stop/start.
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// MainActorMutationBridge.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Run a `@MainActor` node-tree mutation from a language-side dispatch adapter that may
|
||||
/// execute either on the main thread or inline on a background NRT driver thread.
|
||||
///
|
||||
/// Phase 201 made the engine's add / schedule path and `Synthesizer.build`/`release`/`free`
|
||||
/// `@MainActor`. Most language-side adapters dispatch those mutations through
|
||||
/// `DispatchQueue.main.async`, so they already run on main. Two adapters can run a mutation
|
||||
/// **inline on the calling thread**:
|
||||
///
|
||||
/// - `LyrebirdMessageContext(nrtEngine:)` — the NRT inline dispatcher (`_dispatch = { $0() }`)
|
||||
/// used by `TriggerListener._drainSync`. An NRT render driven from a background thread
|
||||
/// would invoke the mutation off-main.
|
||||
/// - `LyrebirdAudioUnit.allocateRenderResources()` — overrides a nonisolated `AUAudioUnit`
|
||||
/// method; AU hosts *usually* call it on main, but the contract does not guarantee it.
|
||||
///
|
||||
/// A bare `MainActor.assumeIsolated` would **trap** (`dispatch_assert_queue_fail`) on those
|
||||
/// off-main paths. This bridge instead:
|
||||
///
|
||||
/// - runs `body` inline via `assumeIsolated` when already on the main thread (the common
|
||||
/// case — zero hop), and
|
||||
/// - hops synchronously to main otherwise. NRT is offline (not the RT audio thread), so a
|
||||
/// synchronous main hop is acceptable; it never runs on the real-time render callback,
|
||||
/// which uses the default `DispatchQueue.main.async` dispatcher and never reaches here.
|
||||
///
|
||||
/// `body` is intentionally **not** `@Sendable` so it can capture the non-`Sendable` engine /
|
||||
/// synthesizer it mutates; `DispatchQueue.sync` does not escape the closure, so this is safe.
|
||||
/// `body` returns `Void`: a non-`Sendable` result would have to cross back from the main
|
||||
/// thread on the off-main hop, which `DispatchQueue.sync` rejects. All node-tree mutations
|
||||
/// here are fire-and-forget, so `Void` is sufficient and keeps the signature simple.
|
||||
@inline(__always)
|
||||
internal func lyrebirdRunMainActorMutation(_ body: @MainActor () throws -> Void) rethrows {
|
||||
// NOTE: no `_lyrebirdAssertNotOnRTThread()` here. `RTThreadIdentity` is a thread-local
|
||||
// marker that persists on pooled/reused threads (and AU drivers may mark the allocate
|
||||
// thread), so an assert false-positives on legitimate off-main callers like AUv3
|
||||
// `allocateRenderResources`. RT-path purity is instead enforced statically by the
|
||||
// `generatorSourcesContainNoActorHopMachinery` source lint (Phase201IsolationGuardTests).
|
||||
if Thread.isMainThread {
|
||||
try MainActor.assumeIsolated(body)
|
||||
return
|
||||
}
|
||||
try DispatchQueue.main.sync { try MainActor.assumeIsolated(body) }
|
||||
}
|
||||
@@ -81,6 +81,19 @@ internal enum RTThreadIdentity {
|
||||
let sentinel: UnsafeMutableRawPointer? = UnsafeMutableRawPointer(bitPattern: _markerBitPattern)
|
||||
return pthread_getspecific(_key) == sentinel
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
/// TEST-ONLY: clear the RT marker on the calling thread.
|
||||
///
|
||||
/// Production never unmarks — an RT render thread stays an RT render thread for the
|
||||
/// engine's life. But tests that call ``markCurrentThreadAsRT()`` on a transient
|
||||
/// `DispatchQueue(label:)` worker must clear it before that pthread returns to the
|
||||
/// system pool; otherwise the stale marker can false-trip `_lyrebirdAssertNotOnRTThread`
|
||||
/// in a later test that the pool hands the same thread. Not compiled in release.
|
||||
internal static func _clearCurrentThreadRTMarkForTesting() {
|
||||
pthread_setspecific(_key, nil)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - DEBUG assert helper
|
||||
|
||||
@@ -1291,7 +1291,7 @@ public final class SynthesisEngine {
|
||||
/// dropped and the binding (if just acquired) released. Callers can react by
|
||||
/// retrying after a future block, increasing `eventQueueCapacity` at engine
|
||||
/// init time, or surfacing a UI-level back-off.
|
||||
public func schedule(
|
||||
@MainActor public func schedule(
|
||||
_ synth: any Synthesizer,
|
||||
at time: SampleTime
|
||||
) throws {
|
||||
@@ -1320,7 +1320,7 @@ public final class SynthesisEngine {
|
||||
/// - `EngineAddError.boundToOtherEngine` — synth is bound to a different engine.
|
||||
/// - `EngineAddError.pendingQueueFull` — pendingQueue was full; the event was
|
||||
/// dropped and the binding (if just acquired) released.
|
||||
public func schedule(
|
||||
@MainActor public func schedule(
|
||||
_ synth: any Synthesizer,
|
||||
after seconds: Double
|
||||
) throws {
|
||||
@@ -1393,7 +1393,7 @@ public final class SynthesisEngine {
|
||||
/// Equivalent to `schedule(_:at:currentTime)`. The synthesizer lands at the head of
|
||||
/// `mainGroup` — newest-first order. Safe to call from the main thread.
|
||||
/// - Throws: `EngineAddError` — see `schedule(_:at:)` for cases.
|
||||
public func add(_ synth: any Synthesizer) throws {
|
||||
@MainActor public func add(_ synth: any Synthesizer) throws {
|
||||
try schedule(synth, at: currentTime)
|
||||
}
|
||||
|
||||
@@ -1407,7 +1407,7 @@ public final class SynthesisEngine {
|
||||
/// group-relative insertion, or `.before(_:)` / `.after(_:)` for sibling-relative
|
||||
/// insertion (linear O(n) tree search; falls back to `mainGroup` head on miss).
|
||||
/// - Throws: `EngineAddError` — see `schedule(_:at:)` for cases.
|
||||
public func add(
|
||||
@MainActor public func add(
|
||||
_ synth: any Synthesizer,
|
||||
position: NodePosition
|
||||
) throws {
|
||||
@@ -1744,7 +1744,10 @@ public final class SynthesisEngine {
|
||||
/// Build the generator DAG and pre-allocate the linked-list `PreparedNode`.
|
||||
/// All allocation and `build()`/`rebuildGraph()` happen here on the calling thread;
|
||||
/// the RT thread never allocates in `applyEvent`.
|
||||
private func prepareNode(_ synth: any Synthesizer) -> PreparedNode {
|
||||
/// `@MainActor`: invokes `build()` / `rebuildGraph()` (the `@MainActor` language-side
|
||||
/// add surface — Phase 201). The node-tree add path runs on the main thread by
|
||||
/// contract (it also touches `nodeTreeMirror`, observed by SwiftUI).
|
||||
@MainActor private func prepareNode(_ synth: any Synthesizer) -> PreparedNode {
|
||||
if let base: SynthesizerBase = synth as? SynthesizerBase {
|
||||
base.rebuildGraph()
|
||||
} else {
|
||||
@@ -1754,7 +1757,7 @@ public final class SynthesisEngine {
|
||||
}
|
||||
|
||||
/// Build the generator DAG, pre-allocate the linked-list node, and wrap in a `.add` event.
|
||||
private func prepareAddEvent(
|
||||
@MainActor private func prepareAddEvent(
|
||||
_ synth: any Synthesizer,
|
||||
at time: SampleTime
|
||||
) -> ScheduledEvent {
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
/// ``SpectralPlayBuffer`` conform out of the box. Any future generator that
|
||||
/// supports `.freeNode` semantics can opt in by adopting this protocol and
|
||||
/// forwarding to its own atomic flag, then calling
|
||||
/// ``_registerAutoFreeIfNeeded(_:)`` from its designated init.
|
||||
/// `_registerAutoFreeIfNeeded(_:)` from its designated init.
|
||||
public protocol DoneActionWatchable: AnyObject {
|
||||
/// `true` once the generator's `doneAction == .freeNode` has
|
||||
/// fired. Backed by an atomic load — safe to read from any thread.
|
||||
|
||||
+22
-10
@@ -56,8 +56,13 @@ public struct LyrebirdMessageContext: @unchecked Sendable {
|
||||
public func add(_ synth: any Synthesizer) {
|
||||
let args: SynthArgs = SynthArgs(engine, synth)
|
||||
_dispatch {
|
||||
do { try args.engine.add(args.synth) }
|
||||
catch { print("[Lyrebird] MessageContext.add failed: \(error)") }
|
||||
// `_dispatch` runs this on main (default `DispatchQueue.main.async`) or inline on
|
||||
// the NRT driver thread. `engine.add` is `@MainActor` (Phase 201); the bridge runs
|
||||
// it inline when already on main and hops synchronously otherwise — never traps.
|
||||
lyrebirdRunMainActorMutation {
|
||||
do { try args.engine.add(args.synth) }
|
||||
catch { print("[Lyrebird] MessageContext.add failed: \(error)") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,8 +79,10 @@ public struct LyrebirdMessageContext: @unchecked Sendable {
|
||||
) {
|
||||
let args: SynthArgs = SynthArgs(engine, synth)
|
||||
_dispatch {
|
||||
do { try args.engine.schedule(args.synth, at: time) }
|
||||
catch { print("[Lyrebird] MessageContext.schedule(at:) failed: \(error)") }
|
||||
lyrebirdRunMainActorMutation {
|
||||
do { try args.engine.schedule(args.synth, at: time) }
|
||||
catch { print("[Lyrebird] MessageContext.schedule(at:) failed: \(error)") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,8 +93,10 @@ public struct LyrebirdMessageContext: @unchecked Sendable {
|
||||
) {
|
||||
let args: SynthArgs = SynthArgs(engine, synth)
|
||||
_dispatch {
|
||||
do { try args.engine.schedule(args.synth, after: seconds) }
|
||||
catch { print("[Lyrebird] MessageContext.schedule(after:) failed: \(error)") }
|
||||
lyrebirdRunMainActorMutation {
|
||||
do { try args.engine.schedule(args.synth, after: seconds) }
|
||||
catch { print("[Lyrebird] MessageContext.schedule(after:) failed: \(error)") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,10 +133,13 @@ public struct LyrebirdMessageContext: @unchecked Sendable {
|
||||
// but a warning posts to LyrebirdMessageCenter so debug builds get
|
||||
// visibility into typo'd OSC / MIDI param names that would
|
||||
// otherwise route silently to nowhere.
|
||||
do {
|
||||
try args.synth.updateParameter(args.key, value: args.value)
|
||||
} catch {
|
||||
Task { @MainActor in
|
||||
// `updateParameter` is `@MainActor` (Phase 201). `_dispatch` runs this on main
|
||||
// (default) or inline on the NRT driver — the bridge runs inline on main and hops
|
||||
// synchronously off-main, never trapping.
|
||||
lyrebirdRunMainActorMutation {
|
||||
do {
|
||||
try args.synth.updateParameter(args.key, value: args.value)
|
||||
} catch {
|
||||
LyrebirdMessageCenter.shared.post(
|
||||
.warning,
|
||||
"parameter '\(args.key)' on \(type(of: args.synth)) — \(error)",
|
||||
|
||||
@@ -31,24 +31,24 @@
|
||||
///
|
||||
/// ## Do not double-register
|
||||
///
|
||||
/// A `RootRegistering` generator that auto-registers from inside ``build()``
|
||||
/// **and** is also passed to ``SynthesizerBase/addOutputGenerator(_:)`` will
|
||||
/// A `RootRegistering` generator that auto-registers from inside `build()`
|
||||
/// **and** is also passed to `SynthesizerBase.addOutputGenerator(_:)` will
|
||||
/// appear twice in `outputGenerators`. Within one block segment the second
|
||||
/// evaluation is short-circuited by the ``Generator/_segmentSerial`` fan-out
|
||||
/// evaluation is short-circuited by the `_segmentSerial` fan-out
|
||||
/// cache (no `_computeSamples` re-run), so the side effect fires exactly
|
||||
/// once — but the double entry adds a redundant cache check per segment. Let
|
||||
/// auto-registration handle it, or construct outside ``build()`` and register
|
||||
/// auto-registration handle it, or construct outside `build()` and register
|
||||
/// manually — never both.
|
||||
///
|
||||
/// ## Relationship to `DoneActionWatchable`
|
||||
///
|
||||
/// `RootRegistering` mirrors the ``DoneActionWatchable`` auto-registration
|
||||
/// pattern. Both protocols read the same
|
||||
/// ``SynthesizerBase/_currentlyBuildingRef`` task-local set by
|
||||
/// ``SynthesizerBase/rebuildGraph()``. A generator may conform to both
|
||||
/// `_SynthesizerBuildContext.currentRef` task-local set by
|
||||
/// `SynthesizerBase.rebuildGraph()`. A generator may conform to both
|
||||
/// (e.g. ``RecordBuffer/Audio``): the init calls
|
||||
/// ``DoneActionWatchable/_registerAutoFreeIfNeeded(_:)`` and then
|
||||
/// ``_registerAsRootIfBuilding()``.
|
||||
/// `_registerAutoFreeIfNeeded(_:)` and then
|
||||
/// `_registerAsRootIfBuilding()`.
|
||||
public protocol RootRegistering: Generator {}
|
||||
|
||||
extension RootRegistering {
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
/// Additive ``Out`` writers that run **after** ReplaceOut accumulate into the
|
||||
/// replaced content as normal.
|
||||
///
|
||||
/// Inside a ``ParallelGroup``, ReplaceOut routes through ``ScratchBuses.replace``
|
||||
/// Inside a ``ParallelGroup``, ReplaceOut routes through `ScratchBuses.replace`
|
||||
/// and only overwrites *this child's scratch contribution*. It does not scrub
|
||||
/// other siblings' parallel writes nor any pre-parallel engine-bus content. See
|
||||
/// `docs/engine/eventlist-routing-design.md` for the full semantic table.
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
/// `[-step, step]` to the current state, clamping to `[low, high]`.
|
||||
///
|
||||
/// RT-side counterpart to ``Pattern/brownian(low:high:step:start:length:seed:)``.
|
||||
/// Backed by the same module-internal ``BrownianPatternEngine``. Complement
|
||||
/// Backed by the same module-internal `BrownianPatternEngine`. Complement
|
||||
/// to ``DemandTemporalBrownian``: this is a plain stateless-parameter
|
||||
/// Brownian walk, while ``DemandTemporalBrownian`` accepts
|
||||
/// ``RTTemporalParameter`` bounds / step that can evolve over time.
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
/// Demand-rate geometric series: `start, start·ratio, start·ratio², …`.
|
||||
///
|
||||
/// RT-side counterpart to ``Pattern/geometric(start:ratio:length:)``. Backed
|
||||
/// by the same module-internal ``GeometricPatternEngine``.
|
||||
/// by the same module-internal `GeometricPatternEngine`.
|
||||
///
|
||||
/// **RT contract** — `nextValue()` and `reset()` are pure arithmetic; no
|
||||
/// allocation, no locks. Single-owner per puller.
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
/// Demand-rate random pick avoiding the same *index* as the previous pick.
|
||||
///
|
||||
/// RT-side counterpart to ``Pattern/nonRepeatingRandom(_:repeats:seed:)``.
|
||||
/// Backed by the same module-internal ``NonRepeatingRandomPatternEngine``
|
||||
/// Backed by the same module-internal `NonRepeatingRandomPatternEngine`
|
||||
/// parameterised over `Double`. Matches SC `Dxrand` semantics.
|
||||
///
|
||||
/// **Index-based, not value-based.** If `values` contains duplicate doubles
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
/// Demand-rate arithmetic series: `start, start + step, start + 2·step, …`.
|
||||
///
|
||||
/// RT-side counterpart to ``Pattern/series(start:step:length:)``. Backed by
|
||||
/// the same module-internal ``SeriesPatternEngine`` — algorithm and behaviour
|
||||
/// the same module-internal `SeriesPatternEngine` — algorithm and behaviour
|
||||
/// match exactly. `length == -1` runs forever.
|
||||
///
|
||||
/// **RT contract** — `nextValue()` and `reset()` are pure arithmetic; no
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
/// cycles through the permuted order. Same permutation replays on `reset()`.
|
||||
///
|
||||
/// RT-side counterpart to ``Pattern/shuffle(_:repeats:seed:)``. Backed by the
|
||||
/// same module-internal ``ShufflePatternEngine`` parameterised over `Double`.
|
||||
/// same module-internal `ShufflePatternEngine` parameterised over `Double`.
|
||||
/// Matches SC `Dshuf` semantics.
|
||||
///
|
||||
/// **RT contract** — Fisher-Yates runs once at init (off the RT thread).
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
/// Demand-rate uniform random samples in `[low, high]`.
|
||||
///
|
||||
/// RT-side counterpart to ``Pattern/uniformRandom(low:high:length:seed:)``.
|
||||
/// Backed by the same module-internal ``UniformRandomPatternEngine``.
|
||||
/// Backed by the same module-internal `UniformRandomPatternEngine`.
|
||||
/// Complement to the pool-based ``DemandRandom``: this draws continuous
|
||||
/// values inside a range rather than picking from a discrete set.
|
||||
///
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
/// the matching entry in `weights`.
|
||||
///
|
||||
/// RT-side counterpart to ``Pattern/weightedRandom(_:weights:repeats:seed:)``.
|
||||
/// Backed by the same module-internal ``WeightedRandomPatternEngine``
|
||||
/// Backed by the same module-internal `WeightedRandomPatternEngine`
|
||||
/// parameterised over `Double`. Matches SC `Dwrand` semantics.
|
||||
///
|
||||
/// **Init preconditions** — `values.count == weights.count`, all weights
|
||||
|
||||
@@ -227,5 +227,6 @@ The full helper-boundary policy lives in [`docs/protocols/writing-generators.md`
|
||||
- ``LyrebirdProcess``
|
||||
- ``ValidGeneratorInput``
|
||||
- ``ValueComputable``
|
||||
- `docs/protocols/writing-generators.md` § 3.1 — init-time resolution contract
|
||||
- `docs/protocols/writing-generators.md` § 13 — shared helper functions
|
||||
|
||||
Further reading: `docs/protocols/writing-generators.md` § 3.1 (init-time resolution
|
||||
contract) and § 13 (shared helper functions).
|
||||
|
||||
@@ -189,7 +189,7 @@ Affected parameters include ``AmbiEncoder1/init(input:azimuth:elevation:mul:add:
|
||||
|
||||
To convert at the language-side boundary — UI knobs that present degrees to
|
||||
musicians, OSC messages from external apps, score files that author in degrees —
|
||||
use ``degreesToRadians(_:)`` and ``radiansToDegrees(_:)`` from `LyrebirdMusicMath`:
|
||||
use `degreesToRadians(_:)` and `radiansToDegrees(_:)` from `LyrebirdMusicMath`:
|
||||
|
||||
```swift
|
||||
let azDeg: Double = 45.0
|
||||
|
||||
@@ -529,8 +529,6 @@ A 20-minute mono buffer at 48 kHz is ~460 MB; four of them is ~1.8 GB and severa
|
||||
3. `await` that task, then `clear()` the buffers in place and rebuild the input synths so the next performance starts fresh.
|
||||
4. If the engine is stopped while a write is still in flight, retain the `Task` and `await` it before allocating fresh buffers for the next session — otherwise the writer's pinned refs and new allocations coexist (~2× memory peak).
|
||||
|
||||
```swift
|
||||
|
||||
```swift
|
||||
// On engine .stopped — launch a background write that survives invalidate / nil-out.
|
||||
@discardableResult
|
||||
@@ -1026,10 +1024,10 @@ The `LyrebirdUI` module provides SwiftUI panels that bind directly to a `Lyrebir
|
||||
|
||||
| View | Bound to | Purpose |
|
||||
|------|----------|---------|
|
||||
| ``LyrebirdProcessView`` | one `LyrebirdProcess` | Start / Release transport, amp slider, running-state indicator. |
|
||||
| ``LyrebirdEventListView`` | one `LyrebirdEventList` | Now/Next event display, master amp slider, Next / Skip / Release All / Kill All / Reset / Set Next. |
|
||||
| ``LyrebirdRunningProcessesView`` | one `LyrebirdEventList` | One `LyrebirdProcessView` per currently-running process owned by the list. Appears when a process starts; disappears when it finishes. |
|
||||
| ``LyrebirdEventListPerformanceView`` | one `LyrebirdEventList` | Larger performance-focused panel. |
|
||||
| `LyrebirdProcessView` | one `LyrebirdProcess` | Start / Release transport, amp slider, running-state indicator. |
|
||||
| `LyrebirdEventListView` | one `LyrebirdEventList` | Now/Next event display, master amp slider, Next / Skip / Release All / Kill All / Reset / Set Next. |
|
||||
| `LyrebirdRunningProcessesView` | one `LyrebirdEventList` | One `LyrebirdProcessView` per currently-running process owned by the list. Appears when a process starts; disappears when it finishes. |
|
||||
| `LyrebirdEventListPerformanceView` | one `LyrebirdEventList` | Larger performance-focused panel. |
|
||||
|
||||
### Mounting in a Host View
|
||||
|
||||
@@ -1057,11 +1055,11 @@ struct MyPiece: View {
|
||||
}
|
||||
```
|
||||
|
||||
`LyrebirdRunningProcessesView` polls `eventList.allProcesses` at 10 Hz (same cadence as the other panels), filters to processes for which `isRunning == true`, and instantiates one ``LyrebirdProcessView`` per surviving entry. Identity is tracked by `ObjectIdentifier`, not by `LyrebirdProcess.id`, so two processes that happen to share an `id` string render as distinct rows. The poll only re-assigns its `@State` snapshot when the set of running identities changes — child `LyrebirdProcessView` instances persist across ticks, so per-row UI state (slider drag, focus) is not destroyed every 100 ms.
|
||||
`LyrebirdRunningProcessesView` polls `eventList.allProcesses` at 10 Hz (same cadence as the other panels), filters to processes for which `isRunning == true`, and instantiates one `LyrebirdProcessView` per surviving entry. Identity is tracked by `ObjectIdentifier`, not by `LyrebirdProcess.id`, so two processes that happen to share an `id` string render as distinct rows. The poll only re-assigns its `@State` snapshot when the set of running identities changes — child `LyrebirdProcessView` instances persist across ticks, so per-row UI state (slider drag, focus) is not destroyed every 100 ms.
|
||||
|
||||
### Standalone (non-EventList) Processes
|
||||
|
||||
``LyrebirdRunningProcessesView`` is scoped to one `LyrebirdEventList`. A standalone process created directly via `LyrebirdProcess.init(...)` and played via `process.play(engine:)` is not visible there — host code keeps its own reference and embeds a ``LyrebirdProcessView`` for it directly:
|
||||
`LyrebirdRunningProcessesView` is scoped to one `LyrebirdEventList`. A standalone process created directly via `LyrebirdProcess.init(...)` and played via `process.play(engine:)` is not visible there — host code keeps its own reference and embeds a `LyrebirdProcessView` for it directly:
|
||||
|
||||
```swift
|
||||
LyrebirdProcessView(process: standaloneProcess, engine: engine)
|
||||
@@ -1069,7 +1067,7 @@ LyrebirdProcessView(process: standaloneProcess, engine: engine)
|
||||
|
||||
### macOS Standalone Windows
|
||||
|
||||
Each panel has a `presentInWindow(...)` factory that opens a free-floating ``LyrebirdWindow`` — useful for REPL / CLI demos that have no parent SwiftUI scene:
|
||||
Each panel has a `presentInWindow(...)` factory that opens a free-floating `LyrebirdWindow` — useful for REPL / CLI demos that have no parent SwiftUI scene:
|
||||
|
||||
```swift
|
||||
let win = LyrebirdRunningProcessesView.presentInWindow(
|
||||
@@ -1092,11 +1090,11 @@ win.close()
|
||||
- ``LyrebirdProcessError``
|
||||
- ``LyrebirdTimelineEntry``
|
||||
- ``LyrebirdTimelineError``
|
||||
- ``LyrebirdProcessView``
|
||||
- ``LyrebirdEventListView``
|
||||
- ``LyrebirdRunningProcessesView``
|
||||
- ``LyrebirdEventListPerformanceView``
|
||||
- <doc:ValueComputable>
|
||||
- <doc:ScoreSystem>
|
||||
- <doc:SynthesizerProtocol>
|
||||
- <doc:RoutineTask>
|
||||
|
||||
SwiftUI panels (in the separate `LyrebirdUI` module): `LyrebirdProcessView`,
|
||||
`LyrebirdEventListView`, `LyrebirdRunningProcessesView`,
|
||||
`LyrebirdEventListPerformanceView`.
|
||||
|
||||
@@ -32,7 +32,7 @@ Optional GUI module.
|
||||
import LyrebirdUI
|
||||
```
|
||||
|
||||
Provides: `LyrebirdWindow` (AppKit/SwiftUI host), `@SynthParam` property wrapper, and pre-built slider/knob views. Uses Swift 5 language mode to avoid actor-isolation diagnostics in SwiftUI/AppKit interop.
|
||||
Provides: `LyrebirdWindow` (AppKit/SwiftUI host), `@SynthParam` property wrapper, and pre-built slider/knob views. Builds under Swift 6 language mode (Phase 202).
|
||||
|
||||
**Rule:** never import `LyrebirdUI` in `Lyrebird` — GUI code must stay in this module only.
|
||||
|
||||
@@ -49,7 +49,7 @@ lyrebird export MySynth
|
||||
lyrebird repl
|
||||
```
|
||||
|
||||
Provides an interactive `lyrebird>` shell with history and tab completion. Uses Swift 5 language mode (LineNoise predates Swift 6 concurrency annotations).
|
||||
Provides an interactive `lyrebird>` shell with history and tab completion. Builds under Swift 6 language mode (Phase 202).
|
||||
|
||||
See <doc:CLIGuide> for a full walkthrough.
|
||||
|
||||
@@ -104,12 +104,12 @@ swift test
|
||||
```
|
||||
LyrebirdC
|
||||
└── Lyrebird (links CoreAudio, AudioToolbox, Accelerate)
|
||||
├── LyrebirdUI (SwiftUI + AppKit, Swift 5 mode)
|
||||
├── LyrebirdUI (SwiftUI + AppKit)
|
||||
├── LyrebirdDemo
|
||||
├── LyrebirdBenchmark
|
||||
└── LyrebirdUIDemo (also links LyrebirdUI)
|
||||
|
||||
LyrebirdCLI (links LineNoise, Swift 5 mode)
|
||||
LyrebirdCLI (links LineNoise)
|
||||
```
|
||||
|
||||
## Choosing a Starting Point
|
||||
|
||||
@@ -147,8 +147,8 @@ public func ratioToCents(_ ratios: [Double]) -> [Double] { ratios.map { ratioToC
|
||||
/// Useful for driving pitch-shift / playback-rate generators that take a ratio
|
||||
/// while you reason musically in semitones — e.g. `PitchShift.Audio(pitchRatio: midiToRatio(12))`.
|
||||
///
|
||||
/// Synonym for ``semitonesToRatio(_:)`` with an SC-flavored name that mirrors
|
||||
/// ``midiToHz(_:)``. Both compile to the same expression; pick whichever reads
|
||||
/// Synonym for `semitonesToRatio(_:)` with an SC-flavored name that mirrors
|
||||
/// `midiToHz(_:)`. Both compile to the same expression; pick whichever reads
|
||||
/// best at the call site.
|
||||
@inline(__always)
|
||||
public func midiToRatio(_ semitones: Double) -> Double { semitonesToRatio(semitones) }
|
||||
@@ -160,7 +160,7 @@ public func midiToRatio(_ semitones: Int) -> Double { semitonesToRatio(Double(se
|
||||
/// Frequency ratio → semitone interval (MIDI delta). `2.0` → `12.0`, `0.5` → `-12.0`,
|
||||
/// `1.0` → `0.0`. Returns `-.infinity` / `NaN` for `ratio <= 0`.
|
||||
///
|
||||
/// Synonym for ``ratioToSemitones(_:)`` paired with ``midiToRatio(_:)``.
|
||||
/// Synonym for `ratioToSemitones(_:)` paired with `midiToRatio(_:)`.
|
||||
@inline(__always)
|
||||
public func ratioToMidi(_ ratio: Double) -> Double { ratioToSemitones(ratio) }
|
||||
|
||||
@@ -434,7 +434,7 @@ public extension Collection where Element == Double {
|
||||
func semitonesToRatio() -> [Double] { map { LyrebirdSynth.semitonesToRatio($0) } }
|
||||
|
||||
/// Semitone intervals → frequency ratio per element. SC-flavored synonym
|
||||
/// for ``semitonesToRatio()`` matching the ``midiToHz()`` / ``hzToMidi()``
|
||||
/// for `semitonesToRatio(_:)` matching the `midiToHz(_:)` / `hzToMidi(_:)`
|
||||
/// naming pair. Language-side only — allocates a new `[Double]`.
|
||||
func midiToRatio() -> [Double] { map { LyrebirdSynth.midiToRatio($0) } }
|
||||
|
||||
|
||||
@@ -75,7 +75,11 @@ public final class Group: Synthesizer {
|
||||
// MARK: - Synthesizer conformance
|
||||
|
||||
/// Groups have no generator graph of their own.
|
||||
public func build() {}
|
||||
///
|
||||
/// `nonisolated`: a less-isolated witness still satisfies the `@MainActor`
|
||||
/// `Synthesizer.build()` requirement. Lets the engine install `mainGroup` pre-start
|
||||
/// from `init` without an actor hop.
|
||||
nonisolated public func build() {}
|
||||
|
||||
/// Evaluate all children in insertion order.
|
||||
public func evaluate(
|
||||
@@ -104,7 +108,13 @@ public final class Group: Synthesizer {
|
||||
/// only the first call starts the cascade.
|
||||
///
|
||||
/// Language-side only — do not call from the RT thread.
|
||||
public func release(engine: SynthesisEngine) {
|
||||
///
|
||||
/// `@MainActor` (Phase 201): the child cascade calls the `@MainActor`
|
||||
/// `child.release`/`child.free`. The self-free poll timer — which runs its handler on a
|
||||
/// utility queue and therefore must NOT be main-actor-isolated — is installed by the
|
||||
/// `nonisolated` helper `_startSelfFreeTimer(engine:)` so the handler does not inherit
|
||||
/// this method's isolation (which would trap when the timer fires off-main).
|
||||
@MainActor public func release(engine: SynthesisEngine) {
|
||||
let (exchanged, _) = _releaseStarted.compareExchange(
|
||||
expected: false, desired: true, ordering: .sequentiallyConsistent
|
||||
)
|
||||
@@ -144,6 +154,18 @@ public final class Group: Synthesizer {
|
||||
return
|
||||
}
|
||||
|
||||
_startSelfFreeTimer(engine: engine)
|
||||
}
|
||||
|
||||
/// Install the repeating utility-queue timer that self-frees this group once its child
|
||||
/// count reaches zero.
|
||||
///
|
||||
/// `nonisolated` so the `setEventHandler` closure does NOT inherit `release`'s
|
||||
/// `@MainActor` isolation (Phase 201) — a main-actor-isolated handler would trap
|
||||
/// (`dispatch_assert_queue_fail`) when the timer fires on the utility queue. The handler
|
||||
/// touches only the atomic count off-main and hops to main (via the `@unchecked Sendable`
|
||||
/// ``GroupFreeArgs``) for the actual `free`.
|
||||
nonisolated private func _startSelfFreeTimer(engine: SynthesisEngine) {
|
||||
// Poll count atomically; self-free when empty. `source` is captured strongly in its
|
||||
// own handler — this intentional retain cycle is broken by the `source.cancel()` calls
|
||||
// on all exit paths, so the timer does not leak.
|
||||
@@ -153,11 +175,14 @@ public final class Group: Synthesizer {
|
||||
guard let self: Group, let engine: SynthesisEngine else { source.cancel(); return }
|
||||
if self._atomicCount.load(ordering: .relaxed) == 0 {
|
||||
source.cancel()
|
||||
// Hop to main: `free(engine:)` mutates `engine.nodeTreeMirror`,
|
||||
// which is observed by SwiftUI on the main thread. Touching it
|
||||
// from the timer's utility queue would race with view reads.
|
||||
// Hop to main: `free(engine:)` is `@MainActor` and mutates
|
||||
// `engine.nodeTreeMirror`, which is observed by SwiftUI on the main
|
||||
// thread. Touching it from the timer's utility queue would race with
|
||||
// view reads. `assumeIsolated` documents that this runs on main.
|
||||
let args: GroupFreeArgs = GroupFreeArgs(group: self, engine: engine)
|
||||
DispatchQueue.main.async { args.group.free(engine: args.engine) }
|
||||
DispatchQueue.main.async {
|
||||
MainActor.assumeIsolated { args.group.free(engine: args.engine) }
|
||||
}
|
||||
}
|
||||
}
|
||||
source.resume()
|
||||
@@ -170,7 +195,7 @@ public final class Group: Synthesizer {
|
||||
/// removed from its parent in the node tree.
|
||||
///
|
||||
/// Language-side only — do not call from the RT thread.
|
||||
public func free(engine: SynthesisEngine) {
|
||||
@MainActor public func free(engine: SynthesisEngine) {
|
||||
let enqueued: Bool = engine.pendingQueue.enqueue(
|
||||
.groupFree(self, parentGroup: nil, at: engine.currentTime)
|
||||
)
|
||||
|
||||
@@ -108,7 +108,7 @@ public final class ParallelGroup: Synthesizer {
|
||||
/// is built immediately (equivalent to the engine's `prepareAddEvent` path).
|
||||
///
|
||||
/// - Parameter synth: The synthesizer to add. Must not already be active in any engine.
|
||||
public func add(_ synth: any Synthesizer) {
|
||||
@MainActor public func add(_ synth: any Synthesizer) {
|
||||
if let base: SynthesizerBase = synth as? SynthesizerBase {
|
||||
base.rebuildGraph()
|
||||
} else {
|
||||
@@ -121,7 +121,11 @@ public final class ParallelGroup: Synthesizer {
|
||||
|
||||
/// Snapshot children and allocate scratch buses. Called by the engine's
|
||||
/// `prepareAddEvent` path (off the RT thread) before this group is wired in.
|
||||
public func build() {
|
||||
///
|
||||
/// `nonisolated`: a less-isolated witness satisfies the `@MainActor` `build()`
|
||||
/// requirement. Mutates only nonisolated snapshot/scratch state, read on the RT thread
|
||||
/// in `evaluate()` after the add barrier.
|
||||
nonisolated public func build() {
|
||||
childrenSnapshot.removeAll(keepingCapacity: true)
|
||||
var node: PreparedNode? = head
|
||||
while let current: PreparedNode = node {
|
||||
|
||||
@@ -43,7 +43,7 @@ public extension Pattern {
|
||||
|
||||
/// Picks one value at random from `values` per call, never picking the
|
||||
/// same *index* as the previous pick. See
|
||||
/// ``NonRepeatingRandomPatternEngine`` for the index-vs-value caveat
|
||||
/// `NonRepeatingRandomPatternEngine` for the index-vs-value caveat
|
||||
/// when `values` contains duplicates.
|
||||
///
|
||||
/// - Parameters:
|
||||
|
||||
@@ -404,7 +404,7 @@ public final class LyrebirdEventList: @unchecked Sendable {
|
||||
/// Master amplitude, lag-smoothed.
|
||||
///
|
||||
/// Writing ramps to the new value over `ampLag` seconds.
|
||||
public var amp: Double {
|
||||
@MainActor public var amp: Double {
|
||||
get { _masterSynth?.$amp.value ?? _initialAmp }
|
||||
set { _masterSynth?.amp = newValue }
|
||||
}
|
||||
@@ -446,14 +446,14 @@ public final class LyrebirdEventList: @unchecked Sendable {
|
||||
/// fires. The synth's lifetime is bounded by `_masterGroup.free()` in
|
||||
/// `_teardownMaster()` — it is automatically released on EventList
|
||||
/// teardown.
|
||||
public func addPreMaster(_ synth: any Synthesizer) throws {
|
||||
@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(_:)``.
|
||||
public func addPostMaster(_ synth: any Synthesizer) throws {
|
||||
@MainActor public func addPostMaster(_ synth: any Synthesizer) throws {
|
||||
try _engine.add(synth, position: .tail(of: _postMasterGroup))
|
||||
}
|
||||
|
||||
@@ -523,7 +523,7 @@ public final class LyrebirdEventList: @unchecked Sendable {
|
||||
/// Play the event at the current ``index`` and increment the index.
|
||||
///
|
||||
/// No-op when ``nextEvent`` is `nil` (past the end).
|
||||
public func next() {
|
||||
@MainActor public func next() {
|
||||
guard _index < _events.count else { return }
|
||||
let idx: Int = _index
|
||||
_index += 1
|
||||
@@ -535,7 +535,7 @@ public final class LyrebirdEventList: @unchecked Sendable {
|
||||
/// Out-of-range indices are silently ignored.
|
||||
///
|
||||
/// - Parameter eventIndex: Zero-based index into the events array.
|
||||
public func play(eventIndex: Int) {
|
||||
@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
|
||||
@@ -622,7 +622,7 @@ public final class LyrebirdEventList: @unchecked Sendable {
|
||||
///
|
||||
/// Calls ``LyrebirdProcess/release(reltime:)`` on each running, non-releasing
|
||||
/// process. Does not advance ``index``.
|
||||
public func releaseAll() {
|
||||
@MainActor public func releaseAll() {
|
||||
for proc: LyrebirdProcess in _allProcesses {
|
||||
if proc.isRunning && !proc.isReleasing {
|
||||
proc.release()
|
||||
@@ -650,7 +650,7 @@ public final class LyrebirdEventList: @unchecked Sendable {
|
||||
/// 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.
|
||||
public func killAll() {
|
||||
@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?()
|
||||
@@ -731,18 +731,18 @@ public final class LyrebirdEventList: @unchecked Sendable {
|
||||
|
||||
/// Poll until `killProc` finishes, then tear down the master on the main thread.
|
||||
/// Uses a DispatchQueue delayed dispatch cascade to avoid blocking the caller.
|
||||
private func _scheduleDeferredMasterTeardown(
|
||||
@MainActor private func _scheduleDeferredMasterTeardown(
|
||||
killProc: LyrebirdProcess,
|
||||
engine: SynthesisEngine
|
||||
) {
|
||||
// Poll interval: 10 ms — matches the watcher timer interval in LyrebirdProcess.
|
||||
let killProcPollIntervalMs: Int = 10
|
||||
func poll() {
|
||||
@MainActor func poll() {
|
||||
if killProc.isRunning {
|
||||
// Still running — re-arm.
|
||||
DispatchQueue.main.asyncAfter(
|
||||
deadline: .now() + .milliseconds(killProcPollIntervalMs)
|
||||
) { poll() }
|
||||
) { MainActor.assumeIsolated { poll() } }
|
||||
} else {
|
||||
// Kill process done — tear down master now.
|
||||
self._teardownMaster()
|
||||
@@ -750,7 +750,7 @@ public final class LyrebirdEventList: @unchecked Sendable {
|
||||
}
|
||||
DispatchQueue.main.asyncAfter(
|
||||
deadline: .now() + .milliseconds(killProcPollIntervalMs)
|
||||
) { poll() }
|
||||
) { MainActor.assumeIsolated { poll() } }
|
||||
}
|
||||
|
||||
/// Kill everything, reset ``index`` to `0`, clear recording state, clear the
|
||||
@@ -767,7 +767,7 @@ public final class LyrebirdEventList: @unchecked Sendable {
|
||||
/// 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.
|
||||
public func reset() {
|
||||
@MainActor public func reset() {
|
||||
stopTimelinePlayback()
|
||||
killAll()
|
||||
stopRecord()
|
||||
@@ -1122,7 +1122,7 @@ public final class LyrebirdEventList: @unchecked Sendable {
|
||||
/// `_startSampleTime` so the first event's stem-filename offset
|
||||
/// (which reads `playSampleTime - _startSampleTime`) is exactly
|
||||
/// zero when both reads share the same origin.
|
||||
private func _firstEventSetup(at originSampleTime: SampleTime) throws {
|
||||
@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
|
||||
@@ -1399,7 +1399,7 @@ public final class LyrebirdEventList: @unchecked Sendable {
|
||||
|
||||
/// Free the master synth and both groups. The master `_bus` is caller-owned
|
||||
/// and is NOT released here.
|
||||
private func _teardownMaster() {
|
||||
@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.
|
||||
|
||||
@@ -59,7 +59,11 @@ final class ProcessRouteSynth: SynthesizerBase {
|
||||
|
||||
/// The `EnvelopeGen.Audio` instance used to drive the amplitude envelope.
|
||||
/// Held as a strong reference so the watcher can read `needsFree` off-RT.
|
||||
private(set) var envGen: EnvelopeGen.Audio?
|
||||
///
|
||||
/// `nonisolated(unsafe)`: assigned in `build()` on main; the `LyrebirdProcess` watcher
|
||||
/// reads `envGen?.needsFree` (an atomic flag) from a utility-queue timer. Effectively
|
||||
/// immutable after `build()`; cross-thread read is safe (Phase 201).
|
||||
nonisolated(unsafe) private(set) var envGen: EnvelopeGen.Audio?
|
||||
|
||||
init(
|
||||
envelope: Envelope,
|
||||
@@ -175,7 +179,10 @@ final class ProcessRouteSynth: SynthesizerBase {
|
||||
/// caller is responsible for routing the process's output to the EventList's
|
||||
/// `bus` (or to any other downstream consumer) if master amp control is wanted.
|
||||
/// - target: Where to insert this process's group in the node tree.
|
||||
/// - body: `async` closure invoked with a ``LyrebirdProcessContext``.
|
||||
/// - body: `async` closure invoked with a ``LyrebirdProcessContext``. Runs on the
|
||||
/// `@MainActor` (Phase 201) so it can construct `@MainActor` `SynthesizerBase`
|
||||
/// subclasses and call `ctx.add(_:)` directly — no `await MainActor.run { … }`
|
||||
/// wrapping needed. `await ctx.wait(_:)` suspends without blocking the main thread.
|
||||
/// - onRelease: Optional callback invoked when ``release(reltime:)`` is
|
||||
/// called. Receives the context so callers can remove synths or update
|
||||
/// parameters before the tail.
|
||||
@@ -214,11 +221,11 @@ public final class LyrebirdProcess: @unchecked Sendable {
|
||||
private let _target: LyrebirdProcessTarget
|
||||
|
||||
/// Maximum amplitude (in dB) that the amplitude slider in
|
||||
/// ``LyrebirdProcessView`` should expose. Defaults to `+12` dB.
|
||||
/// `LyrebirdProcessView` should expose. Defaults to `+12` dB.
|
||||
/// Raise per-process when a source needs additional headroom above unity.
|
||||
/// Has no effect on engine behaviour — purely a UI hint.
|
||||
public let maxUIAmpDb: Double
|
||||
private let _body: @Sendable (LyrebirdProcessContext) async -> Void
|
||||
private let _body: @MainActor @Sendable (LyrebirdProcessContext) async -> Void
|
||||
private let _onRelease: ((LyrebirdProcessContext) -> Void)?
|
||||
private let _onFinished: (() -> Void)?
|
||||
|
||||
@@ -294,7 +301,7 @@ public final class LyrebirdProcess: @unchecked Sendable {
|
||||
/// writable after ``play(engine:)``. Defaults to `1.0`.
|
||||
/// - ampLag: Lag time in seconds applied to amplitude changes. Defaults
|
||||
/// to `0.01` s.
|
||||
/// - maxUIAmpDb: Maximum amplitude (in dB) that ``LyrebirdProcessView``
|
||||
/// - maxUIAmpDb: Maximum amplitude (in dB) that `LyrebirdProcessView`
|
||||
/// should expose on its amplitude slider. Defaults to `+12` dB. Raise
|
||||
/// when a source needs additional UI headroom above unity. Purely a UI
|
||||
/// hint — has no effect on engine behaviour.
|
||||
@@ -327,7 +334,7 @@ public final class LyrebirdProcess: @unchecked Sendable {
|
||||
numChannels: Int,
|
||||
procOut: any ValidBus = 0,
|
||||
target: LyrebirdProcessTarget = .head,
|
||||
body: @escaping @Sendable (LyrebirdProcessContext) async -> Void,
|
||||
body: @escaping @MainActor @Sendable (LyrebirdProcessContext) async -> Void,
|
||||
onRelease: ((LyrebirdProcessContext) -> Void)? = nil,
|
||||
onFinished: (() -> Void)? = nil,
|
||||
) {
|
||||
@@ -379,7 +386,7 @@ public final class LyrebirdProcess: @unchecked Sendable {
|
||||
/// (lag-smoothed over `ampLag` seconds).
|
||||
///
|
||||
/// Changes ramp to the new value over `ampLag` seconds.
|
||||
public var amp: Double {
|
||||
@MainActor public var amp: Double {
|
||||
get { _routeSynth?.$amp.value ?? _initialAmp }
|
||||
set {
|
||||
if let routeSynth: ProcessRouteSynth = _routeSynth {
|
||||
@@ -407,7 +414,7 @@ public final class LyrebirdProcess: @unchecked Sendable {
|
||||
/// (explicit ``kill()`` or natural envelope completion) and its
|
||||
/// main-thread teardown, the process rearms to idle and can be played
|
||||
/// again.
|
||||
public func play(engine: SynthesisEngine) {
|
||||
@MainActor public func play(engine: SynthesisEngine) {
|
||||
do {
|
||||
try _play(engine: engine, parentGroup: engine.mainGroup)
|
||||
} catch {
|
||||
@@ -439,7 +446,7 @@ public final class LyrebirdProcess: @unchecked Sendable {
|
||||
/// - parentGroup: The group to add this process's private group into.
|
||||
/// - playSampleTimeOverride: Optional sample-time origin so EventList
|
||||
/// can align stem-filename offsets to a shared timeline anchor.
|
||||
internal func _play(
|
||||
@MainActor internal func _play(
|
||||
engine: SynthesisEngine,
|
||||
parentGroup: Group,
|
||||
playSampleTimeOverride: SampleTime? = nil
|
||||
@@ -557,8 +564,8 @@ public final class LyrebirdProcess: @unchecked Sendable {
|
||||
_context = context
|
||||
|
||||
// Launch body task.
|
||||
let body: @Sendable (LyrebirdProcessContext) async -> Void = _body
|
||||
_bodyTask = Task {
|
||||
let body: @MainActor @Sendable (LyrebirdProcessContext) async -> Void = _body
|
||||
_bodyTask = Task { @MainActor in
|
||||
await body(context)
|
||||
}
|
||||
|
||||
@@ -582,7 +589,7 @@ public final class LyrebirdProcess: @unchecked Sendable {
|
||||
/// Override support requires EnvelopeGen swap-queue integration and is
|
||||
/// not yet wired — passing a non-nil `reltime` emits a warning but is
|
||||
/// otherwise ignored.
|
||||
public func release(reltime: Double? = nil) {
|
||||
@MainActor public func release(reltime: Double? = nil) {
|
||||
guard _stateRaw.compareExchange(
|
||||
expected: LyrebirdProcess.stateRunning,
|
||||
desired: LyrebirdProcess.stateReleasing,
|
||||
@@ -650,8 +657,10 @@ public final class LyrebirdProcess: @unchecked Sendable {
|
||||
// _teardown (dispatched below) cancels and nils _bodyTask on the main thread.
|
||||
if _engine != nil {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self: LyrebirdProcess, let engine: SynthesisEngine = self._engine else { return }
|
||||
self._teardown(engine: engine)
|
||||
MainActor.assumeIsolated {
|
||||
guard let self: LyrebirdProcess, let engine: SynthesisEngine = self._engine else { return }
|
||||
self._teardown(engine: engine)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -693,8 +702,10 @@ public final class LyrebirdProcess: @unchecked Sendable {
|
||||
// Dispatch teardown to the main thread. Access _engine through self to
|
||||
// avoid sending a non-Sendable SynthesisEngine across isolation boundaries.
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self: LyrebirdProcess, let engine: SynthesisEngine = self._engine else { return }
|
||||
self._teardown(engine: engine)
|
||||
MainActor.assumeIsolated {
|
||||
guard let self: LyrebirdProcess, let engine: SynthesisEngine = self._engine else { return }
|
||||
self._teardown(engine: engine)
|
||||
}
|
||||
}
|
||||
}
|
||||
_watcherTimer = timer
|
||||
@@ -705,7 +716,7 @@ public final class LyrebirdProcess: @unchecked Sendable {
|
||||
|
||||
/// Free group, release bus, stop watcher, close DiskOut, fire `onFinished`.
|
||||
/// Must be called on the main thread.
|
||||
private func _teardown(engine: SynthesisEngine) {
|
||||
@MainActor private func _teardown(engine: SynthesisEngine) {
|
||||
// Cancel the body task first — it is safe to access here because _teardown
|
||||
// always runs on the main thread, which is the single writer of _bodyTask.
|
||||
_bodyTask?.cancel()
|
||||
@@ -771,8 +782,15 @@ public final class LyrebirdProcess: @unchecked Sendable {
|
||||
/// from whichever thread drops the final process reference.
|
||||
deinit {
|
||||
guard let engine: SynthesisEngine = _engine else { return }
|
||||
// `Group.free` is `@MainActor` (Phase 201) — it touches `nodeTreeMirror`. deinit is
|
||||
// nonisolated and may run on any thread, so hop the group-free to main. The bus
|
||||
// release + DiskOut close are nonisolated and run inline. Capture locals (not self,
|
||||
// which is mid-deinit) for the async closure.
|
||||
if let group: Group = _group {
|
||||
group.free(engine: engine)
|
||||
let capturedEngine: SynthesisEngine = engine
|
||||
DispatchQueue.main.async {
|
||||
MainActor.assumeIsolated { group.free(engine: capturedEngine) }
|
||||
}
|
||||
}
|
||||
if let bus: AudioBus = _bus {
|
||||
engine.busAllocator.releaseAudioBus(bus)
|
||||
@@ -799,7 +817,7 @@ public final class LyrebirdProcess: @unchecked Sendable {
|
||||
/// - bus: The allocated route bus (DiskOut reads from this bus).
|
||||
/// - playSampleTime: Engine sample time at play start (used to compute offset).
|
||||
/// - playIndex: Zero-based counter for this process instance.
|
||||
private func _spawnDiskOut(
|
||||
@MainActor private func _spawnDiskOut(
|
||||
config: ProcessRecordingConfig,
|
||||
engine: SynthesisEngine,
|
||||
group: Group,
|
||||
|
||||
@@ -19,5 +19,10 @@ public protocol LyrebirdProcessFactory: Sendable {
|
||||
///
|
||||
/// Each call should return an independent process — callers may
|
||||
/// invoke this repeatedly to spawn distinct concurrent processes.
|
||||
func createProcess() -> LyrebirdProcess
|
||||
///
|
||||
/// `@MainActor` (Phase 201): conformers typically construct `@MainActor`
|
||||
/// `SynthesizerBase` subclasses here, so the factory method is main-actor-isolated.
|
||||
/// The protocol stays `Sendable` (factories are stored / passed across actors); only
|
||||
/// the build step is pinned to main.
|
||||
@MainActor func createProcess() -> LyrebirdProcess
|
||||
}
|
||||
|
||||
@@ -12,18 +12,39 @@
|
||||
///
|
||||
/// The default evaluate() implementation is a no-op. Most users subclass SynthesizerBase,
|
||||
/// which wires evaluate() to a set of registered output generators.
|
||||
///
|
||||
/// ## Actor isolation (Phase 201)
|
||||
///
|
||||
/// The language-side surface (`build`, `release`, `free`) is `@MainActor`-isolated so a
|
||||
/// consumer building under Xcode 26's default `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`
|
||||
/// can subclass `SynthesizerBase` and override `build()` with **no** concurrency
|
||||
/// annotations — the consumer's MainActor default now *matches* the base instead of
|
||||
/// conflicting with a nonisolated override. The single RT-thread entry point, `evaluate`,
|
||||
/// is explicitly `nonisolated` so the engine's render callback reaches it with no actor
|
||||
/// hop. See `ARCHITECTURE.md` §9 and `docs/00-working-order.md` Phase 201.
|
||||
///
|
||||
/// Isolation is declared **per-requirement** rather than at the protocol level on purpose:
|
||||
/// the consumer guarantee comes from `SynthesizerBase` being a `@MainActor` class (so its
|
||||
/// subclasses inherit MainActor), while the engine-internal `Group` / `ParallelGroup`
|
||||
/// conformers stay fully nonisolated — a whole-type `@MainActor` protocol would infer
|
||||
/// MainActor onto their RT-owned linked-list / snapshot state and break the render path.
|
||||
public protocol Synthesizer: AnyObject {
|
||||
|
||||
/// Configure the internal generator DAG. Called once by the engine when this Synthesizer
|
||||
/// is added to the node tree. Allocate all generators here — not during evaluate.
|
||||
func build()
|
||||
///
|
||||
/// `@MainActor` — called once on the main thread when the synth is added.
|
||||
@MainActor func build()
|
||||
|
||||
/// Evaluate one block segment. The engine calls this once per segment (normally once per
|
||||
/// block; may be called multiple times if scheduled events split the block).
|
||||
///
|
||||
/// `nonisolated` — the RT render thread's only entry point into a Synthesizer. Must not
|
||||
/// hop actors. See the type-level isolation note.
|
||||
/// - Parameters:
|
||||
/// - graph: The current SynthGraph context (engine + busOffset).
|
||||
/// - count: Number of samples to produce for this segment.
|
||||
func evaluate(graph: SynthGraph, count: Int)
|
||||
nonisolated func evaluate(graph: SynthGraph, count: Int)
|
||||
|
||||
/// Begin a graceful release of this synthesizer (e.g., set gate → 0).
|
||||
///
|
||||
@@ -31,7 +52,7 @@ public protocol Synthesizer: AnyObject {
|
||||
/// parameter update. The default throws `SynthesizerError.noGate`.
|
||||
///
|
||||
/// Language-side only — never call from the RT audio thread.
|
||||
func release(engine: SynthesisEngine) throws
|
||||
@MainActor func release(engine: SynthesisEngine) throws
|
||||
|
||||
/// Immediately remove this synthesizer from the node tree.
|
||||
///
|
||||
@@ -39,20 +60,20 @@ public protocol Synthesizer: AnyObject {
|
||||
/// as soon as the RT thread applies the event (next block boundary or segment split).
|
||||
///
|
||||
/// Language-side only — never call from the RT audio thread.
|
||||
func free(engine: SynthesisEngine)
|
||||
@MainActor func free(engine: SynthesisEngine)
|
||||
}
|
||||
|
||||
extension Synthesizer {
|
||||
/// Default: no-op. SynthesizerBase overrides this to drive registered output generators.
|
||||
public func evaluate(graph: SynthGraph, count: Int) {}
|
||||
nonisolated public func evaluate(graph: SynthGraph, count: Int) {}
|
||||
|
||||
/// Default: throws `.noGate`. Override in synthesizers with EnvelopeGen gate inputs.
|
||||
public func release(engine: SynthesisEngine) throws {
|
||||
@MainActor public func release(engine: SynthesisEngine) throws {
|
||||
throw SynthesizerError.noGate
|
||||
}
|
||||
|
||||
/// Default: posts an immediate remove event via the engine's scheduling queue.
|
||||
public func free(engine: SynthesisEngine) {
|
||||
@MainActor public func free(engine: SynthesisEngine) {
|
||||
engine.remove(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import Synchronization
|
||||
/// **Side-effect generators auto-register.** Generators conforming to ``RootRegistering`` —
|
||||
/// ``Out/Audio``, ``Out/Control``, ``RecordBuffer/Audio``, ``RecordBuffer/Control``,
|
||||
/// ``DiskOut/Audio``, ``SendTrigger/Audio``, ``SendTrigger/Control`` — added themselves
|
||||
/// to ``outputGenerators`` when constructed inside ``build()``. No ``addOutputGenerator(_:)``
|
||||
/// to `outputGenerators` when constructed inside ``build()``. No ``addOutputGenerator(_:)``
|
||||
/// or ``output(bus:source:)`` call needed; the result may be discarded with `let _ = ...`.
|
||||
/// Use ``addOutputGenerator(_:)`` explicitly only when constructing a `RootRegistering`
|
||||
/// generator OUTSIDE ``build()`` (e.g. in a helper called from a `LyrebirdTask`).
|
||||
@@ -74,6 +74,18 @@ import Synchronization
|
||||
/// `outputGenerators` on the main thread concurrently with `evaluate()` iterating it on
|
||||
/// the RT thread. Always `engine.remove(synth)` and allow at least one `processBlock` to
|
||||
/// pass before re-adding the same instance.
|
||||
///
|
||||
/// ## Actor isolation (Phase 201)
|
||||
///
|
||||
/// The class is `@MainActor`-isolated so consumer subclasses building under Xcode 26's
|
||||
/// `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` default override `build()` / `init()` with
|
||||
/// no concurrency annotations — their MainActor default matches the base. The single
|
||||
/// RT-thread entry point, `evaluate(graph:count:)`, is `nonisolated final`; the only two
|
||||
/// stored properties it reads on the RT thread — `parameterTable` and `outputGenerators` —
|
||||
/// are `nonisolated(unsafe)`, safe by the engine's add-event happens-before barrier
|
||||
/// (see `ARCHITECTURE.md` §9 and the per-property comments below). No new runtime
|
||||
/// synchronisation is introduced.
|
||||
@MainActor
|
||||
open class SynthesizerBase: Synthesizer {
|
||||
|
||||
// MARK: - Generator DAG
|
||||
@@ -84,7 +96,12 @@ open class SynthesizerBase: Synthesizer {
|
||||
/// **RT-safety:** only accessed from `evaluate()` (RT thread) and `rebuildGraph()`
|
||||
/// (main thread, before the Synthesizer enters the node tree). Concurrent access is
|
||||
/// prevented by the scheduling barrier in `SynthesisEngine.prepareAddEvent`.
|
||||
private var outputGenerators: [any Generator] = []
|
||||
///
|
||||
/// `nonisolated(unsafe)`: written in `build()`/`rebuildGraph()` on main; read on the RT
|
||||
/// thread in `evaluate()`. Cross-thread access is ordered by the add-event happens-before
|
||||
/// edge through the SPSC `pendingQueue` — the RT thread cannot reach this synth until
|
||||
/// `build()` has fully returned on main. See `ARCHITECTURE.md` §9.
|
||||
nonisolated(unsafe) private var outputGenerators: [any Generator] = []
|
||||
|
||||
// MARK: - Parameter storage (RT-read / build-write)
|
||||
|
||||
@@ -93,7 +110,12 @@ open class SynthesizerBase: Synthesizer {
|
||||
/// Written during `build()` (main thread, before add). Read during `evaluate()`
|
||||
/// (RT thread, after add) and also when building `SynthGraph` for downstream generators.
|
||||
/// See `ParameterTable` for the full thread-safety model.
|
||||
private let parameterTable: ParameterTable = ParameterTable()
|
||||
///
|
||||
/// `nonisolated(unsafe)`: the `let` reference is immutable; `.inputs` is populated on main
|
||||
/// in `_autoRegisterLiveParams()` before the add event is enqueued, and read on the RT
|
||||
/// thread in `evaluate()` after the add barrier. Same happens-before edge as
|
||||
/// `outputGenerators`. See `ARCHITECTURE.md` §9.
|
||||
nonisolated(unsafe) private let parameterTable: ParameterTable = ParameterTable()
|
||||
|
||||
// MARK: - Engine binding
|
||||
|
||||
@@ -139,9 +161,9 @@ open class SynthesizerBase: Synthesizer {
|
||||
/// stale-pointer-then-retry case (one clear + one retry); more
|
||||
/// iterations imply real contention where the structured error is
|
||||
/// more useful than spinning.
|
||||
private static let bindMaxPasses: Int = 2
|
||||
nonisolated private static let bindMaxPasses: Int = 2
|
||||
|
||||
internal func _bind(to engine: SynthesisEngine) throws {
|
||||
nonisolated internal func _bind(to engine: SynthesisEngine) throws {
|
||||
let rawPointer: UnsafeMutableRawPointer = Unmanaged.passUnretained(engine).toOpaque()
|
||||
let target: UInt = UInt(bitPattern: rawPointer)
|
||||
|
||||
@@ -209,7 +231,7 @@ open class SynthesizerBase: Synthesizer {
|
||||
/// RT-side iteration.
|
||||
///
|
||||
/// - Parameter engine: The engine releasing ownership.
|
||||
internal func _unbind(from engine: SynthesisEngine) {
|
||||
nonisolated internal func _unbind(from engine: SynthesisEngine) {
|
||||
let rawPointer: UnsafeMutableRawPointer = Unmanaged.passUnretained(engine).toOpaque()
|
||||
let target: UInt = UInt(bitPattern: rawPointer)
|
||||
_ = _engineBinding.compareExchange(
|
||||
@@ -241,10 +263,13 @@ open class SynthesizerBase: Synthesizer {
|
||||
/// (where the task-local pointer is `nil` and auto-registration is a no-op).
|
||||
///
|
||||
/// **Do not double-register.** Calling this with a `RootRegistering` generator
|
||||
/// that already auto-registered places it in ``outputGenerators`` twice; the
|
||||
/// that already auto-registered places it in `outputGenerators` twice; the
|
||||
/// second evaluation is short-circuited by the segment-serial fan-out cache but
|
||||
/// the duplicate entry is wasteful.
|
||||
public final func addOutputGenerator(_ generator: any Generator) {
|
||||
/// `nonisolated`: invoked from nonisolated `RootRegistering` generator inits during
|
||||
/// `build()` (on main, before the add barrier). Mutates `outputGenerators`
|
||||
/// (`nonisolated(unsafe)`) — same happens-before justification.
|
||||
public nonisolated final func addOutputGenerator(_ generator: any Generator) {
|
||||
outputGenerators.append(generator)
|
||||
}
|
||||
|
||||
@@ -256,7 +281,11 @@ open class SynthesizerBase: Synthesizer {
|
||||
/// `true`. Set automatically when a `DoneActionWatchable` generator with
|
||||
/// `doneAction: .freeNode` is constructed inside ``build()``, or explicitly via
|
||||
/// ``autoFreeOnDone(_:)``.
|
||||
internal var _autoFreeProbe: (any DoneActionWatchable)?
|
||||
///
|
||||
/// `nonisolated(unsafe)`: set inside `build()` on main (before the add barrier) and read
|
||||
/// later by the engine's auto-free watcher on a utility-queue timer. Effectively immutable
|
||||
/// after `build()` returns — same cross-thread justification as `outputGenerators`.
|
||||
nonisolated(unsafe) internal var _autoFreeProbe: (any DoneActionWatchable)?
|
||||
|
||||
/// `@unchecked Sendable` wrapper around an unowned `SynthesizerBase` pointer.
|
||||
/// Avoids forcing `SynthesizerBase` itself (and every user subclass) to conform
|
||||
@@ -272,11 +301,17 @@ open class SynthesizerBase: Synthesizer {
|
||||
/// `doneAction == .freeNode`. `nil` outside any `build()` context, in which case
|
||||
/// auto-registration is a no-op and the explicit ``autoFreeOnDone(_:)`` escape
|
||||
/// hatch remains available.
|
||||
@TaskLocal internal static var _currentlyBuildingRef: _BuildingRef?
|
||||
|
||||
/// Convenience unwrapping of ``_currentlyBuildingRef``.
|
||||
internal static var _currentlyBuilding: SynthesizerBase? {
|
||||
_currentlyBuildingRef?.synth
|
||||
/// Convenience unwrapping of the build-context task-local.
|
||||
///
|
||||
/// The backing `@TaskLocal` lives in the file-scope ``_SynthesizerBuildContext`` enum,
|
||||
/// not here: `@TaskLocal` on a `@MainActor` class generates a main-actor-isolated
|
||||
/// `$`-projected accessor even under `nonisolated`, which the nonisolated
|
||||
/// generator-init read path cannot reach — so the storage is hoisted out of this
|
||||
/// `@MainActor` class into a plain nonisolated namespace.
|
||||
///
|
||||
/// `nonisolated`: read from nonisolated generator inits during `build()`.
|
||||
nonisolated internal static var _currentlyBuilding: SynthesizerBase? {
|
||||
_SynthesizerBuildContext.currentRef?.synth
|
||||
}
|
||||
|
||||
/// Opt this synthesizer into automatic removal when the given probe
|
||||
@@ -310,7 +345,8 @@ open class SynthesizerBase: Synthesizer {
|
||||
/// Calling this twice replaces the previous probe. Pass a generator that the
|
||||
/// synth's own DAG already retains (the engine does not strengthen the
|
||||
/// reference) — losing the probe to ARC turns the auto-free into a no-op.
|
||||
public final func autoFreeOnDone(_ probe: any DoneActionWatchable) {
|
||||
/// `nonisolated`: callable from `DoneActionWatchable` generator inits during `build()`.
|
||||
public nonisolated final func autoFreeOnDone(_ probe: any DoneActionWatchable) {
|
||||
_autoFreeProbe = probe
|
||||
}
|
||||
|
||||
@@ -351,7 +387,10 @@ open class SynthesizerBase: Synthesizer {
|
||||
/// (sub-)block — no synchronization is required here.
|
||||
///
|
||||
/// Called by the engine — do not call directly.
|
||||
public final func evaluate(graph: SynthGraph, count: Int) {
|
||||
///
|
||||
/// `nonisolated`: the RT render thread's entry point. Reads only `parameterTable` and
|
||||
/// `outputGenerators` (both `nonisolated(unsafe)`), safe by the add-event barrier.
|
||||
public nonisolated final func evaluate(graph: SynthGraph, count: Int) {
|
||||
let localGraph: SynthGraph = SynthGraph(
|
||||
engine: graph.engine,
|
||||
busOffset: graph.busOffset,
|
||||
@@ -539,7 +578,7 @@ open class SynthesizerBase: Synthesizer {
|
||||
/// `outputGenerators`. Always `engine.remove(synth)` before re-adding.
|
||||
internal func rebuildGraph() {
|
||||
outputGenerators.removeAll()
|
||||
SynthesizerBase.$_currentlyBuildingRef.withValue(_BuildingRef(synth: self)) {
|
||||
_SynthesizerBuildContext.$currentRef.withValue(_BuildingRef(synth: self)) {
|
||||
build()
|
||||
}
|
||||
_autoRegisterLiveParams()
|
||||
@@ -578,3 +617,17 @@ open class SynthesizerBase: Synthesizer {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Build-context task-local (nonisolated namespace)
|
||||
|
||||
/// File-scope holder for the `build()`-context task-local.
|
||||
///
|
||||
/// The task-local cannot live as a static on `SynthesizerBase` because that class is
|
||||
/// `@MainActor` (Phase 201): `@TaskLocal` would synthesise a main-actor-isolated
|
||||
/// `$`-projected accessor, which the **nonisolated** generator-init read path
|
||||
/// (`RootRegistering` / `DoneActionWatchable` self-registration) cannot reach. Hoisting it
|
||||
/// into this plain `enum` keeps both the `withValue` writer (on main, inside `rebuildGraph`)
|
||||
/// and the cross-init readers nonisolated.
|
||||
internal enum _SynthesizerBuildContext {
|
||||
@TaskLocal static var currentRef: SynthesizerBase._BuildingRef?
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ public final class VoicePool<S: SynthesizerBase> {
|
||||
/// throw, every voice successfully added so far is rolled back via
|
||||
/// `engine.remove` in reverse order before the error propagates, so the
|
||||
/// engine's node tree is left exactly as it was before this init began.
|
||||
public init(
|
||||
@MainActor public init(
|
||||
voiceCount: Int,
|
||||
group: Group,
|
||||
engine: SynthesisEngine,
|
||||
|
||||
@@ -293,7 +293,7 @@ final class SineToneAudioEnvSynth: SynthesizerBase {
|
||||
}
|
||||
}
|
||||
|
||||
func populateControlEnv(_ engine: SynthesisEngine) {
|
||||
@MainActor func populateControlEnv(_ engine: SynthesisEngine) {
|
||||
for i: Int in 0..<16 {
|
||||
do {
|
||||
try engine.add(SineToneControlEnvSynth(freq: 220.0 * pow(2.0, Double(i) / 12.0), bus: 0))
|
||||
@@ -303,7 +303,7 @@ func populateControlEnv(_ engine: SynthesisEngine) {
|
||||
}
|
||||
}
|
||||
|
||||
func populateAudioEnv(_ engine: SynthesisEngine) {
|
||||
@MainActor func populateAudioEnv(_ engine: SynthesisEngine) {
|
||||
for i: Int in 0..<16 {
|
||||
do {
|
||||
try engine.add(SineToneAudioEnvSynth(freq: 220.0 * pow(2.0, Double(i) / 12.0), bus: 0))
|
||||
@@ -405,7 +405,7 @@ final class PitchShiftSynth: SynthesizerBase {
|
||||
}
|
||||
}
|
||||
|
||||
func populatePoolN(_ engine: SynthesisEngine, count: Int, overlap: Int) {
|
||||
@MainActor func populatePoolN(_ engine: SynthesisEngine, count: Int, overlap: Int) {
|
||||
for i: Int in 0..<count {
|
||||
do {
|
||||
try engine.add(TuneablePitchShiftSynth(
|
||||
@@ -419,7 +419,7 @@ func populatePoolN(_ engine: SynthesisEngine, count: Int, overlap: Int) {
|
||||
}
|
||||
}
|
||||
|
||||
func populate4HeadN(_ engine: SynthesisEngine, count: Int) {
|
||||
@MainActor func populate4HeadN(_ engine: SynthesisEngine, count: Int) {
|
||||
for i: Int in 0..<count {
|
||||
do {
|
||||
try engine.add(PitchShiftSynth(
|
||||
|
||||
@@ -8,7 +8,7 @@ import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A panel that renders one ``LyrebirdProcessView`` per currently-running
|
||||
/// ``LyrebirdProcess`` owned by a ``LyrebirdEventList``.
|
||||
/// `LyrebirdProcess` owned by a `LyrebirdEventList`.
|
||||
///
|
||||
/// Processes appear when they start (transition to running/releasing) and
|
||||
/// disappear when they finish (auto-free or are killed). Identity is tracked
|
||||
@@ -43,7 +43,7 @@ import LyrebirdSynth
|
||||
/// ## Threading
|
||||
///
|
||||
/// The view body and refresh loop run on the main thread.
|
||||
/// ``LyrebirdEventList/allProcesses`` and ``LyrebirdProcess/isRunning`` are
|
||||
/// `LyrebirdEventList.allProcesses` and `LyrebirdProcess.isRunning` are
|
||||
/// documented as safe to read from any thread — the main-thread read here is
|
||||
/// trivially valid.
|
||||
public struct LyrebirdRunningProcessesView: View {
|
||||
@@ -61,11 +61,11 @@ public struct LyrebirdRunningProcessesView: View {
|
||||
/// Creates a running-processes panel bound to the given event list.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - eventList: The ``LyrebirdEventList`` whose running processes will be
|
||||
/// - eventList: The `LyrebirdEventList` whose running processes will be
|
||||
/// rendered. Only processes registered with this list are visible —
|
||||
/// standalone processes (those not owned by an event list) do not
|
||||
/// appear here.
|
||||
/// - engine: The ``SynthesisEngine`` forwarded to each child
|
||||
/// - engine: The `SynthesisEngine` forwarded to each child
|
||||
/// ``LyrebirdProcessView`` for its **Start** button.
|
||||
public init(
|
||||
eventList: LyrebirdEventList,
|
||||
@@ -164,8 +164,8 @@ extension LyrebirdRunningProcessesView {
|
||||
/// with `.close()`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - eventList: The ``LyrebirdEventList`` to track.
|
||||
/// - engine: The ``SynthesisEngine`` forwarded to each child
|
||||
/// - eventList: The `LyrebirdEventList` to track.
|
||||
/// - engine: The `SynthesisEngine` forwarded to each child
|
||||
/// ``LyrebirdProcessView``.
|
||||
/// - title: Window title bar text. Defaults to `"<eventList.id> — Running"`.
|
||||
/// - width: Initial window width in points. Defaults to `360`.
|
||||
|
||||
@@ -71,6 +71,6 @@ that need GUI windows.
|
||||
|
||||
### Live Coding
|
||||
|
||||
The live-coding scratchpad (``LyrebirdScratchView`` / ``LyrebirdScratchModel``) lives
|
||||
The live-coding scratchpad (`LyrebirdScratchView` / `LyrebirdScratchModel`) lives
|
||||
in the separate `LyrebirdLiveCompileUI` module (sub-package `LiveCompile/`). See the
|
||||
`LyrebirdLiveCompileUI` docc archive for the `LiveCoding` article.
|
||||
|
||||
Reference in New Issue
Block a user