1.0.0 release

This commit is contained in:
2026-06-01 18:27:40 -07:00
parent b1ab0f102c
commit 1f20fcab20
1151 changed files with 230703 additions and 14 deletions
+272
View File
@@ -0,0 +1,272 @@
# Lyrebird — Architecture
A technical tour of how Lyrebird runs audio: the thread model, how the non-real-time world talks to the real-time render callback without locks, how a block is split for sample-accurate scheduling, how bus memory is managed, and how work fans out across cores. The audience is engineers who want to answer "how does this actually work?" and "how would I do *X*?" — not a getting-started guide (see [`README.md`](README.md)) and not an API reference (see `docs/`).
The single organizing principle: **the real-time audio thread never allocates, never locks, never blocks.** Every design decision below follows from that constraint.
---
## 1. The thread model
Lyrebird is a single-process framework. At runtime there are up to four kinds of execution context. Knowing which thread you are on tells you what you are allowed to do.
### 1.1 The real-time (RT) audio thread
This is the Core Audio render callback, invoked by the OS audio HAL every `blockSize` samples at real-time scheduling priority. On macOS the callback is driven by an AUHAL unit (`kAudioUnitSubType_HALOutput`, chosen over `DefaultOutput` because it supports full-duplex input + output); on iOS by RemoteIO. The callback path is:
```
HAL → lyrebirdRenderCallback → CoreAudioDriver.render() → SynthesisEngine.processBlock()
```
Everything reachable from `processBlock()` runs under the RT contract:
- **No allocation** — no `Array`/`String`/object creation, no implicit Copy-on-Write reallocs.
- **No locks** — no `Mutex`, `NSLock`, `DispatchSemaphore`, no `os_unfair_lock`.
- **No blocking** — no file/network I/O, no `DispatchQueue.async`, no waiting on another thread.
- **No ARC churn** — no `retain`/`release` on hot paths; cached references are held via `Unmanaged`.
- **No `print` / no dynamic casts** — no Foundation logging, no `as?`/`is` runtime type checks (inputs are classified once at `init`).
The RT thread is the **single writer** of: the engine's audio bus memory, `_currentTime`, the segment serial, and the CPU-load statistics. Everyone else reads those through atomics.
### 1.2 The main / non-RT thread
This is wherever you call the public API: `engine.add(_:)`, `engine.schedule(_:)`, `engine.remove(_:)`, and parameter mutations. It is allowed to do everything the RT thread cannot. Its job is to do all the expensive work — allocate synthesizers, run `build()` to construct the generator DAG, retain references — *before* handing a fully-prepared, pointer-only payload to the RT thread through a lock-free queue. SwiftUI `@Published` updates, file loading, and locks all live here.
### 1.3 The deferred-deallocation worker
When a synth is removed, its memory must not be freed on the RT thread (ARC dealloc can take locks and walk arbitrary deinit chains). Instead the RT thread hands the retained reference to a background queue — `DispatchQueue(label: "lyrebird.free", qos: .background)` — which drains a free-queue on a timer and calls `Unmanaged.release()` off the hot path. ARC deinit therefore always fires on a non-RT thread.
### 1.4 ParallelGroup worker threads
When a `ParallelGroup` evaluates more than one child, it dispatches the children across cores via `DispatchQueue.concurrentPerform`. Those worker invocations run *as part of* one `processBlock()` call — they are RT-priority work and inherit the full RT contract. They are not a long-lived pool you manage; `concurrentPerform` joins before the block returns. (See §7.)
### 1.5 The NRT (offline) render thread
`NRTDriver` is a passive driver: instead of an audio device callback, it runs a tight loop calling `engine.processBlock()` as fast as possible until the requested duration is filled, writing each block to a CAF file via `ExtAudioFile`. The *same* `processBlock` and the *same* scheduling stack run — there is no separate offline code path — but there is no hardware clock, so it renders faster than real time. The RT contract still holds inside `processBlock`, but the driver loop around it is ordinary code.
---
## 2. Non-RT → RT communication: the lock-free handoff
The central problem: the main thread wants to add/remove/retune voices, but cannot take a lock that the RT thread might wait on, and the RT thread cannot allocate or block. The solution is a set of **single-producer / single-consumer (SPSC) lock-free ring queues** plus a strict rule that all allocation happens on the producer side.
### 2.1 SPSCQueue
`SPSCQueue<T>` (in `Sources/Lyrebird/Engine/SPSCQueue.swift`) is the shared primitive. It is a fixed-size ring buffer (`[T?]`, capacity rounded to a power of two) with two atomic, unbounded, monotonically-increasing counters from the `Synchronization` module:
- `writeIdx: Atomic<Int>` — advanced by the producer with a **releasing** store on enqueue.
- `readIdx: Atomic<Int>` — advanced by the consumer with an **acquiring** load on dequeue.
The real slot is `counter & mask`. Occupancy is `writeIdx - readIdx`. The release/acquire pairing establishes a happens-before edge: everything the producer wrote into the slot is visible to the consumer once it observes the new `writeIdx`. No lock is ever taken. Because the capacity is fixed and the buffer is allocated up front, enqueue/dequeue never allocate.
`Synchronization.Atomic` is why the platform floor is **macOS 15 / iOS 18** — earlier OSes lack it.
### 2.2 The queues
| Queue | Direction | Carries | Notes |
|---|---|---|---|
| `pendingQueue` | main → RT | `ScheduledEvent` (add/remove/param/groupFree) | Default capacity 1024 (power-of-2). Enqueue returns `Bool`; on full, the event drops and `pendingQueueDroppedCount` increments so the caller can detect a burst overflow. |
| `freeQueue` | RT → free-worker | `Unmanaged<AnyObject>` | Pre-retained on main thread; released on the background worker. |
| `parameterSourceKillQueue` | RT → main | pointer to a replaced parameter source | Old `@LiveParam`/`@UIParam` source freed off-RT after a swap. |
| `bufferSwapKillQueue` | RT → main | pointer to a replaced `LyrebirdBuffer` | Old buffer freed off-RT after a hot-swap. |
| `triggerQueue` | RT → listener | `TriggerEvent` | RT-side trigger notifications surfaced to non-RT listeners. |
The design pattern is identical across all of them: **whoever can allocate does the allocation; the queue moves only pointers / pre-built values.**
### 2.3 ScheduledEvent — a pointer-only payload
The work the RT thread does to apply an event is deliberately trivial: re-link a node into the tree, or store a parameter value. All the heavy lifting (allocating the synth, calling `build()`, constructing the `PreparedNode`, retaining it) happens on the main thread *before* the event is enqueued. The enum captures exactly the pre-built state needed:
- `.add(PreparedNode, at: SampleTime)` — node already built and retained.
- `.addNode(PreparedNode, NodePosition, at: SampleTime)` — same, with an explicit tree position.
- `.remove(Synthesizer, retainedRef: Unmanaged, at: SampleTime)` — the synth is retained via `Unmanaged.passRetained()` on the main thread so the RT thread can hand it to `freeQueue` without touching ARC.
- `.groupFree(Group, parentGroup: Group?, at: SampleTime)` — frees a whole subtree.
### 2.4 Binding: single-shot atomic compare-exchange
A synthesizer may belong to exactly one engine at a time. This is enforced not with a lock but with a single-shot CAS on `SynthesizerBase._engineBinding: Atomic<UInt>`, which stores the engine pointer's bit pattern:
```
compareExchange(expected: 0, desired: enginePtrBits, ordering: .acquiringAndReleasing)
```
If the slot was already non-zero, the synth is bound elsewhere → `engine.add` throws `EngineAddError.boundToOtherEngine(current:prior:)` (or `.doubleAdd` if it is the *same* engine without an intervening `remove`). The errors map raw pointers back to human-readable `SynthesisEngine.identifier: UUID` values via a process-wide `EngineLifecycleCoordinator` registry (weakly holding every live engine). There is bounded stale-pointer recovery (max 2 passes): if the previously-bound engine has since deinit'd, the binding is cleared and the CAS retried.
`LyrebirdBuffer` extends this to a **two-tier** model for cross-engine sharing: `bindExclusive` (CAS on `_exclusiveEngine`, one engine, fails if any read-only holder) vs. `bindReadOnly` (refcounted via `_readOnlyRefCount: Atomic<Int>`, N engines, fails if an exclusive holder exists). The two tiers are mutually exclusive at any instant. Single-engine code needs none of this — an unbound buffer just works.
---
## 3. The render callback flow
`SynthesisEngine.processBlock()` is the heart of the system. One invocation produces one hardware block. In order:
1. **Mark RT identity** — `RTThreadIdentity.markCurrentThreadAsRT()` sets a thread-local flag so `DEBUG` assertions elsewhere can trap RT-illegal calls.
2. **Flush denormals** — `fesetenv()` enables flush-to-zero so denormal floats don't tank CPU.
3. **Zero the audio buses** — `vDSP_vclr()` clears audio bus memory for the block. (Control buses are *not* zeroed — they persist.)
4. **Copy hardware input** — incoming mic/line samples are `memcpy`'d into the reserved input buses. Never via Swift array assignment (which could trigger a CoW dealloc on the RT thread).
5. **Drain `pendingQueue`** and split the block at event boundaries (§4).
6. **Evaluate each segment** in order via `evaluateSegment(count:busOffset:)`.
7. **Advance `_currentTime`** by `blockSize` with a releasing atomic store.
8. **Update CPU stats** (EMA, relaxed atomics — best-effort).
9. **Write the scope tap** if an oscilloscope capture is attached.
10. **Apply the master gain ramp** — interpolated from the previous block's gain to the current target so volume/mute changes never click.
`blockSize` is capped at **512** (`lyrebirdDefaultResultBufferSize`) because every generator's output buffer is pre-allocated to exactly that size — there is no grow path on the RT thread.
---
## 4. Sample-accurate scheduling: block splitting
Audio is processed in blocks, but musical events must land on exact samples. Lyrebird reconciles the two by **splitting a block into segments at event boundaries** and evaluating each segment independently.
Time is `SampleTime` (`Int64`), a monotonic sample counter incremented by `blockSize` each block, written only by the RT thread and read elsewhere via atomic load. A `ScheduledEvent` carries an absolute `targetTime`.
Within one `processBlock`, with `blockStart = currentTime` and `blockEnd = blockStart + blockSize`:
```
1. Collect events whose targetTime ∈ [blockStart, blockEnd) from pendingQueue
(plus any carried over from a previous block).
2. Sort by targetTime — allocation-free insertion sort.
3. cursor = 0
for each event E, at offset = E.targetTime - blockStart:
if offset > cursor:
evaluateSegment(count: offset - cursor, busOffset: cursor) // render up to the event
applyEvent(E) // pointer-only: link/unlink node, or store a parameter
cursor = offset
evaluateSegment(count: blockSize - cursor, busOffset: cursor) // render the tail
4. currentTime += blockSize
```
So a synth scheduled at sample offset 137 of a 512-sample block causes the block to render as `[0..137)`, then the synth links in, then `[137..512)` renders with it active — and its `Out` generator begins writing at exactly `busOffset = 137`. Events in the past clamp to the block start; a hard cap of **256 events per block** bounds worst-case work (excess defers/drops).
`evaluateSegment` bumps `_atomicSegmentSerial` (releasing store), builds a `SynthGraph` around a pre-allocated empty parameter table (no per-segment alloc), and calls `rootGroup.evaluate(graph:count:)`. Crucially, generators render `count` samples — *not* always `blockSize` — and advance their internal state (oscillator phase, filter history, delay write heads) by exactly `count`. This is why a generator's `_computeSamples` must use `count`, never `engine.blockSize`: it may be called several times within a single block.
---
## 5. Bus memory
Buses are the only shared signal medium between nodes, and all of their memory is pre-allocated at `start()` and never resized.
- `audioBuses: [[Float]]` — shape `[numAudioBuses][blockSize]`.
- `controlBuses: [Float]` — shape `[numControlBuses]` (one ramp-target value per control bus).
Layout reserves the low audio buses for hardware:
```
[0 .. numOutputChannels) → hardware output (memcpy'd to the device)
[numOutputChannels .. +numInputChannels) → hardware input (filled from the device)
[numOutputChannels+numInputChannels .. numAudioBuses) → user buses
```
Per-block semantics differ by type:
- **Audio buses** are zeroed each block, written by `Out.Audio` with `+=` (so multiple voices on one bus mix naturally), and read by `In.Audio`.
- **Control buses** are *not* zeroed; a value persists until overwritten, carrying a single per-block ramp target.
"How would I route one synth into another?" → write to a user audio bus with `Out.Audio(bus: N, ...)` and read it with `In.Audio(bus: N)` in a downstream synth placed later in the node tree. Evaluation order (the node tree, head-to-tail) determines who sees whose output within a block.
### 5.1 ScratchBuses (parallel isolation)
When work is parallelized, concurrent children cannot all `+=` into the same shared engine bus without racing. Each `ParallelGroup` child therefore renders into its own pre-allocated `ScratchBuses` (same shape as the engine buses, plus a per-bus **dirty mask**). After the parallel barrier, a sequential merge pass sums each *dirty* scratch bus into the engine buses with `vDSP_vadd`. The dirty mask is the key optimization: a typical stereo voice touches 2 buses, so the merge does ~2 vector-adds instead of scanning all `numAudioBuses`.
---
## 6. How RT-safety is actually enforced
The contract in §1.1 is upheld by four mechanisms, not by hope:
1. **Pre-allocation everywhere.** Engine buses and parameter tables in `start()`; per-child `ScratchBuses` in `ParallelGroup.build()`; every generator's `_result` buffer (512 doubles) in `GeneratorBase.init()`. The RT thread only ever reads/writes into storage that already exists. `SynthesisEngine.init` rejects `blockSize > 512`.
2. **Atomics-only synchronization.** All cross-thread state is a `Synchronization.Atomic<T>`. Memory ordering is deliberate: releasing stores publish, acquiring loads consume, relaxed loads are used only for best-effort stats. There are no mutexes anywhere on the signal path.
3. **`Unmanaged` for cached references.** The engine caches things like the scope-tap target as `Unmanaged` so the RT thread can reach them without an ARC retain/release. Removal uses `Unmanaged.passRetained()` on the main thread and `Unmanaged.release()` on the free-worker — the RT thread only *moves* the pointer.
4. **Thread-local debug asserts.** The `RTThreadIdentity` TLS flag lets RT-illegal entry points (e.g. running a user `ValueComputable` closure) assert in `DEBUG`. The flag's key is warmed up off-RT in `CoreAudioDriver.init()` so even the first lookup doesn't allocate on the audio thread.
This is the lens for "would this be RT-safe?": if your code, reachable from a generator's `_computeSamples` or `calculatedSamples`, would allocate, lock, log, or touch ARC, it belongs on the main thread or behind a queue — not in the render path. The catalog of helpers in `docs/protocols/writing-generators.md` §13 exists precisely so generator authors never have to hand-roll RT-unsafe boilerplate.
---
## 7. Multi-core: ParallelGroup
`ParallelGroup` is a `Synthesizer` that evaluates its children concurrently to use more than one core for a heavy graph. Its lifecycle inside one segment:
```swift
// 1. Clear each child's scratch buses over the segment's sample range.
for slot in scratchSlots { slot.clearDirtyBuses(offset: offset, count: count) }
// 2. Evaluate.
if children.count == 1 {
// Fast path: skip the dispatch entirely, render inline.
children[0].evaluate(graph: SynthGraph(..., scratchBuses: slots[0]), count: count)
} else {
DispatchQueue.concurrentPerform(iterations: children.count) { i in
// Each i renders into its own scratchSlots[i] — no shared write target, no race.
children[i].evaluate(graph: SynthGraph(..., scratchBuses: scratchSlots[i]), count: count)
}
}
// 3. Barrier has passed. Merge dirty scratch buses into the engine buses.
for slot in scratchSlots {
for bus where slot.dirty[bus] { vDSP_vadd(slot.buses[bus], engine.audioBuses[bus], ...) }
}
```
Correctness rests on isolation and the segment serial:
- **Isolation** — each worker writes only its own `ScratchBuses`, so concurrent `Out.Audio` writes never collide. The merge is sequential.
- **`_atomicSegmentSerial`** — incremented once (releasing) before the parallel region; workers read it (acquiring). Generator result caches key on this serial, so a stale cache from a previous segment is never reused inside a concurrent worker.
Constraints that fall out of the model — useful when answering "why doesn't *X* work in parallel?":
- **No cross-child fan-out.** Sharing one generator instance between two children races on its cache. Build a copy per child.
- **Control-bus writes aren't scratch-isolated.** Two children writing the same control bus race.
- **No nested ParallelGroups.** An inner merge would bypass the outer scratch.
- **Children are fixed at `build()`.** Adding/removing children while active is undefined.
The single-child inline fast path matters: dispatching `concurrentPerform` for one child would cost more in scheduler overhead than it saves.
---
## 8. Multiple engines: EngineHost and NRT batch rendering
A process can run several engines — e.g. one real-time output plus a pool of offline renderers. `EngineHost` is the facade that owns them, keyed by an `EngineHostRole` (`.rtOutput(deviceID:)`, `.nrtRender(slot:)`, `.auxiliary(name:)`, `.custom(_)`). It enforces role uniqueness — a second engine claiming the same `.rtOutput(deviceID:)` throws `.duplicateRole`, because AUHAL output devices are exclusive.
`startAll()` / `stopAll()` are transactional: engines are snapshotted under a (non-RT) lock, started without the lock, and if any one throws, the already-started engines are rolled back with `stop()` so the caller never sees a partial-start state.
For offline batch work, `renderConcurrent(jobs:maxConcurrent:)` spawns short-lived engines on Swift `Task`s (not host-registered), defaulting `maxConcurrent` to `activeProcessorCount`. It uses a seed-and-refill pattern: launch the first `maxConcurrent` jobs, and each completion launches the next queued one. The first failure propagates and cancels the rest. (Caveat: an in-flight render may keep writing its CAF after the stream closes — orphan files are the caller's to clean up.)
Cross-engine object sharing is governed by the binding rules in §2.4. The full ownership matrix lives in `docs/engine/multi-engine-host.md` and `docs/engine/multi-core.md`.
---
## 9. Synthesizer lifecycle, end to end
Putting the pieces together — what `engine.add(synth)` actually does:
1. **(main)** Allocate the synth.
2. **(main)** `synth._bind(to: engine)` via the single-shot CAS (§2.4).
3. **(main)** `synth.build()` — construct the generator DAG, allocate every buffer.
4. **(main)** Wrap in a `PreparedNode`, retain it, enqueue `.add(node, at: time)` onto `pendingQueue`.
5. **(RT)** `processBlock` drains the event at the scheduled offset and links the node into the tree — pointer-only, no allocation (§4).
6. **(RT)** The synth renders from the next segment onward.
And `engine.remove(synth)`:
1. **(main)** `Unmanaged.passRetained(synth)` → `.remove(synth, retainedRef:, at:)` enqueued.
2. **(RT)** Unlink the node from the tree, push `retainedRef` to `freeQueue`, clear the binding CAS. No ARC, no dealloc on the RT thread.
3. **(free-worker)** Drain `freeQueue`, `Unmanaged.release()` → ARC deinit fires off-RT.
`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.
---
## Where to go deeper
| Topic | Doc |
|---|---|
| Engine internals, render pass | `docs/engine/synthesis-engine.md` |
| Core Audio / AUHAL driver | `docs/engine/core-audio-driver.md` |
| Sample-accurate scheduling | `docs/engine/scheduling.md` |
| Bus memory / In / Out | `docs/engine/bus-system.md` |
| ParallelGroup / multi-core | `docs/engine/multi-core.md` |
| EngineHost / NRT batch pool | `docs/engine/multi-engine-host.md` |
| Signal evaluation order | `docs/signal-flow/signal-flow.md` |
| Writing RT-safe generators (helper catalog §13) | `docs/protocols/writing-generators.md` |
+361
View File
@@ -0,0 +1,361 @@
# Lyrebird — Claude Context
Native macOS/iOS audio synthesis framework in Swift. Users implement `Generator` and `Synthesizer` protocols; Lyrebird engine handles Core Audio I/O and signal-graph evaluation. No separate scripting language.
## Pick the Right Agent First
Eight agents live in `~/.claude/agents/` (maintainer's source of truth) and are mirrored into the repo at `.claude/agents/` (auto-discovered) and `claude/agents/` (installer source). Invoked automatically when task description matches; you can also invoke explicitly.
| Agent | Use when |
|---|---|
| `lyrebird_demo_agent` | **Any demo work** — CLI demos, macOS GUI, iOS GUI, NoteController, Xcode project edits. |
| `lyrebird_generator_agent` | **Any new Generator** — oscillator, filter, effect, noise, math operator, bus I/O. |
| `lyrebird_engine_agent` | Engine internals — SynthesisEngine, CoreAudioDriver/iOSAudioDriver, AUHAL, SPSCQueue, ScheduledEvent, Group/ParallelGroup, RT thread architecture. |
| `lyrebird_language_agent` | Non-RT language side — SynthesizerBase, @LiveParam, ParameterNode, LyrebirdRoutine/Task/Clock, Pattern, MIDI, OSC, NRT, Score, demand pattern usage. |
| `lyrebird_swiftui_agent` | LyrebirdUI module — @UIParam, ParameterKnob/Slider/XY/Button/Label, scope/envelope views, platform-conditional code. |
| `lyrebird_architect_agent` | Cross-cutting analysis — duplicate patterns, API consistency, SC naming alignment, refactor planning. **No implementation.** |
| `lyrebird_review_agent` | Pre-merge review (via `/lyrebird_review`) — RT safety, bus rules, protocol correctness, helper usage, test coverage. |
| `pr_review_agent` | General pre-PR review — bugs, security, code smells. Broader scope than `lyrebird_review`. |
**Repo mirror sync** (after editing working copies in `~/.claude/`):
```
bash scripts/sync-claude-from-working.sh # dry-run
bash scripts/sync-claude-from-working.sh --apply
bash scripts/sync-claude-from-working.sh --check # CI: exit 1 on drift
```
Edit only in `~/.claude/`. Script keeps `.claude/` and `claude/` in sync. New agents/skills must be added to the repo manually the first time, then this script keeps them in sync.
**Pre-commit hook** (one-time setup per clone — blocks commits with stale repo mirror):
```
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`.
## Task → Doc Map
**Engine / RT core**
- Engine init, audio driver, render pass → `docs/engine/synthesis-engine.md`, `docs/engine/core-audio-driver.md`, `docs/signal-flow/signal-flow.md`
- Bus memory / In / Out → `docs/engine/bus-system.md`
- Sample-accurate scheduling → `docs/engine/scheduling.md`
- ParallelGroup / multi-core → `docs/engine/multi-core.md`
- Multi-engine host (`EngineHost`) + NRT batch render pool → `docs/engine/multi-engine-host.md`
**Generators**
- Generator protocol + DemandGenerator → `docs/protocols/generator.md`
- **Implementing a new Generator** → `docs/protocols/writing-generators.md` (§13 = shared helpers)
- 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)
- Physical models (BowedString, Flute, Clarinet, ScannedSynthesizer) → `Sources/Lyrebird/Lyrebird.docc/Generators/PhysicalModels.md`, `Sources/Lyrebird/Lyrebird.docc/Generators/ScannedSynthesis.md`
- Oversampling primitives (`HalfbandUpsampler`/`HalfbandDownsampler` 2×/4×) → `Sources/Lyrebird/Lyrebird.docc/Generators/Oversampling.md`
- Spectral processors / FFT chain → `docs/stdlib/spectral.md`
- Extension SDK / out-of-tree generator packages (SPI surface, versioning) → `docs/protocols/extension-sdk.md`
**Synthesizer / language side**
- Synthesizer protocol → `docs/protocols/synthesizer.md`
- Node tree / Group nesting / bus routing → `docs/protocols/node-tree.md`
- Routines / tasks / clock / MIDI / OSC → `docs/tooling/routine-task.md`
- `Pattern<T>` factory catalog (sequence, series, geometric, uniformRandom, brownian, gaussian, cauchy, beta, shuffle, nonRepeatingRandom, weightedRandom, closure, repeating, limit, drop, stutter, switching, concatenate, roundRobin, tuple, interleave, map, filter, reject, accumulate, difference, wrap, clip, round, smooth) → `docs/tooling/routine-task.md` (§ Pattern Factory Reference) + `Sources/Lyrebird/Lyrebird.docc/RoutineTask.md`
- MIDI clock sync (`MIDIClockFollower`) → `docs/tooling/midi-clock-sync.md`
- Non-RT parameter value sources / `ValueComputable` / `ValueComputableClosure` (consumed by `LyrebirdProcess` parameters) → `Sources/Lyrebird/Lyrebird.docc/ValueComputable.md`
- TemporalStream / language-side value generation → `Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md`
- Polyphonic voice pool / step sequencer → `docs/tooling/routine-task.md`
- Score / ScorePlayer / SMF / MusicXML → `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md`
- Performance event sequencing / `LyrebirdProcess` / `LyrebirdEventList` → `Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md`
- NRT / offline render → `docs/tooling/nrt-guide.md`
**Tooling / project**
- CLI / REPL / hot-swap → `docs/tooling/cli-guide.md`, `docs/tooling/repl.md`
- Project scaffolding / package targets → `docs/tooling/project-system.md`, `docs/tooling/targets.md`
- Dev workflow / phase branches / build → `docs/tooling/workflow.md`
- Xcode project templates → `docs/tooling/xcode-templates.md`
- AUv3 plugin internals (`LyrebirdAudioUnit`, `LyrebirdAUVoicePoolBinding`, `AUInput`, preset codable, parameter slots) → `Sources/Lyrebird/Lyrebird.docc/AUv3.md`
**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)`.
**Diagnostics**
- User-visible messages (`LyrebirdMessage`, `LyrebirdMessageCenter`, `LyrebirdMessageView` / Banner) + node-tree mirror (`NodeTreeMirror`, `NodeTreeSnapshot`, `LyrebirdNodeTreeView`) → `docs/diagnostics-guide.md`
**Planning**
- What to build next → `docs/00-working-order.md`
- Completed phases → `docs/01-completed-working-order.md`
## Hard Constraints
One-liners. Detail and rationale lives in linked docs.
**Platform / build**
- macOS 15+ / iOS 18+ / swift-tools 6.0 — `Synchronization.Atomic` requires macOS 15.
- No AVAudioEngine. Use `kAudioUnitSubType_HALOutput` (full duplex AUHAL) on macOS, RemoteIO on iOS.
- No Xcode Playgrounds. All tests use Swift Testing (`@Test`, `#expect`, `@Suite`).
**RT thread (render callback)** — `docs/engine/synthesis-engine.md`, `docs/protocols/writing-generators.md`
- No allocation, locks, blocking, `print`, `String` construction, or `is`/`as?` runtime type checks. Classify inputs at `init`.
- No `!` force unwraps. Use `guard let`, `if let`, `?? fallback`, or `throws`.
- All bus memory pre-allocated at `start()`. Never resized.
- Generator output buffers pre-allocated to `lyrebirdDefaultResultBufferSize` (512). `SynthesisEngine.init` enforces `blockSize ≤ 512`. Every `_computeSamples` opens with `_checkCount(count)` (inherited from `GeneratorBase`). No grow path.
- No shared mutable state between Synthesizer instances — graph-copy-per-instance.
**Module layering**
- No `SwiftUI`, `AppKit`, or `UIKit` imports in core `Lyrebird` module. UI lives in `LyrebirdUI` only.
- Platform-specific input sources (e.g. AppKit `NSEvent` mouse monitors) live in `LyrebirdUI` and conform to a core protocol/base class (e.g. `MouseInputBridge`) that core Generators read from. Install via the registry (e.g. `MouseInput.install(_:)`) at app startup.
**Generator protocol** — `docs/protocols/writing-generators.md`
- `GeneratorBase` is the required base class. Provides `_segmentSerial`, `_cachedResult`, `_subBlockBuffer`, **and `_result`** (mono, pre-allocated to `lyrebirdDefaultResultBufferSize`, zero-filled). Never redeclare these as stored properties.
- Mono generators inherit `_result` directly — no declaration, no init line. Multi-row generators call `super.init(channels: N)` from their designated `init` to allocate N rows in one shot. Dynamic channel counts pass `channels: outChannels` computed in `init`.
- Open every `_computeSamples` with `_checkCount(count)` — the inherited helper that traps if `count > _result[0].count`. Replaces the long-form `precondition(...)` boilerplate.
- `floatValue` is provided by the `AudioGenerator` protocol extension (returns `calculatedSamples(...).first?.first ?? 0`). Do not redeclare in `AudioGenerator` conformers unless you need different scalar semantics (e.g. `ConstantGeneratorInput`). `ControlGenerator` conformers must provide their own `floatValue` returning the block target.
- Buffer factories `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` (in `ResultBuffer.swift`) replace `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals when a generator owns a separately-allocated scratch buffer.
- Every `ControlGenerator.Control.init` calls `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. Never call on the RT thread.
- `Control._computeSamples` uses `count` (not `graph.engine.blockSize`) for phase/state advancement — `_computeSamples` may run N times per audio block in sub-block mode.
- Generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop. Canonical pattern: `Out.Control`. See `docs/protocols/writing-generators.md` §15 for the bypass list and decision rule.
- Multi-row generators (any with `_result.count > 1`) override `var outputChannelCount: Int { get }` to return the fixed channel count set at `init`. `GeneratorBase` defaults to `1`. Missing override silently mono-izes the generator under `+ - * /` operators. Channel count must be derivable from a `let` at init — never runtime-mutable. Detail + cases: `docs/stdlib/multichannel.md`.
- `mul:` / `add:` parameters are channel-aware: mono input broadcasts; equal-N applies element-wise; mismatched multi-row precondition-traps. Same policy as `BinaryOpGenerator`. Detail: `docs/stdlib/multichannel.md`.
## File Organisation
**Every new `.swift` file starts with the MIT SPDX header.** First five lines, before any `import`:
```swift
// <FileName>.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
```
(Blank line after the header, then the file body.) Applies to all source under `Sources/`, `Tests/`, `Demos/`, and `LiveCompile/`. **Exception:** Xcode file-template resources at `Sources/LyrebirdCLI/Resources/XcodeTemplates/*.xctemplate/___FILEBASENAME___.swift` — these keep only Xcode's injected `//___FILEHEADER___` (the header belongs to whoever instantiates the template, not to Lyrebird). Likewise, scaffolder/exporter code that *emits* user-facing Swift source must not bake the Lyrebird copyright into the generated string. Review-blocking: a new tracked `.swift` without the header is a violation.
**One public type per Swift source file.** Generator enums, classes, protocols, support types each in their own file.
- Generator family per file (`OscSawtooth.swift`, `LFSquare.swift`, `Clip.swift`, etc.).
- Shared file-scope helpers go in `*Helpers.swift` (e.g. `OscBandLimitedHelpers.swift`). Access `internal` (no modifier) so visible across files.
- Type-coupled support types (error enums, format enums) each in their own file (e.g. `DiskInError.swift`, `DiskOutFormat.swift`).
- One `@Suite` per test file, named `<TypeName>Tests.swift`.
**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/`
Rule:
1. Place into an existing subfolder if function matches (`Generators/` = concrete `Generator` implementations, `GeneratorCore/` = protocol layer + `MulAdd`, `Engine/` = RT core, `Buses/` = bus memory + allocation, `NodeTree/` = `Group`/`ParallelGroup`/`NodePosition`/`PreparedNode`, `Math/` = constants + numeric utilities, `Kinds/` = cross-cutting enum descriptors, etc.).
2. If no folder fits, **propose a new subfolder in the PR description** (one-line rationale, list of files going in) rather than landing files at root. Reviewers accept or redirect.
3. Subfolder may have further nesting when a family is large (e.g. `Generators/BufferIO/`, `TemporalStream/Algorithms/`).
Loose .swift at `Sources/Lyrebird/` root is a review-blocking violation. `Sources/Lyrebird/Lyrebird.docc/` is the only non-folder exception at root.
Review agents flag any new file introducing a second unrelated public type without explicit prior approval, and flag any new .swift landed at `Sources/Lyrebird/` root.
## Interface Conventions
**Filter resonance parameter naming**:
- `q:` — used for filters parameterised by a **quality factor** (RBJ cookbook, SVF, Butterworth cascade, resonator banks). `q = 1/sqrt(2) ≈ 0.707` is Butterworth (no peak); higher values produce sharper peaks. Range typically `[0.1, ~100]`.
- `resonance:` — used for filters parameterised by a **raw feedback factor** (Moog ladder and other emulation filters). Range typically `[0.0, ~1.0]` where `1.0` is the self-oscillation threshold. Engine may clamp slightly above 1.0 to avoid runaway.
Both are documented at the parameter level; the distinction is principled (different DSP families parameterise resonance differently), and call-site choice should reflect the underlying model rather than a uniform name. New filters route to whichever parameter the underlying algorithm uses naturally.
**`engine.add` / `engine.schedule` are throwing** (Phase 196). Replaced the legacy `Bool`-returning signatures with structured `throws` on all four add/schedule entry points:
```swift
public func add(_ synth: any Synthesizer) throws
public func add(_ synth: any Synthesizer, position: NodePosition) throws
public func schedule(_ synth: any Synthesizer, at time: SampleTime) throws
public func schedule(_ synth: any Synthesizer, after seconds: Double) throws
```
Throws `EngineAddError`: `.boundToOtherEngine(current:prior:)` (cross-engine), `.doubleAdd(engine:)` (same-engine re-add), `.pendingQueueFull`, `.rebuildFailed(underlying:)`. Both UUIDs surface in cross-engine errors via `SynthesisEngine.identifier: UUID`. Internal `_bind(to:) throws` / `_unbind(from:)` on `SynthesizerBase` back the precondition via single-shot atomic CAS. `LyrebirdBuffer` has opt-in two-tier binding (`bindExclusive` / `bindReadOnly`) for cross-engine sharing — see `docs/engine/multi-core.md` § Object ownership rules.
`engine.remove(_:)` and `engine.remove(_:at:)` still return `Bool` — they unbind synchronously on successful enqueue. Documented constraint: allow one `processBlock` between `remove` and re-add of the same instance.
Call-site pattern: every `engine.add` invocation needs `try`. In non-throwing contexts (closures dispatched to `DispatchQueue.main.async`, non-throwing methods), wrap in `do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") }` — the existing `LyrebirdRoutineContext` / `LyrebirdMessageContext` / `LyrebirdProcessContext` adapters use this pattern.
## Swift Code Style Rules
Hard rules. Review agents flag violations.
### 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
// WRONG
vDSP_vsmulD(buf.baseAddress!, 1, &gain, out.baseAddress!, 1, n)
// RIGHT
buf.withUnsafeMutableBufferPointer { b in
guard let base = b.baseAddress else { return }
vDSP_vsmulD(base, 1, &gain, outBase, 1, n)
}
```
### No magic numbers
Every non-trivial literal needs a named `let`. Exempt: `0`, `1`, `-1`, `2` when arithmetic meaning is obvious. Hotspots: queue capacities, trig scale factors (`1.0/sqrt(2.0)`, `0.5*.pi`), vDSP delay-state sizes, normalisation/gain constants.
```swift
// WRONG: SPSCQueue<OpaquePointer>(capacity: 32)
// RIGHT: let killQueueCapacity = 32; SPSCQueue<OpaquePointer>(capacity: killQueueCapacity)
```
### Doc comments on public Generator init parameters
Every new public Generator type documents `init` parameters **in two places** so Xcode Quick Help works from both type name and call site:
1. **Class-level `/// - Parameters:` block** on the `Audio` / `Control` class.
2. **Init-level `/// - Parameters:` block** on the `init` itself.
Each entry states: what it does, unit (Hz / dB / seconds / ratio / [0, 1] / frames), valid range or clamping, default when non-obvious.
```swift
/// Audio-rate lowpass filter.
///
/// - Parameters:
/// - input: Signal to filter.
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist.
/// - q: Resonance factor. `0.707` = Butterworth (no peak). Defaults to `0.707`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Audio: _Base, AudioGenerator {
/// - Parameters:
/// - input: Signal to filter.
/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist.
/// - q: Resonance factor. `0.707` = Butterworth (no peak). Defaults to `0.707`.
/// - mul: Output multiplier. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public init(input: any ValidGeneratorInput, freq: any ValidGeneratorInput,
q: any ValidGeneratorInput = 0.707,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0) { … }
}
```
Exception: unary/binary math operators where the class-level formula makes every param self-evident (`Abs`, `Sign`, `Floor`, etc.) only need `/// - Parameter signal: Input signal.` at both levels.
### Multi-line declarations
Multi-line format required when ≥ 2 type aliases or ≥ 2 init parameters:
```swift
// GeneratorEnum
extension Wrap: GeneratorEnum {
public typealias AudioType = Wrap.Audio
public typealias ControlType = Wrap.Control
}
// Init with ≥ 2 params
public init(
input: any ValidGeneratorInput,
freq: any ValidGeneratorInput,
q: any ValidGeneratorInput,
mul: any ValidGeneratorInput = 1.0
) { … }
// Single-param exception
public init(_ signal: any ValidGeneratorInput) { … }
```
### Explicit type annotations on bindings
Every `let` / `var` binding — stored properties on classes/structs/enums, locals inside functions, and `for x in …` loops — must carry an explicit `: Type` annotation. Inferred bindings (`let x = expr`) are a review-blocking violation in new and modified code.
```swift
// WRONG
let buf = LyrebirdBuffer(count: tableSize)
let intPhase = Int(phase)
let frac = phase - Double(intPhase)
for i in 0..<count { ... }
// RIGHT
let buf: LyrebirdBuffer = LyrebirdBuffer(count: tableSize)
let intPhase: Int = Int(phase)
let frac: Double = phase - Double(intPhase)
for i: Int in 0..<count { ... }
```
Rationale: Xcode's expression type-checker is markedly slower on long generic-heavy synth-graph expressions when intermediate locals are inferred; annotating each binding short-circuits a large slice of that work. Readability win for human readers too — the reader doesn't need to chase the inference graph to learn the type.
Exceptions (Swift grammar forbids `: T` here):
- **Closure-header parameters** — `{ x in … }`. Adding a type annotation requires inserting parens (`{ (x: T) in … }`), which is awkward and often hurts readability. Leave closure params inferred unless the type is genuinely unclear from context.
- **Tuple-pattern destructures** — `let (a, b) = tuple`. Tuple patterns don't accept inline annotations on their elements.
- **Pattern-matching contexts** — `catch let err as Foo`, `case let .foo(x)`. The binding is a pattern variable, not a value binding.
Tool: `Tools/AnnotateBindings/annotate_bindings.py` drives `sourcekit-lsp` to fill in annotations on any new or refactored file. Phase 154 swept the entire pre-existing codebase; every new file is expected to carry annotations from the start.
## Shared RT-Safe Helpers — Must Use
Module-level helpers exist to eliminate repeated boilerplate; inlining any of them in a new generator is a review violation:
- `_checkCount(_:)` — `GeneratorBase` method; first line of every `_computeSamples`
- `_calculatedSamplesBlockRate(graph:count:)` — `Generator` extension; canonical body of any `calculatedSamples` override that bypasses the `ControlGenerator` sub-block path (IIR filters, bus writers, buffer-position advancers, trigger detectors, random drawers)
- `OscillatorBase` — `Generators/Oscillators/OscillatorBase.swift`; extend instead of declaring `_freqInput` / `_freqIsGenerator` / `_phase` / `_mulAdd` inline. Designated `init(freq:phase:mul:add:)` performs canonical phase normalisation. Used by LF / band-limited oscillators (LFSawtooth, LFSquare, LFTriangle, LFDutyCycle, OscSawtooth, OscSquare, OscTriangle, OscDutyCycle) and `Impulse` (post-super-init writes `_phase = 1.0 - initPhase` so `initPhase == 0` fires at sample 0). Table-lookup oscillators (`OscSin`, `OscTable`) intentionally excluded — they store `_phase` in table-index units to avoid a per-sample multiply in the inner loop.
- `NoiseBase` — `Generators/Noise/NoiseBase.swift`; extend instead of declaring `rngState: UInt64` + `_mulAdd: MulAddSpec` inline. Designated `init(initialRngState:mul:add:)`. Used by 23 noise generators across 3 tiers (parameterless, extra-state, distribution-parameterised). LF noise variants and Crackle intentionally excluded.
- `runRBJBiquadBlock(...)` — `Generators/Filters/RBJBiquadHelpers.swift`; module-internal helper holding the shared `_computeSamples` body for `(freq, q)` RBJ biquad filters (LP / HP / AP / Notch). Concrete filters pass the coefficient formula as a closure.
- `runTwoPoleResonatorScalarBlock(input:into:y1:y2:b0:na1:na2:count:)` / `runTwoPoleResonatorInterpolatedBlock(input:into:y1:y2:start:end:count:)` — `Generators/Filters/FilterHelpers.swift`; shared per-sample loop body for two-pole resonator filters (`y[n] = b0·x[n] − na1·y[n−1] − na2·y[n−2]`). Consumed by `RingingFilter` + `ResonatingFilter` — concrete filter passes its coefficient-computation function and one-line helper calls.
- `sampleOrFallback(_:scalar:at:)` — `Generators/Filters/FilterHelpers.swift`; per-sample coefficient lookup with zero-fallback past block end. Replaces the `xxxSamples.map { i < $0.count ? $0[i] : 0 } ?? scalarX` pattern. Used by `SecondOrderSection` (5 coefficient slots) + `FirstOrderSection` (3 slots). `Lag`/`Decay` family use a different end-clamp + `lagCoeff` wrapping convention; helper doesn't apply there.
- `onePoleLowPassStep(state:x:b1:comp:)` — `Generators/Filters/FilterHelpers.swift`; `y = b1·state + comp·x`, mutates state, returns y. `comp = 1 − b1` precomputed by caller. Used by `Lag.Audio` / `Lag2.Audio` (cascade two) / `LagUpDown.Audio` / `Lag2UpDown.Audio` (after asymmetric coefficient selection).
- `leakyIntegratorStep(state:x:b1:)` — `Generators/Filters/FilterHelpers.swift`; `y = x + b1·state`, mutates state, returns y. SC `Decay`/`Decay2` convention (input not attenuated by `1 − b1`). Used by `Decay.Audio` + `Decay2.Audio` (cascade two for attack/decay difference).
- `attackReleaseSmoother(state:target:attackCoeff:attackComp:releaseCoeff:releaseComp:direction:)` — `Generators/Dynamics/DynamicsHelpers.swift`; asymmetric attack/release smoother step with direction selector (`.rising` for envelope followers; `.falling` for compressor/expander gain-target smoothing). Used by `AmplitudeFollower.Audio` (`.rising`) + `Compressor.Audio` / `Expander.Audio` (`.falling`).
- `sampleOrZero(_ p: UnsafePointer<Double>, _ i: Int, _ n: Int) -> Double` — `GeneratorCore/HotLoopHelpers.swift`; `i < n ? p[i] : 0`. Replaces the per-sample `(i < n) ? srcP[i] : 0` boilerplate inside hot loops that read an input row via raw pointer. Module-internal helper used across Filters (Lag / Lag2 / LagUpDown / Lag2UpDown / LeakDC / Decay / Decay2 / SecondOrderSection / FirstOrderSection / RBJBiquad / CombFilter / AllpassFilter) and Delays (DelayLine / DelayLineFeedback). `@_spi(LyrebirdExtensions) public` so out-of-tree generators can adopt the same helper.
- `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate input resolution. Replaces the 8-line `if _xxxIsGenerator { xxxSamples = ...; scalarXxx = 0 } else { xxxSamples = nil; scalarXxx = ... }` boilerplate at the top of any `_computeSamples` that pulls multiple `ValidGeneratorInput` parameters. Used by `Flute` (6 params), `Clarinet` (4 params), `PanXYDistance` (4 params), `PanAzDistance` (4 params). Tuple destructure at the call site is the CLAUDE.md-documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`.
- `applySpatialDistanceFiltering(...)` — `Generators/Panning/SpatialDistanceHelpers.swift`; module-internal shared per-sample pipeline for `PanXYDistance` (Cartesian) and `PanAzDistance` (polar). Both callers pre-compute `(panX, panY)` and the Chebyshev distance metric `posD` from their respective coordinate frames; the rest of the pipeline (amplitude attenuation, cutoff-coefficient caching, Doppler read-rate, delay-line write/read/wrap/clamp, one-pole lowpass, equal-power 4-corner pan) is identical and lives here. Mutates delay-line + one-pole state in place via `inout`. `@inline(__always) internal`.
- `plateReverbInputDiffusion(...)` / `plateReverbTankHalf(...)` — `Generators/Reverb/PlateReverbHelpers.swift`; PlateReverb-specific per-sample sub-blocks. `plateReverbInputDiffusion` runs the 4-stage cascaded Schroeder allpass network on a single sample. `plateReverbTankHalf` runs one half of the figure-of-eight tank (modulated allpass → delay 1 → damping LP → decay scale → allpass 2 → delay 2 write). Consumed twice per sample by `PlateReverb._computeSamples` (left and right halves). All state mutated `inout`. `@inline(__always) internal`.
- `gverbReadEarlyTaps(...)` / `gverbFDNDamperCascade(...)` — `Generators/Reverb/GVerbHelpers.swift`; GVerb-specific per-sample sub-blocks. `gverbReadEarlyTaps` reads four pre-FDN early-reflection taps with branchless wrap + per-tap gains and returns a 4-tuple. `gverbFDNDamperCascade` applies the FDN one-pole LP damper cascade `y = x*(1-damp) + prev*damp` to four raw FDN reads, mutates `fdnDampState[0..3]` with denormal flush, returns 4-tuple. Both `@inline(__always) internal`.
- `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` — `ResultBuffer.swift`; replaces the `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literal
- `_mulAdd.applyIfNeeded(to:graph:count:)`
- `fillRampedResult(into:from:to:mulAdd:graph:count:)`
- `fillScalarRampedResult(into:previousOutputValue:target:count:)` — `MulAdd.swift`; canonical body of every `Math.Control` `_computeSamples` ramp (28 generators). Distinct from `fillRampedResult` because the caller has pre-folded `mul`/`add` into the scalar `target` — the helper writes the ramp without re-applying `MulAddSpec.apply`.
- `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`)
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.
## Code Review
`/lyrebird_review` required before every merge to `main`. Run on feature branch after all work complete. No merge with blocking findings — fix and re-run until clean.
Skill behaviour:
1. `swift test` — stops on failure
2. Invokes `lyrebird_review_agent` (RT safety, bus rules, protocol correctness, helper usage, test coverage)
3. Clean pass → appends one-line phase-completion entry to `MEMORY.md`
Phase completion checklist + branch policy: `docs/00-working-order.md`. After merging a phase to `main`, move its section from `docs/00-working-order.md` into `docs/01-completed-working-order.md` and update the summary table.
## Protocol Hierarchy
```
Generator (base)
├── AudioGenerator (.audio rate — sample-rate processing)
└── ControlGenerator (.control rate — block-rate processing, may sub-block)
DemandGenerator (NOT a Generator — pure value source, pull-based)
├── DemandSequence (sequential cycling)
└── DemandRandom (random pick, xorshift64 PRNG)
Consumed by Demand.Audio (sample-accurate) / Demand.Control (didTrigger gate)
one value per ≤0→>0 trigger edge. Owned by exactly one puller.
ValidGeneratorInput
├── Float / Double / Int literals
├── any Generator
└── Closure (wraps ClosureBody)
Synthesizer
└── DAG of Generator instances (direct wiring)
└── In/Out generators communicate via bus system
Node tree
SynthesisEngine
└── rootGroup (Group, persistent)
├── [pre-main nodes] ← .before(engine.mainGroup)
├── mainGroup (Group, persistent) ← engine.add(_:) default target (head-insertion)
│ └── Synthesizer instances
└── [post-main nodes] ← .after(engine.mainGroup)
```
## Legacy Code
`legacy/Lyrebird/LyrebirdSynth/Lyrebird/` — useful patterns:
- `LyrebirdTypes.swift` — ValidGeneratorInput protocol, type aliases
- `LyrebirdUgen.swift` — Generator base
- `LyrebirdNode.swift` — node tree / groups
- `LyrebirdGraph.swift` — build closure pattern, graph copy
- `UGens/` — oscillators, filters, envelopes, delays (modernize as Generators, don't copy)
+197
View File
@@ -0,0 +1,197 @@
# Contributing to Lyrebird
Two distinct paths, depending on what you're building:
1. **A new built-in Generator** that lands *in this repo* (`Sources/Lyrebird/Generators/…`) — for primitives that belong in the core standard library: oscillators, filters, effects, noise sources, math operators, bus I/O.
2. **An out-of-tree Swift package** that depends on Lyrebird and adds its own Generators / Synthesizers — for domain-specific or third-party libraries you publish and version yourself (e.g. `LyrebirdATK`).
If you're unsure which you want: contribute in-tree only if the unit is small, general-purpose, and broadly useful. Anything large, opinionated, or with heavy data/dependencies belongs in its own package.
This guide assumes you've read [`README.md`](README.md), [`ARCHITECTURE.md`](ARCHITECTURE.md) (especially the threading model), and [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md).
---
## The one rule everything follows
**The real-time audio thread never allocates, never locks, never blocks.** Every constraint below derives from that. If you internalize nothing else, internalize this: anything reachable from a generator's `_computeSamples` / `calculatedSamples` that allocates memory, takes a lock, logs, builds a `String`, force-unwraps, or does a runtime cast is a defect. See [`ARCHITECTURE.md`](ARCHITECTURE.md) §6 for how this is enforced and why.
---
## Part 1 — Contributing a built-in Generator
### Before you start
- Read [`docs/protocols/writing-generators.md`](docs/protocols/writing-generators.md) end to end. It is the authoritative spec; this section is a checklist, not a replacement.
- §13 of that doc is the **shared RT-safe helper catalog**. Inlining boilerplate that a helper already provides is a review-blocking violation. Skim it before writing a loop by hand.
- The hard constraints in [`CLAUDE.md`](CLAUDE.md) ("Hard Constraints", "Swift Code Style Rules", "Shared RT-Safe Helpers — Must Use") are enforced by the review agents. Read them.
### Workflow
1. **Branch.** Each unit of work lives on its own branch off `main` (`phase-<N>` or a descriptive name). Never commit directly to `main`.
2. **Scaffold.** Use the Xcode file templates rather than copying an existing file by hand:
```bash
lyrebird install-templates # one-time
```
Then **New File… ▸ Lyrebird** picks the right template: *Generator*, *Oscillator*, *Noise Generator*, *Filter*, *Multi-Channel Generator*, *DemandGenerator*, plus a *Generator Test Suite*.
3. **Implement** following the rules below.
4. **Test** — every new Generator needs a test suite (see checklist).
5. **Review** — run `/lyrebird_review` on your branch. No merge with blocking findings.
### Decide: Audio rate or Control rate?
- **`AudioGenerator`** — per-sample processing (`.audio` rate). Oscillators, filters, anything whose output must be sample-accurate.
- **`ControlGenerator`** — block-rate, may sub-block (`.control` rate). Envelopes, LFOs, slow modulation. Cheaper. A `ControlGenerator` feeds an `AudioGenerator` input transparently.
If a unit is useful at both rates, implement both via the **enum namespace pattern** (`Foo.Audio` / `Foo.Control` + `GeneratorEnum` conformance). `docs/protocols/writing-generators.md` §1 walks this.
### Hard rules for the generator body
- **Subclass `GeneratorBase`.** It provides `_segmentSerial`, `_cachedResult`, `_subBlockBuffer`, and `_result` (mono, pre-allocated). Never redeclare these.
- **First line of every `_computeSamples` is `_checkCount(count)`.** It traps if `count` exceeds the pre-allocated buffer. No grow path exists.
- **Pre-allocate everything in `init`.** Bus memory, scratch buffers, vDSP setup objects. `init` runs off the RT thread; `_computeSamples` must only read/write existing storage. Use `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` instead of `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals.
- **Use `count`, never `engine.blockSize`,** for phase/state advancement — a `Control._computeSamples` may run several times per audio block in sub-block mode.
- **Generators with per-audio-block state** (bus writers, position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop via `_calculatedSamplesBlockRate(graph:count:)`. See §15 for the bypass list.
- **Multi-row generators** (`_result.count > 1`) call `super.init(channels: N)` and override `outputChannelCount`. Missing the override silently mono-izes the generator under `+ - * /`. Channel count must be a `let` fixed at init.
- **Extend the right base** where one exists: `OscillatorBase`, `NoiseBase`. Don't re-declare `_phase` / `_mulAdd` / `rngState` inline.
- **Denormal hygiene** — flush denormals to zero in feedback paths (filters, delays, reverbs).
### Swift code style (review-blocking)
- **No force unwraps.** No `!` on optionals, no `try!`. Use `guard let` / `if let` / `?? fallback` / `throws`.
- **No magic numbers.** Every non-trivial literal gets a named `let` (exempt: `0`, `1`, `-1`, `2` where arithmetic meaning is obvious).
- **Explicit type annotations on every binding** — `let x: Int = …`, `for i: Int in …`. (Exceptions: closure params, tuple destructures, pattern-match bindings.) Tool: `Tools/AnnotateBindings/annotate_bindings.py`.
- **Doc comments on every public `init` parameter, in two places** (class-level `/// - Parameters:` block *and* on the `init` itself) — state what it does, unit (Hz / dB / seconds / ratio / [0,1] / frames), range/clamping, default. This is what makes Xcode Quick Help useful from both the type and the call site.
- **Filter resonance naming:** `q:` for quality-factor filters (RBJ, SVF, Butterworth — `0.707` = Butterworth); `resonance:` for raw-feedback filters (Moog ladder, `[0,1]`). Route to whichever the algorithm uses naturally.
- **Multi-line declaration format** when ≥ 2 type aliases or ≥ 2 init params.
### File organization (review-blocking)
- **One public type per file.** Each Generator family in its own file (`OscSawtooth.swift`, `Clip.swift`).
- **Never drop a new `.swift` at `Sources/Lyrebird/` root.** Place into the matching subfolder (`Generators/`, `GeneratorCore/`, `Filters/`, `Math/`, etc.). If none fits, propose a new subfolder in the PR description — don't land at root.
- Shared file-scope helpers go in `*Helpers.swift` with `internal` access.
### Testing checklist
One `@Suite` per test file, named `<TypeName>Tests.swift`, using Swift Testing (`@Test`, `#expect`). At minimum:
- Output is non-silent / correct for a known input.
- Audio and Control variants agree where both exist.
- Edge counts: `count` of 1, sub-block sizes, full block.
- Block-boundary instance reuse (state persists correctly across blocks).
- Multi-channel: `outputChannelCount` correct; operator broadcasting behaves.
Run the suite:
```bash
swift test --no-parallel --filter <TypeName>Tests
```
Full suite before merge:
```bash
swift test --no-parallel
```
> Always `--no-parallel`. The default parallel runner SIGABRTs at xctest teardown on multi-engine combos — a known, production-irrelevant flake. One pre-existing flake (`RTThreadIdentity` retain-race) may show on the full run; the filtered suite is deterministic.
### Submitting
- Branch off `main`, implement, test, run `/lyrebird_review` until clean.
- PR description: one-line rationale, list of files, and (if you added a subfolder) why.
- Update DocC: add the type to the relevant `Sources/Lyrebird/Lyrebird.docc/` topic and, where appropriate, `docs/stdlib/generators.md`.
---
## Part 2 — Contributing an out-of-tree Swift package
For Generators / Synthesizers you publish and version yourself. The reference implementation is `LyrebirdATK` (ambisonics). Authoritative docs:
- [`docs/protocols/extension-sdk.md`](docs/protocols/extension-sdk.md) — the stable public API surface (tier 1) and `@_spi(LyrebirdExtensions)` symbols (tier 2) you may rely on, plus versioning policy.
- [`docs/extension-authors-guide.md`](docs/extension-authors-guide.md) — end-to-end walk-through building a package using LyrebirdATK as the model.
### Why a separate package?
In-tree contribution couples you to Lyrebird's release cycle and review bar. A separate package lets you own your source, ship your own releases, and pull heavy data or third-party dependencies that don't belong in core. Core users add your package and pin the version range they want.
### Naming
- Package and module: prefix with `Lyrebird` if it's a general toolkit (`LyrebirdATK`), or use your own namespace otherwise.
- Generators follow the same enum-namespace + `.Audio`/`.Control` conventions as core. Don't shadow core type names.
### `Package.swift` shape
```swift
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "LyrebirdMyExtension",
platforms: [.macOS(.v15), .iOS(.v18)], // match core's floor — Synchronization.Atomic
products: [
.library(name: "LyrebirdMyExtension", targets: ["LyrebirdMyExtension"]),
],
dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"),
],
targets: [
.target(
name: "LyrebirdMyExtension",
dependencies: [.product(name: "Lyrebird", package: "Lyrebird")]),
.testTarget(
name: "LyrebirdMyExtensionTests",
dependencies: ["LyrebirdMyExtension"]),
]
)
```
> Replace the URL with the real repository once published. During development, depend on a local checkout instead: `.package(name: "Lyrebird", path: "/path/to/LyrebirdII")`.
### What you may import
```swift
import LyrebirdSynth // tier-1 stable API — Generator/Synthesizer/GeneratorBase, engine types
import struct LyrebirdSynth.MulAddSpec // tier-2 symbols require @_spi
```
For tier-2 helpers (MulAdd helpers, the xorshift64 PRNG, test hooks):
```swift
@_spi(LyrebirdExtensions) import LyrebirdSynth
```
- **Tier 1** is the contract: it follows semver and won't break within a major version.
- **Tier 2** (`@_spi(LyrebirdExtensions)`) is available but may change between minor versions — pin a tight range if you depend on it. See `extension-sdk.md` § Versioning policy.
### Same RT rules apply
A Generator in your package runs on the same RT thread under the same contract. Everything in Part 1's "Hard rules for the generator body" and "Swift code style" applies identically — subclass `GeneratorBase`, `_checkCount(count)` first, pre-allocate in `init`, no allocation/locks/force-unwraps on the RT path. Reuse the tier-2 helpers (`sampleOrZero`, `resolveGeneratorOrScalar`, etc.) where they're `@_spi`-exposed rather than re-rolling them.
### Testing, compatibility, publishing
- Test with Swift Testing, same as core. Verify your package builds against the **minimum** Lyrebird version in your dependency range, not just the latest.
- Maintain a compatibility matrix (your version ↔ Lyrebird version) — see `extension-authors-guide.md` § Compatibility matrix.
- Tag releases semver. Document which Lyrebird major version each release targets.
### Listing your package
Once published, open a PR adding a row to the **Extensions** table in [`README.md`](README.md). One line: package name (linked) + short description.
---
## Repo maintenance contributors
If you also edit the Claude agent definitions or skills (maintainers working in `~/.claude/`):
- Edit only the working copies in `~/.claude/`. Sync the repo mirrors with:
```bash
bash scripts/sync-claude-from-working.sh --apply
bash scripts/sync-claude-from-working.sh --check # CI / pre-commit drift check
```
- Enable the pre-commit drift guard once per clone: `git config core.hooksPath .githooks`.
---
## Questions
Architecture / threading questions: [`ARCHITECTURE.md`](ARCHITECTURE.md). Generator authoring: [`docs/protocols/writing-generators.md`](docs/protocols/writing-generators.md). Extension packages: [`docs/extension-authors-guide.md`](docs/extension-authors-guide.md). Everything else: the task→doc map in [`CLAUDE.md`](CLAUDE.md).
---
## License
Lyrebird is MIT-licensed ([`LICENSE`](LICENSE)). By contributing in-tree, you agree your contributions are licensed under the same terms. Out-of-tree packages you publish keep whatever license you choose.
@@ -0,0 +1,523 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 60;
objects = {
/* Begin PBXBuildFile section */
D900000000000000000000D1 /* LyrebirdAUv3DemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = D900000000000000000000D0 /* LyrebirdAUv3DemoApp.swift */; };
D900000000000000000000D3 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D900000000000000000000D2 /* ContentView.swift */; };
D900000000000000000000DA /* LyrebirdFMExtension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = E900000000000000000000E5 /* LyrebirdFMExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
E900000000000000000000E1 /* LyrebirdFM.swift in Sources */ = {isa = PBXBuildFile; fileRef = E900000000000000000000E0 /* LyrebirdFM.swift */; };
E900000000000000000000E3 /* LyrebirdFMAudioUnit.swift in Sources */ = {isa = PBXBuildFile; fileRef = E900000000000000000000E2 /* LyrebirdFMAudioUnit.swift */; };
E900000000000000000000E7 /* LyrebirdFMAudioUnitViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E900000000000000000000E6 /* LyrebirdFMAudioUnitViewController.swift */; };
E900000000000000000000EC /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = F900000000000000000000FB /* LyrebirdUI */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
D900000000000000000000DC /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = F9000000000000000000001 /* Project object */;
proxyType = 1;
remoteGlobalIDString = E900000000000000000000E4;
remoteInfo = LyrebirdFMExtension;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
D900000000000000000000D9 /* Embed App Extensions */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 13;
files = (
D900000000000000000000DA /* LyrebirdFMExtension.appex in Embed App Extensions */,
);
name = "Embed App Extensions";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
D900000000000000000000C1 /* LyrebirdAUv3Demo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdAUv3Demo.app; sourceTree = BUILT_PRODUCTS_DIR; };
D900000000000000000000D0 /* LyrebirdAUv3DemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LyrebirdAUv3DemoApp.swift; sourceTree = "<group>"; };
D900000000000000000000D2 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };
D900000000000000000000D4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
D900000000000000000000D5 /* LyrebirdAUv3Demo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdAUv3Demo.entitlements; sourceTree = "<group>"; };
E900000000000000000000E0 /* LyrebirdFM.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LyrebirdFM.swift; sourceTree = "<group>"; };
E900000000000000000000E2 /* LyrebirdFMAudioUnit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LyrebirdFMAudioUnit.swift; sourceTree = "<group>"; };
E900000000000000000000E5 /* LyrebirdFMExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = LyrebirdFMExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };
E900000000000000000000E6 /* LyrebirdFMAudioUnitViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LyrebirdFMAudioUnitViewController.swift; sourceTree = "<group>"; };
E900000000000000000000E8 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
E900000000000000000000E9 /* LyrebirdFMExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdFMExtension.entitlements; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
D900000000000000000000C7 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
E900000000000000000000EA /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
E900000000000000000000EC /* LyrebirdUI in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
F9000000000000000000002 /* Main */ = {
isa = PBXGroup;
children = (
D900000000000000000000CE /* LyrebirdAUv3Demo */,
E900000000000000000000EE /* LyrebirdFMExtension */,
F9000000000000000000003 /* Products */,
);
sourceTree = "<group>";
};
F9000000000000000000003 /* Products */ = {
isa = PBXGroup;
children = (
D900000000000000000000C1 /* LyrebirdAUv3Demo.app */,
E900000000000000000000E5 /* LyrebirdFMExtension.appex */,
);
name = Products;
sourceTree = "<group>";
};
D900000000000000000000CE /* LyrebirdAUv3Demo */ = {
isa = PBXGroup;
children = (
D900000000000000000000D0 /* LyrebirdAUv3DemoApp.swift */,
D900000000000000000000D2 /* ContentView.swift */,
D900000000000000000000D4 /* Info.plist */,
D900000000000000000000D5 /* LyrebirdAUv3Demo.entitlements */,
);
path = LyrebirdAUv3Demo;
sourceTree = "<group>";
};
E900000000000000000000EE /* LyrebirdFMExtension */ = {
isa = PBXGroup;
children = (
E900000000000000000000E0 /* LyrebirdFM.swift */,
E900000000000000000000E2 /* LyrebirdFMAudioUnit.swift */,
E900000000000000000000E6 /* LyrebirdFMAudioUnitViewController.swift */,
E900000000000000000000E8 /* Info.plist */,
E900000000000000000000E9 /* LyrebirdFMExtension.entitlements */,
);
path = LyrebirdFMExtension;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
D900000000000000000000C0 /* LyrebirdAUv3Demo */ = {
isa = PBXNativeTarget;
buildConfigurationList = D900000000000000000000CA /* Build configuration list for PBXNativeTarget "LyrebirdAUv3Demo" */;
buildPhases = (
D900000000000000000000C6 /* Sources */,
D900000000000000000000C7 /* Frameworks */,
D900000000000000000000C8 /* Resources */,
D900000000000000000000D9 /* Embed App Extensions */,
);
buildRules = (
);
dependencies = (
D900000000000000000000DB /* PBXTargetDependency */,
);
name = LyrebirdAUv3Demo;
productName = LyrebirdAUv3Demo;
productReference = D900000000000000000000C1 /* LyrebirdAUv3Demo.app */;
productType = "com.apple.product-type.application";
};
E900000000000000000000E4 /* LyrebirdFMExtension */ = {
isa = PBXNativeTarget;
buildConfigurationList = E900000000000000000000ED /* Build configuration list for PBXNativeTarget "LyrebirdFMExtension" */;
buildPhases = (
E900000000000000000000EF /* Sources */,
E900000000000000000000EA /* Frameworks */,
E900000000000000000000F0 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = LyrebirdFMExtension;
packageProductDependencies = (
F900000000000000000000FB /* LyrebirdUI */,
);
productName = LyrebirdFMExtension;
productReference = E900000000000000000000E5 /* LyrebirdFMExtension.appex */;
productType = "com.apple.product-type.app-extension";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
F9000000000000000000001 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 0;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2620;
TargetAttributes = {
D900000000000000000000C0 = {
CreatedOnToolsVersion = 16.0;
};
E900000000000000000000E4 = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = F9000000000000000000005 /* Build configuration list for PBXProject "LyrebirdAUv3Demo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = F9000000000000000000002;
packageReferences = (
F9000000000000000000004 /* XCLocalSwiftPackageReference "../.." */,
);
productRefGroup = F9000000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
D900000000000000000000C0 /* LyrebirdAUv3Demo */,
E900000000000000000000E4 /* LyrebirdFMExtension */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
D900000000000000000000C8 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
E900000000000000000000F0 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
D900000000000000000000C6 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D900000000000000000000D1 /* LyrebirdAUv3DemoApp.swift in Sources */,
D900000000000000000000D3 /* ContentView.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
E900000000000000000000EF /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
E900000000000000000000E1 /* LyrebirdFM.swift in Sources */,
E900000000000000000000E3 /* LyrebirdFMAudioUnit.swift in Sources */,
E900000000000000000000E7 /* LyrebirdFMAudioUnitViewController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
D900000000000000000000DB /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = E900000000000000000000E4 /* LyrebirdFMExtension */;
targetProxy = D900000000000000000000DC /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
F9000000000000000000006 /* 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;
CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_NS_ASSERTIONS = YES;
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;
MACOSX_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
F9000000000000000000007 /* 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;
CODE_SIGN_STYLE = Automatic;
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
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;
MACOSX_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
D900000000000000000000CB /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = LyrebirdAUv3Demo/LyrebirdAUv3Demo.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_ASSET_PATHS = "";
DEVELOPMENT_TEAM = "";
ENABLE_HARDENED_RUNTIME = YES;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = LyrebirdAUv3Demo/Info.plist;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdAUv3Demo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Debug;
};
D900000000000000000000CC /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = LyrebirdAUv3Demo/LyrebirdAUv3Demo.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_ASSET_PATHS = "";
DEVELOPMENT_TEAM = "";
ENABLE_HARDENED_RUNTIME = YES;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = LyrebirdAUv3Demo/Info.plist;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdAUv3Demo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Release;
};
E900000000000000000000F1 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = LyrebirdFMExtension/LyrebirdFMExtension.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = "";
ENABLE_HARDENED_RUNTIME = YES;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = LyrebirdFMExtension/Info.plist;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
"@executable_path/../../../../Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdAUv3Demo.LyrebirdFMExtension;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Debug;
};
E900000000000000000000F2 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = LyrebirdFMExtension/LyrebirdFMExtension.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = "";
ENABLE_HARDENED_RUNTIME = YES;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = LyrebirdFMExtension/Info.plist;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
"@executable_path/../../../../Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdAUv3Demo.LyrebirdFMExtension;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
F9000000000000000000005 /* Build configuration list for PBXProject "LyrebirdAUv3Demo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
F9000000000000000000006 /* Debug */,
F9000000000000000000007 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D900000000000000000000CA /* Build configuration list for PBXNativeTarget "LyrebirdAUv3Demo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D900000000000000000000CB /* Debug */,
D900000000000000000000CC /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
E900000000000000000000ED /* Build configuration list for PBXNativeTarget "LyrebirdFMExtension" */ = {
isa = XCConfigurationList;
buildConfigurations = (
E900000000000000000000F1 /* Debug */,
E900000000000000000000F2 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
F9000000000000000000004 /* XCLocalSwiftPackageReference "../.." */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ../..;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
F900000000000000000000FB /* LyrebirdUI */ = {
isa = XCSwiftPackageProductDependency;
package = F9000000000000000000004 /* XCLocalSwiftPackageReference "../.." */;
productName = LyrebirdUI;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = F9000000000000000000001 /* Project object */;
}
@@ -0,0 +1,24 @@
{
"originHash" : "8c7cdbbec3286a359d81508a5a793e75295e1a598c53be84529e7a375cad48be",
"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,92 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2620"
version = "1.7">
<BuildAction
parallelizeBuildables = "NO"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D900000000000000000000C0"
BuildableName = "LyrebirdAUv3Demo.app"
BlueprintName = "LyrebirdAUv3Demo"
ReferencedContainer = "container:LyrebirdAUv3Demo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "E900000000000000000000E4"
BuildableName = "LyrebirdFMExtension.appex"
BlueprintName = "LyrebirdFMExtension"
ReferencedContainer = "container:LyrebirdAUv3Demo.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 = "Debug"
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 = "D900000000000000000000C0"
BuildableName = "LyrebirdAUv3Demo.app"
BlueprintName = "LyrebirdAUv3Demo"
ReferencedContainer = "container:LyrebirdAUv3Demo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "D900000000000000000000C0"
BuildableName = "LyrebirdAUv3Demo.app"
BlueprintName = "LyrebirdAUv3Demo"
ReferencedContainer = "container:LyrebirdAUv3Demo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,25 @@
// ContentView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("LyrebirdFM AUv3")
.font(.title)
.bold()
Text("Run this app once so macOS registers the bundled AUv3 extension. After that, load **Realized Sound: LyrebirdFM** from any AUv3 host — Logic, GarageBand, AUM, Loopy Pro, etc.")
.font(.body)
Spacer()
Text("Lyrebird AUv3 demo")
.font(.caption)
.foregroundStyle(.secondary)
}
.padding(24)
.frame(minWidth: 480, minHeight: 240)
}
}
@@ -0,0 +1,26 @@
<?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>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 Realized Sound. All rights reserved.</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>
<true/>
<key>com.apple.security.files.user-selected.read-only</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,23 @@
// LyrebirdAUv3DemoApp.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
/// Container app for the LyrebirdFM AUv3 extension.
///
/// Installing this app is what registers the bundled `.appex` extension
/// with the system AU registry. The app itself is a minimal SwiftUI
/// placeholder — its only purpose is to ship the extension. Use the AU
/// from any AUv3 host (Logic, GarageBand, AUM, Loopy Pro, etc.) after
/// running the app once.
@main
struct LyrebirdAUv3DemoApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
@@ -0,0 +1,59 @@
<?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>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>LyrebirdFM</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>XPC!</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>NSExtension</key>
<dict>
<key>NSExtensionAttributes</key>
<dict>
<key>AudioComponentBundle</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>AudioComponents</key>
<array>
<dict>
<key>name</key>
<string>Realized Sound: LyrebirdFM</string>
<key>description</key>
<string>Two-operator FM synthesizer (Lyrebird demo)</string>
<key>type</key>
<string>aumu</string>
<key>subtype</key>
<string>LBFM</string>
<key>manufacturer</key>
<string>RLZS</string>
<key>version</key>
<integer>65536</integer>
<key>sandboxSafe</key>
<true/>
<key>tags</key>
<array>
<string>Synth</string>
</array>
</dict>
</array>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.AudioUnit-UI</string>
<key>NSExtensionPrincipalClass</key>
<string>LyrebirdFMExtension.LyrebirdFMAudioUnitViewController</string>
</dict>
</dict>
</plist>
@@ -0,0 +1,44 @@
// LyrebirdFM.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Two-operator FM synthesizer used by the AUv3 demo extension.
///
/// Carrier and modulator are both `OscSin.Audio`. The modulator's output is
/// added to the carrier's frequency input; modulation depth is
/// `modIndex * carrierFreq` so the index reads as a unitless ratio (1.0 ≈
/// one octave of FM bandwidth at the carrier).
///
/// All four `@LiveParam`s map onto AU parameters in `LyrebirdFMAudioUnit`'s
/// `parameterMetadata()` table.
final class LyrebirdFM: SynthesizerBase {
/// Carrier frequency in Hz. Range [20, 8000]. Default 440 (A4).
@LiveParam var carrierFreq: Double = 440.0
/// Modulator-to-carrier frequency ratio. Range [0.25, 16]. Default 2.0
/// (one octave above carrier — produces an even-harmonic-rich timbre).
@LiveParam var modRatio: Double = 2.0
/// Modulation index (unitless). Range [0, 8]. Default 0.5 — mild
/// modulation; sounds close to a sine with extra brightness.
@LiveParam var modIndex: Double = 0.5
/// Output amplitude. Range [0, 1]. Default 0.3 — leaves headroom.
@LiveParam var amp: Double = 0.3
override func build() {
let modFreq = $carrierFreq * $modRatio
let modDepth = $modIndex * $carrierFreq
let modulator = OscSin.Audio(freq: modFreq, mul: modDepth)
let carrier = OscSin.Audio(freq: $carrierFreq + modulator)
let voice = carrier * $amp
// Mono → both stereo channels for AUv3 host compatibility.
output(bus: 0, source: voice)
output(bus: 1, source: voice)
}
}
@@ -0,0 +1,33 @@
// LyrebirdFMAudioUnit.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import AVFoundation
import AudioToolbox
/// AUv3 wrapper around `LyrebirdFM`. Subclasses ``LyrebirdAudioUnit`` and
/// only overrides the two required hooks: `makeSynthesizer()` and
/// `parameterMetadata()`.
///
/// The `AudioComponentDescription` (type `aumu`, subtype `LBFM`,
/// manufacturer `RLZS`) is declared in `Info.plist`'s `AudioComponents`
/// array; this class is instantiated by the AU host via
/// `NSExtensionPrincipalClass` resolution.
public final class LyrebirdFMAudioUnit: LyrebirdAudioUnit {
public override class func makeSynthesizer() -> SynthesizerBase {
LyrebirdFM()
}
public override class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] {
[
"carrierFreq": .init(min: 20, max: 8000, unit: .hertz, displayName: "Carrier Freq"),
"modRatio": .init(min: 0.25, max: 16, unit: .generic, displayName: "Mod Ratio"),
"modIndex": .init(min: 0, max: 8, unit: .generic, displayName: "Mod Index"),
"amp": .init(min: 0, max: 1, unit: .linearGain, displayName: "Output Amp"),
]
}
}
@@ -0,0 +1,38 @@
// LyrebirdFMAudioUnitViewController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import CoreAudioKit
import AVFoundation
/// AUv3 view controller + factory.
///
/// `AUAudioUnitFactory` conformance is how AUv3 hosts instantiate the
/// underlying `AUAudioUnit` — the host loads this view controller as the
/// extension's `NSExtensionPrincipalClass`, calls
/// `createAudioUnit(with:)`, and the resulting AU is what handles render.
///
/// Ships an empty placeholder view. Drop in `LyrebirdSynthView` (from
/// `LyrebirdUI`) to get a Mirror-driven SwiftUI parameter grid.
public final class LyrebirdFMAudioUnitViewController: AUViewController, AUAudioUnitFactory {
/// Strong reference to the AU once `createAudioUnit(with:)` builds it.
/// The host keeps a separate reference; this is held so a SwiftUI view
/// added on top can read parameters from the same instance.
public private(set) var audioUnit: AUAudioUnit?
public override func viewDidLoad() {
super.viewDidLoad()
// Empty stub — install a SwiftUI host (e.g. `LyrebirdSynthView`) here.
}
public func createAudioUnit(
with componentDescription: AudioComponentDescription
) throws -> AUAudioUnit {
let au = try LyrebirdFMAudioUnit(componentDescription: componentDescription)
audioUnit = au
return au
}
}
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
</dict>
</plist>
+156
View File
@@ -0,0 +1,156 @@
# LyrebirdAUv3Demo
Reference AUv3 plugin built on Lyrebird's `LyrebirdAudioUnit`. Ships
**Realized Sound: LyrebirdFM** — a two-operator FM synthesizer — as an
`aumu` instrument loadable in any AUv3 host (Logic, GarageBand, AUM,
Loopy Pro, etc.).
Copy this directory as the starting point for your own Lyrebird-based
AUv3 plugin.
## Layout
```
LyrebirdAUv3Demo/
LyrebirdAUv3Demo.xcodeproj Hand-written Xcode project (app + extension)
LyrebirdAUv3Demo/ Container app target (.app)
LyrebirdAUv3DemoApp.swift SwiftUI app entry — minimal
ContentView.swift One-screen "installer" view
Info.plist
LyrebirdAUv3Demo.entitlements App sandbox
LyrebirdFMExtension/ AUv3 extension target (.appex)
LyrebirdFM.swift The two-op FM SynthesizerBase subclass
LyrebirdFMAudioUnit.swift LyrebirdAudioUnit subclass (metadata + factory)
LyrebirdFMAudioUnitViewController.swift AUViewController + AUAudioUnitFactory stub
Info.plist AudioComponents (aumu / LBFM / RLZS)
LyrebirdFMExtension.entitlements App-extension sandbox
```
## Build
### From the command line
```bash
xcodebuild \
-project Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj \
-scheme LyrebirdAUv3Demo \
-configuration Release \
CODE_SIGN_IDENTITY="-" \
CODE_SIGNING_REQUIRED=NO \
CODE_SIGNING_ALLOWED=NO \
SWIFT_USE_INTEGRATED_DRIVER=NO \
build
```
`SWIFT_USE_INTEGRATED_DRIVER=NO` is the Xcode 26 workaround documented
elsewhere in the Lyrebird build notes; it disables explicit-module-build
so SPM dynamic-framework modules resolve correctly. The
`CODE_SIGN_IDENTITY="-"` triple disables signing entirely for local
builds — for distribution you must set `DEVELOPMENT_TEAM` to your Apple
Developer Team ID and use `Automatic` signing.
### From Xcode
1. Open `LyrebirdAUv3Demo.xcodeproj`.
2. Pick the **LyrebirdAUv3Demo** scheme.
3. In each target's Signing & Capabilities tab, set your Team. The
bundle ID `net.realizedsound.LyrebirdAUv3Demo` is a Realized-Sound
placeholder — change to a prefix you own.
4. Add `SWIFT_USE_INTEGRATED_DRIVER = NO` under each target's
Build Settings → User-Defined (or set it project-wide). Required on
Xcode 26+.
5. **Build & Run** the container app once. This registers the embedded
extension with the AU registry.
## Validate with auval
After running the container app at least once so the extension is
registered:
```bash
auval -v aumu LBFM RLZS
```
A `PASS` summary is what you want. Common gotchas the wrapper already
handles:
- `latency` returns 0 (`LyrebirdAudioUnit.latency`).
- `tailTime` returns 0 (instrument has no internal tail).
- `parameterTree` is populated synchronously in `init`, so `auval`
sees it before render.
- `internalRenderBlock` returns `noErr` and writes valid samples.
- `maximumFramesToRender` is honoured by `AUv3Driver` via ring sizing.
If you see "Cannot get Component's Name strings" or "didn't find the
component", the extension was not registered. Either the container app
has not been launched yet, or `lsregister` did not pick it up. Re-run
the container app from Xcode, then re-run `auval`.
## Smoke test in a host
1. **Logic Pro / GarageBand**: Track → New Software Instrument → AU
Instruments → Realized Sound → LyrebirdFM. Play a few MIDI notes
(this template ships no MIDI handler — the plugin instantiates and
accepts parameter automation, but won't respond to note input until
you wire `LyrebirdAudioUnit.midiHandler`; see [`AUv3.md`](../../Sources/Lyrebird/Lyrebird.docc/AUv3.md)).
2. **AUM / Loopy Pro** (iOS): same idea once the iOS variant of this
demo lands.
## What's in the wrapper
`LyrebirdFMAudioUnit` is the entire wrapper:
```swift
public final class LyrebirdFMAudioUnit: LyrebirdAudioUnit {
public override class func makeSynthesizer() -> SynthesizerBase { LyrebirdFM() }
public override class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] {
[
"carrierFreq": .init(min: 20, max: 8000, unit: .hertz, displayName: "Carrier Freq"),
"modRatio": .init(min: 0.25, max: 16, unit: .generic, displayName: "Mod Ratio"),
"modIndex": .init(min: 0, max: 8, unit: .generic, displayName: "Mod Index"),
"amp": .init(min: 0, max: 1, unit: .linearGain, displayName: "Output Amp"),
]
}
}
```
`LyrebirdAudioUnit` does the rest: parameter tree from `Mirror`, engine
lifecycle, ring-buffered render, `fullState` save / restore. See
[`Sources/Lyrebird/Lyrebird.docc/AUv3.md`](../../Sources/Lyrebird/Lyrebird.docc/AUv3.md)
for the full API surface.
## Copying this template
To ship your own AUv3 plugin:
1. Duplicate `Demos/LyrebirdAUv3Demo/` under a new name.
2. Replace `LyrebirdFM` with your own `SynthesizerBase` subclass.
3. Update `componentSubType` (4-char code, must be unique to your
plugin) and `manufacturer` (your 4-char manufacturer code) in
the extension's `Info.plist → NSExtension → NSExtensionAttributes
→ AudioComponents`.
4. Update `PRODUCT_BUNDLE_IDENTIFIER` in both targets'
build settings to your own reverse-DNS prefix.
5. Replace `Realized Sound: LyrebirdFM` strings with your own
manufacturer + plugin name.
6. Rebuild, run, `auval -v <type> <subType> <manufacturer>`.
## Not yet wired in this template
The framework supports all of the following — this particular demo
template just doesn't include them yet. Each is a follow-up exercise
when copying the template:
- MIDI note input — set `au.midiHandler` and dispatch via
``LyrebirdAUVoicePoolBinding``.
- SwiftUI parameter UI in the view controller — drop in
``LyrebirdSynthView`` (see [`LyrebirdSynthView`](../../Sources/LyrebirdUI/LyrebirdSynthView.swift)).
- Source-slot preset save/restore — conform any source generator to
``LyrebirdAUPresetCodable`` and register it.
- Effect-type AU (`aufx`) — override ``LyrebirdAudioUnit/lyrebirdInputChannels``
and read host audio via ``AUInput/Audio``.
- iOS container app target — duplicate the Mac app target and switch
the platform.
The demo deliberately ships the smallest cut that proves the wrapper
loads and validates.
@@ -0,0 +1,400 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 60;
objects = {
/* Begin PBXBuildFile section */
0306C7C02FAC451300952EAF /* GVerbTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7BF2FAC451300952EAF /* GVerbTest.swift */; };
0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7C12FAC45F200952EAF /* ReverbDemo.swift */; };
035A2F422FAA4F67007F6289 /* PercPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */; };
035A2F432FAA4F67007F6289 /* PercSpectralPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F412FAA4F67007F6289 /* PercSpectralPitchShift.swift */; };
035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F492FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift */; };
035A2F442FAA4F67007F6289 /* PercBufferRead.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F3E2FAA4F67007F6289 /* PercBufferRead.swift */; };
035A2F452FAA4F67007F6289 /* PercPlayBuffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F402FAA4F67007F6289 /* PercPlayBuffer.swift */; };
035A2F472FAA6950007F6289 /* PercTimeStretch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F462FAA6950007F6289 /* PercTimeStretch.swift */; };
035B00012FAB0000007F0001 /* DemoProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035B00032FAB0000007F0001 /* DemoProtocol.swift */; };
035B00022FAB0000007F0001 /* BufferDemos.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035B00042FAB0000007F0001 /* BufferDemos.swift */; };
C1A000000000000000000007 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A000000000000000000006 /* main.swift */; };
C1A000000000000000000013 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C1A000000000000000000012 /* Lyrebird */; };
C1A000000000000000000016 /* SineTone.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A000000000000000000014 /* SineTone.swift */; };
C1A000000000000000000017 /* DelaySample.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A000000000000000000015 /* DelaySample.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
0306C7BF2FAC451300952EAF /* GVerbTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GVerbTest.swift; sourceTree = "<group>"; };
0306C7C12FAC45F200952EAF /* ReverbDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReverbDemo.swift; sourceTree = "<group>"; };
035A2F3E2FAA4F67007F6289 /* PercBufferRead.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercBufferRead.swift; sourceTree = "<group>"; };
035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercPitchShift.swift; sourceTree = "<group>"; };
035A2F402FAA4F67007F6289 /* PercPlayBuffer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercPlayBuffer.swift; sourceTree = "<group>"; };
035A2F412FAA4F67007F6289 /* PercSpectralPitchShift.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercSpectralPitchShift.swift; sourceTree = "<group>"; };
035A2F492FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercSpectralStereoDiffuse.swift; sourceTree = "<group>"; };
035A2F462FAA6950007F6289 /* PercTimeStretch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercTimeStretch.swift; sourceTree = "<group>"; };
035B00032FAB0000007F0001 /* DemoProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoProtocol.swift; sourceTree = "<group>"; };
035B00042FAB0000007F0001 /* BufferDemos.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BufferDemos.swift; sourceTree = "<group>"; };
C1A000000000000000000004 /* LyrebirdDemo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = LyrebirdDemo; sourceTree = BUILT_PRODUCTS_DIR; };
C1A000000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
C1A000000000000000000014 /* SineTone.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineTone.swift; sourceTree = "<group>"; };
C1A000000000000000000015 /* DelaySample.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DelaySample.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
C1A000000000000000000009 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
C1A000000000000000000013 /* Lyrebird in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
035B00052FAB0000007F0001 /* Demos */ = {
isa = PBXGroup;
children = (
0306C7C12FAC45F200952EAF /* ReverbDemo.swift */,
035B00032FAB0000007F0001 /* DemoProtocol.swift */,
035B00042FAB0000007F0001 /* BufferDemos.swift */,
);
path = Demos;
sourceTree = "<group>";
};
035B00062FAB0000007F0001 /* Buffer */ = {
isa = PBXGroup;
children = (
035A2F3E2FAA4F67007F6289 /* PercBufferRead.swift */,
035A2F402FAA4F67007F6289 /* PercPlayBuffer.swift */,
);
path = Buffer;
sourceTree = "<group>";
};
035B00072FAB0000007F0001 /* Granular */ = {
isa = PBXGroup;
children = (
035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */,
035A2F462FAA6950007F6289 /* PercTimeStretch.swift */,
);
path = Granular;
sourceTree = "<group>";
};
035B00082FAB0000007F0001 /* Spectral */ = {
isa = PBXGroup;
children = (
035A2F412FAA4F67007F6289 /* PercSpectralPitchShift.swift */,
035A2F492FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift */,
);
path = Spectral;
sourceTree = "<group>";
};
035B00092FAB0000007F0001 /* General */ = {
isa = PBXGroup;
children = (
C1A000000000000000000015 /* DelaySample.swift */,
C1A000000000000000000014 /* SineTone.swift */,
);
path = General;
sourceTree = "<group>";
};
C1A000000000000000000002 = {
isa = PBXGroup;
children = (
C1A000000000000000000005 /* LyrebirdDemo */,
C1A000000000000000000003 /* Products */,
);
sourceTree = "<group>";
};
C1A000000000000000000003 /* Products */ = {
isa = PBXGroup;
children = (
C1A000000000000000000004 /* LyrebirdDemo */,
);
name = Products;
sourceTree = "<group>";
};
C1A000000000000000000005 /* LyrebirdDemo */ = {
isa = PBXGroup;
children = (
C1A000000000000000000006 /* main.swift */,
035B00052FAB0000007F0001 /* Demos */,
C1A000000000000000000018 /* Synthesizers */,
);
path = LyrebirdDemo;
sourceTree = "<group>";
};
C1A000000000000000000018 /* Synthesizers */ = {
isa = PBXGroup;
children = (
0306C7BF2FAC451300952EAF /* GVerbTest.swift */,
035B00062FAB0000007F0001 /* Buffer */,
035B00072FAB0000007F0001 /* Granular */,
035B00082FAB0000007F0001 /* Spectral */,
035B00092FAB0000007F0001 /* General */,
);
path = Synthesizers;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
C1A00000000000000000000A /* LyrebirdDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = C1A00000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdDemo" */;
buildPhases = (
C1A000000000000000000008 /* Sources */,
C1A000000000000000000009 /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = LyrebirdDemo;
packageProductDependencies = (
C1A000000000000000000012 /* Lyrebird */,
);
productName = LyrebirdDemo;
productReference = C1A000000000000000000004 /* LyrebirdDemo */;
productType = "com.apple.product-type.tool";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
C1A000000000000000000001 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2620;
TargetAttributes = {
C1A00000000000000000000A = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = C1A00000000000000000000E /* Build configuration list for PBXProject "LyrebirdDemo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = C1A000000000000000000002;
packageReferences = (
C1A000000000000000000011 /* XCLocalSwiftPackageReference "../.." */,
);
productRefGroup = C1A000000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
C1A00000000000000000000A /* LyrebirdDemo */,
);
};
/* End PBXProject section */
/* Begin PBXSourcesBuildPhase section */
C1A000000000000000000008 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
035B00012FAB0000007F0001 /* DemoProtocol.swift in Sources */,
035B00022FAB0000007F0001 /* BufferDemos.swift in Sources */,
0306C7C02FAC451300952EAF /* GVerbTest.swift in Sources */,
035A2F422FAA4F67007F6289 /* PercPitchShift.swift in Sources */,
035A2F432FAA4F67007F6289 /* PercSpectralPitchShift.swift in Sources */,
035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */,
035A2F442FAA4F67007F6289 /* PercBufferRead.swift in Sources */,
0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */,
035A2F452FAA4F67007F6289 /* PercPlayBuffer.swift in Sources */,
C1A000000000000000000007 /* main.swift in Sources */,
C1A000000000000000000016 /* SineTone.swift in Sources */,
035A2F472FAA6950007F6289 /* PercTimeStretch.swift in Sources */,
C1A000000000000000000017 /* DelaySample.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
C1A00000000000000000000C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
};
name = Debug;
};
C1A00000000000000000000D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
DEAD_CODE_STRIPPING = YES;
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
};
name = Release;
};
C1A00000000000000000000F /* 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;
DEAD_CODE_STRIPPING = YES;
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;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
C1A000000000000000000010 /* 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;
DEAD_CODE_STRIPPING = YES;
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;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
C1A00000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C1A00000000000000000000C /* Debug */,
C1A00000000000000000000D /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C1A00000000000000000000E /* Build configuration list for PBXProject "LyrebirdDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C1A00000000000000000000F /* Debug */,
C1A000000000000000000010 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
C1A000000000000000000011 /* XCLocalSwiftPackageReference "../.." */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ../..;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
C1A000000000000000000012 /* Lyrebird */ = {
isa = XCSwiftPackageProductDependency;
package = C1A000000000000000000011 /* XCLocalSwiftPackageReference "../.." */;
productName = Lyrebird;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = C1A000000000000000000001 /* 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,79 @@
<?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 = "C1A00000000000000000000A"
BuildableName = "LyrebirdDemo"
BlueprintName = "LyrebirdDemo"
ReferencedContainer = "container:LyrebirdDemo.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"
viewDebuggingEnabled = "No">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C1A00000000000000000000A"
BuildableName = "LyrebirdDemo"
BlueprintName = "LyrebirdDemo"
ReferencedContainer = "container:LyrebirdDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C1A00000000000000000000A"
BuildableName = "LyrebirdDemo"
BlueprintName = "LyrebirdDemo"
ReferencedContainer = "container:LyrebirdDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,136 @@
// BufferDemos.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
final class BufferDemos: DemoProtocol {
private let engine: SynthesisEngine
init(engine: SynthesisEngine) {
self.engine = engine
}
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)
.deletingLastPathComponent() // .../Demos/
.deletingLastPathComponent() // .../LyrebirdDemo/
.deletingLastPathComponent() // .../LyrebirdDemo (package)/
.deletingLastPathComponent() // .../Demos/
.appendingPathComponent("Mozart.aiff")
let percBuffer: LyrebirdBuffer
do {
percBuffer = try LyrebirdBuffer.load(url: percURL)
print("Loaded \(percURL.lastPathComponent): \(percBuffer.count) frames, SR \(percBuffer.sampleRate.map { "\($0) Hz" } ?? "unknown")")
} catch {
print("Failed to load Perc.aiff: \(error)")
engine.stop()
exit(1)
}
let sampleRate = engine.sampleRate
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)
try ctx.wait(seconds: 0.2)
// 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)
try ctx.wait(seconds: 0.2)
// 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
try ctx.wait(seconds: 3)
}
ctx.remove(demo3)
try ctx.wait(seconds: 0.5)
// 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 {
print(" pitchRatio \(label)")
let demo4 = PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate)
ctx.add(demo4)
try ctx.wait(seconds: 5)
ctx.remove(demo4)
try ctx.wait(seconds: 0.3)
}
// 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 {
print(" amount \(label)")
let demo5 = PercSpectralStereoDiffuse(
buffer: percBuffer, amount: amount, engineSampleRate: sampleRate)
ctx.add(demo5)
try ctx.wait(seconds: 5)
ctx.remove(demo5)
try ctx.wait(seconds: 0.3)
}
// 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 {
print(" stretchFactor \(label)")
let demo6 = PercTimeStretch(buffer: percBuffer, stretchFactor: factor)
ctx.add(demo6)
try ctx.wait(seconds: 6)
ctx.remove(demo6)
try ctx.wait(seconds: 0.3)
}
print("\nAll buffer demos complete.")
}
}
}
@@ -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,42 @@
// ReverbDemo.swift
// Lyrebird
//
// 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
final class ReverbDemo: DemoProtocol {
private let engine: SynthesisEngine
init(engine: SynthesisEngine) {
self.engine = engine
}
func runDemo() {
let sampleRate = engine.sampleRate
// sets up its own thread / timing, etc
LyrebirdTask.run(engine: engine) { [sampleRate] ctx in
ctx.tempo = 60.0
let reverbDemo = GVerbTest(
sampleRate: sampleRate
)
ctx.add(reverbDemo)
try ctx.wait(beats: 6) // could also use seconds
ctx.remove(reverbDemo)
print("\nAll buffer demos complete.")
}
}
}
@@ -0,0 +1,36 @@
// PercBufferRead.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// BufferRead demo — normalized-position random-access playback driven by a sine-wave position.
///
/// `BufferRead.Audio` has no internal play-head; position `[0,1]` is entirely external.
/// Here an `OscSin` at the buffer's natural loop frequency is mapped from `[-1, 1]` to `[0, 1]`
/// to sweep forward and backward through the sample sinusoidally. This produces a natural
/// pitch-warping effect as the scan accelerates through the middle and slows at the ends.
///
/// For a true sawtooth scan (constant-speed linear loop), replace the position expression
/// with a dedicated `Phasor.Audio` when available in the stdlib.
final class PercBufferRead: SynthesizerBase {
let buffer: LyrebirdBuffer
init(buffer: LyrebirdBuffer) {
self.buffer = buffer
super.init()
}
override func build() {
// phasorFrequency: frequency at which a linear phasor sweeps 0→1 in one buffer duration.
let scanFreq = buffer.phasorFrequency ?? 1.0
// Sine at scanFreq maps [-1, 1] → [0, 1] giving a smooth forward+backward position sweep.
let position = (OscSin.Audio(freq: scanFreq) + 1.0) * 0.5
let reader = BufferRead.Audio(buffer: buffer, position: position, interpolation: .linear)
output(bus: 0, source: Pan2(input: reader[0], mul: 0.6))
}
}
@@ -0,0 +1,30 @@
// PercPlayBuffer.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Looping PlayBuffer demo — plays `Perc.aiff` in a continuous loop at native sample rate.
///
/// `nativeRateScale` compensates for any mismatch between the file's sample rate and the
/// engine's sample rate. For a stereo engine the mono buffer's single channel is centred
/// via `Pan2`.
final class PercPlayBuffer: SynthesizerBase {
let buffer: LyrebirdBuffer
let engineSampleRate: Double
init(buffer: LyrebirdBuffer, engineSampleRate: Double) {
self.buffer = buffer
self.engineSampleRate = engineSampleRate
super.init()
}
override func build() {
// Compensate for any file SR ≠ engine SR (e.g. 44.1 kHz file in 48 kHz engine).
let rateScale = buffer.nativeRateScale(engineSampleRate: engineSampleRate)
let player = PlayBuffer.Audio(buffer: buffer, loop: true, rate: rateScale)
output(bus: 0, source: Pan2(input: player[0], mul: 0.6))
}
}
@@ -0,0 +1,35 @@
// GVerbTest.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
//
// GVerbTest.swift
// LyrebirdDemo
//
// Created by Joshua Parmenter on 5/6/26.
//
import LyrebirdSynth
final class GVerbTest: SynthesizerBase {
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,
earlyLevel: 0.4,
tailLevel: 0.9,
dryLevel: 0.1,
sampleRate: sampleRate
)
output(bus: 0, source: reverb)
}
}
@@ -0,0 +1,30 @@
// DelaySample.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
final class DelaySample: SynthesizerBase {
let delayTime: any ValidGeneratorInput
let amp: any ValidGeneratorInput
init(delayTime: any ValidGeneratorInput, amp: any ValidGeneratorInput = 0.2) {
self.delayTime = delayTime
self.amp = amp
super.init()
}
override func build() {
let testTone = OscSin.Audio(freq: 220.0) * 0.1
let delay = DelayLine(
input: testTone,
maxDelay: 2.0,
delay: delayTime + (OscSin.Audio(freq: 0.4) * 0.05),
interpolation: DelayInterpolation.cubic
)
output(bus: 0, source: testTone)
output(bus: 1, source: delay)
}
}
@@ -0,0 +1,46 @@
// SineTone.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Stereo sine tone with runtime-updatable frequency and amplitude.
///
/// Parameters are declared as `@LiveParam` properties, backed by `ParameterNode` — a
/// lock-free atomic `AudioGenerator`. Setting a property on the main thread issues a
/// releasing atomic store; the RT thread picks up the new value at the start of the next
/// block and linearly ramps to it over the block, preventing clicks on frequency jumps.
///
/// Usage:
/// ```swift
/// let tone = SineTone()
/// try engine.add(tone)
/// Thread.sleep(forTimeInterval: 2.0)
/// tone.freq = 880.0 // no try, no string — RT-safe atomic write
/// ```
final class SineTone: SynthesizerBase {
let freq: any ValidGeneratorInput
let amp: any ValidGeneratorInput
let outbus: AudioBus
init(
freq: any ValidGeneratorInput,
amp: any ValidGeneratorInput = 0.2,
outbus: AudioBus
) {
self.freq = freq
self.amp = amp
self.outbus = outbus
super.init()
}
override func build() {
// $freq and $amp are ParameterNodes (AudioGenerator) — OscSin detects them as
// generators and requests a full per-sample interpolated block each block.
let osc = OscSin.Audio(freq: freq)
output(bus: outbus.index, source: Pan2(input: osc * amp))
}
}
@@ -0,0 +1,47 @@
// PercPitchShift.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Granular pitch-shift demo — looping PlayBuffer fed into TuneablePitchShift.Audio.
///
/// `pitchRatio` is a `@LiveParam`-backed `ParameterNode` wired directly into
/// `TuneablePitchShift.Audio`. Updating `synth.pitchRatio` on the main thread issues an
/// atomic store; the RT thread ramps to the new value at the next block boundary.
///
/// Pitch ratios:
/// 0.5 = one octave down
/// 0.75 = a minor third down
/// 1.0 = no shift (original pitch)
/// 1.5 = a perfect fifth up
/// 2.0 = one octave up
final class PercPitchShift: SynthesizerBase {
let buffer: LyrebirdBuffer
let engineSampleRate: Double
@LiveParam var pitchRatio: Double = 1.0
init(buffer: LyrebirdBuffer, engineSampleRate: Double) {
self.buffer = buffer
self.engineSampleRate = engineSampleRate
super.init()
}
override func build() {
let rateScale = buffer.nativeRateScale(engineSampleRate: engineSampleRate)
let player = PlayBuffer.Audio(buffer: buffer, loop: true, rate: rateScale)
// $pitchRatio is a ParameterNode — polled once per block by TuneablePitchShift.
let shifted = TuneablePitchShift.Audio(
input: player[0],
pitchRatio: $pitchRatio,
windowSize: 0.11,
overlap: 4,
timeDispersion: 0.01,
interpolation: .cubic
)
output(bus: 0, source: Pan2(input: shifted, mul: 0.5))
}
}
@@ -0,0 +1,66 @@
// PercTimeStretch.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Granular time-stretch demo — drives `TimeStretch.Audio` with a looping position pointer
/// that advances at a rate determined by `stretchFactor`.
///
/// - `stretchFactor > 1.0` = time stretch (e.g. 2.0 = half speed, pitch preserved)
/// - `stretchFactor = 1.0` = native speed
/// - `stretchFactor < 1.0` = time compression (e.g. 0.5 = double speed, pitch preserved)
///
/// `pos` is driven by a `Closure` that maintains a block-rate accumulator,
/// wrapping 0→1 to loop the buffer continuously. The closure is lazily initialised on
/// the first RT block so it can read `sampleRate` and `blockSize` from the live engine.
final class PercTimeStretch: SynthesizerBase {
let buffer: LyrebirdBuffer
let stretchFactor: Double
init(buffer: LyrebirdBuffer, stretchFactor: Double) {
self.buffer = buffer
self.stretchFactor = max(0.01, stretchFactor)
super.init()
}
override func build() {
let nativeDuration = Double(buffer.count) / (buffer.sampleRate ?? 44100.0)
let sf = stretchFactor
var posAccum: Double = 0.0
var posIncPerBlock: Double = 0.0
var posIncInitialized: Bool = false
let posGen = Closure { graph, _ in
if !posIncInitialized {
let sr = Double(graph.engine.sampleRate)
let blockSize = Double(graph.engine.blockSize)
// Advance pos by this much each block to traverse 0→1 in (nativeDuration*sf) sec.
posIncPerBlock = blockSize / (sr * nativeDuration * sf)
posIncInitialized = true
}
let pos = posAccum
posAccum += posIncPerBlock
if posAccum >= 1.0 { posAccum -= 1.0 }
return pos
}
let ts = TimeStretch.Audio(
buffer: buffer,
pos: posGen,
pitchRatio: 1.0,
windowSize: 0.11,
overlap: 6,
timeDispersion: 0.009,
grainDurationJitter: 0.05,
loop: true
)
ts.amp = 0.8
// Perc.aiff is mono — ts[0] picks channel 0; Pan2 centers it.
output(bus: 0, source: Pan2(input: ts, mul: 1.0))
}
}
@@ -0,0 +1,58 @@
// PercSpectralPitchShift.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Phase-vocoder spectral pitch-shift demo — PlayBuffer → SpectralChain.Audio (with SpectralPitchShift).
///
/// Signal chain:
/// 1. `PlayBuffer.Audio` reads Perc.aiff in a loop at native rate.
/// 2. `SpectralChain.Audio` bins the signal into polar (magnitude + phase) spectral
/// frames every `hopSize` samples, dispatches the registered `SpectralPitchShift`
/// processor, and resynthesises audio via overlap-add.
///
/// The phase vocoder introduces latency of approximately `fftSize` samples (≈ 43 ms at 48 kHz
/// with fftSize = 2048). Transient sharpness is reduced compared to granular pitch shifting —
/// this sounds more "smeared" but with better tonal coherence on sustained sounds.
///
/// Pitch ratios > 1.0 shift up; < 1.0 shift down. Range is (0, 4].
final class PercSpectralPitchShift: SynthesizerBase {
let buffer: LyrebirdBuffer
let pitchRatio: Double
let engineSampleRate: Double
init(buffer: LyrebirdBuffer, pitchRatio: Double = 1.5, engineSampleRate: Double) {
self.buffer = buffer
self.pitchRatio = pitchRatio
self.engineSampleRate = engineSampleRate
super.init()
}
override func build() {
let rateScale = buffer.nativeRateScale(engineSampleRate: engineSampleRate)
let player = PlayBuffer.Audio(
buffer: buffer,
loop: true,
rate: rateScale
)
let fftSize = 2048
let hopSize = 512
// SpectralPitchShift is a SpectralProcessor — runs inside SpectralChain.Audio each hop.
let shifter = SpectralPitchShift(fftSize: fftSize, hopSize: hopSize, pitchRatio: pitchRatio)
// Single Generator owns the analysis + processor + IFFT pipeline.
let chain = SpectralChain.Audio(
input: player[0],
fftSize: fftSize,
hopSize: hopSize,
stages: [.mono(shifter)]
)
output(bus: 0, source: Pan2(input: chain, mul: 0.5))
}
}
@@ -0,0 +1,58 @@
// PercSpectralStereoDiffuse.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// SpectralChain.Audio fan-out demo — mono PlayBuffer → SpectralChain.Audio
/// (with SpectralStereoDiffuse) → 2-channel decorrelated stereo output.
///
/// Signal chain:
/// 1. `PlayBuffer.Audio` reads Perc.aiff in a loop at native rate.
/// 2. `SpectralChain.Audio` runs the forward FFT once, then dispatches
/// `SpectralStereoDiffuse` as a `SpectralFanOutProcessor` to write
/// two independent destination buffers (anti-correlated phase
/// randomisation per bin, magnitudes preserved).
/// 3. Two IFFT bank channels resynthesise to a 2-channel output. The
/// chain output is multi-row — wire `chain[0]` to bus 0, `chain[1]`
/// to bus 1.
///
/// `amount = 0` is exact bypass (both channels match the input).
/// `amount = 1` is full per-channel randomisation — wide decorrelated stereo.
final class PercSpectralStereoDiffuse: SynthesizerBase {
let buffer: LyrebirdBuffer
let amount: Double
let engineSampleRate: Double
init(buffer: LyrebirdBuffer, amount: Double = 0.8, engineSampleRate: Double) {
self.buffer = buffer
self.amount = amount
self.engineSampleRate = engineSampleRate
super.init()
}
override func build() {
let rateScale = buffer.nativeRateScale(engineSampleRate: engineSampleRate)
let player = PlayBuffer.Audio(buffer: buffer, loop: true, rate: rateScale)
let fftSize = 2048
let hopSize = 512
let diffuser = SpectralStereoDiffuse(amount: amount, seed: 0xDEADBEEF)
// Fan-out path: SpectralChain.Audio runs forward FFT once, then
// populates two destination buffers via the fanOut processor, then
// runs two IFFTs to produce a 2-channel output.
let chain = SpectralChain.Audio(
input: player[0],
fftSize: fftSize,
hopSize: hopSize,
fanOut: diffuser,
mul: 0.5
)
output(bus: 0, source: chain) // 2 channels out
}
}
@@ -0,0 +1,27 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 2,
driver: CoreAudioDriver()
)
do {
try engine.start()
} catch {
print("Engine failed to start: \(error)")
exit(1)
}
BufferDemos(engine: engine).runDemo()
//ReverbDemo(engine: engine).runDemo()
engine.stop()
+24
View File
@@ -0,0 +1,24 @@
{
"originHash" : "6f06852651ad22a81b6dc75b6f4ee00fbaffb3782ac523486a02978ee45ac96b",
"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: "LyrebirdDemo",
platforms: [.macOS(.v15)],
dependencies: [
.package(path: "../.."),
],
targets: [
.executableTarget(
name: "LyrebirdDemo",
dependencies: [
.product(name: "Lyrebird", package: "LyrebirdII"),
],
path: "LyrebirdDemo"
),
]
)
@@ -0,0 +1,389 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 60;
objects = {
/* Begin PBXBuildFile section */
B9A00000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A000000000000000000007 /* main.swift */; };
B9A00000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A000000000000000000008 /* AppDelegate.swift */; };
B9A00000000000000000000E /* NoteController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A000000000000000000009 /* NoteController.swift */; };
B9A00000000000000000000F /* SineToneUI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A00000000000000000000A /* SineToneUI.swift */; };
B9A000000000000000000010 /* SineToneView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A00000000000000000000B /* SineToneView.swift */; };
B9A00000000000000000001F /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = B9A00000000000000000001D /* LyrebirdUI */; };
B9A000000000000000000030 /* SpectralBinDelayUI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A00000000000000000002D /* SpectralBinDelayUI.swift */; };
B9A000000000000000000031 /* BinDelayController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A00000000000000000002E /* BinDelayController.swift */; };
B9A000000000000000000032 /* BinDelayView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A00000000000000000002F /* BinDelayView.swift */; };
B9A000000000000000000036 /* VectorOscillatorUI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A000000000000000000033 /* VectorOscillatorUI.swift */; };
B9A000000000000000000037 /* VectorOscillatorController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A000000000000000000034 /* VectorOscillatorController.swift */; };
B9A000000000000000000038 /* VectorOscillatorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A000000000000000000035 /* VectorOscillatorView.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
B9A000000000000000000004 /* LyrebirdMacOSDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdMacOSDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
B9A000000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
B9A000000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
B9A000000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
B9A000000000000000000009 /* NoteController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NoteController.swift; sourceTree = "<group>"; };
B9A00000000000000000000A /* SineToneUI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineToneUI.swift; sourceTree = "<group>"; };
B9A00000000000000000000B /* SineToneView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineToneView.swift; sourceTree = "<group>"; };
B9A00000000000000000002D /* SpectralBinDelayUI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpectralBinDelayUI.swift; sourceTree = "<group>"; };
B9A00000000000000000002E /* BinDelayController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BinDelayController.swift; sourceTree = "<group>"; };
B9A00000000000000000002F /* BinDelayView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BinDelayView.swift; sourceTree = "<group>"; };
B9A000000000000000000033 /* VectorOscillatorUI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VectorOscillatorUI.swift; sourceTree = "<group>"; };
B9A000000000000000000034 /* VectorOscillatorController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VectorOscillatorController.swift; sourceTree = "<group>"; };
B9A000000000000000000035 /* VectorOscillatorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VectorOscillatorView.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
B9A000000000000000000012 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
B9A00000000000000000001F /* LyrebirdUI in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
B9A000000000000000000002 = {
isa = PBXGroup;
children = (
B9A000000000000000000005 /* LyrebirdMacOSDemo */,
B9A000000000000000000003 /* Products */,
);
sourceTree = "<group>";
};
B9A000000000000000000003 /* Products */ = {
isa = PBXGroup;
children = (
B9A000000000000000000004 /* LyrebirdMacOSDemo.app */,
);
name = Products;
sourceTree = "<group>";
};
B9A000000000000000000005 /* LyrebirdMacOSDemo */ = {
isa = PBXGroup;
children = (
B9A000000000000000000007 /* main.swift */,
B9A000000000000000000008 /* AppDelegate.swift */,
B9A000000000000000000020 /* UI */,
B9A000000000000000000021 /* Synthesizers */,
B9A000000000000000000006 /* Info.plist */,
);
path = LyrebirdMacOSDemo;
sourceTree = "<group>";
};
B9A000000000000000000020 /* UI */ = {
isa = PBXGroup;
children = (
B9A000000000000000000009 /* NoteController.swift */,
B9A00000000000000000000B /* SineToneView.swift */,
B9A00000000000000000002E /* BinDelayController.swift */,
B9A00000000000000000002F /* BinDelayView.swift */,
B9A000000000000000000034 /* VectorOscillatorController.swift */,
B9A000000000000000000035 /* VectorOscillatorView.swift */,
);
path = UI;
sourceTree = "<group>";
};
B9A000000000000000000021 /* Synthesizers */ = {
isa = PBXGroup;
children = (
B9A00000000000000000000A /* SineToneUI.swift */,
B9A00000000000000000002D /* SpectralBinDelayUI.swift */,
B9A000000000000000000033 /* VectorOscillatorUI.swift */,
);
path = Synthesizers;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
B9A000000000000000000014 /* LyrebirdMacOSDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = B9A000000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdMacOSDemo" */;
buildPhases = (
B9A000000000000000000011 /* Sources */,
B9A000000000000000000012 /* Frameworks */,
B9A000000000000000000013 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = LyrebirdMacOSDemo;
packageProductDependencies = (
B9A00000000000000000001D /* LyrebirdUI */,
);
productName = LyrebirdMacOSDemo;
productReference = B9A000000000000000000004 /* LyrebirdMacOSDemo.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
B9A000000000000000000001 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2620;
TargetAttributes = {
B9A000000000000000000014 = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = B9A000000000000000000018 /* Build configuration list for PBXProject "LyrebirdMacOSDemo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = B9A000000000000000000002;
packageReferences = (
B9A00000000000000000001B /* XCLocalSwiftPackageReference "../.." */,
);
productRefGroup = B9A000000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
B9A000000000000000000014 /* LyrebirdMacOSDemo */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
B9A000000000000000000013 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
B9A000000000000000000011 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
B9A00000000000000000000C /* main.swift in Sources */,
B9A00000000000000000000D /* AppDelegate.swift in Sources */,
B9A00000000000000000000E /* NoteController.swift in Sources */,
B9A00000000000000000000F /* SineToneUI.swift in Sources */,
B9A000000000000000000010 /* SineToneView.swift in Sources */,
B9A000000000000000000030 /* SpectralBinDelayUI.swift in Sources */,
B9A000000000000000000031 /* BinDelayController.swift in Sources */,
B9A000000000000000000032 /* BinDelayView.swift in Sources */,
B9A000000000000000000036 /* VectorOscillatorUI.swift in Sources */,
B9A000000000000000000037 /* VectorOscillatorController.swift in Sources */,
B9A000000000000000000038 /* VectorOscillatorView.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
B9A000000000000000000016 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdMacOSDemo/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdMacOSDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Debug;
};
B9A000000000000000000017 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
DEAD_CODE_STRIPPING = YES;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdMacOSDemo/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdMacOSDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Release;
};
B9A000000000000000000019 /* 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;
DEAD_CODE_STRIPPING = YES;
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;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
B9A00000000000000000001A /* 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;
DEAD_CODE_STRIPPING = YES;
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;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
B9A000000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdMacOSDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
B9A000000000000000000016 /* Debug */,
B9A000000000000000000017 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
B9A000000000000000000018 /* Build configuration list for PBXProject "LyrebirdMacOSDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
B9A000000000000000000019 /* Debug */,
B9A00000000000000000001A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
B9A00000000000000000001B /* XCLocalSwiftPackageReference "../.." */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ../..;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
B9A00000000000000000001D /* LyrebirdUI */ = {
isa = XCSwiftPackageProductDependency;
package = B9A00000000000000000001B /* XCLocalSwiftPackageReference "../.." */;
productName = LyrebirdUI;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = B9A000000000000000000001 /* Project object */;
}
@@ -0,0 +1,24 @@
{
"originHash" : "2f86be2113a80b402938cb09ebb72fe8cb9830066fe5b03aa1d174fcf50e2574",
"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 = "B9A000000000000000000014"
BuildableName = "LyrebirdMacOSDemo.app"
BlueprintName = "LyrebirdMacOSDemo"
ReferencedContainer = "container:LyrebirdMacOSDemo.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 = "B9A000000000000000000014"
BuildableName = "LyrebirdMacOSDemo.app"
BlueprintName = "LyrebirdMacOSDemo"
ReferencedContainer = "container:LyrebirdMacOSDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "B9A000000000000000000014"
BuildableName = "LyrebirdMacOSDemo.app"
BlueprintName = "LyrebirdMacOSDemo"
ReferencedContainer = "container:LyrebirdMacOSDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,77 @@
// AppDelegate.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AppKit
import SwiftUI
import LyrebirdSynth
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
// ──────────────────────────────────────────────────────────────────────────────
final class AppDelegate: NSObject, NSApplicationDelegate {
let engine: SynthesisEngine
// Vector oscillator demo controller (used when demo == .vector)
let vectorController: VectorOscillatorController
// Sine-tone demo controller (used when demo == .sineTone)
let sineController: NoteController
// Bin-delay demo controller (used when demo == .binDelay)
let binDelayController: BinDelayController
var window: LyrebirdWindow?
init(engine: SynthesisEngine) {
let scopeCapture = ScopeCapture(buses: [0, 1], bufferSize: 2048)
engine.scopeTap = scopeCapture
self.engine = engine
self.vectorController = VectorOscillatorController(
engine: engine,
synth: VectorOscillatorUI(),
scopeCapture: scopeCapture
)
self.sineController = NoteController(
engine: engine,
synth: SineToneUI(),
scopeCapture: scopeCapture
)
self.binDelayController = BinDelayController(
engine: engine,
scopeCapture: scopeCapture
)
}
@MainActor
func applicationDidFinishLaunching(_ notification: Notification) {
switch demo {
case .vector:
window = LyrebirdWindow(title: "Lyrebird — Vector Oscillator", width: 380, height: 580)
window?.open {
VectorOscillatorView(controller: self.vectorController)
}
case .binDelay:
window = LyrebirdWindow(title: "Lyrebird — Spectral Bin Delay", width: 440, height: 620)
window?.open {
BinDelayView(controller: self.binDelayController)
}
case .sineTone:
window = LyrebirdWindow(title: "Lyrebird — Sine Tone", width: 360, height: 540)
window?.open {
SineToneView(controller: self.sineController)
}
}
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
true
}
func applicationWillTerminate(_ notification: Notification) {
engine.stop()
}
}
@@ -0,0 +1,26 @@
<?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>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 Realized Sound. All rights reserved.</string>
</dict>
</plist>
@@ -0,0 +1,26 @@
// SineToneUI.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// A stereo sine tone whose frequency, amplitude, and pan are live-controllable from the UI.
final class SineToneUI: SynthesizerBase {
/// Frequency in Hz. Slider range: 440–880 Hz.
@UIParam var frequency: Double = 440.0
/// Output amplitude (linear gain). Knob range: 0–1.
@UIParam var amplitude: Double = 0.25
/// Stereo pan position. Knob range: -1 (hard left) … 0 (center) … +1 (hard right).
@UIParam var pan: Double = 0.0
override func build() {
let osc = OscSin.Audio(freq: $frequency)
output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
}
}
@@ -0,0 +1,108 @@
// SpectralBinDelayUI.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Spectral-bin-delay synthesizer demo.
///
/// An `Impulse.Audio` at 0.2 Hz (one fire per 5 s) drives an FFT analysis chain
/// that includes a `SpectralBinDelay`. The delayed spectral frames are resynthesised
/// via `IFFTSynthesis` and panned to centre stereo on bus 0.
///
/// Two `LyrebirdBuffer`s — `delayTimes` and `feedbacks` — are exposed as public
/// stored properties so the UI can write into them live via `MultiSlider`.
/// Both buffers are pre-allocated at `init` and never reallocated.
///
/// - Note: `sampleRate` must be passed at construction time because
/// `SpectralBinDelay` needs it to convert delay-seconds → hop-frames.
/// Create this synthesizer *after* the engine has started so that
/// `engine.sampleRate` reflects the committed hardware rate.
final class SpectralBinDelayUI: SynthesizerBase {
// MARK: - Constants
/// FFT frame size used throughout the analysis/synthesis chain.
static let fftSize: Int = 1024
/// Number of new samples between FFT hops (75 % overlap).
static let hopSize: Int = 256
/// `fftSize / 2` — the number of independent magnitude/phase bins.
static let halfSize: Int = fftSize / 2
/// Maximum delay time accepted by `SpectralBinDelay` (seconds).
/// Keep below `lyrebirdSpectralBinDelayMaxFrames * hopSize / sampleRate`.
static let maxDelaySeconds: Double = 1.0
// MARK: - Engine sample rate (captured at init — needed in build())
/// Audio sample rate in Hz. Captured from the engine before `build()` runs.
private let engineSampleRate: Double
// MARK: - Parameter buffers (public — UI writes via MultiSlider)
/// Per-bin delay times in seconds. Mono, `halfSize` frames.
/// Default: 0 (clean pass-through until the UI writes new values).
let delayTimes: LyrebirdBuffer
/// Per-bin feedback gains in [0, 0.95). Mono, `halfSize` frames.
/// Default: 0 (clean pass-through until the UI writes new values).
let feedbacks: LyrebirdBuffer
// MARK: - Initialisation
/// - Parameter sampleRate: The engine's committed sample rate (Hz).
/// `SynthesisEngine.sampleRate` is a `let` initialised in `init`, so it
/// is valid as soon as the engine is constructed.
init(sampleRate: Double) {
let halfSize = SpectralBinDelayUI.halfSize
self.engineSampleRate = sampleRate
let dt = LyrebirdBuffer(count: halfSize)
dt.fill(with: 0.0)
let fb = LyrebirdBuffer(count: halfSize)
fb.fill(with: 0.0)
self.delayTimes = dt
self.feedbacks = fb
super.init()
}
// MARK: - Signal graph
override func build() {
let fftSize = SpectralBinDelayUI.fftSize
let hopSize = SpectralBinDelayUI.hopSize
// Source: sparse impulse that fires at 0.2 Hz (once every 5 s).
let impulseFreq = 0.2
let impulse = Impulse.Audio(freq: impulseFreq)
// SpectralBinDelay processor — allocated here inside build() which
// runs off the RT thread before the synthesizer is added to the engine.
let bd = SpectralBinDelay(
fftSize: fftSize,
hopSize: hopSize,
maxDelaySeconds: SpectralBinDelayUI.maxDelaySeconds,
sampleRate: engineSampleRate,
delayTimes: delayTimes,
feedbacks: feedbacks
)
let binDelay = SpectralChain.Audio(
input: impulse,
fftSize: fftSize,
hopSize: hopSize,
stages: [.mono(bd)]
)
// Pan to centre; the effect is mono but we send it to stereo bus 0.
output(bus: 0, source: Pan2(input: binDelay, pan: 0.0))
}
}
@@ -0,0 +1,78 @@
// VectorOscillatorUI.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// A stereo vector oscillator whose XY position, frequency, and amplitude are
/// live-controllable from the UI.
///
/// Four corner wavetables are crossfaded on a 2D XY plane:
///
/// C (triangle) ── D (Hanning) (y = 1)
/// │ │
/// A (sine) ──── B (saw-ish) (y = 0)
/// x=0 x=1
///
/// Moving X blends A↔B (and C↔D); moving Y blends the AB mix into the CD mix.
final class VectorOscillatorUI: SynthesizerBase {
/// X-axis blend position. 0 = corner A/C, 1 = corner B/D.
/// Normalized [0, 1]. XY pad range: 0…1.
@UIParam var x: Double = 0.5
/// Y-axis blend position. 0 = bottom (A, B), 1 = top (C, D).
/// Normalized [0, 1]. XY pad range: 0…1.
@UIParam var y: Double = 0.5
/// Oscillator frequency in Hz. Slider range: 40–2000 Hz.
@UIParam var frequency: Double = 220.0
/// Output amplitude (linear gain). Knob range: 0–1.
@UIParam var amplitude: Double = 0.25
private let bufferA: LyrebirdBuffer // corner A: sine
private let bufferB: LyrebirdBuffer // corner B: 16-partial saw-ish
private let bufferC: LyrebirdBuffer // corner C: triangle
private let bufferD: LyrebirdBuffer // corner D: Hanning window shape
override init() {
let tableSize = lyrebirdDefaultTableSize
let a = LyrebirdBuffer(count: tableSize)
a.fillSine()
let b = LyrebirdBuffer(count: tableSize)
b.fill(partials: 16)
let c = LyrebirdBuffer(count: tableSize)
c.fillTriangle()
let d = LyrebirdBuffer(count: tableSize)
d.fillHanning()
self.bufferA = a
self.bufferB = b
self.bufferC = c
self.bufferD = d
super.init()
}
override func build() {
let osc = VectorOscillator.Audio(
bufferA: bufferA,
bufferB: bufferB,
bufferC: bufferC,
bufferD: bufferD,
freq: $frequency,
x: $x,
y: $y,
mul: $amplitude
)
output(bus: 0, source: Pan2(input: osc, pan: 0.0))
}
}
@@ -0,0 +1,74 @@
// BinDelayController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Observation
import LyrebirdSynth
/// Controller for the spectral-bin-delay demo view.
///
/// Unlike `NoteController`, the synthesizer is created lazily when the user
/// 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.
@Observable
final class BinDelayController {
let engine: SynthesisEngine
let scopeCapture: ScopeCapture
private(set) var engineRunning: Bool = false
private(set) var isPlaying: Bool = false
/// The live synthesizer instance. `nil` until first "Start Synthesizer" tap.
private(set) var synth: SpectralBinDelayUI?
init(engine: SynthesisEngine, scopeCapture: ScopeCapture) {
self.engine = engine
self.scopeCapture = scopeCapture
}
func toggleEngine() {
if engineRunning {
if isPlaying, let s = synth {
engine.remove(s)
isPlaying = false
}
engine.stop()
engineRunning = false
} else {
do {
try engine.start()
engineRunning = true
} catch {
print("Engine failed to start: \(error)")
}
}
}
func toggle() {
if isPlaying {
if let s = synth {
engine.remove(s)
}
isPlaying = false
} else {
guard engineRunning else { return }
// Create the synthesizer lazily so we don't put it in the node tree
// until the user requests it.
if synth == nil {
synth = SpectralBinDelayUI(sampleRate: engine.sampleRate)
}
if let s = synth {
do {
try engine.add(s)
isPlaying = true
} catch {
print("[Lyrebird] BinDelayController.toggle add failed: \(error)")
}
}
}
}
}
@@ -0,0 +1,123 @@
// BinDelayView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
/// Main view for the spectral bin-delay demo (macOS).
///
/// Shows engine and synth toggle buttons, two `MultiSlider` rows for
/// per-bin delay times and feedbacks, an engine status strip, and a scope.
///
/// Every spectral bin is exposed: each `MultiSlider` row contains
/// `SpectralBinDelayUI.halfSize` (512) thin bars, one per FFT bin. The window
/// is sized wide so the full spectrum is visible at once — the demo's purpose
/// is to show that per-bin spectral control is possible, not to make any one
/// bin precisely tweakable.
struct BinDelayView: View {
let controller: BinDelayController
private let sliderHeight: CGFloat = 160
private let maxFeedback = 0.95
var body: some View {
VStack(alignment: .leading, spacing: 20) {
// MARK: Engine row
HStack {
Text("Engine")
.font(.headline)
Spacer()
Button(controller.engineRunning ? "Stop Engine" : "Start Engine") {
controller.toggleEngine()
}
.buttonStyle(.borderedProminent)
.tint(controller.engineRunning ? .red : .green)
}
Divider()
// MARK: Synth row
HStack {
VStack(alignment: .leading, spacing: 2) {
Text("Spectral Bin Delay")
.font(.headline)
Text("Impulse source · 0.2 Hz · fftSize 1024 · hop 256")
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer()
Button(controller.isPlaying ? "Stop" : "Start") {
controller.toggle()
}
.buttonStyle(.bordered)
.tint(controller.isPlaying ? .red : .green)
.disabled(!controller.engineRunning)
}
Divider()
// MARK: Delay times slider
Text("Delay Times (all 512 bins, range 0–1 s)")
.font(.caption)
.foregroundStyle(.secondary)
if let synth = controller.synth {
MultiSlider(
buffer: synth.delayTimes,
count: SpectralBinDelayUI.halfSize,
range: 0.0...1.0,
height: sliderHeight
)
} else {
placeholderSlider(label: "Start synthesizer to enable")
}
// MARK: Feedback slider
Text("Feedbacks (all 512 bins, range 0–0.95)")
.font(.caption)
.foregroundStyle(.secondary)
if let synth = controller.synth {
MultiSlider(
buffer: synth.feedbacks,
count: SpectralBinDelayUI.halfSize,
range: 0.0...maxFeedback,
height: sliderHeight
)
} else {
placeholderSlider(label: "Start synthesizer to enable")
}
Divider()
LyrebirdStatusView(engine: controller.engine)
Divider()
LyrebirdScopeView(capture: controller.scopeCapture)
.frame(height: 120)
}
.padding(20)
.frame(minWidth: 1100)
}
// MARK: - Helpers
@ViewBuilder
private func placeholderSlider(label: String) -> some View {
ZStack {
Color.lyrebirdControlBackground
Text(label)
.font(.caption)
.foregroundStyle(.secondary)
}
.frame(height: sliderHeight)
.overlay(Rectangle().stroke(Color.lyrebirdSeparator, lineWidth: 1))
}
}
@@ -0,0 +1,57 @@
// NoteController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Observation
import LyrebirdSynth
@Observable
final class NoteController {
let engine: SynthesisEngine
let synth: SineToneUI
let scopeCapture: ScopeCapture
private(set) var engineRunning: Bool = false
private(set) var isPlaying: Bool = false
init(engine: SynthesisEngine, synth: SineToneUI, scopeCapture: ScopeCapture) {
self.engine = engine
self.synth = synth
self.scopeCapture = scopeCapture
}
func toggleEngine() {
if engineRunning {
if isPlaying {
engine.remove(synth)
isPlaying = false
}
engine.stop()
engineRunning = false
} else {
do {
try engine.start()
engineRunning = true
} catch {
print("Engine failed to start: \(error)")
}
}
}
func toggle() {
if isPlaying {
engine.remove(synth)
isPlaying = false
} else {
do {
try engine.add(synth)
isPlaying = true
} catch {
print("[Lyrebird] NoteController.toggle add failed: \(error)")
}
}
}
}
@@ -0,0 +1,111 @@
// SineToneView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
struct SineToneView: View {
let controller: NoteController
var body: some View {
VStack(alignment: .leading, spacing: 20) {
HStack {
Text("Engine")
.font(.headline)
Spacer()
Button(controller.engineRunning ? "Stop Engine" : "Start Engine") {
controller.toggleEngine()
}
.buttonStyle(.borderedProminent)
.tint(controller.engineRunning ? .red : .green)
}
Divider()
HStack {
Text("Sine Tone")
.font(.headline)
Spacer()
Button(controller.isPlaying ? "Stop" : "Start") {
controller.toggle()
}
.buttonStyle(.bordered)
.tint(controller.isPlaying ? .red : .green)
.disabled(!controller.engineRunning)
}
ParameterSlider(
"Frequency",
node: controller.synth.$frequency,
range: 440.0...880.0
)
HStack(spacing: 24) {
ParameterKnob(
"Amplitude",
node: controller.synth.$amplitude,
range: 0.0...1.0
)
ParameterKnob(
"Pan",
node: controller.synth.$pan,
range: -1.0...1.0
)
ParameterLabel("Level", node: controller.synth.$amplitude)
Spacer()
}
Divider()
LyrebirdStatusView(engine: controller.engine)
Divider()
LyrebirdScopeView(capture: controller.scopeCapture)
.frame(height: 120)
Divider()
Text("Envelope")
.font(.caption)
.foregroundStyle(.secondary)
LyrebirdEnvelopeView(
Envelope(
levels: [0.0001, 1, 0.6, 0.4, 0.0001],
durations: [0.05, 0.15, 0.4, 0.3],
curves: [.exponential, .exponential, .lin, .exponential],
loopNode: 2,
releaseNode: 4
),
width: 300,
height: 100
)
Divider()
Text("Distribution Preview (Gaussian, 200 samples)")
.font(.caption)
.foregroundStyle(.secondary)
LyrebirdScatterView(
DemandTemporalTendency(distribution: .gauss,
parX: .value(0.5), parY: .value(0.15),
seed: 42)
.samples(count: 200),
yRange: 0.0...1.0,
pointColor: .cyan,
width: 300,
height: 100
)
}
.padding(20)
.frame(minWidth: 340)
}
}
@@ -0,0 +1,61 @@
// VectorOscillatorController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Observation
import LyrebirdSynth
@Observable
final class VectorOscillatorController {
let engine: SynthesisEngine
let synth: VectorOscillatorUI
let scopeCapture: ScopeCapture
private(set) var engineRunning: Bool = false
private(set) var isPlaying: Bool = false
init(
engine: SynthesisEngine,
synth: VectorOscillatorUI,
scopeCapture: ScopeCapture
) {
self.engine = engine
self.synth = synth
self.scopeCapture = scopeCapture
}
func toggleEngine() {
if engineRunning {
if isPlaying {
engine.remove(synth)
isPlaying = false
}
engine.stop()
engineRunning = false
} else {
do {
try engine.start()
engineRunning = true
} catch {
print("Engine failed to start: \(error)")
}
}
}
func toggle() {
if isPlaying {
engine.remove(synth)
isPlaying = false
} else {
do {
try engine.add(synth)
isPlaying = true
} catch {
print("[Lyrebird] VectorOscillatorController.toggle add failed: \(error)")
}
}
}
}
@@ -0,0 +1,79 @@
// VectorOscillatorView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
struct VectorOscillatorView: View {
let controller: VectorOscillatorController
var body: some View {
VStack(alignment: .leading, spacing: 20) {
HStack {
Text("Engine")
.font(.headline)
Spacer()
Button(controller.engineRunning ? "Stop Engine" : "Start Engine") {
controller.toggleEngine()
}
.buttonStyle(.borderedProminent)
.tint(controller.engineRunning ? .red : .green)
}
Divider()
HStack {
Text("Vector Oscillator")
.font(.headline)
Spacer()
Button(controller.isPlaying ? "Stop" : "Start") {
controller.toggle()
}
.buttonStyle(.bordered)
.tint(controller.isPlaying ? .red : .green)
.disabled(!controller.engineRunning)
}
ParameterXY(
xLabel: "X (A↔B)",
xNode: controller.synth.$x,
xRange: 0.0...1.0,
yLabel: "Y (AB↔CD)",
yNode: controller.synth.$y,
yRange: 0.0...1.0
)
.frame(width: 240, height: 240)
HStack(spacing: 24) {
ParameterKnob(
"Frequency",
node: controller.synth.$frequency,
range: 40.0...2000.0
)
ParameterKnob(
"Amplitude",
node: controller.synth.$amplitude,
range: 0.0...1.0
)
Spacer()
}
Divider()
LyrebirdStatusView(engine: controller.engine)
Divider()
LyrebirdScopeView(capture: controller.scopeCapture)
.frame(height: 120)
}
.padding(20)
.frame(minWidth: 340)
}
}
@@ -0,0 +1,22 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AppKit
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
let delegate = AppDelegate(engine: engine)
let app = NSApplication.shared
app.setActivationPolicy(.regular)
app.delegate = delegate
app.run()
@@ -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 /* FMTone.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3C000000000000000000014 /* FMTone.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
E3C000000000000000000004 /* LyrebirdNRTDemo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = LyrebirdNRTDemo; sourceTree = BUILT_PRODUCTS_DIR; };
E3C000000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
E3C000000000000000000014 /* FMTone.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FMTone.swift; sourceTree = "<group>"; };
E3C000000000000000000017 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
E3C000000000000000000018 /* LyrebirdNRTDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdNRTDemo.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 /* LyrebirdNRTDemo */,
E3C000000000000000000003 /* Products */,
);
sourceTree = "<group>";
};
E3C000000000000000000003 /* Products */ = {
isa = PBXGroup;
children = (
E3C000000000000000000004 /* LyrebirdNRTDemo */,
);
name = Products;
sourceTree = "<group>";
};
E3C000000000000000000005 /* LyrebirdNRTDemo */ = {
isa = PBXGroup;
children = (
E3C000000000000000000006 /* main.swift */,
E3C000000000000000000016 /* Synthesizers */,
E3C000000000000000000017 /* Info.plist */,
E3C000000000000000000018 /* LyrebirdNRTDemo.entitlements */,
);
path = LyrebirdNRTDemo;
sourceTree = "<group>";
};
E3C000000000000000000016 /* Synthesizers */ = {
isa = PBXGroup;
children = (
E3C000000000000000000014 /* FMTone.swift */,
);
path = Synthesizers;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
E3C00000000000000000000A /* LyrebirdNRTDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = E3C00000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdNRTDemo" */;
buildPhases = (
E3C000000000000000000008 /* Sources */,
E3C000000000000000000009 /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = LyrebirdNRTDemo;
packageProductDependencies = (
E3C000000000000000000012 /* Lyrebird */,
);
productName = LyrebirdNRTDemo;
productReference = E3C000000000000000000004 /* LyrebirdNRTDemo */;
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 "LyrebirdNRTDemo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = E3C000000000000000000002;
packageReferences = (
E3C000000000000000000011 /* XCLocalSwiftPackageReference "../.." */,
);
productRefGroup = E3C000000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
E3C00000000000000000000A /* LyrebirdNRTDemo */,
);
};
/* End PBXProject section */
/* Begin PBXSourcesBuildPhase section */
E3C000000000000000000008 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
E3C000000000000000000007 /* main.swift in Sources */,
E3C000000000000000000015 /* FMTone.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
E3C00000000000000000000C /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = LyrebirdNRTDemo/LyrebirdNRTDemo.entitlements;
CODE_SIGN_IDENTITY = "-";
CODE_SIGN_STYLE = Manual;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdNRTDemo/Info.plist;
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdNRTDemo;
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 = LyrebirdNRTDemo/LyrebirdNRTDemo.entitlements;
CODE_SIGN_IDENTITY = "-";
CODE_SIGN_STYLE = Manual;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdNRTDemo/Info.plist;
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdNRTDemo;
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 "LyrebirdNRTDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
E3C00000000000000000000C /* Debug */,
E3C00000000000000000000D /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
E3C00000000000000000000E /* Build configuration list for PBXProject "LyrebirdNRTDemo" */ = {
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 = "LyrebirdNRTDemo"
BlueprintName = "LyrebirdNRTDemo"
ReferencedContainer = "container:LyrebirdNRTDemo.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 = "LyrebirdNRTDemo"
BlueprintName = "LyrebirdNRTDemo"
ReferencedContainer = "container:LyrebirdNRTDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "E3C00000000000000000000A"
BuildableName = "LyrebirdNRTDemo"
BlueprintName = "LyrebirdNRTDemo"
ReferencedContainer = "container:LyrebirdNRTDemo.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>LyrebirdNRTDemo writes rendered audio files to the Desktop.</string>
<key>NSDocumentsFolderUsageDescription</key>
<string>LyrebirdNRTDemo 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,50 @@
// FMTone.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// FM tone with an ASR envelope and stereo panning.
///
/// A sine modulator at `modFreq` drives the carrier frequency, producing
/// classic FM timbre. The `pan` argument places the voice in the stereo field
/// (-1 = hard left, 0 = centre, 1 = hard right).
final class FMTone: SynthesizerBase {
let carrierFreq: Double
let modFreq: Double
let modIndex: Double
let amp: Double
let pan: Double
let envelope: Envelope
init(carrierFreq: Double,
modFreq: Double = 220.0,
modIndex: Double = 3.0,
amp: Double = 0.18,
pan: Double = 0.0,
envelope: Envelope = Envelope(
levels: [0, 1, 0.7, 0],
durations: [0.02, 1.5, 0.5],
curves: [2, 0, -3.5]
)
) {
self.carrierFreq = carrierFreq
self.modFreq = modFreq
self.modIndex = modIndex
self.amp = amp
self.pan = pan
self.envelope = envelope
super.init()
}
override func build() {
let env = EnvelopeGen.Control(
envelope: envelope
)
let mod = OscSin.Audio(freq: modFreq) * (carrierFreq * modIndex)
let sig = OscSin.Audio(freq: carrierFreq + mod) * env * amp
output(bus: 0, source: Pan2(input: sig, pan: pan))
}
}
@@ -0,0 +1,93 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
// Output to the Desktop — triggers the NSDesktopFolderUsageDescription TCC prompt on first run.
let outputURL = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Desktop/nrt_output.caf")
// Render parameters.
let sampleRate: Double = 48000
let blockSize: Int = 512
let attackTime: Double = 0.02
let sustainTime: Double = 1.5
let releaseTime: Double = 0.5
let voiceLength: Double = attackTime + sustainTime + releaseTime
// Six FM voices — carrier frequencies, mod ratios, panning positions, start times.
struct VoiceSpec {
var carrier: Double
var modFreq: Double
var pan: Double
var start: Double
}
let voices: [VoiceSpec] = [
VoiceSpec(carrier: 110.0, modFreq: 55.0, pan: -0.6, start: 0.0),
VoiceSpec(carrier: 220.0, modFreq: 110.0, pan: 0.4, start: 0.25),
VoiceSpec(carrier: 330.0, modFreq: 220.0, pan: -0.2, start: 0.5),
VoiceSpec(carrier: 440.0, modFreq: 330.0, pan: 0.6, start: 0.75),
VoiceSpec(carrier: 550.0, modFreq: 110.0, pan: -0.8, start: 1.0),
VoiceSpec(carrier: 660.0, modFreq: 440.0, pan: 0.2, start: 1.25),
]
let sustainLevel: Double = 1.0 / 2.0.squareRoot() // -3 dBFS (1/√2 ≈ sustainLevel)
let interSetDelay: Double = 1.0
let tailDuration: Double = 0.1
let lastStart = voices.map(\.start).max() ?? 0.0
let totalDur = lastStart + interSetDelay + voiceLength + tailDuration
let driver = NRTDriver(outputURL: outputURL, duration: totalDur)
let engine = SynthesisEngine(
blockSize: blockSize,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
driver: driver
)
do {
for v in voices {
try engine.schedule(
FMTone(carrierFreq: v.carrier, modFreq: v.modFreq, pan: v.pan,
envelope: Envelope(
levels: [0.0, 1.0, sustainLevel, 0.0],
durations: [attackTime, sustainTime, releaseTime],
curves: [4.0, -4.0, -10.0])
),
after: v.start
)
}
for v in voices {
try engine.schedule(
FMTone(carrierFreq: v.carrier * 1.2, modFreq: v.modFreq, pan: v.pan,
envelope: Envelope(
levels: [0.0, 1.0, sustainLevel, 0.0],
durations: [attackTime, sustainTime, releaseTime],
curves: [4.0, -4.0, -10.0])
),
after: v.start + interSetDelay
)
}
} catch {
fputs("engine.schedule failed: \(error)\n", stderr)
exit(1)
}
print("Rendering \(String(format: "%.2f", totalDur)) s → \(outputURL.path)")
do {
try engine.start()
print("Done.")
} catch {
fputs("Render failed: \(error)\n", stderr)
exit(1)
}
+24
View File
@@ -0,0 +1,24 @@
{
"originHash" : "53d0f0966ba1616e4ff8eec85e7a64bec7b25b8f9158e10a7813f0cc29c5b538",
"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: "LyrebirdNRTDemo",
platforms: [.macOS(.v15)],
dependencies: [
.package(path: "../.."),
],
targets: [
.executableTarget(
name: "LyrebirdNRTDemo",
dependencies: [
.product(name: "Lyrebird", package: "LyrebirdII"),
],
path: "LyrebirdNRTDemo"
),
]
)
@@ -0,0 +1,362 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 60;
objects = {
/* 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 */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
C8D00000000000000000004 /* LyrebirdScratchDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdScratchDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
C8D00000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
C8D00000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
C8D00000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
C8D00000000000000000009 /* LyrebirdScratchDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScratchDemo.entitlements; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
C8D00000000000000000012 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
C8D0000000000000000000F /* LyrebirdUI in Frameworks */,
C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */,
C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
C8D00000000000000000002 = {
isa = PBXGroup;
children = (
C8D00000000000000000005 /* LyrebirdScratchDemo */,
C8D00000000000000000003 /* Products */,
);
sourceTree = "<group>";
};
C8D00000000000000000003 /* Products */ = {
isa = PBXGroup;
children = (
C8D00000000000000000004 /* LyrebirdScratchDemo.app */,
);
name = Products;
sourceTree = "<group>";
};
C8D00000000000000000005 /* LyrebirdScratchDemo */ = {
isa = PBXGroup;
children = (
C8D00000000000000000007 /* main.swift */,
C8D00000000000000000008 /* AppDelegate.swift */,
C8D00000000000000000006 /* Info.plist */,
C8D00000000000000000009 /* LyrebirdScratchDemo.entitlements */,
);
path = LyrebirdScratchDemo;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
C8D00000000000000000014 /* LyrebirdScratchDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratchDemo" */;
buildPhases = (
C8D00000000000000000011 /* Sources */,
C8D00000000000000000012 /* Frameworks */,
C8D00000000000000000013 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = LyrebirdScratchDemo;
packageProductDependencies = (
C8D0000000000000000001D /* LyrebirdUI */,
C8D0000000000000000001F /* LyrebirdLiveCompile */,
C8D00000000000000000020 /* LyrebirdLiveCompileUI */,
);
productName = LyrebirdScratchDemo;
productReference = C8D00000000000000000004 /* LyrebirdScratchDemo.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
C8D00000000000000000001 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2620;
TargetAttributes = {
C8D00000000000000000014 = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratchDemo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = C8D00000000000000000002;
packageReferences = (
C8D0000000000000000001B /* XCLocalSwiftPackageReference "../.." */,
C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */,
);
productRefGroup = C8D00000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
C8D00000000000000000014 /* LyrebirdScratchDemo */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
C8D00000000000000000013 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
C8D00000000000000000011 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C8D0000000000000000000C /* main.swift in Sources */,
C8D0000000000000000000D /* AppDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
C8D00000000000000000016 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements;
COMBINE_HIDPI_IMAGES = YES;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdScratchDemo/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratchDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Debug;
};
C8D00000000000000000017 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements;
COMBINE_HIDPI_IMAGES = YES;
DEAD_CODE_STRIPPING = YES;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdScratchDemo/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratchDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Release;
};
C8D00000000000000000019 /* 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;
DEAD_CODE_STRIPPING = YES;
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;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
C8D0000000000000000001A /* 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;
DEAD_CODE_STRIPPING = YES;
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;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratchDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C8D00000000000000000016 /* Debug */,
C8D00000000000000000017 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratchDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C8D00000000000000000019 /* Debug */,
C8D0000000000000000001A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
C8D0000000000000000001B /* XCLocalSwiftPackageReference "../.." */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ../..;
};
C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ../../LiveCompile;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
C8D0000000000000000001D /* LyrebirdUI */ = {
isa = XCSwiftPackageProductDependency;
package = C8D0000000000000000001B /* XCLocalSwiftPackageReference "../.." */;
productName = LyrebirdUI;
};
C8D0000000000000000001F /* LyrebirdLiveCompile */ = {
isa = XCSwiftPackageProductDependency;
package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */;
productName = LyrebirdLiveCompile;
};
C8D00000000000000000020 /* LyrebirdLiveCompileUI */ = {
isa = XCSwiftPackageProductDependency;
package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */;
productName = LyrebirdLiveCompileUI;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = C8D00000000000000000001 /* 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 = "C8D00000000000000000014"
BuildableName = "LyrebirdScratchDemo.app"
BlueprintName = "LyrebirdScratchDemo"
ReferencedContainer = "container:LyrebirdScratchDemo.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 = "Debug"
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 = "C8D00000000000000000014"
BuildableName = "LyrebirdScratchDemo.app"
BlueprintName = "LyrebirdScratchDemo"
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C8D00000000000000000014"
BuildableName = "LyrebirdScratchDemo.app"
BlueprintName = "LyrebirdScratchDemo"
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,59 @@
// AppDelegate.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AppKit
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
import LyrebirdLiveCompile
import LyrebirdLiveCompileUI
final class AppDelegate: NSObject, NSApplicationDelegate {
let engine: SynthesisEngine
let session: LiveSession
var model: LyrebirdScratchModel?
var menuController: LyrebirdScratchMenuController?
var window: LyrebirdWindow?
init(engine: SynthesisEngine) {
self.engine = engine
self.session = LiveSession(engine: engine)
}
@MainActor
func applicationDidFinishLaunching(_ notification: Notification) {
do {
try engine.start()
} catch {
print("[LyrebirdScratchDemo] Engine failed to start: \(error)")
}
let model = LyrebirdScratchModel(session: session)
self.model = model
let menuController = LyrebirdScratchMenuController(model: model)
menuController.installMainMenu()
self.menuController = menuController
window = LyrebirdWindow(
title: "Lyrebird — Live Scratch",
width: 720,
height: 560
)
window?.open {
LyrebirdScratchView(model: model)
}
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
true
}
func applicationWillTerminate(_ notification: Notification) {
engine.stop()
session.clearTracked()
}
}
@@ -0,0 +1,26 @@
<?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>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 Realized Sound. All rights reserved.</string>
</dict>
</plist>
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!--
App Sandbox is intentionally OFF.
LyrebirdScratchDemo shells out to `swiftc` at runtime to compile user-
typed Swift snippets, then calls `dlopen` on the resulting unsigned dylib.
Both operations are blocked by the macOS App Sandbox:
- `posix_spawn` / `fork` for the swiftc subprocess is disallowed in a
sandboxed process (com.apple.security.temporary-exception.mach-lookup
grants exist for specific Apple tools only, not arbitrary executables).
- `dlopen` of a dylib that was not shipped with the app bundle and is
not code-signed with a matching team ID is rejected by the sandbox.
This app is a direct-distribution developer tool, not a Mac App Store
submission. Sandbox OFF is the only viable configuration for v1.
Phase 147 polish can revisit if an XPC-worker approach is adopted.
com.apple.security.app-sandbox key is absent (defaults false).
-->
<!--
Hardened Runtime — Disable Library Validation.
With Hardened Runtime enabled (ENABLE_HARDENED_RUNTIME = YES in the
Xcode project), `dlopen` of a dylib that was not signed with the same
Team ID as the host app is rejected by the dynamic linker.
LyrebirdScratchDemo writes snippet dylibs to a per-session temp dir
via `swiftc -emit-library`; those dylibs are unsigned (swiftc does not
sign them). The `CS_ALLOW_UNSIGNED_EXECUTABLE_MEMORY` (library-
validation disable) entitlement tells the kernel to skip the
code-signing check for loaded libraries, allowing `dlopen` to succeed.
Without this entitlement the app would crash with DYLD_PRINT_LIBRARIES
reporting: "Library not loaded: ... Reason: tried: ... no suitable image
found. Did find: ... code signing blocked mmap() of '...'"
-->
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,23 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AppKit
import LyrebirdSynth
import LyrebirdLiveCompile
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
let delegate = AppDelegate(engine: engine)
let app = NSApplication.shared
app.setActivationPolicy(.regular)
app.delegate = delegate
app.run()
@@ -0,0 +1,389 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 60;
objects = {
/* Begin PBXBuildFile section */
B9C00000000000000000000B /* LyrebirdiOSDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000007 /* LyrebirdiOSDemoApp.swift */; };
B9C00000000000000000000C /* NoteController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000008 /* NoteController.swift */; };
B9C00000000000000000000D /* SineToneUI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000009 /* SineToneUI.swift */; };
B9C00000000000000000000E /* SineToneView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C00000000000000000000A /* SineToneView.swift */; };
B9C00000000000000000000F /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = B9C00000000000000000001C /* LyrebirdUI */; };
B9C000000000000000000020 /* SpectralBinDelayUI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C00000000000000000001F /* SpectralBinDelayUI.swift */; };
B9C000000000000000000022 /* BinDelayController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000021 /* BinDelayController.swift */; };
B9C000000000000000000024 /* BinDelayView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000023 /* BinDelayView.swift */; };
B9C000000000000000000028 /* VectorOscillatorUI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000025 /* VectorOscillatorUI.swift */; };
B9C000000000000000000029 /* VectorOscillatorController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000026 /* VectorOscillatorController.swift */; };
B9C00000000000000000002A /* VectorOscillatorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000027 /* VectorOscillatorView.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
B9C000000000000000000004 /* LyrebirdiOSDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdiOSDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
B9C000000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
B9C000000000000000000007 /* LyrebirdiOSDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LyrebirdiOSDemoApp.swift; sourceTree = "<group>"; };
B9C000000000000000000008 /* NoteController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NoteController.swift; sourceTree = "<group>"; };
B9C000000000000000000009 /* SineToneUI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineToneUI.swift; sourceTree = "<group>"; };
B9C00000000000000000000A /* SineToneView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineToneView.swift; sourceTree = "<group>"; };
B9C00000000000000000001F /* SpectralBinDelayUI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpectralBinDelayUI.swift; sourceTree = "<group>"; };
B9C000000000000000000021 /* BinDelayController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BinDelayController.swift; sourceTree = "<group>"; };
B9C000000000000000000023 /* BinDelayView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BinDelayView.swift; sourceTree = "<group>"; };
B9C000000000000000000025 /* VectorOscillatorUI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VectorOscillatorUI.swift; sourceTree = "<group>"; };
B9C000000000000000000026 /* VectorOscillatorController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VectorOscillatorController.swift; sourceTree = "<group>"; };
B9C000000000000000000027 /* VectorOscillatorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VectorOscillatorView.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
B9C000000000000000000011 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
B9C00000000000000000000F /* LyrebirdUI in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
B9C000000000000000000002 = {
isa = PBXGroup;
children = (
B9C000000000000000000005 /* LyrebirdiOSDemo */,
B9C000000000000000000003 /* Products */,
);
sourceTree = "<group>";
};
B9C000000000000000000003 /* Products */ = {
isa = PBXGroup;
children = (
B9C000000000000000000004 /* LyrebirdiOSDemo.app */,
);
name = Products;
sourceTree = "<group>";
};
B9C000000000000000000005 /* LyrebirdiOSDemo */ = {
isa = PBXGroup;
children = (
B9C000000000000000000007 /* LyrebirdiOSDemoApp.swift */,
B9C00000000000000000001D /* UI */,
B9C00000000000000000001E /* Synthesizers */,
B9C000000000000000000006 /* Info.plist */,
);
path = LyrebirdiOSDemo;
sourceTree = "<group>";
};
B9C00000000000000000001D /* UI */ = {
isa = PBXGroup;
children = (
B9C000000000000000000008 /* NoteController.swift */,
B9C00000000000000000000A /* SineToneView.swift */,
B9C000000000000000000021 /* BinDelayController.swift */,
B9C000000000000000000023 /* BinDelayView.swift */,
B9C000000000000000000026 /* VectorOscillatorController.swift */,
B9C000000000000000000027 /* VectorOscillatorView.swift */,
);
path = UI;
sourceTree = "<group>";
};
B9C00000000000000000001E /* Synthesizers */ = {
isa = PBXGroup;
children = (
B9C000000000000000000009 /* SineToneUI.swift */,
B9C00000000000000000001F /* SpectralBinDelayUI.swift */,
B9C000000000000000000025 /* VectorOscillatorUI.swift */,
);
path = Synthesizers;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
B9C000000000000000000013 /* LyrebirdiOSDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = B9C000000000000000000014 /* Build configuration list for PBXNativeTarget "LyrebirdiOSDemo" */;
buildPhases = (
B9C000000000000000000010 /* Sources */,
B9C000000000000000000011 /* Frameworks */,
B9C000000000000000000012 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = LyrebirdiOSDemo;
packageProductDependencies = (
B9C00000000000000000001C /* LyrebirdUI */,
);
productName = LyrebirdiOSDemo;
productReference = B9C000000000000000000004 /* LyrebirdiOSDemo.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
B9C000000000000000000001 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2620;
TargetAttributes = {
B9C000000000000000000013 = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = B9C000000000000000000017 /* Build configuration list for PBXProject "LyrebirdiOSDemo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = B9C000000000000000000002;
packageReferences = (
B9C00000000000000000001A /* XCLocalSwiftPackageReference "../.." */,
);
productRefGroup = B9C000000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
B9C000000000000000000013 /* LyrebirdiOSDemo */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
B9C000000000000000000012 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
B9C000000000000000000010 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
B9C00000000000000000000B /* LyrebirdiOSDemoApp.swift in Sources */,
B9C00000000000000000000C /* NoteController.swift in Sources */,
B9C00000000000000000000D /* SineToneUI.swift in Sources */,
B9C00000000000000000000E /* SineToneView.swift in Sources */,
B9C000000000000000000020 /* SpectralBinDelayUI.swift in Sources */,
B9C000000000000000000022 /* BinDelayController.swift in Sources */,
B9C000000000000000000024 /* BinDelayView.swift in Sources */,
B9C000000000000000000028 /* VectorOscillatorUI.swift in Sources */,
B9C000000000000000000029 /* VectorOscillatorController.swift in Sources */,
B9C00000000000000000002A /* VectorOscillatorView.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
B9C000000000000000000015 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdiOSDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdiOSDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
B9C000000000000000000016 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = LyrebirdiOSDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdiOSDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
B9C000000000000000000018 /* 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;
DEVELOPMENT_TEAM = HE5VJFE9E4;
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;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
B9C000000000000000000019 /* 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";
DEVELOPMENT_TEAM = HE5VJFE9E4;
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;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
B9C000000000000000000014 /* Build configuration list for PBXNativeTarget "LyrebirdiOSDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
B9C000000000000000000015 /* Debug */,
B9C000000000000000000016 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
B9C000000000000000000017 /* Build configuration list for PBXProject "LyrebirdiOSDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
B9C000000000000000000018 /* Debug */,
B9C000000000000000000019 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
B9C00000000000000000001A /* XCLocalSwiftPackageReference "../.." */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ../..;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
B9C00000000000000000001C /* LyrebirdUI */ = {
isa = XCSwiftPackageProductDependency;
package = B9C00000000000000000001A /* XCLocalSwiftPackageReference "../.." */;
productName = LyrebirdUI;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = B9C000000000000000000001 /* Project object */;
}
@@ -0,0 +1,24 @@
{
"originHash" : "2f86be2113a80b402938cb09ebb72fe8cb9830066fe5b03aa1d174fcf50e2574",
"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 = "B9C000000000000000000013"
BuildableName = "LyrebirdiOSDemo.app"
BlueprintName = "LyrebirdiOSDemo"
ReferencedContainer = "container:LyrebirdiOSDemo.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 = "B9C000000000000000000013"
BuildableName = "LyrebirdiOSDemo.app"
BlueprintName = "LyrebirdiOSDemo"
ReferencedContainer = "container:LyrebirdiOSDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "B9C000000000000000000013"
BuildableName = "LyrebirdiOSDemo.app"
BlueprintName = "LyrebirdiOSDemo"
ReferencedContainer = "container:LyrebirdiOSDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,33 @@
<?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>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSMicrophoneUsageDescription</key>
<string>Lyrebird uses the microphone for audio input processing.</string>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
</dict>
<key>UILaunchScreen</key>
<dict/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 Realized Sound. All rights reserved.</string>
</dict>
</plist>
@@ -0,0 +1,80 @@
// LyrebirdiOSDemoApp.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import AVFoundation
import LyrebirdSynth
import LyrebirdUI
// ── Demo selector ─────────────────────────────────────────────────────────────
// Change `demo` to `.sineTone` or `.binDelay` to switch demos.
private enum Demo { case vector, binDelay, sineTone }
private let demo: Demo = .vector
// ──────────────────────────────────────────────────────────────────────────────
@main
struct LyrebirdiOSDemoApp: App {
let engine: SynthesisEngine
// Vector oscillator demo controller (used when demo == .vector)
let vectorController: VectorOscillatorController
// Sine-tone demo controller (used when demo == .sineTone)
let sineController: NoteController
// Bin-delay demo controller (used when demo == .binDelay)
let binDelayController: BinDelayController
init() {
// Pre-activate AVAudioSession to discover the hardware's committed sample rate
// before constructing SynthesisEngine. iOS devices often lock to 48000 Hz regardless
// of the preferred rate — using the actual rate avoids pitch errors and choppy audio.
let session = AVAudioSession.sharedInstance()
try? session.setCategory(.playback, mode: .default)
try? session.setActive(true)
let sampleRate = session.sampleRate // actual hardware rate (44100 or 48000)
let driver = iOSAudioDriver()
let eng = SynthesisEngine(
blockSize: 512,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
driver: driver
)
let scopeCapture = ScopeCapture(buses: [0, 1], bufferSize: 2048)
eng.scopeTap = scopeCapture
self.engine = eng
self.vectorController = VectorOscillatorController(
engine: eng,
synth: VectorOscillatorUI(),
scopeCapture: scopeCapture
)
self.sineController = NoteController(
engine: eng,
synth: SineToneUI(),
scopeCapture: scopeCapture
)
self.binDelayController = BinDelayController(
engine: eng,
scopeCapture: scopeCapture
)
}
var body: some Scene {
WindowGroup {
switch demo {
case .vector:
VectorOscillatorView(controller: vectorController)
.onDisappear { engine.stop() }
case .binDelay:
BinDelayView(controller: binDelayController)
.onDisappear { engine.stop() }
case .sineTone:
SineToneView(controller: sineController)
.onDisappear { engine.stop() }
}
}
}
}
@@ -0,0 +1,26 @@
// SineToneUI.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// A stereo sine tone whose frequency, amplitude, and pan are live-controllable from the UI.
final class SineToneUI: SynthesizerBase {
/// Frequency in Hz. Slider range: 440–880 Hz.
@UIParam var frequency: Double = 440.0
/// Output amplitude (linear gain). Knob range: 0–1.
@UIParam var amplitude: Double = 0.25
/// Stereo pan position. Knob range: -1 (hard left) … 0 (center) … +1 (hard right).
@UIParam var pan: Double = 0.0
override func build() {
let osc = OscSin.Audio(freq: $frequency)
output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
}
}
@@ -0,0 +1,108 @@
// SpectralBinDelayUI.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Spectral-bin-delay synthesizer demo.
///
/// An `Impulse.Audio` at 0.2 Hz (one fire per 5 s) drives an FFT analysis chain
/// that includes a `SpectralBinDelay`. The delayed spectral frames are resynthesised
/// via `IFFTSynthesis` and panned to centre stereo on bus 0.
///
/// Two `LyrebirdBuffer`s — `delayTimes` and `feedbacks` — are exposed as public
/// stored properties so the UI can write into them live via `MultiSlider`.
/// Both buffers are pre-allocated at `init` and never reallocated.
///
/// - Note: `sampleRate` must be passed at construction time because
/// `SpectralBinDelay` needs it to convert delay-seconds → hop-frames.
/// Create this synthesizer *after* the engine has started so that
/// `engine.sampleRate` reflects the committed hardware rate.
final class SpectralBinDelayUI: SynthesizerBase {
// MARK: - Constants
/// FFT frame size used throughout the analysis/synthesis chain.
static let fftSize: Int = 1024
/// Number of new samples between FFT hops (75 % overlap).
static let hopSize: Int = 256
/// `fftSize / 2` — the number of independent magnitude/phase bins.
static let halfSize: Int = fftSize / 2
/// Maximum delay time accepted by `SpectralBinDelay` (seconds).
/// Keep below `lyrebirdSpectralBinDelayMaxFrames * hopSize / sampleRate`.
static let maxDelaySeconds: Double = 1.0
// MARK: - Engine sample rate (captured at init — needed in build())
/// Audio sample rate in Hz. Captured from the engine before `build()` runs.
private let engineSampleRate: Double
// MARK: - Parameter buffers (public — UI writes via MultiSlider)
/// Per-bin delay times in seconds. Mono, `halfSize` frames.
/// Default: 0 (clean pass-through until the UI writes new values).
let delayTimes: LyrebirdBuffer
/// Per-bin feedback gains in [0, 0.95). Mono, `halfSize` frames.
/// Default: 0 (clean pass-through until the UI writes new values).
let feedbacks: LyrebirdBuffer
// MARK: - Initialisation
/// - Parameter sampleRate: The engine's committed sample rate (Hz).
/// `SynthesisEngine.sampleRate` is a `let` initialised in `init`, so it
/// is valid as soon as the engine is constructed.
init(sampleRate: Double) {
let halfSize = SpectralBinDelayUI.halfSize
self.engineSampleRate = sampleRate
let dt = LyrebirdBuffer(count: halfSize)
dt.fill(with: 0.0)
let fb = LyrebirdBuffer(count: halfSize)
fb.fill(with: 0.0)
self.delayTimes = dt
self.feedbacks = fb
super.init()
}
// MARK: - Signal graph
override func build() {
let fftSize = SpectralBinDelayUI.fftSize
let hopSize = SpectralBinDelayUI.hopSize
// Source: sparse impulse that fires at 0.2 Hz (once every 5 s).
let impulseFreq = 0.2
let impulse = Impulse.Audio(freq: impulseFreq)
// SpectralBinDelay processor — allocated here inside build() which
// runs off the RT thread before the synthesizer is added to the engine.
let bd = SpectralBinDelay(
fftSize: fftSize,
hopSize: hopSize,
maxDelaySeconds: SpectralBinDelayUI.maxDelaySeconds,
sampleRate: engineSampleRate,
delayTimes: delayTimes,
feedbacks: feedbacks
)
let binDelay = SpectralChain.Audio(
input: impulse,
fftSize: fftSize,
hopSize: hopSize,
stages: [.mono(bd)]
)
// Pan to centre; the effect is mono but we send it to stereo bus 0.
output(bus: 0, source: Pan2(input: binDelay, pan: 0.0))
}
}
@@ -0,0 +1,78 @@
// VectorOscillatorUI.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// A stereo vector oscillator whose XY position, frequency, and amplitude are
/// live-controllable from the UI.
///
/// Four corner wavetables are crossfaded on a 2D XY plane:
///
/// C (triangle) ── D (Hanning) (y = 1)
/// │ │
/// A (sine) ──── B (saw-ish) (y = 0)
/// x=0 x=1
///
/// Moving X blends A↔B (and C↔D); moving Y blends the AB mix into the CD mix.
final class VectorOscillatorUI: SynthesizerBase {
/// X-axis blend position. 0 = corner A/C, 1 = corner B/D.
/// Normalized [0, 1]. XY pad range: 0…1.
@UIParam var x: Double = 0.5
/// Y-axis blend position. 0 = bottom (A, B), 1 = top (C, D).
/// Normalized [0, 1]. XY pad range: 0…1.
@UIParam var y: Double = 0.5
/// Oscillator frequency in Hz. Slider range: 40–2000 Hz.
@UIParam var frequency: Double = 220.0
/// Output amplitude (linear gain). Knob range: 0–1.
@UIParam var amplitude: Double = 0.25
private let bufferA: LyrebirdBuffer // corner A: sine
private let bufferB: LyrebirdBuffer // corner B: 16-partial saw-ish
private let bufferC: LyrebirdBuffer // corner C: triangle
private let bufferD: LyrebirdBuffer // corner D: Hanning window shape
override init() {
let tableSize = lyrebirdDefaultTableSize
let a = LyrebirdBuffer(count: tableSize)
a.fillSine()
let b = LyrebirdBuffer(count: tableSize)
b.fill(partials: 16)
let c = LyrebirdBuffer(count: tableSize)
c.fillTriangle()
let d = LyrebirdBuffer(count: tableSize)
d.fillHanning()
self.bufferA = a
self.bufferB = b
self.bufferC = c
self.bufferD = d
super.init()
}
override func build() {
let osc = VectorOscillator.Audio(
bufferA: bufferA,
bufferB: bufferB,
bufferC: bufferC,
bufferD: bufferD,
freq: $frequency,
x: $x,
y: $y,
mul: $amplitude
)
output(bus: 0, source: Pan2(input: osc, pan: 0.0))
}
}
@@ -0,0 +1,74 @@
// BinDelayController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Observation
import LyrebirdSynth
/// Controller for the spectral-bin-delay demo view.
///
/// Unlike `NoteController`, the synthesizer is created lazily when the user
/// 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.
@Observable
final class BinDelayController {
let engine: SynthesisEngine
let scopeCapture: ScopeCapture
private(set) var engineRunning: Bool = false
private(set) var isPlaying: Bool = false
/// The live synthesizer instance. `nil` until first "Start Synthesizer" tap.
private(set) var synth: SpectralBinDelayUI?
init(engine: SynthesisEngine, scopeCapture: ScopeCapture) {
self.engine = engine
self.scopeCapture = scopeCapture
}
func toggleEngine() {
if engineRunning {
if isPlaying, let s = synth {
engine.remove(s)
isPlaying = false
}
engine.stop()
engineRunning = false
} else {
do {
try engine.start()
engineRunning = true
} catch {
print("Engine failed to start: \(error)")
}
}
}
func toggle() {
if isPlaying {
if let s = synth {
engine.remove(s)
}
isPlaying = false
} else {
guard engineRunning else { return }
// Create the synthesizer lazily so we don't put it in the node tree
// until the user requests it.
if synth == nil {
synth = SpectralBinDelayUI(sampleRate: engine.sampleRate)
}
if let s = synth {
do {
try engine.add(s)
isPlaying = true
} catch {
print("[Lyrebird] BinDelayController.toggle add failed: \(error)")
}
}
}
}
}
@@ -0,0 +1,131 @@
// BinDelayView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
/// Main view for the spectral bin-delay demo (iOS).
///
/// Shows engine and synth toggle buttons, two `MultiSlider` rows for
/// per-bin delay times and feedbacks, an engine status strip, and a scope.
/// Wrapped in a vertical `ScrollView` for compact-height device compatibility;
/// each `MultiSlider` is also wrapped in a horizontal `ScrollView` so all
/// `SpectralBinDelayUI.halfSize` (512) bin bars remain draggable on narrow
/// iPhone screens. The demo's purpose is to show that per-bin spectral control
/// is possible, not to make any one bin precisely tweakable.
struct BinDelayView: View {
let controller: BinDelayController
private let sliderHeight: CGFloat = 160
private let sliderRowWidth: CGFloat = 1280
private let maxFeedback = 0.95
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
// MARK: Engine row
HStack {
Text("Engine")
.font(.headline)
Spacer()
Button(controller.engineRunning ? "Stop Engine" : "Start Engine") {
controller.toggleEngine()
}
.buttonStyle(.borderedProminent)
.tint(controller.engineRunning ? .red : .green)
}
Divider()
// MARK: Synth row
HStack {
VStack(alignment: .leading, spacing: 2) {
Text("Spectral Bin Delay")
.font(.headline)
Text("Impulse source · 0.2 Hz · fftSize 1024 · hop 256")
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer()
Button(controller.isPlaying ? "Stop" : "Start") {
controller.toggle()
}
.buttonStyle(.bordered)
.tint(controller.isPlaying ? .red : .green)
.disabled(!controller.engineRunning)
}
Divider()
// MARK: Delay times slider
Text("Delay Times (all 512 bins, range 0–1 s)")
.font(.caption)
.foregroundStyle(.secondary)
if let synth = controller.synth {
ScrollView(.horizontal, showsIndicators: true) {
MultiSlider(
buffer: synth.delayTimes,
count: SpectralBinDelayUI.halfSize,
range: 0.0...1.0,
height: sliderHeight
)
.frame(width: sliderRowWidth)
}
} else {
placeholderSlider(label: "Start synthesizer to enable")
}
// MARK: Feedback slider
Text("Feedbacks (all 512 bins, range 0–0.95)")
.font(.caption)
.foregroundStyle(.secondary)
if let synth = controller.synth {
ScrollView(.horizontal, showsIndicators: true) {
MultiSlider(
buffer: synth.feedbacks,
count: SpectralBinDelayUI.halfSize,
range: 0.0...maxFeedback,
height: sliderHeight
)
.frame(width: sliderRowWidth)
}
} else {
placeholderSlider(label: "Start synthesizer to enable")
}
Divider()
LyrebirdStatusView(engine: controller.engine)
Divider()
LyrebirdScopeView(capture: controller.scopeCapture)
.frame(height: 120)
}
.padding(20)
}
}
// MARK: - Helpers
@ViewBuilder
private func placeholderSlider(label: String) -> some View {
ZStack {
Color.lyrebirdControlBackground
Text(label)
.font(.caption)
.foregroundStyle(.secondary)
}
.frame(height: sliderHeight)
.frame(maxWidth: .infinity)
.overlay(Rectangle().stroke(Color.lyrebirdSeparator, lineWidth: 1))
}
}
@@ -0,0 +1,57 @@
// NoteController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Observation
import LyrebirdSynth
@Observable
final class NoteController {
let engine: SynthesisEngine
let synth: SineToneUI
let scopeCapture: ScopeCapture
private(set) var engineRunning: Bool = false
private(set) var isPlaying: Bool = false
init(engine: SynthesisEngine, synth: SineToneUI, scopeCapture: ScopeCapture) {
self.engine = engine
self.synth = synth
self.scopeCapture = scopeCapture
}
func toggleEngine() {
if engineRunning {
if isPlaying {
engine.remove(synth)
isPlaying = false
}
engine.stop()
engineRunning = false
} else {
do {
try engine.start()
engineRunning = true
} catch {
print("Engine failed to start: \(error)")
}
}
}
func toggle() {
if isPlaying {
engine.remove(synth)
isPlaying = false
} else {
do {
try engine.add(synth)
isPlaying = true
} catch {
print("[Lyrebird] NoteController.toggle add failed: \(error)")
}
}
}
}
@@ -0,0 +1,112 @@
// SineToneView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
struct SineToneView: View {
let controller: NoteController
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
HStack {
Text("Engine")
.font(.headline)
Spacer()
Button(controller.engineRunning ? "Stop Engine" : "Start Engine") {
controller.toggleEngine()
}
.buttonStyle(.borderedProminent)
.tint(controller.engineRunning ? .red : .green)
}
Divider()
HStack {
Text("Sine Tone")
.font(.headline)
Spacer()
Button(controller.isPlaying ? "Stop" : "Start") {
controller.toggle()
}
.buttonStyle(.bordered)
.tint(controller.isPlaying ? .red : .green)
.disabled(!controller.engineRunning)
}
ParameterSlider(
"Frequency",
node: controller.synth.$frequency,
range: 440.0...880.0
)
HStack(spacing: 24) {
ParameterKnob(
"Amplitude",
node: controller.synth.$amplitude,
range: 0.0...1.0
)
ParameterKnob(
"Pan",
node: controller.synth.$pan,
range: -1.0...1.0
)
ParameterLabel("Level", node: controller.synth.$amplitude)
Spacer()
}
Divider()
LyrebirdStatusView(engine: controller.engine)
Divider()
LyrebirdScopeView(capture: controller.scopeCapture)
.frame(height: 120)
Divider()
Text("Envelope")
.font(.caption)
.foregroundStyle(.secondary)
LyrebirdEnvelopeView(
Envelope(
levels: [0.0001, 1, 0.6, 0.4, 0.0001],
durations: [0.05, 0.15, 0.4, 0.3],
curves: [.exponential, .exponential, .lin, .exponential],
loopNode: 2,
releaseNode: 4
),
width: 300,
height: 100
)
Divider()
Text("Distribution Preview (Gaussian, 200 samples)")
.font(.caption)
.foregroundStyle(.secondary)
LyrebirdScatterView(
DemandTemporalTendency(distribution: .gauss,
parX: .value(0.5), parY: .value(0.15),
seed: 42)
.samples(count: 200),
yRange: 0.0...1.0,
pointColor: .cyan,
width: 300,
height: 100
)
}
.padding(20)
}
}
}
@@ -0,0 +1,61 @@
// VectorOscillatorController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Observation
import LyrebirdSynth
@Observable
final class VectorOscillatorController {
let engine: SynthesisEngine
let synth: VectorOscillatorUI
let scopeCapture: ScopeCapture
private(set) var engineRunning: Bool = false
private(set) var isPlaying: Bool = false
init(
engine: SynthesisEngine,
synth: VectorOscillatorUI,
scopeCapture: ScopeCapture
) {
self.engine = engine
self.synth = synth
self.scopeCapture = scopeCapture
}
func toggleEngine() {
if engineRunning {
if isPlaying {
engine.remove(synth)
isPlaying = false
}
engine.stop()
engineRunning = false
} else {
do {
try engine.start()
engineRunning = true
} catch {
print("Engine failed to start: \(error)")
}
}
}
func toggle() {
if isPlaying {
engine.remove(synth)
isPlaying = false
} else {
do {
try engine.add(synth)
isPlaying = true
} catch {
print("[Lyrebird] VectorOscillatorController.toggle add failed: \(error)")
}
}
}
}
@@ -0,0 +1,80 @@
// VectorOscillatorView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
struct VectorOscillatorView: View {
let controller: VectorOscillatorController
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
HStack {
Text("Engine")
.font(.headline)
Spacer()
Button(controller.engineRunning ? "Stop Engine" : "Start Engine") {
controller.toggleEngine()
}
.buttonStyle(.borderedProminent)
.tint(controller.engineRunning ? .red : .green)
}
Divider()
HStack {
Text("Vector Oscillator")
.font(.headline)
Spacer()
Button(controller.isPlaying ? "Stop" : "Start") {
controller.toggle()
}
.buttonStyle(.bordered)
.tint(controller.isPlaying ? .red : .green)
.disabled(!controller.engineRunning)
}
ParameterXY(
xLabel: "X (A↔B)",
xNode: controller.synth.$x,
xRange: 0.0...1.0,
yLabel: "Y (AB↔CD)",
yNode: controller.synth.$y,
yRange: 0.0...1.0
)
.frame(width: 240, height: 240)
HStack(spacing: 24) {
ParameterKnob(
"Frequency",
node: controller.synth.$frequency,
range: 40.0...2000.0
)
ParameterKnob(
"Amplitude",
node: controller.synth.$amplitude,
range: 0.0...1.0
)
Spacer()
}
Divider()
LyrebirdStatusView(engine: controller.engine)
Divider()
LyrebirdScopeView(capture: controller.scopeCapture)
.frame(height: 120)
}
.padding(20)
}
}
}
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+282
View File
@@ -0,0 +1,282 @@
# Lyrebird — Installation & Usage
How to add Lyrebird to a project and scaffold the five kinds of app it supports: real-time, real-time + UI, non-real-time (offline) render, AUv3 plugin, and iOS.
The package is hosted at <https://realizedsound.mooo.com/josh/Lyrebird>.
---
## Requirements
| Platform | OS | Xcode | Swift |
|---|---|---|---|
| macOS | 15+ | 16+ | 6.0 |
| iOS | 18+ | 16+ | 6.0 |
The macOS 15 / iOS 18 floor is hard: Lyrebird's lock-free queues use `Synchronization.Atomic`, which is unavailable earlier.
---
## Adding the package
### Swift Package Manager (`Package.swift`)
```swift
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "MyPiece",
platforms: [.macOS(.v15), .iOS(.v18)],
dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"),
],
targets: [
.executableTarget(
name: "MyPiece",
dependencies: [
.product(name: "Lyrebird", package: "Lyrebird"),
.product(name: "LyrebirdUI", package: "Lyrebird"), // only if you need the GUI module
]),
]
)
```
The package vends three products:
| Product | Kind | Use |
|---|---|---|
| `Lyrebird` | dynamic library | Core framework — Generators, Synthesizers, engine, drivers. |
| `LyrebirdUI` | library | SwiftUI parameter controls (`ParameterKnob`, scope/envelope views, `LyrebirdWindow`). |
| `LyrebirdCLI` | executable | The `lyrebird` command-line tool (scaffolding, REPL). |
### In Xcode
**File ▸ Add Package Dependencies…**, paste the repository URL, choose **Up to Next Major Version** from `1.0.0`, and add the `Lyrebird` (and optionally `LyrebirdUI`) products to your target.
### Local checkout (development)
To build against a local clone instead of the remote, use a path dependency:
```swift
.package(name: "Lyrebird", path: "/Users/me/Documents/LyrebirdII")
```
The scaffolder (below) does this automatically with `--lyrebird-path`.
### The dynamic-library note
`Lyrebird` is declared `type: .dynamic` in `Package.swift`. This is a deliberate workaround for an Xcode 26 SwiftPM regression and will revert to `.static` once that is fixed. If you hit `dyld: Library not loaded` under a hardened runtime (sandboxed app or AUv3 extension), add to your entitlements:
```xml
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
```
then clean-build (⇧⌘K). The generated Xcode-project templates already do this; the workspace also sets `SWIFT_USE_INTEGRATED_DRIVER = NO` and `parallelizeBuildables = NO`.
---
## The `lyrebird` CLI
Project scaffolding goes through the `lyrebird` CLI. Install it once onto your `$PATH`:
```bash
swift build -c release --product LyrebirdCLI
cp .build/release/LyrebirdCLI /usr/local/bin/lyrebird
lyrebird --version # verify
```
(From a checkout you can also use `swift run lyrebird …` without installing.)
| Command | Purpose |
|---|---|
| `lyrebird new <name> [--template <t>] [--lyrebird-path <p>]` | Scaffold a new project. |
| `lyrebird run [--release]` | Build and run the project in the current directory. |
| `lyrebird export <name> [--to <p>] [--overwrite]` | Emit a standalone `SynthesizerBase` template file. |
| `lyrebird install-templates [--force]` | Install the Xcode file templates (New File… ▸ Lyrebird). |
| `lyrebird uninstall-templates` | Remove them. |
| `lyrebird repl` | Swift REPL with `import LyrebirdSynth` available. |
| `lyrebird` (no args) | Interactive `lyrebird>` shell. |
Full reference: [`docs/tooling/cli-guide.md`](docs/tooling/cli-guide.md).
---
## Generating projects
`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` |
| `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` |
| `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` |
After scaffolding:
```bash
open <name>/<name>.xcworkspace # SPM-only & Xcode-project templates both ship a workspace
# or, for the SPM-only ones:
cd <name> && lyrebird run
```
To develop against a local Lyrebird checkout instead of the remote URL (path dependency + an `XCLocalSwiftPackageReference` in the generated project):
```bash
lyrebird new <name> --template <t> --lyrebird-path /Users/me/Documents/LyrebirdII
```
### 1. Real-time
```bash
lyrebird new MyPiece --template demo
cd MyPiece && lyrebird run
```
`main.swift` boots a `CoreAudioDriver`, starts the engine, and adds a synth. The shape is:
```swift
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver())
try engine.start()
try engine.add(SineTone())
RunLoop.main.run() // keep the process alive while audio runs
```
### 2. Real-time with UI
```bash
# SPM-only AppKit window:
lyrebird new MyApp --template ui-demo
# or a full macOS .app bundle:
lyrebird new MyApp --template macos-ui-xcode
```
UI templates depend on `LyrebirdUI` and drive parameters with `@UIParam` (SwiftUI-bindable) instead of `@LiveParam`. A knob binds straight to the projected parameter:
```swift
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
struct ContentView: View {
@StateObject var synth = ToneSynth() // ToneSynth: SynthesizerBase with @UIParam
var body: some View {
ParameterKnob(value: synth.$frequency, in: 50...2000, label: "Freq")
}
}
```
### 3. Non-real-time (offline render)
```bash
lyrebird new MyRender --template nrt
cd MyRender && lyrebird run # writes output.caf
```
Identical graph code as real-time — only the driver changes. `NRTDriver` runs `processBlock` in a tight loop (faster than real time) and writes a CAF file:
```swift
let driver = NRTDriver(outputURL: outputURL, duration: totalDuration)
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
driver: driver)
try engine.schedule(FMTone(carrierFreq: 440), after: 0.0)
try engine.schedule(FMTone(carrierFreq: 660), after: 2.5) // sample-accurate
try engine.start() // blocks until `duration` is rendered, then closes the file
```
For batch offline rendering across cores, see `EngineHost.renderConcurrent(jobs:maxConcurrent:)` in [`docs/tooling/nrt-guide.md`](docs/tooling/nrt-guide.md).
### 4. AU plugin (AUv3)
```bash
lyrebird new MyPlugin --template auv3
open MyPlugin/MyPlugin.xcworkspace
```
This generates a host `.app` plus an `aumu` `.appex` extension. Run the host app once to register the extension with the system; it then loads in Logic, GarageBand, AUM, Loopy Pro, etc.
Your DSP is an ordinary `SynthesizerBase`; you expose it by subclassing `LyrebirdAudioUnit` and declaring parameter metadata:
```swift
import LyrebirdSynth
final class MyFMSynth: SynthesizerBase {
@LiveParam var carrierFreq: Double = 440
@LiveParam var modIndex: Double = 0.5
override func build() {
let mod = OscSin.Audio(freq: $carrierFreq * 2, mul: $modIndex * $carrierFreq)
let car = OscSin.Audio(freq: $carrierFreq + mod)
output(bus: 0, source: car * 0.3)
}
}
public final class MyFMSynthAudioUnit: LyrebirdAudioUnit {
public override class func makeSynthesizer() -> SynthesizerBase { MyFMSynth() }
public override class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] {
[
"carrierFreq": .init(min: 20, max: 8000, unit: .hertz),
"modIndex": .init(min: 0, max: 4),
]
}
}
```
`LyrebirdAudioUnit` provides the parameter tree, bus topology, the host-driven `internalRenderBlock` (via the passive `AUv3Driver` + `AUv3RingBuffer` fixed-block→variable-frame adapter), `fullState` preset save/restore, MIDI dispatch, and an optional `LyrebirdSynthView` SwiftUI parameter grid. Full guide: `Sources/Lyrebird/Lyrebird.docc/AUv3.md`. The reference plugin is [`Demos/LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/).
### 5. iOS
```bash
lyrebird new MyApp --template ios-ui
open MyApp/MyApp.xcworkspace # set your signing team, then run on device/simulator
```
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/).
---
## 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:
```bash
lyrebird install-templates # New File… ▸ Lyrebird section appears in Xcode
lyrebird uninstall-templates
```
From a repo checkout you can equivalently run `bash scripts/install-xcode-templates.sh` (`--dry-run` to preview). Catalog: [`docs/tooling/xcode-templates.md`](docs/tooling/xcode-templates.md).
---
## 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:
| Demo | Mirrors template |
|---|---|
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | real-time CLI |
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | `macos-ui-xcode` |
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | `ios-ui` |
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | `nrt` |
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | `auv3` |
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | live-coding scratchpad |
See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for per-demo notes and gotchas.
+16 -13
View File
@@ -1,18 +1,21 @@
MIT License
Copyright (c) 2026 josh
Copyright (c) 2026 Joshua Parmenter / realizedsound
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+188
View File
@@ -0,0 +1,188 @@
# 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.
---
## 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.
Once open, pick a scheme from the scheme picker at the top of the Xcode window and hit Run.
---
## The Six Demos
### 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
You can also run this from the terminal: `cd Demos/LyrebirdDemo && swift run`
---
### LyrebirdMacOSDemo — macOS GUI App
A SwiftUI app with a live oscilloscope, parameter knobs, and real-time audio.
- **Where to add synthesizers:** `Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/Synthesizers/` — `SineToneUI.swift` is the example
- **UI binding:** mark synthesizer properties with `@UIParam` and they auto-appear as knobs in the window. No extra wiring needed.
- **Scope:** `LyrebirdScopeView` is already wired — it shows the first two output channels of whatever is playing
```swift
final class MySynth: SynthesizerBase {
@UIParam var freq: LyrebirdFloat = 440.0
@UIParam var amp: LyrebirdFloat = 0.5
override func build() {
let sig = OscSin.Audio(freq: freq) * amp
output(bus: 0, source: Pan2(input: sig, pan: 0))
}
}
```
---
### LyrebirdiOSDemo — iOS App
A SwiftUI app using `iOSAudioDriver` (RemoteIO). Same `@UIParam` knob system as the macOS demo.
- **Where to add synthesizers:** `Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Synthesizers/`
- **Critical:** `AVAudioSession` must be activated **before** creating `SynthesisEngine`. The demo's `LyrebirdiOSDemoApp.swift` does this — keep that order when adding setup code or the engine will pick up the wrong sample rate.
```swift
// Correct order — do not rearrange:
try AVAudioSession.sharedInstance().setCategory(.playback)
try AVAudioSession.sharedInstance().setActive(true) // ← must come first
let engine = SynthesisEngine(...)
```
- Simulator has no audio output — run on device for sound
---
### LyrebirdNRTDemo — Offline Renderer
A command-line tool that renders audio to a CAF file without playing anything in real time. Useful for batch rendering, testing synthesizer graphs, or processing existing audio.
- **Output file:** `~/Desktop/nrt_output.caf` — open in any DAW or QuickTime after running
- **First run:** macOS will prompt for Desktop folder access. Click Allow. If you dismiss it by mistake, re-enable in System Settings → Privacy & Security → Files and Folders.
- **Where to add synthesizers:** `Demos/LyrebirdNRTDemo/LyrebirdNRTDemo/Synthesizers/` — `FMTone.swift` is the example
- **Schedule voices:** in `main.swift`, call `engine.schedule(MySynth(), after: startTime)`
**Soundfile input:** pass a source file to `NRTDriver` and it feeds audio into the engine's input buses block-by-block, exactly like a microphone would in real time:
```swift
let driver = NRTDriver(
outputURL: outputURL,
duration: 5.0,
inputURL: URL(fileURLWithPath: "/path/to/source.wav"),
inputStartOffset: 2.0 // skip first 2 seconds
)
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 2, // must be ≥ channel count of source file
driver: driver
)
```
Read input channels inside a synthesizer using raw bus indices:
```swift
// Input channel 0 with numOutputChannels=2 → raw bus index 2
let left = In.Audio(bus: 2) // numOutputChannels + 0
let right = In.Audio(bus: 3) // numOutputChannels + 1
```
`ExtAudioFile` handles sample-rate conversion automatically if the source file's rate differs from the engine's. Channels beyond what the file contains stay silent.
---
### 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.
- **First run:** build & run the container app once. macOS registers the embedded extension on launch; after that, every AUv3 host on the machine can see the plugin.
- **Validate from the terminal:** `auval -v aumu LBFM RLZS` should print `PASS`.
- **Where to add synthesizers:** `Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/` — `LyrebirdFM.swift` is the `SynthesizerBase` subclass; `LyrebirdFMAudioUnit.swift` is the `LyrebirdAudioUnit` wrapper.
- **Copy as a template:** see `Demos/LyrebirdAUv3Demo/README.md` for the step-by-step on duplicating this directory to ship your own AUv3 plugin (4-char component subtype, manufacturer code, signing, etc.).
- **Not yet wired in the template:** MIDI input, SwiftUI parameter UI in the view controller, source-slot preset save/restore, effect-type AU (`aufx`), iOS container. The framework supports them all — see [`Sources/Lyrebird/Lyrebird.docc/AUv3.md`](Sources/Lyrebird/Lyrebird.docc/AUv3.md) for the hooks.
---
### LyrebirdScratchDemo — Live-Coding Scratchpad
A macOS app that compiles a typed Swift snippet against the live engine at ⌘↩. Backed by `LyrebirdScratchView` and `LiveSession` from the `LyrebirdLiveCompile` SPM target.
**v1 surface:**
- 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.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 additive. Prior synths stay in the engine.
- **Clear Synths** toolbar button — removes all tracked synths 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.
**Dylib lifetime:** loaded dylibs are never unloaded. `Synthesizer` instances reference types from the dylib; unloading while they are active would crash. Every ⌘↩ evaluation writes a new uniquely-named dylib to a per-session temp dir. This is intentional v1 behaviour; a future release may revisit with an XPC worker approach.
**Not yet implemented:** syntax highlighting, line-number gutter, snippet save/load, multi-snippet tabs, async compile (editor does not freeze during compilation in v1 — swiftc blocks the main actor for the duration of the compile).
---
## Adding a Synthesizer (Any Demo)
1. Create a file in the demo's `Synthesizers/` folder
2. Add it to the Xcode target's Sources build phase (select the target, Build Phases → Compile Sources → `+`)
3. Subclass `SynthesizerBase` and implement `build()`
```swift
import LyrebirdSynth
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
}
}
```
---
## Common Gotchas
| Symptom | Cause | Fix |
|---------|-------|-----|
| `dyld: Library not loaded: @rpath/Lyrebird.framework` | Hardened Runtime's Library Validation rejects the ad-hoc–signed SPM framework | Check that the target's entitlements file contains `com.apple.security.cs.disable-library-validation = true`. Then do Product → Clean Build Folder (⇧⌘K) — Xcode may be launching a cached binary. |
| Desktop file never appears / TCC prompt didn't show | macOS denied Desktop access on first run | System Settings → Privacy & Security → Files and Folders → find the demo and re-enable |
| iOS audio wrong pitch or silent | `AVAudioSession` not activated before engine init | Activate session first — see the iOS demo note above |
| NRT input buses are silent | `In.Audio(bus: n)` uses raw engine bus index | Input channel `n` lives at raw index `numOutputChannels + n`, not `n` |
| Build fails with Swift driver errors | Xcode 26 integrated driver bug | Already worked around in the workspace: `SWIFT_USE_INTEGRATED_DRIVER = NO`, `parallelizeBuildables = NO`, `type: .dynamic` on the Lyrebird library product in `Package.swift` |
---
## Going Deeper
| Topic | Doc |
|-------|-----|
| Engine setup and Core Audio | `docs/engine/synthesis-engine.md` |
| Bus system, In/Out generators | `docs/engine/bus-system.md` |
| Sample-accurate scheduling | `docs/engine/scheduling.md` |
| Generator protocol | `docs/protocols/generator.md` |
| Synthesizer and node tree | `docs/protocols/synthesizer.md` |
| All built-in generators | `docs/stdlib/generators.md` |
| NRT / offline rendering | `docs/tooling/nrt-guide.md` |
| REPL / hot-swap | `docs/tooling/repl.md` |
| Xcode file templates | `docs/tooling/xcode-templates.md` |
| GUI / parameter binding | `docs/ui/gui-system.md` |
| Hard constraints and code style | `CLAUDE.md` |
+24
View File
@@ -0,0 +1,24 @@
{
"originHash" : "1218ecb219f6537e88aa0b013852ec55f6192d2c5a21bdbf7c3c0a1f8438a7e9",
"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
}
+72
View File
@@ -0,0 +1,72 @@
// Package.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// swift-tools-version: 6.0
import PackageDescription
// Phase 167 — `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
// classes (which caused ObjC class double-registration during `swift test`
// in the single-package layout).
//
// macOS-only — the host swiftc-shell-out + dlopen surface cannot run on iOS.
let package = Package(
name: "LyrebirdLiveCompile",
platforms: [.macOS(.v15)],
products: [
.library(
name: "LyrebirdLiveCompile",
type: .dynamic,
targets: ["LyrebirdLiveCompile"]
),
.library(
name: "LyrebirdLiveCompileUI",
targets: ["LyrebirdLiveCompileUI"]
),
],
dependencies: [
.package(name: "Lyrebird", path: "..")
],
targets: [
.target(
name: "LyrebirdLiveCompile",
dependencies: [
.product(name: "Lyrebird", package: "Lyrebird"),
],
path: "Sources/LyrebirdLiveCompile"
),
.target(
name: "LyrebirdLiveCompileUI",
dependencies: [
"LyrebirdLiveCompile",
.product(name: "Lyrebird", package: "Lyrebird"),
],
path: "Sources/LyrebirdLiveCompileUI",
swiftSettings: [.swiftLanguageMode(.v5)]
),
.testTarget(
name: "LyrebirdLiveCompileTests",
dependencies: [
"LyrebirdLiveCompile",
.product(name: "Lyrebird", package: "Lyrebird"),
],
path: "Tests/LyrebirdLiveCompileTests"
),
.testTarget(
name: "LyrebirdLiveCompileUITests",
dependencies: [
"LyrebirdLiveCompile",
"LyrebirdLiveCompileUI",
.product(name: "Lyrebird", package: "Lyrebird"),
],
path: "Tests/LyrebirdLiveCompileUITests",
swiftSettings: [.swiftLanguageMode(.v5)]
),
]
)
@@ -0,0 +1,57 @@
// CompiledSnippet.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 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
// the process — dylib unload is unsafe while live `Synth` instances may still
// reference types defined in the dylib. (See plan in
// `memory/project_live_compile_phases.md` non-goals.)
import Foundation
#if os(macOS)
/// Handle to one successfully compiled and loaded snippet.
///
/// Intentionally a `final class` (not a `struct`): owning the `dlopen` handle
/// via reference identity means moves / copies cannot duplicate or accidentally
/// drop ownership. There is no `deinit` that calls `dlclose` — see the file
/// header.
///
/// `@unchecked Sendable`: every stored field is `let`; the `dlopen` handle and
/// the resolved entry pointer are both thread-safe to hold and read after the
/// compile completes (the loader serialises symbol resolution). Allows
/// `LiveSession.compileAndRunAsync` to return one across a `Task.detached`
/// boundary.
public final class CompiledSnippet: @unchecked Sendable {
/// Module name passed to `swiftc -module-name`; useful for diagnostics.
public let moduleName: String
/// Path to the dylib that was `dlopen`'d.
public let dylibPath: String
/// Resolved entry function pointer. Calling this is Phase 143's job.
public let entry: SnippetEntry
/// Raw `dlopen` handle. Kept so the OS keeps the dylib mapped.
public let handle: UnsafeMutableRawPointer
init(
moduleName: String,
dylibPath: String,
entry: SnippetEntry,
handle: UnsafeMutableRawPointer
) {
self.moduleName = moduleName
self.dylibPath = dylibPath
self.entry = entry
self.handle = handle
}
}
#endif
@@ -0,0 +1,52 @@
// Diagnostic.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
//
// 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
// margin gutter using `(line, column)` directly.
#if os(macOS)
public struct Diagnostic: Equatable, Sendable {
/// 1-based line number in the **user's** snippet body. May be `nil` when the
/// diagnostic landed inside the harness preamble (i.e. the wrapped line
/// number is less than `userBodyLineOffset`) — that almost always points at
/// the user importing a missing module or otherwise breaking the preamble.
public let line: Int?
/// 1-based column number. swiftc emits the same column for preamble and
/// user-body lines, so no translation is needed.
public let column: Int
public let severity: DiagnosticSeverity
public let message: String
/// 1-based line number swiftc actually reported, before user-coordinate
/// translation. Useful for debugging the parser; not surfaced to end users.
public let rawLine: Int
public init(
line: Int?,
column: Int,
severity: DiagnosticSeverity,
message: String,
rawLine: Int
) {
self.line = line
self.column = column
self.severity = severity
self.message = message
self.rawLine = rawLine
}
}
#endif
@@ -0,0 +1,101 @@
// DiagnosticParser.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
//
// `DiagnosticParser.parse(stderr:userBodyLineOffset:)` walks the swiftc stderr
// stream line by line, extracts diagnostics matching the standard
// `<path>:<line>:<column>: <severity>: <message>` shape, and re-maps line
// numbers from wrapped-snippet coordinates back to user-snippet coordinates.
//
// swiftc stderr format (one diagnostic):
//
// /tmp/.../Snippet.swift:7:14: error: cannot convert value of type 'String' to 'Int'
// 7 | let x: Int = "nope"
// | `- error: cannot convert value of type 'String' to 'Int'
//
// We pick up the first line (the location/severity/message header) and ignore
// the source-context lines that follow.
import Foundation
#if os(macOS)
public enum DiagnosticParser {
/// Compiled once at first access. Pattern matches the standard swiftc
/// header line: `<path>:<line>:<column>: <severity>: <message>`.
/// `try!` is safe — the pattern is a compile-time literal that cannot fail
/// `NSRegularExpression`'s validator.
private static let _headerRegex: NSRegularExpression = {
// swiftlint:disable:next force_try
try! NSRegularExpression(
pattern: #"^(.+?):(\d+):(\d+):\s+(error|warning|note):\s+(.*)$"#
)
}()
/// Parse swiftc stderr into a list of structured diagnostics, with line
/// numbers translated to user-snippet coordinates.
///
/// - Parameters:
/// - stderr: Raw swiftc stderr text. May be empty.
/// - userBodyLineOffset: 1-based line on which the user's body starts in
/// the wrapped source — typically `SnippetHarness.wrap(userBody:).userBodyLineOffset`.
/// Diagnostics on `rawLine >= userBodyLineOffset` are mapped to
/// `rawLine - (userBodyLineOffset - 1)`; diagnostics on earlier lines
/// keep `line = nil` to signal "in the harness preamble".
/// - Returns: One `Diagnostic` per matched header line, in stderr order.
public static func parse(stderr: String, userBodyLineOffset: Int) -> [Diagnostic] {
var result: [Diagnostic] = []
for rawLine: String.SubSequence in stderr.split(separator: "\n", omittingEmptySubsequences: false) {
guard let diag: Diagnostic = parseLine(String(rawLine), userBodyLineOffset: userBodyLineOffset) else {
continue
}
result.append(diag)
}
return result
}
/// Parse one stderr line. Returns `nil` for non-header lines (source-context
/// rows, caret markers, blank lines).
static func parseLine(_ rawLine: String, userBodyLineOffset: Int) -> Diagnostic? {
// Pattern (anchored):
// <path>:<line>:<column>: <severity>: <message>
// Where <path> contains no colon-space combos, and <severity> ∈ {error, warning, note}.
//
// The path may legally contain `:` on macOS (filesystem allows it), so use a
// greedy-then-validate approach: scan from the right for the third-from-last
// `:` and split on that. Cheaper: regex with a non-greedy path segment.
let range: NSRange = NSRange(rawLine.startIndex..<rawLine.endIndex, in: rawLine)
guard let match: NSTextCheckingResult = _headerRegex.firstMatch(in: rawLine, range: range),
match.numberOfRanges == 6,
let lineRange: Range<String.Index> = Range(match.range(at: 2), in: rawLine),
let colRange: Range<String.Index> = Range(match.range(at: 3), in: rawLine),
let severityRange: Range<String.Index> = Range(match.range(at: 4), in: rawLine),
let messageRange: Range<String.Index> = Range(match.range(at: 5), in: rawLine),
let rawLineNumber: Int = Int(rawLine[lineRange]),
let column: Int = Int(rawLine[colRange]),
let severity: DiagnosticSeverity = DiagnosticSeverity(rawValue: String(rawLine[severityRange]))
else { return nil }
let userLine: Int?
if rawLineNumber >= userBodyLineOffset {
userLine = rawLineNumber - (userBodyLineOffset - 1)
} else {
userLine = nil
}
return Diagnostic(
line: userLine,
column: column,
severity: severity,
message: String(rawLine[messageRange]),
rawLine: rawLineNumber
)
}
}
#endif
@@ -0,0 +1,19 @@
// DiagnosticSeverity.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
//
// Severity classifier for a parsed swiftc diagnostic line.
#if os(macOS)
public enum DiagnosticSeverity: String, Equatable, Sendable {
case error
case warning
case note
}
#endif
@@ -0,0 +1,51 @@
// LiveCompileError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core
//
// Errors raised by `LiveCompiler.compile(source:)`. RT path never sees these:
// compilation is a main-thread (or background-queue) operation that runs long
// before any audio block.
import Foundation
#if os(macOS)
public enum LiveCompileError: Error, CustomStringConvertible, Equatable, Sendable {
/// `xcrun -f swiftc` and the fallback paths all failed.
case swiftcNotFound
/// `swiftc` exited non-zero. `stderr` carries the raw compiler output; Phase
/// 144 parses it into structured diagnostics.
case compileFailed(exitCode: Int32, stderr: String)
/// `dlopen(dylibPath, RTLD_NOW)` returned `nil`. `message` is the `dlerror()`
/// string at the time of the failure.
case dlopenFailed(path: String, message: String)
/// The dylib opened but did not export the expected entry symbol.
case entrySymbolMissing(symbol: String, message: String)
/// A temp-dir / write step failed before `swiftc` was invoked.
case ioFailed(underlying: String)
public var description: String {
switch self {
case .swiftcNotFound:
return "swiftc binary not found in xcrun or standard toolchain paths"
case .compileFailed(let code, let stderr):
return "swiftc exited \(code):\n\(stderr)"
case .dlopenFailed(let path, let message):
return "dlopen failed for \(path): \(message)"
case .entrySymbolMissing(let symbol, let message):
return "missing snippet entry symbol \(symbol): \(message)"
case .ioFailed(let underlying):
return "IO step failed: \(underlying)"
}
}
}
#endif
@@ -0,0 +1,210 @@
// LiveCompiler.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 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.
import Foundation
#if os(macOS)
import Darwin
#endif
#if os(macOS)
/// Symbol the snippet preamble must export. Snippets declare:
///
/// ```swift
/// @_cdecl("lyrebird_snippet_entry")
/// public func entry(_ ctx: UnsafeMutableRawPointer?) { /* ... */ }
/// ```
public let lyrebirdSnippetEntrySymbol: String = "lyrebird_snippet_entry"
/// One-shot snippet compiler. Stateless — every `compile(source:)` allocates a
/// fresh temp dir, dylib name, and `dlopen` handle.
public enum LiveCompiler {
/// Compile `source` to a dylib and resolve the snippet entry symbol.
///
/// - 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.
/// - 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.
/// - Throws: `LiveCompileError` cases for missing toolchain, compile failure,
/// `dlopen` failure, or missing entry symbol.
public static func compile(
source: String,
extraSwiftcArgs: [String] = []
) throws -> CompiledSnippet {
let swiftc: String = try findSwiftc()
let snippetID: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
let moduleName: String = "LBSnippet_\(snippetID)"
let workDir: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LyrebirdLiveCompile-\(snippetID)", isDirectory: true)
let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path
let dylibPath: String = workDir.appendingPathComponent("lib\(moduleName).dylib").path
do {
try FileManager.default.createDirectory(
at: workDir,
withIntermediateDirectories: true
)
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
} catch {
throw LiveCompileError.ioFailed(underlying: "\(error)")
}
var arguments: [String] = [
"-emit-library",
"-module-name", moduleName,
"-o", dylibPath,
]
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
)
}
guard let handle: UnsafeMutableRawPointer = dlopen(dylibPath, RTLD_NOW) else {
let message: String = dlerror().map { String(cString: $0) } ?? "unknown dlopen error"
throw LiveCompileError.dlopenFailed(path: dylibPath, message: message)
}
guard let symbol: UnsafeMutableRawPointer = dlsym(handle, lyrebirdSnippetEntrySymbol) else {
let message: String = dlerror().map { String(cString: $0) } ?? "unknown dlsym error"
// Leave the dylib mapped — closing it after a successful open would
// unmap its types if anything is already referencing them. The
// failure is post-load, so the safe action is to leak.
throw LiveCompileError.entrySymbolMissing(
symbol: lyrebirdSnippetEntrySymbol,
message: message
)
}
let entry: SnippetEntry = unsafeBitCast(symbol, to: SnippetEntry.self)
return CompiledSnippet(
moduleName: moduleName,
dylibPath: dylibPath,
entry: entry,
handle: handle
)
}
// MARK: - swiftc resolution
/// First-success search:
/// 1. `xcrun -f swiftc` (honours `DEVELOPER_DIR` and the user's active Xcode).
/// 2. Hard-coded toolchain paths.
static func findSwiftc() throws -> String {
if let xcrun: String = swiftcViaXcrun() {
return xcrun
}
let candidates: [String] = [
"/usr/bin/swiftc",
"/usr/local/bin/swiftc",
"/opt/homebrew/bin/swiftc",
]
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
return path
}
throw LiveCompileError.swiftcNotFound
}
/// `xcrun --show-sdk-path` — returns the macOS SDK path used by the user's
/// active Xcode. `nil` when xcrun is missing or returns non-zero.
static func sdkPathViaXcrun() -> String? {
let xcrunPath: String = "/usr/bin/xcrun"
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: xcrunPath)
process.arguments = ["--show-sdk-path"]
let stdout: Pipe = Pipe()
process.standardOutput = stdout
process.standardError = FileHandle.nullDevice
do {
try process.run()
process.waitUntilExit()
} catch {
return nil
}
guard process.terminationStatus == 0 else { return nil }
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
}
private static func swiftcViaXcrun() -> String? {
let xcrunPath: String = "/usr/bin/xcrun"
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: xcrunPath)
process.arguments = ["-f", "swiftc"]
let stdout: Pipe = Pipe()
process.standardOutput = stdout
// xcrun's stderr is short, but attaching a Pipe without draining it could
// deadlock if it ever filled the OS pipe buffer (~64 KB) while we block on
// stdout. Route to /dev/null at the OS level.
process.standardError = FileHandle.nullDevice
do {
try process.run()
process.waitUntilExit()
} catch {
return nil
}
guard process.terminationStatus == 0 else { return nil }
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
}
// MARK: - swiftc invocation
struct SwiftcResult {
let exitCode: Int32
let stderr: String
}
private static func runSwiftc(executable: String, arguments: [String]) throws -> SwiftcResult {
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: executable)
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.
process.standardOutput = FileHandle.nullDevice
do {
try process.run()
} catch {
throw LiveCompileError.ioFailed(underlying: "swiftc launch failed: \(error)")
}
let stderrData: Data = stderrPipe.fileHandleForReading.readDataToEndOfFile()
process.waitUntilExit()
let stderrString: String = String(data: stderrData, encoding: .utf8) ?? ""
return SwiftcResult(exitCode: process.terminationStatus, stderr: stderrString)
}
}
#endif
@@ -0,0 +1,326 @@
// LiveSession.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
//
// `LiveSession` owns the `SynthesisEngine` and tracks every `Synthesizer` that
// each snippet `play(_:)`s, so the next non-additive re-evaluation can
// `engine.remove(_:)` them before running fresh user code. Also caches every
// `CompiledSnippet` so the dylibs stay mapped — see the leak-by-design note in
// `CompiledSnippet.swift`.
#if os(macOS)
import Foundation
import LyrebirdSynth
/// Host-side owner of one live-coding session.
///
/// Holds the `SynthesisEngine` that snippets target, the swiftc flags used to
/// compile snippets, and the tracking lists needed for re-evaluation cleanup.
/// Snippets receive a `SnippetContext` bound to this session through
/// `compileAndRun(_:additive:)`.
public final class LiveSession {
public let engine: SynthesisEngine
/// `-I` paths threaded to `swiftc` for module discovery.
public let importPaths: [URL]
/// `-L` paths threaded to `swiftc` for library search.
public let librarySearchPaths: [URL]
/// Bare library names threaded to `swiftc` as `-l<name>`.
public let libraries: [String]
/// `-Xlinker -rpath -Xlinker <path>` entries baked into the snippet dylib
/// so `dlopen` resolves dependent dylibs (`libLyrebird.dylib` etc.) at
/// runtime without `DYLD_LIBRARY_PATH` ceremony.
public let rpaths: [URL]
/// Side-channel for snippet `context.reportSampleRate(_:)` calls. Tests read
/// via `@testable import`; not part of the public API.
internal var reportedSampleRate: Double?
/// Side-channel for snippet `context.reportMessage(_:)` calls. Tests read
/// via `@testable import`; not part of the public API.
internal var lastSnippetMessage: String?
// Tracked state — all access guarded by `trackingLock`.
private let trackingLock: NSLock = NSLock()
private var trackedSynths: [any Synthesizer] = []
private var loadedSnippets: [CompiledSnippet] = []
public init(
engine: SynthesisEngine,
importPaths: [URL] = LiveSession.defaultImportPaths(),
librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(),
libraries: [String] = ["Lyrebird", "LyrebirdLiveCompile"],
rpaths: [URL] = LiveSession.defaultRpaths()
) {
self.engine = engine
self.importPaths = importPaths
self.librarySearchPaths = librarySearchPaths
self.libraries = libraries
self.rpaths = rpaths
}
/// Wrap `userBody` in the standard harness, compile, and call the snippet's
/// `lyrebird_snippet_entry` with a `SnippetContext` bound to this session.
///
/// - Parameters:
/// - userBody: Swift code that runs inside the snippet entry. Has access
/// to a local `context: SnippetContext`.
/// - additive: When `false` (default), removes every previously tracked
/// synth before running. When `true`, leaves prior synths in place
/// (⌘⇧↩ semantics in the future `LyrebirdScratchView` editor).
/// - Returns: The compiled snippet handle. Retained internally so the dylib
/// stays mapped; callers can ignore it.
@discardableResult
public func compileAndRun(_ userBody: String, additive: Bool = false) throws -> CompiledSnippet {
if !additive {
clearTracked()
}
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: userBody)
let snippet: CompiledSnippet = try compileWrapped(wrapped)
runEntry(of: snippet)
return snippet
}
/// Asynchronous variant of ``compileAndRun(_:additive:)``. The swiftc
/// compile runs on a background `Task.detached`; the snippet entry then
/// executes on the caller's actor (typically the main actor, so snippets
/// can touch UI-side state). Lets `LyrebirdScratchView`'s editor stay
/// responsive during the compile.
///
/// - Precondition: only one in-flight invocation at a time per `LiveSession`.
/// Concurrent calls can interleave `clearTracked()` with the prior call's
/// not-yet-completed `runEntry`, silently dropping tracked synths. The
/// built-in caller `LyrebirdScratchModel` serialises through its
/// `isCompiling` flag; out-of-tree callers must enforce the same.
///
/// - Parameters:
/// - userBody: Same as the synchronous variant.
/// - additive: Same as the synchronous variant.
/// - Returns: The compiled snippet handle. Retained internally.
@discardableResult
public func compileAndRunAsync(_ userBody: String, additive: Bool = false) async throws -> CompiledSnippet {
if !additive {
clearTracked()
}
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: userBody)
let args: [String] = makeSwiftcArgs()
let snippet: CompiledSnippet = try await Task.detached(priority: .userInitiated) {
try LiveSession.compileBlocking(wrapped: wrapped, extraArgs: args)
}.value
runEntry(of: snippet)
return snippet
}
// Synchronous compile body used by both `compileAndRun` and the detached
// background `Task` inside `compileAndRunAsync`. Wraps the
// `LiveCompileError` → `LiveSessionError` translation in one place.
private static func compileBlocking(wrapped: WrappedSnippet, extraArgs: [String]) throws -> CompiledSnippet {
do {
return try LiveCompiler.compile(
source: wrapped.source,
extraSwiftcArgs: extraArgs
)
} catch let error as LiveCompileError {
if case .compileFailed(_, let stderr) = error {
let diagnostics: [Diagnostic] = DiagnosticParser.parse(
stderr: stderr,
userBodyLineOffset: wrapped.userBodyLineOffset
)
throw LiveSessionError.snippetCompileFailed(
diagnostics: diagnostics,
underlying: error
)
}
throw LiveSessionError.compilerError(error)
}
}
private func compileWrapped(_ wrapped: WrappedSnippet) throws -> CompiledSnippet {
try LiveSession.compileBlocking(wrapped: wrapped, extraArgs: makeSwiftcArgs())
}
private func runEntry(of snippet: CompiledSnippet) {
let context: SnippetContext = SnippetContext(session: self)
withExtendedLifetime(context) {
let opaque: UnsafeMutableRawPointer = Unmanaged.passUnretained(context).toOpaque()
snippet.entry(opaque)
}
trackingLock.lock(); defer { trackingLock.unlock() }
loadedSnippets.append(snippet)
}
/// Currently tracked synth count. Thread-safe.
public var trackedSynthCount: Int {
trackingLock.lock(); defer { trackingLock.unlock() }
return trackedSynths.count
}
/// Remove every tracked synth from the engine and clear the tracking list.
/// Called automatically by `compileAndRun(_:additive: false)`.
public func clearTracked() {
let snapshot: [any Synthesizer]
do {
trackingLock.lock(); defer { trackingLock.unlock() }
snapshot = trackedSynths
trackedSynths.removeAll()
}
for synth: any Synthesizer in snapshot {
_ = engine.remove(synth)
}
}
/// Internal hook for `SnippetContext.play(_:)`. Thread-safe.
func track(_ synth: any Synthesizer) {
trackingLock.lock(); defer { trackingLock.unlock() }
trackedSynths.append(synth)
}
// MARK: - swiftc flag construction
private func makeSwiftcArgs() -> [String] {
var args: [String] = []
for path: URL in importPaths {
args += ["-I", path.path]
}
// Clang module maps (e.g. `LyrebirdC.modulemap`) generated by Xcode for
// SPM C targets — surface each as `-Xcc -fmodule-map-file=<path>` so
// swiftc's embedded clang can resolve the underlying C module declared
// in a Swift module's dependency record.
for url: URL in LiveSession.discoverClangModuleMaps(in: importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
// 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
// `-undefined dynamic_lookup` so the snippet's dylib defers symbol
// resolution to runtime, where dyld finds Lyrebird's symbols in the
// already-loaded host process.
let hasDylib: Bool = librarySearchPaths.contains { url in
LiveSession.hasLyrebirdDylib(in: url)
}
if hasDylib {
for path: URL in librarySearchPaths {
args += ["-L", path.path]
}
for lib: String in libraries {
args += ["-l\(lib)"]
}
for path: URL in rpaths {
args += ["-Xlinker", "-rpath", "-Xlinker", path.path]
}
} else {
args += ["-Xlinker", "-undefined", "-Xlinker", "dynamic_lookup"]
}
return args
}
/// Walk up from each import path looking for Xcode's
/// `Build/Intermediates.noindex/GeneratedModuleMaps/` directory and return
/// every `*.modulemap` it contains. Empty on `swift build` SPM layouts
/// (where C modules use the package's own `include/module.modulemap`).
static func discoverClangModuleMaps(in importPaths: [URL]) -> [URL] {
let maxWalk: Int = 6
var found: [URL] = []
var visited: Set<String> = Set<String>()
for start: URL in importPaths {
var cur: URL = start
for _ in 0..<maxWalk {
let probe: URL = cur
.appendingPathComponent("Build")
.appendingPathComponent("Intermediates.noindex")
.appendingPathComponent("GeneratedModuleMaps")
if FileManager.default.fileExists(atPath: probe.path),
!visited.contains(probe.path) {
visited.insert(probe.path)
if let entries: [URL] = try? FileManager.default.contentsOfDirectory(at: probe, includingPropertiesForKeys: nil) {
for entry: URL in entries where entry.pathExtension == "modulemap" {
found.append(entry)
}
}
}
let parent: URL = cur.deletingLastPathComponent()
if parent == cur { break }
cur = parent
}
}
return found
}
// MARK: - Build-dir discovery
/// Best-effort discovery of the SPM `.build/<triple>/<config>` directory
/// that contains `libLyrebird.dylib` and the swiftmodule directories. Used
/// as the default for `importPaths`/`librarySearchPaths`/`rpaths`. Hosts can
/// override by passing explicit URLs.
///
/// Searches, in order:
/// 1. Walks up from `Bundle(for: LiveSession.self).bundleURL` — this resolves
/// to the directory holding `libLyrebirdLiveCompile.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`.
public static func currentBuildDir() -> URL? {
let maxWalk: Int = 6
let candidates: [URL] = [
Bundle(for: LiveSession.self).bundleURL,
Bundle.main.executableURL ?? Bundle.main.bundleURL,
]
// Accept either an SPM-produced .dylib (swift build) or just the
// LyrebirdSynth.swiftmodule (Xcode SPM static-linked into the host app).
// The swiftmodule alone is enough for `-I` module resolution; linking
// falls back to `-undefined dynamic_lookup` when no dylib is found.
// Note: the product/dylib is named `Lyrebird` (libLyrebird.dylib); the
// module/target is named `LyrebirdSynth` (LyrebirdSynth.swiftmodule).
let markers: [String] = ["libLyrebird.dylib", "LyrebirdSynth.swiftmodule"]
for start: URL in candidates {
var cur: URL = start
for _ in 0..<maxWalk {
for marker: String in markers {
let probe: URL = cur.appendingPathComponent(marker)
if FileManager.default.fileExists(atPath: probe.path) {
return cur
}
}
let parent: URL = cur.deletingLastPathComponent()
if parent == cur { break }
cur = parent
}
}
return nil
}
/// `true` when a `libLyrebird.dylib` actually exists in `buildDir`. Used to
/// decide whether to link against the dylib at compile time or fall back to
/// `-undefined dynamic_lookup` so the snippet binds to symbols already
/// resolved in the running process.
public static func hasLyrebirdDylib(in buildDir: URL) -> Bool {
FileManager.default.fileExists(
atPath: buildDir.appendingPathComponent("libLyrebird.dylib").path
)
}
public static func defaultImportPaths() -> [URL] {
guard let buildDir: URL = currentBuildDir() else { return [] }
return [buildDir, buildDir.appendingPathComponent("Modules")]
}
public static func defaultLibrarySearchPaths() -> [URL] {
guard let buildDir: URL = currentBuildDir() else { return [] }
return [buildDir]
}
public static func defaultRpaths() -> [URL] {
guard let buildDir: URL = currentBuildDir() else { return [] }
return [buildDir]
}
}
#endif
@@ -0,0 +1,43 @@
// LiveSessionError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
//
// `LiveSession.compileAndRun(_:additive:)` throws this richer error so callers
// see diagnostics pre-mapped to user-snippet coordinates. Other `LiveCompileError`
// cases (toolchain missing, dlopen failure, etc.) pass through under
// `.compilerError`.
#if os(macOS)
public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
/// Snippet failed to compile. `diagnostics` are already line-mapped via the
/// active `SnippetHarness` offset; `underlying` is the raw `swiftc` failure
/// the diagnostics were parsed from.
case snippetCompileFailed(diagnostics: [Diagnostic], underlying: LiveCompileError)
/// Any other `LiveCompileError` case — toolchain missing, dlopen failure,
/// missing entry symbol, IO failure.
case compilerError(LiveCompileError)
public var description: String {
switch self {
case .snippetCompileFailed(let diagnostics, let underlying):
if diagnostics.isEmpty {
return "snippet compile failed:\n\(underlying)"
}
let summary: String = diagnostics.map { diag -> String in
let location: String = diag.line.map { "\($0):\(diag.column)" } ?? "preamble:\(diag.rawLine):\(diag.column)"
return "\(location) \(diag.severity.rawValue): \(diag.message)"
}.joined(separator: "\n")
return "snippet compile failed:\n\(summary)"
case .compilerError(let underlying):
return "live compile error: \(underlying)"
}
}
}
#endif
@@ -0,0 +1,65 @@
// SnippetContext.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
//
// `SnippetContext` is the public API surface the user's snippet talks to. The
// host (via `LiveSession.compileAndRun`) constructs one of these, passes the
// opaque pointer to the snippet's `lyrebird_snippet_entry`, and the preamble
// hands the snippet a typed `context: SnippetContext` reference.
//
// Surface is intentionally minimal for v1 (open question 4 in the plan). Snippets
// read `context.engine` for `SynthesisEngine`, call `context.play(_:)` to add a
// synth that the host will track for re-evaluation cleanup, and report back via
// the test-friendly `reportSampleRate(_:)` / `reportMessage(_:)` helpers.
#if os(macOS)
import LyrebirdSynth
public final class SnippetContext {
/// Owning session. `unowned` because the host guarantees the session
/// outlives the snippet `entry` call (entry is invoked synchronously inside
/// `LiveSession.compileAndRun` under a `withExtendedLifetime` on `self`).
public unowned let session: LiveSession
/// Convenience accessor — same as `session.engine`.
public var engine: SynthesisEngine { session.engine }
init(session: LiveSession) {
self.session = session
}
/// Add `synth` to the engine and track it so the next non-additive
/// re-evaluation (`LiveSession.compileAndRun(_:additive: false)`) removes it.
/// - Returns: `true` if the engine accepted the enqueue; `false` if
/// `engine.add` threw (e.g. cross-engine binding, double-add, queue full).
@discardableResult
public func play(_ synth: any Synthesizer) -> Bool {
do {
try session.engine.add(synth)
session.track(synth)
return true
} catch {
session.lastSnippetMessage = "engine.add failed: \(error)"
return false
}
}
/// 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.
public func reportSampleRate(_ rate: Double) {
session.reportedSampleRate = rate
}
/// Snippet-side hook for test verification: record an arbitrary message
/// back on the session. Lets tests confirm the snippet body executed.
public func reportMessage(_ message: String) {
session.lastSnippetMessage = message
}
}
#endif
@@ -0,0 +1,19 @@
// SnippetEntry.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 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.
public typealias SnippetEntry = @convention(c) (UnsafeMutableRawPointer?) -> Void
#endif
@@ -0,0 +1,43 @@
// SnippetHarness.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
//
// `SnippetHarness.wrap(userBody:)` produces the full Swift source that
// `LiveCompiler.compile(source:)` feeds to swiftc. The preamble imports the
// modules the snippet needs, declares the C ABI entry, and binds `context: SnippetContext`
// from the opaque pointer the host hands in. The user's body is dropped in as
// the function body.
#if os(macOS)
public enum SnippetHarness {
/// Wraps `userBody` in the standard preamble.
public static func wrap(userBody: String) -> WrappedSnippet {
let preamble: String = """
import LyrebirdSynth
import LyrebirdLiveCompile
@_cdecl("lyrebird_snippet_entry")
public func lyrebird_snippet_entry(_ ctx: UnsafeMutableRawPointer?) {
guard let ctx else { return }
let context = Unmanaged<SnippetContext>.fromOpaque(ctx).takeUnretainedValue()
_ = context
"""
// Count newlines in the preamble: the user's body starts on the next line.
// `components(separatedBy: "\n")` over a string ending in "\n" yields N+1
// elements (the last is empty); offset = count of those elements = lines
// before the user body + 1 (the line on which the body starts).
let lineOffset: Int = preamble.components(separatedBy: "\n").count
let suffix: String = "\n}\n"
let source: String = preamble + userBody + suffix
return WrappedSnippet(source: source, userBodyLineOffset: lineOffset)
}
}
#endif
@@ -0,0 +1,22 @@
// WrappedSnippet.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
//
// 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`
// from each swiftc-reported line so error rows point back at the row the user
// typed.
#if os(macOS)
public struct WrappedSnippet: Equatable {
public let source: String
public let userBodyLineOffset: Int
}
#endif
@@ -0,0 +1,86 @@
# 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`, `dlopen`s 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
```swift
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. Removes synths from the previous run before executing. |
| ⌘⇧↩ | 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.
## Snippet API surface
A snippet has one local in scope:
```swift
context: SnippetContext
```
`SnippetContext` is intentionally minimal in v1:
- `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.reportMessage(_:)` — write back to the host (used by tests; handy for
`print`-style probes during development).
## 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.
## 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.
- 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.
## Topics
- ``LyrebirdScratchView``
- ``LyrebirdScratchModel``
@@ -0,0 +1,288 @@
// LyrebirdScratchMenuController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import AppKit
import UniformTypeIdentifiers
import LyrebirdSynth
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.
@MainActor
public final class LyrebirdScratchMenuController: NSObject {
public let model: LyrebirdScratchModel
public init(model: LyrebirdScratchModel) {
self.model = model
}
/// Construct the full menu bar (App / File / Edit / Run / View / Window /
/// Help) and assign it to `NSApplication.shared.mainMenu`.
public func installMainMenu(appName: String = "LyrebirdScratchDemo") {
let mainMenu: NSMenu = NSMenu()
mainMenu.addItem(appMenuItem(appName: appName))
mainMenu.addItem(fileMenuItem())
mainMenu.addItem(editMenuItem())
mainMenu.addItem(runMenuItem())
mainMenu.addItem(viewMenuItem())
mainMenu.addItem(windowMenuItem())
NSApplication.shared.mainMenu = mainMenu
}
// MARK: App menu
private func appMenuItem(appName: String) -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: appName)
menu.addItem(NSMenuItem(title: "About \(appName)",
action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)),
keyEquivalent: ""))
menu.addItem(NSMenuItem.separator())
let services: NSMenuItem = NSMenuItem(title: "Services", action: nil, keyEquivalent: "")
let servicesMenu: NSMenu = NSMenu(title: "Services")
services.submenu = servicesMenu
NSApplication.shared.servicesMenu = servicesMenu
menu.addItem(services)
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Hide \(appName)",
action: #selector(NSApplication.hide(_:)),
keyEquivalent: "h"))
let hideOthers: NSMenuItem = NSMenuItem(title: "Hide Others",
action: #selector(NSApplication.hideOtherApplications(_:)),
keyEquivalent: "h")
hideOthers.keyEquivalentModifierMask = [.command, .option]
menu.addItem(hideOthers)
menu.addItem(NSMenuItem(title: "Show All",
action: #selector(NSApplication.unhideAllApplications(_:)),
keyEquivalent: ""))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit \(appName)",
action: #selector(NSApplication.terminate(_:)),
keyEquivalent: "q"))
item.submenu = menu
return item
}
// MARK: File menu
private func fileMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "File")
menu.addItem(target(NSMenuItem(title: "New",
action: #selector(newSnippet(_:)),
keyEquivalent: "n")))
menu.addItem(target(NSMenuItem(title: "Open…",
action: #selector(openSnippet(_:)),
keyEquivalent: "o")))
menu.addItem(NSMenuItem.separator())
menu.addItem(target(NSMenuItem(title: "Save",
action: #selector(saveSnippet(_:)),
keyEquivalent: "s")))
let saveAs: NSMenuItem = NSMenuItem(title: "Save As…",
action: #selector(saveSnippetAs(_:)),
keyEquivalent: "s")
saveAs.keyEquivalentModifierMask = [.command, .shift]
menu.addItem(target(saveAs))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Close",
action: #selector(NSWindow.performClose(_:)),
keyEquivalent: "w"))
item.submenu = menu
return item
}
// MARK: Edit menu — wires to the first responder so NSTextView gets it
private func editMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "Edit")
menu.addItem(NSMenuItem(title: "Undo",
action: Selector(("undo:")),
keyEquivalent: "z"))
let redo: NSMenuItem = NSMenuItem(title: "Redo",
action: Selector(("redo:")),
keyEquivalent: "z")
redo.keyEquivalentModifierMask = [.command, .shift]
menu.addItem(redo)
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Cut",
action: #selector(NSText.cut(_:)),
keyEquivalent: "x"))
menu.addItem(NSMenuItem(title: "Copy",
action: #selector(NSText.copy(_:)),
keyEquivalent: "c"))
menu.addItem(NSMenuItem(title: "Paste",
action: #selector(NSText.paste(_:)),
keyEquivalent: "v"))
menu.addItem(NSMenuItem(title: "Select All",
action: #selector(NSText.selectAll(_:)),
keyEquivalent: "a"))
menu.addItem(NSMenuItem.separator())
let find: NSMenuItem = NSMenuItem(title: "Find…",
action: #selector(NSTextView.performFindPanelAction(_:)),
keyEquivalent: "f")
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
menu.addItem(find)
item.submenu = menu
return item
}
// MARK: Run menu
private func runMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "Run")
menu.addItem(target(NSMenuItem(title: "Run",
action: #selector(runSnippet(_:)),
keyEquivalent: "\r")))
let runAdd: NSMenuItem = NSMenuItem(title: "Run Additive",
action: #selector(runSnippetAdditive(_:)),
keyEquivalent: "\r")
runAdd.keyEquivalentModifierMask = [.command, .shift]
menu.addItem(target(runAdd))
menu.addItem(NSMenuItem.separator())
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
action: #selector(clearSynths(_:)),
keyEquivalent: "k")))
item.submenu = menu
return item
}
// MARK: View menu
private func viewMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "View")
let wrap: NSMenuItem = target(NSMenuItem(title: "Wrap Lines",
action: #selector(toggleWrap(_:)),
keyEquivalent: "l"))
wrap.keyEquivalentModifierMask = [.command, .option]
menu.addItem(wrap)
menu.addItem(NSMenuItem.separator())
let inc: NSMenuItem = target(NSMenuItem(title: "Increase Font Size",
action: #selector(increaseFontSize(_:)),
keyEquivalent: "+"))
menu.addItem(inc)
menu.addItem(target(NSMenuItem(title: "Decrease Font Size",
action: #selector(decreaseFontSize(_:)),
keyEquivalent: "-")))
menu.addItem(target(NSMenuItem(title: "Reset Font Size",
action: #selector(resetFontSize(_:)),
keyEquivalent: "0")))
item.submenu = menu
return item
}
// MARK: Window menu
private func windowMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "Window")
menu.addItem(NSMenuItem(title: "Minimize",
action: #selector(NSWindow.performMiniaturize(_:)),
keyEquivalent: "m"))
menu.addItem(NSMenuItem(title: "Zoom",
action: #selector(NSWindow.performZoom(_:)),
keyEquivalent: ""))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Bring All to Front",
action: #selector(NSApplication.arrangeInFront(_:)),
keyEquivalent: ""))
item.submenu = menu
NSApplication.shared.windowsMenu = menu
return item
}
// MARK: - Action targets
private func target(_ item: NSMenuItem) -> NSMenuItem {
item.target = self
return item
}
@objc private func newSnippet(_ sender: Any?) {
model.text = LyrebirdScratchModel.defaultPlaceholder
}
@objc private func openSnippet(_ sender: Any?) {
let panel: NSOpenPanel = NSOpenPanel()
panel.allowedContentTypes = [.swiftSource]
panel.allowsMultipleSelection = false
panel.canChooseDirectories = false
panel.message = "Open a Lyrebird snippet"
if panel.runModal() == .OK, let url: URL = panel.url {
do {
try model.load(from: url)
} catch {
model.reportLoadError(url: url, error: error)
}
}
}
@objc private func saveSnippet(_ sender: Any?) {
if let url: URL = model.documentURL {
do {
try model.save(to: url)
} catch {
model.reportSaveError(url: url, error: error)
}
return
}
saveSnippetAs(sender)
}
@objc private func saveSnippetAs(_ sender: Any?) {
let panel: NSSavePanel = NSSavePanel()
panel.allowedContentTypes = [.swiftSource]
panel.nameFieldStringValue = model.documentURL?.lastPathComponent ?? "snippet.swift"
panel.message = "Save Lyrebird snippet"
if panel.runModal() == .OK, let url: URL = panel.url {
do {
try model.save(to: url)
} catch {
model.reportSaveError(url: url, error: error)
}
}
}
@objc private func runSnippet(_ sender: Any?) {
Task { @MainActor in _ = await model.run(additive: false) }
}
@objc private func runSnippetAdditive(_ sender: Any?) {
Task { @MainActor in _ = await model.run(additive: true) }
}
@objc private func clearSynths(_ sender: Any?) {
model.clearTracked()
}
@objc private func toggleWrap(_ sender: Any?) {
model.toggleWrapsLines()
if let item: NSMenuItem = sender as? NSMenuItem {
item.state = model.wrapsLines ? .on : .off
}
}
@objc private func increaseFontSize(_ sender: Any?) {
model.bumpFontSize(by: 1)
}
@objc private func decreaseFontSize(_ sender: Any?) {
model.bumpFontSize(by: -1)
}
@objc private func resetFontSize(_ sender: Any?) {
model.resetFontSize()
}
}
#endif
@@ -0,0 +1,227 @@
// LyrebirdScratchModel.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile — Phase 145
//
// Backing model for `LyrebirdScratchView`. Owns the editable snippet text, the
// most recent compile result, and the host `LiveSession`. Pulled out of the
// view so logic can be exercised without instantiating SwiftUI.
//
// macOS only — wraps `LyrebirdLiveCompile`, which itself is macOS-only.
#if os(macOS)
import Foundation
import CoreGraphics
import LyrebirdSynth
import LyrebirdLiveCompile
/// Observable backing model for `LyrebirdScratchView`.
///
/// Drives one live-coding editor pane. `run(additive:)` awaits
/// `LiveSession.compileAndRunAsync` so the swiftc invocation runs off the main
/// actor and the editor stays responsive. ``isCompiling`` flips around the
/// await so SwiftUI can disable the Run buttons and surface a "Compiling…"
/// status while the dylib build is in flight.
@MainActor
public final class LyrebirdScratchModel: ObservableObject {
/// Default placeholder text loaded into a fresh model. Walks the user
/// through the two keyboard shortcuts and the in-snippet API surface.
/// `nonisolated` so callers in a non-main context (e.g. SwiftUI init's
/// default-argument evaluation, which is not implicitly main-actor) can
/// reference it without a Swift 6 isolation diagnostic.
public nonisolated static let defaultPlaceholder: String = """
// ⌘↩ — compile + run (removes synths from the previous run first).
// ⌘⇧↩ — 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).
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.reportMessage("playing 440 Hz sine — stereo, centered")
"""
/// Current editor text. View binds to this; user edits flow back here via
/// the `NSTextView` delegate inside `LyrebirdScratchView`.
@Published public var text: String
/// Parsed swiftc diagnostics from the last `run(additive:)` invocation.
/// Empty when the last run compiled cleanly or has not yet been attempted.
@Published public private(set) var diagnostics: [Diagnostic] = []
/// Single-line human-readable status line shown beneath the editor.
/// Updated by `run(additive:)` and `clearTracked()`.
@Published public private(set) var statusMessage: String = ""
/// Mirror of `session.trackedSynthCount`, refreshed after every `run` /
/// `clearTracked` call so the toolbar can show the count without polling.
@Published public private(set) var trackedSynthCount: Int
/// `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.
@Published public private(set) var isCompiling: Bool = false
/// URL of the file the editor text was last saved to or loaded from. `nil`
/// when the editor holds unsaved scratch content. The view uses this to
/// distinguish a silent overwrite (⌘S) from a Save As… prompt.
@Published public private(set) var documentURL: URL?
/// Editor font size in points. Clamped to `[minFontSize, maxFontSize]`.
@Published public var fontSize: CGFloat = 13
/// When `true`, lines wrap at the editor's right edge instead of scrolling
/// horizontally.
@Published public var wrapsLines: Bool = true
public let session: LiveSession
public nonisolated static let minFontSize: CGFloat = 9
public nonisolated static let maxFontSize: CGFloat = 32
public nonisolated static let defaultFontSize: CGFloat = 13
public func bumpFontSize(by delta: CGFloat) {
fontSize = max(LyrebirdScratchModel.minFontSize,
min(LyrebirdScratchModel.maxFontSize, fontSize + delta))
}
public func resetFontSize() {
fontSize = LyrebirdScratchModel.defaultFontSize
}
public func toggleWrapsLines() {
wrapsLines.toggle()
}
/// - Parameters:
/// - session: Host `LiveSession` the model forwards compile + cleanup
/// calls to. Retained for the model's lifetime.
/// - initialText: Seed text loaded into `text`. Defaults to
/// ``defaultPlaceholder``.
public init(
session: LiveSession,
initialText: String = LyrebirdScratchModel.defaultPlaceholder
) {
self.session = session
self.text = initialText
self.trackedSynthCount = session.trackedSynthCount
}
/// Compile and execute the current `text`. Updates `diagnostics`,
/// `statusMessage`, `trackedSynthCount`, and ``isCompiling``.
///
/// Awaits `LiveSession.compileAndRunAsync`, which runs swiftc on a
/// `Task.detached`. The view's Run / Run Additive buttons bind to
/// ``isCompiling`` and stay disabled until this method returns.
///
/// - Parameter additive: When `false`, the session removes every
/// previously tracked synth before running. When `true`, prior synths
/// stay in the engine (⌘⇧↩ in the view).
/// - Returns: `true` when the snippet compiled and its entry returned
/// without throwing; `false` otherwise.
@discardableResult
public func run(additive: Bool) async -> Bool {
guard !isCompiling else { return false }
let body: String = text
diagnostics = []
statusMessage = "Compiling…"
isCompiling = true
defer {
isCompiling = false
trackedSynthCount = session.trackedSynthCount
}
do {
try await session.compileAndRunAsync(body, additive: additive)
let mode: String = additive ? "additive" : "replaced"
statusMessage = "Ran (\(mode)). Tracked synths: \(session.trackedSynthCount)."
return true
} catch let sessionError as LiveSessionError {
switch sessionError {
case .snippetCompileFailed(let diags, let underlying):
if diags.isEmpty {
diagnostics = [Diagnostic(
line: nil,
column: 0,
severity: .error,
message: "\(underlying)",
rawLine: 0
)]
statusMessage = "Compile failed — see diagnostics below."
} else {
diagnostics = diags
let plural: String = diags.count == 1 ? "" : "s"
statusMessage = "Compile failed — \(diags.count) diagnostic\(plural)."
}
case .compilerError(let underlying):
statusMessage = "Compiler error: \(underlying)"
}
return false
} catch {
statusMessage = "Error: \(error)"
return false
}
}
/// Forward to `LiveSession.clearTracked()` and refresh `trackedSynthCount`.
public func clearTracked() {
session.clearTracked()
trackedSynthCount = session.trackedSynthCount
statusMessage = "Cleared tracked synths."
}
// MARK: - Snippet save / load
/// Replace `text` with the UTF-8 contents at `url`, set ``documentURL``
/// for subsequent saves, and refresh the status line.
///
/// - Parameter url: File to read. Caller (view) is responsible for the
/// `NSOpenPanel` UI; this method does the IO.
public func load(from url: URL) throws {
let loaded: String = try String(contentsOf: url, encoding: .utf8)
text = loaded
documentURL = url
diagnostics = []
statusMessage = "Loaded \(url.lastPathComponent)."
}
/// Write `text` to `url` as UTF-8, set ``documentURL``, refresh status.
///
/// - Parameter url: Destination. Overwrites if present. Caller drives the
/// `NSSavePanel` UI.
public func save(to url: URL) throws {
try text.write(to: url, atomically: true, encoding: .utf8)
documentURL = url
statusMessage = "Saved \(url.lastPathComponent)."
}
/// Surface a load failure on the status line without throwing across the
/// view layer. Called by the view after `NSOpenPanel` returned a URL that
/// `load(from:)` rejected.
public func reportLoadError(url: URL, error: Error) {
statusMessage = "Load failed (\(url.lastPathComponent)): \(error.localizedDescription)"
}
/// Surface a save failure on the status line without throwing across the
/// view layer. Called by the view after `NSSavePanel` returned a URL that
/// `save(to:)` rejected.
public func reportSaveError(url: URL, error: Error) {
statusMessage = "Save failed (\(url.lastPathComponent)): \(error.localizedDescription)"
}
}
#endif
@@ -0,0 +1,409 @@
// LyrebirdScratchView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile — Phase 145
//
// `LyrebirdScratchView` — SwiftUI scratchpad editor for live-coded snippets.
// Wraps an `NSTextView` for the editor surface, drives a `LyrebirdScratchModel`
// for compile state, and surfaces parsed `Diagnostic`s in a scrollable list
// below the editor. macOS-only; iOS hosting is deferred (no swiftc on device).
#if os(macOS)
import AppKit
import SwiftUI
import UniformTypeIdentifiers
import LyrebirdSynth
import LyrebirdLiveCompile
/// SwiftUI scratchpad for live-compiled Lyrebird snippets.
///
/// Pair with a `LiveSession` that owns the audio engine, drop the view into a
/// `LyrebirdWindow`, and ⌘↩ replaces the prior run while ⌘⇧↩ adds to it.
/// Diagnostics from a failed compile are listed under the editor with the
/// user's snippet-row coordinates already mapped by `DiagnosticParser`.
///
/// - Parameters:
/// - session: Host `LiveSession` owning the `SynthesisEngine`. Forwarded
/// into the backing ``LyrebirdScratchModel``.
/// - initialText: Seed text loaded into the editor. Defaults to
/// ``LyrebirdScratchModel/defaultPlaceholder``.
///
/// ## Hosting
///
/// ```swift
/// import LyrebirdUI // LyrebirdWindow
/// import LyrebirdLiveCompile // LiveSession
/// import LyrebirdLiveCompileUI // LyrebirdScratchView
///
/// let session = LiveSession(engine: engine)
/// let win = LyrebirdWindow(title: "Lyrebird Scratch", width: 640, height: 480)
/// win.open { LyrebirdScratchView(session: session) }
/// ```
///
/// ## 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`.
@MainActor
public struct LyrebirdScratchView: View {
@StateObject private var model: LyrebirdScratchModel
@State private var engineTick: Int = 0
private let engineRefresh = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
/// Construct with a fresh `LyrebirdScratchModel` wrapping `session`.
///
/// - Parameters:
/// - session: Host live-coding session owning the audio engine. The view
/// does not retain a reference of its own; the wrapped model does.
/// - initialText: Seed text loaded into the editor. Defaults to the
/// onboarding placeholder explaining the two keyboard shortcuts.
public init(
session: LiveSession,
initialText: String = LyrebirdScratchModel.defaultPlaceholder
) {
_model = StateObject(wrappedValue: LyrebirdScratchModel(
session: session,
initialText: initialText
))
}
/// Construct against a pre-built model. Lets tests or alternate hosts
/// inject a model with custom session, text, or pre-populated state.
public init(model: LyrebirdScratchModel) {
_model = StateObject(wrappedValue: model)
}
public var body: some View {
VStack(spacing: 0) {
engineBar
Divider()
ScratchEditor(
text: Binding(
get: { model.text },
set: { model.text = $0 }
),
fontSize: model.fontSize,
wrapsLines: model.wrapsLines
)
.frame(minHeight: editorMinHeight)
Divider()
statusBar
if !model.diagnostics.isEmpty {
Divider()
diagnosticsList
}
}
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
.onReceive(engineRefresh) { _ in engineTick &+= 1 }
}
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)
Spacer()
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(engine.averageCPU))")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
Spacer().frame(width: 8)
Text("synths: \(model.trackedSynthCount)")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
}
.padding(.horizontal, toolbarPadding)
.padding(.vertical, 6)
.id(engineTick)
}
private func formatCPU(_ value: Double) -> String {
String(format: "%.0f%%", value * 100)
}
public func runSnippet(additive: Bool) {
Task { @MainActor in
_ = await model.run(additive: additive)
}
}
public func presentOpenPanel() {
let panel: NSOpenPanel = NSOpenPanel()
panel.allowedContentTypes = [.swiftSource]
panel.allowsMultipleSelection = false
panel.canChooseDirectories = false
panel.message = "Open a Lyrebird snippet"
if panel.runModal() == .OK, let url: URL = panel.url {
do {
try model.load(from: url)
} catch {
model.reportLoadError(url: url, error: error)
}
}
}
public func saveOrPromptForLocation() {
if let url: URL = model.documentURL {
do {
try model.save(to: url)
} catch {
model.reportSaveError(url: url, error: error)
}
return
}
presentSavePanel()
}
public func presentSavePanel() {
let panel: NSSavePanel = NSSavePanel()
panel.allowedContentTypes = [.swiftSource]
panel.nameFieldStringValue = model.documentURL?.lastPathComponent ?? "snippet.swift"
panel.message = "Save Lyrebird snippet"
if panel.runModal() == .OK, let url: URL = panel.url {
do {
try model.save(to: url)
} catch {
model.reportSaveError(url: url, error: error)
}
}
}
private var statusBar: some View {
HStack {
Text(model.statusMessage.isEmpty ? "Ready." : model.statusMessage)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
.lineLimit(1)
.truncationMode(.middle)
Spacer()
}
.padding(.horizontal, statusHPad)
.padding(.vertical, statusVPad)
}
private var diagnosticsList: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, diag in
DiagnosticRow(diagnostic: diag)
}
}
.padding(diagnosticListPadding)
}
.frame(minHeight: diagnosticsMinHeight, maxHeight: diagnosticsMaxHeight)
}
// Layout constants — all in points. Kept private; tuned to match
// LyrebirdEngineStatusView's visual density.
private let scratchMinWidth: CGFloat = 520
private let scratchMinHeight: CGFloat = 420
private let editorMinHeight: CGFloat = 240
private let toolbarSpacing: CGFloat = 8
private let toolbarPadding: CGFloat = 8
private let toolbarDividerHeight: CGFloat = 18
private let statusHPad: CGFloat = 8
private let statusVPad: CGFloat = 4
private let diagnosticRowSpacing: CGFloat = 2
private let diagnosticListPadding: CGFloat = 8
private let diagnosticsMinHeight: CGFloat = 80
private let diagnosticsMaxHeight: CGFloat = 200
private let engineDotSize: CGFloat = 8
}
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
/// message in a compact monospaced row.
private struct DiagnosticRow: View {
let diagnostic: Diagnostic
var body: some View {
HStack(alignment: .firstTextBaseline, spacing: rowGutter) {
Text(locationString)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
.frame(minWidth: locationColumnWidth, alignment: .leading)
Text(diagnostic.severity.rawValue)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(color(for: diagnostic.severity))
.frame(minWidth: severityColumnWidth, alignment: .leading)
Text(diagnostic.message)
.font(.system(.caption, design: .monospaced))
.textSelection(.enabled)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
Spacer(minLength: 0)
}
}
private var locationString: String {
if let line: Int = diagnostic.line {
return "\(line):\(diagnostic.column)"
}
return "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
}
private func color(for severity: DiagnosticSeverity) -> Color {
switch severity {
case .error: return .red
case .warning: return .orange
case .note: return .secondary
}
}
private let rowGutter: CGFloat = 8
private let locationColumnWidth: CGFloat = 80
private let severityColumnWidth: CGFloat = 56
}
/// `NSViewRepresentable` wrapping a vanilla `NSTextView` inside an
/// `NSScrollView`. Monospaced 13 pt, plain text, no smart-quote / dash /
/// auto-correct interference — matches the editor expectations of someone
/// typing Swift code.
private struct ScratchEditor: NSViewRepresentable {
@Binding var text: String
let fontSize: CGFloat
let wrapsLines: Bool
final class Coordinator: NSObject, NSTextViewDelegate {
var parent: ScratchEditor
init(_ parent: ScratchEditor) { self.parent = parent }
func textDidChange(_ notification: Notification) {
guard let tv: NSTextView = notification.object as? NSTextView else { return }
parent.text = tv.string
}
}
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)
}
return scroll
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
context.coordinator.parent = self
guard let tv: NSTextView = scroll.documentView as? NSTextView else { return }
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
let fontChanged: Bool = (tv.font?.pointSize ?? -1) != fontSize
if fontChanged {
tv.font = font
}
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: font)
tv.defaultParagraphStyle = paragraphStyle
tv.typingAttributes = makeAttrs(font: font, paragraph: paragraphStyle)
applyWrap(to: tv, in: scroll)
if tv.string != text {
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
} else if fontChanged {
reapplyAttrs(to: tv, font: font, paragraph: paragraphStyle)
}
}
private func makeAttrs(font: NSFont, paragraph: NSParagraphStyle) -> [NSAttributedString.Key: Any] {
[
.font: font,
.foregroundColor: NSColor.labelColor,
.paragraphStyle: paragraph,
]
}
private func makeParagraphStyle(for font: NSFont) -> NSParagraphStyle {
let style: NSMutableParagraphStyle = NSMutableParagraphStyle()
let spaceAdvance: CGFloat = (" " as NSString).size(withAttributes: [.font: font]).width
let tabWidth: CGFloat = spaceAdvance * tabSpaces
style.tabStops = []
style.defaultTabInterval = tabWidth
return style
}
private func replaceText(in tv: NSTextView,
with newText: String,
font: NSFont,
paragraph: NSParagraphStyle) {
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
let attributed: NSAttributedString = NSAttributedString(string: newText, attributes: attrs)
tv.textStorage?.setAttributedString(attributed)
tv.typingAttributes = attrs
}
private func reapplyAttrs(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
}
private func applyWrap(to tv: NSTextView, in scroll: NSScrollView) {
guard let container: NSTextContainer = tv.textContainer else { return }
if wrapsLines {
scroll.hasHorizontalScroller = false
tv.isHorizontallyResizable = false
tv.autoresizingMask = [.width]
container.widthTracksTextView = true
container.containerSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude)
} else {
scroll.hasHorizontalScroller = true
tv.isHorizontallyResizable = true
tv.autoresizingMask = []
container.widthTracksTextView = false
container.containerSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude)
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude)
}
tv.needsDisplay = true
}
private func configure(_ tv: NSTextView, in scroll: NSScrollView, with coordinator: Coordinator) {
tv.delegate = coordinator
let editorFont: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
tv.font = editorFont
tv.isRichText = false
tv.isAutomaticQuoteSubstitutionEnabled = false
tv.isAutomaticDashSubstitutionEnabled = false
tv.isAutomaticTextReplacementEnabled = false
tv.isAutomaticSpellingCorrectionEnabled = false
tv.smartInsertDeleteEnabled = false
tv.allowsUndo = true
tv.usesFindBar = true
tv.textContainerInset = NSSize(width: editorInset, height: editorInset)
tv.drawsBackground = true
tv.backgroundColor = .textBackgroundColor
tv.textColor = .labelColor
tv.insertionPointColor = .labelColor
tv.selectedTextAttributes = [
.backgroundColor: NSColor.selectedTextBackgroundColor,
.foregroundColor: NSColor.selectedTextColor,
]
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: editorFont)
tv.defaultParagraphStyle = paragraphStyle
tv.typingAttributes = makeAttrs(font: editorFont, paragraph: paragraphStyle)
applyWrap(to: tv, in: scroll)
replaceText(in: tv, with: text, font: editorFont, paragraph: paragraphStyle)
}
private let editorInset: CGFloat = 6
private let tabSpaces: CGFloat = 4
}
#endif

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