Repository Public License
1//2// ORIX Audio3// File: Core/Sources/ORIXAudioCore/Capture/CAFWriter.swift4// Description: Append-only Core Audio Format writer for linear PCM. The file is valid after every write, so a crash loses nothing already flushed.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import Foundation1011public enum PCMSampleFormat: String, Codable, Sendable, CaseIterable {12 case int16, int24, float3213 public var bitsPerChannel: Int { switch self { case .int16: 16; case .int24: 24; case .float32: 32 } }14 public var bytesPerSample: Int { bitsPerChannel / 8 }15}1617public struct CaptureFormat: Codable, Sendable, Hashable {18 public var sampleRate: Double19 public var channels: Int20 public var sampleFormat: PCMSampleFormat21 public init(sampleRate: Double, channels: Int, sampleFormat: PCMSampleFormat) {22 self.sampleRate = sampleRate; self.channels = channels; self.sampleFormat = sampleFormat23 }24 public var bytesPerFrame: Int { channels * sampleFormat.bytesPerSample }25 public var bytesPerSecond: Double { sampleRate * Double(bytesPerFrame) }26}2728/// Writes a CAF file whose audio-data chunk declares size −1 ("extends to end of file", Apple CAF specification).29/// Nothing in the header ever needs patching: after any `write`, the bytes on disk are a complete, readable CAF file.30/// That property is what makes interrupted recordings recoverable.31public final class CAFWriter {32 public static let headerSize = 4 + 2 + 2 + (4 + 8 + 32) + (4 + 8 + 4) // caff header + desc chunk + data chunk header & edit count33 public let url: URL34 public let format: CaptureFormat35 private let handle: FileHandle36 public private(set) var framesWritten = 037 private var scratch = [UInt8]()3839 public var bytesWritten: Int { Self.headerSize + framesWritten * format.bytesPerFrame }4041 public init(url: URL, format: CaptureFormat, protection: FileProtectionType? = nil) throws {42 self.url = url; self.format = format43 var attributes: [FileAttributeKey: Any] = [:]44 if let protection { attributes[.protectionKey] = protection }45 guard FileManager.default.createFile(atPath: url.path, contents: Self.header(for: format), attributes: attributes) else {46 throw CocoaError(.fileWriteUnknown, userInfo: [NSFilePathErrorKey: url.path])47 }48 handle = try FileHandle(forWritingTo: url)49 try handle.seekToEnd()50 }5152 static func header(for f: CaptureFormat) -> Data {53 var d = Data()54 func be<T: FixedWidthInteger>(_ v: T) { withUnsafeBytes(of: v.bigEndian) { d.append(contentsOf: $0) } }55 d.append(contentsOf: Array("caff".utf8)); be(UInt16(1)); be(UInt16(0))56 d.append(contentsOf: Array("desc".utf8)); be(Int64(32))57 be(f.sampleRate.bitPattern)58 d.append(contentsOf: Array("lpcm".utf8))59 // kCAFLinearPCMFormatFlagIsFloat = 1, kCAFLinearPCMFormatFlagIsLittleEndian = 260 be(UInt32(f.sampleFormat == .float32 ? 3 : 2))61 be(UInt32(f.bytesPerFrame)); be(UInt32(1)); be(UInt32(f.channels)); be(UInt32(f.sampleFormat.bitsPerChannel))62 d.append(contentsOf: Array("data".utf8)); be(Int64(-1)); be(UInt32(0))63 return d64 }6566 /// Appends interleaved float samples (`frames × channels` values in −1…1), converting to the file's sample format.67 public func write(interleaved samples: UnsafePointer<Float>, frames: Int) throws {68 let count = frames * format.channels69 let bytes = count * format.sampleFormat.bytesPerSample70 if scratch.count < bytes { scratch = [UInt8](repeating: 0, count: bytes) }71 scratch.withUnsafeMutableBytes { raw in72 switch format.sampleFormat {73 case .float32:74 raw.baseAddress!.copyMemory(from: samples, byteCount: bytes)75 case .int16:76 let p = raw.bindMemory(to: Int16.self)77 for i in 0..<count { p[i] = Int16(max(-32768, min(32767, (samples[i] * 32768).rounded()))).littleEndian }78 case .int24:79 let p = raw.bindMemory(to: UInt8.self)80 for i in 0..<count {81 let v = Int32(max(-8_388_608, min(8_388_607, (Double(samples[i]) * 8_388_608).rounded())))82 p[i * 3] = UInt8(truncatingIfNeeded: v); p[i * 3 + 1] = UInt8(truncatingIfNeeded: v >> 8); p[i * 3 + 2] = UInt8(truncatingIfNeeded: v >> 16)83 }84 }85 }86 try scratch.withUnsafeBytes { try handle.write(contentsOf: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0.baseAddress!), count: bytes, deallocator: .none)) }87 framesWritten += frames88 }8990 /// Forces written audio to stable storage (a checkpoint).91 public func synchronize() throws { try handle.synchronize() }9293 public func close() throws {94 try handle.synchronize()95 try handle.close()96 }9798 /// Inspects a capture file left behind by an interrupted session: returns its format and the number of complete frames.99 /// A trailing partial frame (torn write) is ignored.100 public static func inspect(url: URL) -> (format: CaptureFormat, frames: Int)? {101 guard let h = try? FileHandle(forReadingFrom: url), let head = try? h.read(upToCount: headerSize), head.count == headerSize,102 let size = try? h.seekToEnd() else { return nil }103 try? h.close()104 guard String(decoding: head[0..<4], as: UTF8.self) == "caff", String(decoding: head[8..<12], as: UTF8.self) == "desc",105 String(decoding: head[28..<32], as: UTF8.self) == "lpcm", String(decoding: head[52..<56], as: UTF8.self) == "data" else { return nil }106 func be32(_ o: Int) -> UInt32 { head[o..<(o + 4)].reduce(0) { $0 << 8 | UInt32($1) } }107 let rateBits = head[20..<28].reduce(UInt64(0)) { $0 << 8 | UInt64($1) }108 let flags = be32(32), bytesPerPacket = Int(be32(36)), channels = Int(be32(44)), bits = Int(be32(48))109 let fmt: PCMSampleFormat? = flags & 1 == 1 ? (bits == 32 ? .float32 : nil) : (bits == 16 ? .int16 : bits == 24 ? .int24 : nil)110 guard let fmt, channels > 0, bytesPerPacket == channels * fmt.bytesPerSample else { return nil }111 let format = CaptureFormat(sampleRate: Double(bitPattern: rateBits), channels: channels, sampleFormat: fmt)112 return (format, max(0, Int(size) - headerSize) / format.bytesPerFrame)113 }114}115