844dc4d9cd
Typed throws across the closed-error-set APIs (OSC, MIDI, engine add/schedule, bus/config/parameter, and the WAV/RF64/Spectral file codecs — source-compatible narrowing, new .ioFailure cases), plus internal hardening: NSLock-guarded scheduling/MIDI state moved to Mutex<State>, and the Spectral/FFT scratch owners moved to a ~Copyable RTScratchBuffer RAII buffer. No API or behavioral change. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
254 lines
11 KiB
Swift
254 lines
11 KiB
Swift
// WavFileReader.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import Foundation
|
|
|
|
/// Streaming reader for canonical RIFF/WAVE PCM files, portable to every
|
|
/// platform (no `AudioToolbox` dependency).
|
|
///
|
|
/// Parses the `fmt ` and `data` chunks at construction, then serves interleaved
|
|
/// `Float` samples in `[-1, 1]` a block at a time via ``read(frames:)`` — the
|
|
/// mirror of ``WavFileWriter`` and the shape `NRTDriver`'s input path needs.
|
|
public final class WavFileReader {
|
|
|
|
/// Interleaved channel count.
|
|
public let channels: Int
|
|
/// Sample rate in Hz.
|
|
public let sampleRate: Double
|
|
/// Total number of frames (per-channel sample groups) in the file.
|
|
public let frameCount: Int
|
|
/// Decoded PCM encoding.
|
|
public let encoding: WavEncoding
|
|
|
|
private let handle: FileHandle
|
|
private let bytesPerFrame: Int
|
|
private var framesRemaining: Int
|
|
|
|
/// Opens `url` and parses its WAVE header.
|
|
public init(url: URL) throws(WavFileError) {
|
|
guard let h: FileHandle = try? FileHandle(forReadingFrom: url) else {
|
|
throw WavFileError.cannotOpen(url)
|
|
}
|
|
self.handle = h
|
|
|
|
// RIFF/WAVE magic: "RIFF" <size:4> "WAVE".
|
|
let riff: Data = try Self.readExact(h, 12)
|
|
guard riff.prefix(4).elementsEqual(Array("RIFF".utf8)),
|
|
riff.subdata(in: 8..<12).elementsEqual(Array("WAVE".utf8)) else {
|
|
throw WavFileError.notWave
|
|
}
|
|
|
|
var fmtTag: UInt16 = 0
|
|
var numChannels: UInt16 = 0
|
|
var rate: UInt32 = 0
|
|
var bits: UInt16 = 0
|
|
var dataLength: Int = 0
|
|
var foundFmt: Bool = false
|
|
var foundData: Bool = false
|
|
// File length, for clamping a `data` size the file cannot back. Taken
|
|
// by seeking to the end and back rather than stat-ing the path, so it
|
|
// describes the handle actually being read.
|
|
let scanStart: UInt64 = try Self.fhOffset(h)
|
|
let fileByteCount: Int = Int(try Self.fhSeekToEnd(h))
|
|
try Self.fhSeek(h, to: scanStart)
|
|
|
|
// Walk chunks until the data chunk is located (its body is left unread
|
|
// so reads stream from the current file offset).
|
|
while true {
|
|
guard let chunkHeader: Data = try? Self.readExact(h, 8), chunkHeader.count == 8 else {
|
|
break
|
|
}
|
|
let id: Data = chunkHeader.prefix(4)
|
|
let size: Int = Int(Self.readLE32(chunkHeader, at: 4))
|
|
if id.elementsEqual(Array("fmt ".utf8)) {
|
|
// A `fmt ` chunk always carries at least the 16 PCM bytes.
|
|
// Anything shorter is malformed, and reading the fields at
|
|
// their fixed offsets would index past the chunk and trap.
|
|
guard size >= Self.minimumFmtChunkSize else { throw WavFileError.truncated }
|
|
let fmt: Data = try Self.readExact(h, size)
|
|
guard fmt.count >= Self.minimumFmtChunkSize else { throw WavFileError.truncated }
|
|
fmtTag = Self.readLE16(fmt, at: 0)
|
|
numChannels = Self.readLE16(fmt, at: 2)
|
|
rate = Self.readLE32(fmt, at: 4)
|
|
bits = Self.readLE16(fmt, at: 14)
|
|
// WAVE_FORMAT_EXTENSIBLE is what most 24-bit and multichannel
|
|
// writers emit; the real encoding lives in the first two bytes
|
|
// of the SubFormat GUID, and the rest of the header is
|
|
// identical. Rejecting it outright would refuse ordinary files.
|
|
if fmtTag == Self.waveFormatExtensible, fmt.count >= Self.extensibleFmtChunkSize {
|
|
fmtTag = Self.readLE16(fmt, at: Self.subFormatTagOffset)
|
|
}
|
|
foundFmt = true
|
|
// Chunks are word-aligned: skip a pad byte after an odd size.
|
|
if size % 2 == 1 { _ = try? Self.readExact(h, 1) }
|
|
} else if id.elementsEqual(Array("data".utf8)) {
|
|
// Trust the file, but not past its own end: streaming writers
|
|
// leave a placeholder size (often 0xFFFFFFFF) they never patch,
|
|
// and believing it yields a nonsense frame count and a
|
|
// `.truncated` throw partway through a render instead of a
|
|
// clean EOF.
|
|
let remaining: Int = max(0, fileByteCount - Int(try Self.fhOffset(h)))
|
|
dataLength = min(size, remaining)
|
|
foundData = true
|
|
break
|
|
} else {
|
|
// Unknown chunk (e.g. "fact", "LIST"): skip its padded body by
|
|
// seeking. Reading it would materialise the whole thing just to
|
|
// discard it, and a file with embedded artwork or a large
|
|
// "LIST" ahead of `data` makes that a real allocation.
|
|
let skip: Int = size + (size % 2)
|
|
let current: UInt64 = try Self.fhOffset(h)
|
|
let target: UInt64 = current + UInt64(max(0, skip))
|
|
guard target <= UInt64(fileByteCount) else { break }
|
|
try Self.fhSeek(h, to: target)
|
|
}
|
|
}
|
|
|
|
guard foundFmt, foundData else { throw WavFileError.truncated }
|
|
guard let enc: WavEncoding = Self.encoding(formatTag: fmtTag, bits: bits) else {
|
|
throw WavFileError.unsupportedFormat(formatTag: fmtTag, bitsPerSample: bits)
|
|
}
|
|
|
|
self.encoding = enc
|
|
self.channels = Int(numChannels)
|
|
self.sampleRate = Double(rate)
|
|
self.bytesPerFrame = Int(numChannels) * enc.bytesPerSample
|
|
let totalFrames: Int = bytesPerFrame > 0 ? dataLength / bytesPerFrame : 0
|
|
self.frameCount = totalFrames
|
|
self.framesRemaining = totalFrames
|
|
}
|
|
|
|
/// Reads up to `frames` frames, returning interleaved `Float` samples. The
|
|
/// returned array holds `framesRead * channels` values; `framesRead` may be
|
|
/// smaller than requested at end of file (and zero once exhausted).
|
|
public func read(frames: Int) throws(WavFileError) -> [Float] {
|
|
let toRead: Int = min(frames, framesRemaining)
|
|
guard toRead > 0 else { return [] }
|
|
let byteCount: Int = toRead * bytesPerFrame
|
|
let raw: Data = try Self.readExact(handle, byteCount)
|
|
framesRemaining -= toRead
|
|
|
|
let sampleCount: Int = toRead * channels
|
|
var out: [Float] = [Float](repeating: 0, count: sampleCount)
|
|
raw.withUnsafeBytes { (rawPtr: UnsafeRawBufferPointer) in
|
|
switch encoding {
|
|
case .float32:
|
|
for i: Int in 0..<sampleCount {
|
|
let bits: UInt32 = Self.loadLE32(rawPtr, byteOffset: i * 4)
|
|
out[i] = Float(bitPattern: bits)
|
|
}
|
|
case .int16:
|
|
let inv: Float = 1.0 / 32768.0
|
|
for i: Int in 0..<sampleCount {
|
|
let v: Int16 = Int16(bitPattern: Self.loadLE16(rawPtr, byteOffset: i * 2))
|
|
out[i] = Float(v) * inv
|
|
}
|
|
case .int24:
|
|
let inv: Float = 1.0 / 8388608.0
|
|
for i: Int in 0..<sampleCount {
|
|
let b0: Int32 = Int32(rawPtr[i * 3])
|
|
let b1: Int32 = Int32(rawPtr[i * 3 + 1])
|
|
let b2: Int32 = Int32(rawPtr[i * 3 + 2])
|
|
var v: Int32 = b0 | (b1 << 8) | (b2 << 16)
|
|
if (v & 0x0080_0000) != 0 { v |= ~0x00FF_FFFF } // sign-extend 24→32
|
|
out[i] = Float(v) * inv
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
/// Advances past `frames` frames without materialising them.
|
|
///
|
|
/// Seeks rather than reading: skipping into a long file — a start offset a
|
|
/// minute into a stereo 48 kHz recording is ~23 M samples — would otherwise
|
|
/// allocate the whole skipped region just to discard it. Skipping past the
|
|
/// end simply exhausts the reader.
|
|
///
|
|
/// - Parameter frames: Frames to advance by. Non-positive values do nothing.
|
|
public func skip(frames: Int) throws(WavFileError) {
|
|
let toSkip: Int = min(frames, framesRemaining)
|
|
guard toSkip > 0 else { return }
|
|
let current: UInt64 = try Self.fhOffset(handle)
|
|
try Self.fhSeek(handle, to: current + UInt64(toSkip * bytesPerFrame))
|
|
framesRemaining -= toSkip
|
|
}
|
|
|
|
/// Closes the underlying file handle.
|
|
public func close() {
|
|
try? handle.close()
|
|
}
|
|
|
|
// MARK: - Parsing helpers
|
|
|
|
/// Smallest legal `fmt ` chunk: the 16 bytes of a plain PCM header.
|
|
private static let minimumFmtChunkSize: Int = 16
|
|
/// `fmt ` size that carries the full `WAVEFORMATEXTENSIBLE` payload.
|
|
private static let extensibleFmtChunkSize: Int = 40
|
|
/// Byte offset of the SubFormat GUID's leading format tag within `fmt `.
|
|
private static let subFormatTagOffset: Int = 24
|
|
/// `WAVE_FORMAT_EXTENSIBLE` — the real tag hides in the SubFormat GUID.
|
|
private static let waveFormatExtensible: UInt16 = 0xFFFE
|
|
|
|
private static func encoding(formatTag: UInt16, bits: UInt16) -> WavEncoding? {
|
|
switch (formatTag, bits) {
|
|
case (3, 32): return .float32
|
|
case (1, 16): return .int16
|
|
case (1, 24): return .int24
|
|
default: return nil
|
|
}
|
|
}
|
|
|
|
/// Wraps `FileHandle.offset()`, funneling its foreign error into `WavFileError`.
|
|
private static func fhOffset(_ h: FileHandle) throws(WavFileError) -> UInt64 {
|
|
do { return try h.offset() }
|
|
catch { throw WavFileError.ioFailure(String(describing: error)) }
|
|
}
|
|
|
|
/// Wraps `FileHandle.seekToEnd()`, funneling its foreign error into `WavFileError`.
|
|
private static func fhSeekToEnd(_ h: FileHandle) throws(WavFileError) -> UInt64 {
|
|
do { return try h.seekToEnd() }
|
|
catch { throw WavFileError.ioFailure(String(describing: error)) }
|
|
}
|
|
|
|
/// Wraps `FileHandle.seek(toOffset:)`, funneling its foreign error into `WavFileError`.
|
|
private static func fhSeek(_ h: FileHandle, to offset: UInt64) throws(WavFileError) {
|
|
do { try h.seek(toOffset: offset) }
|
|
catch { throw WavFileError.ioFailure(String(describing: error)) }
|
|
}
|
|
|
|
private static func readExact(_ h: FileHandle, _ count: Int) throws(WavFileError) -> Data {
|
|
guard count > 0 else { return Data() }
|
|
let d: Data?
|
|
do { d = try h.read(upToCount: count) }
|
|
catch { throw WavFileError.ioFailure(String(describing: error)) }
|
|
guard let d, d.count == count else {
|
|
throw WavFileError.truncated
|
|
}
|
|
return d
|
|
}
|
|
|
|
private static func readLE16(_ d: Data, at offset: Int) -> UInt16 {
|
|
let base: Data.Index = d.startIndex + offset
|
|
return UInt16(d[base]) | (UInt16(d[base + 1]) << 8)
|
|
}
|
|
|
|
private static func readLE32(_ d: Data, at offset: Int) -> UInt32 {
|
|
let base: Data.Index = d.startIndex + offset
|
|
return UInt32(d[base]) | (UInt32(d[base + 1]) << 8)
|
|
| (UInt32(d[base + 2]) << 16) | (UInt32(d[base + 3]) << 24)
|
|
}
|
|
|
|
private static func loadLE16(_ p: UnsafeRawBufferPointer, byteOffset: Int) -> UInt16 {
|
|
UInt16(p[byteOffset]) | (UInt16(p[byteOffset + 1]) << 8)
|
|
}
|
|
|
|
private static func loadLE32(_ p: UnsafeRawBufferPointer, byteOffset: Int) -> UInt32 {
|
|
UInt32(p[byteOffset]) | (UInt32(p[byteOffset + 1]) << 8)
|
|
| (UInt32(p[byteOffset + 2]) << 16) | (UInt32(p[byteOffset + 3]) << 24)
|
|
}
|
|
}
|