Cotton code
165 lines · 8.0 KB · SwiftRaw
// The capture file, encoded into the container a meeting is delivered in.//// The recorder writes **linear PCM** into a Core Audio File while it records,// because that is what a killed process leaves READABLE// (`MeetingAudioFormats.capturedExtension` says why, at length, with the// measurements). What a transcriber and a person saving a copy both expect is// an AAC `.m4a`, and PCM is fifty times the size, so the last thing before// `meetings.create` is an export: `AVAssetExportSession` at// `AVAssetExportPresetAppleM4A`.//// **This is a real transcode, and it takes time.** It is not the passthrough// rewrap this file used to hold — that one copied AAC packets between wrappers// at disk speed. Measured on a Mac, ten minutes of 24 kHz PCM exports in about// half a second; a phone is slower and a two-hour meeting is twelve times the// work, so the screen shows a "finishing…" stage with a progress line while it// runs, on the record sheet and on the recovery slip alike. That is what// `watching` is for: the session's own fraction, reported as it goes.//// ── Why a failure is not a refusal ───────────────────────────────────────────//// An export can fail, and the interesting case is exactly the one this whole// lane exists for: a capture file the OS tore off mid-write. That must not cost// the person their recording. **`.caf` is a container the crate and the server// already accept** (`MEETING_AUDIO_TYPES`, `MeetingAudioFormats.formats`), and// the key's extension follows the file — so when the export fails, the capture// file is filed as it is, and the reason goes to the log. The recording is// filed either way; what the export buys is the commoner container and fifty// times less to carry.//// ── Why it is a seam ─────────────────────────────────────────────────────────//// Two callers need it — Stop (`MeetingRecorderModel`) and the recovery slip's// Keep (`MeetingsScreen`) — and neither may need an AVFoundation export running// inside a library test. So the rule about WHICH path is filed is a pure// function over an injected exporter, and the shipping exporter is the only// thing here that touches AVFoundation.import AVFoundationimport CottonKitimport Foundation/// Encoding one container's audio into another's.protocol MeetingAudioExporting: Sendable {    /// Encode the file at `captured` into a file called `named` beside it, and    /// answer where it landed. `watching` is told the fraction done, 0…1, as    /// often as the exporter has something to say. Throws when the file cannot    /// be exported at all.    func export(        _ captured: URL,        as named: String,        watching: @escaping @Sendable (Double) -> Void    ) async throws -> URL}extension MeetingAudioExporting {    /// The same, for a caller with nothing to draw.    func export(_ captured: URL, as named: String) async throws -> URL {        try await export(captured, as: named, watching: { _ in })    }}/// The shipping one: `AVAssetExportSession`, the Apple M4A preset.struct SystemMeetingAudioExport: MeetingAudioExporting {    init() {}    func export(        _ captured: URL,        as named: String,        watching: @escaping @Sendable (Double) -> Void    ) async throws -> URL {        try await run(captured, as: named, watching: watching)    }    /// **On the main actor, deliberately.**    ///    /// `AVAssetExportSession` is not `Sendable`, and the export has to be    /// STARTED and WATCHED at the same time — two things holding the same    /// object, which Swift 6 refuses to let cross an isolation boundary. One    /// actor owning it is the answer, and the main one is the right one: the    /// only thing that happens here is awaiting, the transcode itself runs on    /// AVFoundation's own threads, and the fraction is going straight to a    /// screen anyway.    @MainActor    private func run(        _ captured: URL,        as named: String,        watching: @escaping @Sendable (Double) -> Void    ) async throws -> URL {        // `export(to:as:)` and `states(updateInterval:)` are the two calls that        // are not deprecated, and both arrived in macOS 15 — this package's Mac        // floor is 14. **Nothing on the Mac records**: it ingests meetings from        // this phone and from a backup, so the capture container never appears        // there. So an older Mac answers "not exported" and the caller files the        // capture file, which the crate accepts, rather than this app carrying a        // second export spelling for a path nobody walks.        guard #available(macOS 15, *) else { throw MeetingAudioExportFailure.wouldNotExport }        let destination = captured.deletingLastPathComponent().appendingPathComponent(named)        // An export REFUSES a destination that already exists, and this path is        // reached twice whenever a refused `meetings.create` is retried. The        // file being replaced is this app's own export of a file it still        // holds, never the capture.        if FileManager.default.fileExists(atPath: destination.path(percentEncoded: false)) {            try FileManager.default.removeItem(at: destination)        }        let asset = AVURLAsset(url: captured)        guard            let session = AVAssetExportSession(                asset: asset, presetName: AVAssetExportPresetAppleM4A)        else {            throw MeetingAudioExportFailure.wouldNotExport        }        // The export RUNS in `export(to:as:)`; `states` is the reporting of it,        // and iterating it is how the fraction arrives. Both have to be in        // flight at once, which is what the task is.        let running = Task { @MainActor in try await session.export(to: destination, as: .m4a) }        for await state in session.states(updateInterval: 0.25) {            if case .exporting(let progress) = state { watching(progress.fractionCompleted) }        }        try await running.value        watching(1)        return destination    }}/// Why an export did not happen. One case: the caller's answer is the same/// whatever the reason, and the reason itself goes to the log.enum MeetingAudioExportFailure: Error, Equatable {    case wouldNotExport}/// **Which file `meetings.create` is handed** — the one rule, for the two/// callers that file a recording this phone made.enum MeetingAudioDelivery {    /// The path to file, and the type to declare with it.    ///    /// The encoded MPEG-4 where the export worked; the capture file itself    /// where it did not — see the header for why that is a container choice and    /// not a swallowed failure.    static func prepare(        _ captured: String,        exporting exporter: any MeetingAudioExporting,        named: String = MeetingFiles.deliveredFileName,        watching: @escaping @Sendable (Double) -> Void = { _ in },        log: @Sendable (String) -> Void = Log.warn    ) async -> (path: String, mime: String?) {        guard !captured.isEmpty else { return (captured, nil) }        // Already the delivered container — an import, or a recording made by a        // build older than the CAF one, whose marker names an `.m4a`.        let extensionOf = MeetingAudioFormats.fileExtension(ofFileName: captured)        guard extensionOf == MeetingAudioFormats.capturedExtension else {            return (captured, MeetingAudioFormats.mime(forFileName: captured))        }        do {            let landed = try await exporter.export(                URL(fileURLWithPath: captured), as: named, watching: watching)            let path = landed.path(percentEncoded: false)            return (path, MeetingAudioFormats.mime(forFileName: path))        } catch {            log(                "meeting audio: the capture could not be exported as \(named), filing it as recorded: \(error)"            )            return (captured, MeetingAudioFormats.mime(forFileName: captured))        }    }}