fixes for Swift 6 and threading concerns

This commit is contained in:
2026-06-02 12:09:44 -07:00
parent 2fa4bfd45e
commit c3cc50ddb3
327 changed files with 1596 additions and 199 deletions
+14
View File
@@ -256,6 +256,20 @@ And `engine.remove(synth)`:
`remove` returns `Bool` (it unbinds synchronously on successful enqueue), but there is a documented one-`processBlock` window between `remove` and a re-`add` of the same instance — the RT thread needs a block to actually unlink it. If `freeQueue` overflows, the framework logs one warning and leaks that single reference rather than risk the RT thread; a leaked voice is preferable to an audio dropout or crash.
### 9.1 Actor isolation of the lifecycle (Phase 201)
The Swift-concurrency isolation of `Synthesizer` is split along exactly the thread boundary above:
- **Language side is `@MainActor`.** `SynthesizerBase` is a `@MainActor` class, and the `Synthesizer` protocol declares `build()`, `release(engine:)`, `free(engine:)` as `@MainActor` requirements. Steps 1–4 of the add path (allocate → build → enqueue) and the `engine.add` / `schedule` / `add(position:)` entry points are therefore main-actor-isolated. This is what lets a consumer building under Xcode 26's `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` default 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. (`engine.remove` stays nonisolated — it unbinds via atomics and enqueues a pointer-only event; `_bind` / `_unbind` are nonisolated for the same reason.)
- **The RT entry point is `nonisolated`.** `evaluate(graph:count:)` is `nonisolated final` so the render callback (steps 5–6) reaches it with **no actor hop**. It reads exactly two stored properties cross-thread — `parameterTable` (immutable `let`) and `outputGenerators` (written in `build()` on main, read on RT) — both marked `nonisolated(unsafe)`. Their safety rests entirely on the happens-before edge established by the SPSC `pendingQueue` (§2.1): the RT thread cannot observe the node until it dequeues the `.add` event, which the producer enqueued *after* `build()` fully returned on main. No new runtime synchronisation is introduced by the isolation annotations.
- **`Group` / `ParallelGroup` stay nonisolated.** They satisfy the `@MainActor` `build`/`release`/`free` requirements with less-isolated (nonisolated) witnesses, keeping their RT-owned linked-list / snapshot state reachable from the render thread. `Group.release` installs its self-free poll timer through a `nonisolated` helper so the utility-queue handler does not inherit `@MainActor` (which would trap when it fires off-main).
- **Internal controllers that drive the node tree are `@MainActor`** where they touch the language side: `LyrebirdProcess` (`play`/`_play`/`release`/`amp`/teardown), `LyrebirdEventList` (`play(eventIndex:)`/`next`/`releaseAll`/`killAll`/`reset`/master teardown), `VoicePool.init`, `ParallelGroup.add`. Cross-thread reads that pre-existed the change (e.g. the auto-free watcher reading `EnvelopeGen.needsFree`, `EventList.fireTimes` from process body tasks) are preserved via `nonisolated(unsafe)` on the specific fields they touch.
The guarantee is locked by the committed `RegressionFixtures/MainActorConsumer` package, which compiles an unannotated `SynthesizerBase` subclass under `.swiftLanguageMode(.v6)` + `-default-isolation MainActor`.
---
## Where to go deeper
+3 -4
View File
@@ -47,8 +47,8 @@ let package = Package(
"LyrebirdLiveCompile",
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
],
path: "Sources/LyrebirdLiveCompileUI",
swiftSettings: [.swiftLanguageMode(.v5)]
path: "Sources/LyrebirdLiveCompileUI"
// Swift 6 language mode (Phase 203): inherits the swift-tools 6.0 default.
),
.testTarget(
name: "LyrebirdLiveCompileTests",
@@ -65,8 +65,7 @@ let package = Package(
"LyrebirdLiveCompileUI",
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
],
path: "Tests/LyrebirdLiveCompileUITests",
swiftSettings: [.swiftLanguageMode(.v5)]
path: "Tests/LyrebirdLiveCompileUITests"
),
]
)
@@ -22,7 +22,20 @@ import LyrebirdSynth
/// compile snippets, and the tracking lists needed for re-evaluation cleanup.
/// Snippets receive a `SnippetContext` bound to this session through
/// `compileAndRun(_:additive:)`.
public final class LiveSession {
///
/// `@unchecked Sendable` (Phase 203): a `LiveSession` is shared between its `@MainActor`
/// owner (`LyrebirdScratchModel`) and the `nonisolated` `compileAndRunAsync` it calls, so
/// Swift 6 requires it to be `Sendable`. The conformance is sound by construction:
///
/// - `engine` and all `-I` / `-L` / `-l` / `rpath` configuration are immutable `let`.
/// - The only mutable graph state — `trackedSynths` and `loadedSnippets` — is accessed
/// exclusively under `trackingLock` (`track`, `clearTracked`, `trackedSynthCount`,
/// `runEntry`).
/// - `reportedSampleRate` / `lastSnippetMessage` are test-only side channels (`@testable`),
/// written by the single in-flight snippet entry under the documented
/// one-invocation-at-a-time precondition (see `compileAndRunAsync`) and read by tests
/// after it completes — no concurrent access in practice.
public final class LiveSession: @unchecked Sendable {
public let engine: SynthesisEngine
@@ -78,7 +91,12 @@ public final class LiveSession {
/// (⌘⇧↩ semantics in the future `LyrebirdScratchView` editor).
/// - Returns: The compiled snippet handle. Retained internally so the dylib
/// stays mapped; callers can ignore it.
/// `@MainActor` (Phase 203): runs the snippet entry — and thus the user body's
/// `MainActor.assumeIsolated { … }` and any `context.play(_:)` → `engine.add` — on the
/// main thread, synchronously (swiftc compile included). The async variant
/// ``compileAndRunAsync(_:additive:)`` keeps the compile off-main.
@discardableResult
@MainActor
public func compileAndRun(_ userBody: String, additive: Bool = false) throws -> CompiledSnippet {
if !additive {
clearTracked()
@@ -89,11 +107,16 @@ public final class LiveSession {
return snippet
}
/// Asynchronous variant of ``compileAndRun(_:additive:)``. The swiftc
/// compile runs on a background `Task.detached`; the snippet entry then
/// executes on the caller's actor (typically the main actor, so snippets
/// can touch UI-side state). Lets `LyrebirdScratchView`'s editor stay
/// responsive during the compile.
/// Asynchronous variant of ``compileAndRun(_:additive:)``. The swiftc compile runs on a
/// background `Task.detached` so `LyrebirdScratchView`'s editor stays responsive; the
/// engine-touching steps (`clearTracked()` and the snippet entry via `runEntry`) then run
/// on the **main actor**.
///
/// Running the entry on the main actor matters (Phase 203): the snippet's
/// `context.play(_:)` calls `engine.add(_:)`, which is `@MainActor` (Phase 201) and
/// mutates `engine.nodeTreeMirror` — state observed by SwiftUI on the main thread. A
/// `nonisolated async` method resumes on the generic executor, NOT the caller's actor, so
/// the hop is explicit here rather than assumed.
///
/// - Precondition: only one in-flight invocation at a time per `LiveSession`.
/// Concurrent calls can interleave `clearTracked()` with the prior call's
@@ -108,14 +131,16 @@ public final class LiveSession {
@discardableResult
public func compileAndRunAsync(_ userBody: String, additive: Bool = false) async throws -> CompiledSnippet {
if !additive {
clearTracked()
// `clearTracked()` calls `engine.remove` (touches `nodeTreeMirror`) — main only.
await MainActor.run { clearTracked() }
}
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: userBody)
let args: [String] = makeSwiftcArgs()
let snippet: CompiledSnippet = try await Task.detached(priority: .userInitiated) {
try LiveSession.compileBlocking(wrapped: wrapped, extraArgs: args)
}.value
runEntry(of: snippet)
// Snippet entry runs the user's `context.play(_:)` → `engine.add` (@MainActor).
await MainActor.run { runEntry(of: snippet) }
return snippet
}
@@ -37,7 +37,7 @@ public final class SnippetContext {
/// - Returns: `true` if the engine accepted the enqueue; `false` if
/// `engine.add` threw (e.g. cross-engine binding, double-add, queue full).
@discardableResult
public func play(_ synth: any Synthesizer) -> Bool {
@MainActor public func play(_ synth: any Synthesizer) -> Bool {
do {
try session.engine.add(synth)
session.track(synth)
@@ -17,6 +17,14 @@
public enum SnippetHarness {
/// Wraps `userBody` in the standard preamble.
///
/// The user body runs inside `MainActor.assumeIsolated { … }` (Phase 203): snippets call
/// `@MainActor` API — `context.play(_:)` and `SynthesizerBase` subclass construction
/// (both `@MainActor` since Phase 201) — which would not compile from the nonisolated
/// `@_cdecl` entry under Swift 6. The `assumeIsolated` closure gives the body main-actor
/// isolation at compile time; it is safe at runtime because `LiveSession` always invokes
/// the entry on the main actor (`compileAndRunAsync` hops via `MainActor.run`;
/// `compileAndRun` is `@MainActor`).
public static func wrap(userBody: String) -> WrappedSnippet {
let preamble: String = """
import LyrebirdSynth
@@ -27,14 +35,18 @@ public enum SnippetHarness {
guard let ctx else { return }
let context = Unmanaged<SnippetContext>.fromOpaque(ctx).takeUnretainedValue()
_ = context
MainActor.assumeIsolated {
"""
// Count newlines in the preamble: the user's body starts on the next line.
// `components(separatedBy: "\n")` over a string ending in "\n" yields N+1
// elements (the last is empty); offset = count of those elements = lines
// before the user body + 1 (the line on which the body starts).
// before the user body + 1 (the line on which the body starts). The
// `MainActor.assumeIsolated {` line is part of the preamble, so the offset
// already accounts for it and diagnostic line-mapping stays correct.
let lineOffset: Int = preamble.components(separatedBy: "\n").count
let suffix: String = "\n}\n"
// Close the `assumeIsolated` closure, then the entry function.
let suffix: String = "\n }\n}\n"
let source: String = preamble + userBody + suffix
return WrappedSnippet(source: source, userBodyLineOffset: lineOffset)
}
@@ -11,6 +11,7 @@ import LyrebirdSynth
#if os(macOS)
@MainActor
@Suite("LiveSession diagnostics")
struct LiveSessionDiagnosticsTests {
@@ -11,6 +11,7 @@ import LyrebirdSynth
#if os(macOS)
@MainActor
@Suite("LiveSession")
struct LiveSessionTests {
@@ -73,6 +74,27 @@ struct LiveSessionTests {
#expect(session.lastSnippetMessage == "async hello")
}
/// Phase 203 runtime guard: a snippet driven through `compileAndRunAsync` that calls
/// `context.play(_:)` actually adds and tracks a synth. `context.play` → `engine.add` is
/// `@MainActor` (Phase 201); `compileAndRunAsync` resumes the snippet entry on the main
/// actor (not the nonisolated executor it suspends on), so this exercises that hop.
@Test
func asyncCompileAndRunPlaysAndTracksSynth() async throws {
let engine: SynthesisEngine = makeEngine()
let session: LiveSession = LiveSession(engine: engine)
#expect(session.trackedSynthCount == 0)
let body: String = """
final class SineSynth: SynthesizerBase {
override func build() {
output(bus: 0, source: OscSin.Audio(freq: 440, mul: 0.1))
}
}
_ = context.play(SineSynth())
"""
_ = try await session.compileAndRunAsync(body)
#expect(session.trackedSynthCount == 1)
}
@Test
func asyncCompileFailureSurfacesDiagnosticsThroughSnippetCompileFailed() async {
let engine: SynthesisEngine = makeEngine()
+6 -13
View File
@@ -83,22 +83,17 @@ let package = Package(
// .copy preserves the directory structure exactly (Xcode discovers
// templates by .xctemplate bundle name + TemplateInfo.plist).
.copy("Resources/XcodeTemplates"),
],
// Swift 5 language mode: the LineNoise package pre-dates Swift 6 concurrency
// annotations. The CLI is a single-threaded synchronous command dispatcher —
// strict concurrency checking adds noise without safety benefit here.
swiftSettings: [.swiftLanguageMode(.v5)]
]
// Swift 6 language mode (Phase 202): inherits the swift-tools 6.0 default.
),
.target(
name: "LyrebirdUI",
dependencies: [
"LyrebirdSynth",
],
path: "Sources/LyrebirdUI",
path: "Sources/LyrebirdUI"
// SwiftUI + AppKit + Observation are system frameworks — no linkerSettings needed.
// .v5 mode: avoids Swift 6 actor-isolation diagnostics in SwiftUI/AppKit interop
// until the concurrency model for UI is fully audited (same rationale as LyrebirdCLI).
swiftSettings: [.swiftLanguageMode(.v5)]
// Swift 6 language mode (Phase 202): inherits the swift-tools 6.0 default.
),
// Phase 167 — `LyrebirdLiveCompile` (and its SwiftUI host
// `LyrebirdLiveCompileUI`) moved to the `LiveCompile/` nested SwiftPM
@@ -130,14 +125,12 @@ let package = Package(
"LyrebirdUI",
"LyrebirdSynth",
],
path: "Tests/LyrebirdUITests",
swiftSettings: [.swiftLanguageMode(.v5)]
path: "Tests/LyrebirdUITests"
),
.testTarget(
name: "LyrebirdCLITests",
dependencies: ["LyrebirdCLI"],
path: "Tests/LyrebirdCLITests",
swiftSettings: [.swiftLanguageMode(.v5)]
path: "Tests/LyrebirdCLITests"
),
]
)
-1
View File
@@ -182,7 +182,6 @@ Use `Lyrebird-Package` for day-to-day development of the engine and tests.
|---|---|
| Schemes don't appear | Close Xcode, run `swift package resolve`, reopen |
| `Synchronization.Atomic` not indexed | Requires Xcode 16+ — false errors in older versions, still builds |
| LineNoise concurrency warnings | Expected — `LyrebirdCLI` uses `.swiftLanguageMode(.v5)` intentionally |
| Nimble in Package dependencies | Cosmetic — LineNoise transitive dep, never built in Lyrebird targets |
| Build fails with Swift driver errors | Xcode 26 bug affecting the **demo workspace** (which dynamic-links for live-coding) — it already sets `SWIFT_USE_INTEGRATED_DRIVER = NO` + `parallelizeBuildables = NO`. Your own project links Lyrebird statically and is unaffected. |
| `dyld: Library not loaded` | Only the bundled demos/AUv3 use the dynamic `LyrebirdDynamic` product; their entitlements already set `disable-library-validation`. External consumers link the static `Lyrebird` product and never hit this. |
@@ -0,0 +1,24 @@
{
"originHash" : "761afb81afb2ac947c6453b20b16362a6beb5e16c81166e6f2953e07cff14b07",
"pins" : [
{
"identity" : "linenoise-swift",
"kind" : "remoteSourceControl",
"location" : "https://github.com/andybest/linenoise-swift",
"state" : {
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
"version" : "0.0.3"
}
},
{
"identity" : "nimble",
"kind" : "remoteSourceControl",
"location" : "https://github.com/Quick/Nimble.git",
"state" : {
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
"version" : "7.3.4"
}
}
],
"version" : 3
}
@@ -0,0 +1,41 @@
// swift-tools-version: 6.0
//
// Phase 201 regression fixture — committed smoke test.
//
// Proves that a consumer building under Xcode 26's default
// `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` (reproduced here with
// `.swiftLanguageMode(.v6)` + the raw `-default-isolation MainActor` unsafe flag —
// `.defaultIsolation(MainActor.self)` is unavailable in this SwiftPM toolchain) can
// subclass `SynthesizerBase` and override `build()` with ZERO concurrency annotations.
//
// If `SynthesizerBase`'s `@MainActor` isolation ever regresses, this package fails to
// compile with:
// "main actor-isolated instance method 'build()' has different actor isolation
// from nonisolated overridden declaration"
//
// Build to verify: (cd RegressionFixtures/MainActorConsumer && swift build)
//
// This is a standalone SwiftPM package (not part of the root `swift test`), mirroring
// the `LiveCompile/` sub-package layout. It references the core package by relative path.
import PackageDescription
let package = Package(
name: "MainActorConsumer",
platforms: [.macOS(.v15)],
dependencies: [
.package(name: "Lyrebird", path: "../..")
],
targets: [
.executableTarget(
name: "MainActorConsumer",
dependencies: [
.product(name: "Lyrebird", package: "Lyrebird")
],
swiftSettings: [
.swiftLanguageMode(.v6),
.unsafeFlags(["-default-isolation", "MainActor"])
]
)
]
)
@@ -0,0 +1,21 @@
// main.swift
// MainActorConsumer (Phase 201 regression fixture)
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
// PHASE 201 GUARANTEE: a consumer under the MainActor-default build mode subclasses
// `SynthesizerBase` and overrides `build()` with NO `nonisolated`, NO `@preconcurrency`,
// NO `@MainActor`, NO `nonisolated override init`. If this stops compiling, the
// language-side actor-isolation guarantee has regressed.
final class ToneSynth: SynthesizerBase {
@LiveParam var freq: Double = 440
override func build() {
output(bus: 0, source: OscSin.Audio(freq: $freq) * 0.2)
}
}
let synth = ToneSynth()
print("Phase 201 regression fixture OK: \(synth)")
+21 -3
View File
@@ -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
View File
@@ -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
+11 -13
View File
@@ -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`.
+4 -4
View File
@@ -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) } }
+32 -7
View File
@@ -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.
+37 -19
View File
@@ -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
}
+28 -7
View File
@@ -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?
}
+1 -1
View File
@@ -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,
+4 -4
View File
@@ -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.
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("AUInput.Audio") struct AUInputAudioTests {
@Test func channelMustBeNonNegative() {
@@ -88,9 +88,11 @@ private struct ABLFixture {
}
}
@MainActor
@Suite("AUv3Driver") struct AUv3DriverTests {
@Test func returnsUninitializedBeforeSetup() {
defer { lyrebirdClearRTMarkAfterTestRender() }
let driver: AUv3Driver = AUv3Driver()
let fixture: ABLFixture = ABLFixture(channels: 2, frames: 64)
defer { fixture.deallocate() }
@@ -99,6 +101,7 @@ private struct ABLFixture {
}
@Test func rejectsFrameCountAboveMax() throws {
defer { lyrebirdClearRTMarkAfterTestRender() }
let driver: AUv3Driver = AUv3Driver(maxFramesToRender: 256)
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 128, sampleRate: 44100,
@@ -114,6 +117,7 @@ private struct ABLFixture {
}
@Test func smallHostFrameCountDrivesMultipleEngineBlocks() throws {
defer { lyrebirdClearRTMarkAfterTestRender() }
// Engine block 128; host requests 64 per call — two calls per engine block.
let driver: AUv3Driver = AUv3Driver(maxFramesToRender: 64)
let engine: SynthesisEngine = SynthesisEngine(
@@ -156,6 +160,7 @@ private struct ABLFixture {
}
@Test func largeHostFrameCountPullsMultipleEngineBlocks() throws {
defer { lyrebirdClearRTMarkAfterTestRender() }
// Host wants 1024 per call but engine block is 256 — 4 engine blocks per
// render call.
let driver: AUv3Driver = AUv3Driver(maxFramesToRender: 1024)
@@ -182,6 +187,7 @@ private struct ABLFixture {
}
@Test func alternatingFrameCountsPreserveContinuity() throws {
defer { lyrebirdClearRTMarkAfterTestRender() }
// Hosts may switch frame counts mid-stream; the ring must keep sample
// continuity intact.
let driver: AUv3Driver = AUv3Driver(maxFramesToRender: 1024)
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("AUv3RingBuffer") struct AUv3RingBufferTests {
@Test func capacityRoundsUpToPowerOfTwo() {
@@ -32,6 +32,7 @@ private final class InheritedParamSynth: ParamSynth {
// MARK: - Tests
@MainActor
@Suite("LyrebirdAUParameterMapping discovery") struct LyrebirdAUParameterDiscoveryTests {
@Test func discoversAllLiveParamsInDeclarationOrder() {
@@ -70,6 +71,7 @@ private final class InheritedParamSynth: ParamSynth {
}
}
@MainActor
@Suite("LyrebirdAUParameterMapping tree") struct LyrebirdAUParameterTreeTests {
@Test func buildsOneAUParameterPerSlot() {
@@ -43,6 +43,7 @@ private final class FixturePresetGen: GeneratorBase, AudioGenerator, LyrebirdAUP
func floatValue(graph: SynthGraph) -> Double { _amp }
}
@MainActor
@Suite("LyrebirdAUPresetSourceRegistry") struct LyrebirdAUPresetRegistryTests {
@Test func registerAndMakeRoundTrip() {
@@ -15,6 +15,7 @@ private final class TestVoice: SynthesizerBase {
override func build() { output(bus: 0, source: $freq * $amp * $gate) }
}
@MainActor
@Suite("LyrebirdAUVoicePoolBinding") struct LyrebirdAUVoicePoolBindingTests {
@Test func noteOnAllocatesVoiceAndConfigures() throws {
@@ -21,7 +21,7 @@ private final class PassthroughSynth: SynthesizerBase {
private final class PassthroughEffectAU: LyrebirdAudioUnit {
public override class func makeSynthesizer() -> SynthesizerBase {
PassthroughSynth()
MainActor.assumeIsolated { PassthroughSynth() }
}
public override class var lyrebirdInputChannels: Int { 2 }
public override class var lyrebirdOutputChannels: Int { 2 }
@@ -37,6 +37,7 @@ private func makeEffectDescription() -> AudioComponentDescription {
)
}
@MainActor
@Suite("LyrebirdAudioUnit effect") struct LyrebirdAudioUnitEffectTests {
@Test func effectAUDeclaresInputAndOutputBuses() throws {
@@ -62,7 +63,7 @@ private func makeEffectDescription() -> AudioComponentDescription {
override func build() { output(bus: 0, source: 0.0) }
}
final class StubInstrumentAU: LyrebirdAudioUnit {
public override class func makeSynthesizer() -> SynthesizerBase { StubSynth() }
public override class func makeSynthesizer() -> SynthesizerBase { MainActor.assumeIsolated { StubSynth() } }
}
let desc: AudioComponentDescription = AudioComponentDescription(
componentType: kAudioUnitType_MusicDevice,
@@ -10,6 +10,7 @@ import AudioToolbox
import AVFoundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("LyrebirdAudioUnit MIDI dispatch") struct LyrebirdAudioUnitMIDITests {
@Test func dispatchHandlesNilHeadGracefully() {
@@ -26,7 +26,7 @@ private final class StemRenderSynth: SynthesizerBase {
}
private final class StemRenderAU: LyrebirdAudioUnit {
public override class func makeSynthesizer() -> SynthesizerBase { StemRenderSynth() }
public override class func makeSynthesizer() -> SynthesizerBase { MainActor.assumeIsolated { StemRenderSynth() } }
public override class var lyrebirdOutputBusses: [LyrebirdAUBusSpec] {
[
.init(name: "Main", channelCount: 2),
@@ -48,7 +48,7 @@ private final class SidechainPassthrough: SynthesizerBase {
}
private final class SidechainAU: LyrebirdAudioUnit {
public override class func makeSynthesizer() -> SynthesizerBase { SidechainPassthrough() }
public override class func makeSynthesizer() -> SynthesizerBase { MainActor.assumeIsolated { SidechainPassthrough() } }
public override class var lyrebirdOutputBusses: [LyrebirdAUBusSpec] {
[.init(name: "Output", channelCount: 2)]
}
@@ -67,7 +67,7 @@ private final class SingleBusSynth: SynthesizerBase {
}
private final class SingleBusAU: LyrebirdAudioUnit {
public override class func makeSynthesizer() -> SynthesizerBase { SingleBusSynth() }
public override class func makeSynthesizer() -> SynthesizerBase { MainActor.assumeIsolated { SingleBusSynth() } }
// No bus-spec overrides — must keep the default single-bus behaviour.
}
@@ -81,6 +81,7 @@ private func makeAUDesc(subtype: UInt32) -> AudioComponentDescription {
)
}
@MainActor
@Suite("LyrebirdAudioUnit multi-bus — defaults") struct LyrebirdAudioUnitMultiBusDefaultTests {
@Test func singleBusAUKeeps104aShape() throws {
@@ -97,6 +98,7 @@ private func makeAUDesc(subtype: UInt32) -> AudioComponentDescription {
}
}
@MainActor
@Suite("LyrebirdAudioUnit multi-bus — multi-output") struct LyrebirdAudioUnitMultiOutputBusTests {
@Test func twoOutputBussesAreExposed() throws {
@@ -120,6 +122,7 @@ private func makeAUDesc(subtype: UInt32) -> AudioComponentDescription {
}
@Test func asymmetricBusPullsDoNotCrash() throws {
defer { lyrebirdClearRTMarkAfterTestRender() }
// AU spec lets a host pull bus 0 repeatedly without pulling bus 1.
// Without the driver's saturation guard this would overflow bus 1's
// ring buffer after `capacity / blockSize` engine advances.
@@ -157,6 +160,7 @@ private func makeAUDesc(subtype: UInt32) -> AudioComponentDescription {
}
@Test func renderingRoutesEachBusIndependently() throws {
defer { lyrebirdClearRTMarkAfterTestRender() }
let au: StemRenderAU = try StemRenderAU(componentDescription: makeAUDesc(subtype: 0x534D4F44))
try au.allocateRenderResources()
defer { au.deallocateRenderResources() }
@@ -199,6 +203,7 @@ private func makeAUDesc(subtype: UInt32) -> AudioComponentDescription {
}
}
@MainActor
@Suite("LyrebirdAudioUnit multi-bus — sidechain input") struct LyrebirdAudioUnitSidechainTests {
@Test func twoInputBussesAreExposed() throws {
@@ -219,6 +224,7 @@ private func makeAUDesc(subtype: UInt32) -> AudioComponentDescription {
}
@Test func renderLoopDispatchesPerInputBusPullBlock() throws {
defer { lyrebirdClearRTMarkAfterTestRender() }
// Drive the full internalRenderBlock → driver → _fillInputStagingFromHost
// path with a synthetic pullInputBlock that fills bus 0 ABL with +1.0
// and bus 1 ABL with -1.0. Verify the AU passes bus 0 samples through
@@ -17,7 +17,7 @@ private final class PresetSynth: SynthesizerBase {
}
private final class PresetAU: LyrebirdAudioUnit {
public override class func makeSynthesizer() -> SynthesizerBase { PresetSynth() }
public override class func makeSynthesizer() -> SynthesizerBase { MainActor.assumeIsolated { PresetSynth() } }
public override class func factoryPresetsForLyrebird() -> [LyrebirdAUFactoryPreset] {
[
.init(name: "Bright", scalarValues: ["freq": 880, "amp": 0.8]),
@@ -36,6 +36,7 @@ private func makeDesc() -> AudioComponentDescription {
)
}
@MainActor
@Suite("LyrebirdAudioUnit factory presets") struct LyrebirdAudioUnitFactoryPresetsTests {
@Test func factoryPresetsExposeAllNames() throws {
@@ -22,7 +22,7 @@ private final class TestFMSynth: SynthesizerBase {
private final class TestFMSynthAudioUnit: LyrebirdAudioUnit {
public override class func makeSynthesizer() -> SynthesizerBase {
TestFMSynth()
MainActor.assumeIsolated { TestFMSynth() }
}
public override class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] {
[
@@ -44,6 +44,7 @@ private func makeDescription() -> AudioComponentDescription {
// MARK: - Init / parameter tree
@MainActor
@Suite("LyrebirdAudioUnit init") struct LyrebirdAudioUnitInitTests {
@Test func initSucceedsAndPopulatesParameterTree() throws {
@@ -94,6 +95,7 @@ private func makeDescription() -> AudioComponentDescription {
// MARK: - Resource lifecycle
@MainActor
@Suite("LyrebirdAudioUnit render resources") struct LyrebirdAudioUnitRenderResourceTests {
@Test func allocateAndDeallocateLifecycle() throws {
@@ -127,6 +129,7 @@ private func makeDescription() -> AudioComponentDescription {
}
@Test func renderProducesNonzeroOutputAfterAllocate() throws {
defer { lyrebirdClearRTMarkAfterTestRender() }
let au: TestFMSynthAudioUnit = try TestFMSynthAudioUnit(componentDescription: makeDescription())
try au.allocateRenderResources()
defer { au.deallocateRenderResources() }
@@ -175,6 +178,7 @@ private func makeDescription() -> AudioComponentDescription {
// MARK: - fullState save / restore
@MainActor
@Suite("LyrebirdAudioUnit fullState") struct LyrebirdAudioUnitFullStateTests {
@Test func fullStateRoundTripPreservesScalarLiveParams() throws {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("AdditiveSynthesizer")
struct AdditiveSynthesizerTests {
@@ -8,6 +8,7 @@ import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("AmbiAFormat conversion (B↔A)")
struct AmbiAFormatConversionTests {
@@ -8,6 +8,7 @@ import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("AmbiDecoderMono")
struct AmbiDecoderMonoTests {
@@ -8,6 +8,7 @@ import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("AmbiDecoderStereo")
struct AmbiDecoderStereoTests {
@@ -8,6 +8,7 @@ import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("AmbiDecoderUHJ")
struct AmbiDecoderUHJTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("AmbiEncoder1 parameter ramping")
struct AmbiEncoder1ParameterRampingTests {
@@ -8,6 +8,7 @@ import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("AmbiEncoderStereo")
struct AmbiEncoderStereoTests {
@@ -8,6 +8,7 @@ import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("AmbiEncoderUHJ")
struct AmbiEncoderUHJTests {
@@ -8,6 +8,7 @@ import Testing
import Foundation
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("AmbiSpeakerLayout")
struct AmbiSpeakerLayoutTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("AmplitudeFollower parameter ramping")
struct AmplitudeFollowerParameterRampingTests {
@@ -45,6 +45,7 @@ private func collectSamples(
// MARK: - AudioRateInput suite
@MainActor
@Suite("AudioRateInput")
struct AudioRateInputTests {
@@ -233,6 +234,7 @@ struct AudioRateInputTests {
// MARK: - FMSynthesis suite
@MainActor
@Suite("FMSynthesis")
struct FMSynthesisTests {
@@ -66,6 +66,7 @@ fileprivate final class QuadConstantGen: GeneratorBase, AudioGenerator {
}
}
@MainActor
@Suite("BinaryOpGenerator")
struct BinaryOpGeneratorTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
@@ -137,6 +138,7 @@ struct BinaryOpGeneratorTests {
// MARK: - Multi-channel broadcast
@MainActor
@Suite("BinaryOpGenerator multi-channel broadcast")
struct BinaryOpGeneratorMultiChannelTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
@@ -323,6 +325,7 @@ struct BinaryOpGeneratorMultiChannelTests {
// MARK: - Existential operator overloads (any ValidGeneratorInput op any ValidGeneratorInput)
@MainActor
@Suite("BinaryOpGenerator existential operators")
struct BinaryOpGeneratorExistentialTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
@@ -421,6 +424,7 @@ struct BinaryOpGeneratorExistentialTests {
// MARK: - ConstantGeneratorInput
@MainActor
@Suite("ConstantGeneratorInput")
struct ConstantGeneratorInputTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 8)
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("BowedString")
struct BowedStringTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("BufferRead")
struct BufferReadTests {
@@ -11,6 +11,7 @@ import Testing
/// Per-generator tests verify (1) swap takes effect on the next block, (2) swap to nil
/// silences output, (3) the previously installed buffer is released after the engine's
/// freeQueue drains.
@MainActor
@Suite("BufferSlot adoption — Phase C")
struct BufferSlotAdoptionTests {
@@ -69,6 +69,7 @@ private func makeMinimalLBHR(
// MARK: - Suite
@MainActor
@Suite("HRIRFile")
struct HRIRFileTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("BusAllocator")
struct BusAllocatorTests {
@@ -81,6 +81,7 @@ private final class ControlInputRoutingSynth: SynthesizerBase {
// MARK: - Tests
@MainActor
@Suite("Bus Ergonomics — SynthesizerBase convenience helpers")
struct BusErgonomicsTests {
let engine: SynthesisEngine = makeTestEngine(blockSize: 16)
@@ -29,6 +29,7 @@ private func rms(_ samples: [Double]) -> Double {
// MARK: - ButterworthFilterTests
@MainActor
@Suite("ButterworthFilters")
struct ButterworthFilterTests {
@@ -292,6 +293,7 @@ struct ButterworthFilterTests {
// MARK: - ButterworthBandPassTests
@MainActor
@Suite("ButterworthBandPass")
struct ButterworthBandPassTests {
@@ -438,6 +440,7 @@ struct ButterworthBandPassTests {
// MARK: - ButterworthBandRejectTests
@MainActor
@Suite("ButterworthBandReject")
struct ButterworthBandRejectTests {
+2 -1
View File
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("CPU Statistics")
final class CPUStatsTests {
@@ -17,7 +18,7 @@ final class CPUStatsTests {
try engine.start()
}
deinit {
isolated deinit {
engine.stop()
}
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("ChannelSelect")
struct ChannelSelectTests {
+1
View File
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Chorus")
struct ChorusTests {
+1
View File
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Clarinet")
struct ClarinetTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("CollectionRandomPick")
struct CollectionRandomPickTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Compressor parameter ramping")
struct CompressorParameterRampingTests {
@@ -0,0 +1,175 @@
// Phase201IsolationGuardTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdSynth
/// Phase 201/202 isolation guards.
///
/// These tests protect the main-actor isolation model against silent regression:
///
/// 1. **Off-main bridge** — `lyrebirdRunMainActorMutation` must run a `@MainActor`
/// mutation correctly when invoked from a background thread (synchronous hop to
/// main), without trapping. This path is exercised in production by the NRT inline
/// dispatcher (`LyrebirdMessageContext(nrtEngine:)`) and by AUv3 off-main hosts. The
/// rest of the suite runs `@MainActor` (node-tree mutation is a main-thread API), so
/// these specific tests are deliberately **nonisolated** to drive the off-main path.
///
/// 2. **RT-layer purity** — Generator hot-path sources must never reference actor-hop
/// machinery (`MainActor`, `assumeIsolated`, `DispatchQueue`, `Task {`). Under the
/// Swift 6 language mode such a call would compile silently but violate the
/// `nonisolated` RT render contract. This is a source-text lint.
@Suite("Phase 201/202 isolation guards")
struct Phase201IsolationGuardTests {
// MARK: - Guard A: off-main bridge
/// The bridge runs inline when already on the main thread.
@Test @MainActor func bridgeRunsInlineOnMain() {
var ran: Bool = false
lyrebirdRunMainActorMutation { ran = true }
#expect(ran)
}
/// The bridge hops synchronously to main when called off-main — it must NOT trap
/// (the regression that bare `MainActor.assumeIsolated` would have caused on the
/// NRT inline / off-main AU-host paths).
@Test func bridgeHopsFromBackgroundThreadWithoutTrapping() async {
let done: DispatchSemaphore = DispatchSemaphore(value: 0)
let ran: LockedBool = LockedBool()
// Dispatch onto a background queue so the bridge takes its `main.sync` branch.
DispatchQueue.global(qos: .userInitiated).async {
#expect(!Thread.isMainThread)
lyrebirdRunMainActorMutation {
// Body runs on the main actor.
#expect(Thread.isMainThread)
ran.set(true)
}
done.signal()
}
// Wait off the main thread (this test is nonisolated) so main is free to service
// the bridge's synchronous hop.
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
DispatchQueue.global().async {
_ = done.wait(timeout: .now() + 5)
continuation.resume()
}
}
#expect(ran.get())
}
/// End-to-end: the NRT inline `LyrebirdMessageContext` dispatcher invoked from a
/// background thread routes `ctx.add` through the bridge and the synth's `build()`
/// runs (on main) — proving the off-main NRT add path does not trap.
@Test func nrtInlineContextAddFromBackgroundThreadBuildsSynth() async {
// No `engine.start()` here on purpose: `build()` runs at add time (in `prepareNode`),
// before any render. Starting an NRT render would mark this pooled thread RT via
// `RTThreadIdentity`; that marker persists and could false-trip
// `_lyrebirdAssertNotOnRTThread` in a later `.compute()` test reusing the thread.
let engine: SynthesisEngine = makeTestEngine(blockSize: 8, numAudioBuses: 4)
let builtCount: LockedInt = LockedInt()
final class ProbeSynth: SynthesizerBase, @unchecked Sendable {
let onBuild: @Sendable () -> Void
init(onBuild: @escaping @Sendable () -> Void) { self.onBuild = onBuild; super.init() }
override func build() { onBuild() }
}
let ctx: LyrebirdMessageContext = LyrebirdMessageContext(nrtEngine: engine)
// Synth construction is `@MainActor` (Phase 201); build it on main, then add from
// a background thread to exercise the off-main bridge hop.
let synth: ProbeSynth = await MainActor.run { ProbeSynth { builtCount.increment() } }
let done: DispatchSemaphore = DispatchSemaphore(value: 0)
DispatchQueue.global(qos: .userInitiated).async {
ctx.add(synth) // inline dispatcher → lyrebirdRunMainActorMutation off-main → main hop
done.signal()
}
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
DispatchQueue.global().async {
_ = done.wait(timeout: .now() + 5)
continuation.resume()
}
}
#expect(builtCount.get() == 1)
}
// MARK: - Guard B: RT-layer source purity
/// RT-DSP sources must not reference actor-isolation machinery. Under Swift 6 language
/// mode an `@MainActor` / `assumeIsolated` call inside an RT-path source compiles
/// silently but breaks the `nonisolated` RT render contract — this lint fails the build
/// before that can ship.
///
/// Scope: the pure RT-DSP directories — `Generators/` (concrete units), `GeneratorCore/`
/// (the Generator protocol layer + `MulAdd` + hot-loop helpers), `Oversampling/`,
/// `Spectral/`, and `Math/`. `Engine/` and `NodeTree/` are intentionally NOT scanned:
/// they legitimately host the language-side `@MainActor` surface (`SynthesizerBase`,
/// the `MainActorMutationBridge`) whose `evaluate`/render entry points are separately
/// `nonisolated`.
///
/// Only `MainActor` / `assumeIsolated` are banned — pure actor-isolation hooks with no
/// legitimate place in an RT-DSP unit. `DispatchQueue` / `Task` are intentionally NOT
/// banned: buffer generators (`DiskIn` / `DiskOut`) use a background queue for off-RT
/// disk I/O (the RT side only touches a lock-free ring buffer).
@Test func generatorSourcesContainNoActorHopMachinery() throws {
let rtDspDirs: [String] = [
"Sources/Lyrebird/Generators",
"Sources/Lyrebird/GeneratorCore",
"Sources/Lyrebird/Oversampling",
"Sources/Lyrebird/Spectral",
"Sources/Lyrebird/Math",
]
let forbidden: [String] = [
"MainActor",
"assumeIsolated",
]
let fm: FileManager = FileManager.default
var violations: [String] = []
for dir: String in rtDspDirs {
let root: URL = Self.repoRoot.appendingPathComponent(dir, isDirectory: true)
guard let enumerator: FileManager.DirectoryEnumerator =
fm.enumerator(at: root, includingPropertiesForKeys: nil) else {
Issue.record("Could not enumerate \(root.path)")
continue
}
for case let url as URL in enumerator where url.pathExtension == "swift" {
let text: String = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
for token: String in forbidden where text.contains(token) {
violations.append("\(dir)/\(url.lastPathComponent): contains '\(token)'")
}
}
}
#expect(
violations.isEmpty,
"RT-DSP sources must not use actor-hop machinery (breaks the nonisolated RT contract): \(violations)"
)
}
/// Repo root, derived from this file's path:
/// `<root>/Tests/LyrebirdTests/Concurrency/Phase201IsolationGuardTests.swift`.
private static var repoRoot: URL {
URL(fileURLWithPath: #filePath)
.deletingLastPathComponent() // Concurrency/
.deletingLastPathComponent() // LyrebirdTests/
.deletingLastPathComponent() // Tests/
.deletingLastPathComponent() // <root>
}
}
// MARK: - Tiny thread-safe test helpers
private final class LockedBool: @unchecked Sendable {
private let lock: NSLock = NSLock()
private var value: Bool = false
func set(_ v: Bool) { lock.lock(); value = v; lock.unlock() }
func get() -> Bool { lock.lock(); defer { lock.unlock() }; return value }
}
private final class LockedInt: @unchecked Sendable {
private let lock: NSLock = NSLock()
private var value: Int = 0
func increment() { lock.lock(); value += 1; lock.unlock() }
func get() -> Int { lock.lock(); defer { lock.unlock() }; return value }
}
@@ -10,6 +10,7 @@ import Testing
// MARK: - OscSin.Control Tests
@MainActor
@Suite("OscSin.Control")
struct OscSinControlTests {
let blockSize: Int = 64
@@ -134,6 +135,7 @@ struct OscSinControlTests {
// MARK: - OscTableControl Tests
@MainActor
@Suite("OscTableControl")
struct OscTableControlTests {
let blockSize: Int = 64
@@ -217,6 +219,7 @@ struct OscTableControlTests {
// MARK: - ImpulseControl Tests
@MainActor
@Suite("ImpulseControl")
struct ImpulseControlTests {
// Use blockSize == sampleRate so 1 Hz fires exactly once per block.
@@ -332,6 +335,7 @@ struct ImpulseControlTests {
// MARK: - WhiteNoiseControl Tests
@MainActor
@Suite("WhiteNoiseControl")
struct WhiteNoiseControlTests {
let blockSize: Int = 64
@@ -406,6 +410,7 @@ struct WhiteNoiseControlTests {
// MARK: - LFStepNoiseControl Tests
@MainActor
@Suite("LFStepNoiseControl")
struct LFStepNoiseControlTests {
// blockSize == sampleRate so 1 Hz fires exactly once per block.
@@ -522,6 +527,7 @@ struct LFStepNoiseControlTests {
// MARK: - LFLineNoiseControl Tests
@MainActor
@Suite("LFLineNoiseControl")
struct LFLineNoiseControlTests {
let blockSize: Int = 100
@@ -648,6 +654,7 @@ private final class CountingControl: GeneratorBase, ControlGenerator {
// MARK: - Sub-block control tests
@MainActor
@Suite("ControlGenerator sub-block")
struct ControlGeneratorSubBlockTests {
@@ -826,6 +833,7 @@ struct ControlGeneratorSubBlockTests {
// MARK: - PinkNoiseControl Tests
@MainActor
@Suite("PinkNoiseControl")
struct PinkNoiseControlTests {
let blockSize: Int = 64
@@ -901,6 +909,7 @@ struct PinkNoiseControlTests {
// MARK: - BrownNoiseControl Tests
@MainActor
@Suite("BrownNoiseControl")
struct BrownNoiseControlTests {
let blockSize: Int = 64
@@ -975,6 +984,7 @@ struct BrownNoiseControlTests {
// MARK: - GrayNoiseControl Tests
@MainActor
@Suite("GrayNoiseControl")
struct GrayNoiseControlTests {
let blockSize: Int = 64
@@ -1049,6 +1059,7 @@ struct GrayNoiseControlTests {
// MARK: - ClipNoiseControl Tests
@MainActor
@Suite("ClipNoiseControl")
struct ClipNoiseControlTests {
let blockSize: Int = 64
@@ -1124,6 +1135,7 @@ struct ClipNoiseControlTests {
// MARK: - DustControl Tests
@MainActor
@Suite("DustControl")
struct DustControlTests {
let blockSize: Int = 64
@@ -1200,6 +1212,7 @@ struct DustControlTests {
// MARK: - Dust2Control Tests
@MainActor
@Suite("Dust2Control")
struct Dust2ControlTests {
let blockSize: Int = 64
@@ -1276,6 +1289,7 @@ struct Dust2ControlTests {
// MARK: - CrackleControl Tests
@MainActor
@Suite("CrackleControl")
struct CrackleControlTests {
let blockSize: Int = 64
@@ -1356,6 +1370,7 @@ struct CrackleControlTests {
// MARK: - LFCurveNoiseControl Tests
@MainActor
@Suite("LFCurveNoiseControl")
struct LFCurveNoiseControlTests {
let blockSize: Int = 100
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("ConvolutionReverb.Audio — partitioned overlap-save FFT convolution")
struct ConvolutionReverbTests {
@@ -9,6 +9,7 @@ import Testing
// MARK: - CoreAudioDriverOptions defaults
@MainActor
@Suite("CoreAudioDriverOptions") struct CoreAudioDriverOptionsTests {
@Test func defaultMatchDeviceSampleRateIsFalse() {
let opts: CoreAudioDriverOptions = CoreAudioDriverOptions()
@@ -23,6 +24,7 @@ import Testing
// MARK: - Sample rate validation (offline, no hardware required)
@MainActor
@Suite("CoreAudioDriver sample rate validation") struct CoreAudioSampleRateValidationTests {
@Test func doesNotThrowWhenRatesMatch() throws {
let opts: CoreAudioDriverOptions = CoreAudioDriverOptions()
@@ -73,6 +75,7 @@ import Testing
// MARK: - deviceSampleRate property
@MainActor
@Suite("CoreAudioDriver deviceSampleRate") struct CoreAudioDeviceSampleRateTests {
@Test func deviceSampleRateNilBeforeSetup() {
let driver: CoreAudioDriver = CoreAudioDriver()
@@ -82,6 +85,7 @@ import Testing
// MARK: - Lifecycle (no hardware required)
@MainActor
@Suite("CoreAudioDriver lifecycle") struct CoreAudioDriverLifecycleTests {
@Test func stopBeforeSetupIsNoop() {
let driver: CoreAudioDriver = CoreAudioDriver()
+1
View File
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Decay2")
struct Decay2Tests {
+1
View File
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("Decay")
struct DecayTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("DelayLineFeedback parameter ramping")
struct DelayLineFeedbackParameterRampingTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("DemandBrownian")
struct DemandBrownianTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("DemandConcatenate")
struct DemandConcatenateTests {
@@ -9,6 +9,7 @@ import Testing
// MARK: - DemandSequence
@MainActor
@Suite("DemandSequence")
struct DSequenceTests {
@@ -65,6 +66,7 @@ struct DSequenceTests {
// MARK: - DemandRandom
@MainActor
@Suite("DemandRandom")
struct DRandomTests {
@@ -115,6 +117,7 @@ struct DRandomTests {
// MARK: - Demand.Audio
@MainActor
@Suite("Demand.Audio")
struct DemandAudioTests {
@@ -235,6 +238,7 @@ struct DemandAudioTests {
// MARK: - Demand.Control
@MainActor
@Suite("Demand.Control")
struct DemandControlTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("DemandGeometric")
struct DemandGeometricTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("DemandNonRepeatingRandom")
struct DemandNonRepeatingRandomTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("DemandSeries")
struct DemandSeriesTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("DemandShuffle")
struct DemandShuffleTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("DemandStutter")
struct DemandStutterTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("DemandSwitch")
struct DemandSwitchTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("DemandUniformRandom")
struct DemandUniformRandomTests {
@@ -7,6 +7,7 @@
import Testing
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
@MainActor
@Suite("DemandWeightedRandom")
struct DemandWeightedRandomTests {
@@ -9,6 +9,7 @@ import Testing
// MARK: - denormalsToZero helper
@MainActor
@Suite("denormalsToZero")
struct DenormalsToZeroTests {
@@ -57,6 +58,7 @@ struct DenormalsToZeroTests {
// any computation that would produce a subnormal result is flushed to zero by the
// hardware, so filter outputs and delay-line writes must never be subnormal.
@MainActor
@Suite("FirstOrderSection — no subnormals under FTZ")
struct FirstOrderSectionFTZTests {
@@ -87,6 +89,7 @@ struct FirstOrderSectionFTZTests {
}
}
@MainActor
@Suite("SecondOrderSection — no subnormals under FTZ")
struct SecondOrderSectionFTZTests {
@@ -115,6 +118,7 @@ struct SecondOrderSectionFTZTests {
}
}
@MainActor
@Suite("RBJBandPass — no subnormals under FTZ")
struct RBJBandPassFTZTests {
@@ -141,6 +145,7 @@ struct RBJBandPassFTZTests {
}
}
@MainActor
@Suite("DelayLineFeedback — no subnormals under FTZ")
struct DelayLineFeedbackFTZTests {

Some files were not shown because too many files have changed in this diff Show More