Files
Lyrebird/Sources/Lyrebird/Buffers/LyrebirdBufferFileIO.swift
T
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
Consolidated release: the cross-platform Linux port (engine, generators, CLI,
REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable
WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux
live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive.
See RELEASES.md and LINUX_README.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-10 21:09:11 -07:00

792 lines
34 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
#if canImport(AudioToolbox)
import AudioToolbox
#endif
// MARK: - LyrebirdBufferIOError
/// Errors thrown by `LyrebirdBuffer` file I/O methods.
public enum LyrebirdBufferIOError: Error, Equatable {
#if canImport(AudioToolbox)
/// `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)
/// `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)
#endif
/// 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)
/// 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)
#if !canImport(AudioToolbox)
/// A non-WAV container (`.caf` / `.aiff` / `.aac` / `.alac` / RF64) was
/// requested for `write(to:format:)` off Apple, where only the portable WAV
/// encodings are available. Reading uses the portable ``WavFileReader``,
/// whose failures surface as ``WavFileError``.
case unsupportedFormatOnPlatform(AudioFileFormat)
#endif
}
// 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
#if canImport(AudioToolbox)
/// Bit depth of the Float32 client format used for all file I/O reads and writes.
private let lyrebirdFileIOBitsPerSample: UInt32 = 32
#endif
// 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 {
#if canImport(AudioToolbox)
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
#else
// Portable WAV read. `WavFileReader` throws `WavFileError` on a bad or
// non-WAV file. Like the Apple path, the buffer keeps the file's own
// sample rate — neither path resamples on load.
let reader: WavFileReader = try WavFileReader(url: url)
defer { reader.close() }
let fileChannelCount: Int = reader.channels
guard channel < fileChannelCount else {
throw LyrebirdBufferIOError.channelOutOfRange(
requested: channel, available: fileChannelCount
)
}
let fileFrameCount: Int = reader.frameCount
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: max(1, fileFrameCount))
buffer.setSampleRate(reader.sampleRate)
try portableReadMono(
reader, into: buffer, channel: channel,
framesToRead: fileFrameCount, normalise: normalise
)
return buffer
#endif
}
// 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 {
#if canImport(AudioToolbox)
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
#else
let reader: WavFileReader = try WavFileReader(url: url)
defer { reader.close() }
let fileChannelCount: Int = reader.channels
guard fileChannelCount >= 1 && fileChannelCount <= lyrebirdMaxFileChannelCount else {
throw LyrebirdBufferIOError.invalidChannelCount(fileChannelCount)
}
let fileFrameCount: Int = reader.frameCount
let buffer: LyrebirdBuffer = LyrebirdBuffer(
count: max(1, fileFrameCount),
channelCount: fileChannelCount
)
buffer.setSampleRate(reader.sampleRate)
try portableReadAllChannels(
reader, into: buffer,
framesToRead: fileFrameCount, normalise: normalise
)
return buffer
#endif
}
// 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")
let framesToRead: Int
#if canImport(AudioToolbox)
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)
framesToRead = min(fileFrameCount, count)
try readSamples(
from: fileRef,
into: self,
channel: channel,
fileChannelCount: fileChannelCount,
sampleRate: fileSampleRate,
framesToRead: framesToRead,
normalise: normalise
)
#else
let reader: WavFileReader = try WavFileReader(url: url)
defer { reader.close() }
let fileChannelCount: Int = reader.channels
guard channel < fileChannelCount else {
throw LyrebirdBufferIOError.channelOutOfRange(
requested: channel, available: fileChannelCount
)
}
self.setSampleRate(reader.sampleRate)
framesToRead = min(reader.frameCount, count)
try portableReadMono(
reader, into: self, channel: channel,
framesToRead: framesToRead, normalise: normalise
)
#endif
// 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
}
#if canImport(AudioToolbox)
// 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
}
}
#else
// Portable WAV output. The Apple-only containers (CAF / AIFF-C / AAC /
// ALAC) have no portable encoder; RF64 was already handled above by the
// cross-platform `RF64Writer`. Everything else is a classic-RIFF WAV.
let encoding: WavEncoding = try Self.wavEncoding(for: format)
let writer: WavFileWriter = try WavFileWriter(
url: url, channels: channelCount, sampleRate: sampleRate, encoding: encoding
)
// Finalize even if a write throws partway, so the file's header sizes
// are patched rather than left at zero. `finalize()` is idempotent.
defer { try? writer.finalize() }
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])
}
try writer.write(interleaved: writeBuf, frames: framesThisChunk)
srcOffset += samplesThisChunk
}
}
try writer.finalize()
#endif
}
#if !canImport(AudioToolbox)
/// Maps a WAV ``AudioFileFormat`` to a ``WavEncoding`` for the portable
/// writer; the Apple-only containers throw
/// ``LyrebirdBufferIOError/unsupportedFormatOnPlatform(_:)``. RF64 is written
/// by ``RF64Writer`` before this is reached.
static func wavEncoding(for format: AudioFileFormat) throws -> WavEncoding {
switch format {
case .wavFloat32: return .float32
case .wavInt16: return .int16
case .wavInt24: return .int24
case .rf64Float32, .rf64Int24, .cafFloat32, .aiffFloat32, .aacHigh, .aacMedium, .alac:
throw LyrebirdBufferIOError.unsupportedFormatOnPlatform(format)
}
}
#endif
}
// MARK: - Private helpers
#if canImport(AudioToolbox)
/// 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 }
}
}
}
}
#else
// MARK: - Portable read helpers (non-Apple)
/// Reads one channel of a WAV into a mono buffer's storage, in chunks, with
/// optional peak normalisation. Mirrors the Apple ``readSamples`` helper.
private func portableReadMono(
_ reader: WavFileReader,
into buffer: LyrebirdBuffer,
channel: Int,
framesToRead: Int,
normalise: Bool
) throws {
let fileChannelCount: Int = reader.channels
try buffer.withMutableStorage { storage, _, _ in
var destOffset: Int = 0
while destOffset < framesToRead {
let framesThisChunk: Int = min(lyrebirdFileIOChunkFrames, framesToRead - destOffset)
let block: [Float] = try reader.read(frames: framesThisChunk)
let framesRead: Int = fileChannelCount > 0 ? block.count / fileChannelCount : 0
if framesRead == 0 { break }
for i: Int in 0..<framesRead {
storage[destOffset + i] = Double(block[i * fileChannelCount + channel])
}
destOffset += framesRead
}
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 }
}
}
}
}
/// Reads every channel of a WAV into an interleaved multichannel buffer, in
/// chunks, with optional global-peak normalisation. Mirrors ``readAllChannels``.
private func portableReadAllChannels(
_ reader: WavFileReader,
into buffer: LyrebirdBuffer,
framesToRead: Int,
normalise: Bool
) throws {
let fileChannelCount: Int = reader.channels
let bufChannelCount: Int = buffer.channelCount
try buffer.withMutableStorage { storage, _, _ in
var destFrame: Int = 0
while destFrame < framesToRead {
let framesThisChunk: Int = min(lyrebirdFileIOChunkFrames, framesToRead - destFrame)
let block: [Float] = try reader.read(frames: framesThisChunk)
let framesRead: Int = fileChannelCount > 0 ? block.count / fileChannelCount : 0
if framesRead == 0 { break }
for f: Int in 0..<framesRead {
for ch: Int in 0..<bufChannelCount {
storage[(destFrame + f) * bufChannelCount + ch] =
Double(block[f * fileChannelCount + ch])
}
}
destFrame += framesRead
}
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 }
}
}
}
}
#endif