Files
Lyrebird/docs/engine/portable-wav-codec.md
T
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

4.0 KiB

Portable WAV codec

WavFileWriter / WavFileReader (Sources/Lyrebird/Buffers/) are Lyrebird's own RIFF/WAVE implementation. They exist so offline render (NRTDriver), disk streaming, and buffer file I/O keep working where Apple's ExtAudioFile does not — that is, everywhere except macOS and iOS. On Apple platforms these types are still present but unused; the AudioToolbox path takes over.

Scope is deliberate: canonical RIFF/WAVE with one fmt chunk and one data chunk, in float32, int16, or int24. CAF, AIFF, AAC, and ALAC stay Apple-only and throw NRTDriverError.unsupportedFormatOnPlatform off Apple.

Writing

let writer: WavFileWriter = try WavFileWriter(
    url: url, channels: 2, sampleRate: 48000, encoding: .float32
)
try writer.write(interleaved: block, frames: frameCount)   // once per render block
try writer.finalize()

The header is written up front with placeholder sizes, blocks append, and finalize() seeks back to patch them. Three properties of that contract are worth knowing, because tests pin them:

  • finalize() is idempotent, and only latches on success. A second call is a no-op; a call that throws partway leaves the writer retryable rather than stuck with a file whose sizes are still zero.
  • deinit finalizes best-effort. A writer dropped without an explicit finalize() still produces a readable file rather than leaking its descriptor, though errors there have nowhere to go — call finalize() yourself when you need to know it worked.
  • A 4 GB render throws rather than trapping. RIFF sizes are 32-bit, and the conversion would trap; WavFileError.fileTooLarge is raised instead. Use RF64 (Apple only, for now) for longer material.

Header layout

Integer PCM gets the canonical 44-byte header. Non-PCM tags do not: RIFF requires float32 to declare cbSize — an 18-byte fmt body — and to carry a fact chunk with the per-channel sample count, which finalize() patches along with the sizes. Strict readers reject float files that omit either, so the writer emits a 58-byte header for .float32.

Chunks are word-aligned. An odd data payload (reachable with int24) is followed by a pad byte, counted in the RIFF size but not in the data size.

Reading

let reader: WavFileReader = try WavFileReader(url: url)
let block: [Float] = try reader.read(frames: 512)    // interleaved, [-1, 1]
try reader.skip(frames: 44_100)                      // seeks; does not read
reader.close()
  • WAVE_FORMAT_EXTENSIBLE is understood. Most 24-bit and multichannel writers emit tag 0xFFFE with the real format in the SubFormat GUID; rejecting it would refuse ordinary files.
  • The data size is clamped to the bytes the file actually holds. Streaming writers leave a placeholder size they never patch, and believing it yields a nonsense frame count and a mid-render .truncated throw instead of a clean end of file.
  • skip(frames:) seeks. Reading and discarding a start offset a minute into a stereo 48 kHz file would allocate ~23 M samples for nothing.
  • A fmt chunk too short to hold the fields it must declare throws .truncated rather than reading past its end.

Errors

WavFileError — .cannotCreate, .cannotOpen, .notWave, .unsupportedFormat(formatTag:bitsPerSample:), .truncated, .fileTooLarge(bytes:), .ioFailure(String).

.ioFailure carries the description of an underlying FileHandle read / seek / write / close failure, funneled from the platform I/O layer so the reader and writer surface a single typed error rather than a raw NSError.

These escape NRTDriver and LyrebirdBuffer file I/O on non-Apple platforms, where this codec is the backend. Error handling written against NRTDriverError alone will miss them — see docs/tooling/nrt-guide.md.

  • docs/tooling/nrt-guide.md — offline render, formats, and the error table.
  • docs/engine/alsa-audio-driver.md — the other half of "Lyrebird works off Apple": live audio on Linux.