Repository Public License
1//2// ORIX Audio3// File: ORIXAudio/Services/RecordingFinalizer.swift4// Description: Turns a PCM capture master into the library file, and finds masters left behind by interrupted sessions.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import Foundation10import ORIXAudioCore1112enum FinalizeError: Error, LocalizedError {13 case empty, verification(String)14 var errorDescription: String? {15 switch self {16 case .empty: String(localized: "Nothing was recorded.")17 case .verification(let m): String(localized: "The saved file didn't pass verification (\(m)). The original capture was kept.")18 }19 }20}2122struct FinalizedRecording: Sendable {23 var id: UUID24 var fileName: String25 var info: AudioFileInfo26}2728enum RecordingFinalizer {29 /// Output sample rate for a preset given the capture rate. Only the Voice preset reduces the rate (24 kHz covers speech).30 static func outputSampleRate(for preset: RecordingPreset, captureRate: Double) -> Double {31 preset == .voice && captureRate > 24_000 ? 24_000 : captureRate32 }3334 /// Encodes the master to the preset's format inside the recording's folder. The master and its sidecar are deleted only35 /// after the encoded file has been re-opened and its duration checked.36 static func finalize(_ sidecar: CaptureSidecar, progress: (@Sendable (Double) -> Void)? = nil) throws -> FinalizedRecording {37 guard let inspected = CAFWriter.inspect(url: sidecar.cafURL), inspected.frames > 0 else { throw FinalizeError.empty }38 let reader = try AudioFileReader(url: sidecar.cafURL)39 let preset = sidecar.preset40 let folder = LibraryFiles.ensureFolder(for: sidecar.id)41 let fileName = "audio.\(preset.format.fileExtension)"42 let temp = folder.appendingPathComponent(".\(fileName).partial"), final = folder.appendingPathComponent(fileName)43 let outRate = outputSampleRate(for: preset, captureRate: reader.sampleRate)44 do {45 let writer = try AudioFileWriter(url: temp.appendingPathExtension(preset.format.fileExtension), format: preset.format, inputSampleRate: reader.sampleRate,46 channels: reader.channels, outputSampleRate: outRate, aacBitRate: preset.aacBitRatePerChannel * reader.channels)47 var done = 048 // The reader sees the frames present when it opened; the inspected count is authoritative for a torn file.49 let total = min(reader.frameCount, inspected.frames)50 while done < total {51 let chunk = try reader.read(maxFrames: min(65_536, total - done))52 guard let n = chunk.first?.count, n > 0 else { break }53 try writer.write(chunk)54 done += n55 progress?(Double(done) / Double(total))56 }57 try writer.finish()58 let produced = temp.appendingPathExtension(preset.format.fileExtension)59 let info = try AudioFileReader.info(url: produced)60 let expected = Double(total) / reader.sampleRate61 guard abs(info.duration - expected) < max(0.25, expected * 0.005) else {62 try? FileManager.default.removeItem(at: produced)63 throw FinalizeError.verification(String(format: "%.2f s vs %.2f s", info.duration, expected))64 }65 try? FileManager.default.removeItem(at: final)66 try FileManager.default.moveItem(at: produced, to: final)67 try? FileManager.default.setAttributes([.protectionKey: LibraryFiles.protection], ofItemAtPath: final.path)68 var finalInfo = info69 finalInfo.fileName = fileName70 sidecar.remove()71 return FinalizedRecording(id: sidecar.id, fileName: fileName, info: finalInfo)72 } catch {73 try? FileManager.default.removeItem(at: temp.appendingPathExtension(preset.format.fileExtension))74 throw error75 }76 }77}7879/// A capture master found at launch that no session owns: the app was terminated, crashed or lost power while recording.80struct RecoverableCapture: Identifiable, Sendable {81 var sidecar: CaptureSidecar82 var duration: Double83 var bytes: Int6484 var id: UUID { sidecar.id }85}8687enum RecordingRecovery {88 /// Lists interrupted captures. `activeID` is the session currently recording, if any.89 static func scan(excluding activeID: UUID?) -> [RecoverableCapture] {90 let files = (try? FileManager.default.contentsOfDirectory(at: LibraryFiles.capture, includingPropertiesForKeys: nil)) ?? []91 var out: [RecoverableCapture] = []92 for caf in files where caf.pathExtension == "caf" {93 guard let id = UUID(uuidString: caf.deletingPathExtension().lastPathComponent), id != activeID else { continue }94 let json = caf.deletingPathExtension().appendingPathExtension("json")95 // Without a sidecar the audio is still recoverable: rebuild a minimal one from the file itself.96 let created = ((try? FileManager.default.attributesOfItem(atPath: caf.path)[.creationDate]) as? Date) ?? .now97 let sidecar = LibraryFiles.load(CaptureSidecar.self, from: json)98 ?? CaptureSidecar(id: id, title: String(localized: "Recovered recording"), startedAt: created, preset: .highQuality, markers: [], participants: "")99 guard let inspected = CAFWriter.inspect(url: caf) else { continue }100 if inspected.frames == 0 { sidecar.remove(); continue } // nothing was captured: clean up silently101 out.append(RecoverableCapture(sidecar: sidecar, duration: Double(inspected.frames) / inspected.format.sampleRate, bytes: LibraryFiles.size(of: caf)))102 }103 return out.sorted { $0.sidecar.startedAt > $1.sidecar.startedAt }104 }105}106