SPB Git

Repository Public

Recorder.swift 15.0 KB 308 lines swift

1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXDJEngine/Recorder.swift3// Description: Master recording and export. The render thread feeds a lock-free ring; a writer thread stores 32-bit4//              float CAF (robust to interruption). The take is converted to the chosen format by an explicit export.5//              Export applies trim, fades and gain, then re-reads the result to validate it.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import AVFoundation10import Foundation1112public enum AudioFileFormat: String, Codable, Sendable, CaseIterable, Identifiable {13    case wav24, wav16, aiff24, aiff16, m4aAAC, m4aALAC, flac14    public var id: String { rawValue }1516    public var fileExtension: String {17        switch self {18        case .wav24, .wav16: "wav"19        case .aiff24, .aiff16: "aiff"20        case .m4aAAC, .m4aALAC: "m4a"21        case .flac: "flac"22        }23    }2425    public var displayName: String {26        switch self {27        case .wav24: "WAV 24-bit"28        case .wav16: "WAV 16-bit"29        case .aiff24: "AIFF 24-bit"30        case .aiff16: "AIFF 16-bit"31        case .m4aAAC: "AAC 256 kbps (M4A)"32        case .m4aALAC: "Apple Lossless (M4A)"33        case .flac: "FLAC"34        }35    }3637    public var isLossless: Bool { self != .m4aAAC }3839    func settings(sampleRate: Double) -> [String: Any] {40        var s: [String: Any] = [AVSampleRateKey: sampleRate, AVNumberOfChannelsKey: 2]41        switch self {42        case .wav24, .wav16:43            s[AVFormatIDKey] = kAudioFormatLinearPCM; s[AVLinearPCMBitDepthKey] = self == .wav24 ? 24 : 1644            s[AVLinearPCMIsFloatKey] = false; s[AVLinearPCMIsBigEndianKey] = false; s[AVLinearPCMIsNonInterleaved] = false45        case .aiff24, .aiff16:46            s[AVFormatIDKey] = kAudioFormatLinearPCM; s[AVLinearPCMBitDepthKey] = self == .aiff24 ? 24 : 1647            s[AVLinearPCMIsFloatKey] = false; s[AVLinearPCMIsBigEndianKey] = true; s[AVLinearPCMIsNonInterleaved] = false48        case .m4aAAC: s[AVFormatIDKey] = kAudioFormatMPEG4AAC; s[AVEncoderBitRateKey] = 256_00049        case .m4aALAC: s[AVFormatIDKey] = kAudioFormatAppleLossless; s[AVEncoderBitDepthHintKey] = 2450        case .flac: s[AVFormatIDKey] = kAudioFormatFLAC; s[AVLinearPCMBitDepthKey] = 2451        }52        return s53    }54}5556public struct RecordingStatus: Sendable, Equatable {57    public init() {}58    public var isRecording = false59    public var duration = 0.060    public var bytesWritten: Int64 = 061    public var freeDiskBytes: Int64 = 062    /// Blocks the render thread could not hand over because the writer fell behind (audible gaps in the take).63    public var overruns: UInt32 = 064    public var stoppedReason: String?65    public var url: URL?66}6768public struct ExportOptions: Sendable, Equatable {69    public var format = AudioFileFormat.wav2470    /// Seconds from the start of the source; nil keeps the whole take.71    public var range: ClosedRange<Double>?72    public var fadeIn = 0.073    public var fadeOut = 0.074    /// Gain applied to the audio, in dB.75    public var gainDB = 0.076    /// When set, the gain is chosen so the peak lands on this level (dBFS); `gainDB` is ignored.77    public var normalizePeakDB: Double?78    public var title = ""79    public var artist = ""80    public init() {}81}8283public struct ExportReport: Sendable, Equatable {84    public var url: URL85    public var frames: Int86    public var duration: Double87    public var sampleRate: Double88    public var peakDB: Double89    /// Samples at or above full scale in the written audio (0 when the export is clean).90    public var clippedSamples: Int91    public var appliedGainDB: Double92    public var fileSize: Int6493    /// True when the file was reopened and its length matched what was written.94    public var validated: Bool95}9697public enum RecorderError: Error, LocalizedError, Equatable {98    case alreadyRecording99    case notRunning100    case lowDiskSpace101    case io(String)102    case empty103104    public var errorDescription: String? {105        switch self {106        case .alreadyRecording: "A recording is already in progress."107        case .notRunning: "The audio engine is not running."108        case .lowDiskSpace: "Less than 500 MB is free on the destination disk."109        case let .io(m): "The recording could not be written: \(m)"110        case .empty: "The recording contains no audio."111        }112    }113}114115public final class Recorder: @unchecked Sendable {116    public static let minimumFreeBytes: Int64 = 500 * 1024 * 1024117    private let engine: DJEngine118    private let lock = NSLock()119    private let queue = DispatchQueue(label: "ai.spboucher.orix.dj.recorder", qos: .utility)120    private var timer: DispatchSourceTimer?121    private var file: AVAudioFile?122    private var status = RecordingStatus()123    private var scratch: UnsafeMutablePointer<Float>124    private var buffer: AVAudioPCMBuffer?125    private var lastSpaceCheck = Date.distantPast126    private static let chunk = 16384127128    public init(engine: DJEngine) {129        self.engine = engine130        scratch = .allocate(capacity: Self.chunk * 2)131    }132133    deinit { scratch.deallocate() }134135    public var currentStatus: RecordingStatus {136        lock.lock(); defer { lock.unlock() }137        var s = status138        if s.isRecording { s.overruns = engine.renderState.recordOverruns }139        return s140    }141142    static func freeBytes(at url: URL) -> Int64 {143        let values = try? url.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])144        return values?.volumeAvailableCapacityForImportantUsage ?? 0145    }146147    /// Starts recording the master bus into `directory/In Progress/<name>.caf`. Only ever called from an explicit user action.148    public func start(directory: URL, name: String) throws {149        lock.lock(); defer { lock.unlock() }150        guard !status.isRecording else { throw RecorderError.alreadyRecording }151        let folder = directory.appendingPathComponent("In Progress", isDirectory: true)152        do { try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) } catch { throw RecorderError.io(error.localizedDescription) }153        guard Self.freeBytes(at: folder) >= Self.minimumFreeBytes else { throw RecorderError.lowDiskSpace }154        let safe = name.replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: ":", with: "-")155        let url = folder.appendingPathComponent(safe).appendingPathExtension("caf")156        let sr = engine.core.sampleRate157        let settings: [String: Any] = [AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: sr, AVNumberOfChannelsKey: 2, AVLinearPCMBitDepthKey: 32,158                                       AVLinearPCMIsFloatKey: true, AVLinearPCMIsBigEndianKey: false, AVLinearPCMIsNonInterleaved: false]159        do { file = try AVAudioFile(forWriting: url, settings: settings, commonFormat: .pcmFormatFloat32, interleaved: false) } catch { throw RecorderError.io(error.localizedDescription) }160        buffer = AVAudioPCMBuffer(pcmFormat: file!.processingFormat, frameCapacity: AVAudioFrameCount(Self.chunk))161        status = RecordingStatus(); status.isRecording = true; status.freeDiskBytes = Self.freeBytes(at: folder); status.url = url162        engine.setRecordTap(true)163        let t = DispatchSource.makeTimerSource(queue: queue)164        t.schedule(deadline: .now() + .milliseconds(40), repeating: .milliseconds(40))165        t.setEventHandler { [weak self] in self?.drain() }166        t.resume()167        timer = t168    }169170    /// Writer thread: moves audio from the ring to the file.171    private func drain(final: Bool = false) {172        lock.lock(); defer { lock.unlock() }173        guard let file, let buffer, status.isRecording || final else { return }174        let ring = engine.core.recordRing175        while true {176            let n = ring.read(into: scratch, maxFrames: Self.chunk)177            if n == 0 { break }178            guard let data = buffer.floatChannelData else { break }179            for i in 0 ..< n { data[0][i] = scratch[2 * i]; data[1][i] = scratch[2 * i + 1] }180            buffer.frameLength = AVAudioFrameCount(n)181            do { try file.write(from: buffer) } catch {182                status.stoppedReason = "Writing failed: \(error.localizedDescription)"183                status.isRecording = false184                engine.setRecordTap(false)185                return186            }187            status.duration = Double(file.length) / file.fileFormat.sampleRate188            status.bytesWritten = file.length * 8189        }190        if Date().timeIntervalSince(lastSpaceCheck) > 2, let url = status.url {191            lastSpaceCheck = Date()192            status.freeDiskBytes = Self.freeBytes(at: url)193            if status.freeDiskBytes < Self.minimumFreeBytes / 2, status.isRecording {194                // Stop cleanly while there is still room to close the file.195                status.stoppedReason = "Recording stopped: the disk is almost full."196                status.isRecording = false197                engine.setRecordTap(false)198            }199        }200    }201202    /// Stops and returns the raw take (float CAF). Returns nil when nothing was being recorded.203    @discardableResult public func stop() -> URL? {204        lock.lock()205        guard file != nil else { lock.unlock(); return nil }206        engine.setRecordTap(false)207        timer?.cancel(); timer = nil208        lock.unlock()209        // Let the render thread see the event, then collect what is left in the ring.210        if engine.isRunning { usleep(60000) } else { _ = engine.renderOffline(frames: 512) }211        drain(final: true)212        lock.lock(); defer { lock.unlock() }213        let url = status.url214        file = nil; buffer = nil215        status.isRecording = false216        return url217    }218219    /// Takes left behind by an interrupted session (crash, power loss). CAF files stay readable up to the last write.220    public static func recoverableTakes(in directory: URL) -> [URL] {221        let folder = directory.appendingPathComponent("In Progress", isDirectory: true)222        let items = (try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.fileSizeKey])) ?? []223        return items.filter { $0.pathExtension == "caf" && ((try? $0.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) > 4096 }.sorted { $0.lastPathComponent < $1.lastPathComponent }224    }225}226227public enum AudioExporter {228    /// Peak (linear) of a file, read in chunks.229    public static func peak(of url: URL, range: ClosedRange<Double>? = nil) throws -> Float {230        let file = try AVAudioFile(forReading: url)231        let sr = file.processingFormat.sampleRate232        let start = AVAudioFramePosition((range?.lowerBound ?? 0) * sr)233        let end = min(file.length, range.map { AVAudioFramePosition($0.upperBound * sr) } ?? file.length)234        guard end > start, let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: 65536) else { return 0 }235        file.framePosition = start236        var peak: Float = 0237        while file.framePosition < end {238            try file.read(into: buffer, frameCount: AVAudioFrameCount(min(65536, end - file.framePosition)))239            if buffer.frameLength == 0 { break }240            guard let data = buffer.floatChannelData else { break }241            for c in 0 ..< Int(buffer.format.channelCount) { for i in 0 ..< Int(buffer.frameLength) { peak = max(peak, abs(data[c][i])) } }242        }243        return peak244    }245246    /// Writes `source` to `destination` with trim, fades and gain, then reopens the result to validate it.247    public static func export(source: URL, to destination: URL, options: ExportOptions, progress: ((Double) -> Void)? = nil) throws -> ExportReport {248        let input: AVAudioFile249        do { input = try AVAudioFile(forReading: source) } catch { throw RecorderError.io(error.localizedDescription) }250        let format = input.processingFormat251        let sr = format.sampleRate252        let start = max(0, AVAudioFramePosition((options.range?.lowerBound ?? 0) * sr))253        let end = min(input.length, options.range.map { AVAudioFramePosition($0.upperBound * sr) } ?? input.length)254        let total = Int(end - start)255        guard total > 0 else { throw RecorderError.empty }256        var gainDB = options.gainDB257        if let target = options.normalizePeakDB {258            let p = try peak(of: source, range: options.range)259            gainDB = p > 0 ? target - Double(20 * log10f(p)) : 0260        }261        let gain = Float(pow(10, gainDB / 20))262        try? FileManager.default.removeItem(at: destination)263        var output: AVAudioFile! = nil264        do { output = try AVAudioFile(forWriting: destination, settings: options.format.settings(sampleRate: sr), commonFormat: .pcmFormatFloat32, interleaved: false) } catch { throw RecorderError.io(error.localizedDescription) }265        guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 65536),266              let outBuffer = AVAudioPCMBuffer(pcmFormat: output.processingFormat, frameCapacity: 65536) else { throw RecorderError.io("no buffer") }267        input.framePosition = start268        let fadeIn = Int(options.fadeIn * sr), fadeOut = Int(options.fadeOut * sr)269        var done = 0; var peakOut: Float = 0; var clipped = 0270        while done < total {271            do { try input.read(into: buffer, frameCount: AVAudioFrameCount(min(65536, total - done))) } catch { throw RecorderError.io(error.localizedDescription) }272            let n = Int(buffer.frameLength)273            if n == 0 { break }274            guard let src = buffer.floatChannelData, let dst = outBuffer.floatChannelData else { break }275            let channels = Int(format.channelCount)276            for c in 0 ..< 2 {277                let from = src[min(c, channels - 1)]278                for i in 0 ..< n {279                    let k = done + i280                    var g = gain281                    if k < fadeIn { g *= Float(k) / Float(max(1, fadeIn)) }282                    if total - k <= fadeOut { g *= Float(total - k) / Float(max(1, fadeOut)) }283                    let v = from[i] * g284                    dst[c][i] = v285                    let a = abs(v)286                    if a > peakOut { peakOut = a }287                    if a >= 1 { clipped += 1 }288                }289            }290            outBuffer.frameLength = AVAudioFrameCount(n)291            do { try output.write(from: outBuffer) } catch { throw RecorderError.io(error.localizedDescription) }292            done += n293            progress?(Double(done) / Double(total))294        }295        // Close the writer (the header is finalised when the file object goes away), then reopen to check the result.296        output = nil297        var validated = false298        var size: Int64 = 0299        if let check = try? AVAudioFile(forReading: destination) {300            // Compressed formats pad to whole packets; PCM must match exactly.301            validated = options.format == .m4aAAC ? abs(Int(check.length) - done) < 4096 : Int(check.length) == done302        }303        if let s = try? destination.resourceValues(forKeys: [.fileSizeKey]).fileSize { size = Int64(s) }304        return ExportReport(url: destination, frames: done, duration: Double(done) / sr, sampleRate: sr, peakDB: peakOut > 0 ? Double(20 * log10f(peakOut)) : -120,305                            clippedSamples: clipped, appliedGainDB: gainDB, fileSize: size, validated: validated)306    }307}308
Files main
Menu

Theme