Files
Lyrebird/docs/tooling/nrt-guide.md
T
josh 560724d116 v1.3.0 release: graceful-release fix, quickstart template + demo, documentation accuracy pass
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated
  synths were hard-freed instead of released).
- New: quickstart project template + LyrebirdQuickstartDemo.
- Docs: every example typechecked or provably illustrative (426->542); ~20
  wrong-API examples fixed; root docs brought under the compile guard.
- Fixed: NRT/Score demo Package.swift build from terminal again.

See RELEASES.md for details.
2026-07-17 14:05:01 -07:00

438 lines
16 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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 `Double` (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 |