Files
Lyrebird/Sources/Lyrebird/Spectral/SpectralFrameBufferFileIO.swift
T
2026-06-01 18:27:40 -07:00

206 lines
8.5 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.
// SpectralFrameBufferFileIO.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
// MARK: - Error type
/// Errors thrown by `SpectralFrameBuffer` file I/O.
public enum SpectralFileError: Error, Equatable {
case cannotCreateFile
case cannotOpenFile
case invalidMagic
case invalidHeader
case unsupportedVersion(UInt32)
}
// MARK: - .lbsf format constants
/// Byte length of the `.lbsf` file header.
private let lbsfHeaderSize: Int = 40
/// Supported `.lbsf` format version.
private let lbsfVersion: UInt32 = 1
/// ASCII magic bytes "LBSF".
private let lbsfMagic: [UInt8] = [0x4C, 0x42, 0x53, 0x46]
// Header field byte offsets (all little-endian).
private let lbsfOffsetVersion: Int = 4
private let lbsfOffsetFftSize: Int = 8
private let lbsfOffsetHopSize: Int = 12
private let lbsfOffsetFrameCount: Int = 16
private let lbsfOffsetSampleRate: Int = 20
// MARK: - File I/O extension
/// Binary `.lbsf` file format for `SpectralFrameBuffer`.
///
/// ## Format
///
/// ```
/// Header (40 bytes, little-endian):
/// [0..3] "LBSF" ASCII magic
/// [4..7] version: UInt32 = 1
/// [8..11] fftSize: UInt32
/// [12..15] hopSize: UInt32
/// [16..19] frameCount: UInt32
/// [20..27] sampleRate: Float64 (0 = unknown)
/// [28..39] reserved, zeroed
///
/// Body — per frame (Float32, little-endian):
/// DC: Float32 × 1
/// Nyquist: Float32 × 1
/// Mags: Float32 × (halfSize − 1)
/// Phases: Float32 × (halfSize − 1)
/// ```
///
/// Total = 40 + frameCount × fftSize × 4 bytes.
/// (1 + 1 + (halfSize−1) + (halfSize−1) = fftSize floats per frame.)
///
/// Files written on macOS are little-endian. Since macOS runs on little-endian hardware,
/// no byte-swapping is needed for native reads and writes.
extension SpectralFrameBuffer {
// MARK: - Write
/// Write this buffer to `url` in `.lbsf` format.
///
/// Only the frames that contain valid recorded data are written: the header stores
/// `framesWritten` (not `frameCount`), and the body contains exactly that many frames.
/// This ensures that a partially-filled buffer (e.g. a large pre-allocation used with
/// `SpectralRecordBuffer`) produces a compact file without trailing garbage frames.
public func write(to url: URL) throws {
let path: String = url.path
guard FileManager.default.createFile(atPath: path, contents: nil, attributes: nil) else {
throw SpectralFileError.cannotCreateFile
}
guard let fh: FileHandle = FileHandle(forWritingAtPath: path) else {
throw SpectralFileError.cannotCreateFile
}
// Close on error bail-out; the success path closes explicitly below so
// flush failures surface to the caller rather than being swallowed.
var didClose: Bool = false
defer { if !didClose { try? fh.close() } }
let writtenCount: Int = min(framesWritten, frameCount)
try fh.write(contentsOf: _makeHeader(frameCount: writtenCount))
// Write body: one frame at a time to bound peak memory usage.
let frameFloats: Int = fftSize // 1 + 1 + (halfSize-1) + (halfSize-1) = fftSize
var frameBuf: [Float] = [Float](repeating: 0, count: frameFloats)
for f: Int in 0..<writtenCount {
let base: Int = f * halfSize
frameBuf[0] = _dc[f]
frameBuf[1] = _nyquist[f]
frameBuf.withUnsafeMutableBufferPointer { ptr in
guard let bptr: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
memcpy(bptr + 2, _mag + base + 1, _binCount * MemoryLayout<Float>.stride)
memcpy(bptr + 2 + _binCount, _phase + base + 1, _binCount * MemoryLayout<Float>.stride)
}
let frameData: Data = frameBuf.withUnsafeBufferPointer { Data(buffer: $0) }
try fh.write(contentsOf: frameData)
}
try fh.close()
didClose = true
}
// MARK: - Load
/// Load a `.lbsf` file from `url` and return a new `SpectralFrameBuffer`.
///
/// - Throws: `SpectralFileError` on invalid magic, unsupported version, or I/O failure.
public static func load(url: URL) throws -> SpectralFrameBuffer {
guard let fh: FileHandle = try? FileHandle(forReadingFrom: url) else {
throw SpectralFileError.cannotOpenFile
}
defer { try? fh.close() }
// Read and validate header.
let headerData: Data = fh.readData(ofLength: lbsfHeaderSize)
guard headerData.count == lbsfHeaderSize else {
throw SpectralFileError.invalidMagic
}
guard headerData[0] == lbsfMagic[0], headerData[1] == lbsfMagic[1],
headerData[2] == lbsfMagic[2], headerData[3] == lbsfMagic[3] else {
throw SpectralFileError.invalidMagic
}
// Use loadUnaligned — Data bytes may not be aligned to UInt32/Float64 boundaries.
let version: UInt32 = headerData.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: lbsfOffsetVersion, as: UInt32.self) }
guard version == lbsfVersion else {
throw SpectralFileError.unsupportedVersion(version)
}
let fileFftSize: Int = Int(headerData.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: lbsfOffsetFftSize, as: UInt32.self) })
let fileHopSize: Int = Int(headerData.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: lbsfOffsetHopSize, as: UInt32.self) })
let fileFrameCount: Int = Int(headerData.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: lbsfOffsetFrameCount, as: UInt32.self) })
let fileSampleRate: Float64 = headerData.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: lbsfOffsetSampleRate, as: Float64.self) }
guard fileFftSize >= 4 && (fileFftSize & (fileFftSize - 1)) == 0
&& fileHopSize > 0 && fileFrameCount > 0 else {
throw SpectralFileError.invalidHeader
}
let buf: SpectralFrameBuffer = SpectralFrameBuffer(
fftSize: fileFftSize,
hopSize: fileHopSize,
frameCount: fileFrameCount,
sampleRate: fileSampleRate
)
// Read body frame by frame. Copy into a local Float array to avoid alignment issues.
let frameFloats: Int = fileFftSize
let frameBytes: Int = frameFloats * MemoryLayout<Float>.stride
let binCount: Int = buf._binCount
var frameBuf: [Float] = [Float](repeating: 0, count: frameFloats)
var framesRead: Int = 0
for f: Int in 0..<fileFrameCount {
let data: Data = fh.readData(ofLength: frameBytes)
guard data.count == frameBytes else { break }
frameBuf.withUnsafeMutableBytes { dst in
guard let dstPtr: UnsafeMutableRawPointer = dst.baseAddress else { return }
data.withUnsafeBytes { src in
guard let srcPtr: UnsafeRawPointer = src.baseAddress else { return }
_ = memcpy(dstPtr, srcPtr, frameBytes)
}
}
buf._dc[f] = frameBuf[0]
buf._nyquist[f] = frameBuf[1]
let frameBase: Int = f * buf.halfSize
frameBuf.withUnsafeBufferPointer { ptr in
guard let bptr: UnsafePointer<Float> = ptr.baseAddress else { return }
_ = memcpy(buf._mag + frameBase + 1, bptr + 2, binCount * MemoryLayout<Float>.stride)
_ = memcpy(buf._phase + frameBase + 1, bptr + 2 + binCount, binCount * MemoryLayout<Float>.stride)
}
framesRead += 1
}
// Reflect actual frames read so callers see the true valid range on truncated files.
buf._framesWritten.store(framesRead, ordering: .releasing)
return buf
}
// MARK: - Private helpers
private func _makeHeader(frameCount overrideFrameCount: Int) -> Data {
var d: Data = Data(capacity: lbsfHeaderSize)
d.append(contentsOf: lbsfMagic)
// UInt32 fields
func appendU32(_ v: UInt32) { withUnsafeBytes(of: v) { d.append(contentsOf: $0) } }
func appendF64(_ v: Float64) { withUnsafeBytes(of: v) { d.append(contentsOf: $0) } }
appendU32(lbsfVersion)
appendU32(UInt32(fftSize))
appendU32(UInt32(hopSize))
appendU32(UInt32(overrideFrameCount))
appendF64(sampleRate)
// Reserved (12 bytes zeroed)
let reservedByteCount: Int = lbsfHeaderSize - d.count
d.append(contentsOf: [UInt8](repeating: 0, count: reservedByteCount))
return d
}
}