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
+322
View File
@@ -0,0 +1,322 @@
# 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.
- ``SynthesisEngine`` defaults to a pending event queue capacity of 1024. For large scores pass `eventQueueCapacity:` (must be a power of two) to ``SynthesisEngine/init(blockSize:controlBlockSize:sampleRate:numOutputChannels:numInputChannels:numAudioBuses:numControlBuses:eventQueueCapacity:driver:)`` — a non-power-of-two value traps at startup.
### 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: .caf, sampleRate: 44100)
try buf.write(to: url, format: .aiff, sampleRate: 44100)
try buf.write(to: url, format: .wav, sampleRate: 44100)
```
All formats write 32-bit float (Float32). `Double` (Double) values are downcast 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))
}
}
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 |
| 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>