Repository Public License
1//2// ORIX Audio3// File: Core/Sources/ORIXAudioCore/Export/AudioFileIO.swift4// Description: Chunked audio file reading, metadata inspection and encoding to WAV / AIFF / CAF / Apple Lossless / AAC.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import AVFoundation10import Foundation1112public enum AudioIOError: Error, LocalizedError, Sendable {13 case unreadable(String), noAudioTrack, unsupported(String), cancelled, writeFailed(String)14 public var errorDescription: String? {15 switch self {16 case .unreadable(let m): "This file can't be read as audio (\(m))."17 case .noAudioTrack: "This file has no audio track."18 case .unsupported(let m): "Unsupported: \(m)."19 case .cancelled: "Cancelled."20 case .writeFailed(let m): "The file couldn't be written (\(m))."21 }22 }23}2425/// The encodings ORIX Audio can actually produce on iOS. MP3 is absent on purpose: iOS ships an MP3 decoder but no encoder.26public enum AudioExportFormat: String, CaseIterable, Codable, Sendable, Identifiable {27 case wav16, wav24, aiff16, caf24, alac, aac2829 public var id: String { rawValue }30 public var fileExtension: String {31 switch self { case .wav16, .wav24: "wav"; case .aiff16: "aiff"; case .caf24: "caf"; case .alac, .aac: "m4a" }32 }33 public var displayName: String {34 switch self {35 case .wav16: "WAV · PCM 16-bit"36 case .wav24: "WAV · PCM 24-bit"37 case .aiff16: "AIFF · PCM 16-bit"38 case .caf24: "CAF · PCM 24-bit"39 case .alac: "M4A · Apple Lossless"40 case .aac: "M4A · AAC"41 }42 }43 public var isLossless: Bool { self != .aac }44 public var codecName: String { switch self { case .alac: "Apple Lossless (ALAC)"; case .aac: "AAC-LC"; default: "Linear PCM" } }45 public var bitDepth: Int? { switch self { case .wav16, .aiff16: 16; case .wav24, .caf24, .alac: 24; case .aac: nil } }4647 func settings(sampleRate: Double, channels: Int, aacBitRate: Int) -> [String: Any] {48 var s: [String: Any] = [AVSampleRateKey: sampleRate, AVNumberOfChannelsKey: channels]49 switch self {50 case .wav16, .wav24, .caf24:51 s[AVFormatIDKey] = kAudioFormatLinearPCM; s[AVLinearPCMBitDepthKey] = bitDepth!52 s[AVLinearPCMIsFloatKey] = false; s[AVLinearPCMIsBigEndianKey] = false; s[AVLinearPCMIsNonInterleaved] = false53 case .aiff16:54 s[AVFormatIDKey] = kAudioFormatLinearPCM; s[AVLinearPCMBitDepthKey] = 1655 s[AVLinearPCMIsFloatKey] = false; s[AVLinearPCMIsBigEndianKey] = true; s[AVLinearPCMIsNonInterleaved] = false56 case .alac:57 s[AVFormatIDKey] = kAudioFormatAppleLossless; s[AVEncoderBitDepthHintKey] = 2458 case .aac:59 s[AVFormatIDKey] = kAudioFormatMPEG4AAC; s[AVEncoderBitRateKey] = aacBitRate60 s[AVEncoderAudioQualityKey] = AVAudioQuality.high.rawValue61 }62 return s63 }64}6566public struct AudioFileInfo: Codable, Sendable, Equatable {67 public var fileName: String68 public var fileSize: Int6469 public var duration: Double70 public var sampleRate: Double71 public var channels: Int72 public var codec: String73 public var containerExtension: String74 public var bitDepth: Int?75 /// Average bit rate in bits per second (file size / duration when the container doesn't state it).76 public var bitRate: Double?77 public var isLossless: Bool78 public var frameCount: Int6479}8081/// Sequential reader delivering deinterleaved Float32 chunks at the file's own sample rate.82public final class AudioFileReader {83 public let file: AVAudioFile84 public let url: URL85 public var sampleRate: Double { file.processingFormat.sampleRate }86 public var channels: Int { Int(file.processingFormat.channelCount) }87 public var frameCount: Int { Int(file.length) }88 public var duration: Double { Double(file.length) / sampleRate }89 private var buffer: AVAudioPCMBuffer?9091 public init(url: URL) throws {92 self.url = url93 do { file = try AVAudioFile(forReading: url, commonFormat: .pcmFormatFloat32, interleaved: false) }94 catch { throw AudioIOError.unreadable(error.localizedDescription) }95 guard file.processingFormat.channelCount > 0, file.processingFormat.sampleRate > 0 else { throw AudioIOError.noAudioTrack }96 }9798 public func seek(toFrame frame: Int) { file.framePosition = AVAudioFramePosition(max(0, min(frameCount, frame))) }99100 /// Reads up to `maxFrames` frames. Returns one array per channel; empty arrays at end of file.101 public func read(maxFrames: Int) throws -> [[Float]] {102 if buffer == nil || Int(buffer!.frameCapacity) < maxFrames { buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(maxFrames)) }103 guard let buffer else { throw AudioIOError.unreadable("buffer") }104 let remaining = frameCount - Int(file.framePosition)105 guard remaining > 0 else { return Array(repeating: [], count: channels) }106 do { try file.read(into: buffer, frameCount: AVAudioFrameCount(min(maxFrames, remaining))) }107 catch { throw AudioIOError.unreadable(error.localizedDescription) }108 let n = Int(buffer.frameLength)109 return (0..<channels).map { Array(UnsafeBufferPointer(start: buffer.floatChannelData![$0], count: n)) }110 }111112 /// Reads a frame range as a mono mix (mean of channels).113 public func readMono(frames range: Range<Int>) throws -> [Float] {114 seek(toFrame: range.lowerBound)115 let data = try read(maxFrames: max(0, min(range.upperBound, frameCount) - range.lowerBound))116 return Self.mono(data)117 }118119 public static func mono(_ channels: [[Float]]) -> [Float] {120 guard let first = channels.first else { return [] }121 guard channels.count > 1 else { return first }122 var out = first123 for c in channels.dropFirst() { for i in out.indices where i < c.count { out[i] += c[i] } }124 let g = 1 / Float(channels.count)125 for i in out.indices { out[i] *= g }126 return out127 }128129 public static func info(url: URL) throws -> AudioFileInfo {130 let reader = try AudioFileReader(url: url)131 let fmt = reader.file.fileFormat132 let asbd = fmt.streamDescription.pointee133 let size = (try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? NSNumber)?.int64Value ?? 0134 let codec: String135 var lossless = false136 switch asbd.mFormatID {137 case kAudioFormatLinearPCM: codec = asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0 ? "Linear PCM (float)" : "Linear PCM"; lossless = true138 case kAudioFormatAppleLossless: codec = "Apple Lossless (ALAC)"; lossless = true139 case kAudioFormatMPEG4AAC: codec = "AAC-LC"140 case kAudioFormatMPEG4AAC_HE: codec = "HE-AAC"141 case kAudioFormatMPEGLayer3: codec = "MP3"142 case kAudioFormatFLAC: codec = "FLAC"; lossless = true143 case kAudioFormatOpus: codec = "Opus"144 case kAudioFormatULaw: codec = "µ-law"145 case kAudioFormatALaw: codec = "A-law"146 default:147 let id = asbd.mFormatID148 codec = String(bytes: [UInt8(id >> 24 & 255), UInt8(id >> 16 & 255), UInt8(id >> 8 & 255), UInt8(id & 255)], encoding: .ascii)?.trimmingCharacters(in: .whitespaces) ?? "Unknown"149 }150 var depth: Int? = asbd.mBitsPerChannel > 0 ? Int(asbd.mBitsPerChannel) : nil151 if asbd.mFormatID == kAudioFormatAppleLossless {152 // ALAC stores the source bit depth in the format flags (1 = 16, 2 = 20, 3 = 24, 4 = 32).153 depth = [1: 16, 2: 20, 3: 24, 4: 32][Int(asbd.mFormatFlags)]154 }155 let duration = reader.duration156 return AudioFileInfo(fileName: url.lastPathComponent, fileSize: size, duration: duration, sampleRate: fmt.sampleRate, channels: Int(fmt.channelCount),157 codec: codec, containerExtension: url.pathExtension.lowercased(), bitDepth: depth,158 bitRate: duration > 0 ? Double(size) * 8 / duration : nil, isLossless: lossless, frameCount: Int64(reader.frameCount))159 }160}161162/// Incremental encoder: push deinterleaved float chunks, get a finished file. Resamples when the target rate differs.163public final class AudioFileWriter {164 public let url: URL165 private var file: AVAudioFile?166 private let inputFormat: AVAudioFormat167 private let outputFormat: AVAudioFormat168 private let converter: AVAudioConverter?169 public private(set) var framesWritten = 0170171 public init(url: URL, format: AudioExportFormat, inputSampleRate: Double, channels: Int, outputSampleRate: Double? = nil, aacBitRate: Int = 128_000) throws {172 self.url = url173 // Apple's AAC-LC encoder tops out at 48 kHz: higher-rate sources are resampled rather than rejected.174 let outRate = format == .aac ? min(48_000, outputSampleRate ?? inputSampleRate) : (outputSampleRate ?? inputSampleRate)175 try? FileManager.default.removeItem(at: url)176 guard let inFmt = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: inputSampleRate, channels: AVAudioChannelCount(channels), interleaved: false),177 let outFmt = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: outRate, channels: AVAudioChannelCount(channels), interleaved: false) else {178 throw AudioIOError.unsupported("\(channels) channels at \(inputSampleRate) Hz")179 }180 inputFormat = inFmt; outputFormat = outFmt181 converter = outRate == inputSampleRate ? nil : AVAudioConverter(from: inFmt, to: outFmt)182 do {183 let bitRate = format == .aac ? Self.supportedAACBitRate(nearest: aacBitRate, sampleRate: outRate, channels: channels) : aacBitRate184 file = try AVAudioFile(forWriting: url, settings: format.settings(sampleRate: outRate, channels: channels, aacBitRate: bitRate),185 commonFormat: .pcmFormatFloat32, interleaved: false)186 } catch { throw AudioIOError.writeFailed(error.localizedDescription) }187 }188189 /// The AAC encoder only accepts certain bit rates for a given sample rate and channel count (for example, 96 kbps is190 /// not valid for 22.05 kHz mono). Returns the supported rate closest to the request.191 public static func supportedAACBitRate(nearest requested: Int, sampleRate: Double, channels: Int) -> Int {192 var description = AudioStreamBasicDescription(mSampleRate: sampleRate, mFormatID: kAudioFormatMPEG4AAC, mFormatFlags: 0, mBytesPerPacket: 0,193 mFramesPerPacket: 1024, mBytesPerFrame: 0, mChannelsPerFrame: UInt32(channels), mBitsPerChannel: 0, mReserved: 0)194 guard let pcm = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: sampleRate, channels: AVAudioChannelCount(channels), interleaved: false),195 let aac = AVAudioFormat(streamDescription: &description), let converter = AVAudioConverter(from: pcm, to: aac),196 let rates = converter.applicableEncodeBitRates?.map(\.intValue), !rates.isEmpty else {197 // Conservative fallback: at most 1.5 bits per sample per channel… scaled from the sample rate.198 return min(requested, Int(sampleRate) * channels * 2)199 }200 return rates.min { abs($0 - requested) < abs($1 - requested) } ?? requested201 }202203 public func write(_ channels: [[Float]]) throws {204 guard let file, let n = channels.first?.count, n > 0 else { return }205 guard let buffer = AVAudioPCMBuffer(pcmFormat: inputFormat, frameCapacity: AVAudioFrameCount(n)) else { throw AudioIOError.writeFailed("buffer") }206 buffer.frameLength = AVAudioFrameCount(n)207 for (c, data) in channels.enumerated() where c < Int(inputFormat.channelCount) {208 data.withUnsafeBufferPointer { buffer.floatChannelData![c].update(from: $0.baseAddress!, count: n) }209 }210 do {211 if let converter { try convert(buffer, converter: converter, file: file, end: false) } else { try file.write(from: buffer) }212 } catch let e as AudioIOError { throw e } catch { throw AudioIOError.writeFailed(error.localizedDescription) }213 framesWritten += n214 }215216 private func convert(_ input: AVAudioPCMBuffer?, converter: AVAudioConverter, file: AVAudioFile, end: Bool) throws {217 let capacity = AVAudioFrameCount(Double(input?.frameLength ?? 4096) * outputFormat.sampleRate / inputFormat.sampleRate) + 1024218 nonisolated(unsafe) var supplied = false219 nonisolated(unsafe) let source = input220 while true {221 guard let out = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: capacity) else { throw AudioIOError.writeFailed("buffer") }222 var error: NSError?223 let status = converter.convert(to: out, error: &error) { _, outStatus in224 if supplied || source == nil { outStatus.pointee = end ? .endOfStream : .noDataNow; return nil }225 supplied = true; outStatus.pointee = .haveData; return source226 }227 if let error { throw AudioIOError.writeFailed(error.localizedDescription) }228 if out.frameLength > 0 { try file.write(from: out) }229 if status != .haveData || out.frameLength == 0 { break }230 }231 }232233 /// Flushes the resampler and closes the file. The file is only complete after this returns.234 public func finish() throws {235 if let converter, let file { try convert(nil, converter: converter, file: file, end: true) }236 file?.close()237 file = nil238 }239}240241extension AVAudioFile {242 /// `close()` exists from iOS 18 / macOS 15; this keeps call sites tidy.243 func closeIfPossible() { close() }244}245