// The microphone, behind a seam — the ONE place an `AVAudioRecorder` is built. // // `CapabilityGateSweepTests` names this file as that birthplace, beside the // dictation engine's and the pairing scanner's, and the rule all three keep is // the app's one order (`CottonKit/Capabilities/DeviceCapability.swift`): // // ask → configure the session → construct the object → start // // Nothing platform is built until the gate has answered. That order is not // style: three crashes came from breaking it, each an Objective-C exception // with no Swift error and no Bugsink event, and each invisible on a simulator. // // ── Why a protocol ─────────────────────────────────────────────────────────── // // `MeetingRecorderModel` runs the recorder's effects, and the effects are the // half worth testing: does a phone call pause it, does Stop still create a // meeting from a paused recording, does a refusal keep the file. None of that // needs a microphone, and a test that needed one would not run in CI at all. So // the model holds `any MeetingCapture` and this file holds the only // implementation that touches AVFoundation. // // ── One file, not segments ─────────────────────────────────────────────────── // // `AVAudioRecorder.pause()` and `record()` continue into the SAME file, so a // pause is not a cut and there is no manifest, no rotation and no gap ledger — // all of which the previous runtime's recorder had because it uploaded while it // recorded. This one hands one path to `meetings.create` at Stop and the crate // copies it. // // ── The container and the format, and why neither is the obvious one ───────── // // **An MPEG-4 file is only playable once its moov atom has been written, and // `stop()` is what writes it.** A process killed mid-recording therefore left // an `.m4a` that no player, no probe and no transcriber would open at all — the // walk of 15 Sep 2026 force-quit at 0:13 and got 160 KB `afinfo` refused. // // So the microphone writes a **Core Audio File** (`.caf`). CAF is chunk-based: // while a recording runs, the `data` chunk carries a size of **-1** — "this is // still being written" — and the header is patched with the real size at // `stop()`. A file nothing ever closed is therefore still a file. // // **But a container that survives is not the same as audio that survives**, and // that is what the walk of 16 Sep 2026 found. With AAC inside the CAF, a killed // capture read `audio packets: 0 · estimated duration: 0.000000 sec` over 2,268 // bytes: AAC packets vary in size, so the frame count lives in a **`pakt` // chunk** that is only written at `stop()` — a killed AAC CAF has the bytes and // no table to read them by, the export refuses it outright, and the server // would not transcribe it. // // **Linear PCM has no packet table to lose.** Every packet is the same two // bytes, so a reader gets the frame count by arithmetic over the file's own // size, and `data` at -1 is all it needs. Measured on this Mac, writing 13 s // and taking the bytes mid-write with the writer still open: // // pcm in caf, killed 6.341 s, and the export to .m4a works // aac in caf, killed 0.000 s, 0 packets; the export FAILS (-11800) // aac in m4a, killed no player at all // // The numbers, and what a two-hour meeting costs, are in // Cotton note "The phone and Mac app — how a screen is built". // // So the cost of the change is paid on the way out rather than on the way in: // what is filed is an AAC `.m4a` **encoded** from the PCM at Stop and at the // recovery slip's Keep alike (`MeetingAudioExport.swift`). That is a real // transcode, so the screen shows a "finishing…" stage while it runs, and a // failed export files the PCM CAF as recorded rather than losing the audio. // // The recovery marker still records the STAGE it was at // (`MeetingRecovery.swift`) and the offer still says which case it is, because // a capture file torn off mid-write is readable and still not whole: what is // missing is whatever the writer was holding when the process went. import AVFoundation import CottonKit import Foundation /// What the OS did to a recording without being asked. public enum MeetingCaptureInterruption: Equatable, Sendable { /// A phone call, or another app taking the session. case began /// It gave the session back. **Whether iOS said `shouldResume` is not /// carried**: it routinely omits that option after a call, and treating it /// as a gate is how a recording stays silently paused for the rest of a /// meeting (`MeetingRecorderMachine`, rule 2). case ended } /// The microphone, as the recorder model sees it. @MainActor public protocol MeetingCapture: AnyObject { /// Told when the OS takes the session or gives it back. Set before `open`. var onInterruption: ((MeetingCaptureInterruption) -> Void)? { get set } /// Configure the session and open the file. **Called only after the gate /// answered `.ready`.** func open(at url: URL) throws func pause() /// Start writing into the same file again. Throws when the session will not /// come back — a call that is still up owns it, and the screen says so /// rather than pretending capture resumed. func resume() throws /// Close the file so it is playable, and give the session back. func close() /// The loudest thing reaching the microphone right now, 0…1. func meter() -> Double } /// The shipping one. @MainActor public final class SystemMeetingRecorder: MeetingCapture { public var onInterruption: ((MeetingCaptureInterruption) -> Void)? private var recorder: AVAudioRecorder? private let watch = InterruptionWatch() private let routes = InterruptionWatch() private var sessionActivated = false /// True from `open` or `resume` until `pause` or `close`: what the person /// asked for. A route change (a headset unplugged, a car's Bluetooth taken /// away) can leave `AVAudioRecorder` stopped on its own; while this is /// true the recorder is started again on whatever input remains, into /// the same file (Cotton Meetings, 17 Nov 2026). private var wantsCapture = false /// The rate the capture is written at: 24 kHz for the shell's recorder, /// 16 kHz where the core names the file (Cotton Meetings: a 16 kHz mono /// WAV, `meetings.record.start`, whose header the core rewrites). private let sampleRate: Double public init(sampleRate: Double = 24_000) { self.sampleRate = sampleRate } /// **Linear PCM, 16-bit, mono, 24 kHz** — the format a killed capture can /// still be read from, for the reason the header gives at length. /// /// **The CONTAINER is not in here**: `AVAudioRecorder` takes it from the /// URL's extension, and the URL is `MeetingFiles.capturedFileName` — a /// Core Audio File. /// /// **24 kHz and not 44.1.** PCM is 2 bytes a frame whatever else is true, /// so the sample rate is the whole of the size: 2.75 MiB a minute here /// against 5.06 at 44.1 kHz, which is 330 MiB for a two-hour meeting /// against 607 MiB. The capture is a TEMPORARY file on a person's phone /// beside the `.m4a` encoded from it, so the smaller one is what fits; and /// 24 kHz carries everything up to 12 kHz, which is well above speech and /// above what every transcriber resamples to anyway. /// /// **Mono on purpose.** A meeting is speech in a room, one microphone is /// what a phone has, and a second channel would be the same audio twice at /// twice the bytes. /// /// What is FILED is AAC at the encoder's own rate (about 32 kbps for this /// input, measured), which is 28 MiB for those two hours — comfortably /// inside the crate's ceiling. static let settings: [String: Any] = [ AVFormatIDKey: Int(kAudioFormatLinearPCM), AVSampleRateKey: 24_000.0, AVNumberOfChannelsKey: 1, AVLinearPCMBitDepthKey: 16, AVLinearPCMIsFloatKey: false, AVLinearPCMIsBigEndianKey: false, AVLinearPCMIsNonInterleaved: false, ] public func open(at url: URL) throws { try activateSession() listenForInterruptions() // The object is built HERE, after the session has a category and is // active — see the file header for the three crashes that rule comes // from. var settings = Self.settings settings[AVSampleRateKey] = sampleRate let made = try AVAudioRecorder(url: url, settings: settings) made.isMeteringEnabled = true guard made.record() else { throw MeetingCaptureFailure.wouldNotStart } recorder = made wantsCapture = true listenForRouteChanges() } public func pause() { wantsCapture = false recorder?.pause() } public func resume() throws { try activateSession() guard let recorder, recorder.record() else { throw MeetingCaptureFailure.wouldNotStart } wantsCapture = true } public func close() { wantsCapture = false recorder?.stop() recorder = nil watch.release() routes.release() deactivateSession() } /// Average power rather than peak: what the strip is answering is "is /// anything reaching the microphone", and a peak meter jumps on a consonant /// and reads as a flicker. /// /// **Format-independent**, and it stayed so when the capture went to PCM: /// `AVAudioRecorder` meters the input it is given, before anything is /// written, so there is no encoder in the path at all. −50 dB is the floor — a quiet room, not silence /// — so a pause in speech draws a low bar rather than a gap in the paper, /// which is the same reading `MeetingWaveform.quietest` takes. public func meter() -> Double { guard let recorder else { return 0 } recorder.updateMeters() let decibels = Double(recorder.averagePower(forChannel: 0)) guard decibels.isFinite else { return 0 } let floor = -50.0 guard decibels > floor else { return 0 } return min(1, max(0, (decibels - floor) / -floor)) } // MARK: - The session /// `.record` and not `.playAndRecord`: this screen never plays anything, and /// the wider category would duck whatever else is making sound on the phone /// for no reason. /// /// `.allowBluetooth` is what lets a paired headset's microphone be the one /// used, which is how a meeting is actually recorded. **`.defaultToSpeaker` /// is deliberately absent** — it is an OUTPUT route option and is only legal /// on `.playAndRecord`; setting it here would throw at `setCategory`. private func activateSession() throws { #if os(iOS) let session = AVAudioSession.sharedInstance() try session.setCategory(.record, mode: .default, options: [.allowBluetooth]) try session.setActive(true) sessionActivated = true #endif } /// **Only the object that activated the session deactivates it.** /// `setActive(false)` is process-wide, and a recorder giving back a session /// it never opened is a recorder taking the microphone from whichever one is /// using it — the same rule the dictation recogniser's teardown keeps. private func deactivateSession() { guard sessionActivated else { return } #if os(iOS) try? AVAudioSession.sharedInstance().setActive( false, options: .notifyOthersOnDeactivation) #endif sessionActivated = false } /// The input changed under a running recording. Whatever the reason, if /// the recording should be running and is not, start it again on the /// input that is left — the same file, so the change is not a cut. private func listenForRouteChanges() { #if os(iOS) guard !routes.isHolding else { return } let token = NotificationCenter.default.addObserver( forName: AVAudioSession.routeChangeNotification, object: AVAudioSession.sharedInstance(), queue: .main ) { [weak self] _ in MainActor.assumeIsolated { self?.keepCapturingAfterRouteChange() } } routes.hold(token) #endif } private func keepCapturingAfterRouteChange() { guard wantsCapture, let recorder, !recorder.isRecording else { return } if !recorder.record() { Log.warn("meeting audio: the recorder would not start again after the input changed") } } private func listenForInterruptions() { #if os(iOS) guard !watch.isHolding else { return } let token = NotificationCenter.default.addObserver( forName: AVAudioSession.interruptionNotification, object: AVAudioSession.sharedInstance(), queue: .main ) { [weak self] note in let raw = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt let kind: MeetingCaptureInterruption? = raw == AVAudioSession.InterruptionType.began.rawValue ? .began : raw == AVAudioSession.InterruptionType.ended.rawValue ? .ended : nil guard let kind else { return } // The notification arrives on the main queue (asked for above), and // the seam is `@MainActor`, so this hop asserts what is already // true rather than moving work. MainActor.assumeIsolated { self?.onInterruption?(kind) } } watch.hold(token) #endif } } /// The interruption observer's token, in a box whose own `deinit` can reach it. /// /// **Under Swift 6 a nonisolated `deinit` may not touch a non-`Sendable` /// property of a `@MainActor` class**, and an observer token is /// `any NSObjectProtocol`. That is a compile error rather than a race nobody /// notices, and it is the same one `CottonCore`'s `CoreHandle` exists to /// answer: the thing that must be released from a `deinit` lives in a /// lock-guarded box, and the object above merely uses it. Without the box a /// recorder dropped without `close()` would leave a block observer registered /// against the audio session for the life of the process. private final class InterruptionWatch: @unchecked Sendable { private let lock = NSLock() private var token: (any NSObjectProtocol)? var isHolding: Bool { lock.lock() defer { lock.unlock() } return token != nil } func hold(_ found: any NSObjectProtocol) { lock.lock() defer { lock.unlock() } token = found } func release() { lock.lock() defer { lock.unlock() } if let token { NotificationCenter.default.removeObserver(token) } token = nil } deinit { release() } } /// Why capture would not run. One case, because one case is what a caller can /// act on: the session or the writer refused, the recording did not start, and /// the screen says so with a verb to try again. public enum MeetingCaptureFailure: Error, Equatable, LocalizedError { case wouldNotStart public var errorDescription: String? { switch self { case .wouldNotStart: return ShellLines.line("capture", "meeting.would_not_start") } } }