Files
Lyrebird/Sources/Lyrebird/Buffers/RF64Writer.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

260 lines
11 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.
// 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(RF64WriterError) {
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(RF64WriterError) {
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(RF64WriterError) {
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() }
}
}