Files
Lyrebird/docs/tooling/project-system.md
T
2026-06-01 18:27:40 -07:00

312 lines
12 KiB
Markdown

# 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`.