LyrebirdRandom scalar distribution sampling (seedable value type + shared Random) with DistributionKind.sample dispatcher. Live Scratch editor: rename to LyrebirdScratch, App Support artifact staging, Format Code (⌥⌘F), Render to File (⌥⌘R offline CAF), line-number gutter, manual completion, Foundation in snippets, scroll-jump fix, scheduling/NRT docs.
27 KiB
Live coding with LyrebirdScratchView
A SwiftUI scratchpad for hot-swapping snippets through LyrebirdLiveCompile.
Overview
LyrebirdScratchView pairs an NSTextView-backed Swift editor with a LiveSession
that owns the audio engine. Pressing ⌘↩ wraps the snippet body in the standard
harness, shells out to swiftc, dlopens the resulting dylib, and calls the
snippet's lyrebird_snippet_entry with a SnippetContext bound to the session.
Synthesizers played via context.play(_:) are tracked, so the next non-additive
run replaces them. ⌘⇧↩ layers a new snippet on top of the prior ones.
Compile diagnostics from a failing snippet are parsed by DiagnosticParser
and rendered beneath the editor with line numbers already remapped from the wrapped
source back to the user's snippet coordinates.
The view is macOS-only — LyrebirdLiveCompile shells out to swiftc, which is
unavailable on iOS. The nested LiveCompile/ sub-package declares
platforms: [.macOS(.v15)] and cannot be added to an iOS target.
Hosting
import LyrebirdSynth
import LyrebirdUI // LyrebirdWindow
import LyrebirdLiveCompile // LiveSession
import LyrebirdLiveCompileUI // LyrebirdScratchView
let engine = SynthesisEngine(/* … */)
try engine.start()
let session = LiveSession(engine: engine)
let window = LyrebirdWindow(title: "Lyrebird Scratch", width: 640, height: 480)
window.open {
LyrebirdScratchView(session: session)
}
Keyboard shortcuts
| Shortcut | Action |
|---|---|
| ⌘↩ | Compile + run the whole buffer. Removes the previous run's anonymous synths first (named slots persist). |
| ⌘⇧↩ | Compile + run the whole buffer additively. Keeps previously played synths in the engine. |
| ⌘E | Compile + run just the selection, always additively — adds it to whatever is already playing. No-op with no selection. Works in both Swift and Graph DSL modes. |
| Esc / F5 | Invoke code completion at the caret (Swift mode). Manual only — never auto-triggered on .. See the Code completion section below. |
| ⌥⌘F | Format Code — pretty-print the buffer with the toolchain's swift-format. No-op on a blank buffer; a parse error is logged to the console and leaves the text untouched. |
| ⌥⌘R | Render to File… — bounce the selection (or the whole buffer) to a CAF audio file offline instead of playing it live. Prompts for a path and a duration, renders faster-than-real-time via NRTDriver, and reveals the file in Finder. Only sample-clock timing renders — see NRT: sample-clock timing only under Functional snippets & scheduling. |
The toolbar exposes both as buttons plus a Clear Synths button that calls
LyrebirdScratchModel/clearTracked() — a full reset that removes both the
anonymous tracked synths and every named slot.
Run Selection (⌘E) evaluates only the highlighted text and adds it to the
running graph, without touching the rest of the buffer or the whole-buffer
re-evaluation baseline (the buffer's clean/dirty status still reflects the last
whole run). This is the live-coding "evaluate this line/region" gesture: audition
a single voice or tweak, layer it in, keep going. It reads the editor selection
via LyrebirdScratchModel/updateSelection(_:) and runs it through
LyrebirdScratchModel/runSelection(); disabled when nothing is selected.
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.
Engine panel (scope + status)
The panel at the bottom of the window is a small always-on view of the running engine:
- A live dual-channel oscilloscope of the output (
ScratchScopeView), fed by aScopeCapturethatLiveSessionattaches to the first one or two output buses at init (it must be installed beforestart()). PassattachScope: falsetoLiveSession.initto opt out. - CPU average / peak meter bars and the synth / group / snippet counts, so overrun and node growth are visible at a glance.
Snippet API surface
A snippet has one local in scope:
context: SnippetContext
SnippetContext:
context.engine— the hostSynthesisEngine.context.play(_:)— add aSynthesizerto the engine and register it for cleanup on the next non-additive run.context.play { <graph> }— play a bare generator graph, noSynthesizerBasesubclass needed (wraps it in aClosureSynthesizer).context.play(slot:_:)/context.play(slot:) { <graph> }— play into a named slot (see below).context.reportMessage(_:)— print a line to the Console panel (see below); the live-coding equivalent ofprint.
Console
An always-open panel down the right side of the window is the log:
- Report messages — every
context.reportMessage(_:)line (and host notices like a failedengine.addor a dropped slot swap). - Errors — compile and Graph DSL diagnostics, with their
line:col, shown here rather than in a transient bottom strip so they stay visible while you fix them. - Run notices — a one-line result for each run.
Oldest first, auto-scrolled to the newest, capped at
LyrebirdScratchModel/maxConsoleEntries lines. Clear empties it; a
Reset Session clears it too. The model exposes the log as
LyrebirdScratchModel/consoleEntries.
Functional snippets & scheduling
A Swift-mode snippet is real Swift, not just a graph expression — loops,
let bindings, functions, arrays all work. The harness preamble imports
Foundation, LyrebirdSynth, and LyrebirdLiveCompile, so pow, sin,
sqrt, Date, and the whole generator library are in scope without any
import — which is good, because a snippet can't declare one (its body is
wrapped inside the entry function, and import is only legal at file scope). The
one rule for anything time-based: schedule events, don't Thread.sleep. The snippet body runs
once, synchronously, on the main thread; sleeping in a loop would freeze the UI
(the audio thread is separate, but the editor isn't). Use
engine.schedule(_:after:) for sample-accurate timing instead.
For example, a for loop that plays ten short sine tones a third of a second
apart — a C-major run — each a decaying Line envelope times a sine that frees
itself when done (doneAction: .freeNode), so the voices never pile up:
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0,
440.0, 493.88, 523.25, 587.33, 659.25]
for i in 0..<10 {
let freq: Double = scale[i]
let tone = ClosureSynthesizer {
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
* OscSin.Audio(freq: freq)
}
do { try context.engine.schedule(tone, after: Double(i) * 0.35) }
catch { context.reportMessage("schedule \(i) failed: \(error)") }
}
context.reportMessage("scheduled 10 tones")
The loop returns immediately after scheduling all ten adds; the engine fires
each at its time (0, 0.35, 0.70 … s). A 0.2 s tone with 0.35 s spacing leaves a
short gap between each. This is fire-and-forget scheduling for a fixed sequence.
The one rule: retention
The snippet body runs once, synchronously, then returns. Anything that fires later must be held by something that outlives the snippet — the snippet itself is transient. Three things self-sustain, and everything below builds on them:
engine.schedule(…)— the engine holds the pending event.LyrebirdRoutine/LyrebirdTask— the routine runs on a dedicated background thread that retains it until the body finishes orstop()is called.context.play(…)synths — the session tracks them (and named slots).
A Thread.sleep or busy while loop in the snippet body is the anti-pattern:
it runs on the main thread, so it freezes the editor UI (the RT audio thread
keeps going, but you can't type). Anything that waits belongs on a routine's
background thread, not in the body.
Mechanisms
| Mechanism | Use for | Timing API |
|---|---|---|
context.engine.schedule(_:after:) / schedule(_:at:) |
One-shot "play this at time T" | Seconds, or a SampleTime |
LyrebirdRoutine |
A sequence with pauses; open-ended loops | ctx.wait(seconds:) / wait(beats:) / waitUntil(sampleTime:) |
LyrebirdTask |
Same as a routine but pausable (pause() / resume()) |
same as routine |
LyrebirdClock |
Beat → sample-time reference | clock.sampleTime(beat:), nextBeat(after:) → feed schedule(_:at:) or ctx.waitUntil(sampleTime:) |
Trigger generators (Impulse → Demand / TriggeredRandom / gate) |
Timing inside the audio graph — arps, gated LFOs, step patterns | Sample-accurate, in the running synth |
LyrebirdProcess / LyrebirdEventList, Score / ScorePlayer |
Structured / pre-composed timelines | Event lists |
All of these are reachable from a snippet through context.engine and the public
LyrebirdSynth types — nothing extra is injected.
Waiting: LyrebirdRoutine
For "play N things with a pause between each" — the reactive counterpart to the
fire-and-forget loop above — use a routine. Its body runs on a background thread
(so wait never freezes the UI), and routine.start(engine:) keeps it alive
after the snippet returns:
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0]
let routine = LyrebirdRoutine { ctx in
for freq in scale {
ctx.add(ClosureSynthesizer {
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
* OscSin.Audio(freq: freq)
})
try ctx.wait(seconds: 0.3) // background-thread wait — UI stays live
}
}
routine.start(engine: context.engine) // self-sustaining; survives the snippet
ctx.add(_:) hops to the main-actor engine.add for you. ctx.wait(beats:)
waits at ctx.tempo (default 120 BPM; set ctx.tempo = … in the body to change
it); ctx.waitUntil(sampleTime:) waits to an absolute engine time, which is where
LyrebirdClock.sampleTime(beat:) comes in for on-grid spacing. Call
routine.stop() (e.g. from a later ⌘E) to cancel — the body exits at its next
wait.
Caveats
- Never block the main thread — no
Thread.sleep/ busy loops in the snippet body. Wait on a routine instead. Task { }/DispatchQueue.main.asyncAftertechnically work (they fire later on main and the session keepscontextalive), but preferengine.schedule(sample-accurate) or a routine (proper timed waits) over ad-hoc dispatch.- A
LyrebirdClockused only to compute schedule times is fine to let go; if you need it driving something over time, a routine's thread keeps it alive.
NRT: sample-clock timing only
Render to File (⌥⌘R) is offline. The NRTDriver renders faster than real
time in a tight synchronous burst — 10 s of audio in a fraction of a second —
and it does not wait for anything on the wall clock. So only timing expressed
in engine / sample time survives a render; wall-clock timing silently drops out.
| Mechanism | Live | Render to File |
|---|---|---|
engine.schedule(_:after:/at:) |
✅ | ✅ — fires at its sample time as blocks render |
In-graph triggers (Impulse → Demand / gates) |
✅ | ✅ — per-sample, driven by the render itself (best for NRT) |
LyrebirdClock.sampleTime(beat:) → schedule(_:at:) |
✅ | ✅ — pure beat→sample math |
LyrebirdRoutine / LyrebirdTask (wait(seconds:/beats:)) |
✅ | ❌ — wall-clock sleeps on a background thread; the render finishes before they fire, so their ctx.adds never make the file |
Real-time playback (playTimeline, live ScorePlayer) |
✅ | ❌ — the sample-accurate scheduling underneath is fine; the wall-clock playback driver isn't |
Rule of thumb: if the timing is a routine's wait, it's for live play; to make
the same idea render, re-express it as engine.schedule(_:after:) (fixed
sequence) or an Impulse-driven graph (periodic / patterned). This is a real
footgun — routine timing works when you play it and silently produces an empty or
truncated bounce when you render it.
Note: Graph DSL mode evaluates only generator-graph expressions — no loops or scheduling. Functional code like the above needs Swift mode.
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:
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. |
Start a voice, release it later
The slot name is the handle — the persistent reference you keep across
evaluations. (Swift let/var bindings do not carry from one snippet to the
next: each ⌘↩ / ⌘E is a separately-compiled unit, so a variable declared in one
run is invisible to the next.) So the "start something, let go of it later"
gesture is: name a slot in one evaluation, then release it by name from another —
a natural pairing with Run Selection (⌘E):
// Select this line, ⌘E — starts a persistent, gated voice named "pad":
context.play(slot: "pad") { EnvGen(gate: 1, /* … release-on-done */) * OscSaw.Audio(freq: 110) }
// …later, select this line, ⌘E — graceful release: the envelope tails out,
// then the voice frees itself:
context.release(slot: "pad")
context.release(slot:)triggers the voice's envelope release phase and drops the handle; the voice must free itself (anEnvGen/gate with a free-on-done action) to leave the engine.context.free(slot:)is the immediate hard stop (no tail) — the counterpart torelease.
Clear a slot with context.free(slot: "bass") (or context.session.clearSlot),
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) — release/free it explicitly or hit Clear Synths.
Threading
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:
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-loadedlibLyrebirdLiveCompileDynamic, which turns a benign ObjC class-duplication warning into a hard cast crash when a snippet isdlopen'd.
Compile artifacts & Application Support
Swift-mode compilation points swiftc at the Lyrebird module artifacts: the
swiftmodules, the Lyrebird dylibs, and the C-shim (LyrebirdC) Clang module map.
In a dev checkout those live in the SPM build dir under ~/Documents, so a
non-sandboxed host — and the swiftc subprocess it spawns — trips the macOS
"wants to access your Documents folder" permission gate. (The scratch/compile
temp dirs use /var/folders/… and are never the cause.)
LiveSession/stageArtifacts(from:to:) copies the minimal set into
~/Library/Application Support/LyrebirdScratch/LiveCompile/ — an ungated
location — and rewrites the C module map's absolute umbrella-header path to a
staged copy of the header, so the staged directory is a fully self-contained
compile root. LiveSession/defaultImportPaths() / defaultLibrarySearchPaths()
/ defaultRpaths() then prefer the staged dir when it is populated. Staging is
idempotent (a receipt file skips an unchanged source) and best-effort (falls back
to the build dir on any failure). A host calls it once before constructing the
session:
LiveSession.stageArtifacts() // stage into App Support
let session = LiveSession(engine: engine) // defaults resolve to the staged dir
For a standalone app, ship the artifacts inside the bundle at
Contents/Resources/LyrebirdArtifacts (name = LiveSession/bundledArtifactsDirName);
LiveSession/artifactSourceDir() prefers that over the build dir, so a shipped
LyrebirdScratch.app in /Applications stages without ever reading a
permission-gated folder. In a dev checkout the one-time stage copy still reads
the build dir under ~/Documents; every later launch reuses the staged copy.
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. Press Esc (or F5 — the standard macOS
completion keys) to complete at the caret; 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. Completion is manual, never auto-triggered on . — an
unrequested popup ambushes typing and the built-in completion window is awkward
to dismiss mid-edit.
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.
- 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 is invoked manually with Esc (or F5); there is no
auto-trigger on
.. - The host
.appmust not be sandboxed and must allow library validation to be disabled, sinceswiftcis invoked viaProcessand the resulting unsigned dylib isdlopen'd.
Snippet memory (the dylib leak)
Every ⌘↩ compiles a fresh dylib and dlopens 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.
Two Run-menu commands act on this:
- Reset Session (
LyrebirdScratchModel/resetSession()) — an in-process reset: stops all snippet audio, shuts down the code-completion server (freeing its subprocess and temp workspace), and clears diagnostics and the run baseline. Non-destructive — your buffer is left untouched, so it needs no confirmation. It does not unload the mapped snippet dylibs. - Restart to Reclaim Memory… — relaunches the app (after a confirmation, since unsaved buffer edits are lost), the only way to actually free the mapped dylibs. The fresh process starts at zero.
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,SynthesizerBasesubclasses, 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 (likecontext.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
LyrebirdScratchViewLyrebirdScratchModelScratchEvalMode