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
+369
View File
@@ -0,0 +1,369 @@
# Lyrebird CLI Guide
`lyrebird` is the command-line tool for creating, running, and exporting Lyrebird synthesis projects. This guide walks through a complete workflow from first install to a running audio patch.
---
## Installation
The `lyrebird` binary is built from the Lyrebird package itself. From the root of the Lyrebird repository:
```sh
swift build -c release --product LyrebirdCLI
```
Then copy the binary somewhere on your `PATH`, renaming to `lyrebird`:
```sh
cp .build/release/LyrebirdCLI /usr/local/bin/lyrebird
```
Verify:
```sh
lyrebird version
# lyrebird 0.1.0
```
**Requirement:** macOS 15+, Xcode or a Swift toolchain with `swift` on your `PATH`.
---
## Quick Start
Three commands to go from nothing to audio:
```sh
lyrebird new MyPiece # 1. scaffold a project
cd MyPiece
# edit Sources/MyPiece/main.swift
lyrebird run # 2. build and run
```
That's the complete loop. The rest of this guide explains each step in depth.
---
## Commands
### `lyrebird new <name>`
Scaffolds a new Lyrebird Swift Package in a subdirectory named `<name>`.
```sh
lyrebird new MyPiece
# Created MyPiece/
```
Generated layout:
```
MyPiece/
├── Package.swift
├── MyPiece.xcworkspace/
│ └── contents.xcworkspacedata ← open in Xcode (references Package.swift)
├── Sources/
│ └── MyPiece/
│ └── main.swift ← engine setup + entry point
└── Tests/
└── MyPieceTests/
└── MyPieceTests.swift
```
Open `MyPiece.xcworkspace` in Xcode for SwiftUI previews and debugging; or stay on the terminal with `lyrebird run`.
`main.swift` is pre-wired: engine is created, `engine.start()` is called, and `RunLoop.main.run()` keeps the process alive until Ctrl+C. Add your `Synthesizer` subclasses to the same `Sources/MyPiece/` directory — they share the module namespace so no imports are needed between files.
**Name rules:** valid Swift module identifiers only — ASCII letters, digits, underscores; no leading digit; no spaces or hyphens.
```sh
lyrebird new DrumMachine # OK
lyrebird new "my piece" # error: not a valid Swift module name
lyrebird new 1stPiece # error: not a valid Swift module name
```
**Templates** — `--template <name>`:
- SPM-only (open `Package.swift` in Xcode): `basic` (default), `demo`, `ui-demo`, `nrt`
- Xcode-project (ships `.xcodeproj` + `.xcworkspace`): `macos-ui-xcode`, `ios-ui`, `auv3`
```sh
lyrebird new MyApp --template macos-ui-xcode # macOS .app
lyrebird new MyApp --template ios-ui # iOS .app
lyrebird new MyPlugin --template auv3 # AUv3 host + .appex
```
**Local Lyrebird checkout** — `--lyrebird-path <abs-path>` makes the generated project depend on a local Lyrebird checkout (via `.package(name: "Lyrebird", path: ...)` in `Package.swift`, `XCLocalSwiftPackageReference` in `<name>.xcodeproj`). Use while the published repo URL isn't yet accessible:
```sh
lyrebird new MyApp --template macos-ui-xcode \
--lyrebird-path /Users/me/Documents/LyrebirdII
```
See `docs/tooling/project-system.md` for the layout each template emits.
If the directory already exists, the command fails cleanly and leaves the filesystem unchanged.
---
### `lyrebird run [--release]`
Builds and runs the current project. Must be called from the project's root directory (where `Package.swift` lives).
```sh
lyrebird run # debug build — fast compile, slower audio
lyrebird run --release # release build — full optimisation, use for performance
```
Under the hood this is `swift run` / `swift run -c release`. Exit code from `swift run` passes through, so CI can detect failures normally.
**Use `--release` for real audio work.** Debug builds run without optimisations; vDSP and tight DSP loops can be noticeably slower, and the RT thread may miss its deadline under heavy load.
```sh
cd MyPiece
lyrebird run --release
# Build complete!
# MyPiece running — press Ctrl+C to stop
```
---
### `lyrebird export <name> [--to <path>] [--overwrite]`
Generates a `SynthesizerBase` subclass template and writes it to a `.swift` file. Use this to stub out a new synth inside an existing project.
```sh
# Write BassDrum.swift to the current directory
lyrebird export BassDrum
# Write to a specific path
lyrebird export BassDrum --to Sources/MyPiece/BassDrum.swift
# Replace an existing file
lyrebird export BassDrum --to Sources/MyPiece/BassDrum.swift --overwrite
```
Generated file (`BassDrum.swift`):
```swift
import LyrebirdSynth
// MARK: - BassDrum
/// A Lyrebird synthesizer — generated by `lyrebird export BassDrum` (your subclass).
final class BassDrum: SynthesizerBase {
// MARK: - Parameters
// Declare parameters here. Example:
// let freq: LyrebirdFloat = 440.0
// MARK: - Build
override func build() {
// Wire your signal graph here. Example:
// let osc = OscSin.Audio(freq: freq)
// addOutputGenerator(osc * env)
}
}
```
Without `--overwrite`, the command fails if the destination already exists — safe to run repeatedly without clobbering work in progress.
---
### `lyrebird install-templates [--force]`
Installs Lyrebird's Xcode file templates (Generator, Synthesizer, Task, …) into
`~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`. After install,
Xcode's New File dialog (`⌘N`) shows a "Lyrebird" section listing every shipped
template.
```sh
lyrebird install-templates
# Installed 12 Lyrebird Xcode templates →
# /Users/you/Library/Developer/Xcode/Templates/File Templates/Lyrebird
```
Templates are bundled with the `lyrebird` binary as SPM resources — no repo
checkout needed once `lyrebird` is on your `PATH`.
Fails with `--force`-prompt error if the destination already exists. Pass
`--force` to replace it. See [xcode-templates.md](xcode-templates.md) for the
full template catalog and per-template usage notes.
### `lyrebird uninstall-templates`
Removes the entire `~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`
directory. Will not touch any other Xcode template you have installed.
```sh
lyrebird uninstall-templates
# Removed Lyrebird templates from
# /Users/you/Library/Developer/Xcode/Templates/File Templates/Lyrebird
```
---
### `lyrebird repl`
Runs `swift build` in the current directory, then launches `swift repl` with `-I` /
`-L` / `-l` flags pointing at the package's `.build/debug` artifacts so `import LyrebirdSynth`
works immediately. (`swift package repl` was removed from the toolchain; this is the
canonical replacement — see [repl.md](repl.md) for the raw command.)
```sh
cd MyPiece
lyrebird repl
# Lyrebird 0.1.0 — starting Swift REPL
# Run `import LyrebirdSynth` to access the framework.
```
Inside the REPL:
```swift
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 0,
driver: CoreAudioDriver()
)
try engine.start()
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase {
@LiveParam var freq: LyrebirdFloat = 440.0
override func build() {
let osc = OscSin.Audio(freq: $freq)
output(bus: 0, source: Pan2(input: osc * 0.2))
}
}
let tone = SineTone()
try engine.add(tone)
// While audio plays — parameter writes need no try (atomic store), RT-safe
tone.freq = 880.0
engine.remove(tone)
engine.stop()
```
`@LiveParam` assignments are atomic stores — safe to do from the REPL main thread while the audio thread runs. `engine.add` / `engine.remove` are lock-free and take effect at the next block boundary.
Exit the REPL with Ctrl+D.
See [repl.md](repl.md) for full REPL reference.
---
### `lyrebird help`
Prints the command summary.
```sh
lyrebird help
lyrebird --help
lyrebird -h
```
---
### `lyrebird version`
Prints the version string.
```sh
lyrebird version
lyrebird --version
# lyrebird 0.1.0
```
---
## Interactive Shell
Running `lyrebird` with no arguments enters the `lyrebird>` shell — a LineNoise-powered command loop with history and tab completion.
```sh
lyrebird
# Lyrebird 0.1.0 — Swift audio synthesis
# Type 'help' for available commands, or 'repl' to start a Swift REPL session.
#
# lyrebird>
```
All the same commands work inside the shell:
```
lyrebird> new FMSynth
Created FMSynth/
lyrebird> export Drone --to Sources/FMSynth/Drone.swift
Exported /Users/josh/FMSynth/Sources/FMSynth/Drone.swift
lyrebird> run --release
Build complete!
...
lyrebird> quit
```
**Shell features:**
| Feature | Details |
|---|---|
| Line editing | Arrow keys, Home/End, Ctrl+A/E (linenoise) |
| Tab completion | Prefix-match on all subcommand names |
| History | Up/down arrows; persisted to `~/.lyrebird_history` on exit |
| Case-insensitive verbs | `NEW`, `Run`, `EXPORT` all work |
| Preserved casing on names | `export MySynth` → file named `MySynth.swift`, not `mysynth.swift` |
| Exit | `quit`, `exit`, `:quit`, or Ctrl+D |
---
## A Complete Workflow
```sh
# 1. Scaffold
lyrebird new PadSynth
cd PadSynth
# 2. Stub out a synth
lyrebird export Pad --to Sources/PadSynth/Pad.swift
# 3. Edit Pad.swift — fill in build()
# (your editor here)
# 4. Add to main.swift:
# try engine.add(Pad())
# 5. Test with a debug build first
lyrebird run
# 6. Once stable, run optimised
lyrebird run --release
```
---
## Error Reference
| Error message | Cause | Fix |
|---|---|---|
| `error: directory 'X' already exists.` | `new` target dir present | Remove it or choose a different name |
| `error: 'X' is not a valid Swift module name.` | Name fails identifier rules | Use ASCII letters/digits/underscores only |
| `error: 'X' already exists. Pass --overwrite to replace it.` | `export` destination exists | Add `--overwrite` flag |
| `error: swift not found.` | No Swift toolchain on PATH | Install Xcode or a Swift toolchain |
| `Build failed (exit code N).` | `swift run` failed | Check compiler output above the error |
---
## Reference Docs
| Doc | Contents |
|---|---|
| [project-system.md](project-system.md) | Generated file contents, scaffolder/runner/exporter internals |
| [repl.md](repl.md) | Full REPL reference, threading model, live coding patterns |
| [targets.md](targets.md) | All package targets and when to use each |
+120
View File
@@ -0,0 +1,120 @@
# MIDI Clock Sync
`MIDIClockFollower` estimates BPM from incoming MIDI Clock (0xF8) messages and drives a
`LyrebirdClock` to follow an external transport.
Ableton Link is deferred — see `docs/roadmap/ableton-link.md`.
---
## Overview
MIDI System Real-Time sends 0xF8 bytes 24 times per quarter note. `MIDIClockFollower`
maintains a rolling window of the most recent N tick arrival times (default: 24 ticks =
one quarter-note), computes the average inter-tick interval, and derives a BPM estimate.
When the estimate changes by more than 0.01 BPM it writes `clock.bpm` — which correctly
accumulates beat-offset history inside `LyrebirdClock` so routines and tasks remain
phase-continuous across tempo changes.
Transport messages are handled as follows:
| Message | Effect |
|---------|--------|
| `.start` (0xFA) | `isRunning = true`, clears tick history |
| `.continue` (0xFB) | `isRunning = true`, clears tick history (beat alignment preserved) |
| `.stop` (0xFC) | `isRunning = false`, clears tick history. `clock.bpm` is **not** modified. |
| `.clock` (0xF8) | Updates rolling estimate, pushes to `clock.bpm` if change > epsilon |
All other messages are silently ignored.
---
## Wiring `MIDIClockFollower` to `MIDI`
```swift
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 0,
driver: CoreAudioDriver()
)
try engine.start()
// Create a clock. Initial BPM is a placeholder; the follower will override it quickly.
let clock = LyrebirdClock(engine: engine, bpm: 120.0)
// Create the follower.
let follower = MIDIClockFollower(
engine: engine,
clock: clock,
smoothingWindowTicks: 24, // one quarter-note window
minBPM: 40.0,
maxBPM: 250.0
)
// Create the MIDI integration.
let midi = MIDI(engine: engine)
try midi.start()
// Register a handler that passes every message to the follower.
midi.addHandler(name: "clockFollow") { message, _ in
follower.handle(message)
}
```
After this, any sequence clock running through MIDI will continuously update `clock.bpm`.
Routines and tasks that use `ctx.wait(beats:)` or `clock.nextBeat()` will automatically
track the external tempo.
---
## Parameters
| Parameter | Default | Meaning |
|-----------|---------|---------|
| `smoothingWindowTicks` | `24` | Rolling window size in ticks. 24 = one quarter-note. Smaller windows react faster but are more sensitive to jitter. |
| `minBPM` | `20.0` | Minimum accepted BPM. Estimates below this are clamped. |
| `maxBPM` | `999.0` | Maximum accepted BPM. Estimates above this are clamped. |
---
## Reading the estimate
```swift
print(follower.estimatedBPM) // current rolling BPM estimate
print(follower.isRunning) // true between .start/.continue and .stop
```
`estimatedBPM` returns `0.0` until at least 2 ticks have arrived since the last
`.start`, `.continue`, `reset()`, or initialisation.
---
## Manually resetting
```swift
follower.reset() // clears tick history; clock.bpm and isRunning are unchanged
```
---
## Beat alignment limitation
`LyrebirdClock` does not expose a public beat re-alignment API. When a `.start` message
arrives, `MIDIClockFollower` clears its tick history but cannot reset the clock's beat
phase to match the sender's Song Position Pointer. If beat-phase alignment is required,
snapshot `clock.currentBeat` at the moment `.start` arrives and offset all beat
calculations accordingly.
---
## Thread safety
`MIDIClockFollower` is `@unchecked Sendable`. All internal state is serialised under an
`NSLock`. `handle(_:)` is safe to call from any thread — in normal use it runs on the
`lyrebird.midi` background queue that `MIDI` uses for handler dispatch. The write
to `clock.bpm` is performed outside the follower's lock to prevent lock-ordering issues
with `LyrebirdClock`'s internal lock.
+437
View File
@@ -0,0 +1,437 @@
# Non-Real-Time Rendering Guide
Lyrebird supports offline rendering — running the synthesis engine faster than real time and writing the output directly to an audio file. No audio hardware is required. This is the correct approach for:
- Bouncing a finished piece to a file
- Batch-generating audio assets
- CI/automated testing with audio output verification
- Rendering samples or stems from a Lyrebird synthesizer
---
## Two Approaches
| Approach | What it does | Output format |
|---|---|---|
| `NRTDriver` | Renders the entire engine output to file | CAF (32-bit float) |
| `RecordBuffer` + `LyrebirdBuffer.write()` | Captures a signal path mid-graph, writes after render | AIFF, WAV, or CAF |
Use `NRTDriver` for most cases — it is a drop-in replacement for `CoreAudioDriver` and requires no signal graph changes. Use `RecordBuffer` when you need to capture a specific bus, a pre-effects signal, or multiple signal paths independently.
---
## Approach 1 — `NRTDriver`
### Basic usage
Replace `CoreAudioDriver()` with `NRTDriver(outputURL:duration:)`. Everything else stays the same.
```swift
import Foundation
import LyrebirdSynth
let outputURL = URL(fileURLWithPath: "output.caf")
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0, // no hardware input needed
driver: NRTDriver(outputURL: outputURL, duration: 5.0)
)
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase {
override func build() {
let osc = OscSin.Audio(freq: 440.0)
output(bus: 0, source: Pan2(input: osc * 0.3))
}
}
try engine.start() // blocks until 5 seconds are rendered, then returns
try engine.add(SineTone())
// engine.add is processed on next block — but start() renders all blocks first.
// For NRT, add synthesizers BEFORE start().
```
**Important:** `NRTDriver.start()` is synchronous. It renders all blocks, writes the file, and returns. There is no `RunLoop.main.run()` needed — the process exits naturally after `start()` returns.
### Correct ordering — add synthesizers before `start()`
With `CoreAudioDriver`, `engine.add()` works while audio runs because events are queued block-by-block. With `NRTDriver`, all rendering happens inside `start()`. Synthesizers added via `engine.add()` after `start()` are never rendered.
```swift
// CORRECT for NRT
try engine.add(SineTone())
try engine.add(BassLine())
try engine.start() // renders both
// WRONG for NRT — synthesizers added after start() are ignored
try engine.start()
try engine.add(SineTone()) // too late — rendering already complete
```
### Output file
`NRTDriver` always writes a **CAF** file: 32-bit float, interleaved, at the engine's sample rate. The file is created or overwritten at `outputURL`. The file is closed and flushed when `start()` returns.
```swift
// Absolute path
let url = URL(fileURLWithPath: "/Users/josh/renders/output.caf")
// Relative to working directory
let url = URL(fileURLWithPath: "output.caf")
// Documents folder
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
.appendingPathComponent("render.caf")
```
### Duration
Duration is set at `NRTDriver` init time and cannot be changed. The engine renders exactly `ceil(duration × sampleRate / blockSize)` blocks.
```swift
NRTDriver(outputURL: url, duration: 10.0) // 10 seconds
NRTDriver(outputURL: url, duration: 0.5) // 500 ms — good for short samples
NRTDriver(outputURL: url, duration: 120.0) // 2 minutes
```
### Scheduling multiple timed events
`engine.schedule(_:after:)` and `engine.schedule(_:at:)` work before `start()` because `currentTime` is `0` at that point. The engine holds every event in its pending queue and applies each one at the exact sample offset as it renders blocks — full sample-accurate timing with no extra plumbing required.
The example below schedules 10 sine-tone voices at random start times between 1 and 5 seconds. Each voice runs for 5 seconds via an ASR envelope. In NRT mode the render terminates at `totalDur` and the envelope ends at level 0, so no removal is needed. Total render duration = max start (5 s) + event length (5 s) = **10 seconds**.
```swift
import Foundation
import LyrebirdSynth
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class Blip: SynthesizerBase {
let freq: Double
init(freq: Double) { self.freq = freq; super.init() }
override func build() {
let attackTime = 0.02
let sustainTime = 4.66
let releaseTime = 0.3
let env = EnvelopeGen.Audio(
envelope: Envelope(levels: [0, 1, 0.6, 0],
durations: [attackTime, sustainTime, releaseTime],
curves: [0, 0, 0])
)
let osc = OscSin.Audio(freq: freq) * env * 0.15
output(bus: 0, source: Pan2(input: osc))
}
}
let outputURL = URL(fileURLWithPath: "timed_events.caf")
let sampleRate: Double = 48000
let maxStart = 5.0
let eventLength = 5.0
let totalDur = maxStart + eventLength // 10.0 s
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
driver: NRTDriver(outputURL: outputURL, duration: totalDur)
)
let pitches: [Double] = [220, 277.18, 329.63, 369.99, 440,
493.88, 554.37, 659.25, 739.99, 880]
var rng = SystemRandomNumberGenerator()
for freq in pitches {
let startSec = Double.random(in: 1.0...5.0, using: &rng)
try engine.schedule(Blip(freq: freq), after: startSec)
}
do {
try engine.start()
print("Rendered: \(outputURL.path)")
} catch {
fputs("Render failed: \(error)\n", stderr)
exit(1)
}
```
Key points:
- `after: startSec` is equivalent to `at: engine.seconds(startSec)` when called before `start()` — `currentTime` is `0` so both resolve to the same absolute sample offset.
- The envelope ends at level 0 and `doneAction` defaults to `.nothing` — synths stay in the graph but output silence. In NRT the render terminates at `totalDur` so no removal is needed. In RT, poll `env.needsFree` after each block and call `engine.remove()` when `true`.
- Set `NRTDriver(duration:)` to cover the latest possible start plus the full event length. Events whose scheduled start time falls beyond `duration` are never triggered.
- `pendingQueue` defaults to 1024 slots. For larger scores, pass `eventQueueCapacity:` (must be a power of two) to `SynthesisEngine.init` — a non-power-of-two value traps at startup. Events beyond capacity are silently dropped.
---
### Scheduling events during NRT render
`@LiveParam` and `ParameterNode` use atomic stores — they work correctly during NRT rendering because the render loop calls `calculatedSamples` on every block in sequence. You can set parameters on the main thread before `start()`, but not while rendering (since `start()` blocks the calling thread).
For score-based event sequencing in NRT, use `LyrebirdRoutine` / `LyrebirdTask` before `start()`, or wire parameters as generators driven by envelope/LFO shapes.
```swift
let synth = MySynth()
synth.freq = 880.0 // set before start() — applied from block 0
try engine.add(synth)
try engine.start()
```
---
### Soundfile input
Pass an audio file into the engine as simulated hardware input. Each block, the driver reads the next `blockSize` frames from the file and writes them to the engine's input buses exactly as `iOSAudioDriver` / `CoreAudioDriver` would from a microphone.
```swift
let inputURL = URL(fileURLWithPath: "source.wav")
let outputURL = URL(fileURLWithPath: "processed.caf")
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 2, // must be ≥ file channel count
driver: NRTDriver(outputURL: outputURL, duration: 5.0,
inputURL: inputURL,
inputStartOffset: 0.0) // seconds to skip
)
```
`In.Audio(bus: n)` uses a raw bus index. Input channels start at `numOutputChannels`, so input channel 0 is `In.Audio(bus: numOutputChannels + 0)`, input channel 1 is `In.Audio(bus: numOutputChannels + 1)`, and so on — identical to live hardware input behaviour.
```swift
final class SpectralProcessor: SynthesizerBase {
override func build() {
let inL = In.Audio(bus: 2) // input ch 0 (numOutputChannels = 2)
let inR = In.Audio(bus: 3) // input ch 1
// … process inL / inR …
output(bus: 0, source: Pan2(input: inL))
output(bus: 1, source: Pan2(input: inR))
}
}
try engine.add(SpectralProcessor())
try engine.start()
```
**Rules:**
- `numInputChannels` must be ≥ the file's channel count. Extra input buses stay zero.
- If the file has fewer channels than `numInputChannels`, only those buses are populated; the rest stay zero.
- If the file ends before `duration`, the remaining blocks receive silence — no crash.
- `inputStartOffset` skips that many seconds into the file before rendering begins. Negative values are clamped to 0.
- `ExtAudioFile` handles sample-rate conversion automatically if the file's sample rate differs from the engine's.
- Set `inputURL: nil` (the default) to restore the original behaviour — no file is opened.
---
## Approach 2 — `RecordBuffer` + `LyrebirdBuffer.write()`
Use this when you need to:
- Capture a specific signal path (not the final mix)
- Write AIFF or WAV instead of CAF
- Render with `CoreAudioDriver` while simultaneously saving to disk
### Step 1 — allocate a buffer
Size it to the number of frames you want to capture: `duration × sampleRate`.
```swift
let sampleRate = 44100.0
let duration = 4.0
let frameCount = Int(sampleRate * duration)
let captureBuf = LyrebirdBuffer(count: frameCount) // mono
let captureBuf = LyrebirdBuffer(count: frameCount, channelCount: 2) // stereo
```
### Step 2 — wire `RecordBuffer` into the signal graph
```swift
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class RecordingSynth: SynthesizerBase {
let captureBuf: LyrebirdBuffer
init(captureBuf: LyrebirdBuffer) {
self.captureBuf = captureBuf
super.init()
}
override func build() {
let osc = OscSin.Audio(freq: 220.0)
let sig = osc * 0.4
// RecordBuffer.Audio writes sig to captureBuf and passes sig through as output.
let recorder = RecordBuffer.Audio(input: sig, buffer: captureBuf, loop: false)
output(bus: 0, source: Pan2(input: recorder))
}
}
```
`RecordBuffer.Audio` passes the input signal through unchanged — it records and plays back simultaneously. Set `loop: false` so it stops at the end of the buffer instead of looping.
For stereo capture, supply a two-channel `GeneratorArray` and a buffer with `channelCount: 2`:
```swift
let stereoSig = expand([oscL, oscR]) { $0 }
let recorder = RecordBuffer.Audio(input: stereoSig, buffer: captureBuf, loop: false)
```
### Step 3 — render, then write
With `NRTDriver`:
```swift
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: Int(sampleRate),
numOutputChannels: 2,
numInputChannels: 0,
driver: NRTDriver(outputURL: URL(fileURLWithPath: "capture.caf"), duration: duration)
)
let synth = RecordingSynth(captureBuf: captureBuf)
try engine.add(synth)
try engine.start() // renders and writes the NRT output file
// After start() returns, captureBuf is fully populated — write it separately.
let aiffURL = URL(fileURLWithPath: "output.aiff")
try captureBuf.write(to: aiffURL, format: .aiff, sampleRate: sampleRate)
```
With `CoreAudioDriver` (real-time, write after recording finishes):
```swift
// Wait until recording is done (check doneAction or use a fixed delay)
Thread.sleep(forTimeInterval: duration + 0.1)
engine.stop()
try captureBuf.write(to: URL(fileURLWithPath: "output.wav"), format: .wav, sampleRate: sampleRate)
```
---
## Output Formats
### `NRTDriver` output — CAF only
`NRTDriver` writes CAF (Core Audio Format) unconditionally. CAF supports any sample rate, up to 8 channels, and 32-bit float samples. It is readable by all macOS/iOS audio tools.
To convert to AIFF or WAV after rendering, use `afconvert` (bundled with macOS):
```sh
afconvert -f AIFF -d BEF32 output.caf output.aiff
afconvert -f WAVE -d LEF32 output.caf output.wav
```
### `LyrebirdBuffer.write()` — AIFF, WAV, or CAF
```swift
try buf.write(to: url, format: .caf, sampleRate: 44100) // default
try buf.write(to: url, format: .aiff, sampleRate: 44100) // AIFF-C, Float32
try buf.write(to: url, format: .wav, sampleRate: 44100) // WAV, Float32
```
| Format | Extension | Endian | Channels | Notes |
|---|---|---|---|---|
| `.caf` | `.caf` | little-endian | up to 8 | Best for macOS; default |
| `.aiff` | `.aiff` | big-endian | ≤ 2 recommended | Broad DAW compatibility |
| `.wav` | `.wav` | little-endian | up to 8 | Cross-platform standard |
All formats write 32-bit float samples (Float32). The `LyrebirdFloat` (Double) values in the buffer are converted to Float32 on the way out.
---
## Complete Example — NRT Bounce to AIFF
```swift
import Foundation
import LyrebirdSynth
// --- Example: your synthesizer, defined by subclassing SynthesizerBase ---
final class FMTone: SynthesizerBase {
override func build() {
let mod = OscSin.Audio(freq: 220.0) * 150.0
let osc = OscSin.Audio(freq: 440.0 + mod)
let env = EnvelopeGen.Audio(
envelope: Envelope(levels: [0, 1, 0.6, 0],
durations: [0.01, 0.3, 0.5],
curves: [0, 0, 0])
)
let sig = osc * env * 0.4
output(bus: 0, source: Pan2(input: sig))
}
}
// --- Render ---
let cafURL = URL(fileURLWithPath: "fm_tone.caf")
let aiffURL = URL(fileURLWithPath: "fm_tone.aiff")
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 0,
driver: NRTDriver(outputURL: cafURL, duration: 2.0)
)
try engine.add(FMTone())
do {
try engine.start()
print("Rendered: \(cafURL.path)")
} catch {
fputs("Render failed: \(error)\n", stderr)
exit(1)
}
// Optional: convert to AIFF via afconvert (shell out)
let task = Process()
task.executableURL = URL(fileURLWithPath: "/usr/bin/afconvert")
task.arguments = ["-f", "AIFF", "-d", "BEF32", cafURL.path, aiffURL.path]
try? task.run()
task.waitUntilExit()
if task.terminationStatus == 0 {
print("Exported: \(aiffURL.path)")
}
```
---
## NRT vs RT — Key Differences
| | `CoreAudioDriver` | `NRTDriver` |
|---|---|---|
| `start()` blocks | No — audio runs on background thread | Yes — blocks until render complete |
| `engine.add()` timing | Works anytime audio is running | Must be called **before** `start()` |
| Speed | Real-time (1× wall clock) | Faster than real-time |
| Audio hardware | Required | Not required |
| Output | DAC / speakers | File on disk |
| `RunLoop.main.run()` | Required to keep process alive | Not needed — `start()` returns |
| CI/batch use | Not suitable | Yes |
---
## Error Reference
| Error | Cause | Fix |
|---|---|---|
| `NRTDriverError.cannotCreateFile` | Bad URL, permissions, or full disk | Check the path and disk space |
| `NRTDriverError.writeFailed` | Disk I/O error during render | Check disk space and path permissions |
| `LyrebirdBufferIOError.cannotCreateOutputFile` | Same as above for `write()` | |
| Silent output / all-zeros file | Synthesizers added after `start()` | Move all `engine.add()` calls before `start()` |
| File truncated short | `duration` too short for the patch | Increase `NRTDriver` duration |
---
## Reference Docs
| Doc | Contents |
|---|---|
| [cli-guide.md](cli-guide.md) | CLI commands, project workflow |
| [project-system.md](project-system.md) | Scaffolding and generated file contents |
| [targets.md](targets.md) | `LyrebirdDemo` as a starting point for NRT programs |
+311
View File
@@ -0,0 +1,311 @@
# Project System
A Lyrebird "piece" is a Swift Package that declares Lyrebird as a dependency.
The `lyrebird` CLI handles scaffolding, building, and exporting.
## Scaffold a New Project
```sh
lyrebird new MyPiece [--template <template>]
```
Creates:
```
MyPiece/
├── Package.swift
├── MyPiece.xcworkspace/
│ └── contents.xcworkspacedata (references Package.swift — open in Xcode)
├── Sources/
│ └── MyPiece/
│ └── main.swift (+ AppDelegate.swift, MyPieceSynth.swift for ui-demo)
└── Tests/
└── MyPieceTests/
└── MyPieceTests.swift
```
Open `MyPiece.xcworkspace` in Xcode for full project navigation, debugging, and SwiftUI previews — the workspace points at `Package.swift`, so SPM-resolved deps and targets show up as a normal project. Or run from the terminal with `lyrebird run`.
**Name rules** — the project name must be a valid Swift module identifier:
- ASCII letters, digits, and underscores only (`[A-Za-z0-9_]`)
- Must not start with a digit
- No spaces, hyphens, dots, or Unicode letters (Cyrillic, CJK, etc. are rejected
because SPM module names must be ASCII-safe on all toolchains)
### Templates
Swift-Package-only templates (lightweight; open `Package.swift` in Xcode for SwiftUI previews):
| Template | Command | Description |
|---|---|---|
| `basic` (default) | `lyrebird new MyPiece` | Minimal engine + `RunLoop.main.run()` |
| `demo` | `lyrebird new MyPiece --template demo` | `SineTone` with `@LiveParam` frequency and amplitude |
| `ui-demo` | `lyrebird new MyApp --template ui-demo` | AppKit window with `@UIParam` controls and `LyrebirdWindow`; adds `LyrebirdUI` to package deps |
| `nrt` | `lyrebird new MyRender --template nrt` | `NRTDriver` renders to `output.caf` and exits — no audio hardware needed |
Xcode-project templates (ship a real `.xcodeproj` for deliverables SwiftPM can't express — `.app` bundles, AUv3 extensions):
| Template | Command | Description |
|---|---|---|
| `macos-ui-xcode` | `lyrebird new MyApp --template macos-ui-xcode` | macOS `.app` (AppKit + SwiftUI), `@UIParam` synth, hardened runtime |
| `ios-ui` | `lyrebird new MyApp --template ios-ui` | iOS `.app` (SwiftUI + `iOSAudioDriver`), `AVAudioSession` activation, iPhone + iPad device family |
| `auv3` | `lyrebird new MyPlugin --template auv3` | AUv3 host `.app` + `aumu` `.appex` subclassing `LyrebirdAudioUnit`. Entitlements for both. Subtype + manufacturer pre-filled (manufacturer = `LYRB` placeholder — rewrite for distribution) |
Each Xcode-project template lays out:
```
<name>/
├── <name>.xcodeproj/
│ ├── project.pbxproj
│ └── xcshareddata/xcschemes/<name>.xcscheme
├── <name>.xcworkspace/
│ └── contents.xcworkspacedata (references <name>.xcodeproj)
├── <name>/ (app target sources + Info.plist [+ entitlements for auv3])
│ └── ...
└── <name>Extension/ (auv3 only — extension target + Info.plist + .entitlements)
└── ...
```
Lyrebird is pulled in via a remote SPM dependency on `https://realizedsound.mooo.com/josh/Lyrebird` (configurable via `ProjectScaffolder.lyrebirdPackageURL`). The scaffolded project lives anywhere on disk and does not need a local checkout.
### Microphone input — not pre-wired in any template
No template adds `NSMicrophoneUsageDescription` to the generated `Info.plist`, no template adds the hardened-runtime / sandbox audio-input capability, and the `ios-ui` template's `AVAudioSession` category is `.playback` (output only). Most pieces don't read live input, so the templates default to "no mic capability" rather than triggering a permission prompt on every first run.
If a piece needs live input (e.g. tapping the engine input bus into `ScopeCapture` or routing `In.Audio(bus: numOutputChannels)` through the graph), the project owner must add these themselves:
**Engine init** — set `numInputChannels > 0` and pass a non-nil `inputDeviceID` (macOS) when constructing `SynthesisEngine` / starting the driver.
**macOS** (`macos-ui-xcode`, `ui-demo` opened in Xcode, any AppKit/SwiftUI app):
- Add `NSMicrophoneUsageDescription` (string explaining the use) to the target's `Info.plist`. Required since macOS 10.14 — without it the OS silently denies input access and `CoreAudioDriver` reads zeros.
- If the app is sandboxed: add `com.apple.security.device.audio-input` to the `.entitlements` file. The `macos-ui-xcode` template ships unsandboxed; the `auv3` host app is sandboxed and will need the entitlement before the host can read mic in addition to hosting the plugin.
**iOS** (`ios-ui`):
- Add `NSMicrophoneUsageDescription` to the app `Info.plist`.
- Change the `AVAudioSession` category in the generated `AppDelegate` / `App` activation block from `.playback` to `.playAndRecord` (typically `mode: .default` or `.measurement`, options `[.defaultToSpeaker, .allowBluetooth]` depending on routing needs). `.playback` is output-only and will return zero-filled input buffers regardless of the engine's `numInputChannels`.
The first `start()` call after these are in place triggers the system permission prompt. Until the user grants, input frames remain zero — a scope tap on input buses will draw a flat line.
### `--lyrebird-path` — local checkout mode
While the Lyrebird repository is not yet publicly accessible, pass `--lyrebird-path <abs-path>` to point both `Package.swift` and (for Xcode templates) `<name>.xcodeproj` at a local Lyrebird checkout:
```sh
lyrebird new MyPiece --template macos-ui-xcode \
--lyrebird-path /Users/me/Documents/LyrebirdII
```
The generated `Package.swift` uses `.package(name: "Lyrebird", path: ...)` instead of `.package(url:from:)`; the `.xcodeproj` uses `XCLocalSwiftPackageReference` instead of `XCRemoteSwiftPackageReference`. The path must be absolute (relative paths are resolved against the current working directory).
Switch back to the remote URL by editing the `.package(...)` line in `Package.swift` and the `relativePath`/`repositoryURL` entry in `<name>.xcodeproj/project.pbxproj` once the public repo is available.
### Generated `Package.swift`
```swift
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "MyPiece",
platforms: [.macOS(.v15)],
dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"),
],
targets: [
.executableTarget(
name: "MyPiece",
dependencies: ["Lyrebird"]
),
.testTarget(
name: "MyPieceTests",
dependencies: ["MyPiece"]
),
]
)
```
The URL points to the Lyrebird repository on Bitbucket. Run `swift package resolve` to fetch it.
### Generated `Sources/MyPiece/main.swift`
```swift
// MyPiece — entry point
import Foundation
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 2,
driver: CoreAudioDriver()
)
// Add your Synthesizers here.
// engine.add(MySynth())
do {
try engine.start()
} catch {
fatalError("Engine failed to start: \(error)")
}
print("MyPiece running — press Ctrl+C to stop")
RunLoop.main.run()
```
### Generated `Tests/MyPieceTests/MyPieceTests.swift`
```swift
import Testing
import LyrebirdSynth
@Suite("MyPiece")
struct MyPieceTests {
@Test func engineStartsClean() throws {
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 2,
driver: OfflineDriver()
)
try engine.start()
engine.processBlock(inputSamples: [])
engine.stop()
#expect(engine.audioBuses[0].allSatisfy { $0 == 0.0 })
}
}
```
## File Convention
- **`main.swift`** — configure engine, build node tree, call `engine.start()`
- **One Synthesizer per file** — `ReverbSynth.swift`, `BassDrum.swift`, etc.
- All files in the same target share a module namespace — no imports needed between them
## Run a Project
```sh
lyrebird run # debug build — wraps: swift run
lyrebird run --release # release build — wraps: swift run -c release
```
The `swift` binary is located by checking, in order:
1. `/usr/bin/swift` — Xcode Command Line Tools / Xcode toolchain
2. `/usr/local/bin/swift` — standalone toolchain (Intel Mac)
3. `/opt/homebrew/bin/swift` — Homebrew toolchain (Apple Silicon)
`lyrebird run` exits with the same exit code as `swift run`, so CI scripts can
detect build/runtime failures normally.
## Export a Synthesizer Template
```sh
lyrebird export Tone
lyrebird export Tone --to ./Sources/MyPiece/Tone.swift
lyrebird export Tone --to ./Sources/MyPiece/Tone.swift --overwrite
```
Writes a starter `SynthesizerBase` subclass to the given path (default:
`<Name>.swift` in the current directory). The generated file is ready to drop
into any Lyrebird project's `Sources/` directory and fill in with signal graph
code.
**Flags:**
- `--to <path>` — destination file path; defaults to `<Name>.swift` in CWD
- `--overwrite` — replace an existing file; without this flag the command fails
if the destination already exists
**Name rules** — same ASCII identifier rules as `lyrebird new`.
### Generated template
```swift
import LyrebirdSynth
// MARK: - Tone
/// A Lyrebird synthesizer — generated by `lyrebird export Tone` (your subclass).
final class Tone: SynthesizerBase {
// MARK: - Parameters
// Declare parameters here. Example:
// let freq: LyrebirdFloat = 440.0
// MARK: - Build
override func build() {
// Wire your signal graph here. Example:
// let osc = OscSin.Audio(freq: freq)
// addOutputGenerator(osc * env)
}
}
```
## Interactive Shell
All three commands are also available in the `lyrebird>` interactive shell:
```
lyrebird> new MyPiece
Created MyPiece/
lyrebird> run
Build complete!
...
lyrebird> export Tone --to ./Sources/Tone.swift
Exported /Users/josh/MyPiece/Sources/Tone.swift
```
Shell verbs are case-insensitive (`NEW`, `Run`, `EXPORT` all work); argument
values such as project names preserve the user's original casing.
## Sharing Synthesizers
A reusable effect or instrument library is just a Swift package:
```swift
// In Package.swift
.package(url: "https://github.com/artist/LyrebirdReverb", from: "1.0.0")
```
## Testing
```swift
// Tests/MyPieceTests/ReverbTests.swift
import Testing
import MyPiece
@Test func reverbOutputIsNotSilent() throws {
let engine = SynthesisEngine(
blockSize: 512, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 2,
driver: OfflineDriver()
)
try engine.start()
let reverb = ReverbSynth()
try engine.add(reverb)
engine.processBlock(inputSamples: [])
#expect(engine.audioBuses[0].contains { $0 != 0.0 })
engine.stop()
}
```
Run with `swift test`. No Xcode Playgrounds.
## Implementation
| Type | File | Purpose |
|---|---|---|
| `ProjectScaffolder` | `LyrebirdCLI/ProjectScaffolder.swift` | Creates directory tree and writes template files |
| `ProjectRunner` | `LyrebirdCLI/ProjectRunner.swift` | Locates `swift` binary, execs `swift run [--release]` |
| `SynthExporter` | `LyrebirdCLI/SynthExporter.swift` | Writes `SynthesizerBase` subclass template |
| `validateSwiftIdentifier` | `LyrebirdCLI/NameValidation.swift` | Shared ASCII identifier validation used by both scaffolder and exporter |
`ProjectScaffolder.scaffold(name:in:)` cleans up the partial directory tree on
any mid-scaffold failure, so a failed `lyrebird new` never leaves a broken
directory that blocks a retry with `.projectExists`.
+159
View File
@@ -0,0 +1,159 @@
# REPL & Live Coding
## Launch
```sh
lyrebird repl
```
Prints a banner, runs `swift build` in the current directory, then launches `swift repl`
with `-I` / `-L` / `-l` flags pointing at the package's `.build/debug` artifacts. `import
Lyrebird` works immediately in the REPL session.
The raw command that `lyrebird repl` runs (useful for debugging or scripting):
```sh
swift build
swift repl \
-I .build/debug/Modules \
-I .build/debug/LyrebirdC.build \
-L .build/debug \
-lLyrebird
```
Run from the Lyrebird package directory itself, or from any project whose `Package.swift`
declares Lyrebird as a dependency — SPM resolves transitive deps during `swift build`
and stages them under the same `.build/debug` layout.
```sh
lyrebird # enter the lyrebird> interactive shell (LineNoise-powered)
lyrebird --help # usage help
lyrebird --version
```
## Interactive Shell (`lyrebird>`)
Running `lyrebird` with no arguments enters a LineNoise-powered command shell:
```
Lyrebird 0.1.0 — Swift audio synthesis
Type 'help' for available commands, or 'repl' to start a Swift REPL session.
Commands:
new <name> Scaffold a new Lyrebird Swift Package
run [--release] Build and run the current project
export <name> [--to p] Export a Synthesizer template to a .swift file
repl Launch Swift REPL with Lyrebird available
version Print lyrebird version
help Show this help
quit Exit (also Ctrl+D)
lyrebird> repl
```
Features:
- Arrow-key line editing (linenoise C library, pure Swift wrapper)
- Tab completion for all subcommands
- Persistent command history — saved to `~/.lyrebird_history` on exit
- Shell verbs are case-insensitive (`NEW`, `Run`, `EXPORT` all work);
argument values such as project/synth names preserve the user's original casing
## Basic REPL Session
Once inside the Swift REPL:
```swift
import LyrebirdSynth
// Create and start the engine
let engine = SynthesisEngine(
blockSize: 512, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 2,
driver: CoreAudioDriver()
)
try engine.start()
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class SineTone: SynthesizerBase {
@LiveParam var freq: LyrebirdFloat = 440.0
@LiveParam var amp: LyrebirdFloat = 0.3
override func build() {
let osc = OscSin.Audio(freq: $freq)
output(bus: 0, source: osc * $amp)
}
}
// Add to engine — audio starts immediately
let tone = SineTone()
try engine.add(tone)
// Adjust while running — no try, no string
tone.freq = 880.0
// Remove
engine.remove(tone)
```
## Threading While Audio Runs
- REPL input and graph mutation: **main thread** (the `swift repl` process)
- Audio render callback: **RT thread** (Core Audio)
- `@LiveParam` assignments → `Atomic<UInt64>` store → RT acquiring load, per-sample ramp
- `engine.add` / `engine.remove` → `SPSCQueue` → applied at next block boundary
Audio never stops during node add/remove — the lock-free scheduling mechanism handles it.
## History
Command history for the `lyrebird>` interactive shell is persisted to `~/.lyrebird_history`
and shared across all shell sessions. The path is exposed as
`REPLLauncher.historyFilePath` and mirrored by `InteractiveShell.historyFilePath`.
## Implementation Notes
### `lyrebird repl` — `swift build` + `swift repl` with flags
Older versions of SPM shipped a `swift package repl` subcommand that resolved the whole
dependency graph and dropped you into an `import`-ready REPL with no flags. That
subcommand has been removed from the current Swift toolchain — running it now errors with
`error: Unknown subcommand or plugin name 'repl'`.
`REPLLauncher` replaces it with the canonical two-step invocation:
1. `swift build` — produces `.build/debug/Modules/LyrebirdSynth.swiftmodule`,
`.build/debug/libLyrebird.dylib`, and `.build/debug/LyrebirdC.build/module.modulemap`.
If the build fails, the REPL is not started and the user sees the compiler output
directly (stdout/stderr are inherited).
2. `swift repl -I .build/debug/Modules -I .build/debug/LyrebirdC.build -L .build/debug
-lLyrebird` — the same flags SPM used to compute internally. `-I` points the Swift
driver at the staged `.swiftmodule` and the LyrebirdC C-module modulemap; `-L` /
`-lLyrebird` links the dynamic library so `import LyrebirdSynth` succeeds and runtime
symbols resolve through the dylib's `@rpath` install name.
Run from the Lyrebird package directory itself, or from any project directory whose
`Package.swift` declares Lyrebird as a dependency — both produce the same `.build/debug`
layout after `swift build`.
### LineNoise
`LyrebirdCLI` depends on `andybest/linenoise-swift` (LineNoise 0.0.3). The interactive
shell (`InteractiveShell.run()`) owns the LineNoise instance and manages:
- History load/save (`~/.lyrebird_history`)
- Tab completion callback (prefix-matched subcommands)
The `swift repl` session that fires on `repl` has its own separate REPL history
managed by LLDB/Swift (typically in `~/.lldb/`).
### `CLICommand` parsing
`CLICommand.parse(_:)` is the canonical argument parser for the `lyrebird` binary.
`InteractiveShell.command(from:)` is its shell-line equivalent. Both apply the same
rules:
- Verb is lowercased before matching (case-insensitive commands)
- Positional name arguments are guarded against flag tokens (`hasPrefix("-")`)
- `--to` value is guarded against consuming a subsequent flag as a path
- `--overwrite` is parsed and threaded through to `SynthExporter.export`
See `docs/tooling/project-system.md` for the full `lyrebird new / run / export`
reference.
+319
View File
@@ -0,0 +1,319 @@
# LyrebirdRoutine, LyrebirdTask, and Pattern
Algorithmic event scheduling on background threads. Non-RT — drives high-level events (add/remove synths, change `@LiveParam` values) from sequential code with timed waits.
---
## Pattern\<T\>
Demand-rate value sequence. Not thread-safe; use within a single Routine/Task.
```swift
let freqs = Pattern.sequence([440.0, 550.0, 880.0], repeats: 2)
while let f = freqs.next() { ... } // iterates twice, then next() returns nil
freqs.reset() // restart from beginning
```
| Property/Method | Description |
|---|---|
| `next() -> T?` | Return current value and advance. `nil` when exhausted or values is empty. |
| `reset()` | Restart from first value; clear cycle count. |
| `isExhausted` | `true` after `repeats` full cycles. Always `false` when `repeats == -1`. |
`repeats: -1` (default) = infinite loop.
### Pattern Factory Reference
All variants below are constructed by static factory methods on `Pattern<T>`. Every variant returns a `Pattern<T>` (or `Pattern<[T]>` for `tuple`) backed by a module-internal engine. `next()` / `reset()` / `isExhausted` behave uniformly. Numeric factories require `T == Double` and live on `extension Pattern where T == Double`; the rest are generic.
**Atomic value sources — generic `T`**
| Factory | Behaviour |
|---|---|
| `Pattern.sequence(_:repeats:)` | Cycle through array `repeats` times. `-1` infinite. |
| `Pattern.shuffle(_:repeats:seed:)` | Fisher-Yates permute once at init, then cycle. Same permutation replays on reset. (SC `Pshuf`) |
| `Pattern.nonRepeatingRandom(_:repeats:seed:)` | Random pick avoiding same *index* as previous. Documented index-vs-value caveat for duplicate-value pools. (SC `Pxrand`) |
| `Pattern.weightedRandom(_:weights:repeats:seed:)` | Pick proportional to weight. Init preconditions: equal count, finite non-negative weights, positive sum. (SC `Pwrand`) |
| `Pattern.closure(_:)` | Wrap `() -> T?`. Latches once nil is returned. Reset clears latch but cannot reset closure-internal state. (SC `Pfunc`) |
**Atomic value sources — numeric `Pattern<Double>`**
| Factory | Behaviour |
|---|---|
| `Pattern.series(start:step:length:)` | Arithmetic series. `length == -1` infinite. (SC `Pseries`) |
| `Pattern.geometric(start:ratio:length:)` | Geometric series. (SC `Pgeom`) |
| `Pattern.uniformRandom(low:high:length:seed:)` | Uniform random in `[low, high]`. (SC `Pwhite`) |
| `Pattern.brownian(low:high:step:start:length:seed:)` | Clamped random walk. `start` defaults to midpoint. (SC `Pbrown`) |
| `Pattern.gaussian(mean:stdDev:length:seed:)` | Gaussian (Box-Muller). (SC `Pgauss`) |
| `Pattern.cauchy(location:scale:length:seed:)` | Cauchy (inverse-CDF). (SC `Pcauchy`) |
| `Pattern.beta(alpha:beta:length:seed:)` | Beta(α, β) in `[0, 1]` (two-Gamma). (SC `Pbeta`) |
**Length / range modifiers — generic `T`, wrap any `Pattern<T>`**
| Factory | Behaviour |
|---|---|
| `Pattern.repeating(_:count:)` | Replay upstream `count` times with `reset()` between cycles. `-1` infinite. (SC `Pn`) |
| `Pattern.limit(_:count:)` | Emit at most `count` items returned. `count >= 0` precondition. (SC `Pfin`) |
| `Pattern.drop(_:count:)` | Skip first `count` upstream values lazily. `count >= 0` precondition. (SC `Pdrop`) |
| `Pattern.stutter(_:count:)` | For each upstream value, emit n times where n is the next value from a `Pattern<Int>`. (SC `Pstutter`) |
**Multi-pattern composition — generic `T`**
| Factory | Behaviour |
|---|---|
| `Pattern.switching(_:index:)` | One value per index draw; out-of-range index latches. (SC `Pswitch1`) |
| `Pattern.concatenate(_:)` | Sequential play; advance when active sub-pattern returns nil. |
| `Pattern.roundRobin(_:)` | One value per pattern in rotation; dead slots skipped. (SC `Ppatlace`) |
| `Pattern.tuple(_:)` | Returns `Pattern<[T]>`. Zips children into size-stable arrays. Latches on any child nil. |
| `Pattern.interleave(_:repeats:)` | SC `Place`. Each outer cycle emits one value per sub-list; shorter sub-lists wrap modulo own length. Empty sub-lists silently dropped. `repeats == -1` infinite. |
**Map / filter / reject — generic `T`**
| Factory | Behaviour |
|---|---|
| `Pattern.map(_:_:)` | Wraps `Pattern<U>` with `(U) -> T` transform. Result element type can differ. (SC `Pcollect`) |
| `Pattern.filter(_:where:)` | Keep upstream values where predicate is true. Spin caveat for never-matching infinite source. (SC `Pselect`) |
| `Pattern.reject(_:where:)` | Inverse of `filter`. Routes the same engine with a negated predicate. (SC `Preject`) |
**Numeric transforms — `Pattern<Double>`**
| Factory | Behaviour |
|---|---|
| `Pattern.accumulate(_:initial:)` | Running sum from `initial`. (SC `Paccum`) |
| `Pattern.difference(_:)` | First value verbatim, subsequent = `x[n] - x[n-1]`. (SC `Pdiff`) |
| `Pattern.wrap(_:low:high:)` | Wrap into half-open `[low, high)` via floor-modulo with FP-boundary post-clamp. Precondition `high > low`. (SC `Pwrap`) |
| `Pattern.clip(_:low:high:)` | Clamp to `[low, high]`. Precondition `high >= low`. (SC `Pclip`) |
| `Pattern.round(_:step:)` | Round to nearest multiple of `step`, ties away from zero. Precondition `step > 0`. (SC `Pround`) |
| `Pattern.smooth(_:coefficient:)` | One-pole exponential smoother `y[n] = c·y[n-1] + (1-c)·x[n]`. Coefficient clamped to `[0, 1]`. First sample passes through. (SC `Psmooth`) |
**Composition example**
```swift
// Repeat (cycle through a switch of two sub-patterns picked by an index pattern) 4 times.
let composite: Pattern<Double> = Pattern.repeating(
Pattern.switching(
[Pattern.series(start: 0, step: 1, length: 4),
Pattern.uniformRandom(low: 0, high: 1, length: 4)],
index: Pattern.sequence([0, 1, 0, 1])
),
count: 4
)
```
The same factories on the demand side are implemented as separate `DemandGenerator` types (`DemandSeries`, `DemandShuffle`, `DemandSwitch`, etc.) wrapping the matching Pattern engines — see `docs/stdlib/generators.md` § Demand-rate.
---
## LyrebirdRoutine
Runs a closure **once** on a dedicated background thread (`Thread`, `.userInitiated` QoS).
```swift
let routine = LyrebirdRoutine { ctx in
let freqs = Pattern.sequence([440.0, 550.0, 660.0])
while let freq = freqs.next() {
let tone = SineTone(); tone.freq = freq
ctx.add(tone)
try ctx.wait(seconds: 0.5)
ctx.remove(tone)
try ctx.wait(seconds: 0.1)
}
}
routine.start(engine: engine)
// ... later:
routine.stop()
```
### States
```
idle → (start) → running → (body returns / stop) → stopped
stopped → (reset) → idle
```
### API
| Method | Description |
|---|---|
| `start(engine:)` | Launch background thread. No-op if not `.idle`. |
| `stop()` | Signal stop. Next `ctx.wait()` throws `LyrebirdRoutineError.stopped`. |
| `reset()` | Signal stop and block until thread finishes. Resets to `.idle` for restart. |
---
## LyrebirdTask
Like `LyrebirdRoutine` with `pause()` / `resume()`. Identical body signature.
```swift
let task = LyrebirdTask { ctx in
while true {
ctx.add(nextEvent())
try ctx.wait(seconds: 0.25)
}
}
task.start(engine: engine)
task.pause() // freeze; thread sleeps inside ctx.wait()
task.resume() // continue from where it left off
task.stop()
```
### States
```
idle → running → paused → running → stopped
```
| Method | Description |
|---|---|
| `pause()` | Suspend inside next `ctx.wait()`. Sets state `.paused`. |
| `resume()` | Broadcast on internal condition; resumes `ctx.wait()`. Sets state `.running`. |
| `stop()` / `reset()` | Same as `LyrebirdRoutine`. |
---
## LyrebirdRoutineContext
Passed to the body closure. Provides:
### Timed waits
```swift
try ctx.wait(seconds: 0.5) // sleep ~0.5s; polls stop/pause every 10ms
try ctx.waitUntil(sampleTime: t) // block until engine.currentTime >= t
```
Both throw `LyrebirdRoutineError.stopped` when `stop()` is called. Let the error propagate or catch and rethrow to unwind cleanly.
### Engine calls
All dispatched to the main thread via `DispatchQueue.main.async` to preserve the `pendingQueue` single-producer invariant.
```swift
ctx.add(synth)
ctx.schedule(synth, at: sampleTime)
ctx.schedule(synth, after: 2.0) // seconds
ctx.remove(synth)
ctx.remove(synth, at: sampleTime)
```
---
## Error handling
```swift
let routine = LyrebirdRoutine { ctx in
do {
while true {
try ctx.wait(seconds: 0.25)
// ... produce events ...
}
} catch LyrebirdRoutineError.stopped {
// cleanup if needed
}
// body returns → state = .stopped
}
```
Uncaught `LyrebirdRoutineError.stopped` is silently swallowed by the Routine/Task harness — it always signals a clean stop, not a crash.
---
## Thread model
- One `Thread` per Routine/Task. Thread is created on `start()`, destroyed when body returns.
- `stop()` is non-blocking. `reset()` blocks the calling thread until the body exits.
- Do not call `reset()` from inside the body closure.
- Multiple routines run concurrently and independently.
---
## LyrebirdClock
Named shared clock that multiple routines and tasks can align to without per-routine drift.
### The drift problem
Two routines calling `ctx.wait(beats: 1)` in independent loops accumulate OS scheduler jitter independently and drift apart within seconds. `ctx.waitUntil(sampleTime:)` on a shared sample-time grid never drifts.
```swift
// WRONG — drifts
let a = LyrebirdRoutine { ctx in
while true { ctx.add(Kick()); try ctx.wait(beats: 1) }
}
let b = LyrebirdRoutine { ctx in
while true { ctx.add(Bass()); try ctx.wait(beats: 1) }
}
// RIGHT — locked to same grid
let clock = LyrebirdClock(engine: engine, bpm: 120.0)
let a = LyrebirdRoutine { ctx in
while true {
try ctx.waitUntil(sampleTime: clock.nextBeat())
ctx.add(Kick())
}
}
let b = LyrebirdRoutine { ctx in
while true {
try ctx.waitUntil(sampleTime: clock.nextBeat())
ctx.add(Bass())
}
}
```
### API
```swift
let clock = LyrebirdClock(engine: engine, bpm: 120.0)
```
| Property / Method | Type | Description |
|---|---|---|
| `epoch` | `SampleTime` | Engine sample time at clock creation. |
| `bpm` | `Double` (get/set) | Tempo. Setter accumulates beats elapsed before the change — beat count is continuous. |
| `currentBeat` | `Double` | Beats elapsed since `epoch`, accumulated across tempo changes. |
| `sampleTime(beat:)` | `SampleTime` | Convert beat number → sample time. May return a past sample time. |
| `nextBeat(after:)` | `SampleTime` | Sample time of the next whole beat after `beat` (or `currentBeat` if nil). Exclusive: `nextBeat(after: 4.0)` returns beat 5. |
### Tempo changes
```swift
// Beat count is continuous across bpm changes
clock.bpm = 90.0 // _beatOffset accumulates beats since last change
```
`sampleTime(beat:)` is only accurate within the current tempo segment — beats since the last `bpm` change. Past-segment queries return mathematically extrapolated values, not a reconstruction of the prior tempo.
### Multi-voice example
```swift
let clock = LyrebirdClock(engine: engine, bpm: 120.0)
// Kick on every beat
let kick = LyrebirdRoutine { ctx in
while true {
try ctx.waitUntil(sampleTime: clock.nextBeat())
ctx.add(KickDrum())
}
}
// Bass on every other beat (offset by 0.5)
let bass = LyrebirdRoutine { ctx in
while true {
try ctx.waitUntil(sampleTime: clock.sampleTime(beat: floor(clock.currentBeat) + 1.5))
ctx.add(BassSynth())
}
}
kick.start(engine: engine)
bass.start(engine: engine)
```
### Thread safety
`LyrebirdClock` is `Sendable`. Multiple routines may call `currentBeat`, `sampleTime(beat:)`, and `nextBeat(after:)` concurrently. Only one thread should write `bpm`.
### Following an external MIDI clock
To drive `LyrebirdClock` from incoming MIDI Clock (0xF8) messages, use
`MIDIClockFollower`. See `docs/tooling/midi-clock-sync.md` for the full wiring guide.
+132
View File
@@ -0,0 +1,132 @@
# Package Targets
Lyrebird is structured as a multi-target Swift package. This document describes each target, its role, and when to use it.
---
## Core Targets
### `LyrebirdC`
Thin C shim. Exposes `fesetenv(FE_DFL_DISABLE_DENORMS_ENV)` to Swift — a C-only macro sentinel that Swift cannot reference directly. Linked into `Lyrebird` automatically; you never import this directly.
### `Lyrebird`
The core framework. Import this in any synthesis code.
```swift
import LyrebirdSynth
```
Provides: `SynthesisEngine`, `Generator`/`Synthesizer` protocols, all built-in generators, `LyrebirdBuffer`, `ParameterNode`, bus system, scheduling, and `CoreAudioDriver`. Links `CoreAudio`, `AudioToolbox`, and `Accelerate`.
Built as a `.dynamic` library — required by the Xcode 26 SPM regression (see `Package.swift` note). Reverts to `.static` when that regression is fixed.
### `LyrebirdUI`
Optional GUI module. Import alongside `Lyrebird` when you need parameter controls.
```swift
import LyrebirdUI
```
Provides: `LyrebirdWindow` (AppKit/SwiftUI host), `@SynthParam` property wrapper, and pre-built slider/knob views. Uses Swift 5 language mode to avoid actor-isolation diagnostics in SwiftUI/AppKit interop.
**Rule:** never import `LyrebirdUI` in `Lyrebird` — GUI code must stay in this module only.
---
## Executable Targets
### `LyrebirdCLI` — `lyrebird` command
Project scaffolding, running, and export from the command line.
```
lyrebird new MyProject # scaffold a new project
lyrebird run # compile and run
lyrebird export MySynth # generate a SynthesizerBase template
lyrebird repl # start Swift REPL with Lyrebird importable
```
Provides an interactive `lyrebird>` shell (via LineNoise) with history and tab completion. Uses Swift 5 language mode — LineNoise predates Swift 6 concurrency annotations.
See [cli-guide.md](cli-guide.md) for a full walkthrough.
### `LyrebirdDemo` — headless audio starting point
Command-line synthesis without a GUI. Best starting point for a new synthesis program.
```
swift run LyrebirdDemo
```
Demonstrates: `SynthesizerBase`, `@LiveParam`, `OscSin`, `DelayLine`, `engine.add`/`remove`, and RT-safe parameter updates from the main thread. Runs real-time audio via `CoreAudioDriver`, plays for a few seconds, then stops.
**Copy this target** when you want a headless synthesis starting point. Swap `CoreAudioDriver()` for `NRTDriver(outputURL:duration:)` to render offline to a file — see [nrt-guide.md](nrt-guide.md).
### `LyrebirdUIDemo` — GUI starting point
AppKit application with SwiftUI parameter controls. Best starting point for a windowed synthesis app.
```
swift run LyrebirdUIDemo
```
Demonstrates: `LyrebirdWindow`, `@SynthParam`-bound slider views, `AppDelegate` lifecycle (start/stop engine), and `NoteController` pattern for driving a `Synthesizer` from UI state.
**Copy this target** when you want a windowed synthesis app.
### `LyrebirdBenchmark`
Micro-benchmarks for DSP hot paths. Not a user starting point — run when profiling filter, vDSP, or block-processing performance.
```
swift run -c release LyrebirdBenchmark
```
Reports ns/block and ns/sample for scalar vs. vDSP biquad implementations at `blockSize = 512`. Always run with `-c release`; debug builds give meaningless numbers.
---
## Test Targets
| Target | What it covers |
|---|---|
| `LyrebirdTests` | Core engine: generators, bus system, scheduling, file I/O, all built-in DSP |
| `LyrebirdUITests` | `LyrebirdUI` module: parameter binding, `@SynthParam`, window lifecycle |
| `LyrebirdCLITests` | `LyrebirdCLI`: scaffolder, runner, exporter, REPL commands |
Run all tests:
```
swift test
```
---
## Dependency Map
```
LyrebirdC
└── Lyrebird (links CoreAudio, AudioToolbox, Accelerate)
├── LyrebirdUI (SwiftUI + AppKit, Swift 5 mode)
├── LyrebirdDemo
├── LyrebirdBenchmark
└── LyrebirdUIDemo (also links LyrebirdUI)
LyrebirdCLI (links LineNoise, Swift 5 mode)
```
---
## Choosing a Starting Point
| Goal | Use |
|---|---|
| Headless audio synthesis | `LyrebirdDemo` |
| Windowed app with GUI controls | `LyrebirdUIDemo` |
| CLI tooling / REPL | `lyrebird` (`LyrebirdCLI`) |
| Measure DSP performance | `LyrebirdBenchmark` (release build) |
| Framework import only | `import LyrebirdSynth` |
| GUI parameter controls | `import LyrebirdUI` |
+275
View File
@@ -0,0 +1,275 @@
# REPL → Compile Workflow
This guide walks from a live-coding sketch in the Lyrebird REPL to a fully
compiled, testable Swift Package. Every step uses the `lyrebird` CLI so no
manual project setup is required.
## Overview
```
lyrebird repl → prototype a patch in Swift
lyrebird new → scaffold a compiled project
lyrebird export → generate a Synthesizer source file
(edit) → fill in the signal graph
lyrebird run → compile and run
swift test → verify with tests
```
Because Lyrebird has no separate scripting language, code written in the REPL
(`swift build` + `swift repl` with `-I`/`-L`/`-l` flags) is already real Swift. The same `OscSin`, `Out`, and
`SynthesizerBase` APIs that work in the REPL compile identically in a project.
---
## Step 1 — Prototype in the REPL
Launch the REPL from the Lyrebird package directory:
```sh
lyrebird repl
```
Write your synthesizer inline and iterate until it sounds right:
```swift
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 2,
driver: CoreAudioDriver()
)
try engine.start()
// Example — your synthesizer, defined by subclassing SynthesizerBase
final class KickDrum: SynthesizerBase {
@LiveParam var freq: LyrebirdFloat = 60.0
@LiveParam var decay: LyrebirdFloat = 0.3
override func build() {
let osc = OscSin.Audio(freq: $freq)
let env = EnvelopeGen.Audio(envelope: Envelope(
segmentCount: 2,
levels: [1.0, 1.0, 0.0],
durations: [0.005, $decay]
))
output(bus: 0, source: osc * env)
}
}
let kick = KickDrum()
try engine.add(kick)
// Tune parameters while audio runs — no try, no string.
kick.freq = 80.0
kick.decay = 0.2
```
There is no REPL "state capture" step — you keep the code you wrote and copy
it into the compiled project directly.
---
## Step 2 — Scaffold a Compiled Project
When you are happy with the sketch, scaffold a new Swift Package in a directory
of your choice:
```sh
lyrebird new MyPiece
```
This creates:
```
MyPiece/
├── Package.swift ← swift-tools-version 6.0, macOS 15
├── Sources/
│ └── MyPiece/
│ └── main.swift ← engine setup + entry point
└── Tests/
└── MyPieceTests/
└── MyPieceTests.swift ← starter test suite
```
---
## Step 3 — Export a Synthesizer Template
Generate a starter source file for your synthesizer:
```sh
lyrebird export KickDrum --to MyPiece/Sources/MyPiece/KickDrum.swift
```
The generated file is ready to compile — it only needs the signal graph filled
in with the code you wrote in the REPL:
```swift
import LyrebirdSynth
// MARK: - KickDrum
/// A Lyrebird synthesizer — generated by `lyrebird export KickDrum` (your subclass).
final class KickDrum: SynthesizerBase {
// MARK: - Parameters
@LiveParam var freq: LyrebirdFloat = 60.0
@LiveParam var decay: LyrebirdFloat = 0.3
// MARK: - Build
override func build() {
// Paste the signal graph from your REPL session here.
let osc = OscSin.Audio(freq: $freq)
let env = EnvelopeGen.Audio(envelope: Envelope(
segmentCount: 2,
levels: [1.0, 1.0, 0.0],
durations: [0.005, $decay]
))
output(bus: 0, source: osc * env)
}
}
```
You can export multiple synthesizers; each goes in its own file. All files
in the same target share a module namespace so no imports are needed between
them.
---
## Step 4 — Wire the Synthesizer in main.swift
Open `MyPiece/Sources/MyPiece/main.swift` and instantiate your synthesizer:
```swift
// MyPiece — entry point
import Foundation
import LyrebirdSynth
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 44100,
numOutputChannels: 2,
numInputChannels: 2,
driver: CoreAudioDriver()
)
let kick = KickDrum()
try engine.add(kick)
do {
try engine.start()
} catch {
fatalError("Engine failed to start: \(error)")
}
print("MyPiece running — press Ctrl+C to stop")
RunLoop.main.run()
```
---
## Step 5 — Resolve the Lyrebird Dependency
Open `MyPiece/Package.swift` and update the placeholder URL to the published
Lyrebird repository:
```swift
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"),
```
Resolve the dependency graph:
```sh
cd MyPiece
swift package resolve
```
---
## Step 6 — Run
```sh
lyrebird run # debug build
lyrebird run --release # release build (recommended for real-time audio)
```
`lyrebird run` exits with the same code as `swift run`, so CI pipelines can
detect failures normally.
---
## Step 7 — Test
The scaffolded `MyPieceTests.swift` provides a starter test. Add
synthesizer-specific tests alongside it:
```swift
// Tests/MyPieceTests/KickDrumTests.swift
import Testing
import LyrebirdSynth
import MyPiece
@Suite("KickDrum")
struct KickDrumTests {
@Test func outputIsNonSilentAfterOneBlock() throws {
let engine = SynthesisEngine(
blockSize: 512, sampleRate: 44100,
numOutputChannels: 2, numInputChannels: 2,
driver: OfflineDriver()
)
try engine.start()
let kick = KickDrum()
try engine.add(kick)
engine.processBlock(inputSamples: [])
#expect(engine.audioBuses[0].contains { $0 != 0.0 })
engine.stop()
}
}
```
Run all tests with:
```sh
swift test
```
---
## Why Code Compiles Identically
There is no translation step between REPL and compiled code.
- `lyrebird repl` runs `swift build`, then launches `swift repl` with module/library
flags pointing at `.build/debug`, so the Lyrebird package is importable. The
`import LyrebirdSynth` in the REPL and in
a compiled project resolve to the same module.
- `SynthesizerBase` is declared `open`, so it can be subclassed from any
module — both in tests that use `@testable import LyrebirdSynth` and in
standalone projects that import it as a dependency.
- `@LiveParam`, generators (`OscSin`, `Out`, etc.), and the engine API are all `public` — no special REPL-only API exists.
The only difference is that REPL code is interpreted and compiled code is
optimised. For a release build of a real-time audio piece, `lyrebird run
--release` enables full optimisations.
---
## Command Reference
| Command | Description |
|---|---|
| `lyrebird repl` | Launch Swift REPL with Lyrebird pre-loaded |
| `lyrebird new <name>` | Scaffold a new Swift Package |
| `lyrebird export <name>` | Export a `SynthesizerBase` template to `<name>.swift` |
| `lyrebird export <name> --to <path>` | Export to an explicit path |
| `lyrebird export <name> --to <path> --overwrite` | Overwrite an existing file |
| `lyrebird run` | Build and run the current project (debug) |
| `lyrebird run --release` | Build and run in release mode |
| `swift test` | Run the project's test suite |
See `docs/tooling/repl.md` for REPL details and `docs/tooling/project-system.md`
for the full CLI reference.
+260
View File
@@ -0,0 +1,260 @@
# Xcode File Templates
Lyrebird ships a small set of Xcode file templates (`.xctemplate` bundles) for the
common code shapes — Generators, Synthesizers, and Tasks. After install, they appear
in Xcode's New File dialog (`⌘N`) under a **Lyrebird** section.
---
## Install
Two paths — both copy the same templates to
`~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`. No Xcode
restart required; Xcode rescans on next `⌘N`.
### Via the `lyrebird` CLI (preferred)
```sh
lyrebird install-templates # error if already installed
lyrebird install-templates --force # overwrite existing install
lyrebird uninstall-templates
```
The CLI bundles every `.xctemplate` as an SPM resource on the `LyrebirdCLI`
target, so the binary needs no access to the repo at install time — copy
`lyrebird` to `/usr/local/bin` and `install-templates` keeps working from
any working directory.
Both verbs are also available inside the interactive `lyrebird>` shell.
### Via shell script (repo-checkout install)
From the repo root, equivalent to the CLI:
```sh
bash scripts/install-xcode-templates.sh
bash scripts/install-xcode-templates.sh --dry-run # preview only
bash scripts/uninstall-xcode-templates.sh
```
Re-running `install-xcode-templates.sh` is idempotent (`rsync --delete`).
Both source paths read from `Sources/LyrebirdCLI/Resources/XcodeTemplates/`,
which lives there so SPM can bundle them as a target resource.
---
## Templates shipped
### Tier 1 — usable from any project that depends on Lyrebird
| Template | Generates | Use when |
|---|---|---|
| **Lyrebird Generator** | `public enum <Name>` with `_Base`, `Audio`, `Control` + `GeneratorEnum` conformance | Implementing a new signal-producing or signal-processing Generator family. |
| **Lyrebird Synthesizer** | `final class <Name>: SynthesizerBase` with `@LiveParam` slots and a stubbed `build()` body | Defining a new synth (oscillator + envelope + output) that you add to an engine via `engine.add(_:)`. |
| **Lyrebird Task** | `func make<Name>() -> LyrebirdTask` factory plus a private example Synthesizer | Scheduling a stream of events from a background thread with pause/resume/stop support. |
These templates start with `import LyrebirdSynth` (or `@_spi(LyrebirdExtensions) import
LyrebirdSynth` for the Generator template, which references the SPI-marked `MulAddSpec`)
and use only public + SPI API. They compile cleanly in any project that has Lyrebird
as a Swift Package dependency.
### Tier 1b — in-tree contributor templates
| Template | Generates | Use when |
|---|---|---|
| **Lyrebird Oscillator** | `public enum <Name>` whose `_Base` extends `OscillatorBase`; inherits `_phase` / `_freqInput` / `_freqIsGenerator` / `_mulAdd` | Adding a new oscillator family inside the Lyrebird module. Drop the file under `Sources/Lyrebird/Generators/Oscillators/`. |
| **Lyrebird Noise Generator** | `public enum <Name>` whose `_Base` extends `NoiseBase`; inherits `rngState` + `_mulAdd`; xorshift64 PRNG seeded via `lyrebirdSeedXorshift64(from:mixConstant:)` | Adding a new noise / random-source family. Drop the file under `Sources/Lyrebird/Generators/Noise/`. |
| **Lyrebird Filter** | Audio-only `final class Audio: GeneratorBase` using `runRBJBiquadBlock` with a `computeCoefficients` closure carrying the Audio EQ Cookbook formula | Adding a new RBJ biquad filter shape. Drop the file under `Sources/Lyrebird/Generators/Filters/`. |
These templates extend module-internal base classes (`OscillatorBase`, `NoiseBase`)
or call module-internal helpers (`runRBJBiquadBlock`, `lyrebirdSeedXorshift64`,
`normalizeLFPhase`, `fillRampedResult`) and are **only useful inside the Lyrebird
module**. Each generated file carries an in-tree-only banner comment at the top.
External users adding their own oscillators / noise / filters should start from
the basic **Lyrebird Generator** template and declare the relevant state (phase
accumulator, PRNG state, biquad coefficients) inline.
### Tier 2 — extended Generator + Synthesizer shapes
| Template | Generates | Use when |
|---|---|---|
| **Lyrebird Demand Generator** | `final class <Name>: DemandGenerator` with `nextValue()` / `reset()` / `isExhausted` | Defining a pure value source consumed by `Demand.Audio` / `Demand.Control` pullers — one value per trigger edge. |
| **Lyrebird Multi-Channel Generator** | `final class <Name>: GeneratorBase, AudioGenerator` with fixed `outputChannelCount`, multi-row `_result`, channel-aware mul/add | Adding a Generator whose output has 2+ channels (panners, spatial decoders, multi-bus mixers). Modeled on Pan2. |
| **Lyrebird Synthesizer (UI)** | `final class <Name>: SynthesizerBase` with `@UIParam` slots and a stubbed `build()` body | Defining a synth whose parameters bind to SwiftUI controls (`ParameterKnob`, `ParameterSlider`, `ParameterXY`). Requires the LyrebirdUI module. |
| **Lyrebird UI View** | `public struct <Name>: View` with `@Observable` controller, `ScopeCapture` + `LyrebirdScopeView`, parameter knobs, play/stop button | Building a SwiftUI front-end for a `@UIParam`-annotated synth. Requires the LyrebirdUI module. |
| **Lyrebird Generator Test Suite** | `@Suite("…") struct <Name> { @Test … }` using `makeTestEngine` / `makeSynthGraph` / `advanceBlock` helpers | Adding a Swift Testing suite for a new Generator. Drop the file into `Tests/LyrebirdTests/` — the helpers are module-internal. |
| **Lyrebird NRT Render** | `main.swift` with a `SynthesizerBase` stub and an NRTDriver that renders the duration to disk | Building a standalone executable target that produces an offline audio file. Drop the file into the `Sources/<exec-target>/` directory of an `executableTarget`. |
The UI templates (`Synthesizer (UI)` and `UI View`) add `import LyrebirdUI` and
compile cleanly in projects with both `Lyrebird` and `LyrebirdUI` as
dependencies. The test-suite and NRT templates only compile in their respective
target kinds (`Test`, `executableTarget`) and are reported as `SKIP` in the
in-tree / external validation passes by design.
### Tier 3 — extended subsystems (MIDI / OSC / Spectral / Buffer / Process / AUv3)
| Template | Generates | Use when |
|---|---|---|
| **Lyrebird Spectral Processor** | `final class <Name>: SpectralProcessor` with a `process(spectral:engine:)` body that walks every bin in `SpectralBuffer` | Adding a custom FFT-domain transform (filter, pitch shift, cross-synthesis, freeze). Wire into `SpectralChain.Audio` as a `.mono` stage. |
| **Lyrebird MIDI Handler** | `func make<Name>(engine:clientName:) throws -> MIDI` factory with `noteOn` / `noteOff` / `controlChange` dispatch + a `midiNoteToHz` helper | Wiring CoreMIDI input to engine-level state. Handler closure runs on `lyrebird.midi` queue (not RT). |
| **Lyrebird OSC Handler** | `func make<Name>(engine:port:) throws -> OSCServer` factory with starter `/freq` / `/amp` / `/note/{on,off}` handlers + a `doubleValue(_:)` argument-coercion helper | Wiring an OSC UDP server to engine state. Handlers run on `lyrebird.osc.handlers` queue. |
| **Lyrebird Buffer Reader** | `final class <Name>: SynthesizerBase` that loads a multichannel `LyrebirdBuffer` at init and plays it via `PlayBuffer.Audio` with `nativeRateScale` SR compensation | Building a sample-playback Synthesizer (loop / one-shot / rate-modulated). |
| **Lyrebird Process** | `struct <Name>: LyrebirdProcessFactory` whose `createProcess()` returns a `LyrebirdProcess` with a 4-point envelope (attack / sustain / release / silence), `releaseNode`, async body closure, and `onRelease` / `onFinished` callbacks | Building an envelope-governed audio process (Lyrebird's equivalent of SuperCollider's `ProcMod`). |
| **Lyrebird AUv3 Source-Slot Synth** | A `SynthesizerBase` + `LyrebirdAudioUnit` pair (Synth class + `<Name>AudioUnit` AU wrapper) with `parameterMetadata()` exposing `@LiveParam` slots to the host. Includes step-by-step Info.plist + `AUViewController` integration notes. | Wrapping a Synthesizer as an Audio Unit App Extension (.appex) for Logic / GarageBand / AUM / Loopy Pro. Pair with the `Demos/LyrebirdAUv3Demo` reference project. |
All six Tier 3 templates compile in projects depending on Lyrebird as a Swift
Package and are reported as `OK (external)` by the validator. None require
LyrebirdUI.
Each template prompts for a name in Xcode's dialog. The name becomes both the file
name and the top-level identifier inside the file.
---
## Generated shapes
### Lyrebird Generator
The Generator template emits the canonical pattern matched by every built-in
Generator family in `Sources/Lyrebird/Generators/`:
```swift
public enum MyGenerator {
public class _Base: GeneratorBase {
let inputSource: any ValidGeneratorInput
let _mulAdd: MulAddSpec
public init(
_ signal: any ValidGeneratorInput,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) { ... }
}
public final class Audio: _Base, AudioGenerator {
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
// sample-rate processing
}
}
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
// block-rate scalar + linear ramp to previousOutputValue
}
}
}
extension MyGenerator: GeneratorEnum {
public typealias AudioType = MyGenerator.Audio
public typealias ControlType = MyGenerator.Control
}
```
Fill in `_transform(_:)` (one line) and you have a working Audio + Control pair
with `mul` / `add` wiring and the sub-block ramp pattern already in place.
If you only need one rate, delete the other class plus its line in the
`GeneratorEnum` extension.
See [`writing-generators.md`](../protocols/writing-generators.md) for the full
Generator protocol contract, shared helpers, and decision rules.
### Lyrebird Synthesizer
```swift
public final class MySynth: SynthesizerBase {
@LiveParam public var frequency: Double = 440.0
@LiveParam public var amplitude: Double = 0.25
public override func build() {
let osc = OscSin.Audio(freq: $frequency)
output(bus: 0, source: osc * $amplitude)
}
}
```
Use `$paramName` (the projected value of `@LiveParam`) to pass a live-mutable
parameter as a generator input. Direct mutation (`synth.frequency = 880.0`) is
atomic and RT-safe.
See [`synthesizer.md`](../protocols/synthesizer.md) for the full Synthesizer
protocol and lifecycle.
### Lyrebird Task
```swift
public func makeMyTask() -> LyrebirdTask {
LyrebirdTask { ctx in
while true {
let note = ExampleNote()
ctx.add(note)
try ctx.wait(seconds: 0.25)
}
}
}
```
Call `task.start(engine:)` to begin, `task.pause()` / `task.resume()` to control,
`task.stop()` to exit cleanly (raises `LyrebirdRoutineError.stopped` inside the
next `wait`, which the closure handles internally).
See [`routine-task.md`](routine-task.md) for the full scheduling model.
---
## Validating templates
Templates are validated by `scripts/validate-xcode-templates.sh`. Three modes:
```sh
bash scripts/validate-xcode-templates.sh # --quick (default)
bash scripts/validate-xcode-templates.sh --full # + in-tree compile against Lyrebird
bash scripts/validate-xcode-templates.sh --external # + compile as an external SPM package
```
`--quick` runs `plutil -lint` on each `TemplateInfo.plist` and parses the
expanded `___FILEBASENAME___.swift` with `swift -frontend -parse` to confirm
the generated code is well-formed Swift.
`--full` adds an in-tree compile pass: it drops the expanded file into
`Sources/Lyrebird/Generators/Math/Probe.swift`, runs `swift build`, and removes
the file via `trap` so the working tree stays clean even on failure. This catches
template breakage from upstream API renames (e.g. `EnvGen` → `EnvelopeGen`).
`--external` adds a third pass: for every template whose body contains
`import LyrebirdSynth` (Tier 1 templates), the script creates a temporary SPM package
that depends on the local Lyrebird repo path, drops the expanded file into it,
and runs `swift build`. This proves the template works for users who consume
Lyrebird as a Swift Package dependency. In-tree-only templates (Tier 1b — no
`import LyrebirdSynth` line) are reported as `SKIP` here by design.
CI runs `--external` on every PR that touches `Xcode/Templates/` or
`Sources/Lyrebird/`.
---
## Adding a new template
1. Create `Xcode/Templates/Lyrebird/<Name>.xctemplate/` with two files:
- `TemplateInfo.plist` — kind, summary, options, allowed types
- `___FILEBASENAME___.swift` — source body with Xcode placeholders
2. Use the placeholders Xcode expands:
- `___FILEBASENAME___` — file name (preserves user's casing)
- `___FILEBASENAMEASIDENTIFIER___` — sanitized Swift identifier
- `___FILEHEADER___` — the project's standard file header comment block
- `___FULLUSERNAME___`, `___DATE___`, `___YEAR___` — author / date stamps
3. (Optional) Add a `TemplateIcon.png` (48×48) and `TemplateIcon@2x.png` (96×96)
for the Xcode dialog icon.
4. Add custom prompts in `TemplateInfo.plist > Options` if the template needs
user input beyond the file name (parameter types, channel count, etc.).
5. Run `bash scripts/validate-xcode-templates.sh --full` — must pass.
6. Add an entry to the "Templates shipped" table above.
The `TemplateInfo.plist` schema is described in Apple's Xcode docs under
"File Templates" — the same format is used by Xcode's built-in templates at
`/Applications/Xcode.app/Contents/Developer/Library/Xcode/Templates/File Templates/`.
Copy one of those as a starting point if you need an exotic option type.