Files
Lyrebird/Sources/Lyrebird/Lyrebird.docc/NRTGuide.md
T

362 lines
14 KiB
Markdown

# Non-Real-Time Rendering
@Metadata {
@PageKind(article)
}
Render synthesis output to an audio file without audio hardware, faster than real time.
## Overview
NRT rendering 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
| 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 |
## Approach 1 — NRTDriver
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,
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.add(SineTone())
try engine.start() // blocks until 5 seconds are rendered, then returns
```
**Important:** `NRTDriver.start()` is synchronous — it renders all blocks, writes the file, and returns. Add all synthesizers **before** `start()`. No `RunLoop.main.run()` needed.
### Add synthesizers before start()
```swift
// CORRECT
try engine.add(SineTone()) // your SynthesizerBase subclasses
try engine.add(BassLine())
try engine.start()
// WRONG — synthesizers added after start() are never rendered
try engine.start()
try engine.add(SineTone())
```
### Output file
`NRTDriver` writes CAF: 32-bit float, interleaved, at the engine's sample rate. Created or overwritten at `outputURL`, closed when `start()` returns.
### Duration
```swift
NRTDriver(outputURL: url, duration: 10.0) // 10 seconds
NRTDriver(outputURL: url, duration: 0.5) // 500 ms
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 — 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 = 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.
- **Large scores need two knobs raised, not one.** ``SynthesisEngine`` defaults to a pending event queue capacity of 1024 and a per-block event budget of 256. Pass both to ``SynthesisEngine/init(blockSize:controlBlockSize:sampleRate:numOutputChannels:numInputChannels:numAudioBuses:numControlBuses:eventQueueCapacity:maxEventsPerBlock:driver:)``:
- `eventQueueCapacity:` must hold every event you enqueue before `start()`, since NRT renders synchronously and nothing can refill the queue mid-render. Must be a power of two — a non-power-of-two value traps at startup.
- `maxEventsPerBlock:` bounds the future-event **look-ahead** carried across block boundaries. This is the one that silently bites: pre-schedule 5,000 events and the first block keeps only `maxEventsPerBlock` of them in carry-over and **drops the rest**. Check ``SynthesisEngine/perBlockEventDropCount`` (a console warning is also printed after the render).
Either raise both, or feed events just-in-time from a ``TriggerListener`` — `NRTDriver` drains its handlers after every block, so a handler can schedule the next few events as the render advances, keeping the in-flight count small. See <doc:Scheduling>.
### Soundfile input
Pass an audio file into the engine as simulated hardware input using `inputURL:` and `inputStartOffset:`.
```swift
let engine = SynthesisEngine(
blockSize: 512,
sampleRate: 48000,
numOutputChannels: 2,
numInputChannels: 2, // must be ≥ file channel count
driver: NRTDriver(outputURL: outputURL, duration: 5.0,
inputURL: URL(fileURLWithPath: "source.wav"),
inputStartOffset: 0.0) // seconds to skip into the file
)
```
Each block, the driver reads `blockSize` frames from the file and writes them to the engine's input buses — exactly as live hardware would. `In.Audio(bus: n)` uses raw bus indices; input channels start at `numOutputChannels`, so with 2 output channels, input channel 0 is bus 2, input channel 1 is bus 3:
```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
output(bus: 0, source: inL)
output(bus: 1, source: 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 ends before `duration`, remaining blocks receive silence — no crash or error.
- `inputStartOffset` skips that many seconds into the file before rendering. Negative values are clamped to 0.
- Sample-rate conversion is handled automatically by `ExtAudioFile` if the file's rate differs from the engine's.
- Pass `inputURL: nil` (the default) to disable file input and restore original behaviour.
## Approach 2 — RecordBuffer + LyrebirdBuffer.write()
Use when you need a specific signal path, AIFF/WAV output, or real-time capture.
### Step 1 — allocate a buffer
```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
let recorder = RecordBuffer.Audio(input: sig, buffer: captureBuf, loop: false)
output(bus: 0, source: Pan2(input: recorder))
}
}
```
`RecordBuffer.Audio` passes the input through unchanged — it records and plays simultaneously.
### Step 3 — render, then write
```swift
let synth = RecordingSynth(captureBuf: captureBuf)
try engine.add(synth)
try engine.start() // renders
let aiffURL = URL(fileURLWithPath: "output.aiff")
try captureBuf.write(to: aiffURL, format: .aiff, sampleRate: sampleRate)
```
## Output Formats
### NRTDriver — CAF only
To convert after rendering:
```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: .cafFloat32, sampleRate: 44100)
try buf.write(to: url, format: .aiffFloat32, sampleRate: 44100)
try buf.write(to: url, format: .wavFloat32, sampleRate: 44100)
// Integer WAV encodings, for smaller files / DAW interchange:
try buf.write(to: url, format: .wavInt16, sampleRate: 44100)
try buf.write(to: url, format: .wavInt24, sampleRate: 44100)
// RF64 / BW64 — WAV extension, 64-bit sizes, no 4 GB cap:
try buf.write(to: url, format: .rf64Float32, sampleRate: 44100)
try buf.write(to: url, format: .rf64Int24, sampleRate: 44100)
// Compressed M4A (offline writers only — LyrebirdBuffer.write / NRTDriver):
try buf.write(to: url, format: .aacHigh, sampleRate: 44100) // AAC ~256 kbps (lossy)
try buf.write(to: url, format: .aacMedium, sampleRate: 44100) // AAC ~128 kbps (lossy)
try buf.write(to: url, format: .alac, sampleRate: 44100) // Apple Lossless
```
The buffer's `Double` samples are handed to `ExtAudioFile` as native Float32; the
container's on-disk encoding drives the conversion. The `.cafFloat32` /
`.aiffFloat32` / `.wavFloat32` cases are lossless 32-bit float; `.wavInt16` /
`.wavInt24` quantise to signed 16/24-bit PCM. (`.caf` / `.aiff` / `.wav` remain
as Float32 shorthands.)
**Files past 4 GB**: plain `.wav`/`.aiff` are limited to 4 GB (32-bit size fields) and
throw `fileTooLargeForContainer` past that. For a big file that must keep the `.wav`
extension, use `.rf64Float32` / `.rf64Int24` — RF64/BW64 (EBU Tech 3306) carries 64-bit
sizes in a `ds64` chunk (written by Lyrebird's own ``RF64Writer``; CoreAudio reads it
back). `.cafFloat32` is the other uncapped option.
**Compressed output** (`.aacHigh` / `.aacMedium` / `.alac`): AAC and Apple Lossless in an
`.m4a` container, encoded by `ExtAudioFile`/`AudioConverter`. **Offline writers only** —
`LyrebirdBuffer.write` and `NRTDriver`; ``DiskOut/Audio`` throws `compressedFormatNotSupported`
(real-time streaming of a compressed encoder is out of scope). AAC is lossy and **not
sample-accurate** (encoder priming/padding shifts the signal a few ms), so frame-count
round-trips aren't exact; ALAC is lossless of a 24-bit-quantised source. Introspect a
format with ``AudioFileFormat/isCompressed`` (true for these three) and, for AAC, its
target rate via ``AudioFileFormat/aacBitrate``.
## 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))
}
}
let cafURL = URL(fileURLWithPath: "fm_tone.caf")
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)
}
```
## NRT vs RT
| | `CoreAudioDriver` | `NRTDriver` |
|---|---|---|
| `start()` blocks | No | Yes |
| `engine.add()` timing | Anytime audio is running | Before `start()` only |
| Speed | Real-time | Faster than real-time |
| Audio hardware | Required | Not required |
| Output | DAC / speakers | File on disk |
| CI/batch use | Not suitable | Yes |
## Error Reference
| Error | Cause | Fix |
|---|---|---|
| `NRTDriverError.cannotCreateFile` | Bad output URL or permissions | Check the path and disk space |
| `NRTDriverError.writeFailed` | Disk I/O error during render | Check disk space and permissions |
| `NRTDriverError.cannotOpenInputFile` | `inputURL` not found or unreadable | Verify the file path exists |
| `NRTDriverError.cannotSeekInputFile` | `inputStartOffset` beyond file end | Reduce `inputStartOffset` |
| `NRTDriverError.inputReadFailed` | Disk I/O error reading input file | Check disk health |
| `NRTDriverError.invalidDuration` | `duration` is negative, NaN, or infinite | Pass a finite, non-negative duration |
| `NRTDriverError.fileTooLargeForContainer` | WAV/AIFF render projected past the 4 GB RIFF cap | Use `format: .cafFloat32`, or shorten `duration` |
| `LyrebirdBufferIOError.fileTooLargeForContainer` | `LyrebirdBuffer.write` to WAV/AIFF projected past 4 GB | Use `.cafFloat32`, or split/shorten the buffer |
| Silent output / all-zeros file | Synthesizers added after `start()` | Move all `engine.add()` before `start()` |
| File truncated short | `duration` too short | Increase `NRTDriver` duration |
## See Also
- <doc:EngineSetup>
- <doc:CLIGuide>
- <doc:Targets>