Files
Lyrebird/Sources/Lyrebird/Buffers/LyrebirdBufferFileIO.swift
T

591 lines
25 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// LyrebirdBufferFileIO.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import AudioToolbox
// MARK: - LyrebirdBufferIOError
/// Errors thrown by `LyrebirdBuffer` file I/O methods.
public enum LyrebirdBufferIOError: Error, Equatable {
/// `ExtAudioFileOpenURL` failed with the given status code.
case cannotOpenFile(OSStatus)
/// Querying the file's `AudioStreamBasicDescription` failed.
case cannotQueryFileFormat(OSStatus)
/// Querying the file's frame count failed.
case cannotQueryFrameCount(OSStatus)
/// Setting the ExtAudioFile client format to Float32 failed.
case cannotSetClientFormat(OSStatus)
/// `ExtAudioFileRead` returned a non-zero status.
case readFailed(OSStatus)
/// The requested channel index is outside the range of channels in the file.
case channelOutOfRange(requested: Int, available: Int)
/// The file's ASBD reports a channel count that is 0 or exceeds `lyrebirdMaxFileChannelCount`.
/// This guard fires in `queryFileProperties` before any allocation using the channel count.
case invalidChannelCount(Int)
/// `ExtAudioFileCreateWithURL` failed when creating the output file.
case cannotCreateOutputFile(OSStatus)
/// Setting the output file's client format failed.
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
/// Number of audio frames processed per `ExtAudioFileRead` or `ExtAudioFileWrite` call.
/// Small enough to keep stack pressure low; large enough to amortize the per-call overhead.
private let lyrebirdFileIOChunkFrames: Int = 4096
/// Bit depth of the Float32 client format used for all file I/O reads and writes.
private let lyrebirdFileIOBitsPerSample: UInt32 = 32
// MARK: - LyrebirdBuffer + File I/O
public extension LyrebirdBuffer {
// MARK: - load(url:channel:normalise:)
/// Allocate a new mono `LyrebirdBuffer` sized exactly to the file's frame count and fill
/// it from the specified channel.
///
/// - Parameters:
/// - url: Audio file to read. Any format supported by `ExtAudioFile` is accepted
/// (AIFF, WAV, CAF, MP3, AAC, …). The file's native format is converted to
/// Float32 transparently.
/// - channel: Zero-based channel index to extract. Defaults to `0` (first/only channel
/// for mono files). Pass `1` for the right channel of a stereo file.
/// Throws `channelOutOfRange` if the index is ≥ the file's channel count.
/// - normalise: When `true`, divides every sample by the peak absolute value so the
/// loudest sample is ±1. Silent files (peak == 0) are left unchanged.
///
/// To load **all** channels from a file into a single multichannel buffer, use
/// `loadAllChannels(url:normalise:)` instead.
///
/// Must be called on a non-RT thread before the returned buffer is passed to any
/// generator running in the engine.
static func load(
url: URL,
channel: Int = 0,
normalise: Bool = false
) throws -> LyrebirdBuffer {
var fileRef: ExtAudioFileRef?
let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &fileRef)
guard openStatus == noErr, let fileRef: ExtAudioFileRef else {
throw LyrebirdBufferIOError.cannotOpenFile(openStatus)
}
defer { ExtAudioFileDispose(fileRef) }
let (fileFrameCount, fileChannelCount, fileSampleRate) = try queryFileProperties(fileRef)
guard channel < fileChannelCount else {
throw LyrebirdBufferIOError.channelOutOfRange(
requested: channel, available: fileChannelCount
)
}
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: max(1, fileFrameCount))
buffer.setSampleRate(fileSampleRate)
try readSamples(
from: fileRef,
into: buffer,
channel: channel,
fileChannelCount: fileChannelCount,
sampleRate: fileSampleRate,
framesToRead: fileFrameCount,
normalise: normalise
)
return buffer
}
// MARK: - loadAllChannels(url:normalise:)
/// Allocate a new `LyrebirdBuffer` sized to the file's frame count and channel count,
/// and fill it with all channels from the audio file.
///
/// The returned buffer has `channelCount` equal to the file's channel count and stores
/// data in interleaved order: `[ch0_f0, ch1_f0, …, ch0_f1, ch1_f1, …]`. Access
/// samples with `buffer[frame: i, channel: ch]`.
///
/// - Parameters:
/// - url: Audio file to read. Any format supported by `ExtAudioFile` is accepted.
/// - normalise: When `true`, divides every sample by the global peak absolute value
/// (across all channels) so the loudest sample in the file is ±1.
/// Silent files (all-zero) are left unchanged.
///
/// Must be called on a non-RT thread before the returned buffer is passed to any
/// generator running in the engine.
static func loadAllChannels(
url: URL,
normalise: Bool = false
) throws -> LyrebirdBuffer {
var fileRef: ExtAudioFileRef?
let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &fileRef)
guard openStatus == noErr, let fileRef: ExtAudioFileRef else {
throw LyrebirdBufferIOError.cannotOpenFile(openStatus)
}
defer { ExtAudioFileDispose(fileRef) }
let (fileFrameCount, fileChannelCount, fileSampleRate) = try queryFileProperties(fileRef)
// queryFileProperties guarantees fileChannelCount ∈ [1, lyrebirdMaxFileChannelCount],
// so fileChannelCount is used directly as the buffer's channel count.
let buffer: LyrebirdBuffer = LyrebirdBuffer(
count: max(1, fileFrameCount),
channelCount: fileChannelCount
)
buffer.setSampleRate(fileSampleRate)
try readAllChannels(
from: fileRef,
into: buffer,
fileChannelCount: fileChannelCount,
sampleRate: fileSampleRate,
framesToRead: fileFrameCount,
normalise: normalise
)
return buffer
}
// MARK: - fill(fromFile:channel:normalise:)
/// Fill this **mono** buffer with samples from the specified channel of an audio file.
///
/// Requires `channelCount == 1`. For multichannel buffers, use `loadAllChannels(url:)`.
///
/// - If the file has **more** frames than `self.count`, reading stops at `self.count`
/// (the file is truncated to fit the buffer).
/// - If the file has **fewer** frames than `self.count`, the remaining samples are
/// zero-padded.
/// - Throws `channelOutOfRange` if `channel` ≥ the file's channel count.
///
/// Must be called before `invalidate()` and before the buffer enters RT use.
func fill(
fromFile url: URL,
channel: Int = 0,
normalise: Bool = false
) throws {
precondition(
channelCount == lyrebirdBufferMonoChannelCount,
"fill(fromFile:) requires a mono buffer (channelCount == 1); "
+ "this buffer has channelCount == \(channelCount). "
+ "Use loadAllChannels(url:) for multichannel files."
)
precondition(isValid, "fill(fromFile:) called on an invalidated LyrebirdBuffer")
var fileRef: ExtAudioFileRef?
let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &fileRef)
guard openStatus == noErr, let fileRef: ExtAudioFileRef else {
throw LyrebirdBufferIOError.cannotOpenFile(openStatus)
}
defer { ExtAudioFileDispose(fileRef) }
let (fileFrameCount, fileChannelCount, fileSampleRate) = try queryFileProperties(fileRef)
guard channel < fileChannelCount else {
throw LyrebirdBufferIOError.channelOutOfRange(
requested: channel, available: fileChannelCount
)
}
self.setSampleRate(fileSampleRate)
let framesToRead: Int = min(fileFrameCount, count)
try readSamples(
from: fileRef,
into: self,
channel: channel,
fileChannelCount: fileChannelCount,
sampleRate: fileSampleRate,
framesToRead: framesToRead,
normalise: normalise
)
// Zero-pad if the file was shorter than the buffer.
if framesToRead < count {
withMutableStorage { storage, bufCount, _ in
for i: Int in framesToRead..<bufCount {
storage[i] = 0.0
}
}
}
}
// MARK: - write(to:format:sampleRate:)
/// Write the buffer's contents to an audio file.
///
/// 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 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
/// "Persisting Captured Input Buffers" subsection of the Process System
/// article (DocC: <doc:ProcessSystem>) — it covers the background-task
/// pattern (captures strong buffer refs, gated on the next session via
/// `await`) that lets large buffers (4 × ~460 MB) flush to disk without
/// blocking the UI and without doubling peak memory on rapid stop/start.
func write(
to url: URL,
format: AudioFileFormat = .caf,
sampleRate: Double = 44100
) throws {
precondition(
channelCount <= lyrebirdMaxFileChannelCount,
"LyrebirdBuffer.write(to:) channelCount \(channelCount) exceeds "
+ "lyrebirdMaxFileChannelCount (\(lyrebirdMaxFileChannelCount))"
)
// 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
)
}
// 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
}
// 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 / encoding to match the file format automatically.
var clientFormat: AudioStreamBasicDescription =
format.makeClientASBD(sampleRate: sampleRate, channels: channelCount)
var fileRef: ExtAudioFileRef?
let createStatus: OSStatus = ExtAudioFileCreateWithURL(
url as CFURL,
format.audioFileTypeID,
&fileFormat,
nil,
AudioFileFlags.eraseFile.rawValue,
&fileRef
)
guard createStatus == noErr, let fileRef: ExtAudioFileRef else {
throw LyrebirdBufferIOError.cannotCreateOutputFile(createStatus)
}
defer { ExtAudioFileDispose(fileRef) }
let setStatus: OSStatus = ExtAudioFileSetProperty(
fileRef,
kExtAudioFileProperty_ClientDataFormat,
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
&clientFormat
)
guard setStatus == noErr else {
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.
let samplesPerChunk: Int = lyrebirdFileIOChunkFrames * channelCount
var writeBuf: [Float] = [Float](repeating: 0, count: samplesPerChunk)
try withStorage { storage, frameCount, nch in
let totalSamples: Int = frameCount * nch
var srcOffset: Int = 0
while srcOffset < totalSamples {
let samplesThisChunk: Int = min(samplesPerChunk, totalSamples - srcOffset)
let framesThisChunk: Int = samplesThisChunk / nch
for i: Int in 0..<samplesThisChunk {
writeBuf[i] = Float(storage[srcOffset + i])
}
let writeStatus: OSStatus = writeBuf.withUnsafeMutableBufferPointer { ptr in
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(nch),
mDataByteSize: UInt32(samplesThisChunk * MemoryLayout<Float>.size),
mData: ptr.baseAddress
)
)
return ExtAudioFileWrite(fileRef, UInt32(framesThisChunk), &bufList)
}
guard writeStatus == noErr else {
throw LyrebirdBufferIOError.writeFailed(writeStatus)
}
srcOffset += samplesThisChunk
}
}
}
}
// MARK: - Private helpers
/// Query an open `ExtAudioFileRef` for its frame count, channel count, and sample rate.
///
/// Validates that `mChannelsPerFrame` is in `[1, lyrebirdMaxFileChannelCount]` before
/// returning, so callers never receive a channel count that would cause an out-of-memory
/// allocation. Throws `LyrebirdBufferIOError.invalidChannelCount` if the check fails.
///
/// Returns `(frameCount, channelCount, sampleRate)`.
private func queryFileProperties(
_ fileRef: ExtAudioFileRef
) throws -> (frameCount: Int, channelCount: Int, sampleRate: Double) {
var fileFormat: AudioStreamBasicDescription = AudioStreamBasicDescription()
var formatPropSize: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
let formatStatus: OSStatus = ExtAudioFileGetProperty(
fileRef,
kExtAudioFileProperty_FileDataFormat,
&formatPropSize,
&fileFormat
)
guard formatStatus == noErr else {
throw LyrebirdBufferIOError.cannotQueryFileFormat(formatStatus)
}
let rawChannelCount: Int = Int(fileFormat.mChannelsPerFrame)
guard rawChannelCount >= 1 && rawChannelCount <= lyrebirdMaxFileChannelCount else {
throw LyrebirdBufferIOError.invalidChannelCount(rawChannelCount)
}
var frameCount: Int64 = 0
var countPropSize: UInt32 = UInt32(MemoryLayout<Int64>.size)
let countStatus: OSStatus = ExtAudioFileGetProperty(
fileRef,
kExtAudioFileProperty_FileLengthFrames,
&countPropSize,
&frameCount
)
guard countStatus == noErr else {
throw LyrebirdBufferIOError.cannotQueryFrameCount(countStatus)
}
return (Int(frameCount), rawChannelCount, fileFormat.mSampleRate)
}
/// Configure `fileRef` for interleaved Float32 reads with `fileChannelCount` channels,
/// then read `framesToRead` frames, extracting only `channel` into `buffer` (mono output).
/// Applies per-channel normalisation if `normalise` is true.
///
/// `sampleRate` must be the value already read from the file's ASBD by `queryFileProperties` —
/// passing it in avoids a redundant `ExtAudioFileGetProperty` call.
private func readSamples(
from fileRef: ExtAudioFileRef,
into buffer: LyrebirdBuffer,
channel: Int,
fileChannelCount: Int,
sampleRate: Double,
framesToRead: Int,
normalise: Bool
) throws {
var clientFormat: AudioStreamBasicDescription = AudioStreamBasicDescription(
mSampleRate: sampleRate,
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
mBytesPerPacket: UInt32(MemoryLayout<Float>.size * fileChannelCount),
mFramesPerPacket: 1,
mBytesPerFrame: UInt32(MemoryLayout<Float>.size * fileChannelCount),
mChannelsPerFrame: UInt32(fileChannelCount),
mBitsPerChannel: lyrebirdFileIOBitsPerSample,
mReserved: 0
)
let setStatus: OSStatus = ExtAudioFileSetProperty(
fileRef,
kExtAudioFileProperty_ClientDataFormat,
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
&clientFormat
)
guard setStatus == noErr else {
throw LyrebirdBufferIOError.cannotSetClientFormat(setStatus)
}
var readBuf: [Float] = [Float](repeating: 0, count: lyrebirdFileIOChunkFrames * fileChannelCount)
try buffer.withMutableStorage { storage, _, _ in
var destOffset: Int = 0
while destOffset < framesToRead {
let framesThisChunk: Int = min(lyrebirdFileIOChunkFrames, framesToRead - destOffset)
var framesToReadThisCall: UInt32 = UInt32(framesThisChunk)
let readStatus: OSStatus = readBuf.withUnsafeMutableBufferPointer { ptr in
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(fileChannelCount),
mDataByteSize: UInt32(framesThisChunk
* fileChannelCount
* MemoryLayout<Float>.size),
mData: ptr.baseAddress
)
)
return ExtAudioFileRead(fileRef, &framesToReadThisCall, &bufList)
}
guard readStatus == noErr else {
throw LyrebirdBufferIOError.readFailed(readStatus)
}
let framesRead: Int = Int(framesToReadThisCall)
for i: Int in 0..<framesRead {
storage[destOffset + i] = Double(readBuf[i * fileChannelCount + channel])
}
destOffset += framesRead
if framesRead == 0 { break }
}
if normalise && framesToRead > 0 {
var peak: Double = 0.0
for i: Int in 0..<framesToRead {
let v: Double = abs(storage[i])
if v > peak { peak = v }
}
if peak > 0.0 {
for i: Int in 0..<framesToRead { storage[i] /= peak }
}
}
}
}
/// Configure `fileRef` for interleaved Float32 reads with `fileChannelCount` channels,
/// then read `framesToRead` frames into `buffer`, preserving all channels.
/// Applies global-peak normalisation (across all channels) if `normalise` is true.
///
/// `sampleRate` must be the value already read from the file's ASBD by `queryFileProperties` —
/// passing it in avoids a redundant `ExtAudioFileGetProperty` call.
private func readAllChannels(
from fileRef: ExtAudioFileRef,
into buffer: LyrebirdBuffer,
fileChannelCount: Int,
sampleRate: Double,
framesToRead: Int,
normalise: Bool
) throws {
// queryFileProperties guarantees fileChannelCount == buffer.channelCount:
// any file reporting more than lyrebirdMaxFileChannelCount channels is rejected
// before this helper is reached. Use the buffer's actual channel count to index storage.
let bufChannelCount: Int = buffer.channelCount
var clientFormat: AudioStreamBasicDescription = AudioStreamBasicDescription(
mSampleRate: sampleRate,
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
mBytesPerPacket: UInt32(MemoryLayout<Float>.size * fileChannelCount),
mFramesPerPacket: 1,
mBytesPerFrame: UInt32(MemoryLayout<Float>.size * fileChannelCount),
mChannelsPerFrame: UInt32(fileChannelCount),
mBitsPerChannel: lyrebirdFileIOBitsPerSample,
mReserved: 0
)
let setStatus: OSStatus = ExtAudioFileSetProperty(
fileRef,
kExtAudioFileProperty_ClientDataFormat,
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
&clientFormat
)
guard setStatus == noErr else {
throw LyrebirdBufferIOError.cannotSetClientFormat(setStatus)
}
var readBuf: [Float] = [Float](repeating: 0, count: lyrebirdFileIOChunkFrames * fileChannelCount)
try buffer.withMutableStorage { storage, _, _ in
var destFrame: Int = 0
while destFrame < framesToRead {
let framesThisChunk: Int = min(lyrebirdFileIOChunkFrames, framesToRead - destFrame)
var framesToReadThisCall: UInt32 = UInt32(framesThisChunk)
let readStatus: OSStatus = readBuf.withUnsafeMutableBufferPointer { ptr in
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: UInt32(fileChannelCount),
mDataByteSize: UInt32(framesThisChunk
* fileChannelCount
* MemoryLayout<Float>.size),
mData: ptr.baseAddress
)
)
return ExtAudioFileRead(fileRef, &framesToReadThisCall, &bufList)
}
guard readStatus == noErr else {
throw LyrebirdBufferIOError.readFailed(readStatus)
}
let framesRead: Int = Int(framesToReadThisCall)
for f: Int in 0..<framesRead {
for ch: Int in 0..<bufChannelCount {
// Interleave into the buffer: storage[frame * bufChannelCount + ch]
storage[(destFrame + f) * bufChannelCount + ch] =
Double(readBuf[f * fileChannelCount + ch])
}
}
destFrame += framesRead
if framesRead == 0 { break }
}
// Global-peak normalisation across all channels.
if normalise && framesToRead > 0 {
let totalSamples: Int = framesToRead * bufChannelCount
var peak: Double = 0.0
for i: Int in 0..<totalSamples {
let v: Double = abs(storage[i])
if v > peak { peak = v }
}
if peak > 0.0 {
for i: Int in 0..<totalSamples { storage[i] /= peak }
}
}
}
}