11 Commits

Author SHA1 Message Date
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
731 changed files with 74335 additions and 4840 deletions
+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.
### 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:
- **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.
- **`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`.
### 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
+40 -1
View File
@@ -31,6 +31,23 @@ 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`.
## 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
**Engine / RT core**
@@ -43,6 +60,7 @@ The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/
**Generators**
- Generator protocol + DemandGenerator → `docs/protocols/generator.md`
- **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`
- Multi-channel / `outputChannelCount` / channel-aware operators → `docs/stdlib/multichannel.md`
- Musical math (MIDI↔Hz, dB, intervals) → `docs/stdlib/generators.md` (LyrebirdMusicMath section)
@@ -61,6 +79,7 @@ The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/
- TemporalStream / language-side value generation → `Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md`
- Polyphonic voice pool / step sequencer → `docs/tooling/routine-task.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`
- NRT / offline render → `docs/tooling/nrt-guide.md`
@@ -74,9 +93,11 @@ The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/
**UI**
- 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)`.
- 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**
- 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**
- What to build next → `docs/00-working-order.md`
@@ -138,7 +159,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):
`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:
@@ -178,6 +199,23 @@ Call-site pattern: every `engine.add` invocation needs `try`. In non-throwing co
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
Never `!` on optionals or `try!`. Hotspots: `UnsafeBufferPointer.baseAddress` in Accelerate calls, `Array.first!`/`last!` on output channels, `try!` in test helpers, `dict[key]!`.
```swift
@@ -306,6 +344,7 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th
- `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)`
- `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`)
- `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`).
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.
@@ -17,8 +17,8 @@ final class BufferDemos: DemoProtocol {
func runDemo() {
// BufferDemos.swift lives at .../Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift
// — 4 components up to reach .../Demos/ where Perc.aiff lives.
let percURL = URL(fileURLWithPath: #filePath)
// — 4 components up to reach .../Demos/ where Mozart.aiff lives.
let percURL: URL = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent() // .../Demos/
.deletingLastPathComponent() // .../LyrebirdDemo/
.deletingLastPathComponent() // .../LyrebirdDemo (package)/
@@ -35,13 +35,58 @@ final class BufferDemos: DemoProtocol {
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
// Demo 1 — PlayBuffer (looping at native rate)
print("\n── Demo 1: PlayBuffer (looping) ──")
let demo1 = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate)
ctx.add(demo1)
try ctx.wait(seconds: 6)
ctx.remove(demo1)
@@ -49,7 +94,6 @@ final class BufferDemos: DemoProtocol {
// Demo 2 — BufferRead (sine-wave position scan)
print("\n── Demo 2: BufferRead (sine-wave position scan) ──")
let demo2 = PercBufferRead(buffer: percBuffer)
ctx.add(demo2)
try ctx.wait(seconds: 6)
ctx.remove(demo2)
@@ -57,19 +101,10 @@ final class BufferDemos: DemoProtocol {
// Demo 3 — PlayBuffer → PitchShift (cycling through pitch ratios)
print("\n── Demo 3: PlayBuffer → PitchShift ──")
let demo3 = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate)
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 {
print(" pitchRatio \(label)")
demo3.pitchRatio = ratio
ctx.set(pitchRatioNode, to: ratio) // live-param write from the task body
try ctx.wait(seconds: 3)
}
ctx.remove(demo3)
@@ -77,16 +112,9 @@ final class BufferDemos: DemoProtocol {
// Demo 4 — PlayBuffer → SpectralChain.Audio (with SpectralPitchShift)
print("\n── Demo 4: PlayBuffer → SpectralChain.Audio (SpectralPitchShift) ──")
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 {
for (index, (_, label)) in spectralRatios.enumerated() {
print(" pitchRatio \(label)")
let demo4 = PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate)
let demo4: PercSpectralPitchShift = demo4Array[index]
ctx.add(demo4)
try ctx.wait(seconds: 5)
ctx.remove(demo4)
@@ -95,16 +123,9 @@ final class BufferDemos: DemoProtocol {
// Demo 5 — SpectralChain.Audio fan-out (mono → 2-channel decorrelated stereo)
print("\n── Demo 5: SpectralChain.Audio fan-out (SpectralStereoDiffuse) ──")
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 {
for (index, (_, label)) in diffuseSteps.enumerated() {
print(" amount \(label)")
let demo5 = PercSpectralStereoDiffuse(
buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
let demo5: PercSpectralStereoDiffuse = demo5Array[index]
ctx.add(demo5)
try ctx.wait(seconds: 5)
ctx.remove(demo5)
@@ -113,17 +134,9 @@ final class BufferDemos: DemoProtocol {
// Demo 6 — TimeStretch (granular, pitch-preserved time stretching + compression)
print("\n── Demo 6: TimeStretch (granular time-stretch / compression) ──")
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 {
for (index, (_, label)) in stretchSteps.enumerated() {
print(" stretchFactor \(label)")
let demo6 = PercTimeStretch(buffer: percBuffer, stretchFactor: factor)
let demo6: PercTimeStretch = demo6Array[index]
ctx.add(demo6)
try ctx.wait(seconds: 6)
ctx.remove(demo6)
@@ -7,5 +7,10 @@
import LyrebirdSynth
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
// SPDX-License-Identifier: MIT
//
// BufferDemos 2.swift
// LyrebirdDemo
//
// Created by Joshua Parmenter on 5/6/26.
//
import Foundation
import LyrebirdSynth
@@ -25,18 +17,31 @@ final class ReverbDemo: DemoProtocol {
func runDemo() {
let sampleRate = engine.sampleRate
// sets up its own thread / timing, etc
LyrebirdTask.run(engine: engine) { [sampleRate] ctx in
let sampleRate: Double = engine.sampleRate
// `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
let reverbDemo = GVerbTest(
sampleRate: sampleRate
)
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)
print("\nAll buffer demos complete.")
print("\nAll reverb demos complete.")
}
}
}
@@ -14,17 +14,21 @@
import LyrebirdSynth
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
init(sampleRate: Double) {
self.sampleRate = sampleRate
}
override func build() {
let impulse = Impulse.Audio(freq: 0.5)
let reverb = GVerb.Audio(source: impulse,
roomSize: 70.0,
reverbTime: 3.0,
reverbTime: $reverbTime, // live ParameterNode, not the baked scalar
earlyLevel: 0.4,
tailLevel: 0.9,
dryLevel: 0.1,
+4 -3
View File
@@ -9,7 +9,7 @@ import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 2,
driver: CoreAudioDriver()
@@ -22,6 +22,7 @@ do {
exit(1)
}
BufferDemos(engine: engine).runDemo()
//ReverbDemo(engine: engine).runDemo()
// BufferDemos(engine: engine).runDemo()
ReverbDemo(engine: engine).runDemo()
engine.stop()
+1 -1
View File
@@ -17,7 +17,7 @@ let package = Package(
.executableTarget(
name: "LyrebirdDemo",
dependencies: [
.product(name: "Lyrebird", package: "LyrebirdII"),
.product(name: "Lyrebird", package: "Lyrebird"),
],
path: "LyrebirdDemo"
),
@@ -12,7 +12,7 @@ import LyrebirdUI
// ── Demo selector ─────────────────────────────────────────────────────────────
// Change `demo` to `.sineTone` or `.binDelay` to switch demos.
private enum Demo { case vector, binDelay, sineTone }
private let demo: Demo = .binDelay
private let demo: Demo = .vector
// ──────────────────────────────────────────────────────────────────────────────
final class AppDelegate: NSObject, NSApplicationDelegate {
@@ -26,6 +26,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
let binDelayController: BinDelayController
var window: LyrebirdWindow?
@MainActor
init(engine: SynthesisEngine) {
let scopeCapture = ScopeCapture(buses: [0, 1], bufferSize: 2048)
engine.scopeTap = scopeCapture
@@ -13,6 +13,7 @@ import LyrebirdSynth
/// first taps "Start Synthesizer" — this is necessary because
/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed
/// sample rate, which is only valid after `engine.start()` returns.
@MainActor
@Observable
final class BinDelayController {
@@ -7,6 +7,7 @@
import Observation
import LyrebirdSynth
@MainActor
@Observable
final class NoteController {
@@ -7,6 +7,7 @@
import Observation
import LyrebirdSynth
@MainActor
@Observable
final class VectorOscillatorController {
@@ -9,14 +9,19 @@ import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
let delegate = AppDelegate(engine: engine)
let app = NSApplication.shared
app.setActivationPolicy(.regular)
app.delegate = delegate
app.run()
// AppDelegate.init is @MainActor (it builds @MainActor SynthesizerBase synths
// and UI controllers). 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()
}
@@ -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
}
+1 -1
View File
@@ -17,7 +17,7 @@ let package = Package(
.executableTarget(
name: "LyrebirdNRTDemo",
dependencies: [
.product(name: "Lyrebird", package: "LyrebirdII"),
.product(name: "Lyrebird", package: "Lyrebird"),
],
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,44 @@
// 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 Core Audio and runs the graph on the RT thread.
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
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 {
fputs("Lyrebird quickstart failed to start: \(error)\n", stderr)
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,693 @@
// ScoreDemo.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
/// 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 Desktop.
let xmlURL: URL = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Desktop/LyrebirdScoreDemo.musicxml")
let xmlString: String = score.toMusicXMLString()
do {
try xmlString.write(to: xmlURL, atomically: true, encoding: .utf8)
print("MusicXML written → \(xmlURL.path)")
} catch {
fputs("Failed to write MusicXML: \(error)\n", stderr)
}
// 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 {
fputs("MusicXML round-trip failed: \(error)\n", stderr)
}
// 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 = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Desktop/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 {
fputs("Failed to write sectioned showcase: \(error)\n", stderr)
}
// 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 {
fputs("engine.schedule failed for beat \(event.beat): \(error)\n", stderr)
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,48 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
// Output paths — both land on the Desktop.
let cafURL: URL = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Desktop/LyrebirdScoreDemo.caf")
// 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: cafURL, duration: totalDuration)
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, cafURL.path))
do {
try engine.start()
print("Done.")
} catch {
fputs("Render failed: \(error)\n", stderr)
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,9 +9,10 @@
/* Begin PBXBuildFile section */
C8D0000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000007 /* main.swift */; };
C8D0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000008 /* AppDelegate.swift */; };
C8D0000000000000000000F /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdUI */; };
C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001F /* LyrebirdLiveCompile */; };
C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUI */; };
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; };
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; };
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
@@ -27,14 +28,28 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
C8D0000000000000000000F /* LyrebirdUI in Frameworks */,
C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */,
C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */,
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */,
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase 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 PBXGroup section */
C8D00000000000000000002 = {
isa = PBXGroup;
@@ -73,6 +88,7 @@
C8D00000000000000000011 /* Sources */,
C8D00000000000000000012 /* Frameworks */,
C8D00000000000000000013 /* Resources */,
C8D00000000000000000035 /* Embed Frameworks */,
);
buildRules = (
);
@@ -80,9 +96,8 @@
);
name = LyrebirdScratchDemo;
packageProductDependencies = (
C8D0000000000000000001D /* LyrebirdUI */,
C8D0000000000000000001F /* LyrebirdLiveCompile */,
C8D00000000000000000020 /* LyrebirdLiveCompileUI */,
C8D0000000000000000001D /* LyrebirdDynamic */,
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */,
);
productName = LyrebirdScratchDemo;
productReference = C8D00000000000000000004 /* LyrebirdScratchDemo.app */;
@@ -248,6 +263,10 @@
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
// Xcode 26 explicit-module-build regression: SPM dynamic-library
// framework binaries (LyrebirdDynamic / LyrebirdLiveCompileUIDynamic)
// are not emitted under the integrated driver. Classic driver fixes it.
SWIFT_USE_INTEGRATED_DRIVER = NO;
};
name = Debug;
};
@@ -303,6 +322,8 @@
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
// Xcode 26 explicit-module-build regression — see Debug config.
SWIFT_USE_INTEGRATED_DRIVER = NO;
};
name = Release;
};
@@ -341,20 +362,15 @@
/* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
C8D0000000000000000001D /* LyrebirdUI */ = {
C8D0000000000000000001D /* LyrebirdDynamic */ = {
isa = XCSwiftPackageProductDependency;
package = C8D0000000000000000001B /* XCLocalSwiftPackageReference "../.." */;
productName = LyrebirdUI;
productName = LyrebirdDynamic;
};
C8D0000000000000000001F /* LyrebirdLiveCompile */ = {
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */ = {
isa = XCSwiftPackageProductDependency;
package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */;
productName = LyrebirdLiveCompile;
};
C8D00000000000000000020 /* LyrebirdLiveCompileUI */ = {
isa = XCSwiftPackageProductDependency;
package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */;
productName = LyrebirdLiveCompileUI;
productName = LyrebirdLiveCompileUIDynamic;
};
/* 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
}
@@ -7,18 +7,28 @@
import AppKit
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
import LyrebirdLiveCompile
// 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.
final class AppDelegate: NSObject, NSApplicationDelegate {
let engine: SynthesisEngine
let session: LiveSession
var model: LyrebirdScratchModel?
var menuController: LyrebirdScratchMenuController?
var window: LyrebirdWindow?
var window: NSWindow?
@MainActor
init(engine: SynthesisEngine) {
self.engine = engine
self.session = LiveSession(engine: engine)
@@ -32,20 +42,30 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
print("[LyrebirdScratchDemo] Engine failed to start: \(error)")
}
let model = LyrebirdScratchModel(session: session)
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session)
self.model = model
let menuController = LyrebirdScratchMenuController(model: model)
let menuController: LyrebirdScratchMenuController = LyrebirdScratchMenuController(model: model)
menuController.installMainMenu()
self.menuController = menuController
window = LyrebirdWindow(
title: "Lyrebird — Live Scratch",
width: 720,
height: 560
let windowWidth: CGFloat = 720
let windowHeight: CGFloat = 560
let hosting: NSHostingController<LyrebirdScratchView> =
NSHostingController(rootView: LyrebirdScratchView(model: model))
let initialSize: CGSize = CGSize(width: windowWidth, height: windowHeight)
let win: NSWindow = NSWindow(
contentRect: NSRect(origin: .zero, size: initialSize),
styleMask: [.titled, .closable, .resizable, .miniaturizable],
backing: .buffered,
defer: false
)
window?.open {
LyrebirdScratchView(model: model)
}
// Keep ownership in Swift — NSWindow defaults to releasing on close.
win.isReleasedWhenClosed = false
win.title = "Lyrebird — Live Scratch"
win.contentViewController = hosting
win.center()
win.makeKeyAndOrderFront(nil)
self.window = win
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
@@ -17,7 +17,7 @@
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.
This could be revisited if an XPC-worker approach is adopted.
com.apple.security.app-sandbox key is absent (defaults false).
-->
@@ -6,9 +6,8 @@
import AppKit
import LyrebirdSynth
import LyrebirdLiveCompile
let engine = SynthesisEngine(
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
@@ -16,8 +15,14 @@ let engine = SynthesisEngine(
driver: CoreAudioDriver()
)
let delegate = AppDelegate(engine: engine)
let app = NSApplication.shared
app.setActivationPolicy(.regular)
app.delegate = delegate
app.run()
// 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()
}
@@ -16,6 +16,7 @@ private let demo: Demo = .vector
// ──────────────────────────────────────────────────────────────────────────────
@main
@MainActor
struct LyrebirdiOSDemoApp: App {
let engine: SynthesisEngine
@@ -13,6 +13,7 @@ import LyrebirdSynth
/// first taps "Start Synthesizer" — this is necessary because
/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed
/// sample rate, which is only valid after `engine.start()` returns.
@MainActor
@Observable
final class BinDelayController {
@@ -7,6 +7,7 @@
import Observation
import LyrebirdSynth
@MainActor
@Observable
final class NoteController {
@@ -7,6 +7,7 @@
import Observation
import LyrebirdSynth
@MainActor
@Observable
final class VectorOscillatorController {
+102 -6
View File
@@ -100,14 +100,25 @@ Full reference: [`docs/tooling/cli-guide.md`](docs/tooling/cli-guide.md).
## 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).
| 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` |
| `ui-demo` | SPM-only | AppKit window with `@UIParam` knobs + `LyrebirdWindow`. | `CoreAudioDriver` |
| `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` |
| `ios-ui` | Xcode-project | iOS `.app` (SwiftUI), with `AVAudioSession` activation. | `iOSAudioDriver` (RemoteIO) |
| `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
```
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
lyrebird new <name> --template <t> --lyrebird-path /Users/me/Documents/LyrebirdII
@@ -167,9 +180,9 @@ import LyrebirdSynth
import LyrebirdUI
struct ContentView: View {
@StateObject var synth = ToneSynth() // ToneSynth: SynthesizerBase with @UIParam
let synth: ToneSynth // ToneSynth: SynthesizerBase with @UIParam
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/).
### 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
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
lyrebird install-templates # New File… ▸ Lyrebird section appears in Xcode
@@ -263,14 +357,16 @@ From a repo checkout you can equivalently run `bash scripts/install-xcode-templa
## 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 |
|---|---|
| [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | `quickstart` |
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | real-time CLI |
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | `macos-ui-xcode` |
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | `ios-ui` |
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | `nrt` |
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | `score` |
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | `auv3` |
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | live-coding scratchpad |
+40 -12
View File
@@ -1,26 +1,37 @@
# 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
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.
---
## 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
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
- **Wire it up:** in `main.swift`, call `engine.schedule(MySynth(), after: 0.0)`
- **To stop:** Ctrl-C in the Xcode console, or just let the synthesizer's done action free it
- **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:** `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 give a voice an envelope/line that frees itself (see below)
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
final class MySynth: SynthesizerBase {
@UIParam var freq: LyrebirdFloat = 440.0
@UIParam var amp: LyrebirdFloat = 0.5
@UIParam var freq: Double = 440.0
@UIParam var amp: Double = 0.5
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))
}
}
@@ -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
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.
@@ -125,10 +149,12 @@ 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.
- `context.engine` — the host `SynthesisEngine`, started at launch.
- `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.
- **⌘↩** — 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.
- **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:**
`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.
@@ -152,11 +178,12 @@ final class MySynth: SynthesizerBase {
override func build() {
let sig = OscSin.Audio(freq: 440) * 0.3
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
@@ -182,6 +209,7 @@ final class MySynth: SynthesizerBase {
| Synthesizer and node tree | `docs/protocols/synthesizer.md` |
| All built-in generators | `docs/stdlib/generators.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` |
| Xcode file templates | `docs/tooling/xcode-templates.md` |
| GUI / parameter binding | `docs/ui/gui-system.md` |
+41 -4
View File
@@ -7,7 +7,7 @@
// swift-tools-version: 6.0
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
// resolution forces SwiftPM to dynamic-link `libLyrebirdLiveCompile.dylib`
// against `libLyrebird.dylib` instead of statically embedding `Lyrebird`'s
@@ -20,13 +20,25 @@ let package = Package(
name: "LyrebirdLiveCompile",
platforms: [.macOS(.v15)],
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(
name: "LyrebirdLiveCompile",
name: "LyrebirdLiveCompileDynamic",
type: .dynamic,
targets: ["LyrebirdLiveCompile"]
),
.library(
name: "LyrebirdLiveCompileUI",
name: "LyrebirdLiveCompileUIDynamic",
type: .dynamic,
targets: ["LyrebirdLiveCompileUI"]
),
],
@@ -34,10 +46,34 @@ let package = Package(
.package(name: "Lyrebird", path: "..")
],
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(
name: "LyrebirdLiveCompile",
dependencies: [
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
// Instant, no-swiftc graph evaluation for the editor's DSL mode.
"LyrebirdGraphDSLEmbedded",
],
path: "Sources/LyrebirdLiveCompile"
),
@@ -48,13 +84,14 @@ let package = Package(
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
],
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(
name: "LyrebirdLiveCompileTests",
dependencies: [
"LyrebirdLiveCompile",
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
"LyrebirdGraphDSLEmbedded",
],
path: "Tests/LyrebirdLiveCompileTests"
),
+1
View File
@@ -0,0 +1 @@
../../Sources/LyrebirdGraphDSL
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core
// LyrebirdLiveCompile — core
//
// `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
@@ -35,7 +35,7 @@ public final class CompiledSnippet: @unchecked Sendable {
/// Path to the dylib that was `dlopen`'d.
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
/// Raw `dlopen` handle. Kept so the OS keeps the dylib mapped.
@@ -4,13 +4,13 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
// LyrebirdLiveCompile
//
// One parsed `swiftc` diagnostic, with `line` already mapped from the wrapped-
// snippet coordinate space back to the user's snippet coordinate space (via the
// `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.
#if os(macOS)
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
// LyrebirdLiveCompile
//
// `DiagnosticParser.parse(stderr:userBodyLineOffset:)` walks the swiftc stderr
// stream line by line, extracts diagnostics matching the standard
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
// LyrebirdLiveCompile
//
// Severity classifier for a parsed swiftc diagnostic line.
@@ -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)
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 only.
#if os(macOS)
/// 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
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core
// LyrebirdLiveCompile — core
//
// Errors raised by `LiveCompiler.compile(source:)`. RT path never sees these:
// compilation is a main-thread (or background-queue) operation that runs long
@@ -4,12 +4,12 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core
// LyrebirdLiveCompile — core
//
// `LiveCompiler.compile(source:)` shells out to `swiftc -emit-library`, then
// `dlopen`s the resulting dylib and resolves the snippet entry symbol. No UI,
// no `SynthesisEngine` binding (those land in phases 143–146). macOS only —
// iOS cannot exec swiftc.
// no `SynthesisEngine` binding (those are handled by the harness and session
// layers). macOS only — iOS cannot exec swiftc.
import Foundation
#if os(macOS)
@@ -34,8 +34,8 @@ public enum LiveCompiler {
///
/// - Parameters:
/// - source: Full Swift source, including the `@_cdecl("lyrebird_snippet_entry")`
/// entry. Phase 143's `SnippetHarness` will wrap user input in a preamble that
/// provides this; Phase 142 callers (incl. tests) write the full file.
/// entry. `SnippetHarness` wraps user input in a preamble that provides
/// this; direct callers (incl. tests) write the full file.
/// - extraSwiftcArgs: Extra args appended to the `swiftc` invocation. Tests use
/// this for `-suppress-warnings` etc. Production callers leave empty.
/// - Returns: `CompiledSnippet` holding the dlopen handle and entry pointer.
@@ -190,10 +190,11 @@ public enum LiveCompiler {
process.arguments = arguments
let stderrPipe: Pipe = Pipe()
process.standardError = stderrPipe
// stdout discarded — swiftc emits no useful output in -emit-library mode.
// Use FileHandle.nullDevice (not Pipe()) so the OS drops the bytes itself;
// an undrained Pipe deadlocks against the blocking stderr read below if
// swiftc ever writes more than the pipe buffer (~64 KB) to stdout.
// stdout discarded — swiftc emits no useful output in the modes used
// here (-emit-library and -typecheck). Use FileHandle.nullDevice (not
// Pipe()) so the OS drops the bytes itself; an undrained Pipe deadlocks
// against the blocking stderr read below if swiftc ever writes more than
// the pipe buffer (~64 KB) to stdout.
process.standardOutput = FileHandle.nullDevice
do {
try process.run()
@@ -205,6 +206,53 @@ public enum LiveCompiler {
let stderrString: String = String(data: stderrData, encoding: .utf8) ?? ""
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
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
// LyrebirdLiveCompile
//
// `LiveSession` owns the `SynthesisEngine` and tracks every `Synthesizer` that
// each snippet `play(_:)`s, so the next non-additive re-evaluation can
@@ -23,14 +23,15 @@ import LyrebirdSynth
/// Snippets receive a `SnippetContext` bound to this session through
/// `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
/// Swift 6 requires it to be `Sendable`. The conformance is sound by construction:
///
/// - `engine` and all `-I` / `-L` / `-l` / `rpath` configuration are immutable `let`.
/// - The only mutable graph state — `trackedSynths` and `loadedSnippets` — is accessed
/// exclusively under `trackingLock` (`track`, `clearTracked`, `trackedSynthCount`,
/// `runEntry`).
/// - The mutable graph state — `trackedSynths`, `loadedSnippets`, and the named-slot map
/// `slottedSynths` — is accessed exclusively under `trackingLock` (`track`,
/// `clearTracked`, `trackedSynthCount`, `runEntry`, `assignSlot`, `clearSlot`,
/// `clearSlots`, `slotCount`, `slotNames`).
/// - `reportedSampleRate` / `lastSnippetMessage` are test-only side channels (`@testable`),
/// written by the single in-flight snippet entry under the documented
/// one-invocation-at-a-time precondition (see `compileAndRunAsync`) and read by tests
@@ -53,6 +54,12 @@ public final class LiveSession: @unchecked Sendable {
/// runtime without `DYLD_LIBRARY_PATH` ceremony.
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
/// via `@testable import`; not part of the public API.
internal var reportedSampleRate: Double?
@@ -66,11 +73,38 @@ public final class LiveSession: @unchecked Sendable {
private var trackedSynths: [any Synthesizer] = []
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?
public init(
engine: SynthesisEngine,
importPaths: [URL] = LiveSession.defaultImportPaths(),
librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(),
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompile"],
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
rpaths: [URL] = LiveSession.defaultRpaths()
) {
self.engine = engine
@@ -91,7 +125,7 @@ public final class LiveSession: @unchecked Sendable {
/// (⌘⇧↩ semantics in the future `LyrebirdScratchView` editor).
/// - Returns: The compiled snippet handle. Retained internally so the dylib
/// stays mapped; callers can ignore it.
/// `@MainActor` (Phase 203): runs the snippet entry — and thus the user body's
/// `@MainActor`: runs the snippet entry — and thus the user body's
/// `MainActor.assumeIsolated { … }` and any `context.play(_:)` → `engine.add` — on the
/// main thread, synchronously (swiftc compile included). The async variant
/// ``compileAndRunAsync(_:additive:)`` keeps the compile off-main.
@@ -112,8 +146,8 @@ public final class LiveSession: @unchecked Sendable {
/// engine-touching steps (`clearTracked()` and the snippet entry via `runEntry`) then run
/// on the **main actor**.
///
/// Running the entry on the main actor matters (Phase 203): the snippet's
/// `context.play(_:)` calls `engine.add(_:)`, which is `@MainActor` (Phase 201) and
/// Running the entry on the main actor matters: the snippet's
/// `context.play(_:)` calls `engine.add(_:)`, which is `@MainActor` and
/// mutates `engine.nodeTreeMirror` — state observed by SwiftUI on the main thread. A
/// `nonisolated async` method resumes on the generic executor, NOT the caller's actor, so
/// the hop is explicit here rather than assumed.
@@ -208,9 +242,314 @@ public final class LiveSession: @unchecked Sendable {
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
}
/// 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 {
lastSnippetMessage =
"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
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] = []
for path: URL in importPaths {
args += ["-I", path.path]
@@ -222,6 +561,19 @@ public final class LiveSession: @unchecked Sendable {
for url: URL in LiveSession.discoverClangModuleMaps(in: importPaths) {
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)"]
}
return args
}
private func makeSwiftcArgs() -> [String] {
var args: [String] = makeModuleResolutionArgs()
// 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
// case — modules statically linked into the host app), use
@@ -279,6 +631,33 @@ public final class LiveSession: @unchecked Sendable {
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
}
// MARK: - Build-dir discovery
/// Best-effort discovery of the SPM `.build/<triple>/<config>` directory
@@ -288,7 +667,7 @@ public final class LiveSession: @unchecked Sendable {
///
/// Searches, in order:
/// 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.
/// 2. Walks up from `Bundle.main.executableURL` — fallback for the case
/// where the host bundles the dylibs into an `.app`.
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
// LyrebirdLiveCompile
//
// `LiveSession.compileAndRun(_:additive:)` throws this richer error so callers
// see diagnostics pre-mapped to user-snippet coordinates. Other `LiveCompileError`
@@ -23,6 +23,12 @@ public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
/// missing entry symbol, IO failure.
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 {
switch self {
case .snippetCompileFailed(let diagnostics, let underlying):
@@ -36,6 +42,15 @@ public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
return "snippet compile failed:\n\(summary)"
case .compilerError(let 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)
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,184 @@
// 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 only.
#if os(macOS)
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)"]
}
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? {
let p: Process = Process()
p.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
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 arch(arm64)
let arch: String = "arm64"
#else
let arch: String = "x86_64"
#endif
return "\(arch)-apple-macosx15.0"
}
/// 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
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
// LyrebirdLiveCompile
//
// `SnippetContext` is the public API surface the user's snippet talks to. The
// host (via `LiveSession.compileAndRun`) constructs one of these, passes the
@@ -48,6 +48,94 @@ public final class SnippetContext {
}
}
/// 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.lastSnippetMessage = "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))
}
/// Snippet-side hook for test verification: report the engine's sample rate
/// back through the session so tests can confirm the `context.engine`
/// linkage compiled and called correctly.
@@ -4,16 +4,15 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core
// LyrebirdLiveCompile — core
//
// C ABI signature of the snippet's exported entry point.
#if os(macOS)
/// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. Phase
/// 143 will pass a pointer to a `LiveSession` (or harness context) here;
/// Phase 142 only requires that snippets can declare a function matching this
/// signature.
/// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. The host
/// passes a pointer to a `LiveSession` (or harness context) here; snippets need
/// only declare a function matching this signature.
public typealias SnippetEntry = @convention(c) (UnsafeMutableRawPointer?) -> Void
#endif
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
// LyrebirdLiveCompile
//
// `SnippetHarness.wrap(userBody:)` produces the full Swift source that
// `LiveCompiler.compile(source:)` feeds to swiftc. The preamble imports the
@@ -18,9 +18,9 @@ public enum SnippetHarness {
/// 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
/// (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
/// isolation at compile time; it is safe at runtime because `LiveSession` always invokes
/// the entry on the main actor (`compileAndRunAsync` hops via `MainActor.run`;
@@ -0,0 +1,413 @@
// 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 only — the whole live-compile surface shells out to the toolchain.
#if os(macOS)
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 {
let xcrun: Process = Process()
xcrun.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
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 only.
#if os(macOS)
/// 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)
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
@@ -4,11 +4,11 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
// LyrebirdLiveCompile
//
// 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
// 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
// typed.
@@ -0,0 +1,38 @@
// EditorPositionMapping.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile
//
// Maps an `NSTextView` UTF-16 insertion offset to a zero-based (line, character)
// position. LSP positions are UTF-16-based, matching `NSTextView`'s own offsets,
// so no re-encoding is needed — only newline counting.
#if os(macOS)
/// Convert a UTF-16 offset into `text` to a zero-based `(line, character)`
/// where `character` is a UTF-16 code-unit column — the coordinate space
/// `sourcekit-lsp` expects. An offset past the end clamps to the final position.
func editorLineAndUTF16Char(in text: String, utf16Offset: Int) -> (line: Int, character: Int) {
let units: String.UTF16View = text.utf16
var idx: String.UTF16View.Index = units.startIndex
var consumed: Int = 0
var line: Int = 0
var character: Int = 0
let newline: UInt16 = 10
while consumed < utf16Offset, idx < units.endIndex {
if units[idx] == newline {
line += 1
character = 0
} else {
character += 1
}
idx = units.index(after: idx)
consumed += 1
}
return (line, character)
}
#endif
@@ -41,11 +41,18 @@ window.open {
| Shortcut | Action |
|----------|--------|
| ⌘↩ | Compile + run. Removes synths from the previous run before executing. |
| ⌘↩ | Compile + run. Removes the previous run's *anonymous* synths first (named slots persist). |
| ⌘⇧↩ | Compile + run additively. Keeps previously played synths in the engine. |
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
`LiveSession.clearTracked()` directly.
``LyrebirdScratchModel/clearTracked()`` — a full reset that removes both the
anonymous tracked synths and every named slot.
The engine status pill at the top-left is also a **Start/Stop** button
(``LyrebirdScratchModel/toggleEngine()``): green "engine running" when live,
red "▶ start engine" when stopped. A snippet is only audible while the engine
is running; the host normally starts it at launch, but this lets the user
recover from a failed start (e.g. no output device) without relaunching.
## Snippet API surface
@@ -55,32 +62,236 @@ A snippet has one local in scope:
context: SnippetContext
```
`SnippetContext` is intentionally minimal in v1:
`SnippetContext`:
- `context.engine` — the host `SynthesisEngine`.
- `context.play(_:)` — add a `Synthesizer` to the engine and register it for
cleanup on the next non-additive run.
- `context.play { <graph> }` — play a bare generator graph, no `SynthesizerBase`
subclass needed (wraps it in a `ClosureSynthesizer`).
- `context.play(slot:_:)` / `context.play(slot:) { <graph> }` — play into a
**named slot** (see below).
- `context.reportMessage(_:)` — write back to the host (used by tests; handy for
`print`-style probes during development).
## Named slots (hot-swap)
`context.play(slot: "name") { … }` installs a voice under a name. Re-running a
slot definition **replaces just that voice in place** — the new voice starts
before the old one is removed (a brief overlap, no gap), while everything else
keeps playing:
```swift
context.play(slot: "bass") { OscSaw.Audio(freq: 55, mul: 0.2) }
context.play(slot: "lead") { Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0) }
```
Unlike anonymous `context.play`, a slotted voice is **not** torn down by the
next non-additive (⌘↩) run — that is what lets you edit and re-evaluate one
voice at a time while the rest of the patch keeps going (the `Pdef` idiom).
| API | Lifetime |
|-----|----------|
| `context.play(_:)` / `context.play { }` | Removed on the next non-additive run. |
| `context.play(slot:) { }` | Persists; a same-name re-run replaces it in place. |
Clear a slot with `context.session.clearSlot("bass")`, all slots with
`context.session.clearSlots()`. The toolbar **Clear Synths** button is a full
reset — anonymous synths *and* every slot. A slot definition you delete from the
buffer and stop re-running is *not* auto-removed (a `Pdef`-style gotcha) — clear
it explicitly or hit Clear Synths.
## Threading
All UI is `@MainActor`-isolated. `LiveSession.compileAndRun` is invoked
synchronously inside the button action, so the editor freezes for the duration
of the `swiftc` invocation (≈ 1 second cold, much faster on warm cache). v1
accepts that trade-off; an off-main compile path is on the polish list.
All UI is `@MainActor`-isolated. The Run / Run Additive actions dispatch a
`Task` that awaits ``LyrebirdScratchModel/run(additive:)``, which awaits
`LiveSession.compileAndRunAsync` — the `swiftc` subprocess runs on a background
`Task.detached`, so the editor stays responsive while a compile is in flight.
The snippet entry then resumes on the main actor to touch engine + UI state.
`LyrebirdScratchMenuController` disables the Run / Run Additive commands
whenever ``ReevalState/canEvaluate`` is `false` (a compile is in flight or the
buffer is empty); `run(additive:)` additionally guards re-entrancy on
``LyrebirdScratchModel/isCompiling``.
## Re-evaluation readiness
``LyrebirdScratchModel/reevalState`` publishes a ``ReevalState`` — a structured
signal for *when* a re-evaluation is available and whether it would change
anything:
| State | Meaning |
|-------|---------|
| `.empty` | Buffer is blank. Nothing to run. |
| `.dirty` | Edited since the last run (or never run). An eval is available. |
| `.compiling` | A compile + run is in flight. |
| `.queued(untilBeat:)` | Compiled; a quantized slot swap is scheduled but not yet audible (see below). |
| `.clean` | Buffer matches what is currently playing. |
| `.failed(diagnosticCount:)` | The last run failed to compile. |
The editor renders this as a colored dot + label in the status bar.
``ReevalState/canEvaluate`` is `true` whenever a run can be triggered right now
(non-blank buffer, no compile already running) — hosts can gate their own Run
controls on it.
## Quantized swaps (on-beat latency masking)
A `swiftc` build finishes a few hundred milliseconds after ⌘↩ — long enough to
feel loose against a running groove. Point the session at a `LyrebirdClock` and
choose a `SwapQuantize` mode, and named-slot swaps land on the next musical
boundary instead of whenever the compile happens to finish:
```swift
let clock = LyrebirdClock(engine: engine, bpm: 120)
let session = LiveSession(engine: engine)
session.swapClock = clock
session.swapQuantize = .nextBar(beatsPerBar: 4) // .immediate | .nextBeat | .nextBar
```
Now `context.play(slot: "bass") { … }` **schedules** the new voice's add and the
old voice's removal at the same upcoming boundary sample time (`engine.schedule` /
`engine.remove(_:at:)`), so the swap is glitch-free and on-grid. Because the
change is quantized to a boundary that is comfortably past the compile, the
compile latency is hidden: you edit, hit ⌘↩, and the change drops exactly on the
downbeat.
While the swap is pending, ``LyrebirdScratchModel/reevalState`` reads
`.queued(untilBeat:)` (a purple badge); it settles to `.clean` once the clock
passes the boundary (or `.dirty` if you edit again first). ``LiveSession/pendingSwapBeat``
exposes the target beat. `.immediate` (or no `swapClock`) makes swaps take effect
at once. Anonymous `context.play` is unaffected; quantization applies to named
slots only.
Re-running a slot while its previous quantized swap is still pending is safe: the
previous voice's removal is always scheduled no earlier than its own add, so a
just-scheduled voice is never left orphaned.
## First-run latency (module-cache prewarm)
A snippet compiles in ~0.1 s once the Swift/Clang module cache is warm — but the
*first* compile of a session pays ~2–3 s to build the precompiled module for the
large `LyrebirdSynth` interface. Left alone, that cost lands on the user's first
⌘↩ (the "time to first sound").
``LiveSession/prewarm()`` moves it into the background: it type-checks a trivial
import-only snippet on a detached `.utility` task, warming swiftc's default
module cache so the first real compile is already fast. `LyrebirdScratchView`
calls it from `onAppear` (idempotent — safe to call again). It is *not* wired
into `LyrebirdScratchModel.init`, so constructing a model never shells out to
swiftc; a headless host should call `session.prewarm()` at launch itself.
A prewarm never throws: a failure (e.g. a missing toolchain) leaves
``LiveSession/isPrewarmed`` `false` — so a later call retries, and the first
real compile simply pays the cold build itself and surfaces any real error
through its own diagnostics.
> Note: the prewarm deliberately uses swiftc's default module cache rather than a
> pinned `-module-cache-path`. A freshly-built dedicated cache produces module
> metadata that diverges from the already-loaded `libLyrebirdLiveCompileDynamic`,
> which turns a benign ObjC class-duplication warning into a hard cast crash when
> a snippet is `dlopen`'d.
## Code completion
Swift code completion is provided by the toolchain's `sourcekit-lsp`, driven over
stdio by ``SourceKitLSPClient`` and bridged to the editor by
``SnippetCompletionService``. Typing `.` after an expression pops the standard
completion window; the candidates are the real symbols the snippet would see at
compile time — `LyrebirdSynth` generators (`OscSin.` → `Audio`, `Control`, …),
the injected `context` (`context.` → `play`, `engine`, …), and the Swift
standard library.
How it resolves those symbols for an otherwise free-standing file: the service
maintains a small temp workspace holding the snippet **wrapped** in the same
`SnippetHarness` preamble the compiler uses, next to a `compile_commands.json`
carrying the host `LiveSession`'s `-I` / module-map / link flags. sourcekit-lsp's
compilation-database build system reads that file. The caret is mapped through
the harness line offset, so a completion request at the user's row hits the right
row in the wrapped document. Completion is Swift-mode only — graph-DSL mode is
interpreted and needs no compiler — and best-effort: any LSP failure yields no
candidates rather than an error.
## Limitations
- macOS only.
- No syntax highlighting, code completion, or line-number gutter (deferred).
- Compiled dylibs are leaked by design — types in a loaded snippet may still be
referenced by tracked synths; unloading is unsafe.
- Syntax highlighting is a lightweight built-in lexer (`ScratchSwiftTokenizer`) —
approximate by design, not a full parser. Completion (above) uses the real
compiler via sourcekit-lsp; the two are independent.
- Completion currently triggers on `.`; a manual-invoke shortcut is a possible
follow-up.
- The host `.app` must not be sandboxed and must allow library validation to be
disabled, since `swiftc` is invoked via `Process` and the resulting unsigned
dylib is `dlopen`'d.
## Snippet memory (the dylib leak)
Every ⌘↩ compiles a fresh dylib and `dlopen`s it; those dylibs are **never
unloaded**, so a session's mapped memory grows one dylib per successful
evaluation. ``LiveSession/loadedSnippetCount`` reports how many are mapped — a
host can nudge the user to restart after a very long session.
This is a hard limit of the compiled approach, not an oversight. Reclaiming the
memory would require `dlclose`, which is **unsafe** for these dylibs: `dlopen`
registers a Swift dylib's type metadata and protocol-conformance records into
process-global runtime caches, and `dlclose` unmaps the dylib without
deregistering them — leaving those caches pointing into freed memory, so a later
type operation can crash. That holds even after every synth a snippet produced
has been removed. A refcount-gated `dlclose` was therefore considered and
rejected rather than shipped as a crash-prone flag.
``LiveSession/resetAll()`` (the toolbar **Clear Synths**) is the pressure-relief
valve: it stops all snippet audio — removing every anonymous and slotted synth —
and gives a clean slate without tearing down the engine, but it does not reclaim
the mapped dylibs. Only restarting the process does. The **Graph DSL mode**
below sidesteps dylibs entirely and is the structural fix.
The editor makes this visible rather than silent: the engine bar shows a
**"snippets: N"** count (`LyrebirdScratchModel.loadedSnippetCount`), and once it
crosses ``LyrebirdScratchModel/snippetRestartThreshold`` (50) the count turns
orange and a warning banner appears — nudging the user to restart to reclaim the
memory, or to switch to Graph DSL mode (which maps no dylibs). It is a nudge, not
a hard stop: the choice stays with the user.
## Graph DSL mode (instant, no compile)
The status-bar toggle switches the editor between two evaluators:
- **Swift** — the full snippet path above: swiftc compiles a dylib, which is
`dlopen`'d and run. The whole language, `SynthesizerBase` subclasses, arbitrary
code — at the cost of a compile and a permanently mapped dylib.
- **Graph DSL** — the interpreted graph-DSL. The buffer is lexed, parsed, and
built into a generator graph **in-process**: no swiftc, no dylib, microseconds
instead of a compile round-trip, and nothing leaks. The trade is scope — only
generator-graph *expressions*, not arbitrary Swift.
A DSL buffer is one statement per line:
```
bass = OscSawtooth.Audio(freq: 55, mul: 0.15)
Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0)
```
- A **bare** line plays anonymously and is tracked, so a non-additive re-run
(⌘↩) replaces it — exactly like `context.play { … }`.
- A **named** line (`name = …`) installs a persistent, hot-swappable named slot
(like `context.play(slot:)`): it survives a non-additive re-run and is swapped
in place on the next evaluation, so you can mutate one voice while others keep
playing. Quantized swaps apply here too.
Generators are spelled **exactly** as in a Lyrebird `build()` —
`OscSin.Audio(freq:)`, `.Control` for the control-rate variant — so a graph you
like in the editor pastes into a project unchanged (only the wrapping differs;
see the `LyrebirdGraphDSL` design notes). The bare `OscSin(…)` no-rate form is a
DSL shorthand for the audio variant.
The whole program is built **before** any engine mutation, so a syntax or build
error leaves the currently-playing graph untouched — a bad edit never drops
audio. Errors surface in the same gutter as swiftc diagnostics: a parse error
points at its line/column; a build error (unknown generator, bad argument)
reports at file scope. See ``LyrebirdScratchModel/switchMode(to:)`` and
``LiveSession/runGraphDSL(_:additive:resources:)``.
## Topics
- ``LyrebirdScratchView``
- ``LyrebirdScratchModel``
- ``ScratchEvalMode``
@@ -13,8 +13,12 @@ import LyrebirdLiveCompile
/// Builds and installs the macOS application menu bar for a live-coding host
/// driven by a `LyrebirdScratchModel`. Owns the action targets so menu items
/// stay wired for the lifetime of the controller.
///
/// Conforms to `NSMenuItemValidation` so the Run / Run Additive commands
/// disable when the buffer cannot be evaluated — i.e. while a compile is in
/// flight or the buffer is empty (``ReevalState/canEvaluate``).
@MainActor
public final class LyrebirdScratchMenuController: NSObject {
public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation {
public let model: LyrebirdScratchModel
@@ -201,6 +205,21 @@ public final class LyrebirdScratchMenuController: NSObject {
return item
}
// MARK: - Menu validation
/// Disable the Run / Run Additive commands whenever the buffer cannot be
/// evaluated (a compile is in flight, or the buffer is empty). All other
/// items stay enabled. AppKit calls this automatically for items whose
/// target is this controller.
public func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
switch menuItem.action {
case #selector(runSnippet(_:)), #selector(runSnippetAdditive(_:)):
return model.reevalState.canEvaluate
default:
return true
}
}
// MARK: - Action targets
private func target(_ item: NSMenuItem) -> NSMenuItem {
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile — Phase 145
// LyrebirdUI/LiveCompile
//
// Backing model for `LyrebirdScratchView`. Owns the editable snippet text, the
// most recent compile result, and the host `LiveSession`. Pulled out of the
@@ -16,7 +16,11 @@
import Foundation
import CoreGraphics
import LyrebirdSynth
import LyrebirdLiveCompile
// Re-exported so consumers that link only the `LyrebirdLiveCompileUI` product
// (e.g. the LyrebirdScratchDemo app) get the `LyrebirdLiveCompile` API
// (`LiveSession`, …) without separately linking the `LyrebirdLiveCompile`
// dynamic product — which clashes in Xcode with the static target embed.
@_exported import LyrebirdLiveCompile
/// Observable backing model for `LyrebirdScratchView`.
///
@@ -38,27 +42,54 @@ public final class LyrebirdScratchModel: ObservableObject {
// ⌘⇧↩ — additive run (keep previously played synths around).
//
// The snippet body has `context: SnippetContext` in scope.
// `context.engine` → the host `SynthesisEngine`.
// `context.play(synth)` → adds a `Synthesizer` and tracks it for cleanup.
// `context.reportMessage(_)`→ writes back to the host (useful for `print`-style probes).
// `context.play { <graph> }` → play a bare generator graph, no subclass needed.
// `context.play(synth)` → add a `Synthesizer` you declared.
// `context.engine` → the host `SynthesisEngine`.
// `context.reportMessage(_)` → write back to the host (`print`-style probes).
class SineSynth: SynthesizerBase {
override func build() {
let sine = OscSin.Audio(freq: 440, mul: 0.15)
let stereo = Pan2(input: sine, pan: 0)
output(bus: 0, source: stereo)
}
}
let synth = SineSynth()
_ = context.play(synth)
context.play { Pan2(input: OscSin.Audio(freq: 440, mul: 0.15), pan: 0) }
context.reportMessage("playing 440 Hz sine — stereo, centered")
"""
/// Placeholder for the interpreted graph-DSL mode. Shows the instant path:
/// no `context`, no subclass — just generator-graph expressions, one per
/// line, spelled exactly as they would be in a Lyrebird `build()`.
public nonisolated static let graphDSLPlaceholder: String = """
# Graph DSL — instant, no compile. One graph expression per line.
# A bare line plays anonymously; `name = …` plays a named, hot-swappable slot.
# Generators are spelled exactly as in Swift: OscSin.Audio(freq: 440) * 0.1
bass = OscSawtooth.Audio(freq: 55, mul: 0.15)
Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0)
"""
/// The seed text for a given evaluation mode.
public nonisolated static func defaultPlaceholder(for mode: ScratchEvalMode) -> String {
switch mode {
case .swift: return defaultPlaceholder
case .graphDSL: return graphDSLPlaceholder
}
}
/// Current editor text. View binds to this; user edits flow back here via
/// the `NSTextView` delegate inside `LyrebirdScratchView`.
@Published public var text: String
///
/// Edits recompute ``reevalState`` (unless a compile is in flight, which
/// owns the state until it resolves).
@Published public var text: String {
didSet { recomputeReevalStateAfterEdit() }
}
/// Structured re-evaluation readiness signal. See ``ReevalState``. The view
/// binds a status badge to this and gates the Run controls on
/// ``ReevalState/canEvaluate``.
@Published public private(set) var reevalState: ReevalState
/// Text of the most recent *successful* run. `nil` before the first
/// successful run. Compared against ``text`` to decide `.clean` vs `.dirty`.
private var lastEvaluatedText: String?
/// Parsed swiftc diagnostics from the last `run(additive:)` invocation.
/// Empty when the last run compiled cleanly or has not yet been attempted.
@@ -72,6 +103,37 @@ public final class LyrebirdScratchModel: ObservableObject {
/// `clearTracked` call so the toolbar can show the count without polling.
@Published public private(set) var trackedSynthCount: Int
/// Mirror of `session.loadedSnippetCount` — compiled snippet dylibs mapped
/// into the process this session. Each successful **Swift-mode** run maps
/// one; they are never unloaded (`dlclose` is unsafe for Swift dylibs — see
/// ``LiveSession/resetAll()``), so this only grows until a process restart.
/// Graph-DSL runs add nothing. Refreshed alongside ``trackedSynthCount``.
@Published public private(set) var loadedSnippetCount: Int
/// Count of mapped snippet dylibs past which the editor nudges the user to
/// restart (or switch to the leak-free Graph DSL mode).
public nonisolated static let snippetRestartThreshold: Int = 50
/// A restart suggestion once ``loadedSnippetCount`` reaches
/// ``snippetRestartThreshold``, else `nil`. The mapped dylibs cannot be
/// reclaimed without a process restart (by design), so this is the
/// user-facing safety valve over that leak.
public var snippetMemoryHint: String? {
LyrebirdScratchModel.snippetMemoryHint(count: loadedSnippetCount)
}
/// Pure form of ``snippetMemoryHint`` — the message for `count` mapped
/// snippets, or `nil` below `threshold`. Factored out so the boundary is
/// unit-testable without running dozens of real compiles.
nonisolated static func snippetMemoryHint(
count: Int,
threshold: Int = LyrebirdScratchModel.snippetRestartThreshold
) -> String? {
guard count >= threshold else { return nil }
return "\(count) compiled snippets are mapped and can't be freed without "
+ "restarting. Restart to reclaim memory, or use Graph DSL mode (no compile, no leak)."
}
/// `true` while a `run(additive:)` invocation is awaiting the background
/// swiftc compile. View code disables Run / Run Additive buttons against
/// this so a second compile cannot stack on top of a still-running one.
@@ -89,8 +151,39 @@ public final class LyrebirdScratchModel: ObservableObject {
/// horizontally.
@Published public var wrapsLines: Bool = true
/// Which evaluator ``run(additive:)`` sends the buffer through. `.swift`
/// compiles a snippet dylib; `.graphDSL` interprets a generator graph
/// instantly. Toggle via ``switchMode(to:)`` so the seed placeholder swaps
/// with the mode. See ``ScratchEvalMode``.
@Published public private(set) var evalMode: ScratchEvalMode = .swift
public let session: LiveSession
/// Lazily-created code-completion service (Swift mode only). Spun up on the
/// first completion request so a session that never triggers completion
/// never launches `sourcekit-lsp`.
private var _completion: SnippetCompletionService?
/// Fetch Swift code-completion candidates for the current buffer at a
/// zero-based user-space `line` / `character` (UTF-16). Returns `[]` in
/// graph-DSL mode (the interpreter needs no LSP) or on any LSP failure —
/// completion is best-effort and never surfaces an error to the editor.
public func completionItems(line: Int, character: Int) async -> [LSPCompletionItem] {
guard evalMode == .swift else { return [] }
let service: SnippetCompletionService
if let existing: SnippetCompletionService = _completion {
service = existing
} else {
service = SnippetCompletionService(session: session)
_completion = service
}
do {
return try await service.completions(userBody: text, line: line, character: character)
} catch {
return []
}
}
public nonisolated static let minFontSize: CGFloat = 9
public nonisolated static let maxFontSize: CGFloat = 32
public nonisolated static let defaultFontSize: CGFloat = 13
@@ -120,6 +213,44 @@ public final class LyrebirdScratchModel: ObservableObject {
self.session = session
self.text = initialText
self.trackedSynthCount = session.trackedSynthCount
self.loadedSnippetCount = session.loadedSnippetCount
// No run yet: blank buffer is `.empty`, otherwise `.dirty` (runnable,
// never evaluated). `lastEvaluatedText` stays nil until a run succeeds.
self.reevalState = LyrebirdScratchModel.isBlank(initialText) ? .empty : .dirty
}
/// Whether `text` is empty once whitespace and newlines are stripped.
private nonisolated static func isBlank(_ text: String) -> Bool {
text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
/// Recompute ``reevalState`` from the current buffer after a user edit.
/// A no-op while a compile is in flight — the run owns the state until it
/// resolves (edits made mid-compile are re-evaluated once it finishes).
private func recomputeReevalStateAfterEdit() {
guard !isCompiling else { return }
reevalState = derivedIdleState()
}
/// Settle a `.queued` state once its scheduled swap has become audible.
/// Called on the editor's heartbeat (the view's refresh timer): when the
/// session no longer reports a pending swap, drop back to the idle state
/// (`.clean`, or `.dirty` if the buffer was edited while queued). No-op
/// unless the current state is `.queued`.
public func refreshQueuedState() {
guard case .queued = reevalState else { return }
if session.pendingSwapBeat == nil {
reevalState = derivedIdleState()
}
}
/// The readiness state implied by the current buffer when no compile is in
/// flight: `.empty` for a blank buffer, `.clean` when it matches the last
/// successful run, `.dirty` otherwise.
private func derivedIdleState() -> ReevalState {
if LyrebirdScratchModel.isBlank(text) { return .empty }
if let last: String = lastEvaluatedText, last == text { return .clean }
return .dirty
}
/// Compile and execute the current `text`. Updates `diagnostics`,
@@ -136,19 +267,30 @@ public final class LyrebirdScratchModel: ObservableObject {
/// without throwing; `false` otherwise.
@discardableResult
public func run(additive: Bool) async -> Bool {
switch evalMode {
case .swift: return await runSwiftSnippet(additive: additive)
case .graphDSL: return runGraphDSLBuffer(additive: additive)
}
}
/// Swift path: compile the buffer to a dylib off-main and run it.
private func runSwiftSnippet(additive: Bool) async -> Bool {
guard !isCompiling else { return false }
let body: String = text
diagnostics = []
statusMessage = "Compiling…"
isCompiling = true
reevalState = .compiling
defer {
isCompiling = false
trackedSynthCount = session.trackedSynthCount
loadedSnippetCount = session.loadedSnippetCount
}
do {
try await session.compileAndRunAsync(body, additive: additive)
let mode: String = additive ? "additive" : "replaced"
statusMessage = "Ran (\(mode)). Tracked synths: \(session.trackedSynthCount)."
settleReevalAfterSuccess(body: body)
return true
} catch let sessionError as LiveSessionError {
switch sessionError {
@@ -169,19 +311,122 @@ public final class LyrebirdScratchModel: ObservableObject {
}
case .compilerError(let underlying):
statusMessage = "Compiler error: \(underlying)"
case .graphDSLFailed(let diags, _):
// Not expected on the Swift path, but map it faithfully.
diagnostics = diags
statusMessage = "DSL error — \(diags.count) diagnostic(s)."
}
reevalState = .failed(diagnosticCount: diagnostics.count)
return false
} catch {
statusMessage = "Error: \(error)"
reevalState = .failed(diagnosticCount: diagnostics.count)
return false
}
}
/// Forward to `LiveSession.clearTracked()` and refresh `trackedSynthCount`.
/// Graph-DSL path: interpret the buffer in-process — instant, no swiftc, so
/// no `isCompiling` spinner and no `await`. A parse/build failure leaves the
/// currently-playing graph untouched (the session builds before it mutates).
private func runGraphDSLBuffer(additive: Bool) -> Bool {
guard !isCompiling else { return false }
let body: String = text
diagnostics = []
defer {
trackedSynthCount = session.trackedSynthCount
loadedSnippetCount = session.loadedSnippetCount
}
do {
try session.runGraphDSL(body, additive: additive)
let mode: String = additive ? "additive" : "replaced"
statusMessage = "Ran DSL (\(mode)). Tracked synths: \(session.trackedSynthCount)."
settleReevalAfterSuccess(body: body)
return true
} catch let sessionError as LiveSessionError {
if case .graphDSLFailed(let diags, _) = sessionError {
diagnostics = diags
let plural: String = diags.count == 1 ? "" : "s"
statusMessage = "DSL error — \(diags.count) diagnostic\(plural)."
} else {
statusMessage = "Error: \(sessionError)"
}
reevalState = .failed(diagnosticCount: diagnostics.count)
return false
} catch {
statusMessage = "Error: \(error)"
reevalState = .failed(diagnosticCount: diagnostics.count)
return false
}
}
/// Record the just-run text as the baseline and settle the readiness state:
/// `.queued` when the buffer is unchanged and a quantized slot swap is
/// scheduled but not yet audible, otherwise the derived idle state (`.clean`,
/// or `.dirty` if the buffer was edited while the run was in flight).
private func settleReevalAfterSuccess(body: String) {
lastEvaluatedText = body
let idle: ReevalState = derivedIdleState()
if idle == .clean, let beat: Double = session.pendingSwapBeat {
reevalState = .queued(untilBeat: beat)
} else {
reevalState = idle
}
}
/// Switch evaluation mode. When the buffer still holds the *current* mode's
/// untouched placeholder, swap in the target mode's placeholder so the seed
/// example matches the mode; any edited buffer is left as-is.
///
/// The new mode's evaluator has not run whatever is on screen, so the last-run
/// baseline is dropped (the buffer reads as `.dirty`) and any diagnostics from
/// a prior run in the old mode are cleared — leaving them would show gutter
/// markers against a buffer the current mode never evaluated.
public func switchMode(to mode: ScratchEvalMode) {
guard mode != evalMode else { return }
if text == LyrebirdScratchModel.defaultPlaceholder(for: evalMode) {
text = LyrebirdScratchModel.defaultPlaceholder(for: mode)
}
lastEvaluatedText = nil
diagnostics = []
evalMode = mode
reevalState = derivedIdleState()
}
/// Start the audio engine if stopped, or stop it if running. Surfaces the
/// outcome (including a start failure — e.g. no audio device) on the status
/// line. The host normally starts the engine at launch; this lets the user
/// see the state and recover from a failed start without relaunching.
public func toggleEngine() {
let engine: SynthesisEngine = session.engine
if engine.isRunning {
engine.stop()
statusMessage = "Engine stopped."
} else {
do {
try engine.start()
statusMessage = "Engine started."
} catch {
statusMessage = "Engine failed to start: \(error)"
}
}
}
/// Full reset: remove both the anonymous tracked synths *and* every named
/// slot from the engine, then refresh `trackedSynthCount`.
///
/// Clearing the engine means nothing the buffer produced is still playing,
/// so the "last run" baseline is dropped and the buffer reads as `.dirty`
/// (or `.empty`) — a re-evaluation is again meaningful.
public func clearTracked() {
session.clearTracked()
session.resetAll()
trackedSynthCount = session.trackedSynthCount
statusMessage = "Cleared tracked synths."
// `resetAll` stops audio but does NOT unload the compiled snippet dylibs
// (unsafe), so the mapped-snippet count is unchanged — refresh the mirror
// so the UI stays truthful about it.
loadedSnippetCount = session.loadedSnippetCount
statusMessage = "Cleared all synths (tracked + slots)."
lastEvaluatedText = nil
reevalState = derivedIdleState()
}
// MARK: - Snippet save / load
@@ -193,10 +438,14 @@ public final class LyrebirdScratchModel: ObservableObject {
/// `NSOpenPanel` UI; this method does the IO.
public func load(from url: URL) throws {
let loaded: String = try String(contentsOf: url, encoding: .utf8)
// Drop the run baseline first so the `text` didSet — and the explicit
// recompute below — treat freshly loaded content as unrun (`.dirty`).
lastEvaluatedText = nil
text = loaded
documentURL = url
diagnostics = []
statusMessage = "Loaded \(url.lastPathComponent)."
reevalState = derivedIdleState()
}
/// Write `text` to `url` as UTF-8, set ``documentURL``, refresh status.
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile — Phase 145
// LyrebirdUI/LiveCompile
//
// `LyrebirdScratchView` — SwiftUI scratchpad editor for live-coded snippets.
// Wraps an `NSTextView` for the editor surface, drives a `LyrebirdScratchModel`
@@ -45,12 +45,15 @@ import LyrebirdLiveCompile
///
/// ## Threading
///
/// All UI work is `@MainActor`-isolated. The Run / Run Additive buttons
/// dispatch a `Task` that awaits `LyrebirdScratchModel.run(additive:)`, which
/// itself awaits `LiveSession.compileAndRunAsync`. The swiftc subprocess runs
/// on a background `Task.detached`; the snippet entry then resumes on the
/// main actor so it can touch UI-side state. Both Run buttons disable while
/// ``LyrebirdScratchModel/isCompiling`` is `true`.
/// All UI work is `@MainActor`-isolated. The Run / Run Additive commands (in the
/// menu bar built by ``LyrebirdScratchMenuController``) dispatch a `Task` that
/// awaits `LyrebirdScratchModel.run(additive:)`, which itself awaits
/// `LiveSession.compileAndRunAsync`. The swiftc subprocess runs on a background
/// `Task.detached`; the snippet entry then resumes on the main actor so it can
/// touch UI-side state. The menu controller gates the Run commands on
/// ``ReevalState/canEvaluate`` (disabled while a compile is in flight or the
/// buffer is empty); `run(additive:)` additionally guards re-entrancy on
/// ``LyrebirdScratchModel/isCompiling``.
@MainActor
public struct LyrebirdScratchView: View {
@@ -84,6 +87,10 @@ public struct LyrebirdScratchView: View {
public var body: some View {
VStack(spacing: 0) {
engineBar
if let hint: String = model.snippetMemoryHint {
Divider()
snippetMemoryBanner(hint)
}
Divider()
ScratchEditor(
text: Binding(
@@ -91,7 +98,10 @@ public struct LyrebirdScratchView: View {
set: { model.text = $0 }
),
fontSize: model.fontSize,
wrapsLines: model.wrapsLines
wrapsLines: model.wrapsLines,
requestCompletions: { line, character in
await model.completionItems(line: line, character: character)
}
)
.frame(minHeight: editorMinHeight)
Divider()
@@ -102,18 +112,37 @@ public struct LyrebirdScratchView: View {
}
}
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
.onReceive(engineRefresh) { _ in engineTick &+= 1 }
.onAppear {
// Warm the module cache in the background so the first ⌘↩ is ~0.1 s
// instead of paying the ~2–3 s cold `LyrebirdSynth` .pcm build.
// Idempotent — safe if `onAppear` fires again.
model.session.prewarm()
}
.onReceive(engineRefresh) { _ in
engineTick &+= 1
// Settle a `.queued` readiness badge once its swap has fired.
model.refreshQueuedState()
}
}
private var engineBar: some View {
let engine: SynthesisEngine = model.session.engine
return HStack(spacing: toolbarSpacing) {
Circle()
.fill(engine.isRunning ? Color.green : Color.red)
.frame(width: engineDotSize, height: engineDotSize)
Text(engine.isRunning ? "engine running" : "engine stopped")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
Button {
model.toggleEngine()
engineTick &+= 1
} label: {
HStack(spacing: reevalBadgeSpacing) {
Circle()
.fill(engine.isRunning ? Color.green : Color.red)
.frame(width: engineDotSize, height: engineDotSize)
Text(engine.isRunning ? "engine running" : "▶ start engine")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(engine.isRunning ? Color.secondary : Color.primary)
}
}
.buttonStyle(.plain)
.help(engine.isRunning ? "Stop the audio engine" : "Start the audio engine")
Spacer()
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(engine.averageCPU))")
.font(.system(.caption, design: .monospaced))
@@ -122,12 +151,35 @@ public struct LyrebirdScratchView: View {
Text("synths: \(model.trackedSynthCount)")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
Spacer().frame(width: 8)
Text("snippets: \(model.loadedSnippetCount)")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(model.snippetMemoryHint == nil ? Color.secondary : Color.orange)
.help("Compiled snippet dylibs mapped this session. They can't be "
+ "unloaded without restarting (Graph DSL mode maps none).")
}
.padding(.horizontal, toolbarPadding)
.padding(.vertical, 6)
.id(engineTick)
}
/// Warning strip shown once mapped snippet dylibs cross the restart
/// threshold — the user-facing safety valve over the by-design leak.
private func snippetMemoryBanner(_ hint: String) -> some View {
HStack(spacing: reevalBadgeSpacing) {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(.orange)
Text(hint)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.primary)
.fixedSize(horizontal: false, vertical: true)
Spacer(minLength: 0)
}
.padding(.horizontal, toolbarPadding)
.padding(.vertical, 6)
.background(Color.orange.opacity(0.12))
}
private func formatCPU(_ value: Double) -> String {
String(format: "%.0f%%", value * 100)
}
@@ -180,18 +232,96 @@ public struct LyrebirdScratchView: View {
}
private var statusBar: some View {
HStack {
HStack(spacing: toolbarSpacing) {
reevalBadge
Text(model.statusMessage.isEmpty ? "Ready." : model.statusMessage)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
.lineLimit(1)
.truncationMode(.middle)
Spacer()
modePicker
}
.padding(.horizontal, statusHPad)
.padding(.vertical, statusVPad)
}
/// Segmented toggle between the Swift-compile and instant graph-DSL
/// evaluators. Routes through ``LyrebirdScratchModel/switchMode(to:)`` so the
/// seed placeholder follows the mode.
private var modePicker: some View {
Picker("Mode", selection: Binding(
get: { model.evalMode },
// Defer to the next main-actor tick: the Picker's `set` runs inside
// SwiftUI's view-update pass, and `switchMode` mutates @Published
// state ("Publishing changes from within view updates is not
// allowed"). Scheduling it off the current pass avoids that.
set: { newMode in Task { @MainActor in model.switchMode(to: newMode) } }
)) {
ForEach(ScratchEvalMode.allCases, id: \.self) { mode in
Text(mode.title).tag(mode)
}
}
.pickerStyle(.segmented)
.labelsHidden()
.fixedSize()
.help("Swift compiles a snippet dylib; Graph DSL interprets a generator graph instantly, no compile.")
}
/// Re-evaluation readiness indicator: a colored dot + short label bound to
/// ``LyrebirdScratchModel/reevalState``. Tells the user at a glance whether
/// an eval is available (dirty), in flight (compiling), matches what is
/// playing (clean), or failed.
private var reevalBadge: some View {
HStack(spacing: reevalBadgeSpacing) {
Circle()
.fill(reevalColor)
.frame(width: engineDotSize, height: engineDotSize)
Text(reevalLabel)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
}
.help(reevalHelp)
}
private var reevalColor: Color {
switch model.reevalState {
case .empty: return .secondary
case .clean: return .green
case .dirty: return .yellow
case .compiling: return .blue
case .queued: return .purple
case .failed: return .red
}
}
private var reevalLabel: String {
switch model.reevalState {
case .empty: return "empty"
case .clean: return "clean"
case .dirty: return "dirty"
case .compiling: return "compiling"
case .queued: return "queued"
case .failed: return "failed"
}
}
private var reevalHelp: String {
switch model.reevalState {
case .empty: return "Nothing to evaluate."
case .clean: return "Buffer matches what is playing. ⌘↩ re-runs it."
case .dirty: return "Edited since the last run — ⌘↩ to re-evaluate."
case .compiling: return "Compiling…"
case .queued(let beat):
return String(format: "Compiled — swap lands on beat %.0f.", beat)
case .failed(let count):
let plural: String = count == 1 ? "" : "s"
return count == 0
? "Last run failed to compile."
: "Last run failed — \(count) diagnostic\(plural)."
}
}
private var diagnosticsList: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
@@ -219,6 +349,7 @@ public struct LyrebirdScratchView: View {
private let diagnosticsMinHeight: CGFloat = 80
private let diagnosticsMaxHeight: CGFloat = 200
private let engineDotSize: CGFloat = 8
private let reevalBadgeSpacing: CGFloat = 4
}
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
@@ -250,7 +381,12 @@ private struct DiagnosticRow: View {
if let line: Int = diagnostic.line {
return "\(line):\(diagnostic.column)"
}
return "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
// No user-body line. A swiftc preamble hit carries a real (1-based)
// rawLine; a graph-DSL file-scope error carries rawLine 0 (there is no
// harness/preamble at all), so label the two cases distinctly.
return diagnostic.rawLine >= 1
? "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
: "(file)"
}
private func color(for severity: DiagnosticSeverity) -> Color {
@@ -266,7 +402,37 @@ private struct DiagnosticRow: View {
private let severityColumnWidth: CGFloat = 56
}
/// `NSViewRepresentable` wrapping a vanilla `NSTextView` inside an
/// `NSTextView` subclass that fixes member-completion behavior.
///
/// The default `rangeForUserCompletion` scans back over the whole dotted
/// expression, so completing a member right after a `.` (e.g. `context.` →
/// `engine`) would *replace* the receiver (`context`) with the chosen member
/// instead of inserting after the dot. When the character before the insertion
/// point is a `.`, this override returns an empty range at the caret, so the
/// completion is a pure insertion and `context.engine` is produced.
/// UTF-16 code unit for `.` (the member-access operator that triggers and
/// shapes completion).
private let dotCharacterCode: unichar = 46
/// Whether `selection` is a bare insertion point sitting immediately after a
/// `.` in `text` — the member-completion trigger condition.
private func caretFollowsDot(in text: NSString, selection: NSRange) -> Bool {
guard selection.length == 0, selection.location > 0, selection.location <= text.length
else { return false }
return text.character(at: selection.location - 1) == dotCharacterCode
}
final class ScratchTextView: NSTextView {
override var rangeForUserCompletion: NSRange {
let sel: NSRange = selectedRange()
if caretFollowsDot(in: string as NSString, selection: sel) {
return NSRange(location: sel.location, length: 0)
}
return super.rangeForUserCompletion
}
}
/// `NSViewRepresentable` wrapping a ``ScratchTextView`` inside an
/// `NSScrollView`. Monospaced 13 pt, plain text, no smart-quote / dash /
/// auto-correct interference — matches the editor expectations of someone
/// typing Swift code.
@@ -275,24 +441,90 @@ private struct ScratchEditor: NSViewRepresentable {
@Binding var text: String
let fontSize: CGFloat
let wrapsLines: Bool
/// Async source of code-completion candidates for a zero-based user-space
/// (line, UTF-16 character). Supplied by the view from the model.
let requestCompletions: @MainActor (_ line: Int, _ character: Int) async -> [LSPCompletionItem]
@MainActor
final class Coordinator: NSObject, NSTextViewDelegate {
var parent: ScratchEditor
/// Candidate insert-texts from the most recent completion fetch; served
/// synchronously to the text view's completion window via the delegate.
private var _completionStrings: [String] = []
/// Monotonic id of the latest completion request; a resolving fetch only
/// applies its results if it is still the newest (so a slow older request
/// can't clobber a fresher one that landed first).
private var _completionGeneration: Int = 0
init(_ parent: ScratchEditor) { self.parent = parent }
func textDidChange(_ notification: Notification) {
guard let tv: NSTextView = notification.object as? NSTextView else { return }
parent.text = tv.string
parent.applyHighlight(to: tv)
// Auto-trigger member completion right after a `.` is typed.
if caretFollowsDot(in: tv.string as NSString, selection: tv.selectedRange()) {
triggerCompletion(tv)
}
}
/// The text view calls this synchronously from `complete(_:)`; return the
/// candidates fetched asynchronously just before. Replaces the default
/// dictionary-word completions entirely.
func textView(_ textView: NSTextView,
completions words: [String],
forPartialWordRange charRange: NSRange,
indexOfSelectedItem index: UnsafeMutablePointer<Int>?) -> [String] {
_completionStrings
}
/// Fetch completions for the current caret position, then show the text
/// view's completion window. No-op when the selection is non-empty (a
/// range is selected, not an insertion point) or the fetch is empty.
func triggerCompletion(_ tv: NSTextView) {
let sel: NSRange = tv.selectedRange()
guard sel.length == 0 else { return }
let (line, character): (Int, Int) = editorLineAndUTF16Char(
in: tv.string, utf16Offset: sel.location)
let request: @MainActor (Int, Int) async -> [LSPCompletionItem] = parent.requestCompletions
_completionGeneration += 1
let generation: Int = _completionGeneration
Task { @MainActor [weak self, weak tv] in
let items: [LSPCompletionItem] = await request(line, character)
guard let self: Coordinator = self, let tv: NSTextView = tv,
!items.isEmpty else { return }
// Ignore a superseded request (a newer trigger fired meanwhile)
// and one whose caret has since moved.
guard generation == self._completionGeneration,
tv.selectedRange() == sel else { return }
self._completionStrings = items.map { $0.insertText }
tv.complete(nil)
}
}
}
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSScrollView {
let scroll: NSScrollView = NSTextView.scrollableTextView()
if let tv: NSTextView = scroll.documentView as? NSTextView {
configure(tv, in: scroll, with: context.coordinator)
}
// Build the scroll view around a `ScratchTextView` subclass so its
// `rangeForUserCompletion` override can keep member completion from
// eating the receiver expression (see the class doc).
let scroll: NSScrollView = NSScrollView()
scroll.borderType = .noBorder
scroll.hasVerticalScroller = true
scroll.autoresizingMask = [.width, .height]
let tv: ScratchTextView = ScratchTextView(frame: .zero)
tv.autoresizingMask = [.width]
tv.isVerticallyResizable = true
tv.isHorizontallyResizable = false
tv.minSize = NSSize(width: 0, height: 0)
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude)
tv.textContainer?.widthTracksTextView = true
scroll.documentView = tv
configure(tv, in: scroll, with: context.coordinator)
return scroll
}
@@ -311,7 +543,7 @@ private struct ScratchEditor: NSViewRepresentable {
if tv.string != text {
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
} else if fontChanged {
reapplyAttrs(to: tv, font: font, paragraph: paragraphStyle)
applyHighlight(to: tv, font: font, paragraph: paragraphStyle)
}
}
@@ -340,16 +572,28 @@ private struct ScratchEditor: NSViewRepresentable {
let attributed: NSAttributedString = NSAttributedString(string: newText, attributes: attrs)
tv.textStorage?.setAttributedString(attributed)
tv.typingAttributes = attrs
applyHighlight(to: tv, font: font, paragraph: paragraph)
}
private func reapplyAttrs(to tv: NSTextView,
font: NSFont,
paragraph: NSParagraphStyle) {
// MARK: - Syntax highlighting
/// Re-tokenize the buffer and paint token colors via
/// ``ScratchSyntaxHighlighter``. Attribute-only — the string and the
/// selection are untouched.
private func applyHighlight(to tv: NSTextView,
font: NSFont,
paragraph: NSParagraphStyle) {
guard let storage: NSTextStorage = tv.textStorage else { return }
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
let range: NSRange = NSRange(location: 0, length: storage.length)
storage.setAttributes(attrs, range: range)
tv.typingAttributes = attrs
let base: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
tv.typingAttributes = base
}
/// Convenience for the delegate path, which has only the text view: rebuilds
/// the font/paragraph from the current `fontSize`.
func applyHighlight(to tv: NSTextView) {
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
applyHighlight(to: tv, font: font, paragraph: makeParagraphStyle(for: font))
}
private func applyWrap(to tv: NSTextView, in scroll: NSScrollView) {
@@ -378,7 +622,15 @@ private struct ScratchEditor: NSViewRepresentable {
tv.delegate = coordinator
let editorFont: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
tv.font = editorFont
tv.isRichText = false
// Rich text so per-token foreground colors render. User styling can't
// creep in: every edit re-runs `applyHighlight`, which normalizes the
// font/paragraph over the whole buffer before recoloring, and the smart
// substitutions below stay disabled.
tv.isRichText = true
// Rich text would otherwise allow dragged/pasted images to inject
// NSTextAttachment glyphs into the buffer; keep it plain-text-only so the
// content is always compilable Swift source.
tv.importsGraphics = false
tv.isAutomaticQuoteSubstitutionEnabled = false
tv.isAutomaticDashSubstitutionEnabled = false
tv.isAutomaticTextReplacementEnabled = false
@@ -0,0 +1,78 @@
// ReevalState.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile
//
// `ReevalState` is the structured re-evaluation readiness signal published by
// `LyrebirdScratchModel`. It answers "can I re-evaluate, and would it change
// anything?" for the editor UI — distinct from the free-text `statusMessage`.
// A snippet's buffer becomes `.dirty` when edited away from the last
// successfully-run text, flips to `.compiling` while a run is in flight, and
// settles to `.clean` (buffer matches what is playing) or `.failed` afterward.
//
// macOS only — the whole LiveCompile UI surface is macOS-only.
#if os(macOS)
/// Re-evaluation readiness of a live-coding buffer.
///
/// Published by ``LyrebirdScratchModel/reevalState`` so the editor can show a
/// status badge and enable/disable the Run controls without inspecting the
/// free-text status line.
///
/// State machine:
///
/// - ``empty`` → editing non-blank text → ``dirty``
/// - ``dirty`` → run starts → ``compiling``
/// - ``compiling`` → success → ``clean`` (or ``dirty`` if the buffer was edited
/// mid-compile; or ``queued(untilBeat:)`` if the run scheduled a quantized
/// slot swap that has not yet fired) / failure → ``failed(diagnosticCount:)``
/// - ``queued(untilBeat:)`` → the scheduled swap fires → ``clean`` (or
/// ``dirty`` if the buffer was edited while queued)
/// - ``clean`` / ``queued(untilBeat:)`` / ``failed(diagnosticCount:)`` →
/// editing → ``dirty`` (or ``empty`` if the buffer is cleared to whitespace)
public enum ReevalState: Equatable, Sendable {
/// Buffer is empty or whitespace-only. Nothing to evaluate.
case empty
/// Buffer matches the text of the last successful run — re-evaluating would
/// re-run the same source. Re-evaluation is still permitted (e.g. additive).
case clean
/// Buffer has been edited since the last successful run (or has never been
/// run) and holds non-blank content. A re-evaluation is available and would
/// change what is playing.
case dirty
/// A compile + run is in flight. Run controls should be disabled.
case compiling
/// The run compiled and its slot swap is scheduled but has not yet fired —
/// the change becomes audible on `untilBeat` (a `LyrebirdClock` beat). Only
/// reached when swaps are quantized (see `SwapQuantize`); the state settles
/// to ``clean`` once the clock passes the boundary.
case queued(untilBeat: Double)
/// The last run failed to compile. `diagnosticCount` is the number of
/// parsed diagnostics (0 when the failure produced no line-mapped
/// diagnostics, e.g. a toolchain error).
case failed(diagnosticCount: Int)
/// `true` when a re-evaluation can be triggered right now — i.e. the buffer
/// holds runnable content and no compile is already in flight. A pending
/// quantized swap (``queued``) does not block a further edit + re-run.
public var canEvaluate: Bool {
switch self {
case .empty, .compiling:
return false
case .clean, .dirty, .queued, .failed:
return true
}
}
}
#endif
@@ -0,0 +1,31 @@
// ScratchEvalMode.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile
//
// Which evaluator the scratch editor runs the buffer through.
#if os(macOS)
/// The evaluation path for a `LyrebirdScratchModel`'s buffer.
public enum ScratchEvalMode: String, CaseIterable, Sendable {
/// Full Swift snippet compiled with swiftc into a dylib and run — the whole
/// language, `SynthesizerBase` subclasses, arbitrary code. Costs a compile.
case swift
/// Interpreted graph-DSL — instant, no swiftc, but only generator-graph
/// expressions (`OscSin.Audio(freq: 440) * 0.1`, `bass = …`).
case graphDSL
/// Human-readable label for a mode toggle.
public var title: String {
switch self {
case .swift: return "Swift"
case .graphDSL: return "Graph DSL"
}
}
}
#endif
@@ -4,7 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile — Phase 147
// LyrebirdUI/LiveCompile
//
// Vertical line-number gutter for `ScratchEditor`'s `NSTextView`. Installed as
// the scroll view's `verticalRulerView` so it tracks scroll position for free.
@@ -0,0 +1,199 @@
// ScratchSwiftTokenizer.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile
//
// A small, dependency-free lexer that classifies the colorable spans of Swift
// source — comments, string literals, numbers, keywords, and Capitalized type
// names — for the scratch editor's syntax highlighting. It is intentionally
// approximate (a highlighter, not a parser): good enough to read code at a
// glance, and re-run whole on every keystroke — a full grapheme walk of the
// buffer, fine for typical snippet sizes (not tuned or validated for very large
// documents). Pure (no AppKit) so it is unit-testable. Ranges are `NSRange`
// (UTF-16), matching `NSTextView`.
//
// macOS only — consumed by the macOS-only scratch editor.
#if os(macOS)
import Foundation
/// Classifies Swift source into colorable token spans for syntax highlighting.
enum ScratchSwiftTokenizer {
/// A colorable category. Uncategorized text (identifiers, punctuation,
/// whitespace) produces no token and renders in the default text color.
enum Kind: Equatable {
case keyword
case type
case string
case number
case comment
}
/// One colorable span. `range` is a UTF-16 `NSRange` into the source.
struct Token: Equatable {
let range: NSRange
let kind: Kind
}
/// Swift keywords (plus a few common contextual ones) colored as keywords.
private static let keywords: Set<String> = [
"associatedtype", "class", "deinit", "enum", "extension", "fileprivate",
"func", "import", "init", "inout", "internal", "let", "open", "operator",
"private", "precedencegroup", "protocol", "public", "rethrows", "static",
"struct", "subscript", "typealias", "var",
"break", "case", "continue", "default", "defer", "do", "else",
"fallthrough", "for", "guard", "if", "in", "repeat", "return", "switch",
"where", "while",
"as", "await", "catch", "false", "is", "nil", "self", "Self", "super",
"throw", "throws", "true", "try", "Any",
"async", "some", "any", "mutating", "nonmutating", "weak", "unowned",
"final", "lazy", "indirect", "convenience", "required", "optional",
"override", "dynamic", "willSet", "didSet", "get", "set",
"actor", "nonisolated", "isolated", "distributed", "consuming",
"borrowing", "sending", "each",
]
/// UTF-16 length of the `"""` multiline-string delimiter.
private static let tripleQuoteDelimiterLength: Int = 3
/// Classify `text` into colorable token spans, left to right.
static func tokens(in text: String) -> [Token] {
let chars: [Character] = Array(text)
let count: Int = chars.count
// Prefix table of UTF-16 offsets so `[a, b)` maps to an exact NSRange
// even with multi-unit characters (emoji in a comment, etc.).
var utf16Starts: [Int] = [Int](repeating: 0, count: count + 1)
var acc: Int = 0
for k: Int in 0..<count {
utf16Starts[k] = acc
acc += chars[k].utf16.count
}
utf16Starts[count] = acc
func makeRange(_ start: Int, _ end: Int) -> NSRange {
NSRange(location: utf16Starts[start], length: utf16Starts[end] - utf16Starts[start])
}
var tokens: [Token] = []
var i: Int = 0
while i < count {
let c: Character = chars[i]
// Line comment: // … end of line
if c == "/", i + 1 < count, chars[i + 1] == "/" {
let start: Int = i
i += 2
while i < count, chars[i] != "\n" { i += 1 }
tokens.append(Token(range: makeRange(start, i), kind: .comment))
continue
}
// Block comment: /* … */ with Swift's nesting.
if c == "/", i + 1 < count, chars[i + 1] == "*" {
let start: Int = i
i += 2
var depth: Int = 1
while i < count, depth > 0 {
if chars[i] == "/", i + 1 < count, chars[i + 1] == "*" {
depth += 1
i += 2
} else if chars[i] == "*", i + 1 < count, chars[i + 1] == "/" {
depth -= 1
i += 2
} else {
i += 1
}
}
tokens.append(Token(range: makeRange(start, i), kind: .comment))
continue
}
// String literal: triple-quoted (multiline) or single-line.
if c == "\"" {
let start: Int = i
if i + 2 < count, chars[i + 1] == "\"", chars[i + 2] == "\"" {
i += tripleQuoteDelimiterLength
while i < count {
if chars[i] == "\\" { i = min(i + 2, count); continue }
if chars[i] == "\"", i + 2 < count,
chars[i + 1] == "\"", chars[i + 2] == "\"" {
i += tripleQuoteDelimiterLength
break
}
i += 1
}
} else {
i += 1
while i < count {
if chars[i] == "\\" { i = min(i + 2, count); continue } // escape
if chars[i] == "\"" { i += 1; break }
if chars[i] == "\n" { break } // unterminated
i += 1
}
}
tokens.append(Token(range: makeRange(start, i), kind: .string))
continue
}
// Number literal (must start with a digit here).
if c.isNumber {
let start: Int = i
i += 1
while i < count {
let d: Character = chars[i]
if (d == "e" || d == "E" || d == "p" || d == "P"),
i + 1 < count, chars[i + 1] == "+" || chars[i + 1] == "-" {
i += 2 // signed exponent, e.g. 1e-10
} else if d.isHexDigit || d == "_"
|| d == "x" || d == "X" || d == "o" || d == "O"
|| d == "b" || d == "B" || d == "e" || d == "E"
|| d == "p" || d == "P" {
i += 1
} else if d == ".", i + 1 < count, chars[i + 1].isNumber {
i += 1 // decimal point (not a range/member `.`)
} else {
break
}
}
tokens.append(Token(range: makeRange(start, i), kind: .number))
continue
}
// Attribute: @escaping, @MainActor, …
if c == "@" {
let start: Int = i
i += 1
while i < count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" {
i += 1
}
tokens.append(Token(range: makeRange(start, i), kind: .keyword))
continue
}
// Identifier: keyword, Capitalized type, or plain (no token).
if c.isLetter || c == "_" {
let start: Int = i
i += 1
while i < count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" {
i += 1
}
let word: String = String(chars[start..<i])
if keywords.contains(word) {
tokens.append(Token(range: makeRange(start, i), kind: .keyword))
} else if let first: Character = word.first, first.isUppercase {
tokens.append(Token(range: makeRange(start, i), kind: .type))
}
continue
}
i += 1
}
return tokens
}
}
#endif
@@ -0,0 +1,54 @@
// ScratchSyntaxHighlighter.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile
//
// Paints ``ScratchSwiftTokenizer`` token colors onto an `NSTextStorage`. Split
// out of the SwiftUI `NSViewRepresentable` so the tokenizer→color→storage wiring
// is unit-testable against a plain `NSTextStorage` (no window / view needed).
//
// macOS only.
#if os(macOS)
import AppKit
enum ScratchSyntaxHighlighter {
/// Foreground color for a token kind. `NSColor.system*` are dynamic, so they
/// adapt to the editor's light/dark appearance automatically.
static func color(for kind: ScratchSwiftTokenizer.Kind) -> NSColor {
switch kind {
case .keyword: return .systemPink
case .type: return .systemPurple
case .string: return .systemRed
case .number: return .systemBlue
case .comment: return .systemGreen
}
}
/// Normalize `baseAttributes` (font / paragraph / label color) over the whole
/// storage — so a paste or font change can't leave stray styling — then
/// overlay per-token foreground colors. Attribute-only: the string is not
/// changed, so the caller's selection is preserved.
static func apply(to storage: NSTextStorage, baseAttributes: [NSAttributedString.Key: Any]) {
let full: NSRange = NSRange(location: 0, length: storage.length)
storage.beginEditing()
storage.setAttributes(baseAttributes, range: full)
for token: ScratchSwiftTokenizer.Token in ScratchSwiftTokenizer.tokens(in: storage.string) {
// Ranges come from the same string, but guard against any bounds
// drift before touching the storage.
let end: Int = token.range.location + token.range.length
if token.range.location >= 0, end <= storage.length {
storage.addAttribute(.foregroundColor,
value: color(for: token.kind),
range: token.range)
}
}
storage.endEditing()
}
}
#endif
@@ -0,0 +1,55 @@
// GraphDSLDiagnosticMapperTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdGraphDSLEmbedded
@testable import LyrebirdLiveCompile
@Suite("GraphDSLDiagnosticMapper")
struct GraphDSLDiagnosticMapperTests {
@Test
func parseErrorMapsSpanToLineAndColumn() {
// Offset 4 in "abc\nX" → line 2, column 1 (the char after the newline).
let span: DSLSpan = DSLSpan.point(4)
let error: DSLParseError = DSLParseError(kind: .unexpectedCharacter("%"), span: span)
let diags: [Diagnostic] = GraphDSLDiagnosticMapper.diagnostics(for: error, source: "abc\n%")
#expect(diags.count == 1)
#expect(diags[0].line == 2)
#expect(diags[0].column == 1)
#expect(diags[0].severity == .error)
#expect(diags[0].message.contains("unexpected"))
}
@Test
func firstColumnOfFirstLineIsOneOne() {
let error: DSLParseError = DSLParseError(kind: .unclosedParen, span: DSLSpan.point(0))
let diags: [Diagnostic] = GraphDSLDiagnosticMapper.diagnostics(for: error, source: "OscSin(")
#expect(diags[0].line == 1)
#expect(diags[0].column == 1)
}
@Test
func buildErrorHasNoLine() {
let error: DSLBuildError = DSLBuildError.unknownBuiltin("Nope")
let diags: [Diagnostic] = GraphDSLDiagnosticMapper.diagnostics(for: error, source: "Nope()")
#expect(diags.count == 1)
#expect(diags[0].line == nil)
#expect(diags[0].message.contains("Nope"))
}
@Test
func offsetPastEndClampsToFinalPosition() {
let error: DSLParseError = DSLParseError(kind: .unclosedParen, span: DSLSpan.point(1_000))
let diags: [Diagnostic] = GraphDSLDiagnosticMapper.diagnostics(for: error, source: "ab\ncd")
// Two lines, second is "cd": clamps to line 2, column 3 (past 'd').
#expect(diags[0].line == 2)
#expect(diags[0].column == 3)
}
}
#endif
@@ -86,6 +86,48 @@ struct LiveCompilerTests {
// The resolved path must point at an actual executable on disk.
#expect(FileManager.default.isExecutableFile(atPath: path))
}
// MARK: - Prewarm
/// Module-resolution args pointing at the built Lyrebird modules, mirroring
/// `LiveSession.makeModuleResolutionArgs()`.
private func moduleResolutionArgs() -> [String] {
let importPaths: [URL] = LiveSession.defaultImportPaths()
var args: [String] = []
for path: URL in importPaths {
args += ["-I", path.path]
}
for url: URL in LiveSession.discoverClangModuleMaps(in: importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
return args
}
/// The prewarm type-checks `import LyrebirdSynth` / `import LyrebirdLiveCompile`;
/// with real module-resolution args it must succeed (cold ~2–3 s the first
/// time it builds the `.pcm`). This exercises the mechanism directly, not
/// behind `LiveSession.prewarm()`'s error-swallowing `try?`.
@Test
func prewarmSucceedsWithModuleResolutionArgs() throws {
try LiveCompiler.prewarm(extraSwiftcArgs: moduleResolutionArgs())
}
@Test
func prewarmThrowsWhenModulesUnresolvable() {
// No `-I`: `import LyrebirdSynth` cannot be found → type-check fails.
do {
try LiveCompiler.prewarm(extraSwiftcArgs: [])
Issue.record("expected prewarm to throw with no module paths")
} catch let LiveCompileError.compileFailed(exitCode, stderr) {
#expect(exitCode != 0)
#expect(!stderr.isEmpty)
} catch {
Issue.record("expected LiveCompileError.compileFailed, got \(error)")
}
}
}
#endif
@@ -52,7 +52,7 @@ struct LiveSessionDiagnosticsTests {
@Test
func compilerErrorWrapsUnderlyingForNonCompileFailures() {
// Force a non-compile error by pointing at a build dir that doesn't exist.
// The Phase 142 compile path still succeeds (a swiftc invocation with -I
// The compile path still succeeds (a swiftc invocation with -I
// pointing at a missing dir surfaces as `compileFailed` via swiftc's own
// "no such module" — not `compilerError`). Instead, drive a real
// compilerError case by routing through a LiveCompileError that isn't
@@ -60,7 +60,7 @@ struct LiveSessionDiagnosticsTests {
// entrySymbolMissing — but a real run with full build dir succeeds.
// We just verify the type LiveSessionError.compilerError exists and is
// representable; behavioural coverage of non-compileFailed cases is
// exercised at the LiveCompiler layer (Phase 142 tests).
// exercised at the LiveCompiler layer.
let err: LiveSessionError = LiveSessionError.compilerError(.swiftcNotFound)
#expect(String(describing: err).contains("swiftc"))
}
@@ -0,0 +1,176 @@
// LiveSessionGraphDSLTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdSynth
import LyrebirdGraphDSLEmbedded
@testable import LyrebirdLiveCompile
@MainActor
@Suite("LiveSession graph-DSL")
struct LiveSessionGraphDSLTests {
/// NRT engine — `start()` is never called. The DSL graphs use only
/// oscillators (no `LyrebirdBuffer`), so no engine run cycle is needed and
/// the buffer-teardown race is avoided.
private func makeSession() -> LiveSession {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
return LiveSession(engine: engine)
}
@Test
func anonymousStatementIsTracked() throws {
let session: LiveSession = makeSession()
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
#expect(session.trackedSynthCount == 1)
#expect(session.slotCount == 0)
}
@Test
func multipleAnonymousStatementsEachTrack() throws {
let session: LiveSession = makeSession()
try session.runGraphDSL("OscSin(freq: 440) * 0.1\nOscSawtooth(freq: 55) * 0.2")
#expect(session.trackedSynthCount == 2)
}
@Test
func namedStatementGoesToASlotNotTracked() throws {
let session: LiveSession = makeSession()
try session.runGraphDSL("bass = OscSawtooth(freq: 55) * 0.2")
#expect(session.trackedSynthCount == 0)
#expect(session.slotCount == 1)
#expect(session.slotNames == ["bass"])
}
@Test
func nonAdditiveReRunReplacesAnonymousSynths() throws {
let session: LiveSession = makeSession()
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
try session.runGraphDSL("OscSin(freq: 220) * 0.1")
#expect(session.trackedSynthCount == 1)
}
@Test
func additiveReRunKeepsPriorSynths() throws {
let session: LiveSession = makeSession()
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
try session.runGraphDSL("OscSin(freq: 220) * 0.1", additive: true)
#expect(session.trackedSynthCount == 2)
}
@Test
func namedSlotSurvivesNonAdditiveReRun() throws {
let session: LiveSession = makeSession()
try session.runGraphDSL("bass = OscSawtooth(freq: 55) * 0.2")
// A plain anonymous re-run should not disturb the slot.
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
#expect(session.slotCount == 1)
#expect(session.trackedSynthCount == 1)
}
@Test
func parseErrorThrowsGraphDSLFailedWithLine() {
let session: LiveSession = makeSession()
// `%` starts no token — a lex error on the second line.
#expect {
try session.runGraphDSL("OscSin(freq: 1)\n%%%")
} throws: { error in
guard case LiveSessionError.graphDSLFailed(let diags, _) = error else { return false }
return diags.count == 1 && diags[0].line == 2
}
}
@Test
func buildErrorThrowsGraphDSLFailedWithoutLine() {
let session: LiveSession = makeSession()
#expect {
try session.runGraphDSL("NotAGenerator(freq: 1)")
} throws: { error in
guard case LiveSessionError.graphDSLFailed(let diags, _) = error else { return false }
return diags.count == 1 && diags[0].line == nil
}
}
@Test
func failedEvaluationLeavesPriorGraphUntouched() throws {
let session: LiveSession = makeSession()
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
#expect(session.trackedSynthCount == 1)
// A broken non-additive re-run must NOT clear the playing graph — the
// program is built before any engine mutation.
#expect(throws: LiveSessionError.self) {
try session.runGraphDSL("Nope(freq: 1)")
}
#expect(session.trackedSynthCount == 1)
}
/// Engine whose `pendingQueue` holds only `capacity` (power-of-two) adds
/// before it fills — and it is never processed, so it never drains. Lets a
/// test drive a deterministic mid-run `.pendingQueueFull`.
private func makeSmallQueueSession(capacity: Int) -> LiveSession {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: capacity,
driver: OfflineDriver()
)
return LiveSession(engine: engine)
}
@Test
func engineRejectionIsPerStatementNotAbortAll() {
// A small pending queue fills partway through eight statements. Continue-
// on-error attempts EVERY statement, so `tracked + failed == 8` and more
// than one failed. An abort-on-first-error loop would stop at the first
// rejection, leaving `tracked + failed < 8` and exactly one diagnostic.
let session: LiveSession = makeSmallQueueSession(capacity: 4)
let count: Int = 8
let source: String = (0..<count)
.map { "OscSin(freq: \(100 + $0)) * 0.1" }
.joined(separator: "\n")
var thrownDiags: [Diagnostic] = []
do {
try session.runGraphDSL(source)
Issue.record("expected a pendingQueueFull failure")
} catch let LiveSessionError.graphDSLFailed(diags, _) {
thrownDiags = diags
} catch {
Issue.record("unexpected error: \(error)")
}
#expect(session.trackedSynthCount + thrownDiags.count == count)
#expect(thrownDiags.count >= 2)
#expect(session.trackedSynthCount >= 1)
}
@Test
func resetAllClearsDSLTrackedAndSlots() throws {
let session: LiveSession = makeSession()
try session.runGraphDSL("bass = OscSawtooth(freq: 55) * 0.2\nOscSin(freq: 440) * 0.1")
#expect(session.trackedSynthCount == 1)
#expect(session.slotCount == 1)
session.resetAll()
#expect(session.trackedSynthCount == 0)
#expect(session.slotCount == 0)
}
}
#endif
@@ -74,9 +74,9 @@ struct LiveSessionTests {
#expect(session.lastSnippetMessage == "async hello")
}
/// Phase 203 runtime guard: a snippet driven through `compileAndRunAsync` that calls
/// Runtime guard: a snippet driven through `compileAndRunAsync` that calls
/// `context.play(_:)` actually adds and tracks a synth. `context.play` → `engine.add` is
/// `@MainActor` (Phase 201); `compileAndRunAsync` resumes the snippet entry on the main
/// `@MainActor`; `compileAndRunAsync` resumes the snippet entry on the main
/// actor (not the nonisolated executor it suspends on), so this exercises that hop.
@Test
func asyncCompileAndRunPlaysAndTracksSynth() async throws {
@@ -95,6 +95,158 @@ struct LiveSessionTests {
#expect(session.trackedSynthCount == 1)
}
/// Bare-graph `context.play { … }` — no `SynthesizerBase` subclass — adds
/// and tracks a synth, exercising the `ClosureSynthesizer` forwarder.
@Test
func closurePlayAddsAndTracksBareGraph() async throws {
let engine: SynthesisEngine = makeEngine()
let session: LiveSession = LiveSession(engine: engine)
#expect(session.trackedSynthCount == 0)
_ = try await session.compileAndRunAsync(
"context.play { OscSin.Audio(freq: 440, mul: 0.1) }"
)
#expect(session.trackedSynthCount == 1)
}
// MARK: - Named slots
@Test
func assignSlotReplacesInPlaceKeepingOneVoice() throws {
let session: LiveSession = LiveSession(engine: makeEngine())
let first: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
try session.engine.add(first)
session.assignSlot("bass", synth: first)
#expect(session.slotCount == 1)
#expect(session.slotNames == ["bass"])
// Re-assigning the same name replaces the voice — count stays 1.
let second: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
try session.engine.add(second)
session.assignSlot("bass", synth: second)
#expect(session.slotCount == 1)
// Slots are separate from the anonymous tracked list.
#expect(session.trackedSynthCount == 0)
}
@Test
func clearSlotRemovesNamedSlotOnly() throws {
let session: LiveSession = LiveSession(engine: makeEngine())
let a: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
let b: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
try session.engine.add(a); session.assignSlot("a", synth: a)
try session.engine.add(b); session.assignSlot("b", synth: b)
#expect(session.slotCount == 2)
#expect(session.clearSlot("a") == true)
#expect(session.slotCount == 1)
#expect(session.slotNames == ["b"])
// Clearing an empty slot is a no-op.
#expect(session.clearSlot("missing") == false)
#expect(session.slotCount == 1)
}
@Test
func clearSlotsRemovesAllSlots() throws {
let session: LiveSession = LiveSession(engine: makeEngine())
let a: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
let b: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
try session.engine.add(a); session.assignSlot("a", synth: a)
try session.engine.add(b); session.assignSlot("b", synth: b)
#expect(session.slotCount == 2)
session.clearSlots()
#expect(session.slotCount == 0)
}
@Test
func clearTrackedLeavesSlotsIntact() throws {
// Slots must survive a non-additive re-evaluation (that is the whole
// point) — `clearTracked()` clears only the anonymous list.
let session: LiveSession = LiveSession(engine: makeEngine())
let anon: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
let slotted: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
try session.engine.add(anon); session.track(anon)
try session.engine.add(slotted); session.assignSlot("bass", synth: slotted)
#expect(session.trackedSynthCount == 1)
#expect(session.slotCount == 1)
session.clearTracked()
#expect(session.trackedSynthCount == 0)
#expect(session.slotCount == 1)
}
// MARK: - Swap quantization
@Test
func quantizedSwapSchedulesAndReportsPendingBeat() throws {
let engine: SynthesisEngine = makeEngine()
let session: LiveSession = LiveSession(engine: engine)
session.swapClock = LyrebirdClock(engine: engine, bpm: 120)
session.swapQuantize = .nextBeat
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
#expect(session.slotCount == 1)
// Offline clock sits at beat 0, so the swap targets beat 1 and is pending.
#expect(session.pendingSwapBeat == 1.0)
}
@Test
func immediateSwapReportsNoPendingBeat() throws {
let engine: SynthesisEngine = makeEngine()
let session: LiveSession = LiveSession(engine: engine)
// No clock set → immediate regardless of the quantize mode.
session.swapQuantize = .nextBeat
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
#expect(session.slotCount == 1)
#expect(session.pendingSwapBeat == nil)
}
/// A running engine: two quantized swaps of the same slot must leave exactly
/// one voice in the node tree once the scheduled events have fired.
@Test
func quantizedSwapReplaceEndsWithOneVoiceInTree() throws {
let engine: SynthesisEngine = makeEngine()
try engine.start()
let session: LiveSession = LiveSession(engine: engine)
session.swapClock = LyrebirdClock(engine: engine, bpm: 120)
session.swapQuantize = .nextBeat
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.2 })
#expect(session.slotCount == 1)
// Beat 1 @ 120 bpm / 48 kHz = 24000 samples; 64-sample blocks.
for _: Int in 0..<500 { engine.processBlock(inputSamples: []) }
#expect(engine.synthesizerCount == 1)
}
/// Regression: clearing a slot *before* its scheduled quantized add fires
/// must not orphan the pending voice. The removal is scheduled no earlier
/// than the add, so the add and remove cancel out — the tree ends empty.
@Test
func clearSlotsBeforeScheduledSwapFiresLeavesNoOrphan() throws {
let engine: SynthesisEngine = makeEngine()
try engine.start()
let session: LiveSession = LiveSession(engine: engine)
session.swapClock = LyrebirdClock(engine: engine, bpm: 120)
session.swapQuantize = .nextBeat
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
session.clearSlots()
#expect(session.slotCount == 0)
for _: Int in 0..<500 { engine.processBlock(inputSamples: []) }
#expect(engine.synthesizerCount == 0)
}
/// End-to-end through the real swiftc pipeline: `context.play(slot:) { }`
/// installs one voice, and a non-additive re-run of the same slot replaces
/// it in place (still one voice) — the slot survives the non-additive clear.
@Test
func closureSlotPlayReplacesAcrossReevaluations() async throws {
let session: LiveSession = LiveSession(engine: makeEngine())
_ = try await session.compileAndRunAsync(
"context.play(slot: \"bass\") { OscSin.Audio(freq: 110, mul: 0.1) }"
)
#expect(session.slotCount == 1)
#expect(session.trackedSynthCount == 0)
_ = try await session.compileAndRunAsync(
"context.play(slot: \"bass\") { OscSin.Audio(freq: 220, mul: 0.1) }"
)
#expect(session.slotCount == 1)
}
@Test
func asyncCompileFailureSurfacesDiagnosticsThroughSnippetCompileFailed() async {
let engine: SynthesisEngine = makeEngine()
@@ -122,6 +274,102 @@ struct LiveSessionTests {
#expect(session.trackedSynthCount == 0)
}
@Test
func discoverSPMModuleMapsMatchesTopLevelBuildDirMapsAndDedups() throws {
// Fixture mirroring the `swift build` layout: a C target's generated map
// sits at `<buildDir>/<Target>.build/module.modulemap`, while a Swift
// target's map is one level deeper (`.build/include/module.modulemap`)
// and must NOT be picked up.
let fm: FileManager = FileManager.default
let root: URL = fm.temporaryDirectory
.appendingPathComponent("spm-maps-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: root) }
let cTargetMap: URL = root
.appendingPathComponent("LyrebirdC.build", isDirectory: true)
.appendingPathComponent("module.modulemap")
let swiftTargetMap: URL = root
.appendingPathComponent("LyrebirdSynth.build", isDirectory: true)
.appendingPathComponent("include", isDirectory: true)
.appendingPathComponent("module.modulemap")
let nonBuildMap: URL = root
.appendingPathComponent("Modules", isDirectory: true)
.appendingPathComponent("module.modulemap")
for url: URL in [cTargetMap, swiftTargetMap, nonBuildMap] {
try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try "module X {}".write(to: url, atomically: true, encoding: .utf8)
}
// Pass the same path twice to exercise dedup.
let found: [URL] = LiveSession.discoverSPMModuleMaps(in: [root, root])
#expect(found.count == 1)
// Suffix match, not full-path equality: the temp dir resolves through
// the `/var` → `/private/var` symlink, so `contentsOfDirectory` returns
// a differently-prefixed but equivalent path.
#expect(found.first?.path.hasSuffix("LyrebirdC.build/module.modulemap") == true)
}
// MARK: - Session reset + snippet accounting
@Test
func resetAllClearsTrackedAndSlots() throws {
let session: LiveSession = LiveSession(engine: makeEngine())
let anon: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
let slotted: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
try session.engine.add(anon); session.track(anon)
try session.engine.add(slotted); session.assignSlot("bass", synth: slotted)
#expect(session.trackedSynthCount == 1)
#expect(session.slotCount == 1)
session.resetAll()
#expect(session.trackedSynthCount == 0)
#expect(session.slotCount == 0)
}
@Test
func resetAllClearsPendingSwap() throws {
let engine: SynthesisEngine = makeEngine()
let session: LiveSession = LiveSession(engine: engine)
session.swapClock = LyrebirdClock(engine: engine, bpm: 120)
session.swapQuantize = .nextBeat
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
#expect(session.pendingSwapBeat == 1.0)
session.resetAll()
#expect(session.pendingSwapBeat == nil)
#expect(session.slotCount == 0)
}
@Test
func loadedSnippetCountGrowsPerCompile() async throws {
let session: LiveSession = LiveSession(engine: makeEngine())
#expect(session.loadedSnippetCount == 0)
_ = try await session.compileAndRunAsync("context.reportMessage(\"a\")")
#expect(session.loadedSnippetCount == 1)
_ = try await session.compileAndRunAsync("context.reportMessage(\"b\")")
#expect(session.loadedSnippetCount == 2)
}
// MARK: - Module-cache prewarm
@Test
func prewarmCompletesAndSetsFlag() async {
let session: LiveSession = LiveSession(engine: makeEngine())
#expect(session.isPrewarmed == false)
// Await the detached prewarm task (a real `swiftc -typecheck` that warms
// swiftc's default module cache — cold ~2–3 s the first time).
await session.prewarm().value
#expect(session.isPrewarmed == true)
}
@Test
func prewarmIsIdempotentAfterCompletion() async {
let session: LiveSession = LiveSession(engine: makeEngine())
await session.prewarm().value
#expect(session.isPrewarmed == true)
// A second call is a no-op (already warmed) and returns immediately.
await session.prewarm().value
#expect(session.isPrewarmed == true)
}
@Test
func swiftcArgsIncludeImportLibrarySearchAndRpathFlags() {
let buildDir: URL = URL(fileURLWithPath: "/tmp/fake-build")
@@ -0,0 +1,70 @@
// SnippetCompletionServiceTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import Foundation
import LyrebirdSynth
@testable import LyrebirdLiveCompile
/// Integration tests that spawn the toolchain's real `sourcekit-lsp` and drive
/// it end-to-end. Serialised (`.serialized`) because each launches a server
/// subprocess; kept out of the fast unit path by their inherent latency.
@MainActor
@Suite("SnippetCompletionService", .serialized)
struct SnippetCompletionServiceTests {
private func makeSession() -> LiveSession {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
return LiveSession(engine: engine)
}
/// Member completion after `OscSin.` resolves the generator's nested types —
/// proof that sourcekit-lsp sees `LyrebirdSynth` via the generated
/// `compile_commands.json`.
@Test func completesGeneratorMembers() async throws {
let service: SnippetCompletionService = SnippetCompletionService(session: makeSession())
try await service.start()
defer { service.shutdownSynchronously() }
let body: String = "let x = OscSin."
let items: [LSPCompletionItem] = try await service.completions(
userBody: body, line: 0, character: body.count)
let labels: Set<String> = Set(items.map { $0.label })
#expect(labels.contains("Audio"), "expected OscSin.Audio; got \(labels.sorted())")
#expect(labels.contains("Control"), "expected OscSin.Control; got \(labels.sorted())")
}
/// The injected `context` binding is in scope for the snippet body, so its
/// members (`play`, `engine`, …) complete.
@Test func completesContextMembers() async throws {
let service: SnippetCompletionService = SnippetCompletionService(session: makeSession())
try await service.start()
defer { service.shutdownSynchronously() }
let body: String = "context."
let items: [LSPCompletionItem] = try await service.completions(
userBody: body, line: 0, character: body.count)
let labels: Set<String> = Set(items.map { $0.label })
#expect(labels.contains("engine"), "expected context.engine; got \(labels.sorted())")
#expect(labels.contains { $0.hasPrefix("play") },
"expected a context.play member; got \(labels.sorted())")
}
}
#endif
@@ -0,0 +1,68 @@
// SourceKitLSPClientTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import Foundation
@testable import LyrebirdLiveCompile
@Suite("SourceKitLSPClient")
struct SourceKitLSPClientTests {
/// A server that never answers must make a request FAIL (`timedOut`) within
/// the timeout — not hang. Uses `/bin/sleep` as a stand-in process that stays
/// alive but speaks no LSP, so the `initialize` request in `start()` times
/// out. Regression guard for the task-group/continuation deadlock where a
/// dropped-but-not-resumed continuation left `request(...)` awaiting forever.
@Test func requestTimesOutOnUnresponsiveServer() async {
let client: SourceKitLSPClient = SourceKitLSPClient(
executableURL: URL(fileURLWithPath: "/bin/sleep"),
arguments: ["3600"],
requestTimeout: 0.5
)
let start: Date = Date()
await #expect(throws: SourceKitLSPError.self) {
try await client.start(rootURI: "file:///tmp")
}
let elapsed: TimeInterval = Date().timeIntervalSince(start)
// Must resolve near the 0.5 s timeout, not hang (the old bug never returned).
#expect(elapsed < 5.0, "start() took \(elapsed)s — expected a prompt timeout")
client.shutdown()
}
/// A server that launches then exits immediately (EOF on stdout) must fail
/// an in-flight request promptly rather than hang the full timeout — the
/// reader marks the client not-running and fails pending requests on EOF.
/// `/usr/bin/true` exits 0 at once.
@Test func serverExitFailsRequestPromptly() async {
let client: SourceKitLSPClient = SourceKitLSPClient(
executableURL: URL(fileURLWithPath: "/usr/bin/true"),
requestTimeout: 10.0
)
let start: Date = Date()
await #expect(throws: SourceKitLSPError.self) {
try await client.start(rootURI: "file:///tmp")
}
let elapsed: TimeInterval = Date().timeIntervalSince(start)
#expect(elapsed < 5.0, "server-exit took \(elapsed)s — expected a prompt failure, not a timeout")
client.shutdown()
}
/// Launching a non-existent executable surfaces `.launchFailed` rather than
/// crashing or hanging.
@Test func launchFailureIsReported() async {
let client: SourceKitLSPClient = SourceKitLSPClient(
executableURL: URL(fileURLWithPath: "/nonexistent/sourcekit-lsp-xyz"),
requestTimeout: 0.5
)
await #expect(throws: SourceKitLSPError.self) {
try await client.start(rootURI: "file:///tmp")
}
client.shutdown()
}
}
#endif
@@ -0,0 +1,51 @@
// SwapQuantizeTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@MainActor
@Suite("SwapQuantize")
struct SwapQuantizeTests {
/// Offline engine that never processes a block, so `clock.currentBeat`
/// stays at 0 — target beats are then deterministic.
private func makeClock(bpm: Double = 120) -> LyrebirdClock {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
return LyrebirdClock(engine: engine, bpm: bpm)
}
@Test func immediateHasNoTargetBeat() {
#expect(SwapQuantize.immediate.targetBeat(clock: makeClock()) == nil)
}
@Test func nextBeatTargetsUpcomingWholeBeat() {
#expect(SwapQuantize.nextBeat.targetBeat(clock: makeClock()) == 1.0)
}
@Test func nextBarTargetsUpcomingBarBoundary() {
#expect(SwapQuantize.nextBar(beatsPerBar: 4).targetBeat(clock: makeClock()) == 4.0)
}
@Test func nextBarClampsNonPositiveBeatsPerBar() {
// beatsPerBar <= 0 clamps to 1, behaving like `.nextBeat`.
#expect(SwapQuantize.nextBar(beatsPerBar: 0).targetBeat(clock: makeClock()) == 1.0)
}
}
#endif
@@ -0,0 +1,53 @@
// EditorPositionMappingTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
@testable import LyrebirdLiveCompileUI
@Suite("editorLineAndUTF16Char")
struct EditorPositionMappingTests {
@Test func offsetZeroIsOrigin() {
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "abc\ndef", utf16Offset: 0)
#expect(line == 0)
#expect(char == 0)
}
@Test func withinFirstLineCountsColumns() {
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "let x = OscSin.", utf16Offset: 15)
#expect(line == 0)
#expect(char == 15)
}
@Test func afterNewlineResetsColumn() {
// "abc\nde" — offset 5 is the 'e' on line 1, column 2.
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "abc\nde", utf16Offset: 5)
#expect(line == 1)
#expect(char == 1)
}
@Test func startOfSecondLineIsColumnZero() {
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "ab\ncd", utf16Offset: 3)
#expect(line == 1)
#expect(char == 0)
}
@Test func offsetPastEndClampsToFinalPosition() {
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "ab\ncd", utf16Offset: 999)
#expect(line == 1)
#expect(char == 2)
}
@Test func astralCharacterCountsAsTwoUTF16Units() {
// "😀x" — the emoji is a surrogate pair (2 UTF-16 units); 'x' is at char 2.
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "😀x", utf16Offset: 2)
#expect(line == 0)
#expect(char == 2)
}
}
#endif
@@ -72,8 +72,8 @@ struct LyrebirdScratchModelTests {
func runInvalidSnippetSurfacesUserCoordinateDiagnostics() async throws {
let session: LiveSession = makeSession()
// `let x: Int = "nope"` — guaranteed type-check error on the first row
// of the user body. Phase 144 maps the wrapped-source line back to
// user line 1.
// of the user body. The diagnostic parser maps the wrapped-source line
// back to user line 1.
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "let x: Int = \"nope\"\n"
@@ -95,7 +95,7 @@ struct LyrebirdScratchModelTests {
await model.run(additive: false)
model.clearTracked()
#expect(model.trackedSynthCount == 0)
#expect(model.statusMessage == "Cleared tracked synths.")
#expect(model.statusMessage == "Cleared all synths (tracked + slots).")
}
@Test
@@ -166,6 +166,151 @@ struct LyrebirdScratchModelTests {
#expect(model.text == original)
#expect(model.documentURL == nil)
}
// MARK: - Re-eval readiness signal
@Test
func blankInitialTextIsEmptyState() {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: " \n\t")
#expect(model.reevalState == .empty)
#expect(model.reevalState.canEvaluate == false)
}
@Test
func nonBlankInitialTextIsDirtyState() {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "// hi")
#expect(model.reevalState == .dirty)
#expect(model.reevalState.canEvaluate == true)
}
@Test
func editingBlankToContentGoesDirty() {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "")
#expect(model.reevalState == .empty)
model.text = "context.reportMessage(\"x\")"
#expect(model.reevalState == .dirty)
}
// A successful run drives the buffer `.dirty` → `.compiling` → `.clean`.
// (`LiveSession.discoverSPMModuleMaps` makes the snippet compile under a
// bare `swift test`, so a valid snippet reliably succeeds here.)
@Test
func runSettlesToCleanOnSuccess() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "context.reportMessage(\"x\")"
)
#expect(model.reevalState == .dirty)
let ok: Bool = await model.run(additive: false)
#expect(ok)
#expect(model.reevalState == .clean)
}
@Test
func editingAfterCleanReturnsToDirty() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "context.reportMessage(\"x\")"
)
let ok: Bool = await model.run(additive: false)
#expect(ok)
#expect(model.reevalState == .clean)
model.text = "context.reportMessage(\"y\")"
#expect(model.reevalState == .dirty)
}
@Test
func failedRunEntersFailedWithDiagnosticCount() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "let x: Int = \"nope\"\n"
)
await model.run(additive: false)
#expect(model.reevalState == .failed(diagnosticCount: model.diagnostics.count))
#expect(model.diagnostics.isEmpty == false)
}
@Test
func clearTrackedDropsBaselineToDirty() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "context.reportMessage(\"x\")"
)
let ok: Bool = await model.run(additive: false)
#expect(ok)
#expect(model.reevalState == .clean)
model.clearTracked()
// Nothing the buffer produced is still playing → a re-run is meaningful.
#expect(model.reevalState == .dirty)
}
@Test
func quantizedRunEntersQueuedThenSettles() async throws {
let session: LiveSession = makeSession()
session.swapClock = LyrebirdClock(engine: session.engine, bpm: 120)
session.swapQuantize = .nextBeat
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "context.play(slot: \"bass\") { OscSin.Audio(freq: 110, mul: 0.1) }"
)
let ok: Bool = await model.run(additive: false)
#expect(ok)
// Compiled + scheduled: queued until beat 1 (offline clock sits at 0).
if case .queued(let beat) = model.reevalState {
#expect(beat == 1.0)
} else {
Issue.record("expected .queued, got \(model.reevalState)")
}
// Still pending → refresh is a no-op.
model.refreshQueuedState()
if case .queued = model.reevalState {} else {
Issue.record("expected still .queued")
}
// Once the swap is no longer pending (here: clock dropped), it settles
// to .clean since the buffer is unchanged.
session.swapClock = nil
model.refreshQueuedState()
#expect(model.reevalState == .clean)
}
@Test
func clearTrackedFullResetAlsoClearsSlots() throws {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "// x")
let slotted: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
try session.engine.add(slotted)
session.assignSlot("bass", synth: slotted)
#expect(session.slotCount == 1)
// The model's "Clear Synths" is a full reset — tracked + slots.
model.clearTracked()
#expect(session.slotCount == 0)
}
@Test
func loadEntersDirtyEvenIfContentMatchesPriorRun() async throws {
let session: LiveSession = makeSession()
let source: String = "context.reportMessage(\"x\")"
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: source)
let ok: Bool = await model.run(additive: false)
#expect(ok)
#expect(model.reevalState == .clean)
// Load the *same* source from disk: the run baseline is dropped, so it
// reads as dirty rather than clean.
let url: URL = FileManager.default
.temporaryDirectory
.appendingPathComponent("scratch_\(UUID().uuidString).swift")
defer { try? FileManager.default.removeItem(at: url) }
try source.write(to: url, atomically: true, encoding: .utf8)
try model.load(from: url)
#expect(model.reevalState == .dirty)
}
}
#endif
@@ -0,0 +1,36 @@
// ReevalStateTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
@testable import LyrebirdLiveCompileUI
@Suite("ReevalState")
struct ReevalStateTests {
@Test
func canEvaluateFalseWhenEmptyOrCompiling() {
#expect(ReevalState.empty.canEvaluate == false)
#expect(ReevalState.compiling.canEvaluate == false)
}
@Test
func canEvaluateTrueWhenRunnable() {
#expect(ReevalState.dirty.canEvaluate == true)
#expect(ReevalState.clean.canEvaluate == true)
#expect(ReevalState.queued(untilBeat: 4.0).canEvaluate == true)
#expect(ReevalState.failed(diagnosticCount: 0).canEvaluate == true)
#expect(ReevalState.failed(diagnosticCount: 3).canEvaluate == true)
}
@Test
func failedCarriesDiagnosticCount() {
#expect(ReevalState.failed(diagnosticCount: 2) == .failed(diagnosticCount: 2))
#expect(ReevalState.failed(diagnosticCount: 2) != .failed(diagnosticCount: 5))
}
}
#endif
@@ -0,0 +1,51 @@
// ScratchModelCompletionTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@testable import LyrebirdLiveCompileUI
/// Integration: `LyrebirdScratchModel.completionItems` end-to-end through the
/// real `sourcekit-lsp`. Serialized (each launches a server).
@Suite("LyrebirdScratchModel completion", .serialized)
@MainActor
struct ScratchModelCompletionTests {
private func makeModel(text: String) -> LyrebirdScratchModel {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text)
}
@Test func swiftModeCompletesGeneratorMembers() async {
let model: LyrebirdScratchModel = makeModel(text: "let x = OscSin.")
let items: [LSPCompletionItem] = await model.completionItems(line: 0, character: 15)
let labels: Set<String> = Set(items.map { $0.label })
#expect(labels.contains("Audio"))
#expect(labels.contains("Control"))
}
@Test func graphDSLModeReturnsNoCompletions() async {
let model: LyrebirdScratchModel = makeModel(text: "OscSin.")
model.switchMode(to: .graphDSL)
// DSL mode needs no swiftc/LSP; completion is a no-op (and no server spawns).
let items: [LSPCompletionItem] = await model.completionItems(line: 0, character: 7)
#expect(items.isEmpty)
}
}
#endif
@@ -0,0 +1,47 @@
// ScratchModelEngineTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@testable import LyrebirdLiveCompileUI
@Suite("LyrebirdScratchModel engine toggle")
@MainActor
struct ScratchModelEngineTests {
private func makeModel() -> LyrebirdScratchModel {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
return LyrebirdScratchModel(session: LiveSession(engine: engine))
}
@Test func toggleStartsThenStopsEngine() throws {
let model: LyrebirdScratchModel = makeModel()
let engine: SynthesisEngine = model.session.engine
#expect(engine.isRunning == false)
model.toggleEngine()
#expect(engine.isRunning)
#expect(model.statusMessage == "Engine started.")
model.toggleEngine()
#expect(engine.isRunning == false)
#expect(model.statusMessage == "Engine stopped.")
}
}
#endif
@@ -0,0 +1,153 @@
// ScratchModelGraphDSLTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@testable import LyrebirdLiveCompileUI
@Suite("LyrebirdScratchModel graph-DSL mode")
@MainActor
struct ScratchModelGraphDSLTests {
private func makeSession() -> LiveSession {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
return LiveSession(engine: engine)
}
@Test
func defaultsToSwiftMode() {
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: makeSession())
#expect(model.evalMode == .swift)
}
@Test
func graphDSLPlaceholderIsGraphOnly() {
let placeholder: String = LyrebirdScratchModel.graphDSLPlaceholder
#expect(placeholder.contains("OscSin.Audio"))
// No `context` API in the DSL surface.
#expect(!placeholder.contains("context"))
}
@Test
func switchModeSwapsUntouchedPlaceholder() {
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: makeSession())
// Buffer still holds the untouched Swift placeholder.
model.switchMode(to: .graphDSL)
#expect(model.evalMode == .graphDSL)
#expect(model.text == LyrebirdScratchModel.graphDSLPlaceholder)
}
@Test
func switchModePreservesEditedBuffer() {
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: makeSession(),
initialText: "OscSin(freq: 440) * 0.1"
)
model.switchMode(to: .graphDSL)
#expect(model.evalMode == .graphDSL)
#expect(model.text == "OscSin(freq: 440) * 0.1")
}
@Test
func switchModeToSameModeIsNoOp() {
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: makeSession())
let before: String = model.text
model.switchMode(to: .swift)
#expect(model.text == before)
}
@Test
func switchModeClearsStaleDiagnostics() async {
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: makeSession(),
initialText: "NotAGenerator(freq: 1)"
)
model.switchMode(to: .graphDSL)
_ = await model.run(additive: false)
#expect(!model.diagnostics.isEmpty)
// Switching modes must not leave the old run's gutter markers behind.
model.switchMode(to: .swift)
#expect(model.diagnostics.isEmpty)
}
@Test
func switchModeDropsRunBaselineSoBufferReadsDirty() async {
// A buffer that matches the last Swift run must NOT read as `.clean`
// after switching to the DSL evaluator, which never ran it.
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: makeSession(),
initialText: "OscSin(freq: 440) * 0.1"
)
model.switchMode(to: .graphDSL)
_ = await model.run(additive: false)
#expect(model.reevalState == .clean)
// Back to Swift with the same text: the Swift evaluator hasn't run it.
model.switchMode(to: .swift)
#expect(model.reevalState == .dirty)
}
@Test
func runValidGraphDSLReachesCleanAndTracks() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "OscSin(freq: 440) * 0.1"
)
model.switchMode(to: .graphDSL)
let ok: Bool = await model.run(additive: false)
#expect(ok)
#expect(model.reevalState == .clean)
#expect(model.trackedSynthCount == 1)
#expect(model.diagnostics.isEmpty)
}
@Test
func runBrokenGraphDSLFailsWithDiagnostics() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "NotAGenerator(freq: 1)"
)
model.switchMode(to: .graphDSL)
let ok: Bool = await model.run(additive: false)
#expect(!ok)
#expect(!model.diagnostics.isEmpty)
if case .failed = model.reevalState {} else {
Issue.record("expected .failed, got \(model.reevalState)")
}
}
@Test
func brokenReRunKeepsPriorGraphPlaying() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "OscSin(freq: 440) * 0.1"
)
model.switchMode(to: .graphDSL)
_ = await model.run(additive: false)
#expect(model.trackedSynthCount == 1)
model.text = "Nope(freq: 1)"
let ok: Bool = await model.run(additive: false)
#expect(!ok)
// The prior graph is untouched — a bad edit never drops audio.
#expect(model.trackedSynthCount == 1)
}
}
#endif
@@ -0,0 +1,68 @@
// ScratchModelMemoryTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@testable import LyrebirdLiveCompileUI
@Suite("LyrebirdScratchModel snippet memory")
@MainActor
struct ScratchModelMemoryTests {
private func makeModel() -> LyrebirdScratchModel {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
return LyrebirdScratchModel(session: LiveSession(engine: engine))
}
@Test func freshModelMirrorsZeroMappedSnippets() {
let model: LyrebirdScratchModel = makeModel()
#expect(model.loadedSnippetCount == 0)
#expect(model.snippetMemoryHint == nil)
}
@Test func hintIsNilBelowThreshold() {
let below: Int = LyrebirdScratchModel.snippetRestartThreshold - 1
#expect(LyrebirdScratchModel.snippetMemoryHint(count: 0) == nil)
#expect(LyrebirdScratchModel.snippetMemoryHint(count: below) == nil)
}
@Test func hintAppearsAtAndAboveThreshold() {
let at: Int = LyrebirdScratchModel.snippetRestartThreshold
let atHint: String? = LyrebirdScratchModel.snippetMemoryHint(count: at)
#expect(atHint != nil)
#expect(atHint?.contains("\(at)") == true)
#expect(LyrebirdScratchModel.snippetMemoryHint(count: at + 100) != nil)
}
@Test func clearTrackedRefreshesSnippetMirror() {
// resetAll (behind clearTracked) does not reclaim dylibs, so the mirror
// stays in sync with the session — 0 on a fresh session.
let model: LyrebirdScratchModel = makeModel()
model.clearTracked()
#expect(model.loadedSnippetCount == 0)
}
@Test func hintMentionsRestartAndDSLAlternative() {
let hint: String = LyrebirdScratchModel.snippetMemoryHint(
count: LyrebirdScratchModel.snippetRestartThreshold) ?? ""
#expect(hint.lowercased().contains("restart"))
#expect(hint.contains("Graph DSL"))
}
}
#endif
@@ -0,0 +1,101 @@
// ScratchSwiftTokenizerTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import Foundation
@testable import LyrebirdLiveCompileUI
@Suite("ScratchSwiftTokenizer")
struct ScratchSwiftTokenizerTests {
/// The token kind covering the first occurrence of `substring`, or `nil` if
/// no token exactly covers it. Verifies the range maps back to `substring`.
private func kind(of substring: String, in source: String) -> ScratchSwiftTokenizer.Kind? {
let ns: NSString = source as NSString
let target: NSRange = ns.range(of: substring)
for token: ScratchSwiftTokenizer.Token in ScratchSwiftTokenizer.tokens(in: source) {
if NSEqualRanges(token.range, target) { return token.kind }
}
return nil
}
@Test func keywordsAndTypesAndPlainIdentifiers() {
let src: String = "let osc = OscSin.Audio(freq: 440)"
#expect(kind(of: "let", in: src) == .keyword)
#expect(kind(of: "OscSin", in: src) == .type)
// Lowercase identifiers produce no token.
#expect(kind(of: "osc", in: src) == nil)
#expect(kind(of: "freq", in: src) == nil)
}
@Test func numbers() {
#expect(kind(of: "440", in: "freq: 440") == .number)
#expect(kind(of: "0.15", in: "mul: 0.15") == .number)
#expect(kind(of: "0xFF", in: "let x = 0xFF") == .number)
}
@Test func numberDoesNotEatRangeOperator() {
// `1...5` must not be swallowed into one number token — the `.` is only
// consumed when followed by a digit.
let src: String = "for i in 1...5 {}"
#expect(kind(of: "1", in: src) == .number)
#expect(kind(of: "5", in: src) == .number)
}
@Test func strings() {
#expect(kind(of: "\"hello\"", in: "reportMessage(\"hello\")") == .string)
// Escaped quote stays inside the string.
let esc: String = "let s = \"a\\\"b\""
#expect(kind(of: "\"a\\\"b\"", in: esc) == .string)
}
@Test func lineAndBlockComments() {
#expect(kind(of: "// hello", in: "let x = 1 // hello") == .comment)
// Nested block comment closes at the outer `*/`.
let nested: String = "/* a /* b */ c */"
#expect(kind(of: nested, in: nested) == .comment)
}
@Test func attributesColorAsKeyword() {
#expect(kind(of: "@MainActor", in: "@MainActor func f() {}") == .keyword)
}
@Test func utf16RangesSurviveMultiUnitCharacters() {
// An emoji (2 UTF-16 units) before a keyword: the keyword's NSRange must
// still line up with the NSString substring.
let src: String = "// 🎹\nlet x = 1"
#expect(kind(of: "let", in: src) == .keyword)
#expect(kind(of: "1", in: src) == .number)
}
@Test func emptyStringProducesNoTokens() {
#expect(ScratchSwiftTokenizer.tokens(in: "").isEmpty)
}
// Regression: a lone trailing backslash inside an unterminated string used to
// overrun the UTF-16 offset table and trap. Tokenizing must not crash, for
// both single-line and triple-quoted strings.
@Test func trailingBackslashAtEndOfBufferDoesNotCrash() {
_ = ScratchSwiftTokenizer.tokens(in: "\"\\") // opening " then \
_ = ScratchSwiftTokenizer.tokens(in: "\"\"\"\\") // triple-open then \
_ = ScratchSwiftTokenizer.tokens(in: "let s = \"abc\\") // realistic edit
// A backslash as the very last character overall.
_ = ScratchSwiftTokenizer.tokens(in: "\\")
}
@Test func signedExponentIsOneNumberToken() {
#expect(kind(of: "1e-10", in: "let x = 1e-10") == .number)
#expect(kind(of: "2.5E+3", in: "let y = 2.5E+3") == .number)
}
@Test func concurrencyKeywords() {
#expect(kind(of: "actor", in: "actor A {}") == .keyword)
#expect(kind(of: "nonisolated", in: "nonisolated func f() {}") == .keyword)
}
}
#endif
@@ -0,0 +1,54 @@
// ScratchSyntaxHighlighterTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import AppKit
@testable import LyrebirdLiveCompileUI
@Suite("ScratchSyntaxHighlighter")
@MainActor
struct ScratchSyntaxHighlighterTests {
private func color(_ storage: NSTextStorage, at index: Int) -> NSColor? {
storage.attribute(.foregroundColor, at: index, effectiveRange: nil) as? NSColor
}
@Test func paintsTokenColorsOntoStorage() {
let source: String = "let x = 1 // note"
let storage: NSTextStorage = NSTextStorage(string: source)
let base: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor.labelColor]
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
let ns: NSString = source as NSString
// Keyword, number, comment each get their kind's color.
#expect(color(storage, at: ns.range(of: "let").location)
== ScratchSyntaxHighlighter.color(for: .keyword))
#expect(color(storage, at: ns.range(of: "1").location)
== ScratchSyntaxHighlighter.color(for: .number))
#expect(color(storage, at: ns.range(of: "// note").location)
== ScratchSyntaxHighlighter.color(for: .comment))
// A plain identifier keeps the base color.
#expect(color(storage, at: ns.range(of: "x").location) == NSColor.labelColor)
}
@Test func reapplyNormalizesAwayStaleColors() {
// Edit the source so a previously-colored keyword becomes a plain
// identifier; re-applying must reset it to the base color, not leave the
// old keyword color behind.
let storage: NSTextStorage = NSTextStorage(string: "let value = 1")
let base: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor.labelColor]
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
// "let" -> "lot" (no longer a keyword).
let ns0: NSString = "let value = 1" as NSString
storage.replaceCharacters(in: ns0.range(of: "let"), with: "lot")
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
let ns1: NSString = storage.string as NSString
#expect(color(storage, at: ns1.range(of: "lot").location) == NSColor.labelColor)
}
}
#endif
@@ -0,0 +1,51 @@
// ScratchTextViewTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import AppKit
@testable import LyrebirdLiveCompileUI
@Suite("ScratchTextView.rangeForUserCompletion")
@MainActor
struct ScratchTextViewTests {
private func makeTextView(_ text: String, caret: Int) -> ScratchTextView {
let tv: ScratchTextView = ScratchTextView(frame: .zero)
tv.string = text
tv.setSelectedRange(NSRange(location: caret, length: 0))
return tv
}
/// Right after a `.`, the completion range is EMPTY at the caret — so a
/// member completion inserts after the dot instead of replacing the
/// receiver expression (the `context.` → erases `context` bug).
@Test func afterDotRangeIsEmptyAtCaret() {
let tv: ScratchTextView = makeTextView("context.", caret: 8)
let range: NSRange = tv.rangeForUserCompletion
#expect(range == NSRange(location: 8, length: 0))
}
/// A dotted member expression: completing after the second dot must not
/// reach back over `context.engine`.
@Test func afterNestedDotRangeIsEmptyAtCaret() {
let text: String = "context.engine."
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
let range: NSRange = tv.rangeForUserCompletion
#expect(range == NSRange(location: text.utf16.count, length: 0))
}
/// Mid-identifier (no preceding dot) falls through to the default behavior,
/// which covers the whole partial word so it gets replaced on completion.
@Test func partialIdentifierUsesDefaultWordRange() {
let tv: ScratchTextView = makeTextView("OscSi", caret: 5)
let range: NSRange = tv.rangeForUserCompletion
// Default range spans the partial word `OscSi` (length 5 from offset 0).
#expect(range == NSRange(location: 0, length: 5))
}
}
#endif
+6
View File
@@ -1,6 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Demos/LyrebirdQuickstartDemo/LyrebirdQuickstartDemo.xcodeproj">
</FileRef>
<FileRef
location = "group:Demos/LyrebirdDemo/LyrebirdDemo.xcodeproj">
</FileRef>
@@ -19,4 +22,7 @@
<FileRef
location = "group:Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj">
</FileRef>
<FileRef
location = "group:Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj">
</FileRef>
</Workspace>
+25 -2
View File
@@ -22,6 +22,7 @@ let package = Package(
// never reference this product — they use `Lyrebird` (static) above.
.library(name: "LyrebirdDynamic", type: .dynamic, targets: ["LyrebirdSynth"]),
.library(name: "LyrebirdUI", targets: ["LyrebirdUI"]),
.library(name: "LyrebirdGraphDSL", targets: ["LyrebirdGraphDSL"]),
.executable(name: "LyrebirdCLI", targets: ["LyrebirdCLI"]),
],
dependencies: [
@@ -41,8 +42,8 @@ let package = Package(
// swift-docc-plugin — command plugin that drives DocC documentation builds.
// Registers two commands available to all targets in this package:
// • In Xcode: Product ▸ Build Documentation (or scheme-level build action)
// • From CLI: swift package generate-documentation --target Lyrebird
// swift package preview-documentation --target Lyrebird
// • From CLI: swift package generate-documentation --target LyrebirdSynth
// swift package preview-documentation --target LyrebirdSynth
// No target-level plugins: entry is needed — command plugins apply package-wide.
.package(
url: "https://github.com/apple/swift-docc-plugin",
@@ -110,6 +111,16 @@ let package = Package(
path: "Sources/LyrebirdBenchmark",
swiftSettings: [.unsafeFlags(["-O"])]
),
// Interpreted graph-DSL. Pure Swift over core `LyrebirdSynth` types —
// no swiftc, no AppKit — so it is cross-platform (iOS included). The
// `DSLBuiltin` registry it consumes is emitted by the separate
// `DSLRegistryGen` code-gen tool (the only thing that depends on
// swift-syntax); this shipped target does not.
.target(
name: "LyrebirdGraphDSL",
dependencies: ["LyrebirdSynth"],
path: "Sources/LyrebirdGraphDSL"
),
.testTarget(
name: "LyrebirdTests",
dependencies: ["LyrebirdSynth"],
@@ -127,6 +138,18 @@ let package = Package(
],
path: "Tests/LyrebirdUITests"
),
.testTarget(
name: "LyrebirdGraphDSLTests",
dependencies: [
"LyrebirdGraphDSL",
"LyrebirdSynth",
],
path: "Tests/LyrebirdGraphDSLTests",
linkerSettings: [
.linkedFramework("AudioToolbox"),
.linkedFramework("Accelerate"),
]
),
.testTarget(
name: "LyrebirdCLITests",
dependencies: ["LyrebirdCLI"],
+23 -8
View File
@@ -120,7 +120,7 @@ The REPL is text-only and works from any project that depends on Lyrebird; the s
## New here?
**Read [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md)** — it covers the six demo projects, how to open the workspace, where to add synthesizers, and the gotchas that will bite you.
**Read [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md)** — it covers the eight demo projects, how to open the workspace, where to add synthesizers, and the gotchas that will bite you.
---
@@ -151,7 +151,7 @@ Full walk-through (SPM manifest form, local-path dev dependency, per-template de
## Opening in Xcode
For the demo projects, open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj`. The workspace links all six demos to the local Lyrebird package.
For the demo projects, open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj`. The workspace links all eight demos to the local Lyrebird package.
For the package itself:
@@ -161,16 +161,18 @@ xed . # opens Package.swift — Xcode auto-generates schemes for every target
### Schemes
Workspace scheme selector exposes eight entries:
Workspace scheme selector exposes ten entries:
| Scheme | Purpose | Platform |
|---|---|---|
| `Lyrebird-Package` | Umbrella — builds Lyrebird + LyrebirdUI + LyrebirdLiveCompile + LyrebirdC + LyrebirdBenchmark + LyrebirdCLI, runs the test suites, launches/profiles `LyrebirdCLI` | macOS |
| `LyrebirdQuickstartDemo` | CLI — fastest sound: a one-oscillator `SineTone` that plays 440 Hz for 10 s and exits | macOS |
| `LyrebirdUI` | Builds the `LyrebirdUI` module only (SwiftUI parameter controls + visualisations) | macOS |
| `LyrebirdDemo` | CLI — plays through default output via `CoreAudioDriver` | macOS |
| `LyrebirdMacOSDemo` | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS |
| `LyrebirdiOSDemo` | SwiftUI app — same UI via `iOSAudioDriver` (RemoteIO) | iOS |
| `LyrebirdNRTDemo` | CLI — offline render to CAF via `NRTDriver` | macOS |
| `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders to CAF via `NRTDriver` | macOS |
| `LyrebirdAUv3Demo` | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro, etc. Run the host app once to register the extension. | macOS |
| `LyrebirdScratchDemo` | Live-coding scratchpad — type Swift snippets, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
@@ -192,7 +194,7 @@ Use `Lyrebird-Package` for day-to-day development of the engine and tests.
```bash
swift build # build all targets
swift test # run all 3544 tests
swift test # run all 5481 tests
swift test --filter LyrebirdTests # run one suite
swift run lyrebird # run the CLI
swift run lyrebird repl # Swift REPL with Lyrebird available
@@ -203,14 +205,16 @@ swift run LyrebirdDemo # run the hardware smoke-test demo
## Demo projects
All six live in [`Demos/`](Demos/). Open via `Lyrebird.xcworkspace`.
All eight live in [`Demos/`](Demos/). Open via `Lyrebird.xcworkspace`.
| Demo | What it does | Platform |
|---|---|---|
| [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | CLI — fastest sound: a one-oscillator `SineTone` plays 440 Hz for 10 s, then exits (mirrors the `quickstart` template) | macOS |
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | CLI — plays through default output via `CoreAudioDriver` | macOS |
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS |
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | SwiftUI app — same UI system via `iOSAudioDriver` (RemoteIO) | iOS |
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render to CAF file via `NRTDriver` | macOS |
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | CLI — notated `Score` → MusicXML export + offline render to CAF via `NRTDriver` | macOS |
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro | macOS |
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
@@ -231,8 +235,10 @@ lyrebird --help # verify
Then:
```bash
lyrebird new MyPiece --template ui-demo # scaffold a standalone project
open MyPiece/MyPiece.xcworkspace # open in Xcode (workspace refs Package.swift)
lyrebird new MyFirstSound --template quickstart # fastest path to sound (plays 10 s, then exits)
cd MyFirstSound && lyrebird run # hear it
lyrebird new MyPiece --template ui-demo # a richer standalone project
open MyPiece/MyPiece.xcworkspace # open in Xcode (workspace refs Package.swift)
lyrebird # enter the lyrebird> interactive shell
lyrebird repl # Swift REPL with Lyrebird importable
lyrebird --version
@@ -269,14 +275,16 @@ LyrebirdII/
│ ├── LyrebirdCLI/ # lyrebird CLI binary
│ └── LyrebirdDemo/ # macOS CLI hardware smoke-test
├── Demos/
│ ├── LyrebirdQuickstartDemo/ # fastest sound — SineTone plays 10 s then exits
│ ├── LyrebirdDemo/ # (same as Sources/LyrebirdDemo — workspace target)
│ ├── LyrebirdMacOSDemo/ # macOS SwiftUI app
│ ├── LyrebirdiOSDemo/ # iOS SwiftUI app
│ ├── LyrebirdNRTDemo/ # offline renderer
│ ├── LyrebirdScoreDemo/ # notated Score → MusicXML + offline render
│ ├── LyrebirdAUv3Demo/ # AUv3 `aumu` plugin reference (LyrebirdFM)
│ └── LyrebirdScratchDemo/ # live-coding scratchpad (macOS, no sandbox)
├── Tests/
│ ├── LyrebirdTests/ # 3544 engine + generator tests
│ ├── LyrebirdTests/ # 5253 engine + generator tests
│ ├── LyrebirdUITests/ # SwiftUI component tests
│ └── LyrebirdCLITests/ # CLI tests
└── docs/
@@ -329,6 +337,7 @@ swift package --disable-sandbox preview-documentation --target Lyrebird
| Topic | Doc |
|---|---|
| **Start here / demo projects** | [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) |
| **What's new / release notes** | [`RELEASES.md`](RELEASES.md) |
| Engine setup and Core Audio | `docs/engine/synthesis-engine.md` |
| Bus memory / In / Out | `docs/engine/bus-system.md` |
| Sample-accurate scheduling | `docs/engine/scheduling.md` |
@@ -359,6 +368,12 @@ swift package --disable-sandbox preview-documentation --target Lyrebird
---
## Release notes
Per-version changes are in [`RELEASES.md`](RELEASES.md). The current release
(1.1) adds the algorithmic-composition stack: a music-theory toolkit, pattern
library, score DSL, and MusicXML / MIDI round-trips.
## Contributing
New Generators (in-tree) and out-of-tree extension packages are both welcome — see [`CONTRIBUTING.md`](CONTRIBUTING.md).
+390
View File
@@ -0,0 +1,390 @@
# Releases
Notable changes per release. Newest first.
This project follows semantic versioning: a minor bump (1.0 → 1.1) adds
functionality in a backward-compatible way.
---
## 1.4.0 — Live-coding scratch editor, interpreted Graph DSL, `ClosureSynthesizer` + `SampleLoop`
A minor release. Fully backward-compatible — no changes to existing public API.
Adds a live-coding editor and an interpreted graph language on the tooling side,
two new core building blocks (`ClosureSynthesizer`, `SampleLoop`), and one
real-time correctness fix in the disk recorder.
### New — `ClosureSynthesizer`: play a graph without a subclass
The shortest path from a generator graph to sound. Instead of declaring a
`SynthesizerBase` subclass and overriding `build()`, hand a closure that returns
the output graph:
```swift
try engine.add(ClosureSynthesizer { OscSin.Audio(freq: 440, mul: 0.1) })
try engine.add(ClosureSynthesizer(bus: 0) { Pan2(input: saw, pan: 0) })
```
The closure runs once, inside `build()`, on the main thread when the synth is
added — so each instance builds its own graph (the usual
graph-copy-per-instance rule). A multi-channel source fans out across
consecutive buses from `bus`, exactly as `output(bus:source:)` does. This is
also the primitive the scratch editor's "play a bare graph" and Graph DSL paths
build on.
### New — `SampleLoop`: inline per-sample DSP + single-sample feedback
The RT-safe escape hatch for custom sample-accurate DSP — including
**single-sample feedback loops** (one-pole filters, waveguides, comb/allpass
structures) — without declaring a whole new `Generator` type.
- **No per-block allocation.** `SampleLoop` owns its pre-allocated output buffer
(inherited `_result`) and resolves its inputs once per block via the fan-out
cache, then hands both to your closure to fill the whole block in one pass —
unlike `Closure`, which allocates a fresh `[Double]` and evaluates one sample
at a time.
- **Typed `inout` feedback state.** State is built by `makeState(numChannels)`
and passed `inout` to the body, so a filter can carry `y[n-1]` across samples
and blocks correctly.
- **Channel inference + broadcast.** Output width is inferred from the inputs
(`max` of their channel counts, or `1` with none); each input is broadcast up
to that width, so the same body scales to any channel count. Mismatched
multi-row inputs precondition-trap at construction, matching
`BinaryOpGenerator`'s policy.
### New — Live-coding scratch editor (`LyrebirdLiveCompile`, macOS)
An interactive scratch pad that compiles and plays Swift snippets against a
running engine, with hot-swap and safety scaffolding built in:
- **Bare-graph & subclass play** — `context.play { … }` for a graph,
`context.play(synth)` for a declared `Synthesizer`.
- **Named slots (Pdef-style hot-swap)** — re-running a `play(slot:)` replaces
just that voice in place; other slots keep playing. Swaps can quantize to the
next beat/bar for glitch-free, on-grid transitions.
- **Re-evaluation readiness** — a status badge (empty / dirty / compiling /
clean / queued / failed) gates the Run controls.
- **Syntax highlighting** and a line-number gutter.
- **Code completion** via the toolchain's `sourcekit-lsp`: typing `.` resolves
the real symbols the snippet would see at compile time — `LyrebirdSynth`
generators (`OscSin.` → `Audio`, `Control`), the injected `context`, and the
standard library.
- **Fast first sound** — the module cache is prewarmed at launch, so the first
⌘↩ is ~0.1 s instead of a ~2 s cold build.
- **Snippet-memory safety** — each compiled snippet maps a dylib that can't be
safely unloaded; the editor surfaces a live "snippets: N" count and nudges a
restart (or a switch to the leak-free Graph DSL mode) past a threshold.
### New — Interpreted Graph DSL (`LyrebirdGraphDSL`, cross-platform)
A small text→graph language that plays **instantly — no swiftc, no dylib, no
leak** — and is the structural answer to the snippet-dylib cost:
```
bass = OscSawtooth.Audio(freq: 55, mul: 0.15)
Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0)
```
- **304 built-in generators**, code-generated from generator init signatures, so
new generators appear automatically. Audio- and control-rate variants and
buffer resources are supported.
- **Paste-compatible** — the rate suffix is the exact Swift nested-class name
(`OscSin.Control`), so a graph expression written in the editor pastes into a
Lyrebird project unchanged.
- A mode toggle in the scratch editor runs the buffer through this path on the
same track/slot machinery as the Swift path, with errors in the same gutter.
### Fixed — `DiskOut` real-time data race
`DiskOut`'s ring buffer was a Swift `[[Float]]` shared between the real-time
render thread (writer) and its background disk-writer thread (reader). Even at
disjoint frame ranges, Swift `Array` access is not race-free — the subscript and
`withUnsafeMutableBufferPointer` touch the array's shared storage pointer and
copy-on-write / refcount bookkeeping, which the frame-counter atomics did not
fence. Under load this corrupted the heap (surfacing as retain-count aborts).
The ring is now backed by raw contiguous `UnsafeMutableBufferPointer<Float>`
storage, so the existing release/acquire frame-counter fence alone makes the
single-producer/single-consumer handoff correct. Confirmed with ThreadSanitizer;
also eliminated the long-standing parallel-`swift test` teardown crash.
---
## 1.3.0 — Graceful-release fix, quickstart template, documentation accuracy pass
A minor release. Backward-compatible: one real-time behavior fix, one new
project template, and a large sweep that makes the documentation's code
examples verifiably correct.
### Fixed — graceful release now works for `SynthesizerBase` subclasses
`release(engine:)` and `free(engine:)` were `Synthesizer` protocol requirements
satisfied only by extension defaults; `SynthesizerBase` declared neither, so a
subclass override was unreachable through an `any Synthesizer` reference. Because
`Group.release(engine:)` cascades to its children through exactly that
existential, **every gated `SynthesizerBase` subclass was hard-freed instead of
released** — envelope release phases were skipped (audible as clicks and missing
release tails). `SynthesizerBase` now declares both as `open` members, so
overrides dispatch through the vtable. Pinned by `SynthesizerReleaseDispatchTests`.
### New — `quickstart` project template + demo
- `lyrebird new MyFirstSound --template quickstart` scaffolds the shortest path
to sound: a one-oscillator `SineTone`, the engine, and a `main` that plays a
440 Hz tone for ten seconds and exits. Featured as the fast option across the
CLI help, README, and getting-started docs.
- A matching bundled **`LyrebirdQuickstartDemo`** Xcode project ships in the
workspace so the same starting point is runnable without the CLI.
### Documentation — every example now typechecked or provably illustrative
- Extended the doc-snippet compile guard to the published entry-point articles,
the generator reference, and the root docs (`README` / `LYREBIRD_START_HERE` /
`INSTALLATION_AND_USAGE`), which were previously checked by nothing. Recorded
compilable examples rose from 426 to 542.
- Fixed roughly twenty copy-paste examples that never compiled — wrong parameter
labels and orders (`LinLin`, `SpringReverb`, `BufferGrain`), nonexistent APIs
(`LFNoise2`, `DoneAction.freeSynth`, `buildGraph()`, `midiNoteToHz`,
`LyrebirdBuffer(path:)`, a `>` operator on generators), missing required
arguments (`CombFilter`/`AllpassFilter` `maxDelay`), a Swift 6 concurrency
violation in the canonical routine example, and stale test counts. Removed an
unsupported NRT-replay workflow that documented a fabricated driver API.
### Fixed — demo terminal builds
`LyrebirdNRTDemo` and `LyrebirdScoreDemo` pinned a stale `package: "LyrebirdII"`
in their `Package.swift`, so standalone `swift build` / `swift run` from the demo
directory failed. Corrected to `Lyrebird`.
---
## 1.2.0 — Generator catalog expansion *(planned)*
A minor release. Adds roughly forty SuperCollider-parity generators —
triggers, time-domain analysis, chaotic oscillators, resonator banks, dynamics,
waveshaping, routing/morph, and psychoacoustic metering — plus an iOS path fix.
Fully backward-compatible; no changes to existing public API.
### New generators
**Trigger / timing.** `Trig` and `Trig1` (fixed-duration gate from a trigger),
`Schmidt` (hysteresis threshold), `Stepper` (trigger-advanced counter),
`PulseCount` (count triggers, reset on a second input), `TriggeredDelay` (hold
then re-emit a trigger).
**Phasor / slew.** `Phasor` (sample-accurate sweeping ramp with wrap bounds and
trigger-reset), `Slew` (asymmetric slew-rate limiter).
**Time-domain analysis.** `RunningMin`, `RunningMax` (running extrema, reset on
trigger), `Slope` (per-sample first difference), `ZeroCrossing` (zero-crossing
frequency estimator).
**Routing / morph.** `Select` (index-select one of N inputs), `CrossFade`
(equal-power two-input mix), `LinearCrossFade` (linear two-input mix).
**Waveshaping / distortion.** `Waveshaper` (transfer-function table lookup with
interpolation), `CrossoverDistortion` (dead-zone crossover), `Disintegrator`
(probabilistic sample mangling).
**Resonant filter / LFO.** `Formlet` (FOF-style resonant formant filter),
`LFGauss` (Gaussian-bell LFO).
**Chaotic oscillators.** `LorenzLinear`, `HenonStepped`, `QuadStepped`,
`LinCongStepped`, `GbmanStepped`, `StandardStepped`, `FBSineStepped`,
`LatoocarfianStepped`, `CuspStepped` — discrete chaotic maps, frequency-stepped
where SuperCollider steps them.
**Resonator banks.** `Klank` (fixed bank of fixed-frequency resonators) and
`Klang` (bank of sine partials), both runtime-respecifiable.
**Dynamics.** `Normalizer` (look-ahead peak normalizer) and `Balance` (RMS
level matcher, with `logDomain` for dB-domain gain and `smooth` for decoupled
gain lag).
**Metering.** `BeatTrack` (FFT-based tempo / beat tracker) and `Loudness`
(Zwicker / ISO 532 B psychoacoustic loudness in sones).
> `DFM1` (the remaining catalog candidate) is intentionally omitted: its source
> and lookup tables are GPL, incompatible with this project's MIT license.
### Tooling
- **ShoeGaze moved out of tree.** The guitar-pedalboard framework and its
project/pedal scaffolding now live in a standalone ShoeGaze repository that
depends on Lyrebird as a package. Lyrebird's CLI no longer ships the
`shoegaze` / `shoegaze-ios` project templates or the "ShoeGaze Pedal" Xcode
file template.
### Fixes
- **`LyrebirdPaths.home` on iOS** now returns the app's Documents directory
instead of `homeDirectoryForCurrentUser` (the sandbox root, which is not
writable on iOS). Unchanged on macOS.
### Internals (no API impact)
- The 4-point Catmull-Rom cubic interpolation duplicated across oscillator
table reads, `PlayBuffer`, and the fractional-delay lines is now a single
shared `catmullRomCubic` kernel.
- Generator tests regrouped by family.
---
## 1.1.1 — Real-time performance + score-timing fixes *(planned)*
A patch release: real-time CPU improvements to the synthesis engine's hot path,
internal generator consolidation, and two score-side timing fixes. Fully
backward-compatible — no public API changes.
### Real-time performance
The generator render path (`_computeSamples`) is now Accelerate-accelerated
where it was previously scalar. Wins are largest for the primitives that appear
in nearly every patch:
- **Unary math waveshapers** (`Sin` / `Cos` / `Exp` / `Log` / `Sqrt` / `Floor`
/ `Ceil` / `Abs`) — vectorized via vForce / vDSP (~3× faster on a typical
chained-op voice).
- **Arithmetic operators** (`+` `−` `×` `÷` on generators, via
`BinaryOpGenerator`) — vDSP dispatch, **bit-identical** to the scalar result
(divide uses true-division, never reciprocal-multiply). Roughly 2–3.5× faster;
applies to every `osc * gain + offset`-style graph.
- **`LinLin`** — single fused `vDSP_vsmsaD` affine map (~27% faster).
- **State-variable filter (`SVF`)** — shared per-block kernel; generator-driven
cutoff uses block-boundary coefficient interpolation instead of a per-sample
`sin()`.
- **`Chorus` / `Flanger`** — power-of-two delay lines (bitwise index wrap).
- **Butterworth band-pass / band-reject** — now use the same background-thread
vDSP biquad-cascade path the low-pass / high-pass filters already had.
All vectorized paths keep a scalar fallback for short upstream blocks, so output
is unchanged on every code path (transcendentals within tolerance; arithmetic
and filter sums bit-exact).
### Internals (no API impact)
- Generator consolidation: the duplicated Butterworth cascade machinery, SVF
block body, unary-math and binary-op inner loops, and power-of-two buffer
sizing are now shared helpers (`ButterworthSectionEngine`, `runSVFBlock`,
`UnaryMathVectorHelpers`, `BinaryOpVectorHelpers`, `lyrebirdNextPowerOfTwo`,
`computeButterworthQs`). Several hundred lines of duplication removed.
- New `LyrebirdBenchmark` target with before/after reference numbers
(`docs/benchmarks/gp-baseline.md`).
- Language-side consolidation: shared `isCounterExhausted` / `resetAll` Pattern
helpers, a `_RandomPatternBase` for the random pattern engines, a
`TemporalAlgorithmBase` for the counter-driven temporal algorithms, a shared
MusicXML `<direction>` / `<pitch>` emit helper, and a single
engine-mutation-to-main-queue dispatch helper shared by the routine/process
contexts.
### Score / MusicXML
- **`ScorePart` entrance offset** — a part can enter later than the start of its
section via `offset:` (`ScoreOffset.measures(_:)` / `.beats(_:)` /
`.fraction(_:)`). Resolved at build time into leading rests (the same way
`FillMeasure()` is resolved), so it flows through section sizing, MusicXML bar
splitting, and `flatten()` with no special handling.
- **MusicXML barline-fill fix** — corrected two emit-side defects in sectioned
scores with rest-padded short parts: a barline-crossing atom that exactly
filled a bar left the measure open (shifting every later note by one division,
rendering constant 4/4 as 5/4), and section auto-padding used meter-agnostic
rests that straddled barlines. Padding is now bar-grid aligned (clean
whole-measure rests; anacrusis-aware). Lowering/playback math was already
correct — both fixes are export-only.
---
## 1.1 — Enhanced algorithmic composition tools
Release 1.1 turns Lyrebird's score side from a thin event list into a full
**algorithmic composition and notation toolkit**: a spelling-aware music-theory
layer, a pattern/sequence library, a composable score DSL, and lossless MusicXML
and Standard MIDI File round-trips. The real-time synthesis engine is unchanged —
this release is additive and language-side.
### Music theory toolkit
- Spelling-aware **`Interval`**, **`Scale`**, and **`PitchCollection`** types
(cells, sets, 12-tone rows) built on the existing `Letter` / `Accidental` /
`NoteName` / `Pitch` foundation.
- Diatonic-vs-chromatic transposition that preserves enharmonic spelling
(`B♯` stays `B♯`, never collapses to `C`), scale-degree mapping between scales,
and conversion straight to Hz / seconds for synthesis.
- **`Pitch.mapIntoRange(low:high:)`** — fold a pitch into a register by whole
octaves while preserving pitch class and spelling.
- See [`docs/stdlib/theory.md`](docs/stdlib/theory.md).
### Patterns
- `Pattern<T>` factory catalog for sequences, series, random and stochastic
distributions (uniform, brownian, gaussian, cauchy, beta, weighted, shuffle…),
and combinators (map, filter, stutter, switching, interleave, round-robin…).
- **`Pattern.sequence(_:repeats:offset:)`** — start a sequence partway through
its list via `offset`.
- Euclidean rhythm generator.
- See [`Sources/Lyrebird/Lyrebird.docc/RoutineTask.md`](Sources/Lyrebird/Lyrebird.docc/RoutineTask.md).
### Score DSL and notation
- A result-builder score DSL — `Score`, `Part`, `Note`, `Rest`, `Chord`,
`Tuplet`, `Voice`, `Staff` — that flattens to sample-accurate `ScoreEvent`s and
plays back through `ScorePlayer`.
- Notation features: dynamics, articulations, **crescendo / diminuendo hairpins**,
**slurs** (a `Slur { }` block plus per-note `spanners:` for shared-boundary and
overlapping spans), authored ties, grace notes, repeats and volta endings,
mid-piece tempo changes, key signatures and transposing parts, mid-voice clef
changes, grand-staff `Staff` grouping, and sustain `Pedal` marks.
- Meter: `TimeSignature` + segmented `MeterMap`, mid-piece meter changes,
anacrusis (pickup) bars, and polymeter (per-part meter overrides).
- `ScoreTimeline` musical addressing (`BeatPosition`) with overlap policies and
multi-voice fills.
- See [`Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`](Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md).
### Score structure and page layout
- **`Section { }`** blocks group parts into sequential sections, each with its
own local bar/beat numbering. Assembled into a `Score`, sections render
sequentially with continuous global measure numbers and a rehearsal mark per
section; tacet instruments are auto-filled so every staff stays bar-aligned.
`ScorePart` gains an `id` (defaults to `name`) to match the same instrument
across sections.
- **`PageLayout`** sets MusicXML page defaults: page size
(`letter` / `legal` / `tabloid` / `a4` / `a3` / custom mm), `portrait` /
`landscape` orientation, per-side odd/even margins, and `<scaling>`. Authored
in millimeters and converted to MusicXML tenths on export.
- **`NoteDisplay`** per-note display overrides via a `display:` parameter on
`Note` / `Chord`: custom notehead shape (`x`, `diamond`, `slash`, `.hidden`,
raw `.other(_)`, …), note size (`cue` / `large`), hidden stem, and hidden
beam.
- **Glissandos / slides** between two notes via the spanner API
(`.beginGlissando(_:)` / `.endGlissando`): glissando (wavy/curved) or slide
(straight) `kind`, a line type (`solid` / `dashed` / `dotted` / `wavy`), and an
optional text label.
### Import / export
- **MusicXML** export and import (`score-partwise` 4.0) with a spelling- and
event-faithful round trip across the notation features above.
- **Standard MIDI File** round-trip (`Score` ↔ SMF).
### API and internals
- `Score.timeSignature` and the `Score` initializers take a typed
`TimeSignature` (a `(numerator, denominator)` pair converts via
`TimeSignature(_:)`) instead of a raw tuple.
- Internal cleanups with no API impact: the MusicXML encoder and parser were
split from two monoliths into focused, grouped extension files, and the
parser's per-`<note>` state was extracted into a dedicated value type.
> **Namespace note:** the score DSL exposes capitalized free functions
> (`Note`, `Chord`, `Voice`, `Slur`, `Crescendo`, …). `Voice` in particular can
> collide with same-named types from other frameworks — qualify or alias if you
> hit an ambiguity.
---
## 1.0 — Initial release
First public release: the real-time synthesis engine, the `Generator` /
`Synthesizer` protocols and standard-library generators, the Core Audio and
non-real-time drivers, `LyrebirdUI`, the `lyrebird` CLI and project scaffolding,
and the AUv3 plug-in support.
@@ -82,7 +82,7 @@ open class LyrebirdAudioUnit: AUAudioUnit {
/// Required override. Construct and return the synthesizer instance that this
/// AU should host.
///
/// `@MainActor` (Phase 201): the override constructs a `@MainActor` `SynthesizerBase`
/// `@MainActor`: the override constructs a `@MainActor` `SynthesizerBase`
/// subclass, so the factory must be main-actor-isolated for a consumer building under
/// the MainActor-default mode to override it with no concurrency annotations — the same
/// rationale as `SynthesizerBase.build()`. Invoked from `init` on the host's main thread.
@@ -443,7 +443,7 @@ open class LyrebirdAudioUnit: AUAudioUnit {
newEngine.auOutputBusOffsets = _outputBusOffsets
newEngine.auInputBusOffsets = _inputBusOffsets
try newEngine.start()
// `engine.add` is `@MainActor` (Phase 201). `allocateRenderResources()` overrides
// `engine.add` is `@MainActor`. `allocateRenderResources()` overrides
// `AUAudioUnit`'s nonisolated declaration, so this method cannot itself be
// `@MainActor`. AU hosts usually call render-resource allocation on the main thread,
// but the contract does not guarantee it — the bridge runs the add inline when on
@@ -240,6 +240,11 @@ public final class NRTDriver: AudioDriver {
throw NRTDriverError.writeFailed(writeStatus)
}
}
// Synchronous render is done and the freeWorker timer only starts after this
// returns — emit any per-block event-drop warning here so it reaches the console
// even if the process exits before that timer (or `stop()`) runs.
engine.drainPerBlockEventDropWarning()
}
public func stop() {

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