Files
Lyrebird/Sources/Lyrebird/Buffers/WavFileWriter.swift
T
josh 844dc4d9cd v2.1.0 release: Swift 6.4 modernization
Typed throws across the closed-error-set APIs (OSC, MIDI, engine add/schedule,
bus/config/parameter, and the WAV/RF64/Spectral file codecs — source-compatible
narrowing, new .ioFailure cases), plus internal hardening: NSLock-guarded
scheduling/MIDI state moved to Mutex<State>, and the Spectral/FFT scratch owners
moved to a ~Copyable RTScratchBuffer RAII buffer. No API or behavioral change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 19:54:59 -07:00

279 lines
12 KiB
Swift

// WavFileWriter.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Streaming writer for canonical RIFF/WAVE PCM files, portable to every
/// platform (no `AudioToolbox` dependency).
///
/// Designed for the offline-render block model: construct once, call
/// ``write(interleaved:frames:)`` per rendered block, then ``finalize()`` to
/// patch the RIFF/`data` chunk sizes. Samples are supplied interleaved
/// (`frame0ch0, frame0ch1, frame1ch0, …`) as `Float` in `[-1, 1]`; integer
/// encodings clamp and round, float32 stores losslessly.
public final class WavFileWriter {
private let channels: Int
private let encoding: WavEncoding
private let handle: FileHandle
private var dataBytesWritten: Int = 0
private var finalized: Bool = false
/// Whether the RIFF word-align pad byte has already been appended.
private var padByteWritten: Bool = false
/// Byte count of this file's header, which depends on the encoding — see
/// ``headerSize(for:)``.
private let headerByteCount: Int
/// Offset of the `data` chunk's size field, patched by ``finalize()``.
private let dataChunkSizeOffset: UInt64
// Integer PCM uses the canonical 44-byte header: 12 RIFF/WAVE + 24 `fmt `
// (8 header + 16 body) + 8 `data` header.
private static let pcmHeaderSize: Int = 44
/// Non-PCM tags (float32) must declare `cbSize`, making the `fmt ` body 18
/// bytes, and must carry a `fact` chunk. That is 2 more `fmt ` bytes plus a
/// 12-byte `fact` chunk: 44 + 2 + 12.
private static let nonPCMHeaderSize: Int = 58
private static let riffChunkSizeOffset: UInt64 = 4
/// `fact`'s sample-count field, present only in the non-PCM layout.
private static let factSampleCountOffset: UInt64 = 46
private static let pcmDataChunkSizeOffset: UInt64 = 40
private static let nonPCMDataChunkSizeOffset: UInt64 = 54
/// `fmt ` body size for plain PCM tags, and for tags that need `cbSize`.
private static let pcmFmtBodySize: UInt32 = 16
private static let extendedFmtBodySize: UInt32 = 18
/// `fact` chunk body: one `UInt32` sample count.
private static let factBodySize: UInt32 = 4
/// Header length for `encoding`. Non-PCM formats carry more (see above).
private static func headerSize(for encoding: WavEncoding) -> Int {
encoding.isPCM ? pcmHeaderSize : nonPCMHeaderSize
}
/// - Parameters:
/// - url: Destination file path. Overwritten if it exists.
/// - channels: Interleaved channel count. Must be ≥ 1.
/// - sampleRate: Sample rate in Hz.
/// - encoding: PCM encoding. Defaults to ``WavEncoding/float32``.
public init(
url: URL,
channels: Int,
sampleRate: Double,
encoding: WavEncoding = .float32
) throws(WavFileError) {
precondition(channels >= 1, "WavFileWriter requires at least one channel")
self.channels = channels
self.encoding = encoding
self.headerByteCount = Self.headerSize(for: encoding)
self.dataChunkSizeOffset = encoding.isPCM
? Self.pcmDataChunkSizeOffset
: Self.nonPCMDataChunkSizeOffset
let header: Data = Self.makeHeader(
channels: channels,
sampleRate: sampleRate,
encoding: encoding
)
let fm: FileManager = FileManager.default
guard fm.createFile(atPath: url.path, contents: header) else {
throw WavFileError.cannotCreate(url)
}
let h: FileHandle
do { h = try FileHandle(forWritingTo: url) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
self.handle = h
try Self.fhSeekToEnd(h)
}
/// Appends one block of interleaved `Float` samples.
///
/// - Parameters:
/// - samples: Interleaved buffer, length ≥ `frames * channels`.
/// - frames: Number of frames (per-channel sample groups) to write.
public func write(interleaved samples: [Float], frames: Int) throws(WavFileError) {
let needed: Int = frames * channels
precondition(samples.count >= needed, "interleaved buffer shorter than frames * channels")
var out: Data = Data(capacity: needed * encoding.bytesPerSample)
switch encoding {
case .float32:
for i: Int in 0..<needed {
var le: UInt32 = samples[i].bitPattern.littleEndian
withUnsafeBytes(of: &le) { out.append(contentsOf: $0) }
}
case .int16:
// Full-scale maps to 32767 / 8388607, not 32768 / 8388608, so an
// input of exactly +1.0 cannot overflow the signed range. The
// reader divides by the power of two, which is the usual pairing;
// the resulting round-trip difference is ~0.003 %, well below the
// quantisation step.
let scale: Float = 32767.0
for i: Int in 0..<needed {
let clamped: Float = min(1.0, max(-1.0, samples[i]))
var le: Int16 = Int16((clamped * scale).rounded()).littleEndian
withUnsafeBytes(of: &le) { out.append(contentsOf: $0) }
}
case .int24:
let scale: Float = 8388607.0
for i: Int in 0..<needed {
let clamped: Float = min(1.0, max(-1.0, samples[i]))
let v: Int32 = Int32((clamped * scale).rounded())
out.append(UInt8(truncatingIfNeeded: v))
out.append(UInt8(truncatingIfNeeded: v >> 8))
out.append(UInt8(truncatingIfNeeded: v >> 16))
}
}
try Self.fhWrite(handle, out)
dataBytesWritten += out.count
}
deinit {
// Last-resort finalize: a writer dropped without one leaves an open
// descriptor and a header whose sizes are still zero, i.e. a file no
// reader can use. Errors here have nowhere to go, hence `try?`.
try? finalize()
}
/// Patches the RIFF and `data` chunk sizes and closes the file. Idempotent.
public func finalize() throws(WavFileError) {
guard !finalized else { return }
// Chunks are word-aligned: an odd `data` payload (possible with int24)
// needs a pad byte, which counts toward the RIFF size but not the
// `data` size. Recorded before the patch sequence below, so a
// `finalize()` that throws partway and is retried — by an explicit
// second call, or by `deinit` — does not append a second pad byte while
// sizing the file for one.
let padByteCount: Int = dataBytesWritten % 2
if padByteCount > 0 && !padByteWritten {
try Self.fhSeekToEnd(handle)
try Self.fhWrite(handle, [UInt8(0)])
padByteWritten = true
}
let riffChunkSize: UInt32 = try Self.riffChunkSize(
headerBytes: headerByteCount,
dataBytes: dataBytesWritten + padByteCount
)
let dataChunkSize: UInt32 = UInt32(dataBytesWritten)
try Self.fhSeek(handle, to: Self.riffChunkSizeOffset)
try Self.fhWrite(handle, Self.leBytes(riffChunkSize))
if !encoding.isPCM {
// `fact` carries the per-channel sample count, which is only known
// now that writing has finished.
let bytesPerFrame: Int = channels * encoding.bytesPerSample
let frames: UInt32 = bytesPerFrame > 0
? UInt32(dataBytesWritten / bytesPerFrame)
: 0
try Self.fhSeek(handle, to: Self.factSampleCountOffset)
try Self.fhWrite(handle, Self.leBytes(frames))
}
try Self.fhSeek(handle, to: dataChunkSizeOffset)
try Self.fhWrite(handle, Self.leBytes(dataChunkSize))
try Self.fhClose(handle)
// Set last: a throw above must leave the writer retryable rather than
// latching "finalized" over a file whose sizes are still zero.
finalized = true
}
/// RIFF chunk size for a file with this header and payload.
///
/// Split out so the 4 GB boundary can be tested without writing 4 GB: the
/// conversion below would *trap* rather than throw, and a trap in a render
/// that has been running for an hour is the worst possible outcome.
///
/// - Throws: ``WavFileError/fileTooLarge(bytes:)`` past `UInt32.max`.
@_spi(LyrebirdExtensions)
public static func riffChunkSize(headerBytes: Int, dataBytes: Int) throws(WavFileError) -> UInt32 {
let payload: Int = headerBytes - 8 + dataBytes
guard payload <= Int(UInt32.max) else {
throw WavFileError.fileTooLarge(bytes: payload)
}
return UInt32(payload)
}
// MARK: - FileHandle wrappers (funnel foreign errors into WavFileError)
/// Wraps `FileHandle.seekToEnd()`, funneling its foreign error into `WavFileError`.
private static func fhSeekToEnd(_ h: FileHandle) throws(WavFileError) {
do { 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)) }
}
/// Wraps `FileHandle.write(contentsOf:)`, funneling its foreign error into `WavFileError`.
private static func fhWrite(_ h: FileHandle, _ bytes: [UInt8]) throws(WavFileError) {
do { try h.write(contentsOf: bytes) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
/// Wraps `FileHandle.write(contentsOf:)` for a `Data` payload.
private static func fhWrite(_ h: FileHandle, _ bytes: Data) throws(WavFileError) {
do { try h.write(contentsOf: bytes) }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
/// Wraps `FileHandle.close()`, funneling its foreign error into `WavFileError`.
private static func fhClose(_ h: FileHandle) throws(WavFileError) {
do { try h.close() }
catch { throw WavFileError.ioFailure(String(describing: error)) }
}
// MARK: - Header
private static func makeHeader(
channels: Int,
sampleRate: Double,
encoding: WavEncoding
) -> Data {
let numChannels: UInt16 = UInt16(channels)
let rate: UInt32 = UInt32(sampleRate.rounded())
let blockAlign: UInt16 = UInt16(channels * encoding.bytesPerSample)
let byteRate: UInt32 = rate * UInt32(blockAlign)
// RIFF requires a non-PCM tag to declare `cbSize` (so the `fmt ` body
// is 18 bytes, not 16) and to carry a `fact` chunk. Strict readers
// reject a float32 file that omits either.
let isPCM: Bool = encoding.isPCM
let subchunk1Size: UInt32 = isPCM ? pcmFmtBodySize : extendedFmtBodySize
var d: Data = Data(capacity: headerSize(for: encoding))
d.append(contentsOf: Array("RIFF".utf8))
d.append(contentsOf: leBytes(UInt32(0))) // patched in finalize
d.append(contentsOf: Array("WAVE".utf8))
d.append(contentsOf: Array("fmt ".utf8))
d.append(contentsOf: leBytes(subchunk1Size))
d.append(contentsOf: leBytes(encoding.formatTag))
d.append(contentsOf: leBytes(numChannels))
d.append(contentsOf: leBytes(rate))
d.append(contentsOf: leBytes(byteRate))
d.append(contentsOf: leBytes(blockAlign))
d.append(contentsOf: leBytes(encoding.bitsPerSample))
if !isPCM {
d.append(contentsOf: leBytes(UInt16(0))) // cbSize: no extension
d.append(contentsOf: Array("fact".utf8))
d.append(contentsOf: leBytes(factBodySize))
d.append(contentsOf: leBytes(UInt32(0))) // patched in finalize
}
d.append(contentsOf: Array("data".utf8))
d.append(contentsOf: leBytes(UInt32(0))) // patched in finalize
return d
}
// Extract bytes low-first from the native value. The right shifts already
// yield little-endian order on any host, so no `.littleEndian` pre-swap
// (which, combined with these shifts, would double-transform on a big-endian host).
private static func leBytes(_ value: UInt32) -> [UInt8] {
return [UInt8(truncatingIfNeeded: value), UInt8(truncatingIfNeeded: value >> 8),
UInt8(truncatingIfNeeded: value >> 16), UInt8(truncatingIfNeeded: value >> 24)]
}
private static func leBytes(_ value: UInt16) -> [UInt8] {
return [UInt8(truncatingIfNeeded: value), UInt8(truncatingIfNeeded: value >> 8)]
}
}