36 Commits

Author SHA1 Message Date
josh 56726223f6 v2.3.2 release: README — add a 'write your own Generator' example
Adds a complete HardClip audio-rate distortion to the quick-taste section,
showing GeneratorBase + AudioGenerator conformance, init-time input
resolution, the _checkCount guard, and filling/returning the pre-allocated
_result in place — the Generator-authoring counterpart to the existing
graph-composition example.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-29 13:57:47 -08:00
josh 8e600f3a66 v2.3.1: add LyrebirdGUIDemo to the Xcode workspace scheme list
Follow-up to the v2.3.1 content: reference the LyrebirdGUIDemo package from
Lyrebird.xcworkspace so Xcode surfaces its scheme, and note it in the README
schemes table.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-29 11:41:18 -08:00
josh 06bdcbbe92 v2.3.1 release: cross-platform LyrebirdGUIDemo + Linux demo ports + doc refresh
- New Demos/LyrebirdGUIDemo: one shared source (synths + node-based views) that
  bootstraps SwiftUI on macOS and GTK4/SwiftOpenUI on Linux; LYREBIRD_DEMO=vector|sine.
- The four CLI demos (Quickstart/Demo/NRT/Score) now build and run on Linux.
- README + Linux getting-started refreshed; LyrebirdATK row removed from the
  Extensions section pending collaborator sign-off.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-29 11:34:24 -08:00
josh 162da89319 docs: point package URLs at git.lyrebirdsynth.net
Mirror of the dev-repo URL rename. The public gitea host is now reached at
git.lyrebirdsynth.net (a DNS CNAME to realizedsound.mooo.com, the former
hostname; both resolve to the same server). Updates the consumer-facing package
URLs in the README, CONTRIBUTING, install/getting-started docs, the
ProjectScaffolder.lyrebirdPackageURL constant, and the release-prep skill notes.
Doc-only; legacy mooo URLs still resolve, so non-breaking. No tag.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-28 15:19:03 -08:00
josh 9f244b1939 v2.3.0 release: onEditingEnded edit-ended callback on continuous controls
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-25 13:59:52 -08:00
josh 24ea32e47c v2.2.0 release: live-parameter ramp origin primed at synth add
A @UIParam/@LiveParam value assigned after construction but before the first render
is now delivered flat on the first block instead of ramping from the property-
declaration default (fixes e.g. a NoiseGate restored from saved rig state latching
open and ignoring its threshold). Backed by a new internal-facing
LiveParameterValue._primeRampOrigin() (default no-op, source-compatible); live
changes after start still ramp. See RELEASES.md for the full behavior-change note.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-03 12:25:29 -08:00
josh c14efe998a docs(readme): add Linux equivalents for adding the package and opening the project
Mirror of Lyrebird dev HEAD. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 18:44:50 -07:00
josh 63b630b317 docs(readme): name VS Code as the Linux IDE in Requirements
Mirror of Lyrebird dev HEAD. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 16:40:58 -07:00
josh 3668739d20 docs(readme): add Linux row to the Requirements table
Mirror of Lyrebird dev HEAD. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 16:40:05 -07:00
josh 6e7f4c0076 docs(readme): note Linux support alongside macOS/iOS
Mirror of Lyrebird dev HEAD (c8cbb52f). README intro + quick-taste engine line now
name the platform audio backends (Core Audio on Apple, ALSA on Linux). No code change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-18 16:36:10 -07:00
josh f8878324fd v2.1.1 release: delay-click fix + internal consolidation
Mirror of Lyrebird dev HEAD (9f791c7c) minus maintainer-only paths. Patch release:
fixes the allpass fractional-delay click (DelayLine/CombFilter/AllpassFilter/
DelayLineFeedback under a modulated delay) and lands the internal code-quality
consolidation pass (~160 deduped sites + shared base classes/helpers, bit-identical
output). No public API removed or changed. See RELEASES.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-07 21:20:49 -07:00
josh 844dc4d9cd v2.1.0 release: Swift 6.4 modernization
Typed throws across the closed-error-set APIs (OSC, MIDI, engine add/schedule,
bus/config/parameter, and the WAV/RF64/Spectral file codecs — source-compatible
narrowing, new .ioFailure cases), plus internal hardening: NSLock-guarded
scheduling/MIDI state moved to Mutex<State>, and the Spectral/FFT scratch owners
moved to a ~Copyable RTScratchBuffer RAII buffer. No API or behavioral change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 19:54:59 -07:00
josh 2c20b02e59 docs: consumer migration guide for Lyrebird 1.x → 2.0
Mirror of the dev-repo docs commit: add docs/migrating-to-2.0.md (module
rename + @UIParam/UIParamNode move into core LyrebirdSynth, with the fix)
and the cross-reference from DEVELOPMENT_AND_RELEASE.md. Docs-only; will be
reconciled by the next full release sync.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-23 21:21:45 -07:00
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
Consolidated release: the cross-platform Linux port (engine, generators, CLI,
REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable
WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux
live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive.
See RELEASES.md and LINUX_README.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-10 21:09:11 -07:00
josh 77580ee98e v1.7.2 release: sample-rate-invariant TriodeStage coupling + Mesa/Soldano tone stacks
- TriodeStage coupling DC-blocker corner is now held constant in Hz across sample
  rates (was a fixed pole whose corner drifted up with Fs, thinning low end at high
  rates); evaluated at init, off the RT thread.
- New ToneStackModel cases .mesa and .soldano (Faust tonestacks-library values).
- GrayNoise output clamped to [-1, 1] (Int32.min edge).
2026-08-03 15:57:54 -07:00
josh ea0aa84ca7 v1.7.1 release: GuitarML Proteus/NeuralPi model importer
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-01 20:31:38 -07:00
josh 3e33f09e07 v1.7.0 release: amp-modeling core (ToneStack, TriodeStage, LSTMAmp)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-01 19:55:12 -07:00
josh d6875da2cb v1.6.4 release: LookAheadLimiter releaseTime decoupled from lookAheadTime
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-31 18:10:54 -07:00
josh 5e6534a615 v1.6.3 release: notarization-ready macos-ui-xcode template
Scaffolded macOS app now ships audio-input entitlement + mic usage string
under Hardened Runtime (unsandboxed for performance), and compiles under
Swift 6 (NoteController/AppDelegate marked @MainActor).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 08:38:41 -07:00
josh 9ec92277de v1.6.2 release: Live Scratch distributable/notarized app
Bundle Lyrebird swiftmodules + relocatable LyrebirdC module into the app so a
notarized, moved LyrebirdScratch.app can compile snippets off the build machine.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 20:13:47 -07:00
josh 90dc00f323 v1.6.1 release: Live Scratch Swift-toolchain detection + app icon
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 19:19:44 -07:00
josh 8eb64f883f v1.6.0 release: soundfile format expansion (WAV int depths + RF64 >4GB, AIFF/CAF, AAC/ALAC compressed, 4GB guard, unified AudioFileFormat)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 17:45:34 -07:00
josh 62b2f5dbec v1.5.0 release: LyrebirdRandom + Live Scratch editor
LyrebirdRandom scalar distribution sampling (seedable value type + shared
Random) with DistributionKind.sample dispatcher. Live Scratch editor: rename to
LyrebirdScratch, App Support artifact staging, Format Code (⌥⌘F), Render to File
(⌥⌘R offline CAF), line-number gutter, manual completion, Foundation in snippets,
scroll-jump fix, scheduling/NRT docs.
2026-07-22 07:53:12 -07:00
josh 8519cabe42 v1.4.2 release: live-coding editor — Run Selection, slot release, engine panel, console, manual completion
Additive conveniences to the macOS-only Live Scratch editor. No changes to
existing public API.

- Run Selection (⌘E): evaluate just the highlighted text, additively.
- Graceful slot release: context.release(slot:) / free(slot:).
- Engine panel: live oscilloscope (ScopeCapture) + CPU avg/peak + counts.
- Reset Session / Restart to Reclaim Memory.
- Always-open console panel (report messages + errors with line:col).
- Faster typing: debounced highlight, updateNSView fast-path, publish guards.
- Manual code completion (Esc / F5), no auto-trigger on `.`; completion
  replaces the partial word, not the receiver expression.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 11:09:30 -07:00
josh abc64df4d7 v1.4.1 release: Learning Swift for Lyrebird intro guide
Documentation-only release. Adds docs/learning-swift/ — a four-part
introduction to Swift for Lyrebird users coming from SuperCollider,
Max/MSP, Csound, etc. (Hello World, Swift basics & best practices,
types & functional programming, Xcode/packages/debugging). Linked from
README.md and LYREBIRD_START_HERE.md. See RELEASES.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 12:10:00 -07:00
josh 38d2107f64 v1.4.0 release: live-coding scratch editor, interpreted Graph DSL, ClosureSynthesizer + SampleLoop 2026-07-20 10:02:49 -07:00
josh 560724d116 v1.3.0 release: graceful-release fix, quickstart template + demo, documentation accuracy pass
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated
  synths were hard-freed instead of released).
- New: quickstart project template + LyrebirdQuickstartDemo.
- Docs: every example typechecked or provably illustrative (426->542); ~20
  wrong-API examples fixed; root docs brought under the compile guard.
- Fixed: NRT/Score demo Package.swift build from terminal again.

See RELEASES.md for details.
2026-07-17 14:05:01 -07:00
josh 63d6e0746f v1.2.4 release: bus-rate guard on Out/In/ReplaceOut constructors 2026-07-14 16:12:53 -07:00
josh c058493a98 v1.2.3 release: remove ShoeGaze CLI scaffolding (ShoeGaze now standalone) 2026-07-04 22:48:23 -07:00
josh 8a2eb191a2 improve freq trackers 2026-07-02 14:48:37 -07:00
josh 676e8d3278 1.2.1 release to support some ShoeGaze features 2026-07-02 10:20:40 -07:00
josh 032b7c39d3 prep for 1.2.0 release updates 2026-06-21 11:45:58 -07:00
josh 73191c958f Music XML updates and optimizations 2026-06-16 20:55:32 -07:00
josh ca1ee503cc more cleanup, prep for 1.1.0 2026-06-10 08:47:11 -07:00
josh 1c03e39eac cleanup 2026-06-10 08:41:23 -07:00
josh f59fd3b55a bugfixes, better MusicXML support and 1.1.0 2026-06-10 08:41:07 -07:00
1117 changed files with 102278 additions and 18775 deletions
+18
View File
@@ -1,4 +1,8 @@
.build/ .build/
.build-linux/
.build-glibc/
.build-docker*/
build/
.claude/settings.local.json .claude/settings.local.json
.claude/worktrees/ .claude/worktrees/
*.o *.o
@@ -8,3 +12,17 @@
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
xcuserdata/ xcuserdata/
*.xcuserstate *.xcuserstate
# Linux container scratch build trees (docker runs with the repo mounted).
.build-alsa/
.build-alsa-amd64/
.build-noalsa/
# Spike sub-packages build their own .build when run from their directory.
spikes/**/.build/
# Local SwiftOpenUI fork clone for the @Observable GUI spike (patched, user-local).
spikes/SwiftOpenUI/
# All local Docker/scratch build trees.
.build-*/
+45 -1
View File
@@ -256,12 +256,14 @@ 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. `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) ### 9.1 Actor isolation of the lifecycle
The Swift-concurrency isolation of `Synthesizer` is split along exactly the thread boundary above: 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.) - **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.)
- **`SynthesizerBase` declares `release(engine:)` / `free(engine:)` as `open` members, not just protocol conformances.** The `Synthesizer` extension supplies defaults for both, but a protocol-extension default is bound **statically** at the conformance — `SynthesizerBase`'s. Were the base to declare no member of its own, a subclass could not `override` them at all, and a subclass method declared without `override` would be invisible to every caller holding an `any Synthesizer`: the call would reach the extension default and throw `.noGate`. That matters because the callers that drive the lifecycle are exactly those existential ones — `Group.release` cascades to children as `any Synthesizer`, freeing any child that throws `.noGate`, so a gated subclass would be hard-freed and its envelope release phase skipped. Declaring both as `open` class members makes the witness a class method, so the call dispatches through the vtable and subclass overrides run. Pinned by `SynthesizerReleaseDispatchTests`.
- **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. - **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). - **`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).
@@ -270,6 +272,48 @@ The Swift-concurrency isolation of `Synthesizer` is split along exactly the thre
The guarantee is locked by the committed `RegressionFixtures/MainActorConsumer` package, which compiles an unannotated `SynthesizerBase` subclass under `.swiftLanguageMode(.v6)` + `-default-isolation MainActor`. The guarantee is locked by the committed `RegressionFixtures/MainActorConsumer` package, which compiles an unannotated `SynthesizerBase` subclass under `.swiftLanguageMode(.v6)` + `-default-isolation MainActor`.
### 9.2 Working with the isolation from a routine or task
A `LyrebirdRoutine` / `LyrebirdTask` body is `@Sendable` and runs on its own background thread. `SynthesizerBase` is `@MainActor`. Those two facts drive every ergonomic question below, so it is worth being precise about **what is actually main-bound, and why**:
| Step | Main-bound? | Why |
|---|---|---|
| `init` (allocate the synth) | **Yes** — but for an *ergonomic* reason, not an RT one | See "Why `init` is not `nonisolated`" below |
| `build()` (construct the DAG) | **Yes — load-bearing** | Must complete-before the `.add` enqueue; that is the happens-before edge the RT thread relies on (§9.1) |
| `engine.add` / `schedule` | **Yes — load-bearing** | `pendingQueue` is SPSC: exactly one producer |
| `engine.remove` | No | Unbinds via atomics, enqueues a pointer-only event |
| Writing a `@LiveParam` | No — but the *property* is main-isolated | The value itself crosses via a lock-free atomic (see "Mutating parameters") |
| `evaluate()` (RT) | No — `nonisolated final` | The render callback must reach it with no actor hop |
**Constructing a synth inside a body — `ctx.onMain`.** Because a body cannot touch `@MainActor` state directly, the historical idiom was to pre-allocate every synth *outside* the body and capture it (the `BufferDemos` pattern). That forces the set of synths to be known in advance. ``LyrebirdRoutineContext/onMain(_:)`` removes the restriction — it runs a main-actor closure, blocks the body until it returns, and hands the (possibly non-`Sendable`) result back:
```swift
LyrebirdTask.run(engine: engine) { ctx in
while ctx.now < 10.0 {
let grain: Grain = ctx.onMain { Grain(startPos: nextPos(), rate: nextRate()) }
ctx.add(grain) // async hop; grain self-frees via its envelope
try ctx.wait(seconds: 0.05) // drift-compensated as usual
}
}
```
The hop is synchronous, so its cost counts as work between `wait` calls — which `wait(seconds:)` already compensates for by shortening the next sleep. Keep the closure short (build one synth, not a batch): it blocks both the body and the main thread. Note `build()` does **not** run inside `onMain` — it runs later, on main, inside `ctx.add`'s dispatched `engine.add`.
`onMain` **requires a serviced main thread**, and this is the one way to misuse it. `ctx.add` is fire-and-forget (`DispatchQueue.main.async`) and merely delays if main is busy; `onMain` hops synchronously with no timeout, so if main is never serviced it blocks the body forever with no diagnostic. A GUI run loop services it; so does a CLI parked on `waitUntilComplete()` / `LyrebirdTask.run`, which pump the main run loop for exactly this reason. The trap is `task.start(engine:)` followed by blocking main on something that is not a run loop (a bare `Thread.sleep`, a semaphore wait) — park on `waitUntilComplete()` instead. Re-entering the caller's own thread is *not* a hazard: `lyrebirdRunMainActorMutation` branches on `Thread.isMainThread` and runs the closure inline when already on main, so `onMain` is self-deadlock-free whichever thread calls it.
**Mutating parameters — `ctx.set`, not property writes.** Construction is *pre-publication*: the synth is thread-local, unshared, and the RT thread cannot reach it, which is what makes hopping to main for it a pure formality. A parameter write is *post-publication*: the synth is live in the tree and the RT thread reads it every block. Safety there comes from `ParameterNode`'s atomic — **not** from isolation. So capture the projected node on main once, then drive it from the body:
```swift
let cutoff: ParameterNode = filter.$cutoff // captured on main
LyrebirdTask.run(engine: engine) { ctx in
ctx.set(cutoff, to: 1200) // releasing atomic store — no dispatch
}
```
`ctx.set` is **not** a main hop: unlike `ctx.add`, it writes the atomic inline on the body's own thread. The only cost is the one-line capture. (`synth.cutoff = 1200` and `synth.$cutoff` are both main-isolated — the property inherits the class's isolation even though `LiveParam` itself is a plain, atomic-backed struct.)
**Why `init` is not `nonisolated`.** It looks free — the base `init()` is empty, `build()` is not called from it, and a fresh synth is unshared. It is not free. Under `-default-isolation MainActor` a consumer subclass that declares no init gets an *implicit `@MainActor init()`*, which would then override a `nonisolated` base init and fail with `different actor isolation from nonisolated overridden declaration` — breaking every unannotated consumer, i.e. exactly the §9.1 guarantee. The main test suite cannot catch this (it does not build under that flag); `RegressionFixtures/MainActorConsumer` is the only thing that does. **If you are tempted to relax the isolation on `SynthesizerBase.init`, build that fixture first.** `ctx.onMain` exists precisely because it buys the same ergonomics additively, with no isolation change.
--- ---
## Where to go deeper ## Where to go deeper
+62 -8
View File
@@ -12,7 +12,7 @@ Eight agents live in `~/.claude/agents/` (maintainer's source of truth) and are
| `lyrebird_generator_agent` | **Any new Generator** — oscillator, filter, effect, noise, math operator, bus I/O. | | `lyrebird_generator_agent` | **Any new Generator** — oscillator, filter, effect, noise, math operator, bus I/O. |
| `lyrebird_engine_agent` | Engine internals — SynthesisEngine, CoreAudioDriver/iOSAudioDriver, AUHAL, SPSCQueue, ScheduledEvent, Group/ParallelGroup, RT thread architecture. | | `lyrebird_engine_agent` | Engine internals — SynthesisEngine, CoreAudioDriver/iOSAudioDriver, AUHAL, SPSCQueue, ScheduledEvent, Group/ParallelGroup, RT thread architecture. |
| `lyrebird_language_agent` | Non-RT language side — SynthesizerBase, @LiveParam, ParameterNode, LyrebirdRoutine/Task/Clock, Pattern, MIDI, OSC, NRT, Score, demand pattern usage. | | `lyrebird_language_agent` | Non-RT language side — SynthesizerBase, @LiveParam, ParameterNode, LyrebirdRoutine/Task/Clock, Pattern, MIDI, OSC, NRT, Score, demand pattern usage. |
| `lyrebird_swiftui_agent` | LyrebirdUI module — @UIParam, ParameterKnob/Slider/XY/Button/Label, scope/envelope views, platform-conditional code. | | `lyrebird_swiftui_agent` | LyrebirdUI module — ParameterKnob/Slider/XY/Button/Label, scope/envelope views, platform-conditional code. (@UIParam/UIParamNode themselves live in core `Lyrebird`.) |
| `lyrebird_architect_agent` | Cross-cutting analysis — duplicate patterns, API consistency, SC naming alignment, refactor planning. **No implementation.** | | `lyrebird_architect_agent` | Cross-cutting analysis — duplicate patterns, API consistency, SC naming alignment, refactor planning. **No implementation.** |
| `lyrebird_review_agent` | Pre-merge review (via `/lyrebird_review`) — RT safety, bus rules, protocol correctness, helper usage, test coverage. | | `lyrebird_review_agent` | Pre-merge review (via `/lyrebird_review`) — RT safety, bus rules, protocol correctness, helper usage, test coverage. |
| `pr_review_agent` | General pre-PR review — bugs, security, code smells. Broader scope than `lyrebird_review`. | | `pr_review_agent` | General pre-PR review — bugs, security, code smells. Broader scope than `lyrebird_review`. |
@@ -31,10 +31,29 @@ git config core.hooksPath .githooks
``` ```
The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/agents/` is absent (contributors without working copies are not blocked). Bypass for one commit with `git commit --no-verify`. The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/agents/` is absent (contributors without working copies are not blocked). Bypass for one commit with `git commit --no-verify`.
## Repo Guard Scripts
These guards catch classes of regression that **`swift build` / `swift test` structurally cannot**. Both are manual/CI (too slow for pre-commit). Run before a release or a merge that touches their surface.
| Script | Guards | Run when |
|---|---|---|
| `bash scripts/check-swift6-consumer.sh` | The zero-annotation consumer guarantee — builds `RegressionFixtures/MainActorConsumer` under `.swiftLanguageMode(.v6)` + `-default-isolation MainActor`. The main package **does not build under that flag**, so the test suite cannot catch an isolation regression. | Any change to `SynthesizerBase` / `Synthesizer` actor isolation. Non-negotiable: `swift test` passing is *not* evidence here. |
| `bash scripts/check-docc.sh` | New DocC warnings — broken symbol links, ambiguous refs, article/symbol collisions. DocC links pin a symbol's **full signature**, so adding one parameter silently breaks every link to it. Nothing else checks this. | Any change to a public signature, or edits to `.docc` / doc comments. |
| `bash scripts/check-doc-impact.sh [range]` | **Reports** (never fails) which docs a diff's public-API changes may have invalidated. Doc rot is usually *caused* by an API change, and a diff-only read cannot find the stale references — they live in files the diff never touches. Run by `/lyrebird_review` step 2b; suppresses refs the compile guard already covers. | Any change to a public signature. |
| `bash scripts/check-doc-snippets.sh` | Doc **examples** that stop compiling. `swift build` never sees a code fence and `check-docc.sh` only validates links, so examples rot silently — `engine.add` became throwing and 11 examples kept calling it without `try`; `LyrebirdFloat` was deleted and 75 references outlived it. Both are type errors, so the fences are typechecked against the real API. | Any change to a public signature, or edits to `.docc` / doc comments. |
`check-docc.sh` is a **ratchet**: it fails on warnings absent from `scripts/docc-warnings-baseline.txt`. That baseline is now **empty** — the catalog is at zero warnings — so in practice any new warning fails the build. Keep it that way; the baseline may only shrink. (`--strict` asserts zero explicitly and is equivalent while the baseline is empty. `--update-baseline` exists for the rare deliberate exception — prefer fixing the link.)
**Golden values need a test, not a guard.** A typecheck proves an example still *compiles*; it cannot see a documented result drift. Where a doc asserts concrete output (`// → 0.744, 0.046, …`), pin it with a test — `DistributionKindGoldenValueTests` and `_DocTheorySnippetCheckTests` are the two instances. This is not optional pedantry: three of the four `DistributionKind` sequences had silently drifted, and their fences also passed a `seed:` argument to a type that has no such parameter.
`check-doc-snippets.sh` checks the fences recorded in `scripts/doc-snippets-manifest.txt` (currently **426** of 1458). That set is produced by asking the **compiler** which fences compile — `--classify` — never by hand-annotating fences. A fence that compiles under no preamble self-excludes, which is how iOS-only examples, `Package.swift` snippets and pseudo-code drop out with no skip list. **Coverage is therefore partial by construction**: a fragment like `try engine.add(MySynth())`, which needs both an `engine` and a `MySynth` in scope, is *not* checked. The fix for an important uncovered example is to make it self-contained in the doc — which is better documentation anyway — not to grow the preamble table. Re-run `--classify` after adding examples or deliberately changing what is checkable.
## Task → Doc Map ## Task → Doc Map
**Engine / RT core** **Engine / RT core**
- Engine init, audio driver, render pass → `docs/engine/synthesis-engine.md`, `docs/engine/core-audio-driver.md`, `docs/signal-flow/signal-flow.md` - Engine init, audio driver, render pass → `docs/engine/synthesis-engine.md`, `docs/engine/core-audio-driver.md`, `docs/signal-flow/signal-flow.md`
- Linux live audio (`ALSAAudioDriver`, `makeDefaultAudioDriver()`, libasound build requirement) → `docs/engine/alsa-audio-driver.md`
- Portable WAV read/write off Apple (`WavFileWriter` / `WavFileReader`, header layout, `WavFileError`) → `docs/engine/portable-wav-codec.md`
- Bus memory / In / Out → `docs/engine/bus-system.md` - Bus memory / In / Out → `docs/engine/bus-system.md`
- Sample-accurate scheduling → `docs/engine/scheduling.md` - Sample-accurate scheduling → `docs/engine/scheduling.md`
- ParallelGroup / multi-core → `docs/engine/multi-core.md` - ParallelGroup / multi-core → `docs/engine/multi-core.md`
@@ -43,6 +62,7 @@ The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/
**Generators** **Generators**
- Generator protocol + DemandGenerator → `docs/protocols/generator.md` - Generator protocol + DemandGenerator → `docs/protocols/generator.md`
- **Implementing a new Generator** → `docs/protocols/writing-generators.md` (§13 = shared helpers) - **Implementing a new Generator** → `docs/protocols/writing-generators.md` (§13 = shared helpers)
- Inline custom per-sample DSP / single-sample feedback without a new Generator type (`SampleLoop` — pre-allocated output, typed `inout` feedback state, channel inference + broadcast) → `Sources/Lyrebird/Generators/Core/SampleLoop.swift`
- Built-in generator catalog → `docs/stdlib/generators.md` - Built-in generator catalog → `docs/stdlib/generators.md`
- Multi-channel / `outputChannelCount` / channel-aware operators → `docs/stdlib/multichannel.md` - Multi-channel / `outputChannelCount` / channel-aware operators → `docs/stdlib/multichannel.md`
- Musical math (MIDI↔Hz, dB, intervals) → `docs/stdlib/generators.md` (LyrebirdMusicMath section) - Musical math (MIDI↔Hz, dB, intervals) → `docs/stdlib/generators.md` (LyrebirdMusicMath section)
@@ -57,10 +77,13 @@ The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/
- Routines / tasks / clock / MIDI / OSC → `docs/tooling/routine-task.md` - Routines / tasks / clock / MIDI / OSC → `docs/tooling/routine-task.md`
- `Pattern<T>` factory catalog (sequence, series, geometric, uniformRandom, brownian, gaussian, cauchy, beta, shuffle, nonRepeatingRandom, weightedRandom, closure, repeating, limit, drop, stutter, switching, concatenate, roundRobin, tuple, interleave, map, filter, reject, accumulate, difference, wrap, clip, round, smooth) → `docs/tooling/routine-task.md` (§ Pattern Factory Reference) + `Sources/Lyrebird/Lyrebird.docc/RoutineTask.md` - `Pattern<T>` factory catalog (sequence, series, geometric, uniformRandom, brownian, gaussian, cauchy, beta, shuffle, nonRepeatingRandom, weightedRandom, closure, repeating, limit, drop, stutter, switching, concatenate, roundRobin, tuple, interleave, map, filter, reject, accumulate, difference, wrap, clip, round, smooth) → `docs/tooling/routine-task.md` (§ Pattern Factory Reference) + `Sources/Lyrebird/Lyrebird.docc/RoutineTask.md`
- MIDI clock sync (`MIDIClockFollower`) → `docs/tooling/midi-clock-sync.md` - MIDI clock sync (`MIDIClockFollower`) → `docs/tooling/midi-clock-sync.md`
- Linux MIDI (`MIDI` via ALSA sequencer — `MIDI/ALSAMIDI.swift`, `ALSASeqMIDIEvent` mapping; needs CALSA/libasound) → `Sources/Lyrebird/MIDI/ALSAMIDI.swift`
- Linux OSC (`OSCClient` / `OSCServer` POSIX-UDP transport off Apple, `OSCServerError`; codec unchanged) → `Sources/Lyrebird/OSC/OSCServer.swift`
- Non-RT parameter value sources / `ValueComputable` / `ValueComputableClosure` (consumed by `LyrebirdProcess` parameters) → `Sources/Lyrebird/Lyrebird.docc/ValueComputable.md` - Non-RT parameter value sources / `ValueComputable` / `ValueComputableClosure` (consumed by `LyrebirdProcess` parameters) → `Sources/Lyrebird/Lyrebird.docc/ValueComputable.md`
- TemporalStream / language-side value generation → `Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md` - TemporalStream / language-side value generation → `Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md`
- Polyphonic voice pool / step sequencer → `docs/tooling/routine-task.md` - Polyphonic voice pool / step sequencer → `docs/tooling/routine-task.md`
- Score / ScorePlayer / SMF / MusicXML → `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md` - Score / ScorePlayer / SMF / MusicXML → `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`
- Pitch / scale theory toolkit (spelling-aware `Interval` / `Scale` / `PitchCollection` / 12-tone rows, diatonic-vs-chromatic transposition, scale mapping; → notation + Hz/seconds for synthesis) → `docs/stdlib/theory.md` (types under `Sources/Lyrebird/Score/Theory/`)
- Performance event sequencing / `LyrebirdProcess` / `LyrebirdEventList` → `Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md` - Performance event sequencing / `LyrebirdProcess` / `LyrebirdEventList` → `Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md`
- NRT / offline render → `docs/tooling/nrt-guide.md` - NRT / offline render → `docs/tooling/nrt-guide.md`
@@ -68,15 +91,18 @@ The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/
- CLI / REPL / hot-swap → `docs/tooling/cli-guide.md`, `docs/tooling/repl.md` - CLI / REPL / hot-swap → `docs/tooling/cli-guide.md`, `docs/tooling/repl.md`
- Project scaffolding / package targets → `docs/tooling/project-system.md`, `docs/tooling/targets.md` - Project scaffolding / package targets → `docs/tooling/project-system.md`, `docs/tooling/targets.md`
- Dev workflow / phase branches / build → `docs/tooling/workflow.md` - Dev workflow / phase branches / build → `docs/tooling/workflow.md`
- Linux user setup (toolchain, VS Code, build/test, run a sample) → `docs/linux-getting-started.md`
- Xcode project templates → `docs/tooling/xcode-templates.md` - Xcode project templates → `docs/tooling/xcode-templates.md`
- AUv3 plugin internals (`LyrebirdAudioUnit`, `LyrebirdAUVoicePoolBinding`, `AUInput`, preset codable, parameter slots) → `Sources/Lyrebird/Lyrebird.docc/AUv3.md` - AUv3 plugin internals (`LyrebirdAudioUnit`, `LyrebirdAUVoicePoolBinding`, `AUInput`, preset codable, parameter slots) → `Sources/Lyrebird/Lyrebird.docc/AUv3.md`
**UI** **UI**
- LyrebirdUI / parameter binding → `docs/ui/gui-system.md` - LyrebirdUI / parameter binding → `docs/ui/gui-system.md`
- Live-compile scratchpad (`LyrebirdScratchView`, `LyrebirdLiveCompile`, `LyrebirdLiveCompileUI`) → `LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md`. **Lives in the separate `LiveCompile/` SwiftPM sub-package** (Phase 167) — cross-package dependency forces `libLyrebirdLiveCompile.dylib` to dynamic-link `libLyrebird.dylib` instead of statically embedding it, eliminating the ObjC class double-registration crash that aborted full `swift test` runs in the single-package layout. Build sub-package with `(cd LiveCompile && swift build)` / `(cd LiveCompile && swift test)`. - Live-compile scratchpad (`LyrebirdScratchView`, `LyrebirdLiveCompile`, `LyrebirdLiveCompileUI`) → `LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md`. **Lives in the separate `LiveCompile/` SwiftPM sub-package** (Phase 167) — cross-package dependency forces `libLyrebirdLiveCompile.dylib` to dynamic-link `libLyrebird.dylib` instead of statically embedding it, eliminating the ObjC class double-registration crash that aborted full `swift test` runs in the single-package layout. Build sub-package with `(cd LiveCompile && swift build)` / `(cd LiveCompile && swift test)`.
- Interpreted graph-DSL (`LyrebirdGraphDSL` target — cross-platform, no swiftc) + its code-gen (`Tools/DSLRegistryGen`, separate SwiftPM package so swift-syntax stays out of the main build; run `scripts/generate-dsl-registry.sh`, committed output, `--check` drift guard) → `docs/tooling/graph-dsl-design.md`. Registry (`Sources/LyrebirdGraphDSL/Generated/GeneratedDSLRegistry.swift`) is generated from generator init signatures — regenerate + commit after changing a public generator init. In progress (LC-8); language/parser not yet built.
**Diagnostics** **Diagnostics**
- User-visible messages (`LyrebirdMessage`, `LyrebirdMessageCenter`, `LyrebirdMessageView` / Banner) + node-tree mirror (`NodeTreeMirror`, `NodeTreeSnapshot`, `LyrebirdNodeTreeView`) → `docs/diagnostics-guide.md` - User-visible messages (`LyrebirdMessage`, `LyrebirdMessageCenter`, `LyrebirdMessageView` / Banner) + node-tree mirror (`NodeTreeMirror`, `NodeTreeSnapshot`, `LyrebirdNodeTreeView`) → `docs/diagnostics-guide.md`
- Developer-side debugging (per-instance RT debug tap `SynthesizerBase.debugTap`, `GeneratorBase.debugTag`, LLDB breakpoint recipes for inspecting a live voice / generator) → `Sources/Lyrebird/Lyrebird.docc/Debugging.md`
**Planning** **Planning**
- What to build next → `docs/00-working-order.md` - What to build next → `docs/00-working-order.md`
@@ -88,7 +114,8 @@ One-liners. Detail and rationale lives in linked docs.
**Platform / build** **Platform / build**
- macOS 15+ / iOS 18+ / swift-tools 6.0 — `Synchronization.Atomic` requires macOS 15. - macOS 15+ / iOS 18+ / swift-tools 6.0 — `Synchronization.Atomic` requires macOS 15.
- No AVAudioEngine. Use `kAudioUnitSubType_HALOutput` (full duplex AUHAL) on macOS, RemoteIO on iOS. - No AVAudioEngine. Use `kAudioUnitSubType_HALOutput` (full duplex AUHAL) on macOS, RemoteIO on iOS, blocking `snd_pcm_writei` on a dedicated thread (ALSA) on Linux.
- Never name a concrete driver in code that is meant to build on more than one platform — call `makeDefaultAudioDriver()`. Which drivers exist depends on how Lyrebird itself was built (a Linux build without libasound, or one cross-compiled from macOS, has no `ALSAAudioDriver`), so a consumer-side `#if` is a guess. Code already locked to one platform is exempt and should name its driver directly — e.g. the AppKit-only `ui-demo` scaffold template emits `CoreAudioDriver()`.
- No Xcode Playgrounds. All tests use Swift Testing (`@Test`, `#expect`, `@Suite`). - No Xcode Playgrounds. All tests use Swift Testing (`@Test`, `#expect`, `@Suite`).
**RT thread (render callback)** — `docs/engine/synthesis-engine.md`, `docs/protocols/writing-generators.md` **RT thread (render callback)** — `docs/engine/synthesis-engine.md`, `docs/protocols/writing-generators.md`
@@ -108,9 +135,9 @@ One-liners. Detail and rationale lives in linked docs.
- Open every `_computeSamples` with `_checkCount(count)` — the inherited helper that traps if `count > _result[0].count`. Replaces the long-form `precondition(...)` boilerplate. - Open every `_computeSamples` with `_checkCount(count)` — the inherited helper that traps if `count > _result[0].count`. Replaces the long-form `precondition(...)` boilerplate.
- `floatValue` is provided by the `AudioGenerator` protocol extension (returns `calculatedSamples(...).first?.first ?? 0`). Do not redeclare in `AudioGenerator` conformers unless you need different scalar semantics (e.g. `ConstantGeneratorInput`). `ControlGenerator` conformers must provide their own `floatValue` returning the block target. - `floatValue` is provided by the `AudioGenerator` protocol extension (returns `calculatedSamples(...).first?.first ?? 0`). Do not redeclare in `AudioGenerator` conformers unless you need different scalar semantics (e.g. `ConstantGeneratorInput`). `ControlGenerator` conformers must provide their own `floatValue` returning the block target.
- Buffer factories `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` (in `ResultBuffer.swift`) replace `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals when a generator owns a separately-allocated scratch buffer. - Buffer factories `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` (in `ResultBuffer.swift`) replace `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals when a generator owns a separately-allocated scratch buffer.
- Every `ControlGenerator.Control.init` calls `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. Never call on the RT thread. - Every sub-blocking `ControlGenerator.Control.init` calls `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. Never call on the RT thread. **Exception:** `BlockRateControlGenerator` conformers never sub-block and omit the call (see the bypass bullet below).
- `Control._computeSamples` uses `count` (not `graph.engine.blockSize`) for phase/state advancement — `_computeSamples` may run N times per audio block in sub-block mode. - `Control._computeSamples` uses `count` (not `graph.engine.blockSize`) for phase/state advancement — `_computeSamples` may run N times per audio block in sub-block mode.
- Generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop. Canonical pattern: `Out.Control`. See `docs/protocols/writing-generators.md` §15 for the bypass list and decision rule. - Control generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, analysers) must advance once per audio block, bypassing the sub-block loop. Conform to `BlockRateControlGenerator` (marker protocol in `GeneratorCore/BlockRateControlGenerator.swift`) — its `calculatedSamples` default routes to the block-rate gateway and the conformer skips `_setupSubBlockBuffer()`. This replaced the old per-generator `calculatedSamples { _calculatedSamplesBlockRate(...) }` forwarder. A true sub-blocking Control must NOT conform. See `docs/protocols/writing-generators.md` §15 for the decision rule.
- Multi-row generators (any with `_result.count > 1`) override `var outputChannelCount: Int { get }` to return the fixed channel count set at `init`. `GeneratorBase` defaults to `1`. Missing override silently mono-izes the generator under `+ - * /` operators. Channel count must be derivable from a `let` at init — never runtime-mutable. Detail + cases: `docs/stdlib/multichannel.md`. - Multi-row generators (any with `_result.count > 1`) override `var outputChannelCount: Int { get }` to return the fixed channel count set at `init`. `GeneratorBase` defaults to `1`. Missing override silently mono-izes the generator under `+ - * /` operators. Channel count must be derivable from a `let` at init — never runtime-mutable. Detail + cases: `docs/stdlib/multichannel.md`.
- `mul:` / `add:` parameters are channel-aware: mono input broadcasts; equal-N applies element-wise; mismatched multi-row precondition-traps. Same policy as `BinaryOpGenerator`. Detail: `docs/stdlib/multichannel.md`. - `mul:` / `add:` parameters are channel-aware: mono input broadcasts; equal-N applies element-wise; mismatched multi-row precondition-traps. Same policy as `BinaryOpGenerator`. Detail: `docs/stdlib/multichannel.md`.
@@ -138,7 +165,7 @@ One-liners. Detail and rationale lives in linked docs.
**Never drop new files at `Sources/Lyrebird/` root.** Every new `.swift` file goes into a subfolder grouped by function. Existing top-level subfolders (alphabetical): **Never drop new files at `Sources/Lyrebird/` root.** Every new `.swift` file goes into a subfolder grouped by function. Existing top-level subfolders (alphabetical):
`AUv3/` `AudioDrivers/` `Buffers/` `Buses/` `Capture/` `Diagnostics/` `Distributions/` `Engine/` `Envelopes/` `External/` `GeneratorCore/` `Generators/` `Kinds/` `MIDI/` `Math/` `NodeTree/` `OSC/` `Oversampling/` `Parameters/` `Patterns/` `Process/` `Scheduling/` `Score/` `Spectral/` `Synthesizer/` `TemporalStream/` `Trigger/` `ValueCompute/` `Voices/` `AUv3/` `AudioDrivers/` `Buffers/` `Buses/` `Capture/` `Diagnostics/` `Distributions/` `Engine/` `Envelopes/` `External/` `GeneratorCore/` `Generators/` `Kinds/` `MIDI/` `Math/` `NodeTree/` `OSC/` `Oversampling/` `Parameters/` `Patterns/` `Process/` `Scheduling/` `Score/` `Spectral/` `Synthesizer/` `TemporalStream/` `Trigger/` `Utilities/` `ValueCompute/` `Voices/`
Rule: Rule:
@@ -172,12 +199,31 @@ Throws `EngineAddError`: `.boundToOtherEngine(current:prior:)` (cross-engine), `
`engine.remove(_:)` and `engine.remove(_:at:)` still return `Bool` — they unbind synchronously on successful enqueue. Documented constraint: allow one `processBlock` between `remove` and re-add of the same instance. `engine.remove(_:)` and `engine.remove(_:at:)` still return `Bool` — they unbind synchronously on successful enqueue. Documented constraint: allow one `processBlock` between `remove` and re-add of the same instance.
`engine.stop()` also unbinds every non-persistent synth it was hosting (including ones nested inside drained `Group` subtrees) as part of its node-tree teardown, so a stop-then-re-add of the same instance — to the same engine or a different one — needs no such wait; the RT thread is already halted before `stop()`'s unbind pass runs. See `docs/engine/synthesis-engine.md` § `stop()` node-tree teardown contract.
Call-site pattern: every `engine.add` invocation needs `try`. In non-throwing contexts (closures dispatched to `DispatchQueue.main.async`, non-throwing methods), wrap in `do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") }` — the existing `LyrebirdRoutineContext` / `LyrebirdMessageContext` / `LyrebirdProcessContext` adapters use this pattern. Call-site pattern: every `engine.add` invocation needs `try`. In non-throwing contexts (closures dispatched to `DispatchQueue.main.async`, non-throwing methods), wrap in `do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") }` — the existing `LyrebirdRoutineContext` / `LyrebirdMessageContext` / `LyrebirdProcessContext` adapters use this pattern.
## Swift Code Style Rules ## Swift Code Style Rules
Hard rules. Review agents flag violations. Hard rules. Review agents flag violations.
### No phase numbers in code or docs
Never write phase numbers (`Phase 228`, `Phase 228c`, `phase-224`, `pre-Phase-209c`, `// Phase 216:`, `(Phase 201)`, `— Phase 214`) in source comments, doc-comments (`///`), `.docc` markdown, `@Suite`/`@Test` display strings, or test function / type / file names. Phase numbers are meaningless to external readers — they belong **only** in planning docs (`docs/00-working-order.md`, `docs/01-completed-working-order.md`), commit messages, and `MEMORY.md`/phase history. Describe the **behavior or reason** instead:
```swift
// WRONG
// Phase 216: emit a tempo direction for this measure when a TempoChange targets it.
let cap = ... // Phase 228c
/// > Note: Phase 224 wires this as model state.
@Suite("EngineHost (Phase 197)")
// RIGHT
// Emit a tempo direction for this measure when a TempoChange targets it.
let cap = ...
/// > Note: this is model state.
@Suite("EngineHost")
```
Exception: the DSP term **"phase"** that is NOT a planning reference — oscillator `phase`, `phase accumulator`, `phase offset`, `_phase`, `initPhase`, `phase modulation`, "Phase 0.25 in an 8-sample table" — is a real audio term, never touch it. The rule targets `Phase <number>` planning tags only.
### No force unwraps ### No force unwraps
Never `!` on optionals or `try!`. Hotspots: `UnsafeBufferPointer.baseAddress` in Accelerate calls, `Array.first!`/`last!` on output channels, `try!` in test helpers, `dict[key]!`. Never `!` on optionals or `try!`. Hotspots: `UnsafeBufferPointer.baseAddress` in Accelerate calls, `Array.first!`/`last!` on output channels, `try!` in test helpers, `dict[key]!`.
```swift ```swift
@@ -285,9 +331,12 @@ Tool: `Tools/AnnotateBindings/annotate_bindings.py` drives `sourcekit-lsp` to fi
Module-level helpers exist to eliminate repeated boilerplate; inlining any of them in a new generator is a review violation: Module-level helpers exist to eliminate repeated boilerplate; inlining any of them in a new generator is a review violation:
- `_checkCount(_:)` — `GeneratorBase` method; first line of every `_computeSamples` - `_checkCount(_:)` — `GeneratorBase` method; first line of every `_computeSamples`
- `_calculatedSamplesBlockRate(graph:count:)` — `Generator` extension; canonical body of any `calculatedSamples` override that bypasses the `ControlGenerator` sub-block path (IIR filters, bus writers, buffer-position advancers, trigger detectors, random drawers) - `BlockRateControlGenerator` — `GeneratorCore/BlockRateControlGenerator.swift`; marker protocol a `ControlGenerator` conforms to when its state must advance once per audio block (IIR filters, bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, analysers). Supplies the block-rate `calculatedSamples` gateway for free and lets the conformer skip `_setupSubBlockBuffer()`. The standard way to bypass sub-blocking — superseded the per-generator `_calculatedSamplesBlockRate` forwarder. A true sub-blocker must NOT conform.
- `_calculatedSamplesBlockRate(graph:count:)` — `Generator` extension; the block-rate gateway the `BlockRateControlGenerator` default calls. Call it directly only in the rare case a generator needs the bypass but cannot conform to the marker
- `OscillatorBase` — `Generators/Oscillators/OscillatorBase.swift`; extend instead of declaring `_freqInput` / `_freqIsGenerator` / `_phase` / `_mulAdd` inline. Designated `init(freq:phase:mul:add:)` performs canonical phase normalisation. Used by LF / band-limited oscillators (LFSawtooth, LFSquare, LFTriangle, LFDutyCycle, OscSawtooth, OscSquare, OscTriangle, OscDutyCycle) and `Impulse` (post-super-init writes `_phase = 1.0 - initPhase` so `initPhase == 0` fires at sample 0). Table-lookup oscillators (`OscSin`, `OscTable`) intentionally excluded — they store `_phase` in table-index units to avoid a per-sample multiply in the inner loop. - `OscillatorBase` — `Generators/Oscillators/OscillatorBase.swift`; extend instead of declaring `_freqInput` / `_freqIsGenerator` / `_phase` / `_mulAdd` inline. Designated `init(freq:phase:mul:add:)` performs canonical phase normalisation. Used by LF / band-limited oscillators (LFSawtooth, LFSquare, LFTriangle, LFDutyCycle, OscSawtooth, OscSquare, OscTriangle, OscDutyCycle) and `Impulse` (post-super-init writes `_phase = 1.0 - initPhase` so `initPhase == 0` fires at sample 0). Table-lookup oscillators (`OscSin`, `OscTable`) intentionally excluded — they store `_phase` in table-index units to avoid a per-sample multiply in the inner loop.
- `NoiseBase` — `Generators/Noise/NoiseBase.swift`; extend instead of declaring `rngState: UInt64` + `_mulAdd: MulAddSpec` inline. Designated `init(initialRngState:mul:add:)`. Used by 23 noise generators across 3 tiers (parameterless, extra-state, distribution-parameterised). LF noise variants and Crackle intentionally excluded. - `NoiseBase` — `Generators/Noise/NoiseBase.swift`; extend instead of declaring `rngState: UInt64` + `_mulAdd: MulAddSpec` inline. Designated `init(initialRngState:mul:add:)`. Used by 23 noise generators across 3 tiers (parameterless, extra-state, distribution-parameterised). LF noise variants and Crackle intentionally excluded.
- `UnaryMathBase` — `Generators/Math/UnaryMathBase.swift`; extend instead of declaring `inputSource` + `_mulAdd` inline. Designated `init(_:mul:add:)`. The shared `_Base` for the single-input math operators — each is `public class _Base: UnaryMathBase {}`, with `Audio`/`Control` supplying only the per-operator kernel. Used by 14 operators (Abs, Ceil, Floor, Round, Sign, Sqrt, Log, Exp, Sin, Cos, Tan, Tanh, Reciprocal, DbAmp). Multi-input math (Max, Min, Ring1–4, ExpExp, ExpLin, …) keeps its own `_Base`.
- `SpectralFeatureControlBase` — `Generators/Spectral/SpectralFeatureControlBase.swift`; shared base for the control-rate spectral feature analysers (SpectralCentroid, SpectralSpread, SpectralFlatness, SpectralEntropy, SpectralFlux, SpectralRolloff). Owns the analysis handle, spectral buffer, MulAddSpec, ramp state, sub-block bypass, and the drive-analysis → `computeFeature` → ramp body; each `Control` subclass adds only its own params/state and overrides `computeFeature(graph:count:) -> Double`.
- `runRBJBiquadBlock(...)` — `Generators/Filters/RBJBiquadHelpers.swift`; module-internal helper holding the shared `_computeSamples` body for `(freq, q)` RBJ biquad filters (LP / HP / AP / Notch). Concrete filters pass the coefficient formula as a closure. - `runRBJBiquadBlock(...)` — `Generators/Filters/RBJBiquadHelpers.swift`; module-internal helper holding the shared `_computeSamples` body for `(freq, q)` RBJ biquad filters (LP / HP / AP / Notch). Concrete filters pass the coefficient formula as a closure.
- `runTwoPoleResonatorScalarBlock(input:into:y1:y2:b0:na1:na2:count:)` / `runTwoPoleResonatorInterpolatedBlock(input:into:y1:y2:start:end:count:)` — `Generators/Filters/FilterHelpers.swift`; shared per-sample loop body for two-pole resonator filters (`y[n] = b0·x[n] − na1·y[n−1] − na2·y[n−2]`). Consumed by `RingingFilter` + `ResonatingFilter` — concrete filter passes its coefficient-computation function and one-line helper calls. - `runTwoPoleResonatorScalarBlock(input:into:y1:y2:b0:na1:na2:count:)` / `runTwoPoleResonatorInterpolatedBlock(input:into:y1:y2:start:end:count:)` — `Generators/Filters/FilterHelpers.swift`; shared per-sample loop body for two-pole resonator filters (`y[n] = b0·x[n] − na1·y[n−1] − na2·y[n−2]`). Consumed by `RingingFilter` + `ResonatingFilter` — concrete filter passes its coefficient-computation function and one-line helper calls.
- `sampleOrFallback(_:scalar:at:)` — `Generators/Filters/FilterHelpers.swift`; per-sample coefficient lookup with zero-fallback past block end. Replaces the `xxxSamples.map { i < $0.count ? $0[i] : 0 } ?? scalarX` pattern. Used by `SecondOrderSection` (5 coefficient slots) + `FirstOrderSection` (3 slots). `Lag`/`Decay` family use a different end-clamp + `lagCoeff` wrapping convention; helper doesn't apply there. - `sampleOrFallback(_:scalar:at:)` — `Generators/Filters/FilterHelpers.swift`; per-sample coefficient lookup with zero-fallback past block end. Replaces the `xxxSamples.map { i < $0.count ? $0[i] : 0 } ?? scalarX` pattern. Used by `SecondOrderSection` (5 coefficient slots) + `FirstOrderSection` (3 slots). `Lag`/`Decay` family use a different end-clamp + `lagCoeff` wrapping convention; helper doesn't apply there.
@@ -295,7 +344,7 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th
- `leakyIntegratorStep(state:x:b1:)` — `Generators/Filters/FilterHelpers.swift`; `y = x + b1·state`, mutates state, returns y. SC `Decay`/`Decay2` convention (input not attenuated by `1 − b1`). Used by `Decay.Audio` + `Decay2.Audio` (cascade two for attack/decay difference). - `leakyIntegratorStep(state:x:b1:)` — `Generators/Filters/FilterHelpers.swift`; `y = x + b1·state`, mutates state, returns y. SC `Decay`/`Decay2` convention (input not attenuated by `1 − b1`). Used by `Decay.Audio` + `Decay2.Audio` (cascade two for attack/decay difference).
- `attackReleaseSmoother(state:target:attackCoeff:attackComp:releaseCoeff:releaseComp:direction:)` — `Generators/Dynamics/DynamicsHelpers.swift`; asymmetric attack/release smoother step with direction selector (`.rising` for envelope followers; `.falling` for compressor/expander gain-target smoothing). Used by `AmplitudeFollower.Audio` (`.rising`) + `Compressor.Audio` / `Expander.Audio` (`.falling`). - `attackReleaseSmoother(state:target:attackCoeff:attackComp:releaseCoeff:releaseComp:direction:)` — `Generators/Dynamics/DynamicsHelpers.swift`; asymmetric attack/release smoother step with direction selector (`.rising` for envelope followers; `.falling` for compressor/expander gain-target smoothing). Used by `AmplitudeFollower.Audio` (`.rising`) + `Compressor.Audio` / `Expander.Audio` (`.falling`).
- `sampleOrZero(_ p: UnsafePointer<Double>, _ i: Int, _ n: Int) -> Double` — `GeneratorCore/HotLoopHelpers.swift`; `i < n ? p[i] : 0`. Replaces the per-sample `(i < n) ? srcP[i] : 0` boilerplate inside hot loops that read an input row via raw pointer. Module-internal helper used across Filters (Lag / Lag2 / LagUpDown / Lag2UpDown / LeakDC / Decay / Decay2 / SecondOrderSection / FirstOrderSection / RBJBiquad / CombFilter / AllpassFilter) and Delays (DelayLine / DelayLineFeedback). `@_spi(LyrebirdExtensions) public` so out-of-tree generators can adopt the same helper. - `sampleOrZero(_ p: UnsafePointer<Double>, _ i: Int, _ n: Int) -> Double` — `GeneratorCore/HotLoopHelpers.swift`; `i < n ? p[i] : 0`. Replaces the per-sample `(i < n) ? srcP[i] : 0` boilerplate inside hot loops that read an input row via raw pointer. Module-internal helper used across Filters (Lag / Lag2 / LagUpDown / Lag2UpDown / LeakDC / Decay / Decay2 / SecondOrderSection / FirstOrderSection / RBJBiquad / CombFilter / AllpassFilter) and Delays (DelayLine / DelayLineFeedback). `@_spi(LyrebirdExtensions) public` so out-of-tree generators can adopt the same helper.
- `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate input resolution. Replaces the 8-line `if _xxxIsGenerator { xxxSamples = ...; scalarXxx = 0 } else { xxxSamples = nil; scalarXxx = ... }` boilerplate at the top of any `_computeSamples` that pulls multiple `ValidGeneratorInput` parameters. Used by `Flute` (6 params), `Clarinet` (4 params), `PanXYDistance` (4 params), `PanAzDistance` (4 params). Tuple destructure at the call site is the CLAUDE.md-documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`. - `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate input resolution. Replaces the 8-line `if _xxxIsGenerator { xxxSamples = ...; scalarXxx = 0 } else { xxxSamples = nil; scalarXxx = ... }` boilerplate at the top of any `_computeSamples` that pulls multiple `ValidGeneratorInput` parameters. Used across many multi-input generators (`Flute`, `Clarinet`, `KarplusStrong`/`GatedKarplusStrong`, `BowedString`, `PlayBuffer`, `SpatialDistance`, `MuTronIII`, `Hilbert`, the spatial panners, and more). Tuple destructure at the call site is the CLAUDE.md-documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`.
- `applySpatialDistanceFiltering(...)` — `Generators/Panning/SpatialDistanceHelpers.swift`; module-internal shared per-sample pipeline for `PanXYDistance` (Cartesian) and `PanAzDistance` (polar). Both callers pre-compute `(panX, panY)` and the Chebyshev distance metric `posD` from their respective coordinate frames; the rest of the pipeline (amplitude attenuation, cutoff-coefficient caching, Doppler read-rate, delay-line write/read/wrap/clamp, one-pole lowpass, equal-power 4-corner pan) is identical and lives here. Mutates delay-line + one-pole state in place via `inout`. `@inline(__always) internal`. - `applySpatialDistanceFiltering(...)` — `Generators/Panning/SpatialDistanceHelpers.swift`; module-internal shared per-sample pipeline for `PanXYDistance` (Cartesian) and `PanAzDistance` (polar). Both callers pre-compute `(panX, panY)` and the Chebyshev distance metric `posD` from their respective coordinate frames; the rest of the pipeline (amplitude attenuation, cutoff-coefficient caching, Doppler read-rate, delay-line write/read/wrap/clamp, one-pole lowpass, equal-power 4-corner pan) is identical and lives here. Mutates delay-line + one-pole state in place via `inout`. `@inline(__always) internal`.
- `plateReverbInputDiffusion(...)` / `plateReverbTankHalf(...)` — `Generators/Reverb/PlateReverbHelpers.swift`; PlateReverb-specific per-sample sub-blocks. `plateReverbInputDiffusion` runs the 4-stage cascaded Schroeder allpass network on a single sample. `plateReverbTankHalf` runs one half of the figure-of-eight tank (modulated allpass → delay 1 → damping LP → decay scale → allpass 2 → delay 2 write). Consumed twice per sample by `PlateReverb._computeSamples` (left and right halves). All state mutated `inout`. `@inline(__always) internal`. - `plateReverbInputDiffusion(...)` / `plateReverbTankHalf(...)` — `Generators/Reverb/PlateReverbHelpers.swift`; PlateReverb-specific per-sample sub-blocks. `plateReverbInputDiffusion` runs the 4-stage cascaded Schroeder allpass network on a single sample. `plateReverbTankHalf` runs one half of the figure-of-eight tank (modulated allpass → delay 1 → damping LP → decay scale → allpass 2 → delay 2 write). Consumed twice per sample by `PlateReverb._computeSamples` (left and right halves). All state mutated `inout`. `@inline(__always) internal`.
- `gverbReadEarlyTaps(...)` / `gverbFDNDamperCascade(...)` — `Generators/Reverb/GVerbHelpers.swift`; GVerb-specific per-sample sub-blocks. `gverbReadEarlyTaps` reads four pre-FDN early-reflection taps with branchless wrap + per-tap gains and returns a 4-tuple. `gverbFDNDamperCascade` applies the FDN one-pole LP damper cascade `y = x*(1-damp) + prev*damp` to four raw FDN reads, mutates `fdnDampState[0..3]` with denormal flush, returns 4-tuple. Both `@inline(__always) internal`. - `gverbReadEarlyTaps(...)` / `gverbFDNDamperCascade(...)` — `Generators/Reverb/GVerbHelpers.swift`; GVerb-specific per-sample sub-blocks. `gverbReadEarlyTaps` reads four pre-FDN early-reflection taps with branchless wrap + per-tap gains and returns a 4-tuple. `gverbFDNDamperCascade` applies the FDN one-pole LP damper cascade `y = x*(1-damp) + prev*damp` to four raw FDN reads, mutates `fdnDampState[0..3]` with denormal flush, returns 4-tuple. Both `@inline(__always) internal`.
@@ -303,9 +352,14 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th
- `_mulAdd.applyIfNeeded(to:graph:count:)` - `_mulAdd.applyIfNeeded(to:graph:count:)`
- `fillRampedResult(into:from:to:mulAdd:graph:count:)` - `fillRampedResult(into:from:to:mulAdd:graph:count:)`
- `fillScalarRampedResult(into:previousOutputValue:target:count:)` — `MulAdd.swift`; canonical body of every `Math.Control` `_computeSamples` ramp (28 generators). Distinct from `fillRampedResult` because the caller has pre-folded `mul`/`add` into the scalar `target` — the helper writes the ramp without re-applying `MulAddSpec.apply`. - `fillScalarRampedResult(into:previousOutputValue:target:count:)` — `MulAdd.swift`; canonical body of every `Math.Control` `_computeSamples` ramp (28 generators). Distinct from `fillRampedResult` because the caller has pre-folded `mul`/`add` into the scalar `target` — the helper writes the ramp without re-applying `MulAddSpec.apply`.
- `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` - `fillHeldResult(into:value:previousOutputValue:mulAdd:graph:count:)` — `MulAdd.swift`; held-constant counterpart of `fillScalarRampedResult` — fills a block with one value, applies mul/add, sets `previousOutputValue` to the last sample. For block-rate `Control` paths whose output holds one value (one-pole smoothers `Lag`/`Decay`/`LeakDC`/`Slew`/`Formlet`, block-constant analysis `ZeroCrossing`/`Slope`/`RunningMin`/`Max`, trigger/counter latches `Trig`/`Schmidt`/`PulseCount`/`Stepper`; 20 sites). No-op at `count == 0`. NOT for per-sample-varying output.
- `MulAddSpec.applyScalar(_:graph:)` — `MulAdd.swift`; folds scalar `mul`/`add` into one block-constant `target` (returns it unchanged on identity). The scalar counterpart of `applyIfNeeded`; used by the 36 scalar-fold paths (Math.Control plus Routing/Waveshaping crossfades and shapers) before `fillScalarRampedResult`.
- `firstGeneratorSampleOrFloat(_:isGenerator:graph:count:)` / `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate read of a generator-or-scalar input. `first…` reads the block's first sample (`0` if empty) — oscillator/LF/noise `Control` paths; `last…` reads the final sample (ramp endpoint) — dynamics + delay-time paths. Both fall back to `floatValue` for non-generators
- `xorshift64Next(_:)` - `xorshift64Next(_:)`
- `lyrebirdSeedXorshift64(from:mixConstant:)` / `lyrebirdSeedXorshift64(from:)` — `Math/LyrebirdConstants.swift`; init-time xorshift64 seed helper. Two-arg form decorrelates Audio/Control pairs via `mixConstant`; one-arg form is the convenience for stand-alone single-state owners (e.g. `DemandTemporalTendency` / `DemandTemporalBrownian`) - `lyrebirdSeedXorshift64(from:mixConstant:)` / `lyrebirdSeedXorshift64(from:)` — `Math/LyrebirdConstants.swift`; init-time xorshift64 seed helper. Two-arg form decorrelates Audio/Control pairs via `mixConstant`; one-arg form is the convenience for stand-alone single-state owners (e.g. `DemandTemporalTendency` / `DemandTemporalBrownian`)
- `catmullRomCubic(_:_:_:_:t:)` — `Math/CubicInterpolation.swift`; the single shared 4-point Catmull-Rom cubic kernel. Pass `(pM1, p0, p1, p2, t:)` — the sample before the segment, the two bracketing it, the one after, and `t ∈ [0, 1]`. Use instead of inlining the `t²`/`t³` expanded form. `@inline(__always) @_spi(LyrebirdExtensions) public`. Consumers: oscillator table reads (`OscSin` / `oscillatorTableReadCubic`), `PlayBuffer`, `chaoticInterpolate`, and the fractional-delay lines (`DelayLine` / `DelayLineFeedback` / `CombFilter` / `AllpassFilter`).
- `RTScratchBuffer<Element>` — `Buffers/RTScratchBuffer.swift`; a `~Copyable` single-owner heap scratch buffer that replaces hand-paired `allocate`/`deinitialize`/`deallocate` in scratch-owning generators (the Spectral/FFT family). `init(count:)` zero-fills (`Element: Numeric`); `init(count:repeating:)` fills any value. `@inline(__always)` `baseAddress`/`count`/`subscript` (`nonmutating set`) so the hot loop matches the raw pointer. Store as a `let` assigned in `init` — never a per-call local. Not for `[UnsafeMutablePointer]` per-channel arrays (a `~Copyable` cannot be `Array`-stored) or capacity-1 scalar boxes used via `.pointee`. `@_spi(LyrebirdExtensions) public`.
Full table, signatures, examples, and the per-generator exceptions (notably `MathGenerators.Control` and the non-standard ControlGenerator ramp paths) live in `docs/protocols/writing-generators.md` §13. That document is the single source of truth — when adding or removing a helper, update §13 and reference it from here. Full table, signatures, examples, and the per-generator exceptions (notably `MathGenerators.Control` and the non-standard ControlGenerator ramp paths) live in `docs/protocols/writing-generators.md` §13. That document is the single source of truth — when adding or removing a helper, update §13 and reference it from here.
+2 -2
View File
@@ -50,7 +50,7 @@ If a unit is useful at both rates, implement both via the **enum namespace patte
- **First line of every `_computeSamples` is `_checkCount(count)`.** It traps if `count` exceeds the pre-allocated buffer. No grow path exists. - **First line of every `_computeSamples` is `_checkCount(count)`.** It traps if `count` exceeds the pre-allocated buffer. No grow path exists.
- **Pre-allocate everything in `init`.** Bus memory, scratch buffers, vDSP setup objects. `init` runs off the RT thread; `_computeSamples` must only read/write existing storage. Use `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` instead of `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals. - **Pre-allocate everything in `init`.** Bus memory, scratch buffers, vDSP setup objects. `init` runs off the RT thread; `_computeSamples` must only read/write existing storage. Use `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` instead of `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals.
- **Use `count`, never `engine.blockSize`,** for phase/state advancement — a `Control._computeSamples` may run several times per audio block in sub-block mode. - **Use `count`, never `engine.blockSize`,** for phase/state advancement — a `Control._computeSamples` may run several times per audio block in sub-block mode.
- **Generators with per-audio-block state** (bus writers, position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop via `_calculatedSamplesBlockRate(graph:count:)`. See §15 for the bypass list. - **Control generators with per-audio-block state** (bus writers, position advancers, gain smoothers, trigger detectors, random drawers, analysers) conform the `Control` to `BlockRateControlGenerator` to bypass the sub-block loop (no `calculatedSamples` override, no `_setupSubBlockBuffer()`). See writing-generators.md §15.
- **Multi-row generators** (`_result.count > 1`) call `super.init(channels: N)` and override `outputChannelCount`. Missing the override silently mono-izes the generator under `+ - * /`. Channel count must be a `let` fixed at init. - **Multi-row generators** (`_result.count > 1`) call `super.init(channels: N)` and override `outputChannelCount`. Missing the override silently mono-izes the generator under `+ - * /`. Channel count must be a `let` fixed at init.
- **Extend the right base** where one exists: `OscillatorBase`, `NoiseBase`. Don't re-declare `_phase` / `_mulAdd` / `rngState` inline. - **Extend the right base** where one exists: `OscillatorBase`, `NoiseBase`. Don't re-declare `_phase` / `_mulAdd` / `rngState` inline.
- **Denormal hygiene** — flush denormals to zero in feedback paths (filters, delays, reverbs). - **Denormal hygiene** — flush denormals to zero in feedback paths (filters, delays, reverbs).
@@ -127,7 +127,7 @@ let package = Package(
.library(name: "LyrebirdMyExtension", targets: ["LyrebirdMyExtension"]), .library(name: "LyrebirdMyExtension", targets: ["LyrebirdMyExtension"]),
], ],
dependencies: [ dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"), .package(url: "https://git.lyrebirdsynth.net/josh/Lyrebird", from: "1.0.0"),
], ],
targets: [ targets: [
.target( .target(
@@ -17,8 +17,8 @@ final class BufferDemos: DemoProtocol {
func runDemo() { func runDemo() {
// BufferDemos.swift lives at .../Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift // BufferDemos.swift lives at .../Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift
// — 4 components up to reach .../Demos/ where Perc.aiff lives. // — 4 components up to reach .../Demos/ where Mozart.aiff lives.
let percURL = URL(fileURLWithPath: #filePath) let percURL: URL = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent() // .../Demos/ .deletingLastPathComponent() // .../Demos/
.deletingLastPathComponent() // .../LyrebirdDemo/ .deletingLastPathComponent() // .../LyrebirdDemo/
.deletingLastPathComponent() // .../LyrebirdDemo (package)/ .deletingLastPathComponent() // .../LyrebirdDemo (package)/
@@ -35,13 +35,58 @@ final class BufferDemos: DemoProtocol {
exit(1) exit(1)
} }
let sampleRate = engine.sampleRate let sampleRate: Double = engine.sampleRate
let pitchSteps: [(Double, String)] = [
(0.5, "0.5 — octave down"),
(0.75, "0.75 — minor third down"),
(1.0, "1.0 — original pitch"),
(1.5, "1.5 — perfect fifth up"),
(2.0, "2.0 — octave up"),
]
let spectralRatios: [(Double, String)] = [
(0.5, "0.5 — octave down (phase vocoder)"),
(1.0, "1.0 — no shift (phase vocoder passthrough)"),
(1.5, "1.5 — perfect fifth up (phase vocoder)"),
(2.0, "2.0 — octave up (phase vocoder)"),
]
let diffuseSteps: [(Double, String)] = [
(0.0, "0.0 — bypass (mono passthrough on both channels)"),
(0.5, "0.5 — half decorrelation"),
(1.0, "1.0 — full per-channel phase randomisation"),
]
let stretchSteps: [(Double, String)] = [
(3.0, "3.0 — 3× stretch (one-third speed, pitch preserved)"),
(1.5, "1.5 — 1.5× stretch (three-quarter speed, pitch preserved)"),
(1.0, "1.0 — native speed (no stretch)"),
(0.5, "0.5 — 2× compression (double speed, pitch preserved)"),
(0.33, "0.33 — 3× compression (triple speed, pitch preserved)"),
]
// `runDemo()` is @MainActor (see DemoProtocol), so the @MainActor synths are constructed
// directly — no `MainActor.assumeIsolated` wrapping. Build them here, then hand the
// resulting instances / live-param node to the @Sendable task body.
let demo1: PercPlayBuffer = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate)
let demo2: PercBufferRead = PercBufferRead(buffer: percBuffer)
let demo3: PercPitchShift = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
let pitchRatioNode: ParameterNode = demo3.$pitchRatio
let demo4Array: [PercSpectralPitchShift] = spectralRatios.map { ratio, _ in
PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate)
}
let demo5Array: [PercSpectralStereoDiffuse] = diffuseSteps.map { amount, _ in
PercSpectralStereoDiffuse(buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
}
let demo6Array: [PercTimeStretch] = stretchSteps.map { factor, _ in
PercTimeStretch(buffer: percBuffer, stretchFactor: factor)
}
LyrebirdTask.run(engine: engine) { ctx in LyrebirdTask.run(engine: engine) { ctx in
// Demo 1 — PlayBuffer (looping at native rate) // Demo 1 — PlayBuffer (looping at native rate)
print("\n── Demo 1: PlayBuffer (looping) ──") print("\n── Demo 1: PlayBuffer (looping) ──")
let demo1 = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate)
ctx.add(demo1) ctx.add(demo1)
try ctx.wait(seconds: 6) try ctx.wait(seconds: 6)
ctx.remove(demo1) ctx.remove(demo1)
@@ -49,7 +94,6 @@ final class BufferDemos: DemoProtocol {
// Demo 2 — BufferRead (sine-wave position scan) // Demo 2 — BufferRead (sine-wave position scan)
print("\n── Demo 2: BufferRead (sine-wave position scan) ──") print("\n── Demo 2: BufferRead (sine-wave position scan) ──")
let demo2 = PercBufferRead(buffer: percBuffer)
ctx.add(demo2) ctx.add(demo2)
try ctx.wait(seconds: 6) try ctx.wait(seconds: 6)
ctx.remove(demo2) ctx.remove(demo2)
@@ -57,19 +101,10 @@ final class BufferDemos: DemoProtocol {
// Demo 3 — PlayBuffer → PitchShift (cycling through pitch ratios) // Demo 3 — PlayBuffer → PitchShift (cycling through pitch ratios)
print("\n── Demo 3: PlayBuffer → PitchShift ──") print("\n── Demo 3: PlayBuffer → PitchShift ──")
let demo3 = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
ctx.add(demo3) ctx.add(demo3)
let pitchSteps: [(Double, String)] = [
(0.5, "0.5 — octave down"),
(0.75, "0.75 — minor third down"),
(1.0, "1.0 — original pitch"),
(1.5, "1.5 — perfect fifth up"),
(2.0, "2.0 — octave up"),
]
for (ratio, label) in pitchSteps { for (ratio, label) in pitchSteps {
print(" pitchRatio \(label)") print(" pitchRatio \(label)")
demo3.pitchRatio = ratio ctx.set(pitchRatioNode, to: ratio) // live-param write from the task body
try ctx.wait(seconds: 3) try ctx.wait(seconds: 3)
} }
ctx.remove(demo3) ctx.remove(demo3)
@@ -77,16 +112,9 @@ final class BufferDemos: DemoProtocol {
// Demo 4 — PlayBuffer → SpectralChain.Audio (with SpectralPitchShift) // Demo 4 — PlayBuffer → SpectralChain.Audio (with SpectralPitchShift)
print("\n── Demo 4: PlayBuffer → SpectralChain.Audio (SpectralPitchShift) ──") print("\n── Demo 4: PlayBuffer → SpectralChain.Audio (SpectralPitchShift) ──")
for (index, (_, label)) in spectralRatios.enumerated() {
let spectralRatios: [(Double, String)] = [
(0.5, "0.5 — octave down (phase vocoder)"),
(1.0, "1.0 — no shift (phase vocoder passthrough)"),
(1.5, "1.5 — perfect fifth up (phase vocoder)"),
(2.0, "2.0 — octave up (phase vocoder)"),
]
for (ratio, label) in spectralRatios {
print(" pitchRatio \(label)") print(" pitchRatio \(label)")
let demo4 = PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate) let demo4: PercSpectralPitchShift = demo4Array[index]
ctx.add(demo4) ctx.add(demo4)
try ctx.wait(seconds: 5) try ctx.wait(seconds: 5)
ctx.remove(demo4) ctx.remove(demo4)
@@ -95,16 +123,9 @@ final class BufferDemos: DemoProtocol {
// Demo 5 — SpectralChain.Audio fan-out (mono → 2-channel decorrelated stereo) // Demo 5 — SpectralChain.Audio fan-out (mono → 2-channel decorrelated stereo)
print("\n── Demo 5: SpectralChain.Audio fan-out (SpectralStereoDiffuse) ──") print("\n── Demo 5: SpectralChain.Audio fan-out (SpectralStereoDiffuse) ──")
for (index, (_, label)) in diffuseSteps.enumerated() {
let diffuseSteps: [(Double, String)] = [
(0.0, "0.0 — bypass (mono passthrough on both channels)"),
(0.5, "0.5 — half decorrelation"),
(1.0, "1.0 — full per-channel phase randomisation"),
]
for (amount, label) in diffuseSteps {
print(" amount \(label)") print(" amount \(label)")
let demo5 = PercSpectralStereoDiffuse( let demo5: PercSpectralStereoDiffuse = demo5Array[index]
buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
ctx.add(demo5) ctx.add(demo5)
try ctx.wait(seconds: 5) try ctx.wait(seconds: 5)
ctx.remove(demo5) ctx.remove(demo5)
@@ -113,17 +134,9 @@ final class BufferDemos: DemoProtocol {
// Demo 6 — TimeStretch (granular, pitch-preserved time stretching + compression) // Demo 6 — TimeStretch (granular, pitch-preserved time stretching + compression)
print("\n── Demo 6: TimeStretch (granular time-stretch / compression) ──") print("\n── Demo 6: TimeStretch (granular time-stretch / compression) ──")
for (index, (_, label)) in stretchSteps.enumerated() {
let stretchSteps: [(Double, String)] = [
(3.0, "3.0 — 3× stretch (one-third speed, pitch preserved)"),
(1.5, "1.5 — 1.5× stretch (three-quarter speed, pitch preserved)"),
(1.0, "1.0 — native speed (no stretch)"),
(0.5, "0.5 — 2× compression (double speed, pitch preserved)"),
(0.33, "0.33 — 3× compression (triple speed, pitch preserved)"),
]
for (factor, label) in stretchSteps {
print(" stretchFactor \(label)") print(" stretchFactor \(label)")
let demo6 = PercTimeStretch(buffer: percBuffer, stretchFactor: factor) let demo6: PercTimeStretch = demo6Array[index]
ctx.add(demo6) ctx.add(demo6)
try ctx.wait(seconds: 6) try ctx.wait(seconds: 6)
ctx.remove(demo6) ctx.remove(demo6)
@@ -7,5 +7,10 @@
import LyrebirdSynth import LyrebirdSynth
protocol DemoProtocol { protocol DemoProtocol {
func runDemo() /// Main-actor-isolated: demos construct `@MainActor` `SynthesizerBase` synths and are launched
/// from `main.swift`'s top-level code (which runs on the main actor). Isolating the requirement
/// lets conformances build synths and read their `$liveParam` nodes directly — no
/// `MainActor.assumeIsolated { … }` wrapping — before handing Sendable references to a
/// background `LyrebirdTask`/`LyrebirdRoutine` body.
@MainActor func runDemo()
} }
@@ -4,14 +4,6 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound // Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
//
// BufferDemos 2.swift
// LyrebirdDemo
//
// Created by Joshua Parmenter on 5/6/26.
//
import Foundation import Foundation
import LyrebirdSynth import LyrebirdSynth
@@ -25,18 +17,31 @@ final class ReverbDemo: DemoProtocol {
func runDemo() { func runDemo() {
let sampleRate = engine.sampleRate let sampleRate: Double = engine.sampleRate
// sets up its own thread / timing, etc
LyrebirdTask.run(engine: engine) { [sampleRate] ctx in // `runDemo()` is @MainActor (see DemoProtocol), so the @MainActor synth is constructed and
// its live-param node read directly
let reverbDemo: GVerbTest = GVerbTest(sampleRate: sampleRate)
// `$reverbTime` is a Sendable `ParameterNode` — capture it here, then write it from inside
// the @Sendable task body (GVerb picks up each change on the next block). The @MainActor
// `reverbDemo.reverbTime` property itself is NOT reachable from the task body under Swift 6;
// the node is. either grab it outside the task (uncomment below) ...
// let reverbTimeParam: ParameterNode = reverbDemo.$reverbTime
LyrebirdTask.run(engine: engine) { ctx in
ctx.tempo = 60.0 ctx.tempo = 60.0
let reverbDemo = GVerbTest(
sampleRate: sampleRate
)
ctx.add(reverbDemo) ctx.add(reverbDemo)
try ctx.wait(beats: 6) // could also use seconds // ... or use ctx.onMain inside the task
let param: ParameterNode = ctx.onMain {
reverbDemo.$reverbTime
}
try ctx.wait(beats: 2) // hold the starting reverbTime (3.0)
ctx.set(param, to: 8.0) // step: jump to a long tail
try ctx.wait(beats: 2)
try ctx.ramp(param, to: 0.5, beats: 2) // glide: smooth swoosh down to a short tail
ctx.remove(reverbDemo) ctx.remove(reverbDemo)
print("\nAll buffer demos complete.") print("\nAll reverb demos complete.")
} }
} }
} }
@@ -14,6 +14,10 @@
import LyrebirdSynth import LyrebirdSynth
final class GVerbTest: SynthesizerBase { final class GVerbTest: SynthesizerBase {
// A live parameter: `$reverbTime` is a `ParameterNode` (Sendable) that GVerb re-reads every
// block, so writing `reverbTime`/`$reverbTime.value` retunes the running reverb. Change it from
// the main thread or a `LyrebirdTask`/`LyrebirdRoutine` body — see `ReverbDemo`.
@LiveParam var reverbTime: Double = 3.0
private let sampleRate: Double private let sampleRate: Double
init(sampleRate: Double) { init(sampleRate: Double) {
@@ -24,7 +28,7 @@ final class GVerbTest: SynthesizerBase {
let impulse = Impulse.Audio(freq: 0.5) let impulse = Impulse.Audio(freq: 0.5)
let reverb = GVerb.Audio(source: impulse, let reverb = GVerb.Audio(source: impulse,
roomSize: 70.0, roomSize: 70.0,
reverbTime: 3.0, reverbTime: $reverbTime, // live ParameterNode, not the baked scalar
earlyLevel: 0.4, earlyLevel: 0.4,
tailLevel: 0.9, tailLevel: 0.9,
dryLevel: 0.1, dryLevel: 0.1,
+7 -4
View File
@@ -7,12 +7,14 @@
import Foundation import Foundation
import LyrebirdSynth import LyrebirdSynth
// `makeDefaultAudioDriver()` selects the platform backend — Core Audio on Apple,
// ALSA on Linux (needs libasound) — so the demo builds and runs on both.
let engine = SynthesisEngine( let engine = SynthesisEngine(
blockSize: 512, blockSize: 512,
sampleRate: 48000, sampleRate: 44100,
numOutputChannels: 2, numOutputChannels: 2,
numInputChannels: 2, numInputChannels: 2,
driver: CoreAudioDriver() driver: makeDefaultAudioDriver()
) )
do { do {
@@ -22,6 +24,7 @@ do {
exit(1) exit(1)
} }
BufferDemos(engine: engine).runDemo() // BufferDemos(engine: engine).runDemo()
//ReverbDemo(engine: engine).runDemo() ReverbDemo(engine: engine).runDemo()
engine.stop() engine.stop()
+1 -1
View File
@@ -17,7 +17,7 @@ let package = Package(
.executableTarget( .executableTarget(
name: "LyrebirdDemo", name: "LyrebirdDemo",
dependencies: [ dependencies: [
.product(name: "Lyrebird", package: "LyrebirdII"), .product(name: "Lyrebird", package: "Lyrebird"),
], ],
path: "LyrebirdDemo" path: "LyrebirdDemo"
), ),
+24
View File
@@ -0,0 +1,24 @@
{
"originHash" : "c2996d6577ec0139a89be2f2d57d304047b7d5bf7f7eba2577fde9dc2fdc0b91",
"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
}
+48
View File
@@ -0,0 +1,48 @@
// Package.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// swift-tools-version: 6.0
import PackageDescription
// A single cross-platform GUI demo: one shared library of synths + views, and a
// thin executable entry point that bootstraps the native toolkit per platform —
// AppKit/SwiftUI on macOS, GTK4/SwiftOpenUI on Linux. The view bodies are written
// to the subset of the View DSL that both backends share, so the UI is one source.
//
// macOS: swift run LyrebirdGUIDemo (or open the thin Xcode project)
// Linux: swift run LyrebirdGUIDemo (needs libgtk-4-dev + libasound2-dev)
//
// Select the synth with LYREBIRD_DEMO=vector (default) or LYREBIRD_DEMO=sine.
let package = Package(
name: "LyrebirdGUIDemo",
platforms: [.macOS(.v15)],
products: [
.library(name: "LyrebirdGUIDemoKit", targets: ["LyrebirdGUIDemoKit"]),
.executable(name: "LyrebirdGUIDemo", targets: ["LyrebirdGUIDemo"]),
],
dependencies: [
.package(path: "../.."),
],
targets: [
.target(
name: "LyrebirdGUIDemoKit",
dependencies: [
.product(name: "Lyrebird", package: "Lyrebird"),
.product(name: "LyrebirdUI", package: "Lyrebird"),
],
path: "Sources/LyrebirdGUIDemoKit"
),
.executableTarget(
name: "LyrebirdGUIDemo",
dependencies: [
"LyrebirdGUIDemoKit",
.product(name: "Lyrebird", package: "Lyrebird"),
.product(name: "LyrebirdUI", package: "Lyrebird"),
],
path: "Sources/LyrebirdGUIDemo"
),
]
)
+58
View File
@@ -0,0 +1,58 @@
<!--
README.md
Lyrebird
Copyright (c) 2026 Joshua Parmenter / realizedsound
SPDX-License-Identifier: MIT
-->
# LyrebirdGUIDemo — one GUI demo, two platforms
A live-controllable synth GUI that builds and runs from a single source tree on
**macOS** (AppKit + SwiftUI) and **Linux** (GTK4 + SwiftOpenUI). It is the
cross-platform counterpart to the richer, macOS-only `LyrebirdMacOSDemo` Xcode
project.
The split follows the "mostly in a package, thin entry points" shape:
| Piece | Where | Platform |
|---|---|---|
| Synths + views | `Sources/LyrebirdGUIDemoKit/` | shared — one source |
| App bootstrap | `Sources/LyrebirdGUIDemo/main.swift` | one `#if` (AppKit vs GTK4) |
The view bodies are written to the subset of the View DSL that SwiftUI and
SwiftOpenUI share, so there is **one** body per view — not a macOS copy and a
Linux copy. Both back ends bind the same core `@UIParam` / `UIParamNode` model,
so the controls, the oscilloscope, and the CPU meters are identical.
## Run it
```bash
swift run LyrebirdGUIDemo # vector oscillator (default)
LYREBIRD_DEMO=sine swift run LyrebirdGUIDemo # stereo sine tone
```
- **macOS** — no extra setup; a native window opens with live audio via Core Audio.
- **Linux** — needs `libgtk-4-dev` (GUI) and `libasound2-dev` + a sound device
(audio). Without a sound backend the window still opens and the controls work;
there is just no sound (`isLiveAudioAvailable` reports it, and the console says so).
## Open in an IDE
- **Xcode (macOS)** — open the folder (or `Package.swift`); Xcode treats it as a
SwiftPM package. Pick the `LyrebirdGUIDemo` scheme and Run. No `.xcodeproj` to
maintain — the package *is* the project.
- **VS Code (Linux)** — open the folder with the Swift extension
(`swiftlang.swift-vscode`); it picks up `Package.swift`. Run `LyrebirdGUIDemo`
from the test/run explorer or a terminal.
## What each demo shows
- **vector** — `VectorOscillatorUI`: an XY pad crossfades four corner wavetables
(sine / saw-ish / triangle / Hanning); frequency and amplitude knobs; a live
oscilloscope and CPU-load strip.
- **sine** — `SineToneUI`: a frequency slider, amplitude and pan knobs, a level
readout, the scope and CPU strip, and a static envelope plot.
Add a synth by dropping a `SynthesizerBase` subclass and a node-based view into
`LyrebirdGUIDemoKit`, then extend `DemoSelection` and the `demoContent()` switch
in `main.swift`.
@@ -0,0 +1,181 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Thin cross-platform entry point. The shared synths + views live in
// `LyrebirdGUIDemoKit`; this file only bootstraps the native toolkit and opens a
// window hosting the selected demo view:
//
// • macOS — AppKit `NSApplication` + `LyrebirdWindow` (SwiftUI content).
// • Linux — a GTK4 `App`/`WindowGroup` scene run by `GTK4Backend`.
//
// Run either with `swift run LyrebirdGUIDemo`. Pick the synth with
// `LYREBIRD_DEMO=vector` (default) or `LYREBIRD_DEMO=sine`.
//
// `@ViewBuilder` and the window hosts come from SwiftUI on macOS and from
// SwiftOpenUI (re-exported through `LyrebirdUI`) on Linux — hence the single
// `#if canImport(SwiftUI)` import guard.
#if canImport(SwiftUI)
import SwiftUI
#endif
import Foundation
import LyrebirdSynth
import LyrebirdUI
import LyrebirdGUIDemoKit
// MARK: - Shared setup (runs on both platforms)
let selection: DemoSelection = DemoSelection.fromEnvironment()
private let demoBlockSize: Int = 512
private let demoSampleRate: Double = 44_100.0
private let demoScopeBufferSize: Int = 2048
// Oscilloscope tap on the stereo output buses. Must be set before `start()`.
let demoScope: ScopeCapture = ScopeCapture(buses: [0, 1], bufferSize: demoScopeBufferSize)
// Core Audio on Apple, ALSA on a Linux build with libasound, else a silent
// OfflineDriver. The GUI runs either way; `isLiveAudioAvailable` reports which.
let demoDriver: any AudioDriver = makeDefaultAudioDriver()
let demoEngine: SynthesisEngine = SynthesisEngine(
blockSize: demoBlockSize,
sampleRate: demoSampleRate,
numOutputChannels: 2,
numInputChannels: 0,
driver: demoDriver
)
demoEngine.scopeTap = demoScope
// Both synths are cheap to build; only the selected one is added to the engine.
// Building both keeps the node extraction below branch-free (no force-unwrap).
let vectorSynth: VectorOscillatorUI = VectorOscillatorUI()
let sineSynth: SineToneUI = SineToneUI()
let activeSynth: SynthesizerBase = (selection == .vector) ? vectorSynth : sineSynth
// Extract the projected parameter nodes here, in main.swift's top-level
// `@MainActor` context: `SynthesizerBase` is `@MainActor`, so `synth.$…` is only
// reachable on the main actor. The nodes are not actor-isolated, so the
// (nonisolated, on Linux) view body can read them freely.
let vectorX: UIParamNode = vectorSynth.$x
let vectorY: UIParamNode = vectorSynth.$y
let vectorFreq: UIParamNode = vectorSynth.$frequency
let vectorAmp: UIParamNode = vectorSynth.$amplitude
let sineFreq: UIParamNode = sineSynth.$frequency
let sineAmp: UIParamNode = sineSynth.$amplitude
let sinePan: UIParamNode = sineSynth.$pan
// A static example envelope for the sine demo's envelope plot.
let demoEnvelope: Envelope = Envelope(
levels: [0.0001, 1.0, 0.6, 0.4, 0.0001],
durations: [0.05, 0.15, 0.4, 0.3],
curves: [.exponential, .exponential, .lin, .exponential],
loopNode: 2,
releaseNode: 4
)
// `SynthesisEngine` is not Sendable; the status view only reads plain CPU-load
// doubles off it, and this demo runs entirely on the UI thread, so a nonisolated
// handle is safe (mirrors the Linux UI demo).
nonisolated(unsafe) let statusEngine: SynthesisEngine = demoEngine
/// Builds the view for the active selection. `if`/`else` maps to the DSL's
/// `buildEither`, which both backends provide.
///
/// Isolation differs by backend: SwiftUI's `View` is `@MainActor`, so on macOS
/// this must be `@MainActor` to construct the view (and it is called from
/// AppKit's main-actor launch). SwiftOpenUI's `View` is nonisolated, so on Linux
/// this stays nonisolated and is callable from the nonisolated scene closure.
#if canImport(SwiftUI)
@MainActor
#endif
@ViewBuilder
func demoContent() -> some View {
if selection == .vector {
VectorOscillatorDemoView(
xNode: vectorX,
yNode: vectorY,
frequencyNode: vectorFreq,
amplitudeNode: vectorAmp,
scope: demoScope,
engine: statusEngine
)
} else {
SineToneDemoView(
frequencyNode: sineFreq,
amplitudeNode: sineAmp,
panNode: sinePan,
scope: demoScope,
engine: statusEngine,
envelope: demoEnvelope
)
}
}
// Start the engine and add the selected synth. `engine.start()` / `add` are
// @MainActor; main.swift's top level is main-actor isolated, so these are direct
// calls. On a build with no live backend the GUI still runs (silently).
do {
try demoEngine.start()
try demoEngine.add(activeSynth)
} catch {
print("[Lyrebird] demo engine setup failed: \(error)")
}
if !isLiveAudioAvailable {
print("[Lyrebird] no live audio backend — the controls still work, but there is no sound.")
}
// MARK: - macOS front end (AppKit + SwiftUI)
#if os(macOS)
import AppKit
final class DemoAppDelegate: NSObject, NSApplicationDelegate {
var window: LyrebirdWindow?
func applicationDidFinishLaunching(_ notification: Notification) {
let w: LyrebirdWindow = LyrebirdWindow(
title: selection.windowTitle,
width: 380,
height: 620
)
w.open { demoContent() }
window = w
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
true
}
func applicationWillTerminate(_ notification: Notification) {
demoEngine.stop()
}
}
MainActor.assumeIsolated {
let app: NSApplication = NSApplication.shared
app.setActivationPolicy(.regular)
let delegate: DemoAppDelegate = DemoAppDelegate()
app.delegate = delegate
app.run()
}
// MARK: - Linux front end (GTK4 + SwiftOpenUI)
#else
struct DemoApp: App {
var body: some Scene {
WindowGroup(selection.windowTitle) {
demoContent()
}
}
}
GTK4Backend().run(DemoApp.self)
#endif
@@ -0,0 +1,33 @@
// DemoSelection.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Which synthesizer the demo runs, chosen by the `LYREBIRD_DEMO` environment
/// variable. Both front ends (AppKit on macOS, GTK4 on Linux) read the same
/// selection so one binary covers every patch.
public enum DemoSelection: String, Sendable {
/// Vector oscillator with an XY blend pad (the default).
case vector
/// Stereo sine tone with frequency / amplitude / pan controls.
case sine
/// Resolve the selection from `LYREBIRD_DEMO` (defaults to `.vector`).
public static func fromEnvironment() -> DemoSelection {
let raw: String = ProcessInfo.processInfo.environment["LYREBIRD_DEMO"]?.lowercased() ?? "vector"
return DemoSelection(rawValue: raw) ?? .vector
}
/// Title-bar text for the window hosting this demo.
public var windowTitle: String {
switch self {
case .vector: return "Lyrebird — Vector Oscillator"
case .sine: return "Lyrebird — Sine Tone"
}
}
}
@@ -0,0 +1,60 @@
// SineToneDemoView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if canImport(SwiftUI)
import SwiftUI
#endif
import LyrebirdSynth
import LyrebirdUI
/// Live controls for ``SineToneUI``: a frequency slider, amplitude and pan knobs,
/// a level readout, a CPU-load strip, an oscilloscope, and a static envelope plot.
///
/// Node-based for the same reason as ``VectorOscillatorDemoView`` — the body must
/// compile under both SwiftUI's `@MainActor` body and SwiftOpenUI's nonisolated one.
public struct SineToneDemoView: View {
let frequencyNode: UIParamNode
let amplitudeNode: UIParamNode
let panNode: UIParamNode
let scope: ScopeCapture
let engine: SynthesisEngine
let envelope: Envelope
public init(
frequencyNode: UIParamNode,
amplitudeNode: UIParamNode,
panNode: UIParamNode,
scope: ScopeCapture,
engine: SynthesisEngine,
envelope: Envelope
) {
self.frequencyNode = frequencyNode
self.amplitudeNode = amplitudeNode
self.panNode = panNode
self.scope = scope
self.engine = engine
self.envelope = envelope
}
public var body: some View {
VStack {
Text("Lyrebird — Sine Tone")
.font(.headline)
ParameterSlider("Frequency", node: frequencyNode, range: 440.0...880.0)
HStack {
ParameterKnob("Amplitude", node: amplitudeNode, range: 0.0...1.0)
ParameterKnob("Pan", node: panNode, range: -1.0...1.0)
ParameterLabel("Level", node: amplitudeNode, decimalPlaces: 2)
}
LyrebirdStatusView(engine: engine)
LyrebirdScopeView(capture: scope)
.frame(height: 120)
LyrebirdEnvelopeView(envelope)
}
.padding()
}
}
@@ -0,0 +1,31 @@
// SineToneUI.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// A stereo sine tone whose frequency, amplitude, and pan are live-controllable
/// from the UI. The `@UIParam` slots are the same model both the SwiftUI (macOS)
/// and SwiftOpenUI (Linux) controls bind to — one synthesizer, two front ends.
public final class SineToneUI: SynthesizerBase {
/// Frequency in Hz. Slider range: 440–880 Hz.
@UIParam public var frequency: Double = 440.0
/// Output amplitude (linear gain). Knob range: 0–1.
@UIParam public var amplitude: Double = 0.25
/// Stereo pan position. Knob range: -1 (hard left) … 0 (center) … +1 (hard right).
@UIParam public var pan: Double = 0.0
public override init() {
super.init()
}
public override func build() {
let osc: OscSin.Audio = OscSin.Audio(freq: $frequency)
output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
}
}
@@ -0,0 +1,70 @@
// VectorOscillatorDemoView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// One platform `#if` at the import site; identical body beneath. On macOS SwiftUI
// supplies the View DSL; on Linux `LyrebirdUI` re-exports the SwiftOpenUI DSL, so
// `VStack` / `Text` / `.padding()` resolve on both. The Lyrebird controls
// (`ParameterXY`, `ParameterKnob`, …) and views live in `LyrebirdUI` on every
// platform and bind the same core `UIParamNode`s this view is handed.
#if canImport(SwiftUI)
import SwiftUI
#endif
import LyrebirdSynth
import LyrebirdUI
/// Live controls for ``VectorOscillatorUI``: an XY blend pad, frequency and
/// amplitude knobs, a CPU-load strip, and an oscilloscope of the stereo output.
///
/// The view holds the projected `UIParamNode`s rather than the `@MainActor`
/// synthesizer, because SwiftOpenUI's `body` is nonisolated (unlike SwiftUI's).
/// The caller extracts the nodes on the main actor and hands them in; the nodes
/// themselves are not actor-isolated, so a nonisolated body reads them freely.
public struct VectorOscillatorDemoView: View {
let xNode: UIParamNode
let yNode: UIParamNode
let frequencyNode: UIParamNode
let amplitudeNode: UIParamNode
let scope: ScopeCapture
let engine: SynthesisEngine
public init(
xNode: UIParamNode,
yNode: UIParamNode,
frequencyNode: UIParamNode,
amplitudeNode: UIParamNode,
scope: ScopeCapture,
engine: SynthesisEngine
) {
self.xNode = xNode
self.yNode = yNode
self.frequencyNode = frequencyNode
self.amplitudeNode = amplitudeNode
self.scope = scope
self.engine = engine
}
public var body: some View {
VStack {
Text("Lyrebird — Vector Oscillator")
.font(.headline)
ParameterXY(
xLabel: "X (A↔B)", xNode: xNode, xRange: 0.0...1.0,
yLabel: "Y (AB↔CD)", yNode: yNode, yRange: 0.0...1.0
)
.frame(width: 240, height: 240)
HStack {
ParameterKnob("Frequency", node: frequencyNode, range: 40.0...2000.0)
ParameterKnob("Amplitude", node: amplitudeNode, range: 0.0...1.0)
ParameterLabel("Freq (Hz)", node: frequencyNode, decimalPlaces: 1)
}
LyrebirdStatusView(engine: engine)
LyrebirdScopeView(capture: scope)
.frame(height: 120)
}
.padding()
}
}
@@ -0,0 +1,75 @@
// VectorOscillatorUI.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// A stereo vector oscillator whose XY position, frequency, and amplitude are
/// live-controllable from the UI.
///
/// Four corner wavetables are crossfaded on a 2D XY plane:
///
/// C (triangle) ── D (Hanning) (y = 1)
/// │ │
/// A (sine) ──── B (saw-ish) (y = 0)
/// x=0 x=1
///
/// Moving X blends A↔B (and C↔D); moving Y blends the AB mix into the CD mix.
public final class VectorOscillatorUI: SynthesizerBase {
/// X-axis blend position. 0 = corner A/C, 1 = corner B/D. Normalized [0, 1].
@UIParam public var x: Double = 0.5
/// Y-axis blend position. 0 = bottom (A, B), 1 = top (C, D). Normalized [0, 1].
@UIParam public var y: Double = 0.5
/// Oscillator frequency in Hz. Slider range: 40–2000 Hz.
@UIParam public var frequency: Double = 220.0
/// Output amplitude (linear gain). Knob range: 0–1.
@UIParam public var amplitude: Double = 0.25
private let bufferA: LyrebirdBuffer // corner A: sine
private let bufferB: LyrebirdBuffer // corner B: 16-partial saw-ish
private let bufferC: LyrebirdBuffer // corner C: triangle
private let bufferD: LyrebirdBuffer // corner D: Hanning window shape
public override init() {
let tableSize: Int = lyrebirdDefaultTableSize
let a: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
a.fillSine()
let b: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
b.fill(partials: 16)
let c: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
c.fillTriangle()
let d: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
d.fillHanning()
self.bufferA = a
self.bufferB = b
self.bufferC = c
self.bufferD = d
super.init()
}
public override func build() {
let osc: VectorOscillator.Audio = VectorOscillator.Audio(
bufferA: bufferA,
bufferB: bufferB,
bufferC: bufferC,
bufferD: bufferD,
freq: $frequency,
x: $x,
y: $y,
mul: $amplitude
)
output(bus: 0, source: Pan2(input: osc, pan: 0.0))
}
}
@@ -12,7 +12,7 @@ import LyrebirdUI
// ── Demo selector ───────────────────────────────────────────────────────────── // ── Demo selector ─────────────────────────────────────────────────────────────
// Change `demo` to `.sineTone` or `.binDelay` to switch demos. // Change `demo` to `.sineTone` or `.binDelay` to switch demos.
private enum Demo { case vector, binDelay, sineTone } private enum Demo { case vector, binDelay, sineTone }
private let demo: Demo = .binDelay private let demo: Demo = .vector
// ────────────────────────────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────────────────────────────
final class AppDelegate: NSObject, NSApplicationDelegate { final class AppDelegate: NSObject, NSApplicationDelegate {
@@ -26,6 +26,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
let binDelayController: BinDelayController let binDelayController: BinDelayController
var window: LyrebirdWindow? var window: LyrebirdWindow?
@MainActor
init(engine: SynthesisEngine) { init(engine: SynthesisEngine) {
let scopeCapture = ScopeCapture(buses: [0, 1], bufferSize: 2048) let scopeCapture = ScopeCapture(buses: [0, 1], bufferSize: 2048)
engine.scopeTap = scopeCapture engine.scopeTap = scopeCapture
@@ -13,6 +13,7 @@ import LyrebirdSynth
/// first taps "Start Synthesizer" — this is necessary because /// first taps "Start Synthesizer" — this is necessary because
/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed /// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed
/// sample rate, which is only valid after `engine.start()` returns. /// sample rate, which is only valid after `engine.start()` returns.
@MainActor
@Observable @Observable
final class BinDelayController { final class BinDelayController {
@@ -7,6 +7,7 @@
import Observation import Observation
import LyrebirdSynth import LyrebirdSynth
@MainActor
@Observable @Observable
final class NoteController { final class NoteController {
@@ -7,6 +7,7 @@
import Observation import Observation
import LyrebirdSynth import LyrebirdSynth
@MainActor
@Observable @Observable
final class VectorOscillatorController { final class VectorOscillatorController {
@@ -9,14 +9,19 @@ import LyrebirdSynth
let engine = SynthesisEngine( let engine = SynthesisEngine(
blockSize: 512, blockSize: 512,
sampleRate: 48000, sampleRate: 44100,
numOutputChannels: 2, numOutputChannels: 2,
numInputChannels: 0, numInputChannels: 0,
driver: CoreAudioDriver() driver: CoreAudioDriver()
) )
let delegate = AppDelegate(engine: engine) // AppDelegate.init is @MainActor (it builds @MainActor SynthesizerBase synths
let app = NSApplication.shared // and UI controllers). Program entry runs on the main thread, so assert main-
app.setActivationPolicy(.regular) // actor isolation for the AppKit bootstrap rather than hopping asynchronously.
app.delegate = delegate MainActor.assumeIsolated {
app.run() let delegate: AppDelegate = AppDelegate(engine: engine)
let app: NSApplication = NSApplication.shared
app.setActivationPolicy(.regular)
app.delegate = delegate
app.run()
}
@@ -0,0 +1,24 @@
{
"originHash" : "2c98cd4172bcfb3eff9cb6e34a538f80f5e424aa73fbd5bea2b20cf0c8b539b7",
"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
}
@@ -7,9 +7,21 @@
import Foundation import Foundation
import LyrebirdSynth import LyrebirdSynth
// Output to the Desktop — triggers the NSDesktopFolderUsageDescription TCC prompt on first run. // Offline render has no audio device, so this demo runs the same on macOS and Linux.
let outputURL = FileManager.default.homeDirectoryForCurrentUser // Only the output container differs: CAF is Apple-only (it goes through `ExtAudioFile`),
// so off Apple we write the portable WAV codec instead.
#if canImport(AudioToolbox)
// Apple: CAF on the Desktop — triggers the NSDesktopFolderUsageDescription TCC prompt on first run.
let outputURL: URL = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Desktop/nrt_output.caf") .appendingPathComponent("Desktop/nrt_output.caf")
let outputFormat: AudioFileFormat = .cafFloat32
#else
// Linux (and any non-Apple): WAV in the current working directory — no special-folder
// permission needed, and `WavFileWriter` is the portable encoder off Apple.
let outputURL: URL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
.appendingPathComponent("nrt_output.wav")
let outputFormat: AudioFileFormat = .wavFloat32
#endif
// Render parameters. // Render parameters.
let sampleRate: Double = 48000 let sampleRate: Double = 48000
@@ -43,7 +55,7 @@ let tailDuration: Double = 0.1
let lastStart = voices.map(\.start).max() ?? 0.0 let lastStart = voices.map(\.start).max() ?? 0.0
let totalDur = lastStart + interSetDelay + voiceLength + tailDuration let totalDur = lastStart + interSetDelay + voiceLength + tailDuration
let driver = NRTDriver(outputURL: outputURL, duration: totalDur) let driver = NRTDriver(outputURL: outputURL, duration: totalDur, format: outputFormat)
let engine = SynthesisEngine( let engine = SynthesisEngine(
blockSize: blockSize, blockSize: blockSize,
sampleRate: sampleRate, sampleRate: sampleRate,
@@ -77,7 +89,7 @@ do {
) )
} }
} catch { } catch {
fputs("engine.schedule failed: \(error)\n", stderr) FileHandle.standardError.write(Data("engine.schedule failed: \(error)\n".utf8))
exit(1) exit(1)
} }
@@ -87,7 +99,7 @@ do {
try engine.start() try engine.start()
print("Done.") print("Done.")
} catch { } catch {
fputs("Render failed: \(error)\n", stderr) FileHandle.standardError.write(Data("Render failed: \(error)\n".utf8))
exit(1) exit(1)
} }
+1 -1
View File
@@ -17,7 +17,7 @@ let package = Package(
.executableTarget( .executableTarget(
name: "LyrebirdNRTDemo", name: "LyrebirdNRTDemo",
dependencies: [ dependencies: [
.product(name: "Lyrebird", package: "LyrebirdII"), .product(name: "Lyrebird", package: "Lyrebird"),
], ],
path: "LyrebirdNRTDemo" path: "LyrebirdNRTDemo"
), ),
@@ -0,0 +1,328 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 60;
objects = {
/* Begin PBXBuildFile section */
E3C000000000000000000007 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3C000000000000000000006 /* main.swift */; };
E3C000000000000000000013 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = E3C000000000000000000012 /* Lyrebird */; };
E3C000000000000000000015 /* SineTone.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3C000000000000000000014 /* SineTone.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
E3C000000000000000000004 /* LyrebirdQuickstartDemo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = LyrebirdQuickstartDemo; sourceTree = BUILT_PRODUCTS_DIR; };
E3C000000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
E3C000000000000000000014 /* SineTone.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineTone.swift; sourceTree = "<group>"; };
E3C000000000000000000017 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
E3C000000000000000000018 /* LyrebirdQuickstartDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdQuickstartDemo.entitlements; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
E3C000000000000000000009 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
E3C000000000000000000013 /* Lyrebird in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
E3C000000000000000000002 = {
isa = PBXGroup;
children = (
E3C000000000000000000005 /* LyrebirdQuickstartDemo */,
E3C000000000000000000003 /* Products */,
);
sourceTree = "<group>";
};
E3C000000000000000000003 /* Products */ = {
isa = PBXGroup;
children = (
E3C000000000000000000004 /* LyrebirdQuickstartDemo */,
);
name = Products;
sourceTree = "<group>";
};
E3C000000000000000000005 /* LyrebirdQuickstartDemo */ = {
isa = PBXGroup;
children = (
E3C000000000000000000006 /* main.swift */,
E3C000000000000000000016 /* Synthesizers */,
E3C000000000000000000017 /* Info.plist */,
E3C000000000000000000018 /* LyrebirdQuickstartDemo.entitlements */,
);
path = LyrebirdQuickstartDemo;
sourceTree = "<group>";
};
E3C000000000000000000016 /* Synthesizers */ = {
isa = PBXGroup;
children = (
E3C000000000000000000014 /* SineTone.swift */,
);
path = Synthesizers;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
E3C00000000000000000000A /* LyrebirdQuickstartDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = E3C00000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdQuickstartDemo" */;
buildPhases = (
E3C000000000000000000008 /* Sources */,
E3C000000000000000000009 /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = LyrebirdQuickstartDemo;
packageProductDependencies = (
E3C000000000000000000012 /* Lyrebird */,
);
productName = LyrebirdQuickstartDemo;
productReference = E3C000000000000000000004 /* LyrebirdQuickstartDemo */;
productType = "com.apple.product-type.tool";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
E3C000000000000000000001 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 1600;
TargetAttributes = {
E3C00000000000000000000A = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = E3C00000000000000000000E /* Build configuration list for PBXProject "LyrebirdQuickstartDemo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = E3C000000000000000000002;
packageReferences = (
E3C000000000000000000011 /* XCLocalSwiftPackageReference "../.." */,
);
productRefGroup = E3C000000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
E3C00000000000000000000A /* LyrebirdQuickstartDemo */,
);
};
/* End PBXProject section */
/* Begin PBXSourcesBuildPhase section */
E3C000000000000000000008 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
E3C000000000000000000007 /* main.swift in Sources */,
E3C000000000000000000015 /* SineTone.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
E3C00000000000000000000C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = LyrebirdQuickstartDemo/LyrebirdQuickstartDemo.entitlements;
CODE_SIGN_IDENTITY = "-";
CODE_SIGN_STYLE = Manual;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdQuickstartDemo/Info.plist;
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdQuickstartDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
};
name = Debug;
};
E3C00000000000000000000D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = LyrebirdQuickstartDemo/LyrebirdQuickstartDemo.entitlements;
CODE_SIGN_IDENTITY = "-";
CODE_SIGN_STYLE = Manual;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdQuickstartDemo/Info.plist;
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdQuickstartDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
};
name = Release;
};
E3C00000000000000000000F /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
E3C000000000000000000010 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
E3C00000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdQuickstartDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
E3C00000000000000000000C /* Debug */,
E3C00000000000000000000D /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
E3C00000000000000000000E /* Build configuration list for PBXProject "LyrebirdQuickstartDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
E3C00000000000000000000F /* Debug */,
E3C000000000000000000010 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
E3C000000000000000000011 /* XCLocalSwiftPackageReference "../.." */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ../..;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
E3C000000000000000000012 /* Lyrebird */ = {
isa = XCSwiftPackageProductDependency;
package = E3C000000000000000000011 /* XCLocalSwiftPackageReference "../.." */;
productName = Lyrebird;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = E3C000000000000000000001 /* Project object */;
}
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2620"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "E3C00000000000000000000A"
BuildableName = "LyrebirdQuickstartDemo"
BlueprintName = "LyrebirdQuickstartDemo"
ReferencedContainer = "container:LyrebirdQuickstartDemo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "E3C00000000000000000000A"
BuildableName = "LyrebirdQuickstartDemo"
BlueprintName = "LyrebirdQuickstartDemo"
ReferencedContainer = "container:LyrebirdQuickstartDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "E3C00000000000000000000A"
BuildableName = "LyrebirdQuickstartDemo"
BlueprintName = "LyrebirdQuickstartDemo"
ReferencedContainer = "container:LyrebirdQuickstartDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>NSDesktopFolderUsageDescription</key>
<string>LyrebirdQuickstartDemo writes rendered audio files to the Desktop.</string>
<key>NSDocumentsFolderUsageDescription</key>
<string>LyrebirdQuickstartDemo writes rendered audio files to Documents.</string>
</dict>
</plist>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<false/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,21 @@
// SineTone.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
// A Synthesizer is a graph built in `build()`. This one is a single sine
// oscillator, scaled down so it isn't harsh, centred to both speakers with
// Pan2 and written to output bus 0 (left) / bus 1 (right).
//
// This is the same synth the `quickstart` CLI template scaffolds:
// lyrebird new MyFirstSound --template quickstart
final class SineTone: SynthesizerBase {
override func build() {
let sin: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.2)
let pan: Pan2 = Pan2(input: sin, pan: 0)
output(bus: 0, source: pan)
}
}
@@ -0,0 +1,46 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdQuickstartDemo — the shortest path to sound.
//
// Mirrors the `quickstart` CLI template (`lyrebird new … --template quickstart`):
// the engine, a one-oscillator SineTone (see Synthesizers/SineTone.swift), and a
// main that starts it, plays a 440 Hz tone for 10 seconds, then stops and exits.
import Foundation
import LyrebirdSynth
// Seconds to play before exiting.
let quickstartDuration: Double = 5.0
do {
// The engine owns the audio device and runs the graph on the RT thread.
// `makeDefaultAudioDriver()` picks the platform backend — Core Audio on Apple,
// ALSA on Linux (needs libasound) — so this demo builds and runs on both.
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0,
driver: makeDefaultAudioDriver()
)
try engine.start()
let sineTone: SineTone = SineTone()
try engine.add(sineTone) // starts sounding immediately
print("LyrebirdQuickstartDemo: playing a 440 Hz sine for \(Int(quickstartDuration)) seconds…")
Thread.sleep(forTimeInterval: quickstartDuration)
engine.remove(sineTone)
Thread.sleep(forTimeInterval: 0.1)
engine.stop() // closes the device
print("Done.")
} catch {
FileHandle.standardError.write(Data("Lyrebird quickstart failed to start: \(error)\n".utf8))
exit(1)
}
@@ -0,0 +1,24 @@
{
"originHash" : "293673d962d3211d0b8d90755b3dd158ce14df67eed9e956cb4457dba015dc09",
"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,25 @@
// Package.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "LyrebirdQuickstartDemo",
platforms: [.macOS(.v15)],
dependencies: [
.package(path: "../.."),
],
targets: [
.executableTarget(
name: "LyrebirdQuickstartDemo",
dependencies: [
.product(name: "Lyrebird", package: "Lyrebird"),
],
path: "LyrebirdQuickstartDemo"
),
]
)
@@ -0,0 +1,344 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 60;
objects = {
/* Begin PBXBuildFile section */
A5D100000000000000000007 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000006 /* main.swift */; };
A5D100000000000000000013 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = A5D100000000000000000012 /* Lyrebird */; };
A5D100000000000000000015 /* ScoreVoice.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000014 /* ScoreVoice.swift */; };
A5D100000000000000000019 /* DemoProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D100000000000000000018 /* DemoProtocol.swift */; };
A5D10000000000000000001B /* ScoreDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5D10000000000000000001A /* ScoreDemo.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
A5D100000000000000000004 /* LyrebirdScoreDemo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = LyrebirdScoreDemo; sourceTree = BUILT_PRODUCTS_DIR; };
A5D100000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
A5D100000000000000000014 /* ScoreVoice.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScoreVoice.swift; sourceTree = "<group>"; };
A5D100000000000000000017 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
A5D100000000000000000020 /* LyrebirdScoreDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScoreDemo.entitlements; sourceTree = "<group>"; };
A5D100000000000000000018 /* DemoProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoProtocol.swift; sourceTree = "<group>"; };
A5D10000000000000000001A /* ScoreDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScoreDemo.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
A5D100000000000000000009 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
A5D100000000000000000013 /* Lyrebird in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
A5D100000000000000000002 = {
isa = PBXGroup;
children = (
A5D100000000000000000005 /* LyrebirdScoreDemo */,
A5D100000000000000000003 /* Products */,
);
sourceTree = "<group>";
};
A5D100000000000000000003 /* Products */ = {
isa = PBXGroup;
children = (
A5D100000000000000000004 /* LyrebirdScoreDemo */,
);
name = Products;
sourceTree = "<group>";
};
A5D100000000000000000005 /* LyrebirdScoreDemo */ = {
isa = PBXGroup;
children = (
A5D100000000000000000006 /* main.swift */,
A5D100000000000000000016 /* Synthesizers */,
A5D10000000000000000001C /* Demos */,
A5D100000000000000000017 /* Info.plist */,
A5D100000000000000000020 /* LyrebirdScoreDemo.entitlements */,
);
path = LyrebirdScoreDemo;
sourceTree = "<group>";
};
A5D100000000000000000016 /* Synthesizers */ = {
isa = PBXGroup;
children = (
A5D100000000000000000014 /* ScoreVoice.swift */,
);
path = Synthesizers;
sourceTree = "<group>";
};
A5D10000000000000000001C /* Demos */ = {
isa = PBXGroup;
children = (
A5D100000000000000000018 /* DemoProtocol.swift */,
A5D10000000000000000001A /* ScoreDemo.swift */,
);
path = Demos;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
A5D10000000000000000000A /* LyrebirdScoreDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = A5D10000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdScoreDemo" */;
buildPhases = (
A5D100000000000000000008 /* Sources */,
A5D100000000000000000009 /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = LyrebirdScoreDemo;
packageProductDependencies = (
A5D100000000000000000012 /* Lyrebird */,
);
productName = LyrebirdScoreDemo;
productReference = A5D100000000000000000004 /* LyrebirdScoreDemo */;
productType = "com.apple.product-type.tool";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
A5D100000000000000000001 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 1600;
TargetAttributes = {
A5D10000000000000000000A = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = A5D10000000000000000000E /* Build configuration list for PBXProject "LyrebirdScoreDemo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = A5D100000000000000000002;
packageReferences = (
A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */,
);
productRefGroup = A5D100000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
A5D10000000000000000000A /* LyrebirdScoreDemo */,
);
};
/* End PBXProject section */
/* Begin PBXSourcesBuildPhase section */
A5D100000000000000000008 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A5D100000000000000000007 /* main.swift in Sources */,
A5D100000000000000000015 /* ScoreVoice.swift in Sources */,
A5D100000000000000000019 /* DemoProtocol.swift in Sources */,
A5D10000000000000000001B /* ScoreDemo.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
A5D10000000000000000000C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = LyrebirdScoreDemo/LyrebirdScoreDemo.entitlements;
CODE_SIGN_IDENTITY = "-";
CODE_SIGN_STYLE = Manual;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdScoreDemo/Info.plist;
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScoreDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
};
name = Debug;
};
A5D10000000000000000000D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = LyrebirdScoreDemo/LyrebirdScoreDemo.entitlements;
CODE_SIGN_IDENTITY = "-";
CODE_SIGN_STYLE = Manual;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdScoreDemo/Info.plist;
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScoreDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
};
name = Release;
};
A5D10000000000000000000F /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
A5D100000000000000000010 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
A5D10000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdScoreDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A5D10000000000000000000C /* Debug */,
A5D10000000000000000000D /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A5D10000000000000000000E /* Build configuration list for PBXProject "LyrebirdScoreDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A5D10000000000000000000F /* Debug */,
A5D100000000000000000010 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ../..;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
A5D100000000000000000012 /* Lyrebird */ = {
isa = XCSwiftPackageProductDependency;
package = A5D100000000000000000011 /* XCLocalSwiftPackageReference "../.." */;
productName = Lyrebird;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = A5D100000000000000000001 /* Project object */;
}
@@ -0,0 +1,24 @@
{
"originHash" : "2c98cd4172bcfb3eff9cb6e34a538f80f5e424aa73fbd5bea2b20cf0c8b539b7",
"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,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2620"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A5D10000000000000000000A"
BuildableName = "LyrebirdScoreDemo"
BlueprintName = "LyrebirdScoreDemo"
ReferencedContainer = "container:LyrebirdScoreDemo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A5D10000000000000000000A"
BuildableName = "LyrebirdScoreDemo"
BlueprintName = "LyrebirdScoreDemo"
ReferencedContainer = "container:LyrebirdScoreDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A5D10000000000000000000A"
BuildableName = "LyrebirdScoreDemo"
BlueprintName = "LyrebirdScoreDemo"
ReferencedContainer = "container:LyrebirdScoreDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,11 @@
// DemoProtocol.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
protocol DemoProtocol {
func runDemo()
}
@@ -0,0 +1,704 @@
// ScoreDemo.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
/// Directory this demo writes its output files to: the Desktop on Apple (matching the
/// Xcode scheme), the current working directory elsewhere (Linux has no Desktop folder
/// to grant, and `swift run` starts from a known location).
func demoOutputDirectory() -> URL {
#if canImport(AudioToolbox)
return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Desktop")
#else
return URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
#endif
}
/// Builds a multi-part Score using every DSL node type, exports MusicXML, round-trips
/// the document, and reports render statistics.
///
/// Call ``buildAndReport()`` after construction to export MusicXML and print the
/// round-trip summary. ``scheduleVoices(engine:)`` is marked ``@MainActor`` because
/// ``ScoreVoice`` (a ``SynthesizerBase`` subclass) is ``@MainActor``-isolated; call it
/// on the main thread before ``engine.start()``.
final class ScoreDemo: DemoProtocol {
// MARK: - Constants
/// Beats per minute for the demo score.
static let bpm: Double = 108.0
/// Seconds per beat at the demo tempo.
static let secondsPerBeat: Double = 60.0 / ScoreDemo.bpm
/// Extra render tail (seconds) to let the final release decay.
static let tailSeconds: Double = 1.2
/// Pan position for lead-part voices (MIDI channel 0): slightly left.
static let leadPan: Double = -0.4
/// Pan position for bass-part voices (other channels): slightly right.
static let bassPan: Double = 0.5
/// Scale applied to a `ScoreEvent`'s normalized velocity to set voice amplitude.
static let velocityToAmpScale: Double = 0.35
// MARK: - Properties
/// The score built at init time.
let score: Score
/// Total render duration in seconds, including tail.
let totalDuration: Double
// MARK: - Init
init() {
let builtScore: Score = ScoreDemo.makeScore()
self.score = builtScore
self.totalDuration = builtScore.totalBeats * ScoreDemo.secondsPerBeat
+ ScoreDemo.tailSeconds
}
// MARK: - DemoProtocol
/// Export MusicXML and print the round-trip event count. Does not interact with
/// the engine or schedule any voices.
func runDemo() {
// Step 1 — write MusicXML to the demo output directory.
let xmlURL: URL = demoOutputDirectory()
.appendingPathComponent("LyrebirdScoreDemo.musicxml")
let xmlString: String = score.toMusicXMLString()
do {
try xmlString.write(to: xmlURL, atomically: true, encoding: .utf8)
print("MusicXML written → \(xmlURL.path)")
} catch {
FileHandle.standardError.write(Data("Failed to write MusicXML: \(error)\n".utf8))
}
// Step 2 — round-trip sanity check.
let xmlData: Data = score.toMusicXMLData()
do {
let rt: Score = try Score.fromMusicXML(data: xmlData)
let originalCount: Int = score.allEvents.count
let roundTripCount: Int = rt.allEvents.count
print("Round-trip events: \(originalCount) → \(roundTripCount)")
// Verify notation-only elements do not affect event count. Grace
// notes (lead), clef changes (bass), staff grouping + sustain-pedal
// marks (piano) are all skipped by flatten(), so the score's event
// count must equal the round-tripped count.
let selfConsistent: String = (originalCount == roundTripCount) ? "self-consistent" : "MISMATCH"
print("Notation-only event count: \(selfConsistent)")
// Verify tempo changes round-trip.
let originalChanges: Int = score.tempoChanges.count
let rtChanges: Int = rt.tempoChanges.count
print("Round-trip tempo changes: \(originalChanges) → \(rtChanges)")
if originalChanges == rtChanges {
for (orig, recovered): (TempoChange, TempoChange) in zip(score.tempoChanges, rt.tempoChanges) {
let measMatch: String = orig.measure == recovered.measure ? "OK" : "MISMATCH"
let bpmMatch: String = abs(orig.bpm - recovered.bpm) < 0.001 ? "OK" : "MISMATCH"
print(" TempoChange measure=\(orig.measure) \(measMatch) bpm=\(orig.bpm) \(bpmMatch)")
}
}
// Verify per-part key override + transpose round-trip on the clarinet part.
// Part order: 0=lead, 1=bass, 2=clarinet, 3=piano, 4=texture,
// 5=timeline, 6=autovoice, 7=polymeter — so the clarinet is index 2.
if rt.parts.count > 2 {
let clarinet: ScorePart = rt.parts[2]
let keyOK: String = (clarinet.keySignature == .aMajor) ? "OK" : "MISMATCH(\(String(describing: clarinet.keySignature)))"
let transposeOK: String = (clarinet.transpose == .bFlat) ? "OK" : "MISMATCH(\(String(describing: clarinet.transpose)))"
print("Clarinet part key override: \(keyOK)")
print("Clarinet part transpose (bFlat): \(transposeOK)")
print("Score key (G major): \(rt.keySignature == .gMajor ? "OK" : "MISMATCH(\(rt.keySignature))")")
}
} catch {
FileHandle.standardError.write(Data("MusicXML round-trip failed: \(error)\n".utf8))
}
// Step 2b — sectioned showcase: multiple Sections assembled into one
// score (continuous measure numbers + per-section rehearsal marks),
// glissandi, slurs/hairpins, per-note display overrides, tacet fill,
// and a landscape page layout. Section labels export as standard
// <rehearsal> marks — system objects placed once above the top staff (tied
// to the section, not an instrument line, and collision-free). Some editors
// (e.g. Dorico) auto-sequence imported rehearsal marks as A, B, C and hide
// the authored text; that is an editor display setting. The
// `rehearsalMarksAsStaffText: true` option emits boxed <words> staff text
// instead, but that attaches to a staff and can collide with notation.
let showcase: Score = ScoreDemo.makeSectionedShowcase()
let showcaseURL: URL = demoOutputDirectory()
.appendingPathComponent("LyrebirdScoreSections.musicxml")
do {
try showcase.toMusicXMLString().write(to: showcaseURL, atomically: true, encoding: .utf8)
print("Sectioned showcase written → \(showcaseURL.path)")
// Report the assembled measure span + rehearsal marks.
let marks: [(measure: Int, label: String)] = showcase.rehearsalMarks
.sorted { $0.key < $1.key }
.map { (measure: $0.key, label: $0.value) }
let markList: String = marks.map { "\($0.label)@m\($0.measure)" }.joined(separator: ", ")
print("Sections → rehearsal marks: \(markList)")
print("Sectioned showcase parts: \(showcase.parts.map { $0.name }.joined(separator: ", "))")
} catch {
FileHandle.standardError.write(Data("Failed to write sectioned showcase: \(error)\n".utf8))
}
// Step 3 — report render parameters.
let displayBeats: Double = score.totalBeats
let displayDur: Double = totalDuration
print(
String(
format: "Score: %.1f beats at %.0f BPM → %.2f s render (+ %.2f s tail)",
displayBeats,
ScoreDemo.bpm,
displayBeats * ScoreDemo.secondsPerBeat,
ScoreDemo.tailSeconds
)
)
print(String(format: "Total render: %.2f s", displayDur))
}
// MARK: - Voice scheduling
/// Schedule one ``ScoreVoice`` per non-rest event against the engine.
///
/// Must be called on the main actor because ``ScoreVoice`` (a ``SynthesizerBase``
/// subclass) is ``@MainActor``-isolated. Call this after constructing the engine
/// but before ``engine.start()``.
@MainActor
func scheduleVoices(engine: SynthesisEngine) {
let secondsPerBeat: Double = ScoreDemo.secondsPerBeat
let allEvents: [ScoreEvent] = score.allEvents
var scheduledCount: Int = 0
var failedCount: Int = 0
for event: ScoreEvent in allEvents {
guard !event.isRest else { continue }
guard let freqHz: Double = event.pitch.frequency else { continue }
let startSeconds: Double = event.beat * secondsPerBeat
let durSeconds: Double = event.performedDuration * secondsPerBeat
// Separate lead (slight left) from bass (slight right) by MIDI channel.
let pan: Double = event.channel == 0 ? ScoreDemo.leadPan : ScoreDemo.bassPan
let voice: ScoreVoice = ScoreVoice(
freqHz: freqHz,
amp: event.velocity * ScoreDemo.velocityToAmpScale,
durSeconds: durSeconds,
pan: pan
)
do {
try engine.schedule(voice, after: startSeconds)
scheduledCount += 1
} catch {
FileHandle.standardError.write(Data("engine.schedule failed for beat \(event.beat): \(error)\n".utf8))
failedCount += 1
}
}
print("Scheduled \(scheduledCount) voices\(failedCount > 0 ? ", \(failedCount) failed" : "").")
}
// MARK: - Material-creation helpers
//
// Beyond hand-authoring notes, Lyrebird offers several ways to GENERATE score
// material. These helpers feed the `timeline` and `autovoice` parts.
// `ScoreTimeline` is throwing, so the `[ScoreElement]` is built here (outside
// the non-throwing score result-builder) and dropped into a `Part { … }` body.
/// Place notes at explicit musical beats and let the timeline fill the rests.
/// `BeatPosition.beat(_:)` is the felt-beat reading (4/4: beat 1 = downbeat,
/// beat 5 = bar-2 downbeat). See ``ScoreTimeline`` / ``BeatPosition``.
private static func makeTimelineMaterial() -> [ScoreElement] {
do {
return try ScoreTimeline.from(
(.beat(1.0), Note(.named(.d, 5), dur: .quarter, dyn: .mp)),
(.beat(5.0), Note(.named(.f, 5), dur: .quarter, dyn: .mp)),
(.bar(2, beat: 3.0), Note(.named(.a, 5), dur: .half, dyn: .mf, art: .tenuto)),
meter: MeterMap(.fourFour)
)
} catch {
print("[ScoreDemo] timeline material failed: \(error)")
return []
}
}
/// Overlapping placements distributed across voices automatically — a held
/// whole note under a moving line becomes two voices. See
/// ``ScoreTimeline/fillAutoVoiced(_:)``.
private static func makeAutoVoicedMaterial() -> [ScoreElement] {
do {
return try ScoreTimeline.fillAutoVoiced([
(beat: 0.0, element: Note(.named(.c, 4), dur: .whole, dyn: .p)),
(beat: 0.0, element: Note(.named(.e, 5), dur: .quarter, dyn: .mp)),
(beat: 1.0, element: Note(.named(.f, 5), dur: .quarter, dyn: .mp)),
(beat: 2.0, element: Note(.named(.g, 5), dur: .quarter, dyn: .mp)),
(beat: 3.0, element: Note(.named(.e, 5), dur: .quarter, dyn: .mp)),
])
} catch {
print("[ScoreDemo] auto-voiced material failed: \(error)")
return []
}
}
// MARK: - Score construction
/// Builds the demo score: eight parts, each chosen to exercise a different
/// authoring path.
///
/// The hand-authored `lead` part is written **inline** below to show direct
/// result-builder entry; every other part is built by its own `make…Part()`
/// helper for clearer encapsulation. The parts, in document order:
///
/// - **`lead`** *(inline)* — 8-bar melody: crescendo/diminuendo hairpins, a
/// triplet run, tied sixteenths, chords, a grace note (acciaccatura F♯5),
/// and a nested 5:4 ⊃ 3:2 tuplet.
/// - **`bass`** — sustained low line with double-stops, a mid-voice clef
/// change (bass → tenor → bass), a walking eighth-note run, and a triplet
/// fill. Hand-authored.
/// - **`clarinet`** — transposing-instrument demo (B♭): per-part key
/// override (A major) + `<transpose>`. Hand-authored.
/// - **`piano`** — grand staff. Staff 1 (treble) carries two voices (an
/// upper melody and a tied C-major triad); staff 2 (bass) carries a
/// sustained whole-note C under a sustain-pedal marking.
/// - **`texture`** — algorithmic generation via `Generate` (index-driven)
/// and `PatternNotes` (a seeded Brownian MIDI walk).
/// - **`timeline`** — notes placed at explicit `BeatPosition`s with rests
/// auto-filled (`ScoreTimeline`).
/// - **`autovoice`** — overlapping placements distributed across voices
/// automatically (`ScoreTimeline.fillAutoVoiced`).
/// - **`polymeter`** — runs in its OWN 3/4 meter while the score is 4/4
/// (per-part `MeterMap`).
///
/// Score-level features layered over all parts: a forward/backward repeat
/// with 1st/2nd endings (bars 1–4) and tempo changes at bar 3 (132 BPM) and
/// bar 7 (80 BPM). Both are notation-only — playback uses the base tempo.
private static func makeScore() -> Score {
return Score(
bpm: ScoreDemo.bpm,
timeSignature: TimeSignature(4, 4),
keySignature: .gMajor,
// Repeat of bars 1–3 with first/second endings. The backward repeat
// sits at the END of the first ending (bar 3) — the jump-back point.
// On the repeat, the first ending (bar 3) is skipped and the second
// ending (bar 4) plays straight through, so bar 4 has no repeat.
repeats: RepeatStructure(
forwardRepeatMeasures: [1],
backwardRepeatMeasures: [3],
endings: [
Ending(number: 1, startMeasure: 3, stopMeasure: 3),
Ending(number: 2, startMeasure: 4, stopMeasure: 4)
]
),
// Tempo changes. Bar 3 accelerates to 132 BPM; bar 7 relaxes to 80
// BPM. These are notation-only — playback still uses the base bpm
// (108). A tempo change is emitted in every part that reaches that
// measure: bar 3 exists in all parts (incl. the 4-bar piano), bar 7
// only in the 8-bar lead/bass.
tempoChanges: [
TempoChange(measure: 3, bpm: 132.0),
TempoChange(measure: 7, bpm: 80.0)
],
// Page layout — emitted as a MusicXML <defaults> block (US Letter,
// portrait). Engravers honour the page size, orientation, margins,
// and staff scaling on import.
pageLayout: PageLayout(size: .letter, orientation: .portrait)
) {
// Lead melody — kept INLINE to demonstrate direct result-builder
// entry. Every other part is built by a make…Part() helper below.
// 8 bars covering dynamics, articulations, a grace note, and a
// nested tuplet. Bars 1–2 include a Crescendo and Diminuendo hairpin.
Part("lead") {
// Bar 1 — arpeggiated C major with staccato, under a crescendo.
// The high C6 also starts a slur that overlaps into bar 2 —
// demonstrating a shared boundary where a slur-start and a
// hairpin coexist on the same note via the spanners: parameter.
Slur {
Crescendo {
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
Note(.named(.e, 5), dur: .quarter, dyn: .mf, art: .staccato)
Note(.named(.g, 5), dur: .quarter, dyn: .mf, art: .staccato)
// spanners: [.beginSlur] opens a slur here while the Crescendo
// block simultaneously marks this note with the wedge-start.
// The two annotations are independent fields on the atom and
// compose without conflict in MusicXML.
Note(.named(.c, 6), dur: .quarter, dyn: .f, art: .accent)
}
}
// Bar 2 — triplet run followed by legato half note, under a diminuendo.
// The slur started on the C6 above ends on the last triplet note (G5),
// which lies inside the Diminuendo block — the slur overlaps the hairpin.
Diminuendo {
Tuplet(3, inTimeOf: 2) {
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
Note(.named(.a, 5), dur: .quarter, dyn: .mp, spanners: [.beginSlur])
// spanners: [.endSlur] closes the slur here. The Diminuendo
// block's wedge-start is on the B5 triplet note; the slur-stop
// lands on this G5 — overlapping spans, cleanly expressed.
Note(.named(.g, 5), dur: .quarter, dyn: .mp,
spanners: [.endSlur])
}
Note(.named(.f, 5), dur: .half, dyn: .p, art: .legato)
}
// Bar 3 — staccatissimo sixteenth notes, then tenuto half; the
// first two sixteenths are tied (authored tie: sounds
// as one eighth note but is notated as two tied sixteenths).
Note(.named(.e, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo, tie: true)
Note(.named(.e, 5), dur: .sixteenth, dyn: .ff)
Note(.named(.g, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo)
Note(.named(.a, 5), dur: .sixteenth, dyn: .ff, art: .staccatissimo)
Note(.named(.b, 5), dur: .half, dyn: .f, art: .tenuto)
Rest(dur: .quarter)
// Bar 4 — chord, rest, single note
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .accent)
Rest(dur: .quarter)
// Note-display override: a diamond notehead (e.g. a harmonic).
// Notation-only — the flattened event is unchanged.
Note(.named(.d, 5), dur: .quarter, dyn: .mf,
display: NoteDisplay(notehead: .diamond))
// Bar 5 — grace note (acciaccatura F#5) before a nested tuplet.
// Grace is notation-only; flatten() skips it and the
// event count is identical to a score without the grace note.
// The nested 5:4 ⊃ 3:2 tuplet demonstrates per-level
// <tuplet-actual>/<tuplet-normal> bracket engraving.
// Outer children: 3 quarters + inner(3 quarters × 2/3 = 2 quarter-slots)
// = 5 quarter-slots × 4/5 outer scale = 4 beats. Fits the 4/4 bar.
Grace(.named(.fSharp, 5))
Tuplet(5, inTimeOf: 4) {
Note(.named(.c, 5), dur: .quarter, dyn: .mp)
Note(.named(.d, 5), dur: .quarter, dyn: .mp)
Note(.named(.e, 5), dur: .quarter, dyn: .mp)
Tuplet(3, inTimeOf: 2) {
Note(.named(.f, 5), dur: .quarter, dyn: .mp)
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
Note(.named(.gSharp, 5), dur: .quarter, dyn: .mp)
}
}
// Bar 6 — dotted quarter glissando down to the eighth, then a
// legato half. The glissando is a two-note span authored via the
// spanners: parameter (begin on A5, end on G5).
Note(.named(.a, 5), dur: .quarter.dotted, dyn: .mf,
spanners: [.beginGlissando(Glissando())])
Note(.named(.g, 5), dur: .eighth, dyn: .mp, spanners: [.endGlissando])
Note(.named(.fSharp, 5), dur: .half, dyn: .p, art: .legato)
// Bar 7 — marcato descent ppp
Note(.named(.e, 5), dur: .quarter, dyn: .fff, art: .marcato)
Note(.named(.d, 5), dur: .quarter, dyn: .ff)
Note(.named(.c, 5), dur: .quarter, dyn: .f)
Note(.named(.b, 4), dur: .quarter, dyn: .mf)
// Bar 8 — closing chord
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5), .named(.c, 6)], dur: .whole, dyn: .pp, art: .tenuto)
}
ScoreDemo.makeBassPart()
ScoreDemo.makeClarinetPart()
ScoreDemo.makePianoPart()
ScoreDemo.makeTexturePart()
ScoreDemo.makeTimelinePart()
ScoreDemo.makeAutoVoicePart()
ScoreDemo.makePolymeterPart()
}
}
// MARK: - Sectioned showcase
/// A second, self-contained score that demonstrates the section-based
/// authoring stack: multiple ``ScoreSection`` blocks assembled into one
/// score with continuous global measure numbers, per-section rehearsal
/// marks, a tacet instrument auto-filled with rests, glissandi/slides,
/// slurs and hairpins, an intra-note dynamic curve (messa di voce / niente
/// swell), per-note display overrides, and a landscape page layout.
///
/// Two instruments — `flute` (id `fl`) and `cello` (id `vc`) — are matched
/// across sections by `id`. Section labels are single letters (`A`, `B`, `C`):
/// rehearsal marks are system objects that editors typically render as a
/// sequence of letters, so single letters round-trip reliably while custom
/// words may be re-sequenced or hidden. Three sections run sequentially:
/// - **A** (4/4, 2 bars): flute states the theme under a slurred crescendo,
/// then a niente messa-di-voce swell (`dynamicCurve`) over the bar-2 whole
/// note; cello is TACET (auto-filled, stays bar-aligned).
/// - **B** (3/4, 2 bars): flute plays a wavy glissando and an x-notehead /
/// stemless note; cello enters with a straight `slide` glissando.
/// - **C** (4/4, 2 bars): a diminuendo close, a large-notehead final note,
/// sustained cello.
private static func makeSectionedShowcase() -> Score {
return Score(
bpm: 96.0,
keySignature: .cMajor,
// Landscape A4 — emitted as a MusicXML <defaults> block.
pageLayout: PageLayout(size: .a4, orientation: .landscape)
) {
Section("A") {
Part("flute", clef: .treble, id: "fl") {
Crescendo {
Slur {
Note(.named(.c, 5), dur: .quarter, dyn: .p)
Note(.named(.d, 5), dur: .quarter)
Note(.named(.e, 5), dur: .quarter)
Note(.named(.g, 5), dur: .quarter, dyn: .mf)
}
}
// Messa di voce on a single sustained note: a niente swell
// ◦< f >◦ authored via `dynamicCurve`. The dynamics and the
// crescendo/diminuendo hairpins (each closing on a niente
// circle) ride inside this one whole note — no tied split. The
// note's `dyn:` still drives playback velocity.
Note(.named(.c, 5), dur: .whole, dyn: .mf,
dynamicCurve: [(0.0, .niente), (0.5, .f), (1.0, .niente)])
}
// cello is tacet in section A — the lowering fills it with rests.
}
Section("B", meterMap: MeterMap(.threeFour)) {
Part("flute", clef: .treble, id: "fl") {
// Wavy glissando E5 → B5 (two-note span via spanners:).
Note(.named(.e, 5), dur: .quarter, dyn: .mf,
spanners: [.beginGlissando(Glissando())])
Note(.named(.b, 5), dur: .quarter, spanners: [.endGlissando])
// x-notehead (ghost / percussive) — notation-only.
Note(.named(.a, 5), dur: .quarter, display: NoteDisplay(notehead: .x))
// Bar 2: legato half + a stemless note.
Note(.named(.g, 5), dur: .half, dyn: .p, art: .legato)
Note(.named(.fSharp, 5), dur: .quarter,
display: NoteDisplay(hideStem: true))
}
Part("cello", clef: .bass, id: "vc") {
// Straight slide glissando C3 → G3, dashed line.
Note(.named(.c, 3), dur: .half.dotted, dyn: .mp,
spanners: [.beginGlissando(Glissando(kind: .slide, lineType: .dashed))])
Note(.named(.g, 3), dur: .half.dotted, spanners: [.endGlissando])
}
}
Section("C") {
Part("flute", clef: .treble, id: "fl") {
Diminuendo {
Note(.named(.g, 5), dur: .quarter, dyn: .f)
Note(.named(.e, 5), dur: .quarter)
Note(.named(.c, 5), dur: .half, dyn: .pp, art: .legato)
}
// Final note with a large notehead (single pitch, not a chord).
Note(.named(.c, 6), dur: .whole, dyn: .pp, art: .tenuto,
display: NoteDisplay(size: .large))
}
Part("cello", clef: .bass, id: "vc") {
Note(.named(.c, 3), dur: .whole, dyn: .mp)
Note(.named(.c, 3), dur: .whole, dyn: .pp)
}
}
}
}
// MARK: - Part-creation helpers
/// Bass line — sustained low harmonies with occasional double-stops, a
/// mid-voice clef change (bass → tenor → bass), a walking eighth-note run,
/// and a triplet fill. Single voice; carries Crescendo/Diminuendo-free
/// material at the low end of the texture.
private static func makeBassPart() -> ScorePart {
Part("bass", channel: 1, clef: .bass) {
// Bar 1 — low C whole note
Note(.named(.c, 2), dur: .whole, dyn: .mp)
// Bar 2 — G pedal
Note(.named(.g, 2), dur: .whole, dyn: .p)
// Bar 3 — half plus quarter, then quarter rest (sums to 4 beats)
Note(.named(.a, 2), dur: .half, dyn: .mf)
Note(.named(.e, 2), dur: .quarter, dyn: .p)
Rest(dur: .quarter)
// Bar 4 — double-stop chords
Chord([.named(.f, 2), .named(.c, 3)], dur: .half, dyn: .mp)
Chord([.named(.d, 2), .named(.a, 2)], dur: .half, dyn: .mp)
// Mid-voice clef change: switch to tenor clef for the
// walking line so it reads with fewer ledger lines, then switch
// back to bass for the low pedal in bar 6. Display-only — sounding
// pitches are unchanged.
ClefChange(.tenor)
// Bar 5 — walking eighth-note bass line
Note(.named(.c, 3), dur: .eighth, dyn: .mf)
Note(.named(.d, 3), dur: .eighth, dyn: .mp)
Note(.named(.e, 3), dur: .eighth, dyn: .mp)
Note(.named(.f, 3), dur: .eighth, dyn: .mp)
Note(.named(.g, 3), dur: .eighth, dyn: .mf)
Note(.named(.a, 3), dur: .eighth, dyn: .mp)
Note(.named(.b, 3), dur: .eighth, dyn: .mp)
Note(.named(.c, 4), dur: .eighth, dyn: .mf)
ClefChange(.bass)
// Bar 6 — pedal half + triplet fill
Note(.named(.g, 2), dur: .half, dyn: .mp, art: .tenuto)
Tuplet(3, inTimeOf: 2) {
Note(.named(.f, 2), dur: .quarter, dyn: .p)
Note(.named(.e, 2), dur: .quarter, dyn: .p)
Note(.named(.d, 2), dur: .quarter, dyn: .p)
}
// Bar 7 — marcato accent descent
Note(.named(.e, 2), dur: .quarter, dyn: .ff, art: .marcato)
Note(.named(.d, 2), dur: .quarter, dyn: .f, art: .staccato)
Note(.named(.c, 2), dur: .half, dyn: .mf)
// Bar 8 — final bass chord (ppp close)
Chord([.named(.c, 2), .named(.g, 2), .named(.c, 3)], dur: .whole, dyn: .ppp)
}
}
/// B♭ clarinet — transposing-instrument demonstration.
/// Score key: G major. Clarinet written key: A major (a major 2nd up,
/// because a B♭ instrument reads a major 2nd higher than concert pitch).
/// transpose: .bFlat → <transpose><diatonic>-1</diatonic><chromatic>-2</chromatic></transpose>.
/// Flatten returns these AS WRITTEN pitches; concert-pitch playback is future work.
/// Single voice.
private static func makeClarinetPart() -> ScorePart {
Part("clarinet", channel: 3, clef: .treble, keySignature: .aMajor, transpose: .bFlat) {
// Bar 1 — ascending A major scale fragment (written; sounds G major)
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
Note(.named(.cSharp, 6), dur: .quarter, dyn: .mf)
Note(.named(.d, 6), dur: .quarter, dyn: .mf)
// Bar 2 — descending to tonic (written A5, sounds G5)
Note(.named(.e, 6), dur: .quarter, dyn: .mf)
Note(.named(.d, 6), dur: .quarter, dyn: .mp)
Note(.named(.cSharp, 6), dur: .quarter, dyn: .mp)
Note(.named(.a, 5), dur: .quarter, dyn: .p)
}
}
/// Piano — a grand staff demonstrating multi-staff notation.
///
/// Staff 1 (treble) holds two independent voices:
/// - **Voice 1** — a 4-bar melodic fragment.
/// - **Voice 2** — sustained chord tones that overlay from beat 0; bars 1–2
/// tie a C-major triad (C4–E4–G4) across the barline so all three pitches
/// sustain.
/// Staff 2 (bass) holds **Voice 3** — a sustained whole-note C under a
/// sustain-pedal marking (pedal down before the note, released after it).
///
/// In MusicXML this encodes as one part with `<staves>2</staves>`, a
/// `<clef number="1">` (treble) / `<clef number="2">` (bass) pair, a
/// `<staff>` element on every note, `<backup>` between the three voices,
/// and `<pedal>` start/stop directions attached to staff 2.
private static func makePianoPart() -> ScorePart {
Part("piano", channel: 2, clef: .treble) {
Staff(1) {
Voice(1) {
// Bar 1 — stepwise ascent
Note(.named(.c, 5), dur: .quarter, dyn: .mp)
Note(.named(.d, 5), dur: .quarter, dyn: .mp)
Note(.named(.e, 5), dur: .quarter, dyn: .mf)
Note(.named(.f, 5), dur: .quarter, dyn: .mf)
// Bar 2 — triplet decoration with a half note landing
Tuplet(3, inTimeOf: 2) {
Note(.named(.g, 5), dur: .quarter, dyn: .mf)
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
}
Note(.named(.f, 5), dur: .half, dyn: .p, art: .legato)
// Bar 3 — eighth-note run with staccato
Note(.named(.e, 5), dur: .eighth, dyn: .f, art: .staccato)
Note(.named(.d, 5), dur: .eighth, dyn: .f, art: .staccato)
Note(.named(.c, 5), dur: .eighth, dyn: .mf, art: .staccato)
Note(.named(.d, 5), dur: .eighth, dyn: .mf, art: .staccato)
Note(.named(.e, 5), dur: .half, dyn: .p, art: .tenuto)
// Bar 4 — closing whole note
Note(.named(.c, 5), dur: .whole, dyn: .pp)
}
Voice(2) {
// Bar 1 — sustained C major triad tied to bar 2 (chord tie).
// The two identical chords sustain as one across the barline.
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .mp, tie: true)
// Bar 2 — same C major triad (tie target: merges with bar 1 above)
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .mp)
// Bar 3 — A minor
Chord([.named(.a, 3), .named(.c, 4), .named(.e, 4)], dur: .whole, dyn: .mp)
// Bar 4 — close on C major
Chord([.named(.c, 4), .named(.e, 4), .named(.g, 4)], dur: .whole, dyn: .pp)
}
}
Staff(2, clef: .bass) {
Voice(3) {
// Bar 1 — sustained bass C under the sustain pedal. Pedal
// down before the note, released after; both pedal marks are
// notation-only (skipped by flatten(), no ScoreEvent).
Pedal(.start)
Note(.named(.c, 3), dur: .whole, dyn: .mp)
Pedal(.stop)
}
}
}
}
/// Texture — algorithmic note generation. Demonstrates the two generative
/// helpers, both returning `[ScoreElement]` that drops straight into the Part
/// body via the result builder.
private static func makeTexturePart() -> ScorePart {
Part("texture", channel: 4, clef: .treble) {
// `Generate` maps each index 0..<8 through the builder closure —
// here a sixteenth-note whole-tone fragment driven by the index.
Generate(8) { i in
Note(midi: 72 + (i % 6) * 2, dur: .sixteenth, dyn: .pp, art: .staccato)
}
// `PatternNotes` pulls pitches and rhythms from `Pattern` value
// sources: a seeded Brownian MIDI walk for pitch, a repeating
// eighth/eighth/quarter cell for rhythm. Stops early if the pitch
// pattern exhausts before `count`.
PatternNotes(
count: 12,
midi: Pattern.brownian(low: 60.0, high: 84.0, step: 4.0, length: 12, seed: 42),
durations: Pattern.sequence([.eighth, .eighth, .quarter]),
dyn: .p
)
}
}
/// Timeline — notes placed at explicit musical beats (`BeatPosition`), with
/// rests auto-filled by `ScoreTimeline`. Material built in
/// ``makeTimelineMaterial()`` (`ScoreTimeline` is throwing). Single voice.
private static func makeTimelinePart() -> ScorePart {
let material: [ScoreElement] = ScoreDemo.makeTimelineMaterial()
return Part("timeline", channel: 5, clef: .treble) {
material
}
}
/// Auto-voiced — overlapping placements distributed across voices
/// automatically (a held whole note + a moving line → two voices). Material
/// built in ``makeAutoVoicedMaterial()``.
private static func makeAutoVoicePart() -> ScorePart {
let material: [ScoreElement] = ScoreDemo.makeAutoVoicedMaterial()
return Part("autovoice", channel: 6, clef: .treble) {
material
}
}
/// Polymeter — this part runs in its OWN 3/4 meter while the rest of the
/// score is 4/4. Per-part `meterMap` → independent barlines; the encoder
/// renders each part against its own meter. Single voice.
private static func makePolymeterPart() -> ScorePart {
Part("polymeter", channel: 7, clef: .bass, meterMap: MeterMap(.threeFour)) {
for _: Int in 0..<6 {
Note(.named(.g, 2), dur: .quarter, dyn: .mp)
}
}
}
}
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>NSDesktopFolderUsageDescription</key>
<string>LyrebirdScoreDemo writes rendered audio and MusicXML files to the Desktop.</string>
<key>NSDocumentsFolderUsageDescription</key>
<string>LyrebirdScoreDemo writes rendered audio files to Documents.</string>
</dict>
</plist>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<false/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,76 @@
// ScoreVoice.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// A self-terminating NRT voice driven by a ``ScoreEvent``.
///
/// Plays a sawtooth oscillator through a percussive amplitude envelope. The
/// envelope runs to completion and frees the synthesizer node automatically
/// via ``DoneAction/freeNode``, so voices do not pile up during NRT render.
///
/// - Parameters:
/// - freqHz: Fundamental frequency in Hz. Stays within audible range; no internal clamping.
/// - amp: Linear amplitude in `[0, 1]` — maps directly from ``ScoreEvent/velocity``.
/// - durSeconds: Played duration in seconds. The sustain stage occupies the bulk of this
/// duration; a fixed 10 ms attack and 60 ms release are subtracted first. If
/// `durSeconds` is very short (< 70 ms), the sustain collapses to zero and the voice
/// becomes purely percussive.
/// - pan: Stereo position in `[-1, 1]`. Default `0.0` (centre).
final class ScoreVoice: SynthesizerBase {
/// Fundamental frequency in Hz. No internal clamping; stay within audible range.
let freqHz: Double
/// Linear amplitude in `[0, 1]`, from the score event's normalized velocity.
let amp: Double
/// Played duration in seconds — determines sustain stage length.
let durSeconds: Double
/// Stereo pan position in `[-1, 1]`.
let pan: Double
/// Fixed attack duration in seconds.
private static let attackSeconds: Double = 0.01
/// Fixed release duration in seconds.
private static let releaseSeconds: Double = 0.06
init(
freqHz: Double,
amp: Double,
durSeconds: Double,
pan: Double = 0.0
) {
self.freqHz = freqHz
self.amp = amp
self.durSeconds = durSeconds
self.pan = pan
super.init()
}
override func build() {
let attack: Double = ScoreVoice.attackSeconds
let release: Double = ScoreVoice.releaseSeconds
let sustainSeconds: Double = max(0.0, durSeconds - attack - release)
let envelope: Envelope = Envelope(
levels: [0.0, 1.0, 0.8, 0.0],
durations: [attack, sustainSeconds, release],
curves: [-4.0, 0.0, -6.0]
)
// Sawtooth oscillator scaled by envelope and amplitude.
let osc: OscSawtooth.Audio = OscSawtooth.Audio(freq: freqHz)
let env: EnvelopeGen.Control = EnvelopeGen.Control(
envelope: envelope,
doneAction: .freeNode
)
let sig: any ValidGeneratorInput = osc * env * amp
output(bus: 0, source: Pan2(input: sig, pan: pan))
}
}
@@ -0,0 +1,55 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
// Audio output. CAF is Apple-only (ExtAudioFile), so off Apple we render the
// portable WAV codec; `demoOutputDirectory()` is the Desktop on Apple and the
// current working directory elsewhere (see ScoreDemo.swift).
#if canImport(AudioToolbox)
let outputFormat: AudioFileFormat = .cafFloat32
let audioURL: URL = demoOutputDirectory().appendingPathComponent("LyrebirdScoreDemo.caf")
#else
let outputFormat: AudioFileFormat = .wavFloat32
let audioURL: URL = demoOutputDirectory().appendingPathComponent("LyrebirdScoreDemo.wav")
#endif
// Render parameters.
let sampleRate: Double = 48000
let blockSize: Int = 512
// Build the score first — totalDuration must be known before NRTDriver is created.
let demo: ScoreDemo = ScoreDemo()
let totalDuration: Double = demo.totalDuration
// MusicXML export and round-trip before audio engine creation.
demo.runDemo()
// Create NRTDriver and engine.
let driver: NRTDriver = NRTDriver(outputURL: audioURL, duration: totalDuration, format: outputFormat)
let engine: SynthesisEngine = SynthesisEngine(
blockSize: blockSize,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
driver: driver
)
// Schedule all score voices. SynthesizerBase (and thus scheduleVoices) is
// @MainActor-isolated; SwiftPM's top-level entry point is itself main-actor
// isolated, so this is a plain direct call — no MainActor hop needed.
demo.scheduleVoices(engine: engine)
print(String(format: "Rendering %.2f s → %@", totalDuration, audioURL.path))
do {
try engine.start()
print("Done.")
} catch {
FileHandle.standardError.write(Data("Render failed: \(error)\n".utf8))
exit(1)
}
+24
View File
@@ -0,0 +1,24 @@
{
"originHash" : "4acd68de25440f1fcc60a86a69d66a0516f6e9d4f2d769aaab597e24b64fd245",
"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
}
+25
View File
@@ -0,0 +1,25 @@
// Package.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "LyrebirdScoreDemo",
platforms: [.macOS(.v15)],
dependencies: [
.package(path: "../.."),
],
targets: [
.executableTarget(
name: "LyrebirdScoreDemo",
dependencies: [
.product(name: "Lyrebird", package: "Lyrebird"),
],
path: "LyrebirdScoreDemo"
),
]
)
@@ -9,17 +9,35 @@
/* Begin PBXBuildFile section */ /* Begin PBXBuildFile section */
C8D0000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000007 /* main.swift */; }; C8D0000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000007 /* main.swift */; };
C8D0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000008 /* AppDelegate.swift */; }; C8D0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000008 /* AppDelegate.swift */; };
C8D0000000000000000000F /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdUI */; }; C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; };
C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001F /* LyrebirdLiveCompile */; }; C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; };
C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUI */; }; C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
C8D00000000000000000041 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000040 /* Assets.xcassets */; };
/* End PBXBuildFile section */ /* End PBXBuildFile section */
/* Begin PBXCopyFilesBuildPhase section */
C8D00000000000000000035 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */,
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */ /* Begin PBXFileReference section */
C8D00000000000000000004 /* LyrebirdScratchDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdScratchDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; C8D00000000000000000004 /* LyrebirdScratch.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdScratch.app; sourceTree = BUILT_PRODUCTS_DIR; };
C8D00000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; C8D00000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
C8D00000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; }; C8D00000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
C8D00000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; }; C8D00000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
C8D00000000000000000009 /* LyrebirdScratchDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScratchDemo.entitlements; sourceTree = "<group>"; }; C8D00000000000000000009 /* LyrebirdScratch.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScratch.entitlements; sourceTree = "<group>"; };
C8D00000000000000000040 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
/* End PBXFileReference section */ /* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */ /* Begin PBXFrameworksBuildPhase section */
@@ -27,9 +45,8 @@
isa = PBXFrameworksBuildPhase; isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
C8D0000000000000000000F /* LyrebirdUI in Frameworks */, C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */,
C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */, C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */,
C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
@@ -39,7 +56,7 @@
C8D00000000000000000002 = { C8D00000000000000000002 = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
C8D00000000000000000005 /* LyrebirdScratchDemo */, C8D00000000000000000005 /* LyrebirdScratch */,
C8D00000000000000000003 /* Products */, C8D00000000000000000003 /* Products */,
); );
sourceTree = "<group>"; sourceTree = "<group>";
@@ -47,45 +64,47 @@
C8D00000000000000000003 /* Products */ = { C8D00000000000000000003 /* Products */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
C8D00000000000000000004 /* LyrebirdScratchDemo.app */, C8D00000000000000000004 /* LyrebirdScratch.app */,
); );
name = Products; name = Products;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
C8D00000000000000000005 /* LyrebirdScratchDemo */ = { C8D00000000000000000005 /* LyrebirdScratch */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
C8D00000000000000000007 /* main.swift */, C8D00000000000000000007 /* main.swift */,
C8D00000000000000000008 /* AppDelegate.swift */, C8D00000000000000000008 /* AppDelegate.swift */,
C8D00000000000000000006 /* Info.plist */, C8D00000000000000000006 /* Info.plist */,
C8D00000000000000000009 /* LyrebirdScratchDemo.entitlements */, C8D00000000000000000009 /* LyrebirdScratch.entitlements */,
C8D00000000000000000040 /* Assets.xcassets */,
); );
path = LyrebirdScratchDemo; path = LyrebirdScratch;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
/* End PBXGroup section */ /* End PBXGroup section */
/* Begin PBXNativeTarget section */ /* Begin PBXNativeTarget section */
C8D00000000000000000014 /* LyrebirdScratchDemo */ = { C8D00000000000000000014 /* LyrebirdScratch */ = {
isa = PBXNativeTarget; isa = PBXNativeTarget;
buildConfigurationList = C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratchDemo" */; buildConfigurationList = C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratch" */;
buildPhases = ( buildPhases = (
C8D00000000000000000011 /* Sources */, C8D00000000000000000011 /* Sources */,
C8D00000000000000000012 /* Frameworks */, C8D00000000000000000012 /* Frameworks */,
C8D00000000000000000013 /* Resources */, C8D00000000000000000013 /* Resources */,
C8D00000000000000000035 /* Embed Frameworks */,
C8D00000000000000000042 /* Bundle Lyrebird swiftmodules */,
); );
buildRules = ( buildRules = (
); );
dependencies = ( dependencies = (
); );
name = LyrebirdScratchDemo; name = LyrebirdScratch;
packageProductDependencies = ( packageProductDependencies = (
C8D0000000000000000001D /* LyrebirdUI */, C8D0000000000000000001D /* LyrebirdDynamic */,
C8D0000000000000000001F /* LyrebirdLiveCompile */, C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */,
C8D00000000000000000020 /* LyrebirdLiveCompileUI */,
); );
productName = LyrebirdScratchDemo; productName = LyrebirdScratch;
productReference = C8D00000000000000000004 /* LyrebirdScratchDemo.app */; productReference = C8D00000000000000000004 /* LyrebirdScratch.app */;
productType = "com.apple.product-type.application"; productType = "com.apple.product-type.application";
}; };
/* End PBXNativeTarget section */ /* End PBXNativeTarget section */
@@ -96,14 +115,14 @@
attributes = { attributes = {
BuildIndependentTargetsInParallel = 1; BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600; LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2620; LastUpgradeCheck = 2660;
TargetAttributes = { TargetAttributes = {
C8D00000000000000000014 = { C8D00000000000000000014 = {
CreatedOnToolsVersion = 16.0; CreatedOnToolsVersion = 16.0;
}; };
}; };
}; };
buildConfigurationList = C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratchDemo" */; buildConfigurationList = C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratch" */;
compatibilityVersion = "Xcode 14.0"; compatibilityVersion = "Xcode 14.0";
developmentRegion = en; developmentRegion = en;
hasScannedForEncodings = 0; hasScannedForEncodings = 0;
@@ -120,7 +139,7 @@
projectDirPath = ""; projectDirPath = "";
projectRoot = ""; projectRoot = "";
targets = ( targets = (
C8D00000000000000000014 /* LyrebirdScratchDemo */, C8D00000000000000000014 /* LyrebirdScratch */,
); );
}; };
/* End PBXProject section */ /* End PBXProject section */
@@ -130,11 +149,30 @@
isa = PBXResourcesBuildPhase; isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
C8D00000000000000000041 /* Assets.xcassets in Resources */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
/* End PBXResourcesBuildPhase section */ /* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
C8D00000000000000000042 /* Bundle Lyrebird swiftmodules */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Bundle Lyrebird swiftmodules";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "# Bundle the Lyrebird module artifacts into the app so the live-compile scratchpad\n# can `import LyrebirdSynth` / `import LyrebirdLiveCompile` on any machine — they\n# otherwise resolve only from BUILT_PRODUCTS_DIR / the dev source tree, both absent\n# once the .app is exported. LiveSession stages Contents/Resources/LyrebirdArtifacts\n# at launch; artifactSourceDir() / discoverSPMModuleMaps() then find them.\nset -e\nART=\"${TARGET_BUILD_DIR}/${CONTENTS_FOLDER_PATH}/Resources/LyrebirdArtifacts\"\nDEST=\"${ART}/Modules\"\n/bin/rm -rf \"${ART}\"\n/bin/mkdir -p \"${DEST}\"\n# 1. Swift module interfaces the snippet imports (+ their transitive deps).\nfor m in LyrebirdSynth LyrebirdLiveCompile LyrebirdLiveCompileUI LyrebirdGraphDSLEmbedded; do\n SRC=\"${BUILT_PRODUCTS_DIR}/${m}.swiftmodule\"\n if [ -e \"${SRC}\" ]; then /bin/cp -R \"${SRC}\" \"${DEST}/\"; fi\ndone\n# 2. LyrebirdC C-shim Clang module (LyrebirdSynth depends on it; a snippet importing\n# LyrebirdSynth needs its module map + header). The SPM source map uses a header path\n# relative to the map dir, so map + include/ copied together stay self-contained and\n# relocatable — placed at LyrebirdArtifacts/LyrebirdC.build so discoverSPMModuleMaps()\n# finds it once staged.\nCSRC=\"${SRCROOT}/../../Sources/LyrebirdC\"\nif [ -f \"${CSRC}/module.modulemap\" ]; then\n CDEST=\"${ART}/LyrebirdC.build\"\n /bin/mkdir -p \"${CDEST}\"\n /bin/cp \"${CSRC}/module.modulemap\" \"${CDEST}/\"\n [ -d \"${CSRC}/include\" ] && /bin/cp -R \"${CSRC}/include\" \"${CDEST}/\"\nfi\necho \"Bundled Lyrebird modules + LyrebirdC shim into ${ART}\"\n";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */
C8D00000000000000000011 /* Sources */ = { C8D00000000000000000011 /* Sources */ = {
isa = PBXSourcesBuildPhase; isa = PBXSourcesBuildPhase;
@@ -151,19 +189,40 @@
C8D00000000000000000016 /* Debug */ = { C8D00000000000000000016 /* Debug */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
CODE_SIGN_ENTITLEMENTS = LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
AUTOMATION_APPLE_EVENTS = NO;
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES; COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 2;
DEAD_CODE_STRIPPING = YES; DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf; DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_HARDENED_RUNTIME = YES; ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdScratchDemo/Info.plist; ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
ENABLE_RESOURCE_ACCESS_CAMERA = NO;
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
LD_RUNPATH_SEARCH_PATHS = ( LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)", "$(inherited)",
"@executable_path/../Frameworks", "@executable_path/../Frameworks",
); );
MACOSX_DEPLOYMENT_TARGET = 15.0; MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratchDemo; MARKETING_VERSION = 1.6.2;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
RUNTIME_EXCEPTION_ALLOW_DYLD_ENVIRONMENT_VARIABLES = NO;
RUNTIME_EXCEPTION_ALLOW_JIT = NO;
RUNTIME_EXCEPTION_ALLOW_UNSIGNED_EXECUTABLE_MEMORY = NO;
RUNTIME_EXCEPTION_DEBUGGING_TOOL = NO;
RUNTIME_EXCEPTION_DISABLE_EXECUTABLE_PAGE_PROTECTION = NO;
RUNTIME_EXCEPTION_DISABLE_LIBRARY_VALIDATION = NO;
SWIFT_EMIT_LOC_STRINGS = YES; SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0; SWIFT_VERSION = 5.0;
}; };
@@ -172,18 +231,39 @@
C8D00000000000000000017 /* Release */ = { C8D00000000000000000017 /* Release */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
CODE_SIGN_ENTITLEMENTS = LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
AUTOMATION_APPLE_EVENTS = NO;
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES; COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 2;
DEAD_CODE_STRIPPING = YES; DEAD_CODE_STRIPPING = YES;
ENABLE_HARDENED_RUNTIME = YES; ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdScratchDemo/Info.plist; ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
ENABLE_RESOURCE_ACCESS_CAMERA = NO;
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
LD_RUNPATH_SEARCH_PATHS = ( LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)", "$(inherited)",
"@executable_path/../Frameworks", "@executable_path/../Frameworks",
); );
MACOSX_DEPLOYMENT_TARGET = 15.0; MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratchDemo; MARKETING_VERSION = 1.6.2;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
RUNTIME_EXCEPTION_ALLOW_DYLD_ENVIRONMENT_VARIABLES = NO;
RUNTIME_EXCEPTION_ALLOW_JIT = NO;
RUNTIME_EXCEPTION_ALLOW_UNSIGNED_EXECUTABLE_MEMORY = NO;
RUNTIME_EXCEPTION_DEBUGGING_TOOL = NO;
RUNTIME_EXCEPTION_DISABLE_EXECUTABLE_PAGE_PROTECTION = NO;
RUNTIME_EXCEPTION_DISABLE_LIBRARY_VALIDATION = NO;
SWIFT_EMIT_LOC_STRINGS = YES; SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0; SWIFT_VERSION = 5.0;
}; };
@@ -224,6 +304,7 @@
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES; DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf; DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES; ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES; ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -248,6 +329,7 @@
STRING_CATALOG_GENERATE_SYMBOLS = YES; STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_USE_INTEGRATED_DRIVER = NO;
}; };
name = Debug; name = Debug;
}; };
@@ -286,6 +368,7 @@
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES; DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_NS_ASSERTIONS = NO; ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES; ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -303,13 +386,14 @@
STRING_CATALOG_GENERATE_SYMBOLS = YES; STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule; SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O"; SWIFT_OPTIMIZATION_LEVEL = "-O";
SWIFT_USE_INTEGRATED_DRIVER = NO;
}; };
name = Release; name = Release;
}; };
/* End XCBuildConfiguration section */ /* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */ /* Begin XCConfigurationList section */
C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratchDemo" */ = { C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratch" */ = {
isa = XCConfigurationList; isa = XCConfigurationList;
buildConfigurations = ( buildConfigurations = (
C8D00000000000000000016 /* Debug */, C8D00000000000000000016 /* Debug */,
@@ -318,7 +402,7 @@
defaultConfigurationIsVisible = 0; defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release; defaultConfigurationName = Release;
}; };
C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratchDemo" */ = { C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratch" */ = {
isa = XCConfigurationList; isa = XCConfigurationList;
buildConfigurations = ( buildConfigurations = (
C8D00000000000000000019 /* Debug */, C8D00000000000000000019 /* Debug */,
@@ -341,20 +425,15 @@
/* End XCLocalSwiftPackageReference section */ /* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */ /* Begin XCSwiftPackageProductDependency section */
C8D0000000000000000001D /* LyrebirdUI */ = { C8D0000000000000000001D /* LyrebirdDynamic */ = {
isa = XCSwiftPackageProductDependency; isa = XCSwiftPackageProductDependency;
package = C8D0000000000000000001B /* XCLocalSwiftPackageReference "../.." */; package = C8D0000000000000000001B /* XCLocalSwiftPackageReference "../.." */;
productName = LyrebirdUI; productName = LyrebirdDynamic;
}; };
C8D0000000000000000001F /* LyrebirdLiveCompile */ = { C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */ = {
isa = XCSwiftPackageProductDependency; isa = XCSwiftPackageProductDependency;
package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */; package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */;
productName = LyrebirdLiveCompile; productName = LyrebirdLiveCompileUIDynamic;
};
C8D00000000000000000020 /* LyrebirdLiveCompileUI */ = {
isa = XCSwiftPackageProductDependency;
package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */;
productName = LyrebirdLiveCompileUI;
}; };
/* End XCSwiftPackageProductDependency section */ /* End XCSwiftPackageProductDependency section */
}; };
@@ -0,0 +1,24 @@
{
"originHash" : "52fa7c84ca46dcb1ce0f4374a4fb0a5d2c97be57f306d91b8e9efb54af7c3c9e",
"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
}
@@ -16,9 +16,9 @@
<BuildableReference <BuildableReference
BuildableIdentifier = "primary" BuildableIdentifier = "primary"
BlueprintIdentifier = "C8D00000000000000000014" BlueprintIdentifier = "C8D00000000000000000014"
BuildableName = "LyrebirdScratchDemo.app" BuildableName = "LyrebirdScratch.app"
BlueprintName = "LyrebirdScratchDemo" BlueprintName = "LyrebirdScratch"
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj"> ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
</BuildableReference> </BuildableReference>
</BuildActionEntry> </BuildActionEntry>
</BuildActionEntries> </BuildActionEntries>
@@ -31,7 +31,7 @@
shouldAutocreateTestPlan = "YES"> shouldAutocreateTestPlan = "YES">
</TestAction> </TestAction>
<LaunchAction <LaunchAction
buildConfiguration = "Debug" buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0" launchStyle = "0"
@@ -45,9 +45,9 @@
<BuildableReference <BuildableReference
BuildableIdentifier = "primary" BuildableIdentifier = "primary"
BlueprintIdentifier = "C8D00000000000000000014" BlueprintIdentifier = "C8D00000000000000000014"
BuildableName = "LyrebirdScratchDemo.app" BuildableName = "LyrebirdScratch.app"
BlueprintName = "LyrebirdScratchDemo" BlueprintName = "LyrebirdScratch"
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj"> ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
</BuildableReference> </BuildableReference>
</BuildableProductRunnable> </BuildableProductRunnable>
</LaunchAction> </LaunchAction>
@@ -62,9 +62,9 @@
<BuildableReference <BuildableReference
BuildableIdentifier = "primary" BuildableIdentifier = "primary"
BlueprintIdentifier = "C8D00000000000000000014" BlueprintIdentifier = "C8D00000000000000000014"
BuildableName = "LyrebirdScratchDemo.app" BuildableName = "LyrebirdScratch.app"
BlueprintName = "LyrebirdScratchDemo" BlueprintName = "LyrebirdScratch"
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj"> ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
</BuildableReference> </BuildableReference>
</BuildableProductRunnable> </BuildableProductRunnable>
</ProfileAction> </ProfileAction>
@@ -0,0 +1,106 @@
// AppDelegate.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AppKit
import SwiftUI
import LyrebirdSynth
// LyrebirdLiveCompile (LiveSession, …) is re-exported by LyrebirdLiveCompileUI.
import LyrebirdLiveCompileUI
// This demo deliberately does NOT link `LyrebirdUI`. The live-compile stack
// (`LyrebirdLiveCompileUIDynamic`) dynamic-links the single shared
// `LyrebirdDynamic.framework` copy of `LyrebirdSynth`; linking the static
// `LyrebirdUI` product would static-fold a SECOND copy of every `LyrebirdSynth`
// ObjC class into the app binary (intra-package `LyrebirdUI → LyrebirdSynth` is
// always a static edge), producing duplicate-class registration and the
// "mysterious crashes" the runtime warns about. The only `LyrebirdUI` symbol
// this demo used was `LyrebirdWindow`, an `NSWindow`/`NSHostingController`
// wrapper with no `LyrebirdSynth` dependency — inlined below instead.
// Entitlements / signing posture (rationale kept here because Xcode strips
// comments from `LyrebirdScratch.entitlements` on every project resave):
//
// • App Sandbox is intentionally OFF. Live-compile shells out to `swiftc`
// (`posix_spawn`, disallowed under the sandbox) and `dlopen`s the resulting
// UNSIGNED snippet dylib (rejected by the sandbox). This is a direct-
// distribution developer tool, not a Mac App Store app; sandbox-off is the
// only viable configuration. (An XPC-worker split could revisit this.)
// • Hardened Runtime is ON, so the entitlement
// `com.apple.security.cs.disable-library-validation = true` is REQUIRED —
// without it dyld rejects `dlopen` of the unsigned, non-team-signed snippet
// dylib ("code signing blocked mmap()").
//
// Do not remove that entitlement or the app can't load compiled snippets.
final class AppDelegate: NSObject, NSApplicationDelegate {
let engine: SynthesisEngine
let session: LiveSession
var model: LyrebirdScratchModel?
var menuController: LyrebirdScratchMenuController?
var window: NSWindow?
@MainActor
init(engine: SynthesisEngine) {
self.engine = engine
// Stage the Lyrebird compile artifacts into ~/Library/Application Support
// (ungated) before the session reads its default -I/-L/rpath. Without
// this the snippet compiler points swiftc at the SPM build dir under
// ~/Documents, tripping the macOS Documents-folder permission gate.
// Best-effort: if staging fails the session falls back to the build dir.
LiveSession.stageArtifacts()
self.session = LiveSession(engine: engine)
}
@MainActor
func applicationDidFinishLaunching(_ notification: Notification) {
do {
try engine.start()
} catch {
print("[LyrebirdScratch] Engine failed to start: \(error)")
}
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session)
self.model = model
let menuController: LyrebirdScratchMenuController = LyrebirdScratchMenuController(model: model)
menuController.installMainMenu()
self.menuController = menuController
let hosting: NSHostingController<LyrebirdScratchView> =
NSHostingController(rootView: LyrebirdScratchView(model: model))
let win: NSWindow = NSWindow(
contentRect: NSRect(origin: .zero, size: CGSize(width: 720, height: 560)),
styleMask: [.titled, .closable, .resizable, .miniaturizable],
backing: .buffered,
defer: false
)
// Keep ownership in Swift — NSWindow defaults to releasing on close.
win.isReleasedWhenClosed = false
win.title = "Lyrebird — Live Scratch"
win.contentViewController = hosting
// Base geometry: three-quarters of the screen wide, three-quarters tall,
// anchored to the left edge and vertically centered in the visible area
// (below the menu bar, above the Dock).
let visible: NSRect = (win.screen ?? NSScreen.main)?.visibleFrame
?? NSRect(x: 0, y: 0, width: 1440, height: 900)
let width: CGFloat = visible.width * 0.75
let height: CGFloat = visible.height * 0.75
let originX: CGFloat = visible.minX
let originY: CGFloat = visible.minY + (visible.height - height) / 2
win.setFrame(NSRect(x: originX, y: originY, width: width, height: height), display: true)
win.makeKeyAndOrderFront(nil)
self.window = win
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
true
}
func applicationWillTerminate(_ notification: Notification) {
engine.stop()
session.clearTracked()
}
}
@@ -0,0 +1,15 @@
{
"images" : [
{ "idiom" : "mac", "scale" : "1x", "size" : "16x16", "filename" : "icon_16.png" },
{ "idiom" : "mac", "scale" : "2x", "size" : "16x16", "filename" : "icon_32.png" },
{ "idiom" : "mac", "scale" : "1x", "size" : "32x32", "filename" : "icon_32.png" },
{ "idiom" : "mac", "scale" : "2x", "size" : "32x32", "filename" : "icon_64.png" },
{ "idiom" : "mac", "scale" : "1x", "size" : "128x128", "filename" : "icon_128.png" },
{ "idiom" : "mac", "scale" : "2x", "size" : "128x128", "filename" : "icon_256.png" },
{ "idiom" : "mac", "scale" : "1x", "size" : "256x256", "filename" : "icon_256.png" },
{ "idiom" : "mac", "scale" : "2x", "size" : "256x256", "filename" : "icon_512.png" },
{ "idiom" : "mac", "scale" : "1x", "size" : "512x512", "filename" : "icon_512.png" },
{ "idiom" : "mac", "scale" : "2x", "size" : "512x512", "filename" : "icon_1024.png" }
],
"info" : { "author" : "xcode", "version" : 1 }
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 338 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 720 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

@@ -0,0 +1,3 @@
{
"info" : { "author" : "xcode", "version" : 1 }
}
@@ -13,14 +13,14 @@
<key>CFBundlePackageType</key> <key>CFBundlePackageType</key>
<string>APPL</string> <string>APPL</string>
<key>CFBundleShortVersionString</key> <key>CFBundleShortVersionString</key>
<string>1.0</string> <string>1.6.3</string>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>1</string> <string>3</string>
<key>LSMinimumSystemVersion</key> <key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string> <string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSHumanReadableCopyright</key> <key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 Realized Sound. All rights reserved.</string> <string>Copyright © 2026 Realized Sound. All rights reserved.</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict> </dict>
</plist> </plist>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,28 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AppKit
import LyrebirdSynth
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
// AppDelegate.init is `@MainActor` (mirrors the other demos' bootstrap — since
// `SynthesizerBase` is `@MainActor`, AppKit-side construction is main-actor
// isolated). Program entry runs on the main thread, so assert main-actor
// isolation for the AppKit bootstrap rather than hopping asynchronously.
MainActor.assumeIsolated {
let delegate: AppDelegate = AppDelegate(engine: engine)
let app: NSApplication = NSApplication.shared
app.setActivationPolicy(.regular)
app.delegate = delegate
app.run()
}
@@ -1,59 +0,0 @@
// AppDelegate.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AppKit
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
import LyrebirdLiveCompile
import LyrebirdLiveCompileUI
final class AppDelegate: NSObject, NSApplicationDelegate {
let engine: SynthesisEngine
let session: LiveSession
var model: LyrebirdScratchModel?
var menuController: LyrebirdScratchMenuController?
var window: LyrebirdWindow?
init(engine: SynthesisEngine) {
self.engine = engine
self.session = LiveSession(engine: engine)
}
@MainActor
func applicationDidFinishLaunching(_ notification: Notification) {
do {
try engine.start()
} catch {
print("[LyrebirdScratchDemo] Engine failed to start: \(error)")
}
let model = LyrebirdScratchModel(session: session)
self.model = model
let menuController = LyrebirdScratchMenuController(model: model)
menuController.installMainMenu()
self.menuController = menuController
window = LyrebirdWindow(
title: "Lyrebird — Live Scratch",
width: 720,
height: 560
)
window?.open {
LyrebirdScratchView(model: model)
}
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
true
}
func applicationWillTerminate(_ notification: Notification) {
engine.stop()
session.clearTracked()
}
}
@@ -1,45 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!--
App Sandbox is intentionally OFF.
LyrebirdScratchDemo shells out to `swiftc` at runtime to compile user-
typed Swift snippets, then calls `dlopen` on the resulting unsigned dylib.
Both operations are blocked by the macOS App Sandbox:
- `posix_spawn` / `fork` for the swiftc subprocess is disallowed in a
sandboxed process (com.apple.security.temporary-exception.mach-lookup
grants exist for specific Apple tools only, not arbitrary executables).
- `dlopen` of a dylib that was not shipped with the app bundle and is
not code-signed with a matching team ID is rejected by the sandbox.
This app is a direct-distribution developer tool, not a Mac App Store
submission. Sandbox OFF is the only viable configuration for v1.
Phase 147 polish can revisit if an XPC-worker approach is adopted.
com.apple.security.app-sandbox key is absent (defaults false).
-->
<!--
Hardened Runtime — Disable Library Validation.
With Hardened Runtime enabled (ENABLE_HARDENED_RUNTIME = YES in the
Xcode project), `dlopen` of a dylib that was not signed with the same
Team ID as the host app is rejected by the dynamic linker.
LyrebirdScratchDemo writes snippet dylibs to a per-session temp dir
via `swiftc -emit-library`; those dylibs are unsigned (swiftc does not
sign them). The `CS_ALLOW_UNSIGNED_EXECUTABLE_MEMORY` (library-
validation disable) entitlement tells the kernel to skip the
code-signing check for loaded libraries, allowing `dlopen` to succeed.
Without this entitlement the app would crash with DYLD_PRINT_LIBRARIES
reporting: "Library not loaded: ... Reason: tried: ... no suitable image
found. Did find: ... code signing blocked mmap() of '...'"
-->
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
@@ -1,23 +0,0 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AppKit
import LyrebirdSynth
import LyrebirdLiveCompile
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
let delegate = AppDelegate(engine: engine)
let app = NSApplication.shared
app.setActivationPolicy(.regular)
app.delegate = delegate
app.run()
@@ -16,6 +16,7 @@ private let demo: Demo = .vector
// ────────────────────────────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────────────────────────────
@main @main
@MainActor
struct LyrebirdiOSDemoApp: App { struct LyrebirdiOSDemoApp: App {
let engine: SynthesisEngine let engine: SynthesisEngine
@@ -13,6 +13,7 @@ import LyrebirdSynth
/// first taps "Start Synthesizer" — this is necessary because /// first taps "Start Synthesizer" — this is necessary because
/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed /// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed
/// sample rate, which is only valid after `engine.start()` returns. /// sample rate, which is only valid after `engine.start()` returns.
@MainActor
@Observable @Observable
final class BinDelayController { final class BinDelayController {
@@ -7,6 +7,7 @@
import Observation import Observation
import LyrebirdSynth import LyrebirdSynth
@MainActor
@Observable @Observable
final class NoteController { final class NoteController {
@@ -7,6 +7,7 @@
import Observation import Observation
import LyrebirdSynth import LyrebirdSynth
@MainActor
@Observable @Observable
final class VectorOscillatorController { final class VectorOscillatorController {
+105 -9
View File
@@ -2,7 +2,7 @@
How to add Lyrebird to a project and scaffold the five kinds of app it supports: real-time, real-time + UI, non-real-time (offline) render, AUv3 plugin, and iOS. How to add Lyrebird to a project and scaffold the five kinds of app it supports: real-time, real-time + UI, non-real-time (offline) render, AUv3 plugin, and iOS.
The package is hosted at <https://realizedsound.mooo.com/josh/Lyrebird>. The package is hosted at <https://git.lyrebirdsynth.net/josh/Lyrebird>.
--- ---
@@ -29,7 +29,7 @@ let package = Package(
name: "MyPiece", name: "MyPiece",
platforms: [.macOS(.v15), .iOS(.v18)], platforms: [.macOS(.v15), .iOS(.v18)],
dependencies: [ dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"), .package(url: "https://git.lyrebirdsynth.net/josh/Lyrebird", from: "1.0.0"),
], ],
targets: [ targets: [
.executableTarget( .executableTarget(
@@ -100,14 +100,25 @@ Full reference: [`docs/tooling/cli-guide.md`](docs/tooling/cli-guide.md).
## Generating projects ## Generating projects
**First sound in 30 seconds** — the `quickstart` template is the shortest path from an installed CLI to audio:
```bash
lyrebird new MyFirstSound --template quickstart
cd MyFirstSound && lyrebird run # plays a 440 Hz sine for 10 seconds, then exits
```
That's a complete, self-contained Swift Package: a one-oscillator `SineTone`, the engine, and a `main` that starts it, sleeps 10 seconds, and stops. Read it, then reach for the richer templates below.
`lyrebird new <name> --template <template>` is the single entry point. The templates fall into two groups: **SPM-only** (a `Package.swift` + an `.xcworkspace` that references it — open and run with `swift`/Xcode, no `.xcodeproj`) and **Xcode-project** (ship a real `.xcodeproj`, needed for `.app`/`.appex` bundles, code signing, and iOS). `lyrebird new <name> --template <template>` is the single entry point. The templates fall into two groups: **SPM-only** (a `Package.swift` + an `.xcworkspace` that references it — open and run with `swift`/Xcode, no `.xcodeproj`) and **Xcode-project** (ship a real `.xcodeproj`, needed for `.app`/`.appex` bundles, code signing, and iOS).
| Template | Group | What you get | Driver | | Template | Group | What you get | Driver |
|---|---|---|---| |---|---|---|---|
| `basic` *(default)* | SPM-only | Minimal engine + `RunLoop.main.run()`. | `CoreAudioDriver` | | `quickstart` | SPM-only | **Fastest sound.** A one-oscillator `SineTone` that plays a 440 Hz tone for 10 seconds and exits — the shortest path to hearing Lyrebird. | `CoreAudioDriver` |
| `basic` *(default)* | SPM-only | Minimal engine + `RunLoop.main.run()` (no synth wired yet). | `CoreAudioDriver` |
| `demo` | SPM-only | A `SineTone` synth with `@LiveParam` frequency/amplitude. | `CoreAudioDriver` | | `demo` | SPM-only | A `SineTone` synth with `@LiveParam` frequency/amplitude. | `CoreAudioDriver` |
| `ui-demo` | SPM-only | AppKit window with `@UIParam` knobs + `LyrebirdWindow`. | `CoreAudioDriver` | | `ui-demo` | SPM-only | AppKit window with `@UIParam` knobs + `LyrebirdWindow`. | `CoreAudioDriver` |
| `nrt` | SPM-only | Renders to `output.caf`, no hardware needed. | `NRTDriver` | | `nrt` | SPM-only | Renders to `output.caf`, no hardware needed. | `NRTDriver` |
| `score` | SPM-only | Authors a `Score` with the notation DSL, exports `score.musicxml` (round-trips it), then renders the events offline to `.caf`. | `NRTDriver` |
| `macos-ui-xcode` | Xcode-project | macOS `.app` bundle (AppKit + SwiftUI), hardened runtime. | `CoreAudioDriver` | | `macos-ui-xcode` | Xcode-project | macOS `.app` bundle (AppKit + SwiftUI), hardened runtime. | `CoreAudioDriver` |
| `ios-ui` | Xcode-project | iOS `.app` (SwiftUI), with `AVAudioSession` activation. | `iOSAudioDriver` (RemoteIO) | | `ios-ui` | Xcode-project | iOS `.app` (SwiftUI), with `AVAudioSession` activation. | `iOSAudioDriver` (RemoteIO) |
| `auv3` | Xcode-project | AUv3 host `.app` + `aumu` `.appex` subclassing `LyrebirdAudioUnit`. | `AUv3Driver` | | `auv3` | Xcode-project | AUv3 host `.app` + `aumu` `.appex` subclassing `LyrebirdAudioUnit`. | `AUv3Driver` |
@@ -120,7 +131,9 @@ open <name>/<name>.xcworkspace # SPM-only & Xcode-project templates both shi
cd <name> && lyrebird run cd <name> && lyrebird run
``` ```
To develop against a local Lyrebird checkout instead of the remote URL (path dependency + an `XCLocalSwiftPackageReference` in the generated project): **Lyrebird dependency, default behaviour.** When run from a Lyrebird source checkout (e.g. `swift run LyrebirdCLI new …`), the scaffolder pins the generated project to *that same checkout* as a `path:` dependency (and an `XCLocalSwiftPackageReference` in Xcode-bearing templates). This keeps the emitted template source and the Lyrebird it builds against in lockstep — pre-1.0-stable, the published tag lags unreleased Score/Generator API. The CLI prints the chosen dependency, e.g. `Lyrebird dependency: local checkout at /Users/me/Documents/LyrebirdII`. If no local checkout is derivable (an installed binary with no source tree), it falls back to the published remote package and warns.
Override the checkout explicitly with `--lyrebird-path`:
```bash ```bash
lyrebird new <name> --template <t> --lyrebird-path /Users/me/Documents/LyrebirdII lyrebird new <name> --template <t> --lyrebird-path /Users/me/Documents/LyrebirdII
@@ -167,9 +180,9 @@ import LyrebirdSynth
import LyrebirdUI import LyrebirdUI
struct ContentView: View { struct ContentView: View {
@StateObject var synth = ToneSynth() // ToneSynth: SynthesizerBase with @UIParam let synth: ToneSynth // ToneSynth: SynthesizerBase with @UIParam
var body: some View { var body: some View {
ParameterKnob(value: synth.$frequency, in: 50...2000, label: "Freq") ParameterKnob("Freq", node: synth.$frequency, range: 50...2000)
} }
} }
``` ```
@@ -246,11 +259,92 @@ open MyApp/MyApp.xcworkspace # set your signing team, then run on device/si
The iOS template uses `iOSAudioDriver` (RemoteIO) and activates an `AVAudioSession` at launch; the synth/UI code is otherwise identical to the macOS UI template. The reference app is [`Demos/LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/). The iOS template uses `iOSAudioDriver` (RemoteIO) and activates an `AVAudioSession` at launch; the synth/UI code is otherwise identical to the macOS UI template. The reference app is [`Demos/LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/).
### 6. Score / notation (MusicXML + offline render)
```bash
lyrebird new MyScore --template score # aliases: score-musicxml, musicxml
cd MyScore && lyrebird run # writes score.musicxml, round-trips it, renders .caf
```
The `score` template authors music in the language-side **Score DSL** — a result-builder of `Note` / `Rest` / `Chord` / `Tuplet` with exact rational tuplet math (no float drift across nested ratios), spelling-aware pitches (`Note(.named(.c, 5))`), dynamics, and articulations. It exports MusicXML, parses it back for a round-trip sanity check, then schedules one self-freeing voice per `ScoreEvent` against an `NRTDriver`:
```swift
import LyrebirdSynth
let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
Note(.named(.e, 5), dur: .eighth.dotted, dyn: .mf)
Rest(dur: .eighth)
Tuplet(3, inTimeOf: 2) {
Note(.named(.g, 5), dur: .quarter)
Note(.named(.a, 5), dur: .quarter)
Note(.named(.b, 5), dur: .quarter)
}
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .tenuto)
}
Part("bass", channel: 1, clef: .bass) {
Note(.named(.c, 3), dur: .whole, dyn: .mp)
}
}
let xml = score.toMusicXMLString() // export
let restored = try Score.fromMusicXML(data: score.toMusicXMLData()) // round-trip
for event in score.allEvents { // flat, absolute-beat events (rests excluded)
let hz = event.pitch.frequency ?? 0
// schedule a voice at event.beat * secondsPerBeat for event.performedDuration …
}
```
Notable score features:
- **Notation model** — per-part `Clef` (`.auto` infers from pitch range), `KeySignature` (score-level + per-part override), `TempoChange` (measure-indexed), `RepeatStructure` / volta `Ending`, transposing-instrument `Transpose`, grace notes, chord ties, and nested tuplet brackets. These are notation-only — `flatten()` / playback use the base `bpm`.
- **MusicXML round-trip** — `score.toMusicXMLString()` / `.toMusicXMLData()` out, `Score.fromMusicXML(data:)` back. Spelling (letter + accidental, microtonal nine-step grid) is preserved.
- **Sounding vs. notated duration** — `ScoreEvent.duration` is notated; `event.performedDuration` applies `articulation.durationScale` for audio / MIDI note-off.
- **Playback** — `ScorePlayer` walks the flat event list against a `LyrebirdClock` on a `LyrebirdRoutine` (mirrors `MIDIFilePlayer`); SMF bridges via `Score+MIDIFile`.
- **Pitch / scale theory toolkit** — spelling-aware `Interval` / `Scale` / `PitchCollection` / 12-tone rows, diatonic-vs-chromatic transposition, scale-to-scale mapping; results drop straight into the DSL (`Note(.named(...))`). See [`docs/stdlib/theory.md`](docs/stdlib/theory.md).
The template writes both files into the **project root** (next to `Package.swift`) via `LyrebirdPaths.projectRoot()` — see [File output locations](#file-output-locations) — so output lands in the same place whether you run with `lyrebird run`, `swift run`, or Xcode.
Full guide: `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`. Reference project: [`Demos/LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/).
---
## File output locations
When a project writes files (an NRT `.caf`, a MusicXML export, a recording), *where* they land depends on how the binary is launched: `lyrebird run` / `swift run` set the working directory to the package root, but **Xcode sets it to `DerivedData`** and a bare binary inherits whatever shell launched it. Hardcoding `URL(fileURLWithPath: "out.caf")` therefore drops files in surprising places.
`LyrebirdPaths` (core `Lyrebird` module) resolves the common locations for you:
| Member | Resolves to | Use for |
|---|---|---|
| `LyrebirdPaths.projectRoot()` | Folder containing `Package.swift`, found by walking up from the **calling source file** at compile time. Returns `URL?`. | Dev-time render/export output you want beside your project, independent of launch method. |
| `LyrebirdPaths.documents` | `.documentDirectory` (`~/Documents` on macOS; the app sandbox Documents on iOS). | **Shipped apps** writing user-visible data. The right choice on iOS. |
| `LyrebirdPaths.applicationSupport` | `.applicationSupportDirectory` | App-managed data (presets, state) not meant to be user-visible. |
| `LyrebirdPaths.caches` | `.cachesDirectory` | Regenerable data the system may purge. |
| `LyrebirdPaths.temporary` | Per-process temp dir | Scratch files. |
| `LyrebirdPaths.home` | User home | — |
| `LyrebirdPaths.currentWorkingDirectory` | Process cwd | Equals project root under `lyrebird run`; a sensible `??` fallback for `projectRoot()`. |
| `LyrebirdPaths.desktop` *(macOS only)* | `.desktopDirectory`. Returns `URL?`. | Quick dev dumps. Needs an entitlement in a sandboxed app. |
```swift
import LyrebirdSynth
// Dev-time: write beside the project, regardless of launch method.
let dir = LyrebirdPaths.projectRoot() ?? LyrebirdPaths.currentWorkingDirectory
let cafURL = dir.appendingPathComponent("render.caf")
// Shipped app (iOS/macOS): write where the sandbox allows.
let userOut = LyrebirdPaths.documents.appendingPathComponent("render.caf")
```
`projectRoot()` is a compile-time, source-anchored path — it reflects where the binary was **built**, so it does not exist on another user's machine. Use it for development output only; use `documents` / `applicationSupport` in anything you distribute. It walks up to `Package.swift` by default; pass a dot-prefixed `marker: ".xcodeproj"` (or `.xcworkspace`) — matched by extension, so it finds `MyApp.xcodeproj` — for an Xcode-project layout with no manifest.
--- ---
## Xcode file templates ## Xcode file templates
Beyond whole projects, the CLI installs **New File…** templates so you can add a Generator, Synthesizer, Task, Oscillator, Filter, Spectral Processor, AUv3 source-slot synth, test suite, and more without boilerplate: Beyond whole projects, the CLI installs **New File…** templates so you can add a Generator, Synthesizer, Task, Oscillator, Filter, Spectral Processor, Score, AUv3 source-slot synth, test suite, and more without boilerplate:
```bash ```bash
lyrebird install-templates # New File… ▸ Lyrebird section appears in Xcode lyrebird install-templates # New File… ▸ Lyrebird section appears in Xcode
@@ -263,15 +357,17 @@ From a repo checkout you can equivalently run `bash scripts/install-xcode-templa
## Reference projects ## Reference projects
The repo ships six runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.xcworkspace`, covering every template above — start there to see complete, working code: The repo ships eight runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.xcworkspace`, covering every template above — start there to see complete, working code:
| Demo | Mirrors template | | Demo | Mirrors template |
|---|---| |---|---|
| [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | `quickstart` |
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | real-time CLI | | [`LyrebirdDemo`](Demos/LyrebirdDemo/) | real-time CLI |
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | `macos-ui-xcode` | | [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | `macos-ui-xcode` |
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | `ios-ui` | | [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | `ios-ui` |
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | `nrt` | | [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | `nrt` |
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | `score` |
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | `auv3` | | [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | `auv3` |
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | live-coding scratchpad | | [`LyrebirdScratch`](Demos/LyrebirdScratch/) | live-coding scratchpad |
See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for per-demo notes and gotchas. See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for per-demo notes and gotchas.
+781
View File
@@ -0,0 +1,781 @@
<!--
LINUX_PLAN.md
Lyrebird
Copyright (c) 2026 Joshua Parmenter / realizedsound
SPDX-License-Identifier: MIT
-->
# Lyrebird — Linux Support Plan
Hand-off plan for finishing Linux support. Branch:
`feasibility/cross-platform-linux-windows`. Companion docs:
`docs/cross-platform-feasibility.md` (how the port was done) and
`docs/windows-support-plan.md` (Windows, deferred).
**A next agent can pick this up cold from this file.** Every item lists what,
why, where (paths), first steps, and an acceptance check.
---
## 1. Current state (what already works)
The whole non-UI toolchain **cross-compiles to Linux**, verified from macOS:
| Target | musl SDK | glibc SDK |
|---|---|---|
| `LyrebirdSynth` (core engine + generators) | ✅ | ✅ |
| `LyrebirdGraphDSL` | ✅ | ✅ |
| `LyrebirdCLI` | ✗ (LineNoise `import Glibc`) | ✅ |
macOS/iOS builds are **byte-identical** to before the port (all Apple-only code
is behind `#if canImport(...)` or re-exported by `LyrebirdDSP`). Full macOS
suite (5644 tests) passes; the branch passed `/lyrebird_review` twice.
**Architecture that made this work** (do not undo):
- `Sources/LyrebirdDSP/` — a target that `@_exported import`s Accelerate + the
platform C-lib on Apple, and supplies portable scalar/FFT/biquad/vForce
fallbacks off Apple. Generator/synth code writes `import LyrebirdDSP` (never
`import Accelerate`/`import Darwin`) and carries **zero** platform `#if`.
- Portable WAV codec (`Sources/Lyrebird/Buffers/Wav*.swift`) replaces
`ExtAudioFile` off Apple.
- Platform-abstraction files keep their own local `#if`: `MonotonicClock.swift`,
`RTThreadIdentity.swift`, `PlatformCompat.swift` (OSStatus shim),
`AudioFileFormat+AudioToolbox.swift`.
### How to build / verify Linux locally (from a Mac)
Two cross-compile SDKs are installed (reusable):
```bash
# musl (static single binary; best for the core library)
TC=~/Library/Developer/Toolchains/swift-6.3.3-RELEASE.xctoolchain/usr/bin/swift
$TC build --swift-sdk aarch64-swift-linux-musl --target LyrebirdSynth --scratch-path .build-linux
# glibc / Ubuntu 24.04 (the target for CLI + real distros)
$TC build --swift-sdk 6.3.3-RELEASE_ubuntu_noble_aarch64 --target LyrebirdCLI --scratch-path .build-glibc
```
**Critical:** use the **swift.org** toolchain (path above), NOT Xcode's — the
Static Linux SDK's `Foundation.swiftmodule` was built by swift.org's compiler and
a mismatch buries the real errors under ~1244 bogus "Foundation compiled by older
compiler" errors.
The glibc SDK was generated with `swift-sdk-generator` (swift.org ships no
prebuilt glibc bundle). To regenerate:
`swift run swift-sdk-generator make-linux-sdk --distribution-name ubuntu --distribution-version 24.04 --swift-version 6.3.3-RELEASE`.
### Standing maintenance — after every `git merge main`
New generators land on main importing `Darwin`/`Accelerate` directly, which
breaks Linux. Every merge:
```bash
# 1. migrate any new unguarded imports to LyrebirdDSP:
grep -rlnE "^import Accelerate|^import Darwin" Sources/Lyrebird --include='*.swift'
# (skip RTThreadIdentity / MonotonicClock / DiskOutError — their Darwin is guarded)
# 2. new direct `stderr` / `fputs` usage breaks Linux — Swift 6 flags the imported
# C `stderr` global as "not concurrency-safe". Use the portable helper instead:
# core -> lyrebirdPrintError(_:) (Sources/Lyrebird/Utilities/StandardError.swift)
# LyrebirdCLI -> printError(_:) (Sources/LyrebirdCLI/StandardError.swift)
grep -rnE "\bfputs\b|\bstderr\b" Sources/Lyrebird Sources/LyrebirdCLI --include='*.swift'
# 3. delete Finder sync cruft that appears during merges:
find Sources Tests -regex '.* [0-9]+\.swift' -delete
# 4. rebuild Linux to confirm — cross-compile (both SDKs) AND, when Docker is
# available, run the suite natively (matches CI exactly). The stock swift
# image has no ALSA headers, so either add them (needed to compile
# ALSAAudioDriver) or opt out:
# docker build -t lyrebird-alsa - <<'DOCKERFILE'
# FROM swift:6.3.3
# RUN apt-get update && apt-get install -y --no-install-recommends libasound2-dev pkg-config
# DOCKERFILE
# docker run --rm -v "$PWD":/pkg -w /pkg lyrebird-alsa swift test
# # …or, without the ALSA package:
# docker run --rm -e LYREBIRD_DISABLE_ALSA=1 -v "$PWD":/pkg -w /pkg swift:6.3.3 swift test
```
**Scaffolded projects need their own check.** `swift test` never compiles the
source the CLI *emits*, so template regressions are invisible to it — that is
how the `nrt`/`score` templates came to reference a `LyrebirdCLI`-internal
symbol, and how they kept rendering to CAF (an Apple-only container that throws
off Apple) while still compiling. The gated suite builds **and runs** every SPM
template against this checkout:
```bash
LYREBIRD_RUN_BUILD_TESTS=1 swift test --no-parallel --filter ProjectScaffolderBuild
# …and inside the Linux container, where it matters most:
# docker run --rm -v "$PWD":/pkg -w /pkg lyrebird-alsa \
# bash -c 'LYREBIRD_RUN_BUILD_TESTS=1 swift test --no-parallel --filter ProjectScaffolderBuild'
```
Run it after touching `ProjectScaffolder` or any public API a template uses.
**Two arch/build gotchas the CI bring-up already paid for:**
- **BitBucket runners are x86_64; the Mac + its local Docker are arm64.** Some
breakage is x86-only and invisible on an arm64 box — e.g. C code that uses a
Darwin-only `<fenv.h>` macro under an `#if defined(__x86_64__)` branch compiles
on arm64 Linux (wrong branch, and note Linux arm64 predefines `__aarch64__`,
**not** Apple's `__arm64__`) but breaks on x86 glibc. To reproduce CI exactly,
emulate the runner arch locally:
`docker run --rm --platform linux/amd64 -v "$PWD":/pkg -w /pkg swift:6.3.3 swift test`.
- **A library-only build does not compile C target sources — only headers.**
`swift build --target LyrebirdSynth` (a library) will not surface a bad
`Sources/LyrebirdC/*.c`; the `.c` is compiled only when an executable/test
links it. So the build *gate* can be green while `swift test` fails. Always
verify with `swift test` (which links), not just the build gate.
### Verifying on macOS: always `swift test --no-parallel`
Plain `swift test` on macOS reports **~45 failures** on a clean tree. They are
**not real** — `--no-parallel` is the project's canonical command
(`docs/00-working-order.md` step 1) and the full suite passes under it.
The flakes are main-thread starvation, concentrated in `LyrebirdProcess`,
`LyrebirdEventList*`, `RoutineTests` and `ActorIsolationGuardTests`: those tests
dispatch to the main queue and then wait on a wall-clock timeout, while the
parallel runner has `@MainActor` suites saturating main. Recognisable by the
message shape — `got 0 of 3`, `.timedOut`, `Body should have entered`,
`Expected ~0.2s between events, got 2.3s` — never a wrong numeric result.
Parallel is also *slower* here (≈286 s vs ≈94 s), so there is no reason to use
it. Phase 148 fixed an earlier batch in these same suites; residual
parallel-only flakes are recorded in `docs/01-completed-working-order.md`.
**Do not debug these before re-running serially.** If a failure is suspected to
be real, the cheap discriminator is a clean-tree baseline: `git worktree add
<tmp> HEAD` and run the same command there — a failure present at HEAD is not
yours.
Linux in-container runs (`docker run … swift test`) have not shown this; the
affected suites are macOS-host-only, so CI is unaffected.
### IDE for Linux
**VS Code + the official Swift extension** (`swiftlang.swift-vscode`) —
SourceKit-LSP, LLDB, test explorer, SPM. Best-maintained non-Xcode path.
---
## 2. Remaining work — prioritized
Ordered by value for a *usable* Linux Lyrebird. Items 1–3 make it real; 4–8 are
capability/coverage.
**Status board** (update the box when an item lands; each item's own heading
carries the same marker):
| # | Item | Priority | Status |
|---|---|---|---|
| 3 | Linux CI lane | HIGH | ✅ done — green on BitBucket |
| 2 | Golden DSP tests on Linux | HIGH | ✅ done — 6 goldens green in CI |
| 1 | `ALSAAudioDriver` (live audio) | HIGH | ◑ plays on hardware; deeper checks pending |
| 6 | DiskIn + buffer file I/O | MEDIUM | ✅ done — WavFileReader backend |
| 4 | MIDI on Linux | MEDIUM | ⚠️ built, untested on hardware |
| 5 | OSC on Linux | MEDIUM | ✅ done — POSIX UDP, loopback-verified |
| 8 | SwiftOpenUI GUI spike | EXPLORATION | ✅ drag works on hardware (@State + @Observable patch); patch PR-ready |
| 7 | CLI on musl (LineNoise) | LOW | ☐ decision |
### Item 1 — `ALSAAudioDriver` (live audio) — HIGH — ⚠️ BUILT, NOT YET HEARD
**What:** A driver conforming to `AudioDriver` that opens a Linux audio device
and calls `engine.processBlock(inputSamples:)` from a render thread.
**Why:** Without it, Linux only does offline NRT-to-WAV. This is the capability
that makes Linux usable.
**Delivered:** `Sources/Lyrebird/AudioDrivers/ALSAAudioDriver.swift` — a
blocking `snd_pcm_writei` loop on a dedicated thread, the shape the plan
recommended (no callback re-entrancy, no ALSA async-handler restrictions,
back-pressure straight from the device). **Full reference:
`docs/engine/alsa-audio-driver.md`** — transport, duplex, xrun policy,
lifecycle, and the build requirement; that document is canonical, this section
is the plan-level summary.
**Do not name a driver in portable code** — call `makeDefaultAudioDriver()`
(`AudioDrivers/DefaultAudioDriver.swift`), which resolves to `iOSAudioDriver` /
`CoreAudioDriver` / `ALSAAudioDriver` / `OfflineDriver` from *inside* the
module. Which drivers exist is not a function of the OS alone (a Linux build
without libasound, or one cross-compiled from macOS, has no ALSA), so a
consumer-side `#if` is guessing. `isLiveAudioAvailable` reports whether the
build has any live backend at all.
- **Format** `SND_PCM_FORMAT_FLOAT_LE`, matching the engine's `Float` buses, so
nothing in the path converts or dithers.
- **Setup** via `snd_pcm_set_params` (ALSA's own convenience over the
hw/sw-params dance), latency = `blockSize × periodsPerBuffer / sampleRate`.
- **Duplex** when the engine asks for input channels: a capture PCM is opened
and `snd_pcm_link`ed to playback so the two cannot drift; `linkedStreams`
reports whether the kernel accepted the link.
- **RT thread** marks itself via `RTThreadIdentity.markCurrentThreadAsRT()`,
calls `enableFlushToZero()`, and requests `SCHED_FIFO` at 75 % of the policy
range — denial is normal for an unprivileged process and is reported through
`hasRealtimePriority` rather than failing the start.
- **No allocation in the loop**: interleave/deinterleave staging buffers are
raw pointers allocated in `setup(engine:)`.
- **Xrun policy** is factored out into `ALSARecoveryAction.classify(_:)` —
`-EINTR`/`-EAGAIN` retry, `-EPIPE`/`-ESTRPIPE` recover via `snd_pcm_recover`,
anything else stops the loop and lands in `lastError`. The errno values are
spelled out as Linux constants rather than taken from the host's `errno.h`,
so the classification cannot differ per platform (`EAGAIN` is 11 on Linux, 35
on Darwin) and the tests mean the same thing everywhere.
**Build requirement — libasound2-dev.** The `CALSA` system-library target
(`Sources/CALSA/`) needs ALSA's headers. `Package.swift` adds that target only
when the manifest is evaluated **on a Linux host**, so:
- macOS/iOS builds never see it (verified: `swift build`/`swift test` unchanged).
- **Cross-compiling to Linux from a Mac produces a binary with no live-audio
driver** — the host is macOS, so `CALSA` is absent and the driver compiles
away. Build natively on Linux to get audio out; cross-compiles remain
offline-only.
- A native Linux build without the package fails with
`error: 'alsa/asoundlib.h' file not found` → `could not build C module 'CALSA'`.
Fix: `apt-get install libasound2-dev pkg-config`, which the CI lane now does.
Escape hatch for a box that deliberately has no audio stack:
`LYREBIRD_DISABLE_ALSA=1 swift build` (verified — everything but the driver
builds).
**Verified (headless):** 11 new tests in `LyrebirdPortableTests`, green on
macOS and on Linux arm64 + x86_64:
- interleave/deinterleave: frame order, missing channel → silence, short bus →
padded, round-trip identity, extra channel dropped (all platforms — a
transposed index here yields channel-swapped audio, not an error, which is
exactly what nobody notices on a headless box);
- `ALSARecoveryAction` classification of every branch (all platforms);
- Linux-only: `start()` before `setup` throws `.notConfigured`; an unopenable
device throws `.playbackDeviceOpenFailed` and leaves `lastError` clear;
repeated/early `stop()` is safe; defaults and `suggestedControlBlockSize`.
These also serve as the guard that the driver is actually *in* the build — if
the `CALSA` dependency ever stops resolving, the whole file compiles away to
nothing and every other test would still pass.
**Acceptance — basic playback CONFIRMED on hardware.** On an Ubuntu 24.04 arm64
Parallels VM (2026-08-21), the `quickstart` template played its 10-second sine to
the speakers via `makeDefaultAudioDriver()` → `ALSAAudioDriver`. The driver moves
a real speaker — the headline capability is proven. Still to exercise on hardware:
1. ~~sine to speakers~~ ✅ (confirmed at the template default rate; still worth a
pass at both 44.1 and 48 kHz and a couple of block sizes);
2. xrun recovery under load (the `-EPIPE` path is written but never taken);
3. duplex: confirm `snd_pcm_link` succeeds on a real duplex device and that
input reaches the engine;
4. `SCHED_FIFO` grant under a `limits.conf`-configured user;
5. latency sanity vs `periodsPerBuffer`.
Basic output is no longer unproven; the robustness checks (2–5) remain open.
**Follow-ups, deliberately not done here:**
- **PipeWire backend.** ALSA-through-PipeWire's compat layer works, but a native
PipeWire driver is the better long-term desktop path. `AudioDriver` is the
seam; nothing in this driver blocks it.
- ~~**Scaffolder templates emit `CoreAudioDriver()`**~~ ✅ **done** — the CLI
templates (`quickstart`, `basic`, `demo`) now emit
`makeDefaultAudioDriver()`. The first attempt emitted the
`#if canImport(AudioToolbox)` switch in the *generated* source; review caught
that this breaks exactly where it matters — Windows, a cross-compiled Linux
build, and `LYREBIRD_DISABLE_ALSA=1` all lack `ALSAAudioDriver`, so the
emitted `#else` would not compile. Hence the library-side factory. The
`ui-demo` and Xcode templates keep `CoreAudioDriver` deliberately: they import
AppKit / are Xcode projects, so they are Apple-only by construction.
Also fixed here: the `nrt` and `score` templates emitted `printError(...)`, a
helper that exists only inside the `LyrebirdCLI` target, so **every
scaffolded `nrt`/`score` project failed to compile** — a regression from the
earlier stderr port on this branch. They now emit a self-contained
`FileHandle`-based helper. All five CLI templates are verified by scaffolding
and **building** them in the Linux container, not by string inspection.
### Item 2 — Golden-value DSP tests that run on Linux — HIGH — ✅ DONE
**What:** Tests asserting concrete numeric output of the portable FFT/biquad
**through the real generators**, runnable off Apple.
**Why:** `Tests/LyrebirdDSPTests/ScalarDSPParityTests.swift` compares to *real
vDSP* and is therefore `#if canImport(Accelerate)` — **Apple-only**. Nothing
verified that the portable DSP produces correct *audio* on Linux; a packing or
scaling bug in the portable FFT would have shipped silently.
**Delivered:** a new platform-neutral test target `LyrebirdPortableTests`
(`Tests/LyrebirdPortableTests/`, in the main `targets:` array so a Linux host
sees it) holding **6 golden-value tests**, no `#if` guards anywhere:
| Test | Portable code it pins |
|---|---|
| `butterworthLowPassOrder4ImpulseResponse` | `vDSP_biquadD` opaque-setup cascade (`PortableBiquad.swift`) |
| `butterworthHighPassOrder2ImpulseResponse` | same, different coefficient path |
| `klankImpulseResponse` | vector kernel — `vsmulD` / `vmulD` / **`vsubD`** / `sveD` |
| `resonatorBankImpulseResponse` | same kernel, `(freq, decay, amp)` spec order |
| `analysisMagnitudeSpectrumOfBinCentredSine` | forward `vDSP_fft_zrip` + `ctoz` packing and real-FFT scaling |
| `resynthesisReconstructsInputSine` | inverse FFT + windowed overlap-add round trip |
Goldens were captured on macOS (arm64, vDSP-backed) and are compared with a
`absolute + relative × |golden|` tolerance — `1e-9` for the double-precision
filter responses, `1e-5` for the `Float`-internal spectral paths.
`Tests/LyrebirdPortableTests/PortableTestSupport.swift` holds the local
engine/collect helpers (test targets cannot share sources) and deliberately uses
only the public + `@_spi(LyrebirdExtensions)` surface.
**Both directions of the check were verified** (a golden test that cannot fail is
worse than none):
- swapping `vDSP_vsubD`'s operands in `AccelerateShim.swift` → Klank and
ResonatorBank fail on Linux with diffs of `1e7`+ (the classic vDSP
reversed-operand bug, caught).
- swapping real/imag in `vDSP_ctoz` (`PortableFFT.swift`) → both spectral tests
fail with diffs of ~0.29 on a unit-amplitude sine.
Each sabotage was reverted immediately after the run.
**Verified green:** macOS (`swift test --no-parallel`, vDSP path — see the
serial-run note above) and Linux in-container on
both architectures — `docker run --rm [--platform linux/amd64] -v "$PWD":/pkg
-w /pkg swift:6.3.3 swift test` — so the CI lane (Item 3, x86_64 runners) runs
them on every push with no config change; only the explanatory comment in
`bitbucket-pipelines.yml` was updated.
**Regenerating a golden** (only after establishing the change was intended —
unexplained drift is the bug this target exists to catch): run the same graph on
macOS and print each sample with `String(format: "%+.15e")`.
**Not done here (deliberate):** the ~165 files of `LyrebirdTests` are still
macOS-host-only. Most are platform-neutral and could migrate to
`LyrebirdPortableTests` over time, which would widen Linux coverage well beyond
DSP; that is bulk mechanical work, independent of this item, and best done in
slices rather than as one move.
### Item 3 — Linux CI lane — HIGH — ✅ DONE
**What:** CI building + testing on Linux.
**Why:** Locks in the port so a main-merge can't silently regress it (see the
standing-maintenance hazard). CI is also the only place tests actually *run* on
Linux without a local Linux box.
**Delivered:** `bitbucket-pipelines.yml` (the repo remote is BitBucket, not
GitHub) using the official `swift:6.3.3` image. `size: 2x` (8 GB). Builds
`LyrebirdSynth` / `LyrebirdGraphDSL` / `LyrebirdCLI`, then `swift test` runs
every target the Linux manifest exposes: **LyrebirdDSPTests, LyrebirdGraphDSLTests,
LyrebirdCLITests — 239 tests, all green** natively in-container.
**Verified locally** in the same image via Docker Desktop (arm64):
`docker run --rm -v "$PWD":/pkg -w /pkg swift:6.3.3 swift test`.
Supporting changes made to get here:
- **Manifest split** (`Package.swift`): the Apple-only targets — `LyrebirdUI`,
`LyrebirdUITests`, `LyrebirdTests` (imports `AudioToolbox` directly in some
files), and `LyrebirdBenchmark` (micro-benchmarks vDSP) — are appended under
`#if os(macOS)` *after* the `Package(...)` initializer (an `#if` cannot be an
array element in a manifest). On a Linux/Windows host they are simply absent,
so `swift test` compiles only the portable surface. macOS/iOS builds see every
target unchanged; the two remaining test targets' `AudioToolbox`/`Accelerate`
links are now `.when(platforms: [.macOS, .iOS])`.
- **Core `stderr` fix**: a `git merge main` had landed
`fputs(..., stderr)` in `Score/ScoreElementDSL.swift`, which fails Swift 6
concurrency checking on Linux — the exact standing-maintenance hazard. Added
`Utilities/StandardError.swift` (`lyrebirdPrintError(_:)`, `FileHandle`-based)
and routed the call through it. Grep guard added to the maintenance list above.
**Registry compile-memory (resolved):** the generated
`Sources/LyrebirdGraphDSL/Generated/GeneratedDSLRegistry.swift` used to be one
~300-element array literal; the type-checker checked it as a single expression and
needed several GB, so two concurrent heavy compiles OOM-killed the compiler on an
8 GB runner. Fixed in `Tools/DSLRegistryGen`: `emitRegistry` now emits the entries
as fixed-size (`registryChunkSize = 32`) `private static let _chunkN` arrays
concatenated into `generated`, so each chunk type-checks independently. Verified
building at full parallelism on Linux from a clean scratch — no OOM — so CI runs
default `-j` (no cap). Regenerate with `bash scripts/generate-dsl-registry.sh`
after changing a public generator init; the `--check` drift guard stays green.
**Acceptance:** green CI on push to the branch — Pipelines is enabled on the
BitBucket repo.
### Item 4 — MIDI on Linux — MEDIUM — ⚠️ BUILT, NOT YET RECEIVED FROM HARDWARE
**What:** `Sources/Lyrebird/MIDI/` was `#if canImport(CoreMIDI)`-guarded out, so
there was no MIDI in/out on Linux.
**Delivered:** an ALSA-sequencer backend behind the same `MIDI` public API as the
CoreMIDI one.
- **Shared, tested mapping.** `MIDI/ALSASeqMIDIEvent.swift` — a pure enum +
`midiMessage(for:)` that turns a decoded seq event into a `MIDIMessage`,
routing channel-voice events through the existing
`MIDIMessage.from(status:data1:data2:)` so Linux applies the identical parsing
(note-on velocity 0 → note-off, the pitch-bend offset) the CoreMIDI path does.
Pure Swift, no ALSA import, so it is unit-tested on **both** platforms
(`ALSASeqMIDIEventTests`, 8 tests).
- **The backend.** `MIDI/ALSAMIDI.swift`, guarded
`#if !canImport(CoreMIDI) && canImport(CALSA)`, defines `MIDI` for native
Linux: `snd_seq_open`, in/out simple ports, source enumeration
(`snd_seq_query_next_client/port`), auto-subscribe to readable sources, a
`poll()`-based input thread (200 ms cadence so `stop()` is responsive) that
decodes events via the shared mapping and dispatches on the `lyrebird.midi`
queue, and `send` / `sendVirtual` building seq events from `MIDIMessage`.
The handler registry, dispatch contract, and lifecycle discipline mirror the
CoreMIDI class; the two definitions are mutually exclusive so exactly one
`MIDI` compiles per platform.
- `MIDISource` / `MIDIDestination` are now cross-platform: `endpointRef` on
Apple, ALSA `client:port` off Apple. `MIDIError` gained `Equatable` and its
`OSStatus`-carrying cases double as ALSA return-code carriers (`OSStatus` is
`Int32` off Apple). `MIDIMessage` / `+UMP` / `MIDIHandlerToken` were already
neutral.
**Availability:** like `ALSAAudioDriver`, `MIDI` exists on Linux only where
CALSA is linked — absent under `LYREBIRD_DISABLE_ALSA=1` or a cross-compile from
macOS. Consumers that need MIDI everywhere must guard accordingly.
**Verified (headless):** `ALSAMIDITests` (Linux-only) — handler registry, the
not-started send/create guards, safe repeated stop, empty pre-start
enumeration, and a tolerant start/stop that accepts either a real open or a
clean `clientCreateFailed` when `/dev/snd/seq` is absent (the container case),
checking a failed start does not latch `isStarted`. macOS
`swift test --no-parallel` 5714/5714; Linux arm64 302 / x86_64 302;
`LYREBIRD_DISABLE_ALSA=1` 289.
**Acceptance NOT met — no controller has been received from.** The container has
no sequencer device, so the poll loop, event decode from a live controller,
subscription, and `send` to real hardware have never run. Outstanding on a Linux
box with ALSA + a connected controller:
1. receive note-on / note-off / CC / pitch-bend / program-change from a
controller and confirm the decoded `MIDIMessage`;
2. `send` to a hardware synth and hear it;
3. `createVirtualInput` / `createVirtualOutput` visible to other clients
(`aconnect -l`) and round-trip;
4. hot-plug: a controller connected after `start()` appears (the poll loop does
not currently re-enumerate — see below).
**Known limitations / follow-ups:**
- **No hot-plug re-enumeration.** CoreMIDI's `MIDIClientCreateWithBlock`
notification re-runs `_refreshEndpoints` / `_connectAllSources`; the ALSA
backend enumerates and subscribes once at `start()`. A device connected later
is not auto-subscribed. ALSA exposes this via the System announce port
(subscribe to client 0 port 1 and handle `SND_SEQ_EVENT_PORT_START`); left as
a follow-up.
- **UMP / MIDI 2.0.** The CoreMIDI path sends MIDI 1.0 over the UMP API; the
ALSA path is MIDI 1.0 via legacy seq events. Functionally equivalent for the
`MIDIMessage` set; a native UMP seq path is not implemented.
### Item 5 — OSC on Linux — MEDIUM — ✅ DONE
**What:** `OSCClient` / `OSCServer` used Apple's `Network.framework`
(`NWConnection` / `NWListener`), guarded out on Linux.
**Delivered:** POSIX BSD-socket transports under `#else`, no dependencies. The
OSC 1.0 codec (`OSCArgument` / `OSCCodec` / `OSCMessage`) was already portable;
only the transport was swapped, and the handler registry / decode+dispatch is
now shared code rather than living inside the `Network` guard.
- `OSCClient`: a connected UDP socket (`getaddrinfo` → `socket` → `connect`),
opened lazily on the first send on the serial `sendQueue`, reused after. A
resolution/connect failure is latched so a bad host does not re-resolve every
send. `sendto` with a nil destination avoids the name clash with the class's
own `send`.
- `OSCServer`: `socket` + `SO_REUSEADDR` + `bind` to `INADDR_ANY:port`, then a
dedicated receive thread running a `poll()` loop (200 ms cadence) that
`recv`s datagrams and hands them to the shared decode+dispatch. `stop()`
shuts the socket down (unblocking any wait), clears the run flag, joins, and
closes — the same discipline as the ALSA backends. New `OSCServerError`
(`socketFailed` / `bindFailed`, carrying `errno`) is thrown off Apple; on
Apple `NWListener` throws its own error. `OSCHandlerToken` moved out of the
`Network` guard so it exists on both platforms.
**Acceptance MET — verified over real loopback, on both platforms.** Unlike the
ALSA MIDI and audio backends, OSC needs no hardware: `OSCLoopbackTests`
(`Tests/LyrebirdPortableTests`) binds an `OSCServer` on 127.0.0.1 and sends to it
with `OSCClient`, asserting a full argument round trip, glob-pattern address
matching, that a removed handler stops receiving, and safe idempotent stop. It
exercises `Network.framework` on macOS and the POSIX transport on Linux, and
passes on both — including **Linux without ALSA** (OSC is pure POSIX, so it does
not depend on CALSA and runs under `LYREBIRD_DISABLE_ALSA=1`). macOS
`swift test --no-parallel` 5718/5718; Linux arm64 306 / x86_64 306;
`LYREBIRD_DISABLE_ALSA=1` 293.
### Item 6 — DiskIn + LyrebirdBuffer file I/O on Linux — MEDIUM — ✅ DONE
**What:** `Generators/BufferIO/DiskIn.swift` and `Buffers/LyrebirdBufferFileIO.swift`
were fully `#if canImport(AudioToolbox)`-guarded (no portable fallback), so
soundfile-into-buffer loads and disk streaming did not exist off Apple.
**Delivered:** portable `#else` branches on the `WavFileReader` /
`WavFileWriter` backend, mirroring `DiskOut` / `NRTDriver`:
- `LyrebirdBuffer.load` / `loadAllChannels` / `fill` read WAV via
`WavFileReader`; the chunked read + channel-extract + optional peak
normalisation is replicated in two portable helpers
(`portableReadMono` / `portableReadAllChannels`). `channelOutOfRange` /
`invalidChannelCount` stay cross-platform; open/read failures surface as
`WavFileError` (matching the documented `NRTDriver` decision, rather than
wrapping).
- `LyrebirdBuffer.write` gains a `WavFileWriter` branch (RF64 already went
through the portable `RF64Writer` on both platforms); the Apple-only
containers throw a new `LyrebirdBufferIOError.unsupportedFormatOnPlatform`.
- `DiskIn.Audio` streams via `WavFileReader`, reopening the file to loop (the
reader is forward-only). **Sample-rate handling:** `ExtAudioFile` resamples
to the engine rate transparently; the portable reader hands back the file's
native frames, so `DiskIn` folds `fileSampleRate / engineSampleRate` into the
read-position advance (`_readRateScale`, `1.0` on Apple) — a 44.1 kHz file on
a 48 kHz engine plays at the right speed and pitch via the existing linear
interpolation. The buffer-load paths do **not** resample on either platform
(they keep the file's own rate), so no scale is needed there.
- `LyrebirdBufferIOError` split: the `OSStatus` cases are Apple-only; the
semantic cases (`channelOutOfRange`, `invalidChannelCount`,
`fileTooLargeForContainer`) are cross-platform; `unsupportedFormatOnPlatform`
is added off Apple. `DiskInError` stays Apple-only — the portable `DiskIn`
throws `WavFileError`.
**Verified:** new `Tests/LyrebirdPortableTests/PortableFileIOTests.swift` —
mono/stereo load round trips, channel select, `channelOutOfRange`, fill
truncate + zero-pad, peak normalisation, int16 write→load round trip, DiskIn
sample-accurate streaming at matching rate, and (off-Apple only) DiskIn
sample-rate-ratio folding + `write` to a CAF throwing
`unsupportedFormatOnPlatform`. Fixtures are written with `WavFileWriter`, so the
suite runs on both platforms; on Apple the same paths exercise `ExtAudioFile`
and a round trip that agrees on both is the guarantee. macOS
`swift test --no-parallel` 5706/5706; Linux arm64 + x86_64 289/289;
`LYREBIRD_DISABLE_ALSA=1` 281/281.
**One test is portable-only by nature:** the SR-ratio DiskIn test is
`#if !canImport(AudioToolbox)`, because on Apple `ExtAudioFile` does the
conversion inside `DiskIn` (advancing at rate 1) and the exact file-frame
mapping the test asserts only holds for the portable read-position scaling.
### Item 7 — CLI on musl (LineNoise) — LOW / decision
**What:** `LyrebirdCLI` builds on glibc but not musl — the `LineNoise`
dependency does `import Glibc` with no `Musl` support.
**Why / decision:** glibc is the standard Linux target, so this is optional.
Options: (a) accept CLI = glibc-only (recommended); (b) fork/patch LineNoise for
`Musl`; (c) swap the line-editing dependency. Document the choice; don't spend
effort unless a static-musl CLI binary is specifically wanted.
### Item 8 — GUI spike: **SwiftOpenUI** for `LyrebirdUI` on Linux — EXPLORATION
**What:** Evaluate `codelynx/SwiftOpenUI` (MIT) as the path to run `LyrebirdUI`
on Linux. It is a SwiftUI-API reimplementation: **on macOS it imports real
SwiftUI**; on Linux it renders via **GTK4** (needs `libgtk-4-dev`) — the same
"real API on Apple / portable backend elsewhere" pattern Lyrebird already uses
for `LyrebirdDSP`.
**Why it looks reasonable:** its coverage matches what `LyrebirdUI` actually
needs — `Canvas`/`Path`/`Circle`/`Rectangle` (the knobs, scope, and envelope
views are custom-drawn), drag/tap gestures (the XY pad), and the
`@State`/`@Binding` wrappers that `@UIParam` builds on. MIT-licensed.
**Risks / unknowns (why it's a spike, not a commitment):**
- Maturity is modest (~31 stars, effectively one author) — bus-factor risk; the
"Stable" self-label is optimistic. SwiftUI reimplementations always have edge
gaps.
- Lyrebird's AppKit `NSEvent` mouse monitor (`MouseInputBridge`, installed via
`MouseInput.install(_:)`) is Apple-only — a GTK input path is needed for the
mouse-driven generators.
- `@UIParam` (`Sources/LyrebirdUI/`) + `ParameterKnob`/`Slider`/`XY`/scope/
envelope views must actually compile + render against SwiftOpenUI's surface.
**Compile-probe done (container, no display) — the hard 20% answered.**
`codelynx/SwiftOpenUI` (`develop` @ 8100d9c, MIT). Modules `SwiftOpenUI` +
`BackendGTK4` (a `.systemLibrary` on `libgtk-4-dev`). Built the framework **and a
LyrebirdUI-style Canvas knob** in a GTK4 container (`swift:6.3.3` + `libgtk-4-dev`):
SwiftOpenUI + BackendGTK4 compile on Linux, and the knob (custom drawing +
`@Observable` model + drag) compiles. What the probe found:
- **`GraphicsContext` is NOT provided — this is the shim.** SwiftOpenUI's
`Canvas(renderer: { ctx, size in … })` hands back a **Cairo-backed
`DrawingContext`** (`setColor` / `moveTo` / `lineTo` / `arc` / `stroke()` /
`fill()`), not SwiftUI's `GraphicsContext`. So every LyrebirdUI custom-drawn
view — `ParameterKnob`, `LyrebirdScopeView`, `LyrebirdEnvelopeView`,
`LyrebirdSpectrumView`, `LyrebirdScatterView` (the 9 `Canvas` + 6
`GraphicsContext` call sites) — needs its drawing body **rewritten** from
`GraphicsContext.fill/stroke/draw` to `DrawingContext`. The rewrite is
mechanical (both are imperative 2-D drawing) and was proven to compile, but it
is per-view work, not a drop-in.
- **`@Observable` works on Linux (stdlib `Observation`), but SwiftOpenUI does not
re-export it** — a consumer must add `import Observation` explicitly (real
SwiftUI re-exports it). SwiftOpenUI's `DependencyTracking` claims
`@Observable`-driven rebuilds, so `@UIParam`'s backing model should drive
re-renders — but that is runtime behavior still to confirm on a display.
- **Gestures fit.** `.onDrag { (d: DragGestureValue) in … }` carries
`translation`, which is what the knob/XY drags need; the closure shape differs
from SwiftUI's `DragGesture().onChanged`, so a light rewrite.
- Declarative controls (`Slider`, `Button`, `Text`, `VStack`/`HStack`) and the
`@State`/`@Observable` binding port with light friction.
**Update 10 — RESUME with fork patches (2026-09-05).** Re-verified upstream
`develop @ 8100d9c` still has the observation→full-rebuild→gesture-teardown
(`GTKViewHost.rebuild()` still gates the narrow path on `!fromObservation`); no
`@GestureState`, no gesture-identity reconciliation. Confirmed the blocker lives
in the GTK4 render/gesture layer, **below** the state wrappers — so no
`@State`/`@Binding`/`@Observable` choice routes around it (the single-control
`@State` "success" is an artifact of Problem 1's idle-starvation masking Problem
2). Decision: **keep the SwiftUI path for the Linux pre-release** and fix it in
the fork. Two patches planned (B: live redraw via high-priority `queue_draw`
during drag; C: reuse the existing `beginInteractiveUpdate`/`endInteractiveUpdate`
deferral so no rebuild recreates the gesture mid-drag). Full plan, fork-commit
strategy, and validation: **`spikes/SwiftOpenUIKnob/FORK_PATCH_PLAN.md`**.
Patches are the next work session.
**Update 9 — INTERACTIVE-UI BLOCKER (hardware, 2026-08-22). All 8 views build
and the timer-driven ones work; live drag interaction does NOT.** On-hardware
testing of the full demo found two distinct SwiftOpenUI GTK4-backend problems,
both root-caused from the pinned fork source. Both are BEYOND the drag-observable
patch already submitted upstream (that patch fixed single-control gesture
*streaming*, which does work — see below).
What works on hardware: the scope animates, the CPU meters update, audio tracks
live (dragging a knob changes the sound continuously). What fails: the *visual*
of interactive controls.
Bisected with `LYREBIRD_DEMO={knob,controls,full}` (diagnostic scaffolding in
`Sources/LyrebirdUILinuxDemo/`, commit 22dd5b6a — kept until this is resolved):
- `knob` (one knob): gesture STREAMS (sound tracks continuously), but the knob
Canvas only redraws on mouse-UP.
- `controls` (all controls, no animated views): knob/XY drop back to one tick per
gesture; native slider moves but its sound update only lands on mouse-up.
- `full`: scope animates; every interactive control is one-tick.
Root causes (in `.build-*/checkouts/SwiftOpenUI/Sources/Backend/GTK4/Rendering/`):
1. **Idle-starved redraw (Problem 1).** `GTKViewHost.scheduleRebuild` schedules
the redraw with plain `g_idle_add` (default idle priority). During a continuous
drag, higher-priority pointer-motion events saturate the GLib loop and starve
the idle rebuild, so the Canvas only redraws when motion stops (release). Audio
is unaffected because `node.update(_:)` runs directly in the `onChanged`
closure, not via a rebuild. Fix direction: high-priority `gtk_widget_queue_draw`
on the Canvas during drag, not an idle-scheduled full-tree rebuild.
2. **Drag-gesture teardown under sibling rebuilds (Problem 2).** With several
controls bound to one node, a drag triggers a mid-drag rebuild that recreates
the dragged Canvas widget → the `GtkGestureDrag` detaches → one tick. The
single-control case only survives because its rebuild is idle-starved (so the
widget is never recreated during the drag). Fix direction: reconcile the drag-
gesture widget by IDENTITY so it survives rebuilds — exactly the preferred fix
in `spikes/SwiftOpenUIKnob/UPSTREAM_ISSUE.md`, and the drop-target code
(`GTKDropState` widget-pinning) is the in-repo precedent.
Decision (2026-08-22): PAUSE the interactive-UI push and gauge the SwiftOpenUI
maintainer's responsiveness on the submitted PR first. If it is accepted → dig
into Problems 1 & 2 (extend the issue/PR). If rejected with rationale → iterate.
If it goes stale → reconsider the Linux UI approach (swift-cross-ui, or a thinner
GTK layer). Not blocking anything else on the branch — the headless core, audio,
scope/CPU readouts, and static views are all fine; only live *dragging* is
affected. Investigation cost is already paid and captured here, so resuming does
not require re-bisecting.
**Update 8 — control + visualization set ported.** All eight `LyrebirdUI`
controls/views now have `Linux*` counterparts in `LyrebirdUILinux`:
`LinuxParameterKnob` / `Slider` / `Label` / `Button` / `XY` (controls) and
`LinuxScopeView` / `LinuxEnvelopeView` / `LinuxStatusView` (visualization). The
animated views (scope, CPU status) use an `@Observable` model polled by a
Foundation `Timer` on `RunLoop.main` (pumped by the GTK4 backend), NOT
SwiftOpenUI's off-main `.task`. See Update 9 for the interaction blocker found
when these were tested together on hardware.
**Update 7 — symmetric import shape + runnable demo.** Two ergonomics changes
so friends can clone and run:
- **Re-export shims** give both platforms one import shape. `LyrebirdUILinux`
gets `LinuxUIExports.swift` (`@_exported import SwiftOpenUI` +
`@_exported import BackendGTK4`); the macOS `LyrebirdUI` gets
`LyrebirdUIExports.swift` (`@_exported import SwiftUI`). Downstream code is
then `import LyrebirdSynth` + one `#if canImport(LyrebirdUI)` selecting
`LyrebirdUI` (Apple) vs `LyrebirdUILinux` (Linux); body code beneath is
identical because both bind the same core `@UIParam`/`UIParamNode`. In-repo
precedent for `@_exported`: `Sources/LyrebirdDSP/AccelerateShim.swift`.
- **Runnable demo** — new `LyrebirdUILinuxDemo` executable target (opt-in, same
`LYREBIRD_ENABLE_LINUX_UI=1` gate): `KnobDemoSynth` (`@UIParam`
frequency/amplitude sine → `Pan2`), `KnobDemoView` (two `LinuxParameterKnob`s),
and a `main.swift` that starts the engine on `makeDefaultAudioDriver()` (ALSA
if present, else silent Offline) then runs the GTK4 loop. Run with
`LYREBIRD_ENABLE_LINUX_UI=1 swift run LyrebirdUILinuxDemo`. Turn the freq knob,
hear the pitch track (needs a live ALSA device; GUI works regardless).
**Next steps (full cross-platform `LyrebirdUI` merge — deferred).** The symmetric
shape above still keeps two module names. A *true* single unconditional
`import LyrebirdUI` on both platforms needs the modules merged:
1. Make the `LyrebirdUI` target cross-platform: build on Linux too, with internal
`#if canImport(SwiftUI)` (Apple) / `#else` SwiftOpenUI (Linux) branches per
control, and depend on SwiftOpenUI + BackendGTK4 on Linux only.
2. Port the *remaining* controls. Done so far: `ParameterKnob`, `ParameterSlider`,
`ParameterButton`, `ParameterLabel`, `ParameterXY`, `LyrebirdScopeView`,
`LyrebirdEnvelopeView`, and `LyrebirdStatusView` (CPU meters) — all as `Linux*`
in `LyrebirdUILinux`. The core control + visualization set is now ported.
Deferred by choice: the large `LyrebirdEngineStatusView` (601 lines — a
composite of start/stop + counts + a gain slider + a mute toggle + CPU, mostly
duplicating already-ported controls) and the node-tree / message-banner /
running-processes diagnostic views; port those only if the friends round wants
them. NOTES: (a) the scope introduced the periodic-redraw
pattern for animated viz views — an `@Observable` model polled by a Foundation
`Timer` on `RunLoop.main` (which the GTK4 backend pumps ~every 5 ms), NOT
SwiftOpenUI's `.task` (whose closure runs off-main and would race the
observation registrar); its 30 Hz redraw is compile-verified but still needs
on-hardware confirmation. (b) The envelope is static (draws once, no timer).
`DrawingContext` has no text drawing, so the envelope's "L"/"R" marker letters
are omitted (dashed green/orange lines still mark loop/release) — the status
views likely need text, so plan on real `Text` views over/around a `Canvas`
rather than text inside it.
3. Fold `LyrebirdUILinux` + `LyrebirdUILinuxDemo` back into `LyrebirdUI` /
a shared demo; retire the separate module.
4. Gate the whole thing on the SwiftOpenUI dep being available (fork now,
upstream + tag later). Larger review surface — its own branch.
Do this only after the fork→upstream switch settles, so the merged module isn't
pinned to a personal fork.
**Update 6 — shared parameter model moved to core.** The SwiftUI-free
`@UIParam` property wrapper and its `@Observable` `UIParamNode` backing object
moved from the macOS-only `LyrebirdUI` module into core `LyrebirdSynth`
(`Sources/Lyrebird/Parameters/`). Neither imports SwiftUI — only `Observation`
(stdlib, Linux-OK) — so nothing platform-gates them. `LinuxParameterKnob` now
binds a real `UIParamNode` (via a synthesizer's `@UIParam` projected value
`synth.$paramName`) with a value `range`, exactly as the macOS `ParameterKnob`
does — one parameter model drives both platforms. Because `UIParamNode` is
`@Observable`, `node.update(_:)` from a drag takes the GTK4 backend's narrow
redraw path (the fork fix), so the gesture survives. The `UIParamTests` suite
moved to `LyrebirdPortableTests` so Linux exercises it too. The placeholder
`LinuxKnobModel` is gone. No macOS API broke: every real `@UIParam` consumer
already imports `LyrebirdSynth`. Remaining: switch the SwiftOpenUI dep to
upstream `codelynx/SwiftOpenUI` + a tagged release once the PR lands.
**Update 5 — `LyrebirdUILinux` target scaffolded (depends on the fork).** An
opt-in Linux UI target now lives in the main package: build with
`LYREBIRD_ENABLE_LINUX_UI=1` on a Linux host with `libgtk-4-dev`. It depends on
the personal fork `github.com/joshpar/SwiftOpenUI` pinned to commit `1ac66079`
(the drag fix), plus `BackendGTK4`, and holds the first ported control —
`LinuxParameterKnob` (Canvas/`DrawingContext` + `.onDrag`, `@Observable`-backed).
Gated so the **default** Linux build/CI stays lean and fork-free (verified: a
flag-off resolve fetches no fork). macOS/iOS builds never see the target.
Caveats: (1) SwiftPM writes `Package.resolved` at the package root regardless of
`--scratch-path`, so a flagged build adds the fork pin locally — **do not commit
a fork-polluted `Package.resolved`** (the committed one stays fork-free). (2) The
control binds to a local `@Observable`; the shared-model step — moving the
SwiftUI-free `@UIParam` / `UIParamNode` from the macOS-only `LyrebirdUI` module
into core `LyrebirdSynth` so macOS and Linux UIs share one parameter model — is
the next reviewed change. Switch the dep to upstream `codelynx/SwiftOpenUI` + a
tagged release once the PR lands.
**Update 4 — `@Observable` PATCH CONFIRMED on hardware (2026-08-21).** With
`swiftopenui-drag-observable.patch` applied to a fork, the `@Observable` knob
(`spikes/SwiftOpenUIKnobObservable/`) tracks the drag continuously — so
`@UIParam` (which is `@Observable`-backed) can drive a `Canvas` control on Linux
**directly, no `@State` shim**. The patch is display-validated and PR-ready
(`spikes/SwiftOpenUIKnob/PR_DESCRIPTION.md`, `UPSTREAM_ISSUE.md`). **Verdict:
GO** — SwiftOpenUI is a viable single-codebase UI path for Linux, pending (a)
the patch landing upstream or being vendored, and (b) the per-view
`GraphicsContext → DrawingContext` drawing rewrite (mechanical, already shown to
compile). The remaining LyrebirdUI port work is now ordinary, not blocked.
**Update 3 — `@State` drag CONFIRMED on hardware (2026-08-21).** On the Ubuntu
24.04 arm64 VM the `@State` knob tracks the drag continuously — the narrow
mutation path preserves the `GtkGestureDrag`, so the core question ("can a
Canvas control take live drag input on GTK4?") is answered **yes**. The no-fork
`@State` usage pattern is a viable single-codebase path today; LyrebirdUI's
`@UIParam` (which is `@Observable`-backed) would draw from a local `@State` and
sync to the param. The `@Observable` framework patch
(`swiftopenui-drag-observable.patch`) — which would let `@UIParam` drive the
Canvas directly, no `@State` shim — remains **compile-only**; validate it against
a fork (`PATCH_TESTING.md`) before filing the PR.
**Update 2 — drag fix identified (compile-verified), pending display
validation.** Root cause is narrow: SwiftOpenUI's GTK4 backend has a narrow
mutation path that redraws a `Canvas` in place and preserves the drag gesture,
but it is skipped for `@Observable`-driven changes (it falls through to a full
rebuild to re-register observation, and the rebuild destroys the gesture). Two
fixes, both in `spikes/SwiftOpenUIKnob/` (`PATCH_TESTING.md`): a **no-fork
`@State` usage pattern** (the narrow path already covers `@State` Canvas
redraws), and a **framework patch** (`swiftopenui-drag-observable.patch`) that
runs the describe pass under `withObservationTracking` so `@Observable` takes
the narrow path too. Both need the user's GTK4 display to confirm; if they hold,
SwiftOpenUI remains the single-codebase path.
**Update 1 (hardware run, Ubuntu 24.04 arm64): renders + `@Observable`
re-renders, but continuous drag is broken.** A drag handler that writes the
bound value triggers a body rebuild that replaces the GTK drag-gesture widget
(SwiftOpenUI defers that only for *drop*, not drag), so a knob moves one step
per press instead of tracking the drag — the exact interaction every LyrebirdUI
knob/slider/XY needs. See `spikes/SwiftOpenUIKnob/README.md` for the confirmed
root cause and diagnostic. This is now the gating unknown, ahead of the
GraphicsContext rewrite. Resolving it needs an upstream fix (defer the rebuild
for drag gestures, or reuse the gesture widget) or a UI structure that keeps the
gesture widget stable across value redraws.
**Verdict: conditional GO.** The framework builds on Linux and the hard 20%
(custom drawing) is portable via a mechanical per-view `GraphicsContext →
DrawingContext` rewrite that compiles — not a drop-in, but not a wall either.
Still gated on a **display run** (Parallels) to confirm the knob actually
renders, `@Observable` drives re-render, and drag behaves — the container has no
X/Wayland. Risks unchanged: 32 stars / one author, "Stable" self-label
optimistic. Alternative if the display run disappoints: `swift-cross-ui`
(stackotter — own API, bigger rewrite) or stay headless on Linux.
**Reproduce the display run on Parallels:** `apt install libgtk-4-dev`; a
minimal SwiftPM app depending on `SwiftOpenUI` + `BackendGTK4` (Linux) with an
`App`/`WindowGroup`, `import Observation`, a `Canvas(renderer:)` knob drawn via
`DrawingContext`, and `.onDrag`; entry `GTK4Backend().run(App.self)`; then
`swift run`. The exact ~60-line spike is available on request.
---
Windows is planned separatelyWindows is planned separately and on hold (`docs/windows-support-plan.md`).
+282
View File
@@ -0,0 +1,282 @@
# Lyrebird on Linux
Lyrebird is a native audio-synthesis framework in Swift. You implement `Generator`
and `Synthesizer` types; the engine handles audio I/O and signal-graph evaluation.
As of **2.0**, Lyrebird runs on Linux with full parity across the engine, the
standard generator library, offline render, live audio (ALSA), MIDI, OSC, the
GTK4 GUI, and the live-coding scratchpad.
This is the Linux guide: install, build, run, scaffold a project, and the feature
map. For the macOS/iOS story and the framework internals, see the top-level docs.
---
## 1. Requirements
**Distribution.** Ubuntu 24.04 LTS is the tested target — it matches the CI image
(`swift:6.3.3`). Other modern glibc distributions work but are untested. (An ARM64
Ubuntu VM — e.g. Parallels on Apple silicon — is a supported dev setup.)
**Swift toolchain.** Use the **swift.org** toolchain (6.0+), *not* a distro
package. [swiftly](https://www.swift.org/install/linux/) is the easiest installer:
```bash
curl -O https://download.swift.org/swiftly/linux/swiftly-$(uname -m).tar.gz
tar zxf swiftly-$(uname -m).tar.gz && ./swiftly init
# in a new shell:
swiftly install latest
swift --version
```
If a new shell can't find `swift`/`swiftc`/`sourcekit-lsp`, add swiftly's bin
directory to `PATH` (Lyrebird's tools search `PATH`, so this is all that's needed):
```bash
echo 'export PATH="$HOME/.local/share/swiftly/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
```
**System packages.** Install what you need for the features you want:
```bash
# Build/link the core + tests:
sudo apt install build-essential pkg-config
# Live audio + MIDI (ALSA backends). Without this, build with
# LYREBIRD_DISABLE_ALSA=1 — everything compiles, but there is no sound or MIDI:
sudo apt install libasound2-dev
# The GTK4 GUI and the live-coding scratchpad:
sudo apt install libgtk-4-dev libgtksourceview-5-dev libfontconfig-dev
```
**IDE.** There is no Xcode on Linux. The maintained path is **VS Code + the
official Swift extension** (`swiftlang.swift-vscode`) — SourceKit-LSP completion,
diagnostics, LLDB debugging, and a test explorer:
```bash
code --install-extension swiftlang.swift-vscode
```
Open the repository folder; the extension reads `Package.swift` automatically.
Neovim/Emacs with `sourcekit-lsp` also work.
---
## 2. Build and test
```bash
git clone git@bitbucket.org:realizedsound/lyrebird.git
cd lyrebird
swift build
swift test --no-parallel # --no-parallel avoids a known parallel-runner teardown flake
```
On a Linux host the manifest omits the Apple-only targets, so `swift build` /
`swift test` compile the portable surface: the core engine + generators
(`LyrebirdSynth`), the interpreted graph DSL (`LyrebirdGraphDSL`), the CLI
(`LyrebirdCLI`), the GTK4 UI (`LyrebirdUI` + backend), and the Linux demos.
No sound stack on the box? Build and test everything except the ALSA driver:
```bash
LYREBIRD_DISABLE_ALSA=1 swift test --no-parallel
```
The **LiveCompile** live-coding subsystem is a separate SwiftPM package under
`LiveCompile/` (it dynamically links the engine, so it builds on its own):
```bash
cd LiveCompile
swift build
swift test --no-parallel
```
---
## 3. Set up a project
Scaffold a new Swift package wired to Lyrebird with the CLI:
```bash
swift run LyrebirdCLI new MyProject --template quickstart
cd MyProject
swift run
```
Templates:
| `--template` | What you get |
|---|---|
| `quickstart` | Fastest sound — a 440 Hz sine to the speakers. |
| `basic` | Default starter synth + engine setup. |
| `demo` | A richer multi-generator example. |
| `nrt` | Offline render to a WAV (`output.wav`) — no audio device needed. |
| `score` | Render from notation (MusicXML in, WAV out). |
| `ui-demo` | A GUI scaffold (AppKit on macOS; see the GTK4 demos below on Linux). |
The generated project calls `makeDefaultAudioDriver()`, which resolves to
`ALSAAudioDriver` on Linux (or a silent `OfflineDriver` when there is no live
backend — check `isLiveAudioAvailable`). Never name a concrete driver directly in
portable code; `makeDefaultAudioDriver()` picks the right one for how the package
was built.
---
## 4. Run the built-in samples
### Offline render — works with no audio device
The surest first run. Renders a WAV end-to-end, no hardware involved:
```bash
swift run LyrebirdCLI new MyRender --template nrt
cd MyRender && swift run # writes output.wav
```
### Live audio — needs a working sound device
In a VM, make sure the guest has audio (`aplay -l` should list a device):
```bash
swift run LyrebirdCLI new MyTone --template quickstart
cd MyTone && swift run # a sine tone for a few seconds
```
### REPL
```bash
swift run LyrebirdCLI repl
```
Drops into a Swift REPL with `import LyrebirdSynth` wired up — define generators
and synthesizers and add them to a running engine live.
### GTK4 GUI demo
A live parameter-control window (needs `libgtk-4-dev` + a display; sound needs
`libasound2-dev` + a device):
```bash
swift run LyrebirdUILinuxDemo
```
The default window shows live CPU-load meters, a live oscilloscope of the stereo
output, an example envelope plot, and controls for two parameters (frequency and
amplitude): an XY pad, a knob, a slider, and a readout each, plus a gate toggle
and reset. Every control bound to a parameter observes the same `@UIParam` node,
so moving one (say the freq knob) updates the others live — the same parameter
model the macOS SwiftUI controls use.
Pick a focused demo with `LYREBIRD_DEMO`:
| `LYREBIRD_DEMO` | Demo |
|---|---|
| `full` (default) | The full control panel described above. |
| `knob` | A single knob driving a sine tone. |
| `mouse` | `Mouse.X` / `Mouse.Y` / `Mouse.Click` driving synthesis from pointer position. |
| `events` | The process / event-list performance views. |
| `narrowtest` | A narrow-path redraw isolation harness (development aid). |
```bash
LYREBIRD_DEMO=mouse swift run LyrebirdUILinuxDemo
```
### Live-coding scratchpad
A GTK4 window with a real code editor that compiles and runs Swift snippets into
the live engine — Lyrebird's answer to a live-coding environment. It lives in the
`LiveCompile` package and needs `libgtksourceview-5-dev`:
```bash
cd LiveCompile
swift build # build first: the snippet links the engine's dynamic libs
swift run LyrebirdScratchLinuxDemo
```
> The `swift build` step is required before `swift run`: a snippet links against
> `libLyrebirdDynamic` / `libLyrebirdLiveCompileDynamic`, which `swift build`
> produces but `swift run` alone does not.
Type Swift, evaluate, hear it. `context` is your live session:
```swift
context.play { OscSin.Audio(freq: 330, mul: 0.15) }
context.reportMessage("playing 330 Hz")
```
Scratchpad features:
- **Swift editor** — GtkSourceView with syntax highlighting, a line-number gutter,
and auto-indent.
- **Code completion** — `Ctrl+Space` at the caret shows sourcekit-lsp completions
(types, members, parameters), filtered by what you've typed.
- **Run (fresh)** — clears the previous snippet's synths and runs the buffer.
- **Run (additive)** — layers the new snippet on top of what's already playing.
- **Line evaluation** — select one or more lines and Run evaluates just those.
- **Stop audio** — a panic button that clears all snippet audio without tearing
down the engine.
- **Live oscilloscope** — shows the session's stereo output in real time.
- **Save / load** — a File menu (`New`, `Open…`, `Save`, `Save As…`) with
`Ctrl+N` / `Ctrl+O` / `Ctrl+S` / `Ctrl+Shift+S` accelerators and native file
dialogs. Snippets are plain `.swift` files; the title shows a `●` when there are
unsaved edits.
---
## 5. Feature map
| Capability | Linux | Notes |
|---|---|---|
| Core engine + generators | ✅ | `LyrebirdSynth` |
| Interpreted graph DSL | ✅ | `LyrebirdGraphDSL` |
| CLI / REPL / scaffolding | ✅ | glibc; not built under musl |
| Offline render (NRT → WAV) | ✅ | portable WAV codec; CAF/AIFF/AAC are Apple-only |
| Soundfile load / DiskIn | ✅ | WAV only off Apple |
| Live audio | ✅ | ALSA; needs `libasound2-dev` + a device |
| MIDI in/out | ✅ | ALSA sequencer |
| OSC | ✅ | POSIX UDP |
| GTK4 GUI (`LyrebirdUI`) | ✅ | knob / slider / label / button / XY pad + scope + envelope + CPU status; standalone windows; mouse input; on the [SwiftOpenUI](https://github.com/joshpar/SwiftOpenUI) GTK4 backend |
| Live-coding scratchpad | ✅ | `LiveCompile`; editor + completion + save/load + live scope |
| SwiftUI UI | ❌ | macOS/iOS only (Lyrebird uses GTK4 on Linux) |
| AUv3 plugin | ❌ | Apple-only |
The GTK4 UI builds on a pinned release of the
[joshpar/SwiftOpenUI](https://github.com/joshpar/SwiftOpenUI) fork (see
`Package.swift`). To develop against a local checkout of the fork, point
`LYREBIRD_SWIFTOPENUI_LOCAL` at it:
```bash
LYREBIRD_SWIFTOPENUI_LOCAL=/path/to/SwiftOpenUI swift build
```
---
## 6. Troubleshooting
- **No sound / `isLiveAudioAvailable` is false.** Confirm ALSA sees a device with
`aplay -l`. In a VM, enable guest audio. To work without any sound stack, build
with `LYREBIRD_DISABLE_ALSA=1`.
- **`swiftc` / `sourcekit-lsp` not found** (common with swiftly). Add
`~/.local/share/swiftly/bin` to `PATH` (see §1). Lyrebird searches `PATH`, so
no further configuration is needed.
- **`gtk/gtk.h` or `gtksourceview/gtksource.h` not found.** Install the dev
packages: `libgtk-4-dev`, `libgtksourceview-5-dev`, `libfontconfig-dev`.
- **Scratchpad snippet fails to link** (`cannot find -lLyrebirdLiveCompileDynamic`).
Run `swift build` in `LiveCompile/` before `swift run` (see §4).
- **`Package.resolved` shows up as modified after a Linux build.** The Linux
dependency resolve records the SwiftOpenUI pin; run `git checkout Package.resolved`
before committing to keep the tree clean.
---
## 7. Reference
- `docs/linux-getting-started.md` — the original getting-started walkthrough.
- `docs/cross-platform-feasibility.md` — the porting approach.
- `docs/engine/alsa-audio-driver.md` — the Linux audio driver.
- `docs/engine/portable-wav-codec.md` — the off-Apple WAV read/write path.
- `Sources/Lyrebird/MIDI/ALSAMIDI.swift`, `Sources/Lyrebird/OSC/OSCServer.swift` —
the Linux MIDI and OSC backends.
- `LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md`
— the live-coding subsystem.
+43 -14
View File
@@ -1,26 +1,37 @@
# Lyrebird — Start Here # Lyrebird — Start Here
Six demo projects live in this workspace. This guide covers how to open them, what each one does, where to add your own synthesizers, and the gotchas that will bite you if you don't know about them. Eight demo projects live in this workspace. This guide covers how to open them, what each one does, where to add your own synthesizers, and the gotchas that will bite you if you don't know about them.
--- ---
## Opening the Workspace ## Opening the Workspace
Open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj` file. The workspace links all six demo projects together so they share the local Lyrebird package. Open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj` file. The workspace links all eight demo projects together so they share the local Lyrebird package.
Once open, pick a scheme from the scheme picker at the top of the Xcode window and hit Run. Once open, pick a scheme from the scheme picker at the top of the Xcode window and hit Run.
--- ---
## The Six Demos ## The Eight Demos
### LyrebirdQuickstartDemo — Fastest Sound
The shortest path to hearing Lyrebird. A command-line tool that starts the engine, adds a one-oscillator `SineTone`, plays a 440 Hz tone for 10 seconds through `CoreAudioDriver`, then stops and exits. Start here.
- **Where the synth lives:** `Demos/LyrebirdQuickstartDemo/LyrebirdQuickstartDemo/Synthesizers/SineTone.swift` — one `build()` with a single `OscSin.Audio` through `Pan2`.
- **Wire it up:** `main.swift` is `engine.start()` → `engine.add(SineTone())` → `Thread.sleep(10)` → `engine.stop()`. No `RunLoop` — it self-terminates.
- **Run it:** pick the `LyrebirdQuickstartDemo` scheme and hit Run, or from the terminal `cd Demos/LyrebirdQuickstartDemo && swift run`.
- **Same as the CLI template:** this mirrors `lyrebird new MyFirstSound --template quickstart`.
---
### LyrebirdDemo — Real-Time CLI ### LyrebirdDemo — Real-Time CLI
A command-line tool that plays audio through your default output device using `CoreAudioDriver`. A command-line tool that plays audio through your default output device using `CoreAudioDriver`.
- **Where to add synthesizers:** `Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/` — `SineTone.swift` and `DelaySample.swift` are the starting examples - **Where to add synthesizers:** `Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/` — `General/SineTone.swift` and `General/DelaySample.swift` are the starting examples (the folder is grouped into `General/`, `Buffer/`, `Granular/`, `Spectral/`)
- **Wire it up:** in `main.swift`, call `engine.schedule(MySynth(), after: 0.0)` - **Wire it up:** `main.swift` adds a synth and plays it — `try engine.add(mySynth)`, or `try engine.schedule(mySynth, after: seconds)` for sample-accurate start. (As shipped, `main.swift` runs a demo harness — `BufferDemos(engine: engine).runDemo()`; swap in your own.)
- **To stop:** Ctrl-C in the Xcode console, or just let the synthesizer's done action free it - **To stop:** Ctrl-C in the Xcode console, or give a voice an envelope/line that frees itself (see below)
You can also run this from the terminal: `cd Demos/LyrebirdDemo && swift run` You can also run this from the terminal: `cd Demos/LyrebirdDemo && swift run`
@@ -36,11 +47,13 @@ A SwiftUI app with a live oscilloscope, parameter knobs, and real-time audio.
```swift ```swift
final class MySynth: SynthesizerBase { final class MySynth: SynthesizerBase {
@UIParam var freq: LyrebirdFloat = 440.0 @UIParam var freq: Double = 440.0
@UIParam var amp: LyrebirdFloat = 0.5 @UIParam var amp: Double = 0.5
override func build() { override func build() {
let sig = OscSin.Audio(freq: freq) * amp // Use the $-projected nodes ($freq / $amp), not the bare values —
// the projection is what makes each knob update reach the audio graph live.
let sig = OscSin.Audio(freq: $freq) * $amp
output(bus: 0, source: Pan2(input: sig, pan: 0)) output(bus: 0, source: Pan2(input: sig, pan: 0))
} }
} }
@@ -105,6 +118,17 @@ let right = In.Audio(bus: 3) // numOutputChannels + 1
--- ---
### LyrebirdScoreDemo — Score / MusicXML + Offline Render
A command-line tool that builds notated `Score`s with the result-builder DSL, exports them to MusicXML on the Desktop, round-trips them through the parser as a sanity check, then renders the audio to a CAF file via `NRTDriver`.
- **Output files:** `~/Desktop/LyrebirdScoreDemo.musicxml` (a multi-part demo score), `~/Desktop/LyrebirdScoreSections.musicxml` (a sectioned showcase), and `~/Desktop/LyrebirdScoreDemo.caf` (rendered audio). Open the `.musicxml` in Dorico / MuseScore / Finale; open the `.caf` in any DAW.
- **Where the score is built:** `Demos/LyrebirdScoreDemo/LyrebirdScoreDemo/Demos/ScoreDemo.swift` — `makeScore()` (eight parts) and `makeSectionedShowcase()`.
- **Notation coverage:** clefs, keys, dynamics/hairpins, ties, tuplets, grace notes, multi-staff `Staff`/`Voice`, sustain `Pedal`, repeats with 1st/2nd endings, `Section`s + rehearsal marks, glissandi, per-note display overrides, and page layout. Reference: [`Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`](Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md).
- **Rehearsal-mark tip:** use single-letter `Section` labels (`"A"`, `"B"`, `"C"`) — notation editors auto-sequence rehearsal marks and hide custom words.
---
### LyrebirdAUv3Demo — AUv3 Plugin Reference ### LyrebirdAUv3Demo — AUv3 Plugin Reference
A container app + `.appex` extension target shipping **Realized Sound: LyrebirdFM** — a two-operator FM synthesizer wrapped as an `aumu` Audio Unit v3. Loadable in Logic, GarageBand, AUM, Loopy Pro, and any other AUv3 host on macOS. A container app + `.appex` extension target shipping **Realized Sound: LyrebirdFM** — a two-operator FM synthesizer wrapped as an `aumu` Audio Unit v3. Loadable in Logic, GarageBand, AUM, Loopy Pro, and any other AUv3 host on macOS.
@@ -117,7 +141,7 @@ A container app + `.appex` extension target shipping **Realized Sound: LyrebirdF
--- ---
### LyrebirdScratchDemo — Live-Coding Scratchpad ### LyrebirdScratch — Live-Coding Scratchpad
A macOS app that compiles a typed Swift snippet against the live engine at ⌘↩. Backed by `LyrebirdScratchView` and `LiveSession` from the `LyrebirdLiveCompile` SPM target. A macOS app that compiles a typed Swift snippet against the live engine at ⌘↩. Backed by `LyrebirdScratchView` and `LiveSession` from the `LyrebirdLiveCompile` SPM target.
@@ -125,13 +149,15 @@ A macOS app that compiles a typed Swift snippet against the live engine at ⌘
- Type arbitrary Swift code in the editor pane. The snippet body has `context: SnippetContext` in scope. - Type arbitrary Swift code in the editor pane. The snippet body has `context: SnippetContext` in scope.
- `context.engine` — the host `SynthesisEngine`, started at launch. - `context.engine` — the host `SynthesisEngine`, started at launch.
- `context.play(synth)` — adds a `Synthesizer` to the engine and tracks it for cleanup. - `context.play(synth)` — adds a `Synthesizer` to the engine and tracks it for cleanup.
- `context.play { <graph> }` — plays a bare generator graph, no `SynthesizerBase` subclass needed.
- `context.play(slot: "name") { <graph> }` — plays into a named slot; re-running that slot replaces just that voice in place while the rest keeps playing (persists across a ⌘↩ run).
- `context.reportMessage(_:)` — writes a string back to the host status bar. - `context.reportMessage(_:)` — writes a string back to the host status bar.
- **⌘↩** — compile and replace. Removes synths from the previous run, compiles the snippet via `swiftc -emit-library`, `dlopen`s the resulting dylib, calls `lyrebird_snippet_entry`. - **⌘↩** — compile and replace. Removes the previous run's anonymous synths (named slots persist), compiles the snippet via `swiftc -emit-library`, `dlopen`s the resulting dylib, calls `lyrebird_snippet_entry`.
- **⌘⇧↩** — compile additive. Prior synths stay in the engine. - **⌘⇧↩** — compile additive. Prior synths stay in the engine.
- **Clear Synths** toolbar button — removes all tracked synths immediately. - **Clear Synths** toolbar button — full reset: removes all tracked synths *and* every named slot immediately.
**Why this app cannot be sandboxed:** **Why this app cannot be sandboxed:**
`swiftc` is a subprocess (`posix_spawn`); the output dylib is unsigned. Both are blocked by the macOS App Sandbox. This app is a direct-distribution developer tool only. The entitlements file (`LyrebirdScratchDemo.entitlements`) sets `com.apple.security.cs.disable-library-validation = true` to let Hardened Runtime `dlopen` the unsigned snippet dylib. `swiftc` is a subprocess (`posix_spawn`); the output dylib is unsigned. Both are blocked by the macOS App Sandbox. This app is a direct-distribution developer tool only. The entitlements file (`LyrebirdScratch.entitlements`) sets `com.apple.security.cs.disable-library-validation = true` to let Hardened Runtime `dlopen` the unsigned snippet dylib.
**Dylib lifetime:** loaded dylibs are never unloaded. `Synthesizer` instances reference types from the dylib; unloading while they are active would crash. Every ⌘↩ evaluation writes a new uniquely-named dylib to a per-session temp dir. This is intentional v1 behaviour; a future release may revisit with an XPC worker approach. **Dylib lifetime:** loaded dylibs are never unloaded. `Synthesizer` instances reference types from the dylib; unloading while they are active would crash. Every ⌘↩ evaluation writes a new uniquely-named dylib to a per-session temp dir. This is intentional v1 behaviour; a future release may revisit with an XPC worker approach.
@@ -152,11 +178,12 @@ final class MySynth: SynthesizerBase {
override func build() { override func build() {
let sig = OscSin.Audio(freq: 440) * 0.3 let sig = OscSin.Audio(freq: 440) * 0.3
output(bus: 0, source: Pan2(input: sig, pan: 0)) output(bus: 0, source: Pan2(input: sig, pan: 0))
doneAction = .freeEnclosing
} }
} }
``` ```
**Self-freeing voices:** there is no `doneAction` property to set on the synthesizer. Instead, build a `DoneActionWatchable` generator — `EnvelopeGen`, `Line`, `ExponentialLine`, etc. — **inside `build()`** with `doneAction: .freeNode`; it self-registers, and the engine frees the node when that generator finishes. (`DoneAction` cases are `.nothing`, `.freeNode`, `.loop`.)
--- ---
## Common Gotchas ## Common Gotchas
@@ -175,6 +202,7 @@ final class MySynth: SynthesizerBase {
| Topic | Doc | | Topic | Doc |
|-------|-----| |-------|-----|
| New to Swift? Intro for Lyrebird users | `docs/learning-swift/README.md` |
| Engine setup and Core Audio | `docs/engine/synthesis-engine.md` | | Engine setup and Core Audio | `docs/engine/synthesis-engine.md` |
| Bus system, In/Out generators | `docs/engine/bus-system.md` | | Bus system, In/Out generators | `docs/engine/bus-system.md` |
| Sample-accurate scheduling | `docs/engine/scheduling.md` | | Sample-accurate scheduling | `docs/engine/scheduling.md` |
@@ -182,6 +210,7 @@ final class MySynth: SynthesizerBase {
| Synthesizer and node tree | `docs/protocols/synthesizer.md` | | Synthesizer and node tree | `docs/protocols/synthesizer.md` |
| All built-in generators | `docs/stdlib/generators.md` | | All built-in generators | `docs/stdlib/generators.md` |
| NRT / offline rendering | `docs/tooling/nrt-guide.md` | | NRT / offline rendering | `docs/tooling/nrt-guide.md` |
| Score / MusicXML authoring | `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md` |
| REPL / hot-swap | `docs/tooling/repl.md` | | REPL / hot-swap | `docs/tooling/repl.md` |
| Xcode file templates | `docs/tooling/xcode-templates.md` | | Xcode file templates | `docs/tooling/xcode-templates.md` |
| GUI / parameter binding | `docs/ui/gui-system.md` | | GUI / parameter binding | `docs/ui/gui-system.md` |
+74 -4
View File
@@ -7,7 +7,7 @@
// swift-tools-version: 6.0 // swift-tools-version: 6.0
import PackageDescription import PackageDescription
// Phase 167 — `LyrebirdLiveCompile` and `LyrebirdLiveCompileUI` live in this // `LyrebirdLiveCompile` and `LyrebirdLiveCompileUI` live in this
// sub-package so that cross-package `.product(name:, package:)` dependency // sub-package so that cross-package `.product(name:, package:)` dependency
// resolution forces SwiftPM to dynamic-link `libLyrebirdLiveCompile.dylib` // resolution forces SwiftPM to dynamic-link `libLyrebirdLiveCompile.dylib`
// against `libLyrebird.dylib` instead of statically embedding `Lyrebird`'s // against `libLyrebird.dylib` instead of statically embedding `Lyrebird`'s
@@ -20,13 +20,25 @@ let package = Package(
name: "LyrebirdLiveCompile", name: "LyrebirdLiveCompile",
platforms: [.macOS(.v15)], platforms: [.macOS(.v15)],
products: [ products: [
// Product name ≠ target name (mirrors the main package's
// `Lyrebird`/`LyrebirdDynamic` pairing). A `.dynamic` product whose name
// EQUALS its target name collides in Xcode when that target is also
// referenced as a static link elsewhere in the same build graph:
// "Swift package target 'X' is linked as a static library by … but
// cannot be built dynamically because there is a package product with
// the same name." Naming the dynamic products `…Dynamic` removes the
// collision so each target builds as a single shared dylib that every
// consumer links dynamically. Target/module names are unchanged, so
// `import LyrebirdLiveCompile` / `import LyrebirdLiveCompileUI` and the
// test targets (which reference targets by name) are unaffected.
.library( .library(
name: "LyrebirdLiveCompile", name: "LyrebirdLiveCompileDynamic",
type: .dynamic, type: .dynamic,
targets: ["LyrebirdLiveCompile"] targets: ["LyrebirdLiveCompile"]
), ),
.library( .library(
name: "LyrebirdLiveCompileUI", name: "LyrebirdLiveCompileUIDynamic",
type: .dynamic,
targets: ["LyrebirdLiveCompileUI"] targets: ["LyrebirdLiveCompileUI"]
), ),
], ],
@@ -34,10 +46,34 @@ let package = Package(
.package(name: "Lyrebird", path: "..") .package(name: "Lyrebird", path: "..")
], ],
targets: [ targets: [
// The interpreted graph-DSL, compiled from the main package's shared
// sources (a symlink at `Sources/LyrebirdGraphDSLEmbedded`) as a LOCAL
// target here rather than consumed as a main-package product.
//
// Why not the main-package product: any `LyrebirdGraphDSL` product —
// static OR dynamic — bakes a SECOND copy of `LyrebirdSynth` into its
// dylib (a same-package target dependency is always static-embedded), so
// both `libLyrebirdDynamic` and that product's dylib register Lyrebird's
// ObjC classes → double registration → spurious cast failures + SIGSEGV
// under `swift test`. Compiling the DSL as a local target here lets its
// `import LyrebirdSynth` resolve cross-package to the ONE shared
// `libLyrebirdDynamic`. Safe because the DSL is pure value types (no
// classes), so recompiling it in a second module registers nothing with
// the ObjC runtime. Distinct module name (`…Embedded`) avoids any clash
// with the main package's `LyrebirdGraphDSL` in a shared Xcode graph.
.target(
name: "LyrebirdGraphDSLEmbedded",
dependencies: [
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
],
path: "Sources/LyrebirdGraphDSLEmbedded"
),
.target( .target(
name: "LyrebirdLiveCompile", name: "LyrebirdLiveCompile",
dependencies: [ dependencies: [
.product(name: "LyrebirdDynamic", package: "Lyrebird"), .product(name: "LyrebirdDynamic", package: "Lyrebird"),
// Instant, no-swiftc graph evaluation for the editor's DSL mode.
"LyrebirdGraphDSLEmbedded",
], ],
path: "Sources/LyrebirdLiveCompile" path: "Sources/LyrebirdLiveCompile"
), ),
@@ -48,13 +84,14 @@ let package = Package(
.product(name: "LyrebirdDynamic", package: "Lyrebird"), .product(name: "LyrebirdDynamic", package: "Lyrebird"),
], ],
path: "Sources/LyrebirdLiveCompileUI" path: "Sources/LyrebirdLiveCompileUI"
// Swift 6 language mode (Phase 203): inherits the swift-tools 6.0 default. // Swift 6 language mode: inherits the swift-tools 6.0 default.
), ),
.testTarget( .testTarget(
name: "LyrebirdLiveCompileTests", name: "LyrebirdLiveCompileTests",
dependencies: [ dependencies: [
"LyrebirdLiveCompile", "LyrebirdLiveCompile",
.product(name: "LyrebirdDynamic", package: "Lyrebird"), .product(name: "LyrebirdDynamic", package: "Lyrebird"),
"LyrebirdGraphDSLEmbedded",
], ],
path: "Tests/LyrebirdLiveCompileTests" path: "Tests/LyrebirdLiveCompileTests"
), ),
@@ -69,3 +106,36 @@ let package = Package(
), ),
] ]
) )
#if os(Linux)
// On Linux the editor UI is SwiftOpenUI/GTK4 (the macOS AppKit surface is
// #if os(macOS)-gated out). Wire the cross-platform LyrebirdUI product — which
// @_exported re-exports SwiftOpenUI + BackendGTK4 and provides LyrebirdWindow /
// LyrebirdScopeView — into the UI target, plus a runnable minimal scratch demo:
// LYREBIRD_ENABLE_LINUX_UI is not needed; `swift run LyrebirdScratchLinuxDemo`.
if let uiIndex: Int = package.targets.firstIndex(where: { $0.name == "LyrebirdLiveCompileUI" }) {
package.targets[uiIndex].dependencies.append(
.product(name: "LyrebirdUI", package: "Lyrebird")
)
}
package.targets.append(
.executableTarget(
name: "LyrebirdScratchLinuxDemo",
dependencies: [
"LyrebirdLiveCompile",
"LyrebirdLiveCompileUI",
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
.product(name: "LyrebirdUI", package: "Lyrebird"),
],
path: "Sources/LyrebirdScratchLinuxDemo"
// NOTE: a live-compiled snippet links `-lLyrebirdDynamic
// -lLyrebirdLiveCompileDynamic`, so those shared libraries must exist in
// the build dir before you Run. A same-package target can't depend on a
// same-package product to force them, so build the whole package first —
// `swift build` (builds all products, incl. the …Dynamic .so's) — then
// `swift run LyrebirdScratchLinuxDemo`. `swift run` alone only builds the
// executable's own graph and would leave the snippet link unable to find
// libLyrebirdLiveCompileDynamic.so.
)
)
#endif
+1
View File
@@ -0,0 +1 @@
../../Sources/LyrebirdGraphDSL
@@ -0,0 +1,16 @@
// ArtifactStagingError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS) || os(Linux)
/// Errors raised while staging compile artifacts into Application Support.
enum ArtifactStagingError: Error {
/// The staging destination already exists, is non-empty, and does not look
/// like a prior staging root — refused rather than clobbered.
case destinationNotAStagingRoot(String)
}
#endif
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound // Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core // LyrebirdLiveCompile — core
// //
// `CompiledSnippet` owns the `dlopen` handle and the resolved entry function // `CompiledSnippet` owns the `dlopen` handle and the resolved entry function
// pointer for one snippet's dylib. Held by the live session for the lifetime of // pointer for one snippet's dylib. Held by the live session for the lifetime of
@@ -14,7 +14,7 @@
import Foundation import Foundation
#if os(macOS) #if os(macOS) || os(Linux)
/// Handle to one successfully compiled and loaded snippet. /// Handle to one successfully compiled and loaded snippet.
/// ///
@@ -35,7 +35,7 @@ public final class CompiledSnippet: @unchecked Sendable {
/// Path to the dylib that was `dlopen`'d. /// Path to the dylib that was `dlopen`'d.
public let dylibPath: String public let dylibPath: String
/// Resolved entry function pointer. Calling this is Phase 143's job. /// Resolved entry function pointer. The snippet harness calls this.
public let entry: SnippetEntry public let entry: SnippetEntry
/// Raw `dlopen` handle. Kept so the OS keeps the dylib mapped. /// Raw `dlopen` handle. Kept so the OS keeps the dylib mapped.
@@ -4,16 +4,16 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound // Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144 // LyrebirdLiveCompile
// //
// One parsed `swiftc` diagnostic, with `line` already mapped from the wrapped- // One parsed `swiftc` diagnostic, with `line` already mapped from the wrapped-
// snippet coordinate space back to the user's snippet coordinate space (via the // snippet coordinate space back to the user's snippet coordinate space (via the
// `userBodyLineOffset` from `SnippetHarness.wrap(userBody:)`). // `userBodyLineOffset` from `SnippetHarness.wrap(userBody:)`).
// //
// The editor in Phase 145 (`LyrebirdScratchView`) renders diagnostics in its // The editor (`LyrebirdScratchView`) renders diagnostics in its
// margin gutter using `(line, column)` directly. // margin gutter using `(line, column)` directly.
#if os(macOS) #if os(macOS) || os(Linux)
public struct Diagnostic: Equatable, Sendable { public struct Diagnostic: Equatable, Sendable {
/// 1-based line number in the **user's** snippet body. May be `nil` when the /// 1-based line number in the **user's** snippet body. May be `nil` when the
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound // Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144 // LyrebirdLiveCompile
// //
// `DiagnosticParser.parse(stderr:userBodyLineOffset:)` walks the swiftc stderr // `DiagnosticParser.parse(stderr:userBodyLineOffset:)` walks the swiftc stderr
// stream line by line, extracts diagnostics matching the standard // stream line by line, extracts diagnostics matching the standard
@@ -22,7 +22,7 @@
import Foundation import Foundation
#if os(macOS) #if os(macOS) || os(Linux)
public enum DiagnosticParser { public enum DiagnosticParser {
@@ -4,11 +4,11 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound // Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144 // LyrebirdLiveCompile
// //
// Severity classifier for a parsed swiftc diagnostic line. // Severity classifier for a parsed swiftc diagnostic line.
#if os(macOS) #if os(macOS) || os(Linux)
public enum DiagnosticSeverity: String, Equatable, Sendable { public enum DiagnosticSeverity: String, Equatable, Sendable {
case error case error
@@ -0,0 +1,74 @@
// GraphDSLDiagnosticMapper.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// Turns a thrown `DSLParseError` / `DSLBuildError` into the same `[Diagnostic]`
// the swiftc path produces, so `LyrebirdScratchView`'s gutter renders DSL
// failures with no special-casing. Parse errors carry a source span → a real
// (line, column); build errors carry no span → `line: nil` with the message
// alone.
#if os(macOS) || os(Linux)
import LyrebirdGraphDSLEmbedded
/// Maps interpreted-graph-DSL errors to editor diagnostics.
enum GraphDSLDiagnosticMapper {
/// Convert `error` (a `DSLParseError`, a `DSLBuildError`, or anything else)
/// into one or more ``Diagnostic``s, resolving parse-error spans against
/// `source` for a 1-based line/column.
static func diagnostics(for error: Error, source: String) -> [Diagnostic] {
if let parse: DSLParseError = error as? DSLParseError {
let (line, column): (Int, Int) = lineColumn(of: parse.span.start, in: source)
return [Diagnostic(
line: line,
column: column,
severity: .error,
message: parse.description,
rawLine: line
)]
}
if let build: DSLBuildError = error as? DSLBuildError {
// Build errors carry no span; report at file scope.
return [Diagnostic(
line: nil,
column: 0,
severity: .error,
message: build.description,
rawLine: 0
)]
}
return [Diagnostic(
line: nil,
column: 0,
severity: .error,
message: "\(error)",
rawLine: 0
)]
}
/// Map a character `offset` into `source` to a 1-based (line, column).
/// An offset past the end clamps to the final position.
private static func lineColumn(of offset: Int, in source: String) -> (line: Int, column: Int) {
var line: Int = 1
var column: Int = 1
var seen: Int = 0
for character: Character in source {
if seen >= offset { break }
if character == "\n" {
line += 1
column = 1
} else {
column += 1
}
seen += 1
}
return (line, column)
}
}
#endif
@@ -0,0 +1,42 @@
// LSPCompletionItem.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// One parsed code-completion candidate from `sourcekit-lsp`. macOS/Linux only.
#if os(macOS) || os(Linux)
/// One code-completion candidate returned by sourcekit-lsp.
public struct LSPCompletionItem: Sendable, Equatable {
/// Display label (e.g. `Audio`).
public let label: String
/// Type / signature detail (e.g. `OscSin.Audio`), if provided.
public let detail: String?
/// Text to insert when chosen. Falls back to `label` when the server gives
/// no explicit insert text.
public let insertText: String
/// LSP `CompletionItemKind` raw value, or `nil`. Lets the UI pick an icon.
public let kind: Int?
/// Server-provided sort key; the UI orders by this then by `label`.
public let sortText: String?
public init(
label: String,
detail: String?,
insertText: String,
kind: Int?,
sortText: String?
) {
self.label = label
self.detail = detail
self.insertText = insertText
self.kind = kind
self.sortText = sortText
}
}
#endif
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound // Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core // LyrebirdLiveCompile — core
// //
// Errors raised by `LiveCompiler.compile(source:)`. RT path never sees these: // Errors raised by `LiveCompiler.compile(source:)`. RT path never sees these:
// compilation is a main-thread (or background-queue) operation that runs long // compilation is a main-thread (or background-queue) operation that runs long
@@ -12,7 +12,7 @@
import Foundation import Foundation
#if os(macOS) #if os(macOS) || os(Linux)
public enum LiveCompileError: Error, CustomStringConvertible, Equatable, Sendable { public enum LiveCompileError: Error, CustomStringConvertible, Equatable, Sendable {
/// `xcrun -f swiftc` and the fallback paths all failed. /// `xcrun -f swiftc` and the fallback paths all failed.
@@ -4,19 +4,21 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound // Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core // LyrebirdLiveCompile — core
// //
// `LiveCompiler.compile(source:)` shells out to `swiftc -emit-library`, then // `LiveCompiler.compile(source:)` shells out to `swiftc -emit-library`, then
// `dlopen`s the resulting dylib and resolves the snippet entry symbol. No UI, // `dlopen`s the resulting dylib and resolves the snippet entry symbol. No UI,
// no `SynthesisEngine` binding (those land in phases 143–146). macOS only — // no `SynthesisEngine` binding (those are handled by the harness and session
// iOS cannot exec swiftc. // layers). macOS/Linux only — iOS cannot exec swiftc.
import Foundation import Foundation
#if os(macOS) #if canImport(Darwin)
import Darwin import Darwin // dlopen / dlsym / dlerror
#elseif canImport(Glibc)
import Glibc // dlopen / dlsym / dlerror on Linux
#endif #endif
#if os(macOS) #if os(macOS) || os(Linux)
/// Symbol the snippet preamble must export. Snippets declare: /// Symbol the snippet preamble must export. Snippets declare:
/// ///
@@ -26,16 +28,43 @@ import Darwin
/// ``` /// ```
public let lyrebirdSnippetEntrySymbol: String = "lyrebird_snippet_entry" public let lyrebirdSnippetEntrySymbol: String = "lyrebird_snippet_entry"
/// Platform shared-library extension: `dylib` (Mach-O) on macOS, `so` (ELF) on
/// Linux. A snippet is `swiftc -emit-library`'d to `lib<name>.<ext>`, and the
/// resident Lyrebird library is `libLyrebirdDynamic.<ext>`.
#if os(macOS)
let livecompileSharedLibraryExtension: String = "dylib"
#else
let livecompileSharedLibraryExtension: String = "so"
#endif
/// Search `$PATH` for an executable named `name`, returning the first hit or
/// `nil`. Covers toolchains installed outside the hard-coded locations — most
/// notably a swiftly install (`~/.local/share/swiftly/bin`) on Linux, which puts
/// both `swiftc` and `sourcekit-lsp` on `$PATH` but not in `/usr/bin`.
func livecompileExecutableOnPath(_ name: String) -> String? {
guard let pathEnv: String = ProcessInfo.processInfo.environment["PATH"] else { return nil }
for dir: Substring in pathEnv.split(separator: ":") where !dir.isEmpty {
let base: String = String(dir)
let candidate: String = base.hasSuffix("/") ? base + name : base + "/" + name
if FileManager.default.isExecutableFile(atPath: candidate) {
return candidate
}
}
return nil
}
/// One-shot snippet compiler. Stateless — every `compile(source:)` allocates a /// One-shot snippet compiler. Stateless — every `compile(source:)` allocates a
/// fresh temp dir, dylib name, and `dlopen` handle. /// fresh temp dir, shared-library name, and `dlopen` handle.
public enum LiveCompiler { public enum LiveCompiler {
static var sharedLibraryExtension: String { livecompileSharedLibraryExtension }
/// Compile `source` to a dylib and resolve the snippet entry symbol. /// Compile `source` to a dylib and resolve the snippet entry symbol.
/// ///
/// - Parameters: /// - Parameters:
/// - source: Full Swift source, including the `@_cdecl("lyrebird_snippet_entry")` /// - source: Full Swift source, including the `@_cdecl("lyrebird_snippet_entry")`
/// entry. Phase 143's `SnippetHarness` will wrap user input in a preamble that /// entry. `SnippetHarness` wraps user input in a preamble that provides
/// provides this; Phase 142 callers (incl. tests) write the full file. /// this; direct callers (incl. tests) write the full file.
/// - extraSwiftcArgs: Extra args appended to the `swiftc` invocation. Tests use /// - extraSwiftcArgs: Extra args appended to the `swiftc` invocation. Tests use
/// this for `-suppress-warnings` etc. Production callers leave empty. /// this for `-suppress-warnings` etc. Production callers leave empty.
/// - Returns: `CompiledSnippet` holding the dlopen handle and entry pointer. /// - Returns: `CompiledSnippet` holding the dlopen handle and entry pointer.
@@ -52,7 +81,7 @@ public enum LiveCompiler {
let workDir: URL = FileManager.default.temporaryDirectory let workDir: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LyrebirdLiveCompile-\(snippetID)", isDirectory: true) .appendingPathComponent("LyrebirdLiveCompile-\(snippetID)", isDirectory: true)
let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path
let dylibPath: String = workDir.appendingPathComponent("lib\(moduleName).dylib").path let dylibPath: String = workDir.appendingPathComponent("lib\(moduleName).\(sharedLibraryExtension)").path
do { do {
try FileManager.default.createDirectory( try FileManager.default.createDirectory(
@@ -112,11 +141,17 @@ public enum LiveCompiler {
/// First-success search: /// First-success search:
/// 1. `xcrun -f swiftc` (honours `DEVELOPER_DIR` and the user's active Xcode). /// 1. `xcrun -f swiftc` (honours `DEVELOPER_DIR` and the user's active Xcode).
/// 2. Hard-coded toolchain paths. /// 2. An executable `swiftc` on `$PATH` — covers a swiftly install
/// (`~/.local/share/swiftly/bin`) and any Linux toolchain layout that
/// isn't in the hard-coded list.
/// 3. Hard-coded toolchain paths.
static func findSwiftc() throws -> String { static func findSwiftc() throws -> String {
if let xcrun: String = swiftcViaXcrun() { if let xcrun: String = swiftcViaXcrun() {
return xcrun return xcrun
} }
if let onPath: String = swiftcOnPath() {
return onPath
}
let candidates: [String] = [ let candidates: [String] = [
"/usr/bin/swiftc", "/usr/bin/swiftc",
"/usr/local/bin/swiftc", "/usr/local/bin/swiftc",
@@ -128,6 +163,11 @@ public enum LiveCompiler {
throw LiveCompileError.swiftcNotFound throw LiveCompileError.swiftcNotFound
} }
/// Search `$PATH` for an executable `swiftc`. Returns the first hit, or `nil`.
static func swiftcOnPath() -> String? {
livecompileExecutableOnPath("swiftc")
}
/// `xcrun --show-sdk-path` — returns the macOS SDK path used by the user's /// `xcrun --show-sdk-path` — returns the macOS SDK path used by the user's
/// active Xcode. `nil` when xcrun is missing or returns non-zero. /// active Xcode. `nil` when xcrun is missing or returns non-zero.
static func sdkPathViaXcrun() -> String? { static func sdkPathViaXcrun() -> String? {
@@ -190,10 +230,11 @@ public enum LiveCompiler {
process.arguments = arguments process.arguments = arguments
let stderrPipe: Pipe = Pipe() let stderrPipe: Pipe = Pipe()
process.standardError = stderrPipe process.standardError = stderrPipe
// stdout discarded — swiftc emits no useful output in -emit-library mode. // stdout discarded — swiftc emits no useful output in the modes used
// Use FileHandle.nullDevice (not Pipe()) so the OS drops the bytes itself; // here (-emit-library and -typecheck). Use FileHandle.nullDevice (not
// an undrained Pipe deadlocks against the blocking stderr read below if // Pipe()) so the OS drops the bytes itself; an undrained Pipe deadlocks
// swiftc ever writes more than the pipe buffer (~64 KB) to stdout. // against the blocking stderr read below if swiftc ever writes more than
// the pipe buffer (~64 KB) to stdout.
process.standardOutput = FileHandle.nullDevice process.standardOutput = FileHandle.nullDevice
do { do {
try process.run() try process.run()
@@ -205,6 +246,53 @@ public enum LiveCompiler {
let stderrString: String = String(data: stderrData, encoding: .utf8) ?? "" let stderrString: String = String(data: stderrData, encoding: .utf8) ?? ""
return SwiftcResult(exitCode: process.terminationStatus, stderr: stderrString) return SwiftcResult(exitCode: process.terminationStatus, stderr: stderrString)
} }
// MARK: - Module-cache prewarm
/// Build the Clang/Swift module cache (the precompiled `.pcm` for the large
/// `LyrebirdSynth` interface and its dependencies) by **type-checking** a
/// trivial source that imports the same modules a real snippet does.
///
/// The cold cache build costs ~2–3 s and otherwise lands on the user's first
/// ⌘↩; running this once at session start (off-main) moves that cost into the
/// background, so the first real ``compile(source:extraSwiftcArgs:)`` hits a
/// warm cache (~0.1 s). `-typecheck` is enough — the `.pcm`s are produced
/// during import resolution, before codegen/link — and avoids emitting or
/// `dlopen`ing a dylib.
///
/// - Parameter extraSwiftcArgs: The module-resolution flags (`-I`,
/// `-Xcc -fmodule-map-file=…`) that point at the same modules the real
/// compile uses, so both warm the same (default) module cache.
/// `LiveSession` supplies these via its module-resolution args.
/// - Throws: `LiveCompileError` for a missing toolchain, IO failure, or a
/// non-zero type-check exit.
public static func prewarm(extraSwiftcArgs: [String]) throws {
let swiftc: String = try findSwiftc()
let id: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
let workDir: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LyrebirdLiveCompile-prewarm-\(id)", isDirectory: true)
let sourcePath: String = workDir.appendingPathComponent("Prewarm.swift").path
let source: String = "import LyrebirdSynth\nimport LyrebirdLiveCompile\n"
do {
try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true)
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
} catch {
throw LiveCompileError.ioFailed(underlying: "\(error)")
}
defer { try? FileManager.default.removeItem(at: workDir) }
var arguments: [String] = ["-typecheck", "-module-name", "LBPrewarm_\(id)"]
if let sdkPath: String = sdkPathViaXcrun() {
arguments.append(contentsOf: ["-sdk", sdkPath])
}
arguments += extraSwiftcArgs
arguments.append(sourcePath)
let result: LiveCompiler.SwiftcResult = try runSwiftc(executable: swiftc, arguments: arguments)
guard result.exitCode == 0 else {
throw LiveCompileError.compileFailed(exitCode: result.exitCode, stderr: result.stderr)
}
}
} }
#endif #endif
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound // Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143 // LyrebirdLiveCompile
// //
// `LiveSession` owns the `SynthesisEngine` and tracks every `Synthesizer` that // `LiveSession` owns the `SynthesisEngine` and tracks every `Synthesizer` that
// each snippet `play(_:)`s, so the next non-additive re-evaluation can // each snippet `play(_:)`s, so the next non-additive re-evaluation can
@@ -12,7 +12,7 @@
// `CompiledSnippet` so the dylibs stay mapped — see the leak-by-design note in // `CompiledSnippet` so the dylibs stay mapped — see the leak-by-design note in
// `CompiledSnippet.swift`. // `CompiledSnippet.swift`.
#if os(macOS) #if os(macOS) || os(Linux)
import Foundation import Foundation
import LyrebirdSynth import LyrebirdSynth
@@ -23,14 +23,15 @@ import LyrebirdSynth
/// Snippets receive a `SnippetContext` bound to this session through /// Snippets receive a `SnippetContext` bound to this session through
/// `compileAndRun(_:additive:)`. /// `compileAndRun(_:additive:)`.
/// ///
/// `@unchecked Sendable` (Phase 203): a `LiveSession` is shared between its `@MainActor` /// `@unchecked Sendable`: a `LiveSession` is shared between its `@MainActor`
/// owner (`LyrebirdScratchModel`) and the `nonisolated` `compileAndRunAsync` it calls, so /// owner (`LyrebirdScratchModel`) and the `nonisolated` `compileAndRunAsync` it calls, so
/// Swift 6 requires it to be `Sendable`. The conformance is sound by construction: /// Swift 6 requires it to be `Sendable`. The conformance is sound by construction:
/// ///
/// - `engine` and all `-I` / `-L` / `-l` / `rpath` configuration are immutable `let`. /// - `engine` and all `-I` / `-L` / `-l` / `rpath` configuration are immutable `let`.
/// - The only mutable graph state — `trackedSynths` and `loadedSnippets` — is accessed /// - The mutable graph state — `trackedSynths`, `loadedSnippets`, and the named-slot map
/// exclusively under `trackingLock` (`track`, `clearTracked`, `trackedSynthCount`, /// `slottedSynths` — is accessed exclusively under `trackingLock` (`track`,
/// `runEntry`). /// `clearTracked`, `trackedSynthCount`, `runEntry`, `assignSlot`, `clearSlot`,
/// `clearSlots`, `slotCount`, `slotNames`).
/// - `reportedSampleRate` / `lastSnippetMessage` are test-only side channels (`@testable`), /// - `reportedSampleRate` / `lastSnippetMessage` are test-only side channels (`@testable`),
/// written by the single in-flight snippet entry under the documented /// written by the single in-flight snippet entry under the documented
/// one-invocation-at-a-time precondition (see `compileAndRunAsync`) and read by tests /// one-invocation-at-a-time precondition (see `compileAndRunAsync`) and read by tests
@@ -39,6 +40,14 @@ public final class LiveSession: @unchecked Sendable {
public let engine: SynthesisEngine public let engine: SynthesisEngine
/// Output-tapping oscilloscope capture for the editor's scope view. When a
/// fresh tap is installed at init (the engine is not yet running and has no
/// tap), this is that capture; if the engine already had a `scopeTap`, this
/// reuses it; it is `nil` only when no tap is present (attachment declined,
/// or the engine was already running with no tap). Must be installed before
/// `start()`.
public let scope: ScopeCapture?
/// `-I` paths threaded to `swiftc` for module discovery. /// `-I` paths threaded to `swiftc` for module discovery.
public let importPaths: [URL] public let importPaths: [URL]
@@ -53,27 +62,95 @@ public final class LiveSession: @unchecked Sendable {
/// runtime without `DYLD_LIBRARY_PATH` ceremony. /// runtime without `DYLD_LIBRARY_PATH` ceremony.
public let rpaths: [URL] public let rpaths: [URL]
// Prewarm lifecycle — guarded by `trackingLock`. `_prewarmed` flips true
// when a prewarm completes; `_prewarming` guards a call in flight so
// repeat calls (e.g. a view re-appearing) don't spawn a second swiftc.
private var _prewarmed: Bool = false
private var _prewarming: Bool = false
/// Side-channel for snippet `context.reportSampleRate(_:)` calls. Tests read /// Side-channel for snippet `context.reportSampleRate(_:)` calls. Tests read
/// via `@testable import`; not part of the public API. /// via `@testable import`; not part of the public API.
internal var reportedSampleRate: Double? internal var reportedSampleRate: Double?
/// Side-channel for snippet `context.reportMessage(_:)` calls. Tests read /// Most recent snippet `context.reportMessage(_:)` value (tests read this via
/// via `@testable import`; not part of the public API. /// `@testable import`). Backed by the internal message log (`_messageLog`).
internal var lastSnippetMessage: String? internal var lastSnippetMessage: String? { _messageLog.last }
/// Accumulated `context.reportMessage(_:)` output (and host-side notices like
/// a dropped slot swap) since the last drain. Main-thread only — appended
/// during the synchronous snippet entry, drained by the host after each run.
private var _messageLog: [String] = []
/// Append a snippet/host message to the log. Main-thread only.
internal func appendMessage(_ message: String) {
_messageLog.append(message)
}
/// Return and clear the accumulated messages. Called by the host after a run
/// to move them into its console.
public func drainMessages() -> [String] {
let out: [String] = _messageLog
_messageLog.removeAll()
return out
}
// Tracked state — all access guarded by `trackingLock`. // Tracked state — all access guarded by `trackingLock`.
private let trackingLock: NSLock = NSLock() private let trackingLock: NSLock = NSLock()
private var trackedSynths: [any Synthesizer] = [] private var trackedSynths: [any Synthesizer] = []
private var loadedSnippets: [CompiledSnippet] = [] private var loadedSnippets: [CompiledSnippet] = []
// A named-slot occupant plus the sample time its add was scheduled at.
// The add time lets a later teardown schedule the occupant's removal no
// earlier than its own add, so a still-pending *scheduled* voice (quantized
// swap not yet fired) is never orphaned by an immediate clear or an earlier
// re-swap. See `removeSlotOccupant`.
private struct SlotEntry {
let synth: any Synthesizer
let addTime: SampleTime
}
// Named slots — `Pdef`-style persistent voices, keyed by name. Kept
// separate from the anonymous `trackedSynths` so they SURVIVE a
// non-additive re-evaluation: re-running a `context.play(slot: "bass") { … }`
// definition replaces just that voice in place (via `assignSlot`) instead of
// being cleared with the anonymous synths. Guarded by `trackingLock`.
private var slottedSynths: [String: SlotEntry] = [:]
// Swap-quantization config + pending-swap signal — all guarded by
// `trackingLock`. When `_swapClock` is set and `_swapQuantize` is not
// `.immediate`, a slot swap schedules the new voice's add and the old
// voice's removal at the next musical boundary instead of taking effect at
// once (latency masking). `_pendingSwapBeat` is the latest target beat of a
// not-yet-fired scheduled swap, surfaced via ``pendingSwapBeat``.
private var _swapClock: LyrebirdClock?
private var _swapQuantize: SwapQuantize = .immediate
private var _pendingSwapBeat: Double?
/// Samples per channel the scope captures per display frame.
private static let scopeBufferSize: Int = 1024
/// - Parameter attachScope: When `true` (default) and the engine is not yet
/// running and has no existing tap, install a ``ScopeCapture`` on the first
/// one or two output buses for the editor's scope view.
public init( public init(
engine: SynthesisEngine, engine: SynthesisEngine,
attachScope: Bool = true,
importPaths: [URL] = LiveSession.defaultImportPaths(), importPaths: [URL] = LiveSession.defaultImportPaths(),
librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(), librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(),
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompile"], libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
rpaths: [URL] = LiveSession.defaultRpaths() rpaths: [URL] = LiveSession.defaultRpaths()
) { ) {
self.engine = engine self.engine = engine
// Install the scope tap before the host calls `start()` (the RT thread
// caches `scopeTap` at start; setting it afterwards is a no-op).
if attachScope, !engine.isRunning, engine.scopeTap == nil, engine.numOutputChannels >= 1 {
let buses: [Int] = Array(0..<min(2, engine.numOutputChannels))
let capture: ScopeCapture = ScopeCapture(buses: buses, bufferSize: LiveSession.scopeBufferSize)
engine.scopeTap = capture
self.scope = capture
} else {
self.scope = engine.scopeTap
}
self.importPaths = importPaths self.importPaths = importPaths
self.librarySearchPaths = librarySearchPaths self.librarySearchPaths = librarySearchPaths
self.libraries = libraries self.libraries = libraries
@@ -91,7 +168,7 @@ public final class LiveSession: @unchecked Sendable {
/// (⌘⇧↩ semantics in the future `LyrebirdScratchView` editor). /// (⌘⇧↩ semantics in the future `LyrebirdScratchView` editor).
/// - Returns: The compiled snippet handle. Retained internally so the dylib /// - Returns: The compiled snippet handle. Retained internally so the dylib
/// stays mapped; callers can ignore it. /// stays mapped; callers can ignore it.
/// `@MainActor` (Phase 203): runs the snippet entry — and thus the user body's /// `@MainActor`: runs the snippet entry — and thus the user body's
/// `MainActor.assumeIsolated { … }` and any `context.play(_:)` → `engine.add` — on the /// `MainActor.assumeIsolated { … }` and any `context.play(_:)` → `engine.add` — on the
/// main thread, synchronously (swiftc compile included). The async variant /// main thread, synchronously (swiftc compile included). The async variant
/// ``compileAndRunAsync(_:additive:)`` keeps the compile off-main. /// ``compileAndRunAsync(_:additive:)`` keeps the compile off-main.
@@ -112,8 +189,8 @@ public final class LiveSession: @unchecked Sendable {
/// engine-touching steps (`clearTracked()` and the snippet entry via `runEntry`) then run /// engine-touching steps (`clearTracked()` and the snippet entry via `runEntry`) then run
/// on the **main actor**. /// on the **main actor**.
/// ///
/// Running the entry on the main actor matters (Phase 203): the snippet's /// Running the entry on the main actor matters: the snippet's
/// `context.play(_:)` calls `engine.add(_:)`, which is `@MainActor` (Phase 201) and /// `context.play(_:)` calls `engine.add(_:)`, which is `@MainActor` and
/// mutates `engine.nodeTreeMirror` — state observed by SwiftUI on the main thread. A /// 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 /// `nonisolated async` method resumes on the generic executor, NOT the caller's actor, so
/// the hop is explicit here rather than assumed. /// the hop is explicit here rather than assumed.
@@ -208,9 +285,367 @@ public final class LiveSession: @unchecked Sendable {
trackedSynths.append(synth) trackedSynths.append(synth)
} }
// MARK: - Named slots
/// Number of named slots currently holding a synth. Thread-safe.
public var slotCount: Int {
trackingLock.lock(); defer { trackingLock.unlock() }
return slottedSynths.count
}
/// Names of the currently-populated slots. Thread-safe.
public var slotNames: [String] {
trackingLock.lock(); defer { trackingLock.unlock() }
return Array(slottedSynths.keys)
}
/// Install `synth` into the named `slot` immediately, replacing any synth
/// previously held there.
///
/// Internal hook for the immediate path of ``swapSlot(_:synth:)``. **Call
/// after `engine.add(synth)` has succeeded** — the new voice is live before
/// the old one is torn down, so a slot replacement is a brief overlap rather
/// than a silent gap. The previous occupant is removed via
/// ``removeSlotOccupant(_:desired:)`` (scheduled no earlier than its own
/// add, so a still-pending scheduled voice is never orphaned). Thread-safe;
/// `engine.remove` runs outside the lock.
func assignSlot(_ name: String, synth: any Synthesizer) {
let now: SampleTime = engine.currentTime
let previous: SlotEntry?
do {
trackingLock.lock(); defer { trackingLock.unlock() }
previous = slottedSynths[name]
slottedSynths[name] = SlotEntry(synth: synth, addTime: now)
}
if let previous: SlotEntry = previous {
removeSlotOccupant(previous, desired: now)
}
}
/// Remove every named-slot synth from the engine and clear all slots.
/// Anonymous tracked synths are untouched — pair with ``clearTracked()``
/// for a full reset.
public func clearSlots() {
let now: SampleTime = engine.currentTime
let snapshot: [SlotEntry]
do {
trackingLock.lock(); defer { trackingLock.unlock() }
snapshot = Array(slottedSynths.values)
slottedSynths.removeAll()
}
for entry: SlotEntry in snapshot {
removeSlotOccupant(entry, desired: now)
}
}
/// Remove the synth in the named `slot` (if any) from the engine and clear
/// the slot. No-op when the slot is empty. Returns `true` if a synth was
/// removed.
@discardableResult
public func clearSlot(_ name: String) -> Bool {
let now: SampleTime = engine.currentTime
let previous: SlotEntry?
do {
trackingLock.lock(); defer { trackingLock.unlock() }
previous = slottedSynths.removeValue(forKey: name)
}
if let previous: SlotEntry = previous {
removeSlotOccupant(previous, desired: now)
return true
}
return false
}
/// **Gracefully release** the synth in the named `slot` (trigger its
/// envelope release phase) and drop the slot handle, so the voice tails out
/// and then frees itself via its own done-action — rather than being hard-cut
/// like ``clearSlot(_:)``. This is the live-coding "let go of this voice"
/// gesture: pair it with ``SnippetContext/play(slot:_:)-…`` to start a
/// persistent voice under a name and release it later from a separate
/// evaluation.
///
/// The handle is dropped **only if the release succeeds**, so a voice with no
/// gate to release (its `release(engine:)` throws) stays in the slot and can
/// still be stopped with ``clearSlot(_:)`` — it is never orphaned.
///
/// On success the voice is moved from the slot map into the anonymous
/// tracked list, so it remains reachable by ``clearTracked()`` / ``resetAll()``
/// (the toolbar "Clear Synths"). A well-behaved voice self-frees via its
/// done-action before then; a mis-configured one that never self-frees is
/// still reclaimable rather than leaked until a process restart. (A later
/// hard `engine.remove` on an already-self-freed synth is a harmless no-op.)
///
/// - Parameter name: Slot to release.
/// - Returns: `true` if a gated voice was released; `false` if the slot was
/// empty or its occupant had no gate (reported via `lastSnippetMessage`).
///
/// The identity guard below (`… === entry.synth`) is load-bearing, not
/// defensive dead code: `clearSlot` / `clearSlots` / `resetAll` are
/// nonisolated and may run on another thread while this `release(engine:)`
/// call is in flight on the main actor.
@MainActor
@discardableResult
public func releaseSlot(_ name: String) -> Bool {
let entry: SlotEntry?
do {
trackingLock.lock(); defer { trackingLock.unlock() }
entry = slottedSynths[name]
}
guard let entry: SlotEntry = entry else { return false }
do {
try entry.synth.release(engine: engine)
// Released — free the name for reuse and keep the voice reachable by
// the tracked-synth sweep (its safety net until it self-frees).
trackingLock.lock(); defer { trackingLock.unlock() }
if slottedSynths[name]?.synth === entry.synth {
slottedSynths[name] = nil
trackedSynths.append(entry.synth)
}
return true
} catch {
appendMessage(
"slot '\(name)': release failed (\(error)) — use clearSlot() to stop it")
return false
}
}
/// Remove a slot occupant, scheduling the removal no earlier than the
/// occupant's own add time (`max(desired, addTime)`) so a still-pending
/// scheduled add is never orphaned. `desired` is the caller's intended
/// removal time — a swap boundary, or the current time for an immediate
/// teardown. Because the occupant's add is always enqueued before this
/// removal and the engine's per-block event sort is stable at equal times,
/// an add and removal landing on the same sample apply add-then-removal, so
/// the voice is always cleaned up. Runs outside `trackingLock`.
@discardableResult
private func removeSlotOccupant(_ entry: SlotEntry, desired: SampleTime) -> Bool {
let removeAt: SampleTime = max(desired, entry.addTime)
return engine.remove(entry.synth, at: removeAt)
}
// MARK: - Session reset + snippet accounting
/// Panic / clear-everything valve: remove every snippet-played synth — both
/// the anonymous tracked ones (``clearTracked()``) and every named slot
/// (``clearSlots()``) — from the engine, and clear the pending-swap signal.
/// Stops all snippet audio and gives a clean slate without tearing down the
/// engine.
///
/// It does **not** reclaim the compiled snippet dylibs — see
/// ``loadedSnippetCount``. Reclaiming that memory would require `dlclose`,
/// which is unsafe for these Swift dylibs: `dlopen` registers their type
/// metadata and protocol-conformance records into process-global runtime
/// caches that `dlclose` does not deregister, so unmapping the dylib leaves
/// those caches dangling. Mapped snippet memory is therefore reclaimed only
/// by restarting the process. (The interpreted-graph path on the roadmap
/// avoids dylibs entirely and is the structural fix.)
///
/// - Precondition: same one-invocation-at-a-time caveat as
/// ``compileAndRunAsync(_:additive:)``. Calling this concurrently with an
/// in-flight compile can interleave the internal `clearTracked()` with a
/// not-yet-completed `runEntry`, missing a just-added synth (which then
/// leaks until process restart). The built-in ``LyrebirdScratchModel``
/// serialises through its `isCompiling` flag. This is also not a single
/// atomic critical section — the synth removal and the pending-swap clear
/// take `trackingLock` separately — which is acceptable for a panic valve.
public func resetAll() {
clearTracked()
clearSlots()
trackingLock.lock(); defer { trackingLock.unlock() }
_pendingSwapBeat = nil
}
/// Number of compiled snippet dylibs currently mapped into the process.
///
/// Each ⌘↩ compiles a new dylib that stays mapped for the process's lifetime
/// (unloading is unsafe — see ``resetAll()``), so within a session this only
/// grows. Exposed for host observability, e.g. a "restart to reclaim memory"
/// nudge after a very long session. Thread-safe.
public var loadedSnippetCount: Int {
trackingLock.lock(); defer { trackingLock.unlock() }
return loadedSnippets.count
}
// MARK: - Swap quantization (on-beat latency masking)
/// Clock that slot swaps quantize against. When `nil` (default), swaps are
/// always immediate regardless of ``swapQuantize``. Setting it clears any
/// pending-swap signal (``pendingSwapBeat``). Thread-safe.
public var swapClock: LyrebirdClock? {
get { trackingLock.lock(); defer { trackingLock.unlock() }; return _swapClock }
set {
trackingLock.lock(); defer { trackingLock.unlock() }
_swapClock = newValue
_pendingSwapBeat = nil
}
}
/// When a named-slot swap becomes audible. Defaults to ``SwapQuantize/immediate``.
/// Only takes effect when ``swapClock`` is also set. Setting it clears any
/// pending-swap signal (``pendingSwapBeat``). Thread-safe.
public var swapQuantize: SwapQuantize {
get { trackingLock.lock(); defer { trackingLock.unlock() }; return _swapQuantize }
set {
trackingLock.lock(); defer { trackingLock.unlock() }
_swapQuantize = newValue
_pendingSwapBeat = nil
}
}
/// Target beat of the latest scheduled-but-not-yet-fired slot swap, or `nil`
/// when none is pending (immediate mode, the boundary has already passed, or
/// the swap config changed). Self-clearing: returns `nil` once the clock
/// reaches the target beat. Drives the editor's `.queued` readiness state.
///
/// When several slots have swaps pending at different beats this reports the
/// latest of them — treat it as "some swap is still outstanding", not "this
/// specific run's swap". Thread-safe, but not atomic against a concurrent
/// swap: the `_swapClock` snapshot and the `clock.currentBeat` read happen in
/// separate critical sections, so a swap scheduled between them may not yet
/// be reflected. Fine for the main-actor UI that consumes it.
public var pendingSwapBeat: Double? {
let target: Double?
let clock: LyrebirdClock?
do {
trackingLock.lock(); defer { trackingLock.unlock() }
target = _pendingSwapBeat
clock = _swapClock
}
guard let target: Double = target, let clock: LyrebirdClock = clock else { return nil }
return clock.currentBeat < target ? target : nil
}
/// Install `synth` into the named `slot`, quantizing the swap per
/// ``swapQuantize`` / ``swapClock``.
///
/// Immediate mode (`.immediate` or no clock): adds `synth` now and removes
/// the previous slot synth now (via ``assignSlot(_:synth:)``). Quantized
/// mode: schedules `synth`'s add and the previous synth's removal at the same
/// upcoming boundary sample time, so the swap is glitch-free and on-grid,
/// and records the target beat for ``pendingSwapBeat``.
///
/// Backs ``SnippetContext/play(slot:_:)``. `@MainActor` because it touches
/// the engine's node tree (`add`/`schedule`/`remove`).
///
/// - Throws: `EngineAddError` if the engine rejects the add/schedule; the
/// prior slot synth is left in place on throw.
@MainActor
func swapSlot(_ name: String, synth: any Synthesizer) throws {
let clock: LyrebirdClock?
let quantize: SwapQuantize
do {
trackingLock.lock(); defer { trackingLock.unlock() }
clock = _swapClock
quantize = _swapQuantize
}
if let clock: LyrebirdClock = clock, let beat: Double = quantize.targetBeat(clock: clock) {
let time: SampleTime = clock.sampleTime(beat: beat)
try engine.schedule(synth, at: time)
scheduleSlotReplace(name, newSynth: synth, at: time, targetBeat: beat)
} else {
try engine.add(synth)
assignSlot(name, synth: synth)
}
}
/// Commit a scheduled slot replacement: swap the dictionary entry, schedule
/// removal of the previous synth at the boundary `time` (no earlier than its
/// own add), and record the pending target beat. Call only after
/// `engine.schedule(new, at: time)` succeeded. `engine.remove` runs outside
/// the lock; a dropped removal (pending queue full) is surfaced via
/// `lastSnippetMessage` rather than silently leaving an overlap.
private func scheduleSlotReplace(
_ name: String,
newSynth: any Synthesizer,
at time: SampleTime,
targetBeat: Double
) {
let previous: SlotEntry?
do {
trackingLock.lock(); defer { trackingLock.unlock() }
previous = slottedSynths[name]
slottedSynths[name] = SlotEntry(synth: newSynth, addTime: time)
_pendingSwapBeat = max(_pendingSwapBeat ?? targetBeat, targetBeat)
}
if let previous: SlotEntry = previous {
let removed: Bool = removeSlotOccupant(previous, desired: time)
if !removed {
appendMessage(
"slot '\(name)': previous voice removal dropped (pending queue full) — voices may overlap")
}
}
}
// MARK: - Prewarm
/// `true` once a ``prewarm()`` has **succeeded** for this session. A prewarm
/// that failed (e.g. missing toolchain) leaves this `false` so a later call
/// retries. Thread-safe.
public var isPrewarmed: Bool {
trackingLock.lock(); defer { trackingLock.unlock() }
return _prewarmed
}
/// Warm the module cache in the background so the first real ⌘↩ is fast.
///
/// The cold `LyrebirdSynth` `.pcm` build costs ~2–3 s; without a prewarm it
/// lands on the user's first compile. This kicks a detached, `.utility`
/// type-check of a trivial import-only snippet (via
/// ``LiveCompiler/prewarm(extraSwiftcArgs:)``) that warms swiftc's default
/// module cache, so the first `compileAndRunAsync` hits a warm cache
/// (~0.1 s). All the work — including the filesystem walk that builds the
/// compiler flags — runs on the detached task, not the caller's thread.
///
/// Idempotent: a call while a prewarm has already succeeded or is in flight
/// is a no-op. A *failed* prewarm leaves ``isPrewarmed`` `false` (a later
/// call retries); the real compile then simply pays the build itself, so the
/// failure is non-fatal and intentionally not thrown.
///
/// - Returns: The detached `Task`, so callers/tests can `await` its `value`.
/// The no-op case returns an already-scheduled empty task.
@discardableResult
public func prewarm() -> Task<Void, Never> {
let shouldRun: Bool
do {
trackingLock.lock(); defer { trackingLock.unlock() }
shouldRun = !_prewarmed && !_prewarming
if shouldRun { _prewarming = true }
}
guard shouldRun else { return Task {} }
return Task.detached(priority: .utility) { [weak self] in
guard let self: LiveSession = self else { return }
// Off-main: build the flags (a small filesystem walk) here rather
// than on the caller (this method is a synchronous `nonisolated`
// call, so anything before the detached task runs on the caller).
let args: [String] = self.makeModuleResolutionArgs()
do {
try LiveCompiler.prewarm(extraSwiftcArgs: args)
self.finishPrewarm(succeeded: true)
} catch {
self.finishPrewarm(succeeded: false)
}
}
}
/// Record a ``prewarm()`` outcome: clear the in-flight flag, and mark warmed
/// only on success so a failed attempt can retry.
private func finishPrewarm(succeeded: Bool) {
trackingLock.lock(); defer { trackingLock.unlock() }
_prewarming = false
if succeeded { _prewarmed = true }
}
// MARK: - swiftc flag construction // MARK: - swiftc flag construction
private func makeSwiftcArgs() -> [String] { /// Module-resolution flags shared by the real compile and the prewarm:
/// `-I` import paths plus the Xcode + bare-SPM Clang module maps. No linker
/// flags — a `-typecheck` prewarm needs none. Deliberately does **not** pin
/// `-module-cache-path`: prewarm and the real compile both use swiftc's
/// default cache, so the prewarm warms exactly the cache the compile reads.
/// (Pinning a dedicated cache built fresh diverges its module metadata from
/// the already-loaded `libLyrebirdLiveCompileDynamic`, which turns the test
/// bundle's benign ObjC class-duplication warning into a hard cast crash.)
private func makeModuleResolutionArgs() -> [String] {
var args: [String] = [] var args: [String] = []
for path: URL in importPaths { for path: URL in importPaths {
args += ["-I", path.path] args += ["-I", path.path]
@@ -222,6 +657,26 @@ public final class LiveSession: @unchecked Sendable {
for url: URL in LiveSession.discoverClangModuleMaps(in: importPaths) { for url: URL in LiveSession.discoverClangModuleMaps(in: importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"] args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
} }
// Bare-SPM (`swift build` / `swift test`) layout: C-target module maps
// live at `<buildDir>/<CTarget>.build/module.modulemap`, which the Xcode
// discovery above does not cover. Surface them so a snippet's
// `import LyrebirdSynth` can resolve the underlying `LyrebirdC` clang
// module outside Xcode too.
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
#if os(Linux)
// Source-only system-library module maps (CALSA, LyrebirdC) — see the
// helper. Without CALSA's, a Linux `import LyrebirdSynth` fails to resolve.
for url: URL in LiveSession.discoverSourceSystemModuleMaps(in: importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
#endif
return args
}
private func makeSwiftcArgs() -> [String] {
var args: [String] = makeModuleResolutionArgs()
// When a Lyrebird dylib exists in any -L path, link against it // When a Lyrebird dylib exists in any -L path, link against it
// (-l<name>) and bake an rpath. When no dylib is found (Xcode SPM // (-l<name>) and bake an rpath. When no dylib is found (Xcode SPM
// case — modules statically linked into the host app), use // case — modules statically linked into the host app), use
@@ -242,7 +697,15 @@ public final class LiveSession: @unchecked Sendable {
args += ["-Xlinker", "-rpath", "-Xlinker", path.path] args += ["-Xlinker", "-rpath", "-Xlinker", path.path]
} }
} else { } else {
#if os(macOS)
args += ["-Xlinker", "-undefined", "-Xlinker", "dynamic_lookup"] args += ["-Xlinker", "-undefined", "-Xlinker", "dynamic_lookup"]
#else
// ELF has no Mach-O flat-namespace deferred lookup: a snippet resolves
// Lyrebird symbols by NEEDED-linking libLyrebirdDynamic.so, which needs
// it present in a -L path (i.e. hasDylib == true). Reaching here on
// Linux means no such library was found; emit no link flag so the link
// fails loudly rather than adding a macOS-only one.
#endif
} }
return args return args
} }
@@ -279,6 +742,71 @@ public final class LiveSession: @unchecked Sendable {
return found return found
} }
/// Locate SPM-generated Clang module maps for a `swift build` / `swift test`
/// layout. Each C target's map is emitted at
/// `<buildDir>/<CTarget>.build/module.modulemap`; the umbrella header path
/// inside is absolute, so the map alone is enough to resolve the module (no
/// extra `-I` needed). Empty under an Xcode SPM layout, where
/// `discoverClangModuleMaps` handles the `GeneratedModuleMaps` location
/// instead.
static func discoverSPMModuleMaps(in importPaths: [URL]) -> [URL] {
var found: [URL] = []
var visited: Set<String> = Set<String>()
for base: URL in importPaths {
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
at: base,
includingPropertiesForKeys: nil
) else { continue }
for entry: URL in entries where entry.pathExtension == "build" {
let probe: URL = entry.appendingPathComponent("module.modulemap")
if FileManager.default.fileExists(atPath: probe.path),
!visited.contains(probe.path) {
visited.insert(probe.path)
found.append(probe)
}
}
}
return found
}
#if os(Linux)
/// Linux only: locate the `CALSA` **system-library** module map, which lives
/// only in the package *source* tree (`Sources/CALSA/module.modulemap`),
/// never in the build dir — a `.systemLibrary` target emits no
/// `<CTarget>.build/module.modulemap`. `LyrebirdSynth` transitively imports
/// `CALSA` on Linux (the ALSA driver), so a snippet's `import LyrebirdSynth`
/// fails with `missing required module 'CALSA'` unless the map is surfaced.
/// macOS never hits this (Core Audio, no CALSA import). `LyrebirdC` is a
/// regular C target and IS covered by `discoverSPMModuleMaps` (build-tree
/// map) — adding its source map too would `redefinition of module 'LyrebirdC'`.
/// Walks up from each import path (bounded) to the package root.
static func discoverSourceSystemModuleMaps(in importPaths: [URL]) -> [URL] {
let maxWalk: Int = 8
let relativeMaps: [String] = [
"Sources/CALSA/module.modulemap",
]
var found: [URL] = []
var visited: Set<String> = Set<String>()
for start: URL in importPaths {
var cur: URL = start
for _ in 0..<maxWalk {
for rel: String in relativeMaps {
let probe: URL = cur.appendingPathComponent(rel)
if FileManager.default.fileExists(atPath: probe.path),
!visited.contains(probe.path) {
visited.insert(probe.path)
found.append(probe)
}
}
let parent: URL = cur.deletingLastPathComponent()
if parent == cur { break }
cur = parent
}
}
return found
}
#endif
// MARK: - Build-dir discovery // MARK: - Build-dir discovery
/// Best-effort discovery of the SPM `.build/<triple>/<config>` directory /// Best-effort discovery of the SPM `.build/<triple>/<config>` directory
@@ -288,7 +816,7 @@ public final class LiveSession: @unchecked Sendable {
/// ///
/// Searches, in order: /// Searches, in order:
/// 1. Walks up from `Bundle(for: LiveSession.self).bundleURL` — this resolves /// 1. Walks up from `Bundle(for: LiveSession.self).bundleURL` — this resolves
/// to the directory holding `libLyrebirdLiveCompile.dylib` at runtime, /// to the directory holding `libLyrebirdLiveCompileDynamic.dylib` at runtime,
/// which is the SPM debug/release dir. /// which is the SPM debug/release dir.
/// 2. Walks up from `Bundle.main.executableURL` — fallback for the case /// 2. Walks up from `Bundle.main.executableURL` — fallback for the case
/// where the host bundles the dylibs into an `.app`. /// where the host bundles the dylibs into an `.app`.
@@ -306,7 +834,10 @@ public final class LiveSession: @unchecked Sendable {
// (→ libLyrebirdDynamic.dylib); the module/target is `LyrebirdSynth` // (→ libLyrebirdDynamic.dylib); the module/target is `LyrebirdSynth`
// (LyrebirdSynth.swiftmodule). The consumer-facing `Lyrebird` product // (LyrebirdSynth.swiftmodule). The consumer-facing `Lyrebird` product
// is static and produces no dylib, so it is not a marker here. // is static and produces no dylib, so it is not a marker here.
let markers: [String] = ["libLyrebirdDynamic.dylib", "LyrebirdSynth.swiftmodule"] let markers: [String] = [
"libLyrebirdDynamic.\(livecompileSharedLibraryExtension)",
"LyrebirdSynth.swiftmodule",
]
for start: URL in candidates { for start: URL in candidates {
var cur: URL = start var cur: URL = start
for _ in 0..<maxWalk { for _ in 0..<maxWalk {
@@ -330,23 +861,42 @@ public final class LiveSession: @unchecked Sendable {
/// already resolved in the running process. /// already resolved in the running process.
public static func hasLyrebirdDylib(in buildDir: URL) -> Bool { public static func hasLyrebirdDylib(in buildDir: URL) -> Bool {
FileManager.default.fileExists( FileManager.default.fileExists(
atPath: buildDir.appendingPathComponent("libLyrebirdDynamic.dylib").path atPath: buildDir.appendingPathComponent(
"libLyrebirdDynamic.\(livecompileSharedLibraryExtension)"
).path
) )
} }
/// Prefer a populated staged artifacts dir (App Support, ungated) over the
/// SPM build dir (which lives under `~/Documents` in a dev checkout). Hosts
/// that want staging call ``stageArtifacts(from:to:)`` before constructing
/// the session; these defaults then resolve to the staged copy.
private static func resolvedArtifactsDir() -> URL? {
// Prefer the staged dir only when it is populated AND current relative to
// the live build dir — so a stale copy left by a different build (or a
// partial stage) never masquerades as the resolved artifacts for a host
// that did not itself stage.
if let staged: URL = stagedArtifactsDir(),
isArtifactsDirPopulated(staged),
stagedDirIsCurrent(staged) {
return staged
}
return currentBuildDir()
}
public static func defaultImportPaths() -> [URL] { public static func defaultImportPaths() -> [URL] {
guard let buildDir: URL = currentBuildDir() else { return [] } guard let dir: URL = resolvedArtifactsDir() else { return [] }
return [buildDir, buildDir.appendingPathComponent("Modules")] return [dir, dir.appendingPathComponent("Modules")]
} }
public static func defaultLibrarySearchPaths() -> [URL] { public static func defaultLibrarySearchPaths() -> [URL] {
guard let buildDir: URL = currentBuildDir() else { return [] } guard let dir: URL = resolvedArtifactsDir() else { return [] }
return [buildDir] return [dir]
} }
public static func defaultRpaths() -> [URL] { public static func defaultRpaths() -> [URL] {
guard let buildDir: URL = currentBuildDir() else { return [] } guard let dir: URL = resolvedArtifactsDir() else { return [] }
return [buildDir] return [dir]
} }
} }
@@ -0,0 +1,384 @@
// LiveSessionArtifactStaging.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Snippet compilation needs the Lyrebird module artifacts (swiftmodules, the
// Lyrebird dylibs, and the C-shim Clang module map + its umbrella header). In a
// dev checkout those live in the SPM build dir under `~/Documents`, so a
// non-sandboxed host reading them — and the `swiftc` it spawns reading them —
// trips the macOS "wants to access your Documents folder" TCC gate.
//
// Staging copies the minimal artifact set into
// `~/Library/Application Support/LyrebirdScratch/LiveCompile/`, an ungated
// location, and rewrites the C module map's absolute umbrella-header path to the
// staged copy. The default `-I` / `-L` / rpath resolution then prefers the
// staged dir, so a shipped app compiles snippets without ever touching a
// permission-gated folder.
import Foundation
#if os(macOS) || os(Linux)
extension LiveSession {
/// Name of the artifacts subdirectory a host may ship inside its app bundle
/// (`<App>.app/Contents/Resources/<name>`). Staging prefers this over the
/// dev build dir when present, so a shipped app never reads outside its
/// bundle or App Support.
public static let bundledArtifactsDirName: String = "LyrebirdArtifacts"
/// `~/Library/Application Support/LyrebirdScratch/LiveCompile` — the ungated
/// destination for staged compile artifacts. `nil` only if the Application
/// Support directory can't be resolved.
public static func stagedArtifactsDir() -> URL? {
guard let base: URL = FileManager.default.urls(
for: .applicationSupportDirectory,
in: .userDomainMask
).first else { return nil }
return base
.appendingPathComponent("LyrebirdScratch", isDirectory: true)
.appendingPathComponent("LiveCompile", isDirectory: true)
}
/// Whether `dir` is a usable compile root: it has a `Modules/` directory
/// holding at least one `.swiftmodule`.
public static func isArtifactsDirPopulated(_ dir: URL) -> Bool {
let modules: URL = dir.appendingPathComponent("Modules", isDirectory: true)
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
at: modules,
includingPropertiesForKeys: nil
) else { return false }
return entries.contains { $0.pathExtension == "swiftmodule" }
}
/// Where to stage FROM. Prefers a `LyrebirdArtifacts` directory shipped in
/// the app bundle's `Resources` (self-contained, never under a gated
/// folder); falls back to the dev SPM build dir.
public static func artifactSourceDir() -> URL? {
if let resources: URL = Bundle.main.resourceURL {
let bundled: URL = resources.appendingPathComponent(
bundledArtifactsDirName,
isDirectory: true
)
if isArtifactsDirPopulated(bundled) { return bundled }
}
return currentBuildDir()
}
/// Copy the minimal artifact set from `source` (default: ``artifactSourceDir()``)
/// into `destination` (default: ``stagedArtifactsDir()``), rewriting the C
/// module map to point at a staged copy of its umbrella header. Idempotent:
/// skips the copy when the destination is already newer than the source.
/// Best-effort — returns the staged dir on success, `nil` on any failure or
/// when no source/destination could be resolved.
///
/// - Note: In a dev checkout the source is the build dir under `~/Documents`,
/// so the one-time copy still reads that gated folder; every subsequent
/// launch reuses the staged copy and reads only App Support. A shipped app
/// whose `Resources/LyrebirdArtifacts` is populated never reads a gated
/// folder at all.
@discardableResult
public static func stageArtifacts(
from source: URL? = nil,
to destination: URL? = nil
) -> URL? {
guard let dest: URL = destination ?? stagedArtifactsDir() else { return nil }
guard let src: URL = source ?? artifactSourceDir() else { return nil }
do {
try stageArtifactsThrowing(from: src, to: dest)
} catch {
return nil
}
return isArtifactsDirPopulated(dest) ? dest : nil
}
// MARK: - Implementation
static let stageReceiptName: String = ".stage-receipt"
/// Slack in the receipt-vs-source stamp comparison. A `Date` stores seconds
/// since 2001; the receipt records `timeIntervalSince1970`, so reconstructing
/// it adds then subtracts the ~978-million-second epoch offset — floating-
/// point arithmetic at that magnitude perturbs the sub-second fraction, so a
/// bit-exact `>=` can spuriously read "stale" (the string encoding itself is
/// exact; the loss is in the epoch conversion, not the receipt). mtime
/// staleness needs no sub-second resolution — a rebuild moves mtimes by far
/// more than a second.
private static let stageStampToleranceSeconds: TimeInterval = 1.0
/// Whether a staged dir at `dest` is current relative to the artifact source
/// it would stage from. When no source is discoverable (a shipped app with no
/// build dir and no bundled artifacts), any populated staged dir is trusted.
/// Otherwise the receipt must be at or after the source's newest artifact —
/// so a staged copy left by a *different* build (or a partial stage that never
/// wrote a receipt) is ignored and the resolver falls back to the build dir.
/// Compared against ``artifactSourceDir()`` (not the build dir directly) so
/// the base matches what ``stageArtifacts(from:to:)`` actually copies from.
static func stagedDirIsCurrent(_ dest: URL) -> Bool {
guard let source: URL = artifactSourceDir() else { return true }
guard let prior: Date = stageReceiptDate(dest.appendingPathComponent(stageReceiptName, isDirectory: false))
else { return false }
return prior.timeIntervalSince1970 >= sourceArtifactStamp(source).timeIntervalSince1970 - stageStampToleranceSeconds
}
private static func stageArtifactsThrowing(from src: URL, to dest: URL) throws {
let fm: FileManager = FileManager.default
let srcStamp: Date = sourceArtifactStamp(src)
// Up to date? A populated dest whose receipt is at or after the source's
// newest artifact mtime needs no re-copy.
if isArtifactsDirPopulated(dest),
let prior: Date = stageReceiptDate(dest.appendingPathComponent(stageReceiptName, isDirectory: false)),
prior.timeIntervalSince1970 >= srcStamp.timeIntervalSince1970 - stageStampToleranceSeconds {
return
}
// Refuse to clobber a directory we did not create: an existing, non-empty
// `dest` must look like a prior staging root (a receipt or a `Modules/`
// dir) before we replace it. Guards a typo'd `to:` from wiping real data.
if fm.fileExists(atPath: dest.path), !isReplaceableStagingDest(dest) {
throw ArtifactStagingError.destinationNotAStagingRoot(dest.path)
}
// Build everything in a private sibling temp dir, then atomically swap it
// over `dest`. `dest` is therefore only ever fully-complete or absent — a
// failed/partial stage never leaves a dir that *looks* valid, and two
// stagers racing the same `dest` can't observe a half-written tree.
let staging: URL = dest.deletingLastPathComponent()
.appendingPathComponent(".\(dest.lastPathComponent).staging-\(UUID().uuidString)", isDirectory: true)
try fm.createDirectory(at: staging, withIntermediateDirectories: true)
defer { try? fm.removeItem(at: staging) }
// 1. Swift modules.
let srcModules: URL = src.appendingPathComponent("Modules", isDirectory: true)
if fm.fileExists(atPath: srcModules.path) {
try fm.copyItem(at: srcModules, to: staging.appendingPathComponent("Modules", isDirectory: true))
}
// 2. Lyrebird dylibs (the snippet links these and bakes an rpath here;
// at dlopen dyld matches the already-loaded install name, so the copy is
// a link-time search target, not a second loaded image).
for dylib: URL in lyrebirdDylibs(in: src) {
try? fm.copyItem(at: dylib, to: staging.appendingPathComponent(dylib.lastPathComponent))
}
// 2.5. Self-contained C-shim module dirs (`<Module>.build/` holding a
// `module.modulemap` whose header path is relative to the map — as shipped
// in the app bundle's LyrebirdArtifacts). Copy the whole dir verbatim so the
// relative header resolves at the staged location; no path rewrite needed.
// (The absolute-`umbrella header` dev-build maps are handled separately in
// step 3 — a relative-header map is skipped there, so no double-write.)
copySelfContainedModuleMapDirs(from: src, writeInto: staging)
// 3. C module maps + their umbrella headers. Files are written under the
// temp `staging` dir, but the umbrella path baked into each map must
// reference the FINAL `dest` (where they land after the atomic swap) —
// the temp dir is deleted.
stageClangModuleMaps(from: src, writeInto: staging, finalRoot: dest)
#if os(Linux)
// 3.5. CALSA (the ALSA system library) has no `<Module>.build/` map in the
// build dir — its module map lives only in the package source — so the
// steps above miss it and a snippet's `import LyrebirdSynth` can't resolve
// CALSA from the staged root. Copy the source module dir (map + relative
// include/) into a self-contained `CALSA.build/` that `discoverSPMModuleMaps`
// then finds at the staged location. macOS never imports CALSA.
stageCALSAModuleMap(from: src, writeInto: staging)
#endif
// Receipt: store the source stamp so the next call can skip an unchanged
// source.
let stampText: String = String(srcStamp.timeIntervalSince1970)
try stampText.write(
to: staging.appendingPathComponent(stageReceiptName, isDirectory: false),
atomically: true,
encoding: .utf8
)
// Re-check the clobber guard immediately before the swap: the copy phase
// above is a window in which something could have materialized a
// non-staging directory at `dest`. Holding the guard across the whole
// operation, not just at entry, keeps `replaceItemAt` from silently
// wiping a dir we would have refused.
if fm.fileExists(atPath: dest.path), !isReplaceableStagingDest(dest) {
throw ArtifactStagingError.destinationNotAStagingRoot(dest.path)
}
// Atomic swap into place.
if fm.fileExists(atPath: dest.path) {
_ = try fm.replaceItemAt(dest, withItemAt: staging)
} else {
try fm.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true)
do {
try fm.moveItem(at: staging, to: dest)
} catch {
// A concurrent stager may have created `dest` between the check
// and the move; if it is now a valid root, treat as success.
guard isArtifactsDirPopulated(dest) else { throw error }
}
}
}
/// The Lyrebird dylibs present at the top level of `src`.
private static func lyrebirdDylibs(in src: URL) -> [URL] {
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
at: src,
includingPropertiesForKeys: nil
) else { return [] }
return entries.filter {
$0.pathExtension == livecompileSharedLibraryExtension
&& $0.lastPathComponent.hasPrefix("libLyrebird")
}
}
#if os(Linux)
/// Copy the CALSA source module dir (`Sources/CALSA/`: `module.modulemap` +
/// `include/calsa-shim.h`) into `staging/CALSA.build/`, so the staged root is a
/// self-contained compile root for a snippet that transitively imports CALSA.
/// The map's header path is relative, so it resolves verbatim at the staged
/// location. Best-effort: if the source map isn't found (e.g. a detached build
/// dir), staging proceeds without it and the snippet compile surfaces the gap.
private static func stageCALSAModuleMap(from src: URL, writeInto staging: URL) {
let fm: FileManager = FileManager.default
guard let calsaMap: URL = LiveSession.discoverSourceSystemModuleMaps(in: [src]).first else {
return
}
let calsaSrcDir: URL = calsaMap.deletingLastPathComponent()
let stagedDir: URL = staging.appendingPathComponent("CALSA.build", isDirectory: true)
try? fm.copyItem(at: calsaSrcDir, to: stagedDir)
}
#endif
/// A `dest` is safe to replace when it doesn't exist, is empty, or looks like
/// a prior staging root (has a receipt or a `Modules/` dir).
private static func isReplaceableStagingDest(_ dest: URL) -> Bool {
let fm: FileManager = FileManager.default
guard fm.fileExists(atPath: dest.path) else { return true }
if fm.fileExists(atPath: dest.appendingPathComponent(stageReceiptName).path) { return true }
if fm.fileExists(atPath: dest.appendingPathComponent("Modules").path) { return true }
let contents: [URL] = (try? fm.contentsOfDirectory(at: dest, includingPropertiesForKeys: nil)) ?? []
return contents.isEmpty
}
/// For each `<Module>.build/module.modulemap` under `src` whose umbrella
/// header exists, copy the header's `include` directory into
/// `writeInto/<Module>.headers` and write a staged map whose umbrella path
/// points at `finalRoot/<Module>.headers/<header>` — the location those files
/// occupy after the caller's atomic swap of `writeInto` onto `finalRoot`.
/// Best-effort per map: a map with no resolvable umbrella header, or one that
/// fails to copy, is skipped without aborting the rest.
/// Copy each `<Module>.build/` directory under `src` that holds a
/// `module.modulemap` **without** an `umbrella header` directive — i.e. a
/// self-contained map whose `header "…"` path is relative to the map's own
/// directory (as bundled in the app's `LyrebirdArtifacts`). The whole dir is
/// copied verbatim (map + adjacent headers), so the relative path resolves at
/// the staged location and `discoverSPMModuleMaps` finds the copied map. Maps
/// with an absolute `umbrella header` are left for ``stageClangModuleMaps``.
private static func copySelfContainedModuleMapDirs(from src: URL, writeInto staging: URL) {
let fm: FileManager = FileManager.default
guard let entries: [URL] = try? fm.contentsOfDirectory(
at: src,
includingPropertiesForKeys: nil
) else { return }
for buildDir: URL in entries where buildDir.pathExtension == "build" {
let map: URL = buildDir.appendingPathComponent("module.modulemap", isDirectory: false)
guard fm.fileExists(atPath: map.path),
let text: String = try? String(contentsOf: map, encoding: .utf8),
umbrellaHeaderPath(in: text) == nil // self-contained (relative header) only
else { continue }
let stagedDir: URL = staging.appendingPathComponent(buildDir.lastPathComponent, isDirectory: true)
try? fm.removeItem(at: stagedDir)
try? fm.copyItem(at: buildDir, to: stagedDir)
}
}
private static func stageClangModuleMaps(from src: URL, writeInto staging: URL, finalRoot dest: URL) {
let fm: FileManager = FileManager.default
guard let entries: [URL] = try? fm.contentsOfDirectory(
at: src,
includingPropertiesForKeys: nil
) else { return }
for buildDir: URL in entries where buildDir.pathExtension == "build" {
let map: URL = buildDir.appendingPathComponent("module.modulemap", isDirectory: false)
guard fm.fileExists(atPath: map.path),
let text: String = try? String(contentsOf: map, encoding: .utf8),
let umbrella: String = umbrellaHeaderPath(in: text)
else { continue }
let headerURL: URL = URL(fileURLWithPath: umbrella)
guard fm.fileExists(atPath: headerURL.path) else { continue }
let includeDir: URL = headerURL.deletingLastPathComponent()
let moduleName: String = buildDir.deletingPathExtension().lastPathComponent
let headerName: String = headerURL.lastPathComponent
// Files go under the temp staging dir…
let stagedHeaders: URL = staging.appendingPathComponent("\(moduleName).headers", isDirectory: true)
let stagedMapDir: URL = staging.appendingPathComponent(buildDir.lastPathComponent, isDirectory: true)
// …but the baked umbrella path names their final resting place.
let finalHeader: URL = dest
.appendingPathComponent("\(moduleName).headers", isDirectory: true)
.appendingPathComponent(headerName, isDirectory: false)
let rewritten: String = text.replacingOccurrences(of: umbrella, with: finalHeader.path)
do {
try? fm.removeItem(at: stagedHeaders)
try fm.copyItem(at: includeDir, to: stagedHeaders)
try fm.createDirectory(at: stagedMapDir, withIntermediateDirectories: true)
try rewritten.write(
to: stagedMapDir.appendingPathComponent("module.modulemap", isDirectory: false),
atomically: true,
encoding: .utf8
)
} catch {
continue
}
}
}
/// Extract the path inside `umbrella header "..."` from a Clang module map.
static func umbrellaHeaderPath(in modulemap: String) -> String? {
guard let marker: Range<String.Index> = modulemap.range(of: "umbrella header") else { return nil }
let after: Substring = modulemap[marker.upperBound...]
guard let open: String.Index = after.firstIndex(of: "\"") else { return nil }
let afterOpen: Substring = after[after.index(after: open)...]
guard let close: String.Index = afterOpen.firstIndex(of: "\"") else { return nil }
return String(afterOpen[..<close])
}
/// Newest modification date among the artifacts we actually copy — a cheap
/// staleness proxy that avoids walking the whole build tree. Derives the
/// dylib set from the same wildcard scan the copy step uses, so a new/renamed
/// Lyrebird dylib can't slip past the freshness check.
///
/// It does not probe the C module map or its umbrella header directly: a
/// header edit forces `swift build` to rebuild the downstream swiftmodules
/// too, which moves `Modules/`'s mtime — so a header change is caught
/// transitively. (A hand-edited header with no rebuild would not re-stage,
/// but that state never occurs from a normal build.)
private static func sourceArtifactStamp(_ src: URL) -> Date {
let fm: FileManager = FileManager.default
var newest: Date = Date.distantPast
var probes: [URL] = [src.appendingPathComponent("Modules", isDirectory: true)]
probes += lyrebirdDylibs(in: src)
for probe: URL in probes {
if let attrs: [FileAttributeKey: Any] = try? fm.attributesOfItem(atPath: probe.path),
let date: Date = attrs[.modificationDate] as? Date,
date > newest {
newest = date
}
}
return newest
}
private static func stageReceiptDate(_ receipt: URL) -> Date? {
guard let text: String = try? String(contentsOf: receipt, encoding: .utf8),
let interval: TimeInterval = TimeInterval(text.trimmingCharacters(in: .whitespacesAndNewlines))
else { return nil }
return Date(timeIntervalSince1970: interval)
}
}
#endif
@@ -4,14 +4,14 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound // Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144 // LyrebirdLiveCompile
// //
// `LiveSession.compileAndRun(_:additive:)` throws this richer error so callers // `LiveSession.compileAndRun(_:additive:)` throws this richer error so callers
// see diagnostics pre-mapped to user-snippet coordinates. Other `LiveCompileError` // see diagnostics pre-mapped to user-snippet coordinates. Other `LiveCompileError`
// cases (toolchain missing, dlopen failure, etc.) pass through under // cases (toolchain missing, dlopen failure, etc.) pass through under
// `.compilerError`. // `.compilerError`.
#if os(macOS) #if os(macOS) || os(Linux)
public enum LiveSessionError: Error, CustomStringConvertible, Sendable { public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
/// Snippet failed to compile. `diagnostics` are already line-mapped via the /// Snippet failed to compile. `diagnostics` are already line-mapped via the
@@ -23,6 +23,12 @@ public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
/// missing entry symbol, IO failure. /// missing entry symbol, IO failure.
case compilerError(LiveCompileError) case compilerError(LiveCompileError)
/// The interpreted graph-DSL failed to lex/parse/build or its graphs were
/// rejected by the engine. `diagnostics` are already mapped to user-source
/// coordinates (a parse error resolves to a line/column; a build error has
/// `line: nil`). No swiftc is involved — this is the instant DSL path.
case graphDSLFailed(diagnostics: [Diagnostic], underlying: Error)
public var description: String { public var description: String {
switch self { switch self {
case .snippetCompileFailed(let diagnostics, let underlying): case .snippetCompileFailed(let diagnostics, let underlying):
@@ -36,6 +42,15 @@ public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
return "snippet compile failed:\n\(summary)" return "snippet compile failed:\n\(summary)"
case .compilerError(let underlying): case .compilerError(let underlying):
return "live compile error: \(underlying)" return "live compile error: \(underlying)"
case .graphDSLFailed(let diagnostics, let underlying):
if diagnostics.isEmpty {
return "graph DSL failed:\n\(underlying)"
}
let summary: String = diagnostics.map { diag -> String in
let location: String = diag.line.map { "\($0):\(diag.column)" } ?? "?"
return "\(location) \(diag.severity.rawValue): \(diag.message)"
}.joined(separator: "\n")
return "graph DSL failed:\n\(summary)"
} }
} }
} }
@@ -0,0 +1,104 @@
// LiveSessionGraphDSL.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// The editor's instant, no-swiftc evaluation path. `runGraphDSL` lexes, parses,
// and builds interpreted graph-DSL source into `ClosureSynthesizer`s and plays
// them through the SAME tracking + named-slot machinery `compileAndRun` uses, so
// non-additive re-evaluation, slot hot-swap, and `resetAll()` behave identically
// across the Swift and DSL paths. The only difference is speed: a graph edit
// re-evaluates in microseconds instead of a swiftc round-trip.
#if os(macOS) || os(Linux)
import LyrebirdSynth
import LyrebirdGraphDSLEmbedded
extension LiveSession {
/// Evaluate interpreted graph-DSL `source` and play each statement.
///
/// Mirrors ``compileAndRun(_:additive:)`` but with no compiler: the source is
/// interpreted in-process. Each statement becomes one output —
///
/// - an anonymous statement (`OscSin(freq: 440) * 0.1`) is added to the
/// engine and tracked, so a later non-additive run removes it;
/// - a named statement (`bass = OscSawtooth(freq: 55) * 0.2`) is installed into
/// the matching named slot via ``swapSlot(_:synth:)`` — a persistent,
/// hot-swappable voice that survives a non-additive re-evaluation and is
/// replaced in place on the next run.
///
/// The whole program is lexed/parsed/built **before** any engine mutation, so
/// a syntax or build error leaves the currently-playing graph untouched — a
/// *malformed* edit never drops audio. Once the program is valid, playback is
/// best-effort per statement: an engine-level rejection of one statement
/// (e.g. `.pendingQueueFull`) is collected and surfaced but does not abort
/// the others, matching ``SnippetContext/play(_:)``.
///
/// - Parameters:
/// - source: DSL program text (one statement per line).
/// - additive: When `false` (default), removes every previously tracked
/// anonymous synth before playing (named slots persist). When `true`,
/// leaves prior synths in place.
/// - resources: Host resource table resolving bare-identifier references
/// (e.g. buffers). Defaults to an empty table.
/// - Throws: ``LiveSessionError/graphDSLFailed(diagnostics:underlying:)`` with
/// editor-ready diagnostics for a lex/parse/build failure (before any
/// mutation), or for one or more per-statement engine rejections (after the
/// surviving statements have gone live).
@MainActor
public func runGraphDSL(
_ source: String,
additive: Bool = false,
resources: DSLResourceResolver = DSLEmptyResources()
) throws {
// Build everything first — no engine mutation until we know the whole
// program is valid.
let outputs: [DSLOutput]
do {
outputs = try DSLInterpreter.evaluate(source, resources: resources)
} catch {
throw LiveSessionError.graphDSLFailed(
diagnostics: GraphDSLDiagnosticMapper.diagnostics(for: error, source: source),
underlying: error
)
}
if !additive { clearTracked() }
// Play every statement. An engine-level rejection of ONE statement
// (e.g. `.pendingQueueFull`) must not abort the rest — the others still
// go live, mirroring `SnippetContext.play`'s per-statement best-effort
// behavior. Failures are collected and surfaced together; the graphs
// that added successfully keep playing.
var failures: [Diagnostic] = []
var firstError: Error?
for output: DSLOutput in outputs {
let synth: ClosureSynthesizer = ClosureSynthesizer {
// The graph is already built (eagerly, by the interpreter); the
// closure just hands it to `build()`. Each `DSLOutput.graph` is
// owned by exactly one synth, so this never shares a graph.
output.graph
}
do {
if let slot: String = output.slot {
try swapSlot(slot, synth: synth)
} else {
try engine.add(synth)
track(synth)
}
} catch {
if firstError == nil { firstError = error }
failures.append(contentsOf: GraphDSLDiagnosticMapper.diagnostics(for: error, source: source))
}
}
if let firstError: Error = firstError {
throw LiveSessionError.graphDSLFailed(diagnostics: failures, underlying: firstError)
}
}
}
#endif
@@ -0,0 +1,207 @@
// SnippetCompletionService.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// Bridges the live-coding editor to `sourcekit-lsp` (via ``SourceKitLSPClient``)
// so the user gets real Swift code completion — the same symbols the snippet
// would see at compile time (`context`, `LyrebirdSynth` generators, …).
//
// It maintains a small on-disk workspace: the snippet is written WRAPPED in the
// same `SnippetHarness` preamble the compiler uses, next to a
// `compile_commands.json` carrying the module-resolution flags derived from the
// host `LiveSession`. sourcekit-lsp's compilation-database build system reads
// that file, which is what lets `import LyrebirdSynth` and the injected
// `context: SnippetContext` resolve for an otherwise free-standing file.
//
// macOS/Linux only.
#if os(macOS) || os(Linux)
import Foundation
/// Provides code completion for a live-coding editor buffer.
public actor SnippetCompletionService {
private let _client: SourceKitLSPClient
private let _session: LiveSession
private let _workspace: URL
private let _fileURL: URL
private let _fileURI: String
// Version counter for `didChange`, and the offset (from the last wrap) that
// maps a user-body line to its line in the wrapped document.
private var _version: Int = 1
private var _userBodyLineOffset: Int = 1
private var _started: Bool = false
/// - Parameters:
/// - session: Host session whose `importPaths` / `librarySearchPaths` /
/// `libraries` are reused verbatim, so completion sees exactly the
/// modules the real compile links.
/// - client: LSP client to drive (injectable for tests).
public init(
session: LiveSession,
client: SourceKitLSPClient = SourceKitLSPClient()
) {
self._client = client
self._session = session
// URL computation only — no filesystem or subprocess I/O here, so the
// synchronous init never blocks its caller (the @MainActor model).
self._workspace = FileManager.default.temporaryDirectory
.appendingPathComponent("lyrebird-completion-" + UUID().uuidString, isDirectory: true)
self._fileURL = _workspace.appendingPathComponent("snippet.swift")
self._fileURI = "file://" + _fileURL.path
}
/// Create the workspace directory, a seed snippet file, and the
/// `compile_commands.json` describing how to compile it. Runs on the actor
/// executor (off the main thread) — it shells out to `xcrun` for the SDK
/// path, which must not block the UI.
private func _writeWorkspace() {
try? FileManager.default.createDirectory(at: _workspace, withIntermediateDirectories: true)
let seed: WrappedSnippet = SnippetHarness.wrap(userBody: "\n")
try? seed.source.write(to: _fileURL, atomically: true, encoding: .utf8)
let arguments: [String] = SnippetCompletionService.compileArguments(
session: _session, file: _fileURL.path)
let entry: [String: Any] = [
"directory": _workspace.path,
"file": _fileURL.path,
"arguments": arguments
]
if let data: Data = try? JSONSerialization.data(withJSONObject: [entry], options: [.prettyPrinted]) {
try? data.write(to: _workspace.appendingPathComponent("compile_commands.json"))
}
}
/// Build the swiftc invocation for the compilation database: the `-I`
/// module paths, C-target module maps, and link flags from `session`, plus
/// the explicit `-sdk` / `-target` sourcekit-lsp needs for a free-standing
/// file (swiftc infers those during a normal build, but the LSP does not).
static func compileArguments(session: LiveSession, file: String) -> [String] {
var args: [String] = ["swiftc", file]
for path: URL in session.importPaths {
args += ["-I", path.path]
}
for url: URL in LiveSession.discoverClangModuleMaps(in: session.importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
for url: URL in LiveSession.discoverSPMModuleMaps(in: session.importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
#if os(Linux)
// CALSA's system-library module map is source-only (see LiveSession);
// completion needs it too, or `import LyrebirdSynth` fails to resolve.
for url: URL in LiveSession.discoverSourceSystemModuleMaps(in: session.importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
#endif
for path: URL in session.librarySearchPaths {
args += ["-L", path.path]
}
for lib: String in session.libraries {
args += ["-l\(lib)"]
}
if let sdk: String = sdkPath() {
args += ["-sdk", sdk]
}
args += ["-target", targetTriple()]
return args
}
private static func sdkPath() -> String? {
// Linux needs no `-sdk`, and `xcrun` does not exist there. Crucially,
// guard the spawn: on Linux, `Process.run()` throws when the launch path
// is missing, and a subsequent `waitUntilExit()` on a process that never
// started BLOCKS FOREVER (it is a no-op on macOS) — the completion hang.
// The macOS xcrun helpers in LiveCompiler avoid this by checking
// `isExecutableFile(atPath:)` first; do the same here.
let xcrunPath: String = "/usr/bin/xcrun"
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
let p: Process = Process()
p.executableURL = URL(fileURLWithPath: xcrunPath)
p.arguments = ["--show-sdk-path", "--sdk", "macosx"]
let out: Pipe = Pipe()
p.standardOutput = out
p.standardError = Pipe()
try? p.run()
p.waitUntilExit()
let data: Data = out.fileHandleForReading.readDataToEndOfFile()
let path: String? = String(data: data, encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines)
return (path?.isEmpty == false) ? path : nil
}
/// Minimum-deployment target triple. Arch matches the running process;
/// the OS floor matches the package's `macOS 15` minimum.
private static func targetTriple() -> String {
#if os(macOS)
#if arch(arm64)
return "arm64-apple-macosx15.0"
#else
return "x86_64-apple-macosx15.0"
#endif
#else
// Linux GNU triple; the Swift/LLVM spelling of arm64 is `aarch64`.
#if arch(arm64)
return "aarch64-unknown-linux-gnu"
#else
return "x86_64-unknown-linux-gnu"
#endif
#endif
}
/// Launch sourcekit-lsp and open the (empty) document. Call once before the
/// first ``completions(userBody:line:character:)``. Idempotent.
public func start() async throws {
guard !_started else { return }
// Build the workspace (SDK lookup + file writes) here, on the actor
// executor, so the blocking `xcrun` call never lands on the main thread.
_writeWorkspace()
try await _client.start(rootURI: "file://" + _workspace.path)
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: "\n")
_userBodyLineOffset = wrapped.userBodyLineOffset
_client.didOpen(uri: _fileURI, text: wrapped.source, version: _version)
_started = true
}
/// Request completions for `userBody` at the user-space `line` / `character`
/// (both zero-based, in the user's own text — not the wrapped document).
///
/// The body is re-synced to the server first, then the cursor is mapped
/// through the harness offset into the wrapped document.
public func completions(userBody: String, line: Int, character: Int) async throws -> [LSPCompletionItem] {
if !_started { try await start() }
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: userBody)
_userBodyLineOffset = wrapped.userBodyLineOffset
_version += 1
_client.didChange(uri: _fileURI, text: wrapped.source, version: _version)
// User line 0 sits at wrapped line `userBodyLineOffset - 1` (0-based);
// the column is unchanged (the preamble adds only whole lines).
let wrappedLine: Int = line + (_userBodyLineOffset - 1)
return try await _client.completion(uri: _fileURI, line: wrappedLine, character: character)
}
/// Shut down the server and remove the workspace. Safe to call more than once.
public func stop() {
shutdownSynchronously()
_started = false
}
/// Synchronous teardown usable from `deinit` and non-async contexts (a test
/// `defer`): terminate the LSP client and delete the temp workspace. Touches
/// only `let` members, so it is safe to run `nonisolated`. Idempotent.
public nonisolated func shutdownSynchronously() {
_client.shutdown()
try? FileManager.default.removeItem(at: _workspace)
}
deinit {
shutdownSynchronously()
}
}
#endif
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound // Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143 // LyrebirdLiveCompile
// //
// `SnippetContext` is the public API surface the user's snippet talks to. The // `SnippetContext` is the public API surface the user's snippet talks to. The
// host (via `LiveSession.compileAndRun`) constructs one of these, passes the // host (via `LiveSession.compileAndRun`) constructs one of these, passes the
@@ -16,7 +16,7 @@
// synth that the host will track for re-evaluation cleanup, and report back via // synth that the host will track for re-evaluation cleanup, and report back via
// the test-friendly `reportSampleRate(_:)` / `reportMessage(_:)` helpers. // the test-friendly `reportSampleRate(_:)` / `reportMessage(_:)` helpers.
#if os(macOS) #if os(macOS) || os(Linux)
import LyrebirdSynth import LyrebirdSynth
public final class SnippetContext { public final class SnippetContext {
@@ -43,11 +43,134 @@ public final class SnippetContext {
session.track(synth) session.track(synth)
return true return true
} catch { } catch {
session.lastSnippetMessage = "engine.add failed: \(error)" session.appendMessage("engine.add failed: \(error)")
return false return false
} }
} }
/// Play `synth` into a **named slot**, replacing whatever synth was there
/// before — the `Pdef`-style hot-swap primitive.
///
/// Unlike ``play(_:)``, a slotted synth is *not* torn down by the next
/// non-additive re-evaluation. Re-running a `play(slot:)` for the same name
/// swaps that one voice in place (the new voice starts before the old is
/// removed — a brief overlap, no gap), while other slots keep playing.
/// This lets you mutate one voice at a time, live.
///
/// ```swift
/// context.play(slot: "bass") { OscSaw.Audio(freq: 55, mul: 0.2) }
/// ```
///
/// Clear a slot with `context.session.clearSlot("bass")`, or all slots with
/// `context.session.clearSlots()`.
///
/// The swap is immediate by default, or quantized to the next beat/bar when
/// the session has a ``LiveSession/swapClock`` and a non-`.immediate`
/// ``LiveSession/swapQuantize`` — see ``LiveSession/swapSlot(_:synth:)``.
///
/// - Parameters:
/// - name: Slot identifier. Re-using a name replaces that slot's synth.
/// - synth: The `Synthesizer` to install.
/// - Returns: `true` if the engine accepted the add/schedule; `false` if it
/// threw (in which case the prior slot synth is left in place).
@discardableResult
@MainActor public func play(slot name: String, _ synth: any Synthesizer) -> Bool {
do {
try session.swapSlot(name, synth: synth)
return true
} catch {
session.appendMessage("play(slot: \"\(name)\") failed: \(error)")
return false
}
}
/// Play a bare generator graph into a **named slot** — the `Pdef`-style
/// hot-swap primitive with no `SynthesizerBase` subclass to declare.
///
/// See ``play(slot:_:)`` for the slot semantics.
///
/// ```swift
/// context.play(slot: "lead") { Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0) }
/// ```
///
/// - Parameters:
/// - name: Slot identifier. Re-using a name replaces that slot's synth.
/// - bus: Output bus the graph is written to (multi-channel sources
/// continue into following buses). Defaults to `0`.
/// - make: Builds and returns the output graph. Called once, inside the
/// synthesizer's `build()`.
/// - Returns: `true` if the engine accepted the enqueue; `false` otherwise.
@discardableResult
@MainActor public func play(
slot name: String,
bus: any ValidBus = 0,
_ make: @escaping () -> any ValidGeneratorInput
) -> Bool {
play(slot: name, ClosureSynthesizer(bus: bus, make))
}
/// Add a bare generator graph to the engine — the fastest path to sound in
/// a snippet, with no `SynthesizerBase` subclass to declare.
///
/// ```swift
/// context.play { OscSin.Audio(freq: 440, mul: 0.1) }
/// context.play(bus: 0) { Pan2(input: saw, pan: 0) }
/// ```
///
/// Wraps `make` in a ``ClosureSynthesizer`` and forwards to ``play(_:)`` —
/// the synth is tracked for cleanup on the next non-additive re-evaluation
/// just like any other. Construct the generators inside the closure.
///
/// - Parameters:
/// - bus: Output bus the graph is written to (multi-channel sources
/// continue into following buses). Defaults to `0`.
/// - make: Builds and returns the output graph. Called once, inside the
/// synthesizer's `build()`.
/// - Returns: `true` if the engine accepted the enqueue; `false` if
/// `engine.add` threw.
@discardableResult
@MainActor public func play(
bus: any ValidBus = 0,
_ make: @escaping () -> any ValidGeneratorInput
) -> Bool {
play(ClosureSynthesizer(bus: bus, make))
}
/// **Gracefully release** the voice in a named slot — trigger its envelope
/// release phase and let it tail out and free itself — then drop the slot.
///
/// The live-coding "start a voice, let go of it later" gesture: name a slot
/// with ``play(slot:_:)``, then release it from a *separate* evaluation (e.g.
/// select the line and hit ⌘E):
///
/// ```swift
/// context.play(slot: "pad") { EnvGen(gate: 1, ...) * OscSaw.Audio(freq: 110) }
/// // …later, in another evaluation:
/// context.release(slot: "pad")
/// ```
///
/// The released voice must free itself (an `EnvGen`/gate with a free-on-done
/// action) to leave the engine. For an immediate hard stop instead, use
/// ``free(slot:)``.
///
/// - Parameter name: Slot to release.
/// - Returns: `true` if a gated voice was released; `false` if the slot was
/// empty or its occupant has no gate.
@discardableResult
@MainActor public func release(slot name: String) -> Bool {
session.releaseSlot(name)
}
/// **Immediately** stop and remove the voice in a named slot — a hard cut,
/// no release tail. The counterpart to ``release(slot:)``.
///
/// - Parameter name: Slot to free.
/// - Returns: `true` if a voice was removed; `false` if the slot was empty.
@discardableResult
@MainActor public func free(slot name: String) -> Bool {
session.clearSlot(name)
}
/// Snippet-side hook for test verification: report the engine's sample rate /// Snippet-side hook for test verification: report the engine's sample rate
/// back through the session so tests can confirm the `context.engine` /// back through the session so tests can confirm the `context.engine`
/// linkage compiled and called correctly. /// linkage compiled and called correctly.
@@ -58,7 +181,7 @@ public final class SnippetContext {
/// Snippet-side hook for test verification: record an arbitrary message /// Snippet-side hook for test verification: record an arbitrary message
/// back on the session. Lets tests confirm the snippet body executed. /// back on the session. Lets tests confirm the snippet body executed.
public func reportMessage(_ message: String) { public func reportMessage(_ message: String) {
session.lastSnippetMessage = message session.appendMessage(message)
} }
} }
@@ -4,16 +4,15 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound // Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core // LyrebirdLiveCompile — core
// //
// C ABI signature of the snippet's exported entry point. // C ABI signature of the snippet's exported entry point.
#if os(macOS) #if os(macOS) || os(Linux)
/// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. Phase /// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. The host
/// 143 will pass a pointer to a `LiveSession` (or harness context) here; /// passes a pointer to a `LiveSession` (or harness context) here; snippets need
/// Phase 142 only requires that snippets can declare a function matching this /// only declare a function matching this signature.
/// signature.
public typealias SnippetEntry = @convention(c) (UnsafeMutableRawPointer?) -> Void public typealias SnippetEntry = @convention(c) (UnsafeMutableRawPointer?) -> Void
#endif #endif
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound // Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143 // LyrebirdLiveCompile
// //
// `SnippetHarness.wrap(userBody:)` produces the full Swift source that // `SnippetHarness.wrap(userBody:)` produces the full Swift source that
// `LiveCompiler.compile(source:)` feeds to swiftc. The preamble imports the // `LiveCompiler.compile(source:)` feeds to swiftc. The preamble imports the
@@ -12,21 +12,22 @@
// from the opaque pointer the host hands in. The user's body is dropped in as // from the opaque pointer the host hands in. The user's body is dropped in as
// the function body. // the function body.
#if os(macOS) #if os(macOS) || os(Linux)
public enum SnippetHarness { public enum SnippetHarness {
/// Wraps `userBody` in the standard preamble. /// Wraps `userBody` in the standard preamble.
/// ///
/// The user body runs inside `MainActor.assumeIsolated { … }` (Phase 203): snippets call /// The user body runs inside `MainActor.assumeIsolated { … }`: snippets call
/// `@MainActor` API — `context.play(_:)` and `SynthesizerBase` subclass construction /// `@MainActor` API — `context.play(_:)` and `SynthesizerBase` subclass construction
/// (both `@MainActor` since Phase 201) — which would not compile from the nonisolated /// (both `@MainActor`) — which would not compile from the nonisolated
/// `@_cdecl` entry under Swift 6. The `assumeIsolated` closure gives the body main-actor /// `@_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 /// isolation at compile time; it is safe at runtime because `LiveSession` always invokes
/// the entry on the main actor (`compileAndRunAsync` hops via `MainActor.run`; /// the entry on the main actor (`compileAndRunAsync` hops via `MainActor.run`;
/// `compileAndRun` is `@MainActor`). /// `compileAndRun` is `@MainActor`).
public static func wrap(userBody: String) -> WrappedSnippet { public static func wrap(userBody: String) -> WrappedSnippet {
let preamble: String = """ let preamble: String = """
import Foundation
import LyrebirdSynth import LyrebirdSynth
import LyrebirdLiveCompile import LyrebirdLiveCompile
@@ -0,0 +1,427 @@
// SourceKitLSPClient.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// A minimal LSP JSON-RPC client that drives the toolchain's `sourcekit-lsp`
// executable over stdio to provide Swift code completion for the live-coding
// editor. Only the handful of requests the editor needs are implemented:
// `initialize` / `initialized`, `textDocument/didOpen` / `didChange`, and
// `textDocument/completion`.
//
// macOS/Linux only — the whole live-compile surface shells out to the toolchain.
#if os(macOS) || os(Linux)
import Foundation
/// Nanoseconds in one second — for `Task.sleep`.
private let nanosecondsPerSecond: Double = 1_000_000_000
/// Drives `sourcekit-lsp` over stdio.
///
/// `@unchecked Sendable`: the process handles and the pending-request table are
/// guarded by `_lock`; a dedicated background reader thread parses framed
/// messages and completes the continuations stored under that lock. Public
/// methods are `async` and safe to call from any task.
public final class SourceKitLSPClient: @unchecked Sendable {
private let _process: Process = Process()
private let _stdin: Pipe = Pipe()
private let _stdout: Pipe = Pipe()
private let _lock: NSLock = NSLock()
private var _nextID: Int = 1
// Response continuations keyed by request id, completed by the reader thread.
// The payload is the raw response-body `Data` (Sendable); callers parse it.
private var _pending: [Int: CheckedContinuation<Data, Error>] = [:]
private var _running: Bool = false
// Accumulates stdout bytes until a full `Content-Length`-framed message is available.
private var _readBuffer: Data = Data()
/// Default request timeout in seconds. Completion should be well under this;
/// the ceiling guards against a wedged server.
public static let defaultRequestTimeout: TimeInterval = 15.0
// `nil` = resolve from the toolchain lazily in `start()`. Kept lazy so the
// synchronous `init` — evaluated in the caller's isolation, often the main
// actor via `SnippetCompletionService`'s default argument — never shells out
// to `xcrun`.
private let _explicitExecutableURL: URL?
private let _launchArguments: [String]
private let _requestTimeout: TimeInterval
/// - Parameters:
/// - executableURL: Path to `sourcekit-lsp`. When `nil` (default) it is
/// resolved from the toolchain via `xcrun` inside `start()` — not in
/// `init`, so construction never blocks its caller.
/// - arguments: Launch arguments for the executable (default none).
/// - requestTimeout: Per-request ceiling in seconds before ``request`` fails
/// with ``SourceKitLSPError/timedOut(method:)``.
public init(
executableURL: URL? = nil,
arguments: [String] = [],
requestTimeout: TimeInterval = SourceKitLSPClient.defaultRequestTimeout
) {
self._explicitExecutableURL = executableURL
self._launchArguments = arguments
self._requestTimeout = requestTimeout
}
deinit {
// Safety net: a client dropped without an explicit `shutdown()` would
// otherwise orphan the `sourcekit-lsp` subprocess and leave the reader
// thread blocked in `availableData`. `shutdown()` is idempotent.
shutdown()
}
/// Resolve `sourcekit-lsp` from the active toolchain via `xcrun`, falling
/// back to the conventional Xcode path.
private static func resolveExecutable() -> URL {
// Guard the xcrun spawn: `xcrun` is macOS-only, and on Linux
// `Process.run()` throws for a missing launch path while a following
// `waitUntilExit()` on the never-started process BLOCKS FOREVER (a no-op
// on macOS). Skip straight to the conventional path there, where the
// toolchain ships `/usr/bin/sourcekit-lsp`.
let xcrunPath: String = "/usr/bin/xcrun"
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else {
// No xcrun (Linux): prefer a `sourcekit-lsp` on $PATH (swiftly, a
// custom toolchain, …) over the conventional /usr/bin location.
if let onPath: String = livecompileExecutableOnPath("sourcekit-lsp") {
return URL(fileURLWithPath: onPath)
}
return URL(fileURLWithPath: "/usr/bin/sourcekit-lsp")
}
let xcrun: Process = Process()
xcrun.executableURL = URL(fileURLWithPath: xcrunPath)
xcrun.arguments = ["--find", "sourcekit-lsp"]
let out: Pipe = Pipe()
xcrun.standardOutput = out
xcrun.standardError = Pipe()
try? xcrun.run()
xcrun.waitUntilExit()
let data: Data = out.fileHandleForReading.readDataToEndOfFile()
if let path: String = String(data: data, encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines), !path.isEmpty {
return URL(fileURLWithPath: path)
}
return URL(fileURLWithPath:
"/usr/bin/sourcekit-lsp") // last resort; run(...) will surface a launch error
}
// MARK: - Lifecycle
/// Launch the server, run the `initialize` handshake against `rootURI`, and
/// send `initialized`. Call once per client — the caller (e.g.
/// ``SnippetCompletionService``) guards against a second call; a repeat call
/// here would re-`run()` the process. Resolving the executable (an `xcrun`
/// lookup when no explicit path was given) happens here, off the constructing
/// caller's thread.
public func start(rootURI: String) async throws {
_process.executableURL = _explicitExecutableURL ?? SourceKitLSPClient.resolveExecutable()
_process.arguments = _launchArguments
_process.standardInput = _stdin
_process.standardOutput = _stdout
_process.standardError = Pipe() // discard server logging
do {
try _process.run()
} catch {
throw SourceKitLSPError.launchFailed("\(error)")
}
_setRunning(true)
_startReader()
let params: [String: Any] = [
"processId": Int(ProcessInfo.processInfo.processIdentifier),
"rootUri": rootURI,
"capabilities": [
"textDocument": [
"completion": [
"completionItem": ["snippetSupport": false]
]
]
]
]
_ = try await request(method: "initialize", params: params)
notify(method: "initialized", params: [:])
}
/// Terminate the server. Safe to call multiple times.
public func shutdown() {
_lock.lock()
let wasRunning: Bool = _running
_lock.unlock()
_failAllPending(with: SourceKitLSPError.notRunning)
guard wasRunning else { return }
// Send the graceful `exit` while still marked running (`_send` gates on
// `_running`), then flip the flag and terminate.
notify(method: "exit", params: [:])
_setRunning(false)
_process.terminate()
}
/// Remove and fail every in-flight request continuation with `error`.
/// Under `_lock`, so it never double-resumes against the reader's dispatch.
private func _failAllPending(with error: Error) {
_lock.lock()
let pending: [Int: CheckedContinuation<Data, Error>] = _pending
_pending.removeAll()
_lock.unlock()
for (_, cont): (Int, CheckedContinuation<Data, Error>) in pending {
cont.resume(throwing: error)
}
}
// MARK: - Document sync
/// Open `text` as a Swift document at `uri`.
public func didOpen(uri: String, text: String, version: Int = 1) {
notify(method: "textDocument/didOpen", params: [
"textDocument": [
"uri": uri, "languageId": "swift", "version": version, "text": text
]
])
}
/// Replace the full contents of `uri` with `text` (whole-document sync).
public func didChange(uri: String, text: String, version: Int) {
notify(method: "textDocument/didChange", params: [
"textDocument": ["uri": uri, "version": version],
"contentChanges": [["text": text]]
])
}
// MARK: - Completion
/// Request completions at a zero-based `line` / `character` in `uri`.
/// Returns the parsed items (possibly empty).
public func completion(uri: String, line: Int, character: Int) async throws -> [LSPCompletionItem] {
let body: Data = try await request(method: "textDocument/completion", params: [
"textDocument": ["uri": uri],
"position": ["line": line, "character": character]
])
let message: [String: Any] = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]
// The result is either a CompletionList ({ items: [...] }) or a bare
// CompletionItem[].
let rawItems: [Any]
if let dict: [String: Any] = message["result"] as? [String: Any],
let items: [Any] = dict["items"] as? [Any] {
rawItems = items
} else if let arr: [Any] = message["result"] as? [Any] {
rawItems = arr
} else {
return []
}
var out: [LSPCompletionItem] = []
out.reserveCapacity(rawItems.count)
for case let item as [String: Any] in rawItems {
guard let label: String = item["label"] as? String else { continue }
let detail: String? = item["detail"] as? String
let insert: String = (item["insertText"] as? String)
?? (item["filterText"] as? String)
?? label
let kind: Int? = item["kind"] as? Int
let sortText: String? = item["sortText"] as? String
out.append(LSPCompletionItem(
label: label, detail: detail, insertText: insert, kind: kind, sortText: sortText))
}
return out
}
// MARK: - JSON-RPC plumbing
// Lock-protected mutations, factored into sync helpers so no `NSLock` call
// happens inside an `async` function (forbidden under Swift 6).
private func _setRunning(_ value: Bool) {
_lock.lock(); defer { _lock.unlock() }
_running = value
}
private func _isRunning() -> Bool {
_lock.lock(); defer { _lock.unlock() }
return _running
}
private func _claimRequestID() -> Int? {
_lock.lock(); defer { _lock.unlock() }
guard _running else { return nil }
let id: Int = _nextID; _nextID += 1
return id
}
private func _storePending(_ id: Int, _ cont: CheckedContinuation<Data, Error>) {
_lock.lock(); defer { _lock.unlock() }
_pending[id] = cont
}
/// Remove a pending request AND resume its continuation with `error`.
/// Resuming is essential: a task-group child suspended on
/// `withCheckedThrowingContinuation` is not woken by `cancelAll()`, so
/// merely dropping the entry would leave `request(...)`'s group awaiting a
/// child that never completes — a deadlock. `removeValue` under `_lock` means
/// only one side (this drop, or the reader's dispatch) ever holds the
/// continuation, so there is no double-resume.
private func _dropPending(_ id: Int, resumingWith error: Error) {
_lock.lock()
let cont: CheckedContinuation<Data, Error>? = _pending.removeValue(forKey: id)
_lock.unlock()
cont?.resume(throwing: error)
}
/// Send a request and await its response body (`Data`). Times out per
/// ``requestTimeout``.
private func request(method: String, params: [String: Any]) async throws -> Data {
guard let id: Int = _claimRequestID() else { throw SourceKitLSPError.notRunning }
// Frame the message to `Data` synchronously here so the child task
// captures only Sendable state (`framed`, `id`), never the non-Sendable
// `[String: Any]` params.
guard let framed: Data = _frame(id: id, method: method, params: params) else {
throw SourceKitLSPError.serverError(code: -1, message: "could not encode \(method)")
}
let timeoutSeconds: TimeInterval = _requestTimeout
return try await withThrowingTaskGroup(of: Data.self) { group in
group.addTask { [weak self] in
guard let self: SourceKitLSPClient else { throw SourceKitLSPError.notRunning }
return try await withCheckedThrowingContinuation { cont in
self._storePending(id, cont)
// Close the store-vs-EOF window: if the server died between
// `_claimRequestID` and here, the reader already drained the
// pending table, so fail this one now instead of waiting for
// the timeout. `_dropPending` removes under the lock, so it
// can't double-resume against a concurrent reader/shutdown.
guard self._isRunning() else {
self._dropPending(id, resumingWith: SourceKitLSPError.notRunning)
return
}
self._send(framed)
}
}
group.addTask {
try await Task.sleep(nanoseconds: UInt64(timeoutSeconds * nanosecondsPerSecond))
throw SourceKitLSPError.timedOut(method: method)
}
defer { group.cancelAll() }
do {
guard let first: Data = try await group.next() else {
throw SourceKitLSPError.timedOut(method: method)
}
return first
} catch {
// On timeout / failure, resume and drop the still-pending request
// continuation so its child task completes (cancelAll() alone does
// not wake a suspended continuation) and the group can return.
_dropPending(id, resumingWith: error)
throw error
}
}
}
private func notify(method: String, params: [String: Any]) {
if let framed: Data = _frame(id: nil, method: method, params: params) {
_send(framed)
}
}
/// Build a `Content-Length`-framed JSON-RPC message. Pure; no shared state.
private func _frame(id: Int?, method: String, params: [String: Any]) -> Data? {
var payload: [String: Any] = ["jsonrpc": "2.0", "method": method, "params": params]
if let id: Int = id { payload["id"] = id }
guard let body: Data = try? JSONSerialization.data(withJSONObject: payload) else { return nil }
var framed: Data = Data("Content-Length: \(body.count)\r\n\r\n".utf8)
framed.append(body)
return framed
}
/// Write a pre-framed message to the server's stdin, unless shut down.
private func _send(_ framed: Data) {
_lock.lock()
let running: Bool = _running
_lock.unlock()
guard running else { return }
_stdin.fileHandleForWriting.write(framed)
}
// MARK: - Reader
private func _startReader() {
let handle: FileHandle = _stdout.fileHandleForReading
let thread: Thread = Thread { [weak self] in
while true {
guard let self: SourceKitLSPClient else { return }
self._lock.lock(); let running: Bool = self._running; self._lock.unlock()
guard running else { return }
let chunk: Data = handle.availableData
if chunk.isEmpty {
// EOF — the server exited. Mark not-running so later `_send`s
// don't write to a dead pipe (EPIPE/SIGPIPE), and fail any
// in-flight requests instead of letting them hang to timeout.
self._setRunning(false)
self._failAllPending(with: SourceKitLSPError.notRunning)
return
}
self._lock.lock()
self._readBuffer.append(chunk)
let bodies: [Data] = self._drainMessagesLocked()
self._lock.unlock()
for body: Data in bodies {
self._dispatch(body)
}
}
}
thread.name = "lyrebird.sourcekit-lsp.reader"
thread.start()
}
/// Slice out as many complete `Content-Length`-framed message bodies as are
/// buffered, returning each raw JSON body. Caller holds `_lock`.
private func _drainMessagesLocked() -> [Data] {
var out: [Data] = []
let headerTerminator: Data = Data("\r\n\r\n".utf8)
while true {
guard let headerEnd: Range<Data.Index> = _readBuffer.range(of: headerTerminator) else { break }
let header: String = String(data: _readBuffer[_readBuffer.startIndex..<headerEnd.lowerBound],
encoding: .utf8) ?? ""
var contentLength: Int = 0
for line: Substring in header.split(separator: "\r\n") {
let parts: [Substring] = line.split(separator: ":", maxSplits: 1)
if parts.count == 2, parts[0].trimmingCharacters(in: .whitespaces) == "Content-Length" {
contentLength = Int(parts[1].trimmingCharacters(in: .whitespaces)) ?? 0
}
}
let bodyStart: Data.Index = headerEnd.upperBound
let available: Int = _readBuffer.distance(from: bodyStart, to: _readBuffer.endIndex)
guard available >= contentLength else { break } // wait for more bytes
let bodyEnd: Data.Index = _readBuffer.index(bodyStart, offsetBy: contentLength)
out.append(Data(_readBuffer[bodyStart..<bodyEnd]))
_readBuffer.removeSubrange(_readBuffer.startIndex..<bodyEnd)
}
return out
}
private func _dispatch(_ body: Data) {
guard let message: [String: Any] = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any]
else { return }
// Only responses (carrying our request id) are of interest; server
// notifications (diagnostics, logging) and server→client requests are
// ignored. sourcekit-lsp tolerates unanswered server requests here.
guard let id: Int = message["id"] as? Int else { return }
_lock.lock()
let cont: CheckedContinuation<Data, Error>? = _pending.removeValue(forKey: id)
_lock.unlock()
guard let cont: CheckedContinuation<Data, Error> = cont else { return }
if let error: [String: Any] = message["error"] as? [String: Any] {
let code: Int = error["code"] as? Int ?? 0
let msg: String = error["message"] as? String ?? "unknown"
cont.resume(throwing: SourceKitLSPError.serverError(code: code, message: msg))
return
}
// Hand the raw body back; the caller parses `result` for its own shape.
cont.resume(returning: body)
}
}
#endif
@@ -0,0 +1,39 @@
// SourceKitLSPError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// Errors surfaced by ``SourceKitLSPClient``. macOS/Linux only.
#if os(macOS) || os(Linux)
/// A failure from the `sourcekit-lsp` client.
public enum SourceKitLSPError: Error, CustomStringConvertible {
/// The `sourcekit-lsp` executable could not be launched (bad path, missing
/// toolchain, spawn failure). Thrown from ``SourceKitLSPClient/start(rootURI:)``.
case launchFailed(String)
/// A request was made against a client that was never started or has been
/// shut down (or the server exited). Also used to fail in-flight requests
/// when the server dies.
case notRunning
/// A request exceeded the client's per-request timeout. Guards against a
/// wedged server; carries the LSP method that timed out.
case timedOut(method: String)
/// The server returned a JSON-RPC error response, carrying its code and
/// message.
case serverError(code: Int, message: String)
public var description: String {
switch self {
case .launchFailed(let m): return "sourcekit-lsp failed to launch: \(m)"
case .notRunning: return "sourcekit-lsp is not running"
case .timedOut(let m): return "sourcekit-lsp timed out on \(m)"
case .serverError(let c, let m): return "sourcekit-lsp error \(c): \(m)"
}
}
}
#endif
@@ -0,0 +1,56 @@
// SwapQuantize.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile
//
// `SwapQuantize` chooses when a named-slot swap becomes audible: immediately, or
// aligned to the next beat / bar of a `LyrebirdClock`. Quantizing the swap to a
// musical boundary is what masks compile latency — the `swiftc` build finishes a
// few hundred ms after ⌘↩, then the swap lands exactly on the downbeat rather
// than whenever the compile happened to finish.
#if os(macOS) || os(Linux)
import Foundation
import LyrebirdSynth
/// When a ``LiveSession`` named-slot swap becomes audible.
///
/// Set on ``LiveSession/swapQuantize`` together with a ``LiveSession/swapClock``.
/// With no clock, or `.immediate`, a swap takes effect right away. `.nextBeat` /
/// `.nextBar` schedule the new voice's add and the old voice's removal at the
/// same upcoming boundary sample time, so the swap is glitch-free and on-grid.
public enum SwapQuantize: Sendable, Equatable {
/// Swap immediately, as soon as the snippet runs.
case immediate
/// Swap on the next whole beat boundary.
case nextBeat
/// Swap on the next bar boundary, where a bar is `beatsPerBar` beats.
case nextBar(beatsPerBar: Int)
/// The absolute clock beat this quantization targets from *now*, or `nil`
/// for `.immediate`. `.nextBeat` returns the next whole beat; `.nextBar`
/// returns the next multiple of `beatsPerBar` beats.
///
/// Reads `clock.currentBeat` once; the returned beat is strictly in the
/// future for a running clock (a whole-numbered current beat rounds up to
/// the following boundary, matching `LyrebirdClock.nextBeat`).
public func targetBeat(clock: LyrebirdClock) -> Double? {
switch self {
case .immediate:
return nil
case .nextBeat:
return floor(clock.currentBeat) + 1.0
case .nextBar(let beatsPerBar):
let bar: Double = Double(max(1, beatsPerBar))
return (floor(clock.currentBeat / bar) + 1.0) * bar
}
}
}
#endif
@@ -0,0 +1,155 @@
// SwiftFormatter.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — snippet source formatting.
//
// Shells out to the toolchain's `swift-format` (the same way `LiveCompiler`
// shells to `swiftc`) to pretty-print a snippet. macOS/Linux only — iOS cannot
// exec subprocesses. Writes the source to a temp file and runs `swift-format format
// <file>`, capturing stdout — avoids the write-stdin/read-stdout pipe deadlock
// a streaming approach risks on large output.
import Foundation
#if os(macOS) || os(Linux)
/// Stateless `swift-format` wrapper.
public enum SwiftFormatter {
/// Format `source` and return the pretty-printed result. Runs synchronously
/// (spawns `swift-format`); call off the main thread.
///
/// - Parameter source: Swift source to format. Top-level snippet code is
/// accepted — `swift-format` formats whatever parses.
/// - Returns: The formatted source.
/// - Throws: ``SwiftFormatterError`` for a missing tool, a non-zero exit
/// (typically a parse error), or an I/O failure.
public static func format(source: String) throws -> String {
let tool: String = try findSwiftFormat()
let id: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
let workDir: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LyrebirdSwiftFormat-\(id)", isDirectory: true)
let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path
do {
try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true)
} catch {
throw SwiftFormatterError.ioFailed("\(error)")
}
// Register cleanup as soon as the dir exists, so a later write failure
// doesn't leak it.
defer { try? FileManager.default.removeItem(at: workDir) }
do {
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
} catch {
throw SwiftFormatterError.ioFailed("\(error)")
}
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: tool)
process.arguments = ["format", sourcePath]
let stdoutPipe: Pipe = Pipe()
let stderrPipe: Pipe = Pipe()
process.standardOutput = stdoutPipe
process.standardError = stderrPipe
do {
try process.run()
} catch {
throw SwiftFormatterError.ioFailed("swift-format launch failed: \(error)")
}
// Drain stdout AND stderr concurrently before waiting. `swift-format` can
// emit both a large formatted buffer and (on a broken snippet) a large
// diagnostic stream; reading them sequentially would deadlock if the
// stream we aren't reading yet fills its OS pipe buffer while the child
// blocks writing to it.
let outHandle: FileHandle = stdoutPipe.fileHandleForReading
let errHandle: FileHandle = stderrPipe.fileHandleForReading
let group: DispatchGroup = DispatchGroup()
let drainQueue: DispatchQueue = DispatchQueue(
label: "net.realizedsound.lyrebird.swift-format-drain",
attributes: .concurrent
)
// Box the drained bytes in reference cells: on Linux the `DispatchQueue`
// closures are `@Sendable` and cannot mutate a captured `var`. Each
// closure writes its own box (no shared mutation), and `group.wait()`
// fences before the reads below.
let outBox: SwiftFormatterDataBox = SwiftFormatterDataBox()
let errBox: SwiftFormatterDataBox = SwiftFormatterDataBox()
group.enter()
drainQueue.async { outBox.data = outHandle.readDataToEndOfFile(); group.leave() }
group.enter()
drainQueue.async { errBox.data = errHandle.readDataToEndOfFile(); group.leave() }
group.wait()
process.waitUntilExit()
let outData: Data = outBox.data
let errData: Data = errBox.data
guard process.terminationStatus == 0 else {
let stderr: String = String(data: errData, encoding: .utf8) ?? ""
throw SwiftFormatterError.formatFailed(exitCode: process.terminationStatus, stderr: stderr)
}
guard let formatted: String = String(data: outData, encoding: .utf8) else {
throw SwiftFormatterError.ioFailed("swift-format produced non-UTF8 output")
}
return formatted
}
/// Whether a `swift-format` executable is available on this machine.
public static var isAvailable: Bool {
(try? findSwiftFormat()) != nil
}
// MARK: - Tool resolution
/// First-success search: `xcrun -f swift-format`, then hard-coded paths.
static func findSwiftFormat() throws -> String {
if let viaXcrun: String = swiftFormatViaXcrun() {
return viaXcrun
}
let candidates: [String] = [
"/usr/bin/swift-format",
"/usr/local/bin/swift-format",
"/opt/homebrew/bin/swift-format",
]
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
return path
}
throw SwiftFormatterError.toolNotFound
}
private static func swiftFormatViaXcrun() -> String? {
let xcrunPath: String = "/usr/bin/xcrun"
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: xcrunPath)
process.arguments = ["-f", "swift-format"]
let stdout: Pipe = Pipe()
process.standardOutput = stdout
process.standardError = FileHandle.nullDevice
do {
try process.run()
process.waitUntilExit()
} catch {
return nil
}
guard process.terminationStatus == 0 else { return nil }
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
}
}
/// Reference cell for one drained pipe's bytes, so the concurrent drain closures
/// write through a reference instead of mutating a captured `var` (which the
/// Linux `@Sendable` `DispatchQueue` closures forbid). `@unchecked Sendable`:
/// each instance is written by exactly one closure and read only after
/// `DispatchGroup.wait()`.
private final class SwiftFormatterDataBox: @unchecked Sendable {
var data: Data = Data()
}
#endif
@@ -0,0 +1,20 @@
// SwiftFormatterError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS) || os(Linux)
/// Errors raised while formatting snippet source with `swift-format`.
public enum SwiftFormatterError: Error {
/// No `swift-format` executable could be located (no Xcode / toolchain, or
/// an older toolchain that predates the bundled formatter).
case toolNotFound
/// `swift-format` exited non-zero — usually a parse error in the source.
case formatFailed(exitCode: Int32, stderr: String)
/// A filesystem or process I/O failure.
case ioFailed(String)
}
#endif
@@ -0,0 +1,26 @@
// SwiftToolchainStatus.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS) || os(Linux)
/// Result of probing for a usable Swift toolchain (the Swift scratchpad compiles
/// snippets by shelling out to `swiftc`, which requires Xcode or the Command Line
/// Tools). The Graph DSL mode does not need a toolchain, so a `.missing*` status is
/// a soft condition — it gates only the Swift-compile path. Produced by ``ToolchainProbe``.
public enum SwiftToolchainStatus: Equatable, Sendable {
/// `swiftc` and the macOS SDK both resolve — the Swift scratchpad can compile.
case available
/// No developer tools at all (`xcode-select -p` fails and `swiftc` is unresolved).
/// Fix: install the Command Line Tools (`xcode-select --install`) or Xcode.
case missingDeveloperTools
/// A developer directory is selected but `swiftc` could not be resolved.
/// Fix: install/repair Xcode or the Command Line Tools.
case missingSwiftc
/// `swiftc` resolves but the macOS SDK does not — usually an incomplete Xcode.
/// Fix: install a full Xcode.
case missingSDK
}
#endif
@@ -0,0 +1,85 @@
// ToolchainProbe.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS) || os(Linux)
import Foundation
/// Detects whether a usable Swift toolchain is present, so the app can warn the user
/// (with install guidance) instead of only failing into the console on the first Run.
///
/// The resolvers are injectable so the `.missing*` branches can be unit-tested without
/// actually uninstalling the toolchain; the defaults wrap the real `LiveCompiler`
/// resolution (`xcrun -f swiftc`, `xcrun --show-sdk-path`) plus `xcode-select -p`.
///
/// **Not RT-related.** Runs `xcrun` / `xcode-select` subprocesses — call off the main
/// thread (a couple of fast execs).
public struct ToolchainProbe: Sendable {
private let swiftcResolver: @Sendable () -> String?
private let sdkResolver: @Sendable () -> String?
private let developerDirResolver: @Sendable () -> String?
/// - Parameters:
/// - swiftcResolver: Returns the `swiftc` path, or `nil` when unresolved.
/// - sdkResolver: Returns the macOS SDK path, or `nil` when unresolved.
/// - developerDirResolver: Returns the active developer dir (`xcode-select -p`),
/// or `nil` when no developer directory is configured.
public init(
swiftcResolver: @escaping @Sendable () -> String? = ToolchainProbe.defaultSwiftcResolver,
sdkResolver: @escaping @Sendable () -> String? = ToolchainProbe.defaultSDKResolver,
developerDirResolver: @escaping @Sendable () -> String? = ToolchainProbe.developerDirViaXcodeSelect
) {
self.swiftcResolver = swiftcResolver
self.sdkResolver = sdkResolver
self.developerDirResolver = developerDirResolver
}
/// Default `swiftc` resolver — wraps the internal `LiveCompiler.findSwiftc()` so the
/// public `init` default argument does not reference internal API.
public static func defaultSwiftcResolver() -> String? { try? LiveCompiler.findSwiftc() }
/// Default macOS SDK resolver — wraps the internal `LiveCompiler.sdkPathViaXcrun()`.
public static func defaultSDKResolver() -> String? { LiveCompiler.sdkPathViaXcrun() }
/// Classify the current toolchain state.
public func status() -> SwiftToolchainStatus {
let swiftc: String? = swiftcResolver()
let sdk: String? = sdkResolver()
if swiftc != nil && sdk != nil { return .available }
if swiftc == nil {
// No swiftc: distinguish "no developer tools at all" from "tools present
// but swiftc unresolved" by whether a developer dir is configured.
return developerDirResolver() == nil ? .missingDeveloperTools : .missingSwiftc
}
// swiftc resolves but the SDK does not.
return .missingSDK
}
/// Active developer directory via `xcode-select -p`, or `nil` when unset / xcode-select
/// is missing / returns non-zero.
public static func developerDirViaXcodeSelect() -> String? {
let xcodeSelectPath: String = "/usr/bin/xcode-select"
guard FileManager.default.isExecutableFile(atPath: xcodeSelectPath) else { return nil }
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: xcodeSelectPath)
process.arguments = ["-p"]
let stdout: Pipe = Pipe()
process.standardOutput = stdout
process.standardError = FileHandle.nullDevice
do {
try process.run()
process.waitUntilExit()
} catch {
return nil
}
guard process.terminationStatus == 0 else { return nil }
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
}
}
#endif
@@ -4,15 +4,15 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound // Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143 // LyrebirdLiveCompile
// //
// Output of `SnippetHarness.wrap(userBody:)`. Carries the full Swift source // Output of `SnippetHarness.wrap(userBody:)`. Carries the full Swift source
// that `swiftc` will compile, plus the 1-based line number on which the user's // that `swiftc` will compile, plus the 1-based line number on which the user's
// body begins. Phase 144's diagnostic parser subtracts `userBodyLineOffset - 1` // body begins. The diagnostic parser subtracts `userBodyLineOffset - 1`
// from each swiftc-reported line so error rows point back at the row the user // from each swiftc-reported line so error rows point back at the row the user
// typed. // typed.
#if os(macOS) #if os(macOS) || os(Linux)
public struct WrappedSnippet: Equatable { public struct WrappedSnippet: Equatable {
public let source: String public let source: String

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