SPB Git

Repository Public

AudioDecoder.swift 8.4 KB 166 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Audio/AudioDecoder.swift3// Description: Decodes one audio file to float PCM through Core Audio, reading its bytes from a ByteSource.4import Foundation5import AVFoundation6import AudioToolbox78public struct DecoderInfo: Sendable, Equatable {9    public var sampleRate: Double10    public var channels: Int11    /// Bit depth of the source when the format states one (PCM, FLAC, ALAC); nil for lossy codecs.12    public var bitDepth: Int?13    public var lengthFrames: Int6414    public var formatID: String15    public var duration: Double { sampleRate > 0 ? Double(lengthFrames) / sampleRate : 0 }16}1718public enum DecoderError: Error, Sendable, Equatable {19    case cannotOpen(OSStatus)20    case unsupportedFormat21    case readFailed(OSStatus)22    case seekFailed(OSStatus)23}2425private final class SourceBox { let source: ByteSource; var lastError: Error?; init(_ s: ByteSource) { source = s } }2627private let readCallback: AudioFile_ReadProc = { clientData, position, requestCount, buffer, actualCount in28    let box = Unmanaged<SourceBox>.fromOpaque(clientData).takeUnretainedValue()29    do {30        let n = try box.source.read(at: position, into: buffer, count: Int(requestCount))31        actualCount.pointee = UInt32(n)32        return n == 0 && requestCount > 0 ? kAudioFileEndOfFileError : noErr33    } catch {34        box.lastError = error35        actualCount.pointee = 036        return kAudioFileUnspecifiedError37    }38}39private let sizeCallback: AudioFile_GetSizeProc = { clientData in40    Unmanaged<SourceBox>.fromOpaque(clientData).takeUnretainedValue().source.length41}4243/// Decodes one audio file to 32-bit float PCM at the file's own sample rate, reading its bytes from a `ByteSource`44/// (so the same code plays a local file and a file still arriving from the cluster). Core Audio does the decoding:45/// FLAC, ALAC, AAC, MP3, WAV, AIFF. Not thread-safe: one decoding queue owns each decoder.46public final class AudioDecoder: @unchecked Sendable {47    public let info: DecoderInfo48    public let processingFormat: AVAudioFormat49    /// True when this decoder reads a slice of a file (see FLACSliceSource) rather than the whole file.50    public let isSlice: Bool51    private var fileID: AudioFileID?52    private var ext: ExtAudioFileRef?53    private let box: SourceBox54    private let boxPointer: UnsafeMutableRawPointer5556    public static func typeHint(mime: String?, container: String?, codec: String?) -> AudioFileTypeID {57        let m = (mime ?? "").lowercased(), c = (container ?? "").lowercased(), k = (codec ?? "").lowercased()58        if m == "audio/flac" || k == "flac" || c == "flac" { return kAudioFileFLACType }59        if m == "audio/mpeg" || k == "mp3" { return kAudioFileMP3Type }60        if m == "audio/wav" || c == "wav" { return kAudioFileWAVEType }61        if m == "audio/aiff" || c == "aiff" { return kAudioFileAIFFType }62        if m == "audio/aac" || c == "aac" { return kAudioFileAAC_ADTSType }63        if m == "audio/mp4" || c == "mov" || c == "mp4" || c == "m4a" || k == "alac" { return kAudioFileM4AType }64        return 065    }66    public static func typeHint(pathExtension ext: String) -> AudioFileTypeID {67        switch ext.lowercased() {68        case "flac": return kAudioFileFLACType69        case "mp3": return kAudioFileMP3Type70        case "wav", "wave": return kAudioFileWAVEType71        case "aif", "aiff": return kAudioFileAIFFType72        case "aifc": return kAudioFileAIFCType73        case "m4a", "mp4", "m4b": return kAudioFileM4AType74        case "aac": return kAudioFileAAC_ADTSType75        case "caf": return kAudioFileCAFType76        default: return 077        }78    }7980    public init(source: ByteSource, typeHint: AudioFileTypeID = 0) throws {81        box = SourceBox(source)82        isSlice = source is FLACSliceSource83        boxPointer = Unmanaged.passRetained(box).toOpaque()84        var fid: AudioFileID?85        var status = AudioFileOpenWithCallbacks(boxPointer, readCallback, nil, sizeCallback, nil, typeHint, &fid)86        if status != noErr, typeHint != 0 { status = AudioFileOpenWithCallbacks(boxPointer, readCallback, nil, sizeCallback, nil, 0, &fid) }87        guard status == noErr, let fid else {88            let underlying = box.lastError89            Unmanaged<SourceBox>.fromOpaque(boxPointer).release()90            if let underlying { throw underlying }91            throw DecoderError.cannotOpen(status)92        }93        var ref: ExtAudioFileRef?94        status = ExtAudioFileWrapAudioFileID(fid, false, &ref)95        guard status == noErr, let ref else { AudioFileClose(fid); Unmanaged<SourceBox>.fromOpaque(boxPointer).release(); throw DecoderError.cannotOpen(status) }9697        var asbd = AudioStreamBasicDescription()98        var size = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)99        ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd)100        var frames: Int64 = 0101        size = UInt32(MemoryLayout<Int64>.size)102        ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileLengthFrames, &size, &frames)103        guard asbd.mSampleRate > 0, asbd.mChannelsPerFrame > 0, let format = AVAudioFormat(standardFormatWithSampleRate: asbd.mSampleRate, channels: asbd.mChannelsPerFrame) else {104            ExtAudioFileDispose(ref); AudioFileClose(fid); Unmanaged<SourceBox>.fromOpaque(boxPointer).release()105            throw DecoderError.unsupportedFormat106        }107        status = ExtAudioFileSetProperty(ref, kExtAudioFileProperty_ClientDataFormat, UInt32(MemoryLayout<AudioStreamBasicDescription>.size), format.streamDescription)108        guard status == noErr else {109            ExtAudioFileDispose(ref); AudioFileClose(fid); Unmanaged<SourceBox>.fromOpaque(boxPointer).release()110            throw DecoderError.unsupportedFormat111        }112        var depth: Int?113        switch asbd.mFormatID {114        case kAudioFormatLinearPCM: depth = Int(asbd.mBitsPerChannel)115        case kAudioFormatFLAC, kAudioFormatAppleLossless:116            // For lossless codecs Core Audio reports the source bit depth in the format flags.117            depth = [1: 16, 2: 20, 3: 24, 4: 32][asbd.mFormatFlags]118        default: depth = nil119        }120        let id = asbd.mFormatID121        let fourCC = String(bytes: [UInt8(id >> 24 & 0xff), UInt8(id >> 16 & 0xff), UInt8(id >> 8 & 0xff), UInt8(id & 0xff)], encoding: .ascii)?.trimmingCharacters(in: .whitespaces) ?? "?"122        info = DecoderInfo(sampleRate: asbd.mSampleRate, channels: Int(asbd.mChannelsPerFrame), bitDepth: depth, lengthFrames: frames, formatID: fourCC)123        processingFormat = format124        fileID = fid; ext = ref125    }126127    deinit { close() }128129    public func close() {130        if let ext { ExtAudioFileDispose(ext); self.ext = nil }131        if let fileID { AudioFileClose(fileID); self.fileID = nil; Unmanaged<SourceBox>.fromOpaque(boxPointer).release() }132    }133134    /// Fills `buffer` with the next frames. Returns the number of frames read; 0 at the end of the file.135    public func read(into buffer: AVAudioPCMBuffer) throws -> AVAudioFrameCount {136        guard let ext else { return 0 }137        buffer.frameLength = buffer.frameCapacity138        var frames = buffer.frameCapacity139        box.lastError = nil140        let status = ExtAudioFileRead(ext, &frames, buffer.mutableAudioBufferList)141        if status != noErr {142            buffer.frameLength = 0143            if let e = box.lastError { throw e }144            if status == kAudioFileEndOfFileError { return 0 }145            throw DecoderError.readFailed(status)146        }147        // A source error can surface as a short read rather than as a status.148        if frames == 0, let e = box.lastError { buffer.frameLength = 0; throw e }149        buffer.frameLength = frames150        return frames151    }152153    public func seek(toFrame frame: Int64) throws {154        guard let ext else { return }155        box.lastError = nil156        let status = ExtAudioFileSeek(ext, max(0, min(frame, max(0, info.lengthFrames))))157        if status != noErr { if let e = box.lastError { throw e }; throw DecoderError.seekFailed(status) }158    }159160    /// Whether Core Audio on this Mac can open and decode this source. Used to validate format support for real.161    public static func canDecode(_ source: ByteSource, typeHint: AudioFileTypeID = 0) -> Bool {162        guard let d = try? AudioDecoder(source: source, typeHint: typeHint), let buf = AVAudioPCMBuffer(pcmFormat: d.processingFormat, frameCapacity: 4096) else { return false }163        return ((try? d.read(into: buf)) ?? 0) > 0164    }165}166
Files main
Menu

Theme