Files
josh 844dc4d9cd v2.1.0 release: Swift 6.4 modernization
Typed throws across the closed-error-set APIs (OSC, MIDI, engine add/schedule,
bus/config/parameter, and the WAV/RF64/Spectral file codecs — source-compatible
narrowing, new .ioFailure cases), plus internal hardening: NSLock-guarded
scheduling/MIDI state moved to Mutex<State>, and the Spectral/FFT scratch owners
moved to a ~Copyable RTScratchBuffer RAII buffer. No API or behavioral change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 19:54:59 -07:00

18 KiB
Raw Permalink Blame History

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.

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.

// 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.

// 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.

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.

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.

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.

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.

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.

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

// 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:

let stereoSig = expand([oscL, oscR]) { $0 }
let recorder = RecordBuffer.Audio(input: stereoSig, buffer: captureBuf, loop: false)

Step 3 — render, then write

With NRTDriver:

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):

// 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):

afconvert -f AIFF -d BEF32 output.caf output.aiff
afconvert -f WAVE -d LEF32 output.caf output.wav

LyrebirdBuffer.write() — AIFF, WAV, or CAF

try buf.write(to: url, format: .cafFloat32,  sampleRate: 44100)  // default
try buf.write(to: url, format: .aiffFloat32, sampleRate: 44100)  // AIFF-C, Float32
try buf.write(to: url, format: .wavFloat32,  sampleRate: 44100)  // WAV, Float32

// Integer WAV encodings, for smaller files / DAW interchange:
try buf.write(to: url, format: .wavInt16, sampleRate: 44100)     // WAV, 16-bit PCM
try buf.write(to: url, format: .wavInt24, sampleRate: 44100)     // WAV, 24-bit PCM
Format Extension Endian Encoding Channels Notes
.cafFloat32 .caf little-endian 32-bit float up to 8 Best for macOS; default
.aiffFloat32 .aiff big-endian 32-bit float ≤ 2 recommended Broad DAW compatibility
.wavFloat32 .wav little-endian 32-bit float up to 8 Cross-platform standard
.wavInt16 .wav little-endian 16-bit PCM up to 8 Smaller files; lossy quantise
.wavInt24 .wav little-endian 24-bit PCM up to 8 Common DAW interchange depth
.rf64Float32 .wav little-endian 32-bit float up to 8 RF64/BW64 — 64-bit sizes, no 4 GB cap
.rf64Int24 .wav little-endian 24-bit PCM up to 8 RF64/BW64 — 64-bit sizes, no 4 GB cap
.aacHigh / .aacMedium .m4a — AAC (lossy) ~256 / ~128 kbps up to 8 Compressed. Offline writers only. Not sample-accurate.
.alac .m4a — Apple Lossless (24-bit source) up to 8 Compressed lossless. Offline writers only.

The buffer's Double samples are handed to ExtAudioFile as native Float32; the container's on-disk encoding drives the conversion — the Float32 cases are lossless, the integer cases quantise to signed 16/24-bit PCM. (.caf / .aiff / .wav remain as Float32 shorthands for the corresponding …Float32 cases.)

The .rf64* cases keep the .wav extension but use RF64/BW64 (EBU Tech 3306) — 64-bit sizes in a ds64 chunk — so they are exempt from the 4 GB limit that makes plain .wav/.aiff throw fileTooLargeForContainer. Lyrebird emits RF64 with its own RF64Writer (ExtAudioFile has no RF64 writer); CoreAudio reads it back.


Complete Example — NRT Bounce to AIFF

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()
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() calls before start()
File truncated short duration too short for the patch Increase NRTDriver duration

Off Apple (Linux/Windows): the portable WAV codec backs these renders, so a WavFileError — .cannotCreate, .cannotOpen, .notWave, .unsupportedFormat, .truncated, .fileTooLarge, .ioFailure (an underlying FileHandle failure) — can also escape NRTDriver.setup/start. A handler written against NRTDriverError alone will miss those. The Apple-only containers (CAF, AIFF-C, AAC, ALAC) throw NRTDriverError.unsupportedFormatOnPlatform there; render to .wavFloat32 / .wavInt16 / .wavInt24 instead. The codec's own contract — streaming write, idempotent finalize(), header layout, and the read-side clamps — is documented in docs/engine/portable-wav-codec.md.


Reference Docs

Doc Contents
cli-guide.md CLI commands, project workflow
project-system.md Scaffolding and generated file contents
targets.md LyrebirdDemo as a starting point for NRT programs