v1.6.0 release: soundfile format expansion (WAV int depths + RF64 >4GB, AIFF/CAF, AAC/ALAC compressed, 4GB guard, unified AudioFileFormat)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-22 17:45:34 -07:00
parent 62b2f5dbec
commit 8eb64f883f
33 changed files with 2650 additions and 352 deletions
+138 -54
View File
@@ -7,11 +7,13 @@
import Foundation
import AudioToolbox
/// Non-Real-Time audio driver. Renders synchronously to a CAF file.
/// Non-Real-Time audio driver. Renders synchronously to a soundfile in the
/// container/encoding chosen at init (``AudioFileFormat``, default `.cafFloat32`).
/// `start()` blocks until rendering is complete — suitable for score/script workflows.
public final class NRTDriver: AudioDriver {
private let outputURL: URL
private let outputFormat: AudioFileFormat
private let duration: Double
// Optional soundfile fed into the engine as simulated hardware input.
@@ -38,8 +40,13 @@ public final class NRTDriver: AudioDriver {
public var triggerListener: TriggerListener?
/// - Parameters:
/// - outputURL: Destination CAF file path.
/// - outputURL: Destination file path. The extension should match `format`
/// (`.caf` / `.wav` / `.aiff`); see ``AudioFileFormat/fileExtension``.
/// - duration: Render duration in seconds.
/// - format: Container and PCM encoding for the output file. Defaults to
/// `.cafFloat32`. CAF is 64-bit-sized (no 4 GB cap) and carries any channel
/// count, so it suits long or multichannel offline renders; `.wavFloat32` /
/// `.aiffFloat32` / the integer WAV cases are available for interchange.
/// - inputURL: Optional soundfile whose samples are written to the engine's input buses
/// each block, as if they came from a microphone. Channels are mapped in order starting
/// at input bus 0. The engine's `numInputChannels` must be ≥ the file's channel count
@@ -50,11 +57,13 @@ public final class NRTDriver: AudioDriver {
public init(
outputURL: URL,
duration: Double,
format: AudioFileFormat = .cafFloat32,
inputURL: URL? = nil,
inputStartOffset: Double = 0.0
) {
self.outputURL = outputURL
self.outputFormat = format
self.duration = duration
self.inputURL = inputURL
self.inputStartOffset = max(0.0, inputStartOffset)
@@ -128,54 +137,112 @@ public final class NRTDriver: AudioDriver {
count: inputChannelCount)
}
/// Render synchronously to the output file.
///
/// - Throws: `NRTDriverError.invalidDuration` if `duration` is negative, NaN,
/// or infinite; `NRTDriverError.fileTooLargeForContainer` if a WAV/AIFF render
/// is projected past the 4 GB RIFF cap (use `.cafFloat32` for long renders);
/// or the file/IO error cases on create/write failure. For the `.rf64*`
/// formats, a ``RF64WriterError`` may surface instead of an `NRTDriverError`.
public func start() throws {
guard let engine: SynthesisEngine else { return }
// Create and configure an ExtAudioFile for CAF / 32-bit float interleaved output
var fileRef: ExtAudioFileRef?
var format: AudioStreamBasicDescription = AudioStreamBasicDescription(
mSampleRate: engine.sampleRate,
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
mBytesPerPacket: lyrebirdBytesPerSample * UInt32(engine.numOutputChannels),
mFramesPerPacket: 1,
mBytesPerFrame: lyrebirdBytesPerSample * UInt32(engine.numOutputChannels),
mChannelsPerFrame: UInt32(engine.numOutputChannels),
mBitsPerChannel: 32,
mReserved: 0
)
var status: OSStatus = ExtAudioFileCreateWithURL(
outputURL as CFURL,
kAudioFileCAFType,
&format,
nil,
AudioFileFlags.eraseFile.rawValue,
&fileRef
)
guard status == noErr, let fileRef: ExtAudioFileRef else {
throw NRTDriverError.cannotCreateFile(status)
// Validate duration before any Double→Int conversion: Int(_:) traps on a
// non-finite or out-of-range value, and a negative duration would make the
// render loop's `0..<totalBlocks` range crash. Throw instead.
// The `< Double(Int.max)` bound also rejects a finite-but-astronomical
// duration whose block count would overflow the `Int(_:)` conversion.
let blocksDouble: Double = (duration * engine.sampleRate / Double(engine.blockSize)).rounded(.up)
guard duration.isFinite, duration >= 0, blocksDouble < Double(Int.max) else {
throw NRTDriverError.invalidDuration(duration)
}
// Guarantee disposal even if an error is thrown mid-render.
// Total render blocks — computed once and shared by the large-file guard and
// the render loop below, so the two can never drift out of sync.
let totalBlocks: Int = Int(blocksDouble)
// Large-file guard: reject a WAV/AIFF render projected past the 4 GB RIFF/AIFF
// cap before opening the file, so we never emit a truncated/corrupt output.
// CAF is exempt. `projectedByteCount` (inside riffOverflow) saturates on
// overflow, so a frame count near Int.max still yields the correct decision.
let (projectedFrames, framesOverflow): (Int, Bool) =
totalBlocks.multipliedReportingOverflow(by: engine.blockSize)
let effectiveFrames: Int = framesOverflow ? Int.max : projectedFrames
if let overflow: (projected: Int, cap: Int) = outputFormat.riffOverflow(
frameCount: effectiveFrames, channels: engine.numOutputChannels
) {
throw NRTDriverError.fileTooLargeForContainer(
projectedBytes: overflow.projected, cap: overflow.cap
)
}
// Dispose the input file regardless of which output backend construction (or
// the render) throws below — registered before backend selection so an early
// throw can't leak it.
defer {
ExtAudioFileDispose(fileRef)
if let ref: ExtAudioFileRef = inputFileRef { ExtAudioFileDispose(ref) }
inputFileRef = nil
}
// Set client format (same as file format — already float32 interleaved)
status = ExtAudioFileSetProperty(
fileRef,
kExtAudioFileProperty_ClientDataFormat,
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
&format
)
guard status == noErr else {
throw NRTDriverError.cannotSetFormat(status)
// Choose the output backend: RF64Writer (hand-rolled 64-bit WAV) for the RF64
// cases, else ExtAudioFile for CAF / WAV / AIFF. The engine renders Float32, so
// both back-ends receive native Float32 interleaved samples.
let rf64Writer: RF64Writer? = outputFormat.usesRF64Writer
? try RF64Writer(url: outputURL, format: outputFormat,
sampleRate: engine.sampleRate, channels: engine.numOutputChannels)
: nil
var extFileRef: ExtAudioFileRef? = nil
if rf64Writer == nil {
var fileFormat: AudioStreamBasicDescription = outputFormat.makeFileASBD(
sampleRate: engine.sampleRate,
channels: engine.numOutputChannels
)
var createdRef: ExtAudioFileRef?
var status: OSStatus = ExtAudioFileCreateWithURL(
outputURL as CFURL,
outputFormat.audioFileTypeID,
&fileFormat,
nil,
AudioFileFlags.eraseFile.rawValue,
&createdRef
)
guard status == noErr, let createdRef: ExtAudioFileRef else {
throw NRTDriverError.cannotCreateFile(status)
}
// Client format: always native Float32 interleaved. ExtAudioFile converts
// Float32 → int16/int24 on write for the integer WAV formats.
var clientFormat: AudioStreamBasicDescription = outputFormat.makeClientASBD(
sampleRate: engine.sampleRate,
channels: engine.numOutputChannels
)
status = ExtAudioFileSetProperty(
createdRef,
kExtAudioFileProperty_ClientDataFormat,
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
&clientFormat
)
guard status == noErr else {
ExtAudioFileDispose(createdRef)
throw NRTDriverError.cannotSetFormat(status)
}
// Compressed (AAC) formats: push the target bitrate into the encoder.
let encoderStatus: OSStatus = outputFormat.applyEncoderConfig(to: createdRef)
guard encoderStatus == noErr else {
ExtAudioFileDispose(createdRef)
throw NRTDriverError.cannotSetFormat(encoderStatus)
}
extFileRef = createdRef
}
// Render loop — synchronous, no RT constraints
let totalBlocks: Int = Int(ceil(duration * engine.sampleRate / Double(engine.blockSize)))
// Guarantee disposal even if an error is thrown mid-render.
defer {
if let ref: ExtAudioFileRef = extFileRef { ExtAudioFileDispose(ref) }
try? rf64Writer?.close() // idempotent; explicit close below patches ds64 sizes
}
// Render loop — synchronous, no RT constraints. `totalBlocks` was computed
// once above (shared with the large-file guard).
let bs: Int = engine.blockSize
let nch: Int = engine.numOutputChannels
@@ -222,25 +289,35 @@ public final class NRTDriver: AudioDriver {
}
}
// Write interleaved block to file — check status; a failure means a corrupt
// or truncated file, so we throw rather than silently swallow the error.
let writeStatus: OSStatus = writeBuffer.withUnsafeMutableBufferPointer { ptr in
let frameCount: UInt32 = UInt32(bs)
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(nch),
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
mData: ptr.baseAddress
// Write interleaved block to file — a failure means a corrupt or truncated
// file, so we throw rather than silently swallow the error.
if let rf64Writer: RF64Writer {
try writeBuffer.withUnsafeBufferPointer { ptr in
try rf64Writer.writeFloat32Interleaved(ptr, frames: bs)
}
} else if let extFileRef: ExtAudioFileRef {
let writeStatus: OSStatus = writeBuffer.withUnsafeMutableBufferPointer { ptr in
let frameCount: UInt32 = UInt32(bs)
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(nch),
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
mData: ptr.baseAddress
)
)
)
return ExtAudioFileWrite(fileRef, frameCount, &bufList)
}
guard writeStatus == noErr else {
throw NRTDriverError.writeFailed(writeStatus)
return ExtAudioFileWrite(extFileRef, frameCount, &bufList)
}
guard writeStatus == noErr else {
throw NRTDriverError.writeFailed(writeStatus)
}
}
}
// Patch the RF64 ds64 sizes now (idempotent with the defer) so the file is
// finalised before this method returns.
try rf64Writer?.close()
// Synchronous render is done and the freeWorker timer only starts after this
// returns — emit any per-block event-drop warning here so it reaches the console
// even if the process exits before that timer (or `stop()`) runs.
@@ -267,4 +344,11 @@ public enum NRTDriverError: Error {
case cannotSetInputClientFormat(OSStatus)
case cannotSeekInputFile(OSStatus)
case inputReadFailed(OSStatus)
/// `duration` was negative, NaN, or infinite. Pass a finite, non-negative value.
case invalidDuration(Double)
/// The render is projected to exceed the output container's 4 GB (32-bit size
/// field) limit. Only WAV/AIFF are capped; CAF is exempt. `projectedBytes` is
/// the estimated audio-data size, `cap` is `lyrebirdMaxRIFFBytes`. Re-run with
/// `format: .cafFloat32` (64-bit sizes, uncapped) or shorten the duration.
case fileTooLargeForContainer(projectedBytes: Int, cap: Int)
}
@@ -0,0 +1,361 @@
// AudioFileFormat.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AudioToolbox
/// Container-and-encoding format shared by every Lyrebird soundfile writer:
/// ``LyrebirdBuffer/write(to:format:sampleRate:)`` (offline buffer dump),
/// ``DiskOut/Audio`` (real-time streaming recorder), and the NRT driver
/// (offline score render).
///
/// Each case pins both the container (WAV / AIFF-C / CAF) and the PCM sample
/// encoding (Float32, or signed-integer 16/24-bit). Writers always hand
/// `ExtAudioFile` native-Float32 samples as the *client* format (see
/// `makeClientASBD(sampleRate:channels:)`) and let it convert to the *file*
/// format (`makeFileASBD(sampleRate:channels:)`) — so integer encodings cost
/// the caller nothing beyond selecting the case.
///
/// ## Container notes
/// - **WAV** — little-endian, cross-platform standard. Supports Float32 and
/// signed-integer PCM. Classic RIFF caps total file size at 4 GB (32-bit size
/// fields); large renders should fall back to `.cafFloat32`.
/// - **AIFF-C** (`.aiffFloat32`) — big-endian by spec. Uses `kAudioFileAIFCType`
/// (not classic `kAudioFileAIFFType`, which is integer-only) so it can carry
/// Float32 while keeping the `.aiff` extension. Best restricted to ≤ 2 channels
/// for compatibility with legacy readers; also 4 GB-capped.
/// - **CAF** (`.cafFloat32`) — Apple's flexible container: any sample rate, any
/// channel count up to `lyrebirdMaxFileChannelCount`, 64-bit sizes (no 4 GB
/// cap). Default for buffer and NRT writes.
public enum AudioFileFormat: Sendable {
// MARK: - WAV variants
/// WAV container, 32-bit IEEE-754 float, little-endian.
case wavFloat32
/// WAV container, 16-bit signed integer, little-endian.
case wavInt16
/// WAV container, 24-bit signed integer (packed), little-endian.
case wavInt24
// MARK: - AIFF-C variants
/// AIFF-C container, 32-bit IEEE-754 float, big-endian.
case aiffFloat32
// MARK: - CAF variants
/// CAF container, 32-bit IEEE-754 float, little-endian.
case cafFloat32
// MARK: - RF64 / BW64 variants (64-bit-sized WAV, no 4 GB cap)
/// RF64 (BW64) container, 32-bit IEEE-754 float, little-endian. WAV extension.
/// Emitted by ``RF64Writer`` (not `ExtAudioFile`); readable by CoreAudio.
case rf64Float32
/// RF64 (BW64) container, 24-bit signed integer (packed), little-endian.
case rf64Int24
// MARK: - Compressed variants (M4A container — offline writers only)
/// AAC in an M4A container, ~256 kbps. Lossy; **not sample-accurate** (encoder
/// priming/padding). Encoded by `ExtAudioFile`/`AudioConverter`. Offline writers
/// only (`LyrebirdBuffer.write`, `NRTDriver`); ``DiskOut/Audio`` rejects it.
case aacHigh
/// AAC in an M4A container, ~128 kbps. See ``aacHigh``.
case aacMedium
/// Apple Lossless (ALAC) in an M4A container, 24-bit source. Lossless of the
/// 24-bit-quantised signal. Offline writers only; ``DiskOut/Audio`` rejects it.
case alac
// MARK: - Back-compat shorthands
/// WAV / Float32. Alias for ``wavFloat32``.
public static let wav: AudioFileFormat = .wavFloat32
/// AIFF-C / Float32. Alias for ``aiffFloat32``.
public static let aiff: AudioFileFormat = .aiffFloat32
/// CAF / Float32. Alias for ``cafFloat32``.
public static let caf: AudioFileFormat = .cafFloat32
// MARK: - Derived properties
/// AudioToolbox container type ID passed to `ExtAudioFileCreateWithURL`.
///
/// Not meaningful for the RF64 cases (they are written by ``RF64Writer``, not
/// `ExtAudioFile`); those return `kAudioFileWAVEType` as an inert default.
public var audioFileTypeID: AudioFileTypeID {
switch self {
case .wavFloat32, .wavInt16, .wavInt24, .rf64Float32, .rf64Int24:
return kAudioFileWAVEType
case .aiffFloat32:
return kAudioFileAIFCType // AIFF-C: carries Float32; classic AIFF does not
case .cafFloat32:
return kAudioFileCAFType
case .aacHigh, .aacMedium, .alac:
return kAudioFileM4AType
}
}
/// Filesystem extension for the output file (no leading dot).
public var fileExtension: String {
switch self {
case .wavFloat32, .wavInt16, .wavInt24, .rf64Float32, .rf64Int24: return "wav"
case .aiffFloat32: return "aiff"
case .cafFloat32: return "caf"
case .aacHigh, .aacMedium, .alac: return "m4a"
}
}
/// Bits per sample in the *PCM* encoded file. Not meaningful for the compressed
/// cases (they carry no fixed per-sample bit width); returns `0` there.
public var fileBitsPerChannel: UInt32 {
switch self {
case .wavFloat32, .aiffFloat32, .cafFloat32, .rf64Float32: return 32
case .wavInt16: return 16
case .wavInt24, .rf64Int24: return 24
case .aacHigh, .aacMedium, .alac: return 0
}
}
/// `true` when the file encoding is IEEE-754 float; `false` for signed-integer PCM
/// or a compressed codec.
public var isFloatEncoding: Bool {
switch self {
case .wavFloat32, .aiffFloat32, .cafFloat32, .rf64Float32: return true
case .wavInt16, .wavInt24, .rf64Int24, .aacHigh, .aacMedium, .alac: return false
}
}
/// `true` when the container stores big-endian sample data (AIFF-C spec).
public var isBigEndian: Bool {
switch self {
case .aiffFloat32:
return true
case .wavFloat32, .wavInt16, .wavInt24, .cafFloat32, .rf64Float32, .rf64Int24,
.aacHigh, .aacMedium, .alac:
return false
}
}
/// `true` for the compressed codecs (AAC, ALAC) — encoded by
/// `ExtAudioFile`/`AudioConverter` into an M4A container.
public var isCompressed: Bool {
switch self {
case .aacHigh, .aacMedium, .alac:
return true
case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32,
.rf64Float32, .rf64Int24:
return false
}
}
/// Target AAC encode bitrate in bits/second, or `nil` for non-AAC formats.
public var aacBitrate: Int? {
switch self {
case .aacHigh: return aacHighBitrate
case .aacMedium: return aacMediumBitrate
case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32,
.rf64Float32, .rf64Int24, .alac:
return nil
}
}
/// `true` when the container can address files larger than 4 GB.
///
/// WAV (classic RIFF) and AIFF-C carry unsigned **32-bit** size fields, so
/// their total file size is capped at 4 GB (see `lyrebirdMaxRIFFBytes`). CAF
/// (64-bit sizes) and RF64/BW64 (64-bit sizes via the `ds64` chunk) have no such
/// cap. `ExtAudioFile` cannot emit RF64, so those cases are written by
/// ``RF64Writer`` — see ``usesRF64Writer``.
public var supportsLargeFiles: Bool {
switch self {
// CAF/RF64 are 64-bit-sized; the compressed M4A cases are not RIFF at all,
// so the 4 GB RIFF/AIFF guard never applies to them either.
case .cafFloat32, .rf64Float32, .rf64Int24, .aacHigh, .aacMedium, .alac:
return true
case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32:
return false
}
}
/// `true` when this format is emitted by ``RF64Writer`` (hand-rolled 64-bit WAV)
/// rather than `ExtAudioFile`. The three soundfile writers branch on this.
public var usesRF64Writer: Bool {
switch self {
case .rf64Float32, .rf64Int24:
return true
case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32,
.aacHigh, .aacMedium, .alac:
return false
}
}
}
// MARK: - Large-file guard
extension AudioFileFormat {
/// Projected on-disk audio-data size in bytes for `frameCount` interleaved
/// frames across `channels`, at this format's bit depth. Excludes container
/// header/metadata (accounted for by the slack baked into `lyrebirdMaxRIFFBytes`).
///
/// Pure integer arithmetic — safe to evaluate for hypothetical sizes without
/// allocating anything. **Saturates to `Int.max` on overflow** rather than
/// trapping: any frame count large enough to overflow the byte product is, by
/// definition, far past any container cap, so a saturated value gives the guard
/// the correct "over cap" answer without a crash.
func projectedByteCount(frameCount: Int, channels: Int) -> Int {
let bytesPerSample: Int = Int(fileBitsPerChannel / bitsPerByte)
let (samples, sampleOverflow): (Int, Bool) = frameCount.multipliedReportingOverflow(by: channels)
if sampleOverflow { return Int.max }
let (bytes, byteOverflow): (Int, Bool) = samples.multipliedReportingOverflow(by: bytesPerSample)
return byteOverflow ? Int.max : bytes
}
/// Returns `(projected, cap)` when writing `frameCount × channels` frames in
/// this format would overflow the container's addressable size, or `nil` when
/// the write fits (or the container is 64-bit — see ``supportsLargeFiles``).
///
/// The single decision point behind both the `LyrebirdBuffer.write` and
/// `NRTDriver` large-file guards, so the guard reads off the format rather
/// than a hardcoded case list.
func riffOverflow(frameCount: Int, channels: Int) -> (projected: Int, cap: Int)? {
guard !supportsLargeFiles else { return nil }
let projected: Int = projectedByteCount(frameCount: frameCount, channels: channels)
return projected > lyrebirdMaxRIFFBytes ? (projected, lyrebirdMaxRIFFBytes) : nil
}
}
// MARK: - ASBD factories (module-internal)
/// Number of bits in a byte — names the `/ 8` in bytes-per-sample derivations.
private let bitsPerByte: UInt32 = 8
/// Encoder packet geometry (samples per packet) for the compressed codecs.
private let aacFramesPerPacket: UInt32 = 1024
private let alacFramesPerPacket: UInt32 = 4096
/// AAC target bitrates (bits/second) for the two quality tiers.
private let aacHighBitrate: Int = 256_000
private let aacMediumBitrate: Int = 128_000
extension AudioFileFormat {
/// Build the *file* `AudioStreamBasicDescription` for this format: linear PCM
/// with the case's bit depth, encoding flags, and endianness, interleaved
/// across `channels`.
///
/// This is the descriptor handed to `ExtAudioFileCreateWithURL`. Pair it with
/// `makeClientASBD(sampleRate:channels:)` as the client format so
/// `ExtAudioFile` performs any Float32 → integer / endian conversion.
///
/// - Parameters:
/// - sampleRate: Sample rate embedded in the file header, in Hz.
/// - channels: Interleaved channel count. Must be ≥ 1.
func makeFileASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription {
// Compressed codecs (AAC / ALAC): the encoder fills in the packet geometry.
// We supply the format ID, channel count, sample rate, and frames-per-packet;
// `AudioConverter` (behind `ExtAudioFile`) computes the rest.
if isCompressed {
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
asbd.mSampleRate = sampleRate
asbd.mChannelsPerFrame = UInt32(channels)
// AAC vs ALAC: the AAC tiers carry a bitrate, ALAC does not. Deriving the
// codec from `aacBitrate` avoids a `switch self` with an unreachable
// default that could silently leave `mFormatID == 0` for a future case.
if aacBitrate != nil {
asbd.mFormatID = kAudioFormatMPEG4AAC
asbd.mFramesPerPacket = aacFramesPerPacket
} else {
asbd.mFormatID = kAudioFormatAppleLossless
asbd.mFramesPerPacket = alacFramesPerPacket
asbd.mFormatFlags = kAppleLosslessFormatFlag_24BitSourceData
}
return asbd
}
let bytesPerSample: UInt32 = fileBitsPerChannel / bitsPerByte
let bytesPerFrame: UInt32 = bytesPerSample * UInt32(channels)
var flags: AudioFormatFlags = kAudioFormatFlagIsPacked
flags |= isFloatEncoding ? kAudioFormatFlagIsFloat : kAudioFormatFlagIsSignedInteger
if isBigEndian { flags |= kAudioFormatFlagIsBigEndian }
return AudioStreamBasicDescription(
mSampleRate: sampleRate,
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: flags,
mBytesPerPacket: bytesPerFrame,
mFramesPerPacket: 1,
mBytesPerFrame: bytesPerFrame,
mChannelsPerFrame: UInt32(channels),
mBitsPerChannel: fileBitsPerChannel,
mReserved: 0
)
}
/// Build the *client* `AudioStreamBasicDescription`: always native-endian
/// Float32 interleaved across `channels`, independent of the file encoding.
///
/// Every Lyrebird writer feeds `ExtAudioFile` Float32 samples; the file format
/// (from `makeFileASBD(sampleRate:channels:)`) drives the conversion.
///
/// - Parameters:
/// - sampleRate: Sample rate, in Hz. Should match the file ASBD.
/// - channels: Interleaved channel count. Must be ≥ 1.
func makeClientASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription {
let bytesPerFrame: UInt32 = lyrebirdBytesPerSample * UInt32(channels)
return AudioStreamBasicDescription(
mSampleRate: sampleRate,
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
mBytesPerPacket: bytesPerFrame,
mFramesPerPacket: 1,
mBytesPerFrame: bytesPerFrame,
mChannelsPerFrame: UInt32(channels),
mBitsPerChannel: lyrebirdBitsPerSample,
mReserved: 0
)
}
}
// MARK: - Compressed encoder configuration
extension AudioFileFormat {
/// After an `ExtAudioFile` for a compressed format has been created and its client
/// (Float32) format set, push the target AAC bitrate into the underlying
/// `AudioConverter`. No-op for non-AAC formats (ALAC has no bitrate; PCM has none).
///
/// Returns `noErr` on success (or when nothing needed doing), else the failing
/// `OSStatus`. Call from a non-RT thread, before the first `ExtAudioFileWrite`.
func applyEncoderConfig(to fileRef: ExtAudioFileRef) -> OSStatus {
guard let bitrate: Int = aacBitrate else { return noErr }
var converter: AudioConverterRef?
var converterSize: UInt32 = UInt32(MemoryLayout<AudioConverterRef?>.size)
let getStatus: OSStatus = ExtAudioFileGetProperty(
fileRef, kExtAudioFileProperty_AudioConverter, &converterSize, &converter
)
guard getStatus == noErr, let converter: AudioConverterRef else { return getStatus }
var rate: UInt32 = UInt32(bitrate)
let setStatus: OSStatus = AudioConverterSetProperty(
converter, kAudioConverterEncodeBitRate, UInt32(MemoryLayout<UInt32>.size), &rate
)
guard setStatus == noErr else { return setStatus }
// Notify ExtAudioFile that the converter config changed so it re-reads it.
// The property value is a `CFPropertyList?` = NULL; pass a pointer to a nil
// variable (NOT a null data pointer — CoreAudio dereferences the pointer).
var config: CFPropertyList? = nil
return withUnsafePointer(to: &config) { ptr in
ExtAudioFileSetProperty(
fileRef, kExtAudioFileProperty_ConverterConfig,
UInt32(MemoryLayout<CFPropertyList?>.size), ptr
)
}
}
}
@@ -7,44 +7,6 @@
import Foundation
import AudioToolbox
// MARK: - AudioFileFormat
/// Container format for `LyrebirdBuffer.write(to:format:sampleRate:)`.
public enum AudioFileFormat {
/// AIFF-C container (`.aiff`) — lossless Float32, big-endian. Common on macOS.
///
/// Uses `kAudioFileAIFCType` (AIFF-C), not classic `kAudioFileAIFFType`. Classic AIFF
/// supports only integer PCM; AIFF-C adds float and other sample types while retaining
/// the same `.aiff` file extension and broad macOS/iOS compatibility.
///
/// Note: AIFF-C has practical interoperability limits beyond 2 channels. For
/// multichannel (3–8 ch) output, prefer `.caf` or `.wav`.
case aiff
/// WAV container (`.wav`) — lossless Float32, little-endian. Cross-platform standard.
/// Supports up to `lyrebirdMaxFileChannelCount` channels via WAVE_FORMAT_EXTENSIBLE.
case wav
/// Core Audio Format (`.caf`) — Apple's flexible container; supports any sample rate
/// and any channel count up to `lyrebirdMaxFileChannelCount`. Default for writes.
case caf
fileprivate var audioFileTypeID: AudioFileTypeID {
switch self {
case .aiff: return kAudioFileAIFCType // AIFF-C: supports Float32 (classic AIFF does not)
case .wav: return kAudioFileWAVEType
case .caf: return kAudioFileCAFType
}
}
/// Whether the container requires big-endian sample data in the file format descriptor.
/// AIFF-C is big-endian by spec; WAV and CAF use native/little-endian.
fileprivate var requiresBigEndian: Bool {
switch self {
case .aiff: return true
case .wav, .caf: return false
}
}
}
// MARK: - LyrebirdBufferIOError
/// Errors thrown by `LyrebirdBuffer` file I/O methods.
@@ -70,6 +32,11 @@ public enum LyrebirdBufferIOError: Error, Equatable {
case cannotSetOutputFormat(OSStatus)
/// `ExtAudioFileWrite` returned a non-zero status.
case writeFailed(OSStatus)
/// The requested WAV/AIFF write is projected to exceed the container's 4 GB
/// (32-bit size field) limit. `projectedBytes` is the estimated audio-data
/// size; `cap` is `lyrebirdMaxRIFFBytes`. Re-issue the write with `.cafFloat32`
/// (64-bit sizes, uncapped), shorten the buffer, or split it.
case fileTooLargeForContainer(projectedBytes: Int, cap: Int)
}
// MARK: - Constants
@@ -251,18 +218,27 @@ public extension LyrebirdBuffer {
/// Write the buffer's contents to an audio file.
///
/// Supports any `channelCount` in `[1, lyrebirdMaxFileChannelCount]`. The file will
/// contain interleaved Float32 samples at the specified sample rate. For multichannel
/// buffers, `.caf` or `.wav` are recommended; `.aiff` (AIFF-C) is best limited to
/// stereo for maximum compatibility with external readers.
///
/// Converts `Double` (Double) samples to Float32 on the way out.
/// Supports any `channelCount` in `[1, lyrebirdMaxFileChannelCount]` and any
/// ``AudioFileFormat`` case. The buffer's `Double` samples are handed to the
/// writer as native Float32; the container's on-disk encoding (Float32, or
/// signed-integer 16/24-bit for the WAV cases) is produced by its conversion.
/// Most formats go through `ExtAudioFile`; the RF64 cases (`.rf64Float32` /
/// `.rf64Int24`) are written by ``RF64Writer`` instead, since `ExtAudioFile`
/// cannot emit RF64. For multichannel buffers, `.cafFloat32` or `.wavFloat32` are
/// recommended; `.aiffFloat32` (AIFF-C) is best limited to stereo for maximum
/// compatibility with external readers. `.wavFloat32` / `.wavInt16` / `.wavInt24`
/// / `.aiffFloat32` throw ``LyrebirdBufferIOError/fileTooLargeForContainer(projectedBytes:cap:)``
/// past 4 GB — use `.rf64*` or `.cafFloat32` for larger files.
///
/// - Parameters:
/// - url: Destination file. Any existing file at this path is overwritten.
/// - format: Container format. Defaults to `.caf`.
/// - format: Container and PCM encoding. Defaults to `.cafFloat32`.
/// - sampleRate: Sample rate embedded in the file header. Defaults to 44100.
///
/// - Throws: ``LyrebirdBufferIOError`` (`.fileTooLargeForContainer` when a
/// WAV/AIFF write is projected past 4 GB, or the create/write cases on I/O
/// failure). For the `.rf64*` formats, a ``RF64WriterError`` may surface instead.
///
/// **Not RT-safe.** Must be called from a non-RT thread (main thread or background queue).
///
/// For session-end dumps from a ``LyrebirdEventList`` teardown, see the
@@ -282,39 +258,50 @@ public extension LyrebirdBuffer {
+ "lyrebirdMaxFileChannelCount (\(lyrebirdMaxFileChannelCount))"
)
let bytesPerSample: UInt32 = lyrebirdFileIOBitsPerSample / 8 // 4 bytes for Float32
let bytesPerFrame: UInt32 = bytesPerSample * UInt32(channelCount)
// Large-file guard: WAV/AIFF are 4 GB-capped (32-bit size fields). Reject a
// write that would overflow rather than emit a truncated/corrupt file. CAF
// is 64-bit and exempt (riffOverflow returns nil).
if let overflow: (projected: Int, cap: Int) =
format.riffOverflow(frameCount: count, channels: channelCount) {
throw LyrebirdBufferIOError.fileTooLargeForContainer(
projectedBytes: overflow.projected, cap: overflow.cap
)
}
// File format: big-endian flags for AIFF-C; native-endian for WAV/CAF.
let fileFlags: AudioFormatFlags = format.requiresBigEndian
? kAudioFormatFlagIsFloat | kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsPacked
: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked
// RF64 / BW64 is not an ExtAudioFile-writable container — hand it to RF64Writer.
// Client samples are native Float32 interleaved, same as the ExtAudioFile path.
if format.usesRF64Writer {
let writer: RF64Writer = try RF64Writer(
url: url, format: format, sampleRate: sampleRate, channels: channelCount
)
let samplesPerChunk: Int = lyrebirdFileIOChunkFrames * channelCount
var chunkBuf: [Float] = [Float](repeating: 0, count: samplesPerChunk)
try withStorage { storage, frameCount, nch in
var frameOffset: Int = 0
while frameOffset < frameCount {
let framesThisChunk: Int = min(lyrebirdFileIOChunkFrames, frameCount - frameOffset)
let samplesThisChunk: Int = framesThisChunk * nch
for i: Int in 0..<samplesThisChunk {
chunkBuf[i] = Float(storage[frameOffset * nch + i])
}
try chunkBuf.withUnsafeBufferPointer { ptr in
try writer.writeFloat32Interleaved(ptr, frames: framesThisChunk)
}
frameOffset += framesThisChunk
}
}
try writer.close()
return
}
var fileFormat: AudioStreamBasicDescription = AudioStreamBasicDescription(
mSampleRate: sampleRate,
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: fileFlags,
mBytesPerPacket: bytesPerFrame,
mFramesPerPacket: 1,
mBytesPerFrame: bytesPerFrame,
mChannelsPerFrame: UInt32(channelCount),
mBitsPerChannel: lyrebirdFileIOBitsPerSample,
mReserved: 0
)
// File format: container/encoding/endianness per `format`.
var fileFormat: AudioStreamBasicDescription =
format.makeFileASBD(sampleRate: sampleRate, channels: channelCount)
// Client format: always native-endian Float32 interleaved.
// ExtAudioFile converts byte order to match the file format automatically.
var clientFormat: AudioStreamBasicDescription = AudioStreamBasicDescription(
mSampleRate: sampleRate,
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
mBytesPerPacket: bytesPerFrame,
mFramesPerPacket: 1,
mBytesPerFrame: bytesPerFrame,
mChannelsPerFrame: UInt32(channelCount),
mBitsPerChannel: lyrebirdFileIOBitsPerSample,
mReserved: 0
)
// ExtAudioFile converts byte order / encoding to match the file format automatically.
var clientFormat: AudioStreamBasicDescription =
format.makeClientASBD(sampleRate: sampleRate, channels: channelCount)
var fileRef: ExtAudioFileRef?
let createStatus: OSStatus = ExtAudioFileCreateWithURL(
@@ -340,6 +327,12 @@ public extension LyrebirdBuffer {
throw LyrebirdBufferIOError.cannotSetOutputFormat(setStatus)
}
// Compressed (AAC) formats: push the target bitrate into the encoder.
let encoderStatus: OSStatus = format.applyEncoderConfig(to: fileRef)
guard encoderStatus == noErr else {
throw LyrebirdBufferIOError.cannotSetOutputFormat(encoderStatus)
}
// Write in chunks, converting Double (Double) → Float32 as we go.
// The storage is interleaved so sequential reads produce correctly-ordered output
// for any channel count.
+259
View File
@@ -0,0 +1,259 @@
// RF64Writer.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Streaming writer for **RF64 / BW64** WAV files — the 64-bit-sized variant of RIFF
/// WAVE (EBU Tech 3306) that lifts the classic 4 GB container limit.
///
/// `ExtAudioFile` can *read* RF64 but has no RF64 *writer*, so this type emits the
/// container by hand via `FileHandle`: a fixed 104-byte header (`RF64` + `ds64` +
/// `WAVE_FORMAT_EXTENSIBLE` `fmt ` + `data`) followed by little-endian PCM. The
/// `RIFF` and `data` chunk sizes are written as the `0xFFFF_FFFF` sentinel; the true
/// 64-bit sizes live in the `ds64` chunk and are patched in on ``close()``.
///
/// The caller always feeds native **Float32** interleaved samples (matching the other
/// Lyrebird writers' client format); this type converts to the file encoding
/// (Float32 passthrough, or signed 24-bit packed for `.rf64Int24`).
///
/// **Not RT-safe.** Construct, write, and close from a non-RT thread (offline render,
/// buffer dump, or a `DiskOut` background drain).
public final class RF64Writer {
// MARK: - Format constants
/// Value written into the 32-bit `RIFF` and `data` size fields; the real 64-bit
/// sizes live in the `ds64` chunk. `0xFFFF_FFFF` is the RF64 "see ds64" sentinel.
private static let sizeFieldSentinel: UInt32 = 0xFFFF_FFFF
private static let ds64ChunkBodySize: UInt32 = 28 // riffSize(8) + dataSize(8) + sampleCount(8) + tableLen(4)
private static let fmtChunkBodySize: UInt32 = 40 // WAVE_FORMAT_EXTENSIBLE
private static let waveFormatExtensible: UInt16 = 0xFFFE
private static let fmtExtensionSize: UInt16 = 22 // cbSize for EXTENSIBLE
private static let bitsPerByte: Int = 8
/// Absolute byte offset of the first `ds64` size field (`riffSize`). The three
/// 64-bit sizes are contiguous from here (`riffSize`, `dataSize`, `sampleCount`),
/// patched in on ``close()``. Fixed by the header layout built in `buildHeader`.
private static let ds64RiffSizeOffset: UInt64 = 20
/// Total header size in bytes; PCM data begins here.
static let headerByteCount: Int = 104
// KSDATAFORMAT_SUBTYPE GUIDs (16 bytes, as laid out in the file).
private static let subFormatIEEEFloat: [UInt8] =
[0x03, 0, 0, 0, 0, 0, 0x10, 0, 0x80, 0, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]
private static let subFormatPCM: [UInt8] =
[0x01, 0, 0, 0, 0, 0, 0x10, 0, 0x80, 0, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]
/// Full-scale amplitude for signed 24-bit PCM (`2^23 − 1`).
private static let int24FullScale: Float = 8_388_607.0
// MARK: - State (all non-RT, single-writer)
private let format: AudioFileFormat
private let channels: Int
private let bytesPerSample: Int
private let blockAlign: Int
private let fileHandle: FileHandle
private var dataBytesWritten: Int = 0
private(set) public var framesWritten: Int = 0
private var closed: Bool = false
/// Reusable little-endian conversion scratch (int24 path). Grows only.
private var scratch: [UInt8] = []
// MARK: - Init
/// Create the file and write the RF64 header with placeholder (`ds64`) sizes.
///
/// - Parameters:
/// - url: Destination file. Any existing file is truncated.
/// - format: Must be `.rf64Float32` or `.rf64Int24`.
/// - sampleRate: Sample rate in Hz written into the `fmt ` chunk.
/// - channels: Interleaved channel count (≥ 1).
public init(
url: URL,
format: AudioFileFormat,
sampleRate: Double,
channels: Int
) throws {
guard format == .rf64Float32 || format == .rf64Int24 else {
throw RF64WriterError.unsupportedFormat(format)
}
precondition(channels >= 1, "RF64Writer requires channels >= 1, got \(channels)")
self.format = format
self.channels = channels
let bytes: Int = Int(format.fileBitsPerChannel) / RF64Writer.bitsPerByte
self.bytesPerSample = bytes
self.blockAlign = channels * bytes
// Create (truncate) the file, then open a handle for writing.
guard FileManager.default.createFile(atPath: url.path, contents: nil) else {
throw RF64WriterError.cannotCreateFile(url)
}
do {
self.fileHandle = try FileHandle(forWritingTo: url)
} catch {
throw RF64WriterError.cannotCreateFile(url)
}
let header: [UInt8] = RF64Writer.buildHeader(
format: format, sampleRate: sampleRate, channels: channels,
blockAlign: blockAlign, bitsPerChannel: Int(format.fileBitsPerChannel)
)
do {
try fileHandle.write(contentsOf: Data(header))
} catch {
try? fileHandle.close()
throw RF64WriterError.writeFailed(error)
}
}
// MARK: - Header construction
/// Build the fixed 104-byte header by appending chunks in order, so no absolute
/// byte offsets appear here. `close()` later patches the three `ds64` sizes at
/// `ds64RiffSizeOffset` — which is fixed precisely because this layout is fixed.
private static func buildHeader(
format: AudioFileFormat,
sampleRate: Double,
channels: Int,
blockAlign: Int,
bitsPerChannel: Int
) -> [UInt8] {
var h: [UInt8] = []
h.reserveCapacity(headerByteCount)
func fourCC(_ s: String) { h.append(contentsOf: Array(s.utf8)) }
func u16(_ v: UInt16) {
h.append(UInt8(truncatingIfNeeded: v))
h.append(UInt8(truncatingIfNeeded: v >> 8))
}
func u32(_ v: UInt32) {
for i: Int in 0..<4 { h.append(UInt8(truncatingIfNeeded: v >> (8 * i))) }
}
// RF64 / RIFF-size sentinel / WAVE
fourCC("RF64"); u32(sizeFieldSentinel); fourCC("WAVE")
// ds64 chunk — 64-bit sizes zero for now; patched on close().
fourCC("ds64"); u32(ds64ChunkBodySize)
u32(0); u32(0) // riffSize (8)
u32(0); u32(0) // dataSize (8)
u32(0); u32(0) // sampleCount (8)
u32(0) // tableLength
// fmt chunk — WAVE_FORMAT_EXTENSIBLE
fourCC("fmt "); u32(fmtChunkBodySize)
let avgBytesPerSec: UInt32 = UInt32(sampleRate.rounded()) * UInt32(blockAlign)
u16(waveFormatExtensible) // wFormatTag
u16(UInt16(channels)) // nChannels
u32(UInt32(sampleRate.rounded())) // nSamplesPerSec
u32(avgBytesPerSec) // nAvgBytesPerSec
u16(UInt16(blockAlign)) // nBlockAlign
u16(UInt16(bitsPerChannel)) // wBitsPerSample
u16(fmtExtensionSize) // cbSize
u16(UInt16(bitsPerChannel)) // wValidBitsPerSample
u32(0) // dwChannelMask
let guid: [UInt8] = format.isFloatEncoding ? subFormatIEEEFloat : subFormatPCM
h.append(contentsOf: guid) // SubFormat GUID (16)
// data chunk — size sentinel; real size in ds64.
fourCC("data"); u32(sizeFieldSentinel)
return h
}
// MARK: - Write
/// Append `frames` interleaved frames of native Float32 samples, converting to the
/// file encoding. `samples` must contain at least `frames * channels` values.
public func writeFloat32Interleaved(_ samples: UnsafeBufferPointer<Float>, frames: Int) throws {
guard frames > 0 else { return }
let sampleCount: Int = frames * channels
let payload: Data
if format.isFloatEncoding {
// Float32 little-endian passthrough (Apple platforms are little-endian).
guard let base: UnsafePointer<Float> = samples.baseAddress else { return }
payload = Data(buffer: UnsafeBufferPointer(start: base, count: sampleCount))
} else {
// Signed 24-bit packed little-endian. Round to nearest (matches ExtAudioFile).
let byteCount: Int = sampleCount * bytesPerSample
if scratch.count < byteCount { scratch = [UInt8](repeating: 0, count: byteCount) }
for i: Int in 0..<sampleCount {
let clamped: Float = max(-1.0, min(1.0, samples[i]))
let s: Int32 = Int32((clamped * RF64Writer.int24FullScale).rounded())
scratch[i * 3] = UInt8(truncatingIfNeeded: s)
scratch[i * 3 + 1] = UInt8(truncatingIfNeeded: s >> 8)
scratch[i * 3 + 2] = UInt8(truncatingIfNeeded: s >> 16)
}
payload = Data(scratch[0..<byteCount])
}
do {
try fileHandle.write(contentsOf: payload)
} catch {
throw RF64WriterError.writeFailed(error)
}
dataBytesWritten += sampleCount * bytesPerSample
framesWritten += frames
}
// MARK: - Close
/// Finalise the file: write a RIFF word-alignment pad byte if the `data` payload is
/// odd-length, patch the true 64-bit `ds64` sizes, and close the handle. Idempotent.
///
/// The `FileHandle` is closed unconditionally (even if patching throws) so a failed
/// finalise never leaks the descriptor.
public func close() throws {
guard !closed else { return }
closed = true
defer { try? fileHandle.close() }
// RIFF requires a trailing pad byte after an odd-length chunk. The pad is part
// of the file (counted in riffSize) but not in the chunk's own dataSize. If the
// pad write fails, still patch the ds64 sizes below so the file reports its real
// data (not the initialized zero); surface the pad error afterwards.
var padWritten: Int = 0
var padError: Error? = nil
if dataBytesWritten % 2 == 1 {
do { try fileHandle.write(contentsOf: Data([0])); padWritten = 1 }
catch { padError = error }
}
let dataSize: UInt64 = UInt64(dataBytesWritten)
let riffSize: UInt64 = UInt64(RF64Writer.headerByteCount - 8) + dataSize + UInt64(padWritten)
let sampleCount: UInt64 = blockAlign > 0 ? dataSize / UInt64(blockAlign) : 0
func u64LE(_ v: UInt64) -> Data {
var bytes: [UInt8] = [UInt8](repeating: 0, count: 8)
for i: Int in 0..<8 { bytes[i] = UInt8(truncatingIfNeeded: v >> (8 * i)) }
return Data(bytes)
}
do {
try fileHandle.seek(toOffset: RF64Writer.ds64RiffSizeOffset)
try fileHandle.write(contentsOf: u64LE(riffSize)) // ds64.riffSize
try fileHandle.write(contentsOf: u64LE(dataSize)) // ds64.dataSize
try fileHandle.write(contentsOf: u64LE(sampleCount)) // ds64.sampleCount
} catch {
throw RF64WriterError.seekFailed(error)
}
if let padError: Error = padError {
throw RF64WriterError.writeFailed(padError)
}
}
deinit {
// Best-effort: if the owner forgot to close(), still patch sizes so the file
// is readable. Errors are unrecoverable here and deliberately swallowed.
if !closed { try? close() }
}
}
@@ -0,0 +1,20 @@
// RF64WriterError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Errors thrown by ``RF64Writer``.
public enum RF64WriterError: Error {
/// The output file could not be created at the given URL.
case cannotCreateFile(URL)
/// A `FileHandle` write failed; carries the underlying error.
case writeFailed(Error)
/// Seeking back to patch the `ds64` sizes on ``RF64Writer/close()`` failed.
case seekFailed(Error)
/// The format passed to ``RF64Writer/init(url:format:sampleRate:channels:)`` is not
/// an RF64 case. Only `.rf64Float32` / `.rf64Int24` are supported.
case unsupportedFormat(AudioFileFormat)
}
+1
View File
@@ -495,6 +495,7 @@ public final class EngineHost: @unchecked Sendable {
let driver: NRTDriver = NRTDriver(
outputURL: job.outputURL,
duration: job.duration,
format: job.format,
inputURL: job.inputURL,
inputStartOffset: job.inputStartOffset
)
+10 -3
View File
@@ -26,11 +26,16 @@ import Foundation
/// fires automatically.
public struct NRTJob: Sendable {
/// Destination file URL the rendered audio writes to. CAF format
/// per `NRTDriver`'s contract; the file is created by the driver
/// at `engine.start()` time.
/// Destination file URL the rendered audio writes to. The file is
/// created by the driver at `engine.start()` time, using ``format``.
public let outputURL: URL
/// Container and PCM encoding for ``outputURL``. Maps to
/// `NRTDriver.init(format:)`. Defaults to `.cafFloat32` — CAF is
/// 64-bit-sized (no 4 GB cap) and carries any channel count, which
/// suits long offline renders and multichannel stems.
public let format: AudioFileFormat
/// Render duration in seconds. Maps to `NRTDriver.init(duration:)`.
public let duration: Double
@@ -86,6 +91,7 @@ public struct NRTJob: Sendable {
public init(
outputURL: URL,
duration: Double,
format: AudioFileFormat = .cafFloat32,
blockSize: Int = lyrebirdDefaultResultBufferSize,
sampleRate: Double = lyrebirdDefaultSampleRate,
numOutputChannels: Int = 2,
@@ -95,6 +101,7 @@ public struct NRTJob: Sendable {
build: @escaping @Sendable (SynthesisEngine) throws -> Void
) {
self.outputURL = outputURL
self.format = format
self.duration = duration
self.blockSize = blockSize
self.sampleRate = sampleRate
@@ -40,7 +40,8 @@ public enum DiskOut {
/// The overflow guard (`used + count <= _ringSize`) ensures indices never alias.
/// - `_framesWritten` is stored by RT with `.releasing`; BG loads with `.acquiring`.
/// - `_framesRead` is stored by BG with `.releasing`; RT loads with `.acquiring`.
/// - `_fileRef` and `_interleavedWriteBuf` are BG-only after `init`.
/// - `_fileRef`, `_rf64Writer`, `_cumulativeFramesWritten`, and
/// `_interleavedWriteBuf` are BG-only after `init`.
///
/// ## Usage
/// ```swift
@@ -58,6 +59,16 @@ public enum DiskOut {
/// try engine.start() // render / play
/// diskOut.close() // flush remaining frames and close the file
/// ```
///
/// - Parameters:
/// - source: Audio source to record and pass through.
/// - channelCount: Number of channels to record and pass through. Must be ≥ 1.
/// - url: Output file path. Created (or overwritten) immediately in `init`.
/// - sampleRate: Sample rate written into the file header. Defaults to 48000 Hz.
/// - format: Container and PCM encoding (``AudioFileFormat``). Defaults to `.aiffFloat32`.
/// - bufferFrames: Ring buffer capacity in frames. Must be a power of two. Defaults to 8192.
/// - mul: Output scale factor. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
public final class Audio: GeneratorBase, @unchecked Sendable, AudioGenerator, RootRegistering {
// MARK: - Generator protocol
@@ -100,6 +111,10 @@ public enum DiskOut {
private var _interleavedWriteBuf: [Float]
/// Cumulative frames written to the file across the whole session. BG-only
/// (touched only in `_drainAndWrite`). Drives the large-file guard.
private var _cumulativeFramesWritten: Int = 0
// MARK: - Pass-through output
private var _mulAdd: MulAddSpec
@@ -109,14 +124,30 @@ public enum DiskOut {
private var _fileRef: ExtAudioFileRef?
/// RF64 backend for the `.rf64Float32` / `.rf64Int24` formats (`ExtAudioFile`
/// can't write RF64). Exactly one of `_fileRef` / `_rf64Writer` is non-nil.
private var _rf64Writer: RF64Writer?
/// Output container/encoding — fixed at init. Read by the BG drain's
/// large-file guard (`riffOverflow`); CAF/RF64 are exempt.
private let _outputFormat: AudioFileFormat
private let _backgroundQueue: DispatchQueue
private let _stopped: Atomic<Bool> = Atomic(false)
private let _writeError: Atomic<Bool> = Atomic(false)
private let _fileTooLarge: Atomic<Bool> = Atomic(false)
/// `true` if any `ExtAudioFileWrite` call failed during recording.
/// Poll from a non-RT context after `close()` to detect disk write errors.
public var writeError: Bool { _writeError.load(ordering: .acquiring) }
/// `true` if recording stopped early because the file reached the WAV/AIFF
/// 4 GB container cap (see `lyrebirdMaxRIFFBytes`). Frames past the cap are
/// dropped rather than corrupting the file; audio already written stays
/// valid. Always `false` for `.cafFloat32` (CAF is 64-bit, uncapped). Poll
/// from a non-RT context.
public var fileTooLarge: Bool { _fileTooLarge.load(ordering: .acquiring) }
// MARK: - Init
/// Create a streaming disk recorder.
@@ -131,17 +162,21 @@ public enum DiskOut {
/// - url: Output file path. Created or overwritten immediately.
/// - sampleRate: Engine sample rate written into the file header. Defaults
/// to 48 000 Hz.
/// - format: Container format. Defaults to `.aiff`.
/// - format: Container and PCM encoding. Defaults to `.aiffFloat32`.
/// - bufferFrames: Ring buffer capacity in frames. Must be a power of two.
/// Default 8 192 (≈ 170 ms at 48 kHz).
/// - mul: Output scale factor. Defaults to `1.0`.
/// - add: Output offset. Defaults to `0.0`.
///
/// - Throws: ``DiskOutError`` on file-create/format failure for the
/// `ExtAudioFile`-backed formats. For the `.rf64*` formats, a
/// ``RF64WriterError`` may surface instead.
public init(
source: any ValidGeneratorInput,
channelCount: Int,
url: URL,
sampleRate: Double = 48000,
format: DiskOutFormat = .aiff,
format: AudioFileFormat = .aiffFloat32,
bufferFrames: Int = 8192,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
@@ -152,10 +187,16 @@ public enum DiskOut {
bufferFrames > 0 && bufferFrames & (bufferFrames - 1) == 0,
"DiskOut.Audio: bufferFrames \(bufferFrames) must be a power of two"
)
// Streaming a compressed encoder (priming/latency/flush) is out of scope —
// reject before any allocation. AAC / ALAC render offline instead.
guard !format.isCompressed else {
throw DiskOutError.compressedFormatNotSupported(format)
}
let resolvedSource: any ValidGeneratorInput = source._resolvedInput()
self.channelCount = channelCount
self._source = resolvedSource
self._outputFormat = format
self._ringSize = bufferFrames
self._ringMask = bufferFrames - 1
@@ -170,78 +211,60 @@ public enum DiskOut {
_backgroundQueue = DispatchQueue(label: "com.lyrebird.diskout",
qos: .userInitiated)
// Create the output file.
//
// File format is derived from `format` (may be integer-encoded).
// Client format is always Float32 interleaved — ExtAudioFile handles
// the Float32 → int16/int24 conversion transparently.
let fileBytesPerSample: UInt32 = UInt32(format.fileBitsPerChannel / 8)
var fileFormatFlags: AudioFormatFlags = kAudioFormatFlagIsPacked
if format.isFloatEncoding {
fileFormatFlags |= kAudioFormatFlagIsFloat
// Create the output file. RF64 (64-bit WAV) goes through RF64Writer;
// everything else through ExtAudioFile. Client samples are always native
// Float32 interleaved — ExtAudioFile handles Float32 → int16/int24, and
// RF64Writer handles Float32 → RF64 float/int24, transparently.
if format.usesRF64Writer {
do {
_rf64Writer = try RF64Writer(
url: url, format: format, sampleRate: sampleRate, channels: channelCount
)
} catch {
// Pre-`super.init()` throw — `deinit` won't run; free the ring.
// Rethrow the RF64WriterError directly (init throws are untyped).
_ringStorage.deallocate()
throw error
}
} else {
fileFormatFlags |= kAudioFormatFlagIsSignedInteger
}
if format.isBigEndian {
fileFormatFlags |= kAudioFormatFlagIsBigEndian
}
var fileFmt: AudioStreamBasicDescription =
format.makeFileASBD(sampleRate: sampleRate, channels: channelCount)
var rawRef: ExtAudioFileRef?
let createStatus: OSStatus = ExtAudioFileCreateWithURL(
url as CFURL,
format.audioFileTypeID,
&fileFmt,
nil,
AudioFileFlags.eraseFile.rawValue,
&rawRef
)
guard createStatus == noErr, let rawRef: ExtAudioFileRef else {
// These guards throw before `super.init()`, so `deinit` will not
// run — free the raw ring storage explicitly or it leaks. (The
// former `[[Float]]` ring was ARC-managed and torn down here for
// free; raw memory is not.)
_ringStorage.deallocate()
throw DiskOutError.cannotCreateFile(createStatus)
}
_fileRef = rawRef
var fileFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
mSampleRate: sampleRate,
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: fileFormatFlags,
mBytesPerPacket: fileBytesPerSample * UInt32(channelCount),
mFramesPerPacket: 1,
mBytesPerFrame: fileBytesPerSample * UInt32(channelCount),
mChannelsPerFrame: UInt32(channelCount),
mBitsPerChannel: format.fileBitsPerChannel,
mReserved: 0
)
var rawRef: ExtAudioFileRef?
let createStatus: OSStatus = ExtAudioFileCreateWithURL(
url as CFURL,
format.audioFileType,
&fileFmt,
nil,
AudioFileFlags.eraseFile.rawValue,
&rawRef
)
guard createStatus == noErr, let rawRef: ExtAudioFileRef else {
// These guards throw before `super.init()`, so `deinit` will not
// run — free the raw ring storage explicitly or it leaks. (The
// former `[[Float]]` ring was ARC-managed and torn down here for
// free; raw memory is not.)
_ringStorage.deallocate()
throw DiskOutError.cannotCreateFile(createStatus)
}
_fileRef = rawRef
// Client format is always Float32 interleaved, regardless of the file
// encoding. ExtAudioFile converts float→int when writing to the file.
let float32ByteSize: UInt32 = UInt32(MemoryLayout<Float>.size)
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
mSampleRate: sampleRate,
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
mBytesPerPacket: float32ByteSize * UInt32(channelCount),
mFramesPerPacket: 1,
mBytesPerFrame: float32ByteSize * UInt32(channelCount),
mChannelsPerFrame: UInt32(channelCount),
mBitsPerChannel: lyrebirdBitsPerSample,
mReserved: 0
)
let setFmtStatus: OSStatus = ExtAudioFileSetProperty(
rawRef,
kExtAudioFileProperty_ClientDataFormat,
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
&clientFmt
)
guard setFmtStatus == noErr else {
ExtAudioFileDispose(rawRef)
_fileRef = nil
// Pre-`super.init()` throw — `deinit` won't run; free the ring.
_ringStorage.deallocate()
throw DiskOutError.cannotSetFormat(setFmtStatus)
// Client format is always Float32 interleaved, regardless of the file
// encoding. ExtAudioFile converts float→int when writing to the file.
var clientFmt: AudioStreamBasicDescription =
format.makeClientASBD(sampleRate: sampleRate, channels: channelCount)
let setFmtStatus: OSStatus = ExtAudioFileSetProperty(
rawRef,
kExtAudioFileProperty_ClientDataFormat,
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
&clientFmt
)
guard setFmtStatus == noErr else {
ExtAudioFileDispose(rawRef)
_fileRef = nil
// Pre-`super.init()` throw — `deinit` won't run; free the ring.
_ringStorage.deallocate()
throw DiskOutError.cannotSetFormat(setFmtStatus)
}
}
super.init(channels: channelCount)
@@ -264,6 +287,12 @@ public enum DiskOut {
ExtAudioFileDispose(ref)
_fileRef = nil
}
if let writer: RF64Writer = _rf64Writer {
// Patch the ds64 sizes and close. A failure here means the size fields
// stay unpatched; surface it via the same flag as write errors.
do { try writer.close() } catch { _writeError.store(true, ordering: .releasing) }
_rf64Writer = nil
}
}
deinit {
@@ -275,6 +304,10 @@ public enum DiskOut {
// finished its current iteration before deinit can start, so _fileRef
// is not being accessed concurrently; direct disposal is safe.
if let ref: ExtAudioFileRef = _fileRef { ExtAudioFileDispose(ref) }
// RF64Writer.close() patches the ds64 sizes; its own deinit is a
// best-effort fallback, but call it here so a forgotten close() still
// finalises the file. Safe for the same no-concurrent-BG reason above.
try? _rf64Writer?.close()
}
// Free the raw ring storage. Safe here for the same reason the file
// disposal is: the BG loop upgrades its `[weak self]` to a strong
@@ -309,7 +342,14 @@ public enum DiskOut {
let rHead: Int = _framesRead.load(ordering: .relaxed)
let wHead: Int = _framesWritten.load(ordering: .acquiring)
let available: Int = wHead - rHead
guard available > 0, let fileRef: ExtAudioFileRef = _fileRef else { return }
guard available > 0, (_fileRef != nil || _rf64Writer != nil) else { return }
// Once the file has hit the container cap, discard remaining frames
// without writing (keeps the ring draining so the RT side never stalls).
if _fileTooLarge.load(ordering: .acquiring) {
_framesRead.store(rHead + available, ordering: .releasing)
return
}
// Drain in chunks no larger than the interleaved write buffer capacity.
let chunkFrames: Int = _interleavedWriteBuf.count / channelCount // == _ringSize
@@ -317,32 +357,53 @@ public enum DiskOut {
while totalDrained < available {
let toWrite: Int = min(chunkFrames, available - totalDrained)
// Large-file guard: for WAV/AIFF (32-bit-sized), stop before a write
// that would push the file past the 4 GB cap. CAF → riffOverflow nil,
// so this is a no-op for the default streaming format.
if _outputFormat.riffOverflow(
frameCount: _cumulativeFramesWritten + toWrite, channels: channelCount
) != nil {
_fileTooLarge.store(true, ordering: .releasing)
break
}
for f: Int in 0..<toWrite {
let pos: Int = (rHead + totalDrained + f) & _ringMask
for ch: Int in 0..<channelCount {
_interleavedWriteBuf[f * channelCount + ch] = _ringStorage[ch * _ringSize + pos]
}
}
_interleavedWriteBuf.withUnsafeMutableBufferPointer { ptr in
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
let frames: UInt32 = UInt32(toWrite)
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(channelCount),
mDataByteSize: UInt32(
toWrite * channelCount * MemoryLayout<Float>.size),
mData: base
if let rf64Writer: RF64Writer = _rf64Writer {
_interleavedWriteBuf.withUnsafeBufferPointer { ptr in
do { try rf64Writer.writeFloat32Interleaved(ptr, frames: toWrite) }
catch { _writeError.store(true, ordering: .releasing) }
}
} else if let fileRef: ExtAudioFileRef = _fileRef {
_interleavedWriteBuf.withUnsafeMutableBufferPointer { ptr in
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
let frames: UInt32 = UInt32(toWrite)
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(channelCount),
mDataByteSize: UInt32(
toWrite * channelCount * MemoryLayout<Float>.size),
mData: base
)
)
)
let writeStatus: OSStatus = ExtAudioFileWrite(fileRef, frames, &bufList)
if writeStatus != noErr {
_writeError.store(true, ordering: .releasing)
let writeStatus: OSStatus = ExtAudioFileWrite(fileRef, frames, &bufList)
if writeStatus != noErr {
_writeError.store(true, ordering: .releasing)
}
}
}
_cumulativeFramesWritten += toWrite
totalDrained += toWrite
}
// Advance the read head by everything that was available — including any
// frames skipped after an overflow break — so the ring keeps draining.
_framesRead.store(rHead + available, ordering: .releasing)
}
@@ -11,4 +11,9 @@ import AudioToolbox
public enum DiskOutError: Error {
case cannotCreateFile(OSStatus)
case cannotSetFormat(OSStatus)
/// A compressed format (AAC / ALAC) was passed to ``DiskOut/Audio``. Real-time
/// streaming to a compressed codec is not supported — use a PCM or RF64 format
/// for `DiskOut`, and render offline (`LyrebirdBuffer.write` / `NRTDriver`) for
/// AAC / ALAC output.
case compressedFormatNotSupported(AudioFileFormat)
}
@@ -4,87 +4,12 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AudioToolbox
/// Container-and-encoding format for ``DiskOut/Audio``.
/// Deprecated alias for the framework-wide ``AudioFileFormat``.
///
/// Each case encodes both the container (WAV or AIFF) and the PCM bit depth.
/// ``DiskOut/Audio`` always accepts Float32 from the signal graph (the client
/// data format) and delegates any necessary conversion to `ExtAudioFile`.
public enum DiskOutFormat: Sendable {
// MARK: - WAV variants
/// WAV container with 32-bit IEEE-754 float encoding.
case wavFloat32
/// WAV container with 16-bit signed integer encoding.
case wavInt16
/// WAV container with 24-bit signed integer encoding.
case wavInt24
// MARK: - AIFF-C variants
/// AIFF-C container with 32-bit IEEE-754 float encoding.
case aiffFloat32
// MARK: - Deprecated shorthands (kept for DiskOut.Audio default parameter)
/// AIFF-C container with 32-bit float encoding. Alias for ``aiffFloat32``.
public static let aiff: DiskOutFormat = .aiffFloat32
/// WAV container with 32-bit float encoding. Alias for ``wavFloat32``.
public static let wav: DiskOutFormat = .wavFloat32
// MARK: - Derived properties
/// AudioToolbox container type ID used when creating the `ExtAudioFile`.
var audioFileType: AudioFileTypeID {
switch self {
case .wavFloat32, .wavInt16, .wavInt24:
return kAudioFileWAVEType
case .aiffFloat32:
return kAudioFileAIFCType
}
}
/// Filesystem extension for the output file (without the leading dot).
public var fileExtension: String {
switch self {
case .wavFloat32, .wavInt16, .wavInt24:
return "wav"
case .aiffFloat32:
return "aiff"
}
}
/// Bits per sample in the encoded file.
var fileBitsPerChannel: UInt32 {
switch self {
case .wavFloat32, .aiffFloat32:
return 32
case .wavInt16:
return 16
case .wavInt24:
return 24
}
}
/// `true` when the file encoding is IEEE-754 float.
var isFloatEncoding: Bool {
switch self {
case .wavFloat32, .aiffFloat32:
return true
case .wavInt16, .wavInt24:
return false
}
}
/// `true` when the container stores big-endian samples (AIFF-C spec).
var isBigEndian: Bool {
switch self {
case .aiffFloat32:
return true
case .wavFloat32, .wavInt16, .wavInt24:
return false
}
}
}
/// The container/encoding enum is shared across ``DiskOut/Audio``,
/// ``LyrebirdBuffer/write(to:format:sampleRate:)``, and the NRT driver, so it now
/// lives under one name. This alias keeps existing `DiskOutFormat.wavFloat32` /
/// `.aiffFloat32` / `.wav` / `.aiff` spellings compiling; migrate to
/// ``AudioFileFormat`` directly.
@available(*, deprecated, message: "Use AudioFileFormat instead.")
public typealias DiskOutFormat = AudioFileFormat
+39 -4
View File
@@ -250,12 +250,44 @@ 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)
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
```
All formats write 32-bit float (Float32). `Double` (Double) values are downcast on the way out.
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
@@ -316,6 +348,9 @@ do {
| `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 |
@@ -455,11 +455,13 @@ list.stopRecord()
// Inspect state:
list.isRecording // Bool
list.recordDirectory // URL?
list.recordFormat // DiskOutFormat
list.recordFormat // AudioFileFormat
```
**Late-start behavior**: calling `record(directory:format:)` after the first event has already fired is valid. Processes already running do not start recording retroactively — only new ``LyrebirdProcess/play(engine:)`` calls after this point produce stem files.
**4 GB cap on WAV/AIFF stems**: the default `format` is a WAV encoding, and WAV/AIFF-C containers are limited to 4 GB (32-bit size fields). A very long performance can hit that ceiling — the affected stem stops growing at the cap (frames past it are silently dropped; audio already written stays valid) rather than corrupting. For multi-hour sessions record to a 64-bit container: `.cafFloat32`, or `.rf64Float32` / `.rf64Int24` (RF64/BW64 — keeps the `.wav` extension, uncapped). Each stem's ``DiskOut/Audio`` exposes `fileTooLarge` if you need to detect the condition after teardown.
### Stem Filename Scheme
Each stem file is named:
@@ -484,12 +486,16 @@ The offset field is zero-padded to a fixed width (7 integer digits, 4 decimal pl
### Format Options
| ``DiskOutFormat`` case | Container | Encoding | Use when |
| ``AudioFileFormat`` case | Container | Encoding | Use when |
|------------------------|-----------|----------|----------|
| `.wavFloat32` | WAV | 32-bit float | Default. Lossless, DAW-compatible. |
| `.wavInt16` | WAV | 16-bit PCM | Smallest file; -96 dB noise floor. |
| `.wavInt24` | WAV | 24-bit PCM | Balanced. |
| `.aiffFloat32` | AIFF | 32-bit float | Legacy Mac/ProTools compatibility. |
| `.cafFloat32` | CAF | 32-bit float | Long sessions — 64-bit sizes, no 4 GB cap. |
| `.rf64Float32` / `.rf64Int24` | WAV (RF64) | 32-bit float / 24-bit PCM | Long sessions needing the `.wav` extension. |
> Note: The compressed codecs (`.aacHigh` / `.aacMedium` / `.alac`) are **not** available for stem recording — ``DiskOut/Audio`` (which backs stems) rejects them. Compressed output is offline-only (`LyrebirdBuffer.write` / `NRTDriver`).
> Note: A master file that captures the mixed master bus (after the `EventListMasterSynth`) is planned for a future phase. Currently only per-process dry stems are recorded.
@@ -72,6 +72,21 @@ public let lyrebirdBufferMonoChannelCount: Int = 1
/// multichannel configurations.
public let lyrebirdMaxFileChannelCount: Int = 8
/// Largest audio-data payload (bytes) a classic RIFF (WAV) or AIFF-C container can
/// address. Both use unsigned **32-bit** size fields, so the whole file must fit in
/// 4 GB (`0xFFFF_FFFF`). We subtract a header slack so header + data together stay
/// within range regardless of the exact chunk layout.
///
/// `ExtAudioFile` writes only classic RIFF / AIFF — CoreAudio has no RF64 / BW64 /
/// W64 writer — so a WAV/AIFF write past this cap is unreachable and is rejected by
/// the `LyrebirdBuffer.write` / `NRTDriver` large-file guards (throwing
/// `fileTooLargeForContainer`). Use `.cafFloat32` (64-bit sizes, uncapped) instead.
///
/// Rule of thumb: 4 ch × Float32 × 48 kHz ≈ 4 GB in ~43 minutes.
private let riffSizeFieldMax: Int = 0xFFFF_FFFF
private let riffHeaderSlackBytes: Int = 1024
public let lyrebirdMaxRIFFBytes: Int = riffSizeFieldMax - riffHeaderSlackBytes
// MARK: - Granular synthesis
/// Pre-allocated grain pool size for `BufferGrain`.
@@ -246,7 +246,7 @@ public final class LyrebirdEventList: @unchecked Sendable {
/// Non-nil while recording is enabled. Set by ``record(directory:format:)``
/// and cleared by ``stopRecord()``.
private var _recordingDirectory: URL?
private var _recordingFormat: DiskOutFormat = .wavFloat32
private var _recordingFormat: AudioFileFormat = .wavFloat32
private var _isRecording: Bool = false
// MARK: - Timeline state (main-thread only)
@@ -515,8 +515,8 @@ public final class LyrebirdEventList: @unchecked Sendable {
/// Container-and-encoding format used for stem files.
///
/// Defaults to ``DiskOutFormat/wavFloat32``. Set via ``record(directory:format:)``.
public var recordFormat: DiskOutFormat { _recordingFormat }
/// Defaults to ``AudioFileFormat/wavFloat32``. Set via ``record(directory:format:)``.
public var recordFormat: AudioFileFormat { _recordingFormat }
// MARK: - Playback
@@ -818,11 +818,26 @@ public final class LyrebirdEventList: @unchecked Sendable {
/// eagerly (including intermediate directories) before this call returns.
/// A failure to create the directory is logged but does not throw — recording
/// will simply fail silently when the first process attempts to write.
/// - format: Container and PCM encoding. Defaults to ``DiskOutFormat/wavFloat32``.
/// - format: Container and PCM encoding. Defaults to ``AudioFileFormat/wavFloat32``.
/// Must be a PCM or RF64 format — compressed formats (`.aacHigh` / `.aacMedium`
/// / `.alac`) are **rejected** (stems stream through ``DiskOut/Audio``, which is
/// PCM/RF64 only); passing one logs a warning and leaves recording disabled.
public func record(
directory: URL,
format: DiskOutFormat = .wavFloat32
format: AudioFileFormat = .wavFloat32
) {
// Stems are written by DiskOut, which streams PCM/RF64 only — a compressed
// format would make every per-process DiskOut.init throw and recording fail
// silently. Reject it up front with a clear message and do not enable
// recording (render offline for compressed output).
guard !format.isCompressed else {
print("[LyrebirdEventList '\(id)'] Compressed formats (AAC/ALAC) are not "
+ "supported for stem recording — DiskOut streams PCM/RF64 only. "
+ "Recording NOT enabled. Use a PCM/RF64 format for stems, or render "
+ "offline (LyrebirdBuffer.write / NRTDriver) for AAC/ALAC.")
return
}
// Eagerly create the directory so the contract "directory exists when the
// first process plays" is guaranteed regardless of whether any event fires.
do {
@@ -20,7 +20,7 @@ struct ProcessRecordingConfig {
let directory: URL
/// Output file encoding/container format.
let format: DiskOutFormat
let format: AudioFileFormat
/// The EventList's `id`, pre-sanitised for filesystem use.
let sanitisedEventListID: String