// Cotton Meetings' recorder, owned by the APP rather than by a screen (voice // plan, 17 Nov 2026): one tap on the first screen, the Action Button, the // lock screen's control or a Shortcut all start the same recording, and the // Live Activity's Pause, Resume, Mark and Stop act on it with the app never // opened. So nothing here is a view's state: the meetings screen reads this // object, and the intents (`CottonMeetingsLive`) reach it through the app. // // Every DECISION is the shell recorder's (`MeetingRecorderMachine`, its // three rules: a person's pause is sticky, an ended interruption always // resumes, a refusal at Stop keeps the audio). This file runs its effects the // way `MeetingRecorderModel` does, with what an app-owned recorder adds: // // * a KIND, meeting or memo (a memo is the same thing with one speaker); // * MARKS, a moment tapped while recording, kept beside the audio // (`marks.json` in the act's folder) so a killed app keeps them too; // * the LIVE state handed out on every change (`onLive`), which the app // turns into the Live Activity; // * waiting: `start` answers once the microphone is open or refused, so an // intent can say what happened. // // THE CORE NAMES THE FILE (meetings-core, `apps/meetings/CORE.md`): // `meetings.record.start` makes the meeting's row at `recording` from the // first second and answers the path to write, a 16 kHz mono 16-bit WAV whose // header the core rewrites at stop or recovery, so a killed take is whole up // to its last sample. A take's id IS its meeting's id. Every ~10 s // `meetings.record.tick` says how long it has run. At Stop the WAV is encoded // to AAC in place (what goes up is ~15 times smaller) and `meetings.record. // stop` says which (`m4a`, or `wav` where the encode failed). At launch // `meetings.record.recover` finishes every take a killed process left. // While the core answers `not_yet`, the take is written to this app's own // folder and its row is a plain record (`MeetingsCore`). #if os(iOS) import AVFoundation import CottonKit import CottonValues import Foundation import SwiftUI /// A meeting or a memo. A memo is a meeting with one speaker. public enum MeetingKind: String, Sendable, Codable, Equatable, CaseIterable { case meeting case memo } /// What the lock screen and the Dynamic Island draw, as the app hands it out. /// The words are the kit's (`meetings` lines), resolved here so the widget /// extension carries no core and no line set. public struct MeetingsLive: Equatable, Sendable { public var kind: MeetingKind public var startedAt: Date /// Whole spans that are over, in milliseconds. public var bankedMs: Double /// When the running span began; `nil` while paused. public var runningSince: Date? public var marks: Int /// What the Activity says it is doing ("Recording a meeting", "Paused"). public var headline: String public var words: Words public struct Words: Equatable, Sendable { public var pause: String public var resume: String public var stop: String public var mark: String } public var paused: Bool { runningSince == nil } } /// What an act from outside (an intent, the Live Activity) can ask. public enum MeetingsAct: Equatable, Sendable { case start(MeetingKind) case pause case resume case mark case stop } /// What `start` answers, for an intent to say. public enum MeetingsStartAnswer: Equatable, Sendable { case recording case blocked case failed(String) } @MainActor @Observable public final class MeetingsEngine { public static let shared = MeetingsEngine() public private(set) var state = MeetingRecorderState() public private(set) var kind: MeetingKind = .meeting public private(set) var marks: [Int] = [] public private(set) var elapsedMs: Double = 0 public private(set) var meter: [Double] = [] /// Bumped each time a recording is filed, so the list reads again. public private(set) var filed = 0 /// The meeting the last Stop made. public private(set) var lastMeetingId: String? /// The act (folder) of the recording in hand. public private(set) var act = MeetingFiles.newActId() /// Told on every change worth drawing on the lock screen; `nil` when no /// recording is in hand. Set by the app (`CottonMeetingsLive`). @ObservationIgnored public var onLive: (@MainActor (MeetingsLive?) -> Void)? @ObservationIgnored private var coreProvider: (@Sendable () async -> (any CottonCalling)?)? @ObservationIgnored private var capture: any MeetingCapture @ObservationIgnored private let authority: any CapabilityAuthority @ObservationIgnored private let recovery: MeetingRecoveryStore @ObservationIgnored private let files: any MeetingAudioStore @ObservationIgnored private let exporter: any MeetingAudioExporting @ObservationIgnored private let now: () -> Date @ObservationIgnored private var audioPath: String? @ObservationIgnored private var ticker: Task? @ObservationIgnored private var checkpointedAt: Date? @ObservationIgnored private var tickedAt: Date? /// True when the core named the file (`meetings.record.start` answered). @ObservationIgnored private var inCore = false /// The file Stop hands the core and its format: the AAC encoded from the /// take, or the WAV as recorded where the encode failed. @ObservationIgnored private var format: String? @ObservationIgnored private var filedPath: String? @ObservationIgnored private var waiting: [CheckedContinuation] = [] @ObservationIgnored private var generation = 0 static let meterWindow = 120 static let checkpointEvery: TimeInterval = 5 static let tickEvery: TimeInterval = 10 /// The take's file in this app's own folder, while the core has no body /// for `meetings.record.start`. static let localFileName = "audio.wav" init( capture: (any MeetingCapture)? = nil, authority: any CapabilityAuthority = SystemCapabilityAuthority(), recovery: MeetingRecoveryStore = MeetingRecoveryStore(), files: any MeetingAudioStore = AppGroupMeetingAudioStore(), exporter: any MeetingAudioExporting = SystemMeetingAudioExport(), now: @escaping () -> Date = Date.init ) { self.capture = capture ?? MeetingsCaptureChoice.make() self.authority = authority self.recovery = recovery self.files = files self.exporter = exporter self.now = now wire() } /// How the engine reaches the core once the app has opened it. public func attach(_ provider: @escaping @Sendable () async -> (any CottonCalling)?) { coreProvider = provider } // MARK: - Acts /// True while a recording is in hand: recording, paused or being filed. public var isBusy: Bool { switch state.stage { case .idle, .blocked, .saved: return false case .failed: return state.startedAt != nil default: return true } } public func perform(_ act: MeetingsAct) async { switch act { case .start(let kind): _ = await start(kind) case .pause: pause() case .resume: resume() case .mark: mark() case .stop: stop() } } /// Start a recording, and answer once the microphone is open or refused. /// A recording already in hand is left alone and answered as recording. @discardableResult public func start(_ kind: MeetingKind) async -> MeetingsStartAnswer { if isBusy { return .recording } reset() self.kind = kind return await withCheckedContinuation { continuation in waiting.append(continuation) send(.appeared) } } public func pause() { send(.personPaused(at: now())) } public func resume() { send(.personResumed(at: now())) } public func stop() { send(.personStopped(at: now())) } public func retry() { send(.retry) } /// Mark the moment: the elapsed millisecond, kept beside the audio. public func mark() { guard case .recording = state.stage else { if case .paused = state.stage { marks.append(state.elapsed(at: now())); keepMarks(); live() } return } marks.append(state.elapsed(at: now())) keepMarks() live() } /// Discard the recording in hand. The only path that deletes audio the /// person did not file, and only on their word. public func discard() { switch state.stage { case .recording, .paused, .failed: break default: return } generation += 1 stopTicking() capture.close() recovery.clear(id: act) files.discard(act: act) reset() } // MARK: - The machine private func reset() { generation += 1 stopTicking() state = MeetingRecorderState() marks = [] elapsedMs = 0 meter = [] audioPath = nil format = nil filedPath = nil inCore = false checkpointedAt = nil tickedAt = nil act = MeetingFiles.newActId() wire() live() } private func wire() { capture.onInterruption = { [weak self] kind in guard let self else { return } self.send(kind == .began ? .interrupted(at: self.now()) : .interruptionEnded(at: self.now())) } } private func send(_ event: MeetingRecorderEvent) { generation += 1 let mine = generation let effects = MeetingRecorderMachine.step(&state, event) elapsedMs = state.elapsedMs(at: now()) answerWaiters() live() for effect in effects { run(effect) guard generation == mine else { return } } } private func answerWaiters() { let answer: MeetingsStartAnswer? switch state.stage { case .recording: answer = .recording case .blocked: answer = .blocked case .failed(let why): answer = .failed(why) default: answer = nil } guard let answer, !waiting.isEmpty else { return } let held = waiting waiting = [] for one in held { one.resume(returning: answer) } } private func run(_ effect: MeetingRecorderEffect) { switch effect { case .askForMicrophone: Task { [authority] in let answer = await authority.gate([.microphone]) self.send(.gate(answer)) } case .openCapture: let mine = generation Task { await openCapture(mine) } case .pauseCapture: capture.pause() stopTicking() case .resumeCapture: do { try capture.resume() startTicking() } catch { send(.captureFailed(at: now(), why: sentence(error))) } case .closeCapture: stopTicking() capture.close() send(.captureClosed(at: now())) case .prepareAudio: Task { await prepareAudio() } case .create: Task { await create() } case .mark(let stage): guard let audioPath, let startedAt = state.startedAt else { return } checkpointedAt = now() recovery.write( MeetingRecoveryMarker( id: act, path: audioPath, startedAt: CottonDate.format(startedAt), title: nil, durationMs: state.elapsed(at: now()), stage: stage ) ) case .clearMark: recovery.clear(id: act) // The core holds the bytes now. if let audioPath { MeetingsMarks.remove(besideAudio: audioPath) } files.discard(act: act) } } /// Ask the core where to write, then open the microphone there. private func openCapture(_ mine: Int) async { let core = await coreProvider?() var file: URL if let core, let started = try? await MeetingsCore(core: core).recordStart(kind: kind, id: act, startedAt: now()) { guard generation == mine else { return } act = started.meeting file = URL(fileURLWithPath: started.audio_path) inCore = true try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) } else { guard generation == mine else { return } do { file = try files.open(act: act, named: Self.localFileName) } catch { return send(.captureFailed(at: now(), why: sentence(error))) } } do { try capture.open(at: file) } catch { if !inCore { files.discard(act: act) } return send(.captureFailed(at: now(), why: sentence(error))) } audioPath = file.path(percentEncoded: false) keepMarks() send(.captureOpened(at: now())) startTicking() } /// Encode the take to AAC in place: the core is told `m4a`; where the /// encode fails the WAV stays as recorded and the core is told `wav`. private func prepareAudio() async { guard let audioPath, format == nil else { return send(.audioPrepared) } let encoded = await Self.encode(URL(fileURLWithPath: audioPath), exporter: exporter) (format, filedPath) = (encoded.format, encoded.url.path(percentEncoded: false)) send(.audioPrepared) } /// The take as AAC beside it (`.m4a`); the WAV goes once the AAC is /// whole. Where the encode fails, the WAV as recorded. static func encode(_ wav: URL, exporter: any MeetingAudioExporting) async -> (format: String, url: URL) { do { let made = try await exporter.export( wav, as: wav.deletingPathExtension().lastPathComponent + ".m4a", watching: { _ in }) let beside = wav.deletingPathExtension().appendingPathExtension("m4a") if made != beside { try? FileManager.default.removeItem(at: beside) try FileManager.default.moveItem(at: made, to: beside) } try? FileManager.default.removeItem(at: wav) return ("m4a", beside) } catch { Log.warn("meetings: the take could not be encoded, it goes as recorded: \(error)") return ("wav", wav) } } private func create() async { guard let audioPath, let startedAt = state.startedAt else { send(.refused(MeetingsWords.line("recorder.failed", ["why": ShellLines.line("capture", "meeting.nothing_to_file")]))) return } guard let core = await coreProvider?() else { send(.refused(MeetingsWords.line("recorder.no_database"))) return } do { let duration = state.elapsed(at: now()) let meetings = MeetingsCore(core: core) let finish = MeetingsCore.Finish( id: act, path: filedPath ?? audioPath, format: format ?? "wav", duration_ms: duration, marks: marks, ended_at: CottonDate.format(startedAt.addingTimeInterval(Double(duration) / 1000))) if inCore { try await meetings.recordStop(finish) } else { // The start never reached the core: the row is made now and // the take finished as a recovered one would be. _ = try await meetings.recordStart(kind: kind, id: act, startedAt: startedAt) try await meetings.recordRecover(finish) } lastMeetingId = act send(.created(.meetingsMeeting(id: act))) self.filed += 1 // The next tap records again: a filed recording is not "in hand". reset() } catch let error as CottonCallError { send(.refused(error.message)) } catch { send(.refused(sentence(error))) } } // MARK: - A recording the app never finished /// Every recording left on this phone by a process that ended mid-way, /// newest first; never the one in hand. public func recoveryOffers() -> [MeetingRecoveryOffer] { let busyAct = isBusy ? act : nil return MeetingRecovery.offers( markers: recovery.markers(), onDisk: files.captures(), exists: { ((try? FileManager.default.attributesOfItem(atPath: $0)[.size]) as? NSNumber)?.intValue ?? 0 > 0 }, probe: { MeetingAudioLength.milliseconds(atPath: $0) } ).filter { $0.marker.id != busyAct } } /// Keep it: the same encode and the same filing Stop would have done, /// with the marks kept beside it. Answers whether it was filed. public func keepRecovered(_ offer: MeetingRecoveryOffer) async -> Bool { let marker = offer.marker guard let core = await coreProvider?() else { return false } let held = MeetingsMarks.read(besideAudio: marker.path) let duration = offer.durationMs ?? marker.durationMs let startedAt = CottonDate.parse(marker.startedAt) ?? now() do { let meetings = MeetingsCore(core: core) _ = try await meetings.recordStart(kind: held?.kind ?? .meeting, id: marker.id, startedAt: startedAt) try await meetings.recordRecover(MeetingsCore.Finish( id: marker.id, path: marker.path, format: URL(fileURLWithPath: marker.path).pathExtension.lowercased(), duration_ms: duration, marks: held?.marks ?? [], ended_at: CottonDate.format(startedAt.addingTimeInterval(Double(duration) / 1000)))) lastMeetingId = marker.id recovery.clear(id: marker.id) MeetingsMarks.remove(besideAudio: marker.path) files.discard(act: marker.id) filed += 1 return true } catch { Log.warn("meetings: a recovered recording was not filed: \(error)") return false } } /// Once at launch: every take a killed process left is finished by the /// core — each one this app holds by name, with its kind and marks /// (`meetings.record.recover {id, path, …}`), then a sweep for any /// `recording` row left with its audio. A take the core would not take /// stays offered on the first screen. public func recoverAtLaunch() async { guard let core = await coreProvider?() else { return } for offer in recoveryOffers() { _ = await keepRecovered(offer) } // A transcription the system ended with the app is said, not left held. await MeetingsPhoneStep.shared.settleInterrupted(core: core) if let swept = await MeetingsCore(core: core).recordRecover() { for meeting in swept { recovery.clear(id: meeting) } if !swept.isEmpty { filed += 1 } } } /// Discard it, on the person's word. public func discardRecovered(_ offer: MeetingRecoveryOffer) { files.discard(act: offer.marker.id) recovery.clear(id: offer.marker.id) } // MARK: - Marks, beside the audio private func keepMarks() { guard let audioPath else { return } MeetingsMarks.write(MeetingsMarks(kind: kind, marks: marks), besideAudio: audioPath) } // MARK: - The clock private func startTicking() { guard ticker == nil else { return } ticker = Task { [weak self] in while !Task.isCancelled { try? await Task.sleep(for: .milliseconds(200)) guard !Task.isCancelled else { return } self?.tick() } } } private func stopTicking() { ticker?.cancel() ticker = nil } func tick() { guard state.stage.isCapturing else { return } elapsedMs = state.elapsedMs(at: now()) meter.append(capture.meter()) if meter.count > Self.meterWindow { meter.removeFirst(meter.count - Self.meterWindow) } if inCore, tickedAt.map({ now().timeIntervalSince($0) >= Self.tickEvery }) ?? true { tickedAt = now() let meeting = act, duration = state.elapsed(at: now()) Task { [coreProvider] in guard let core = await coreProvider?() else { return } await MeetingsCore(core: core).recordTick(meeting: meeting, durationMs: duration) } } if let checkpointedAt, now().timeIntervalSince(checkpointedAt) < Self.checkpointEvery { return } run(.mark(.recording)) } // MARK: - The lock screen private func live() { guard let onLive else { return } guard let startedAt = state.startedAt else { onLive(nil) return } switch state.stage { case .recording, .paused, .finishing, .saving, .failed: break default: onLive(nil) return } onLive(MeetingsLive( kind: kind, startedAt: startedAt, bankedMs: state.bankedMs, runningSince: state.runningSince, marks: marks.count, headline: MeetingsWords.headline(state.stage, kind: kind), words: .init( pause: MeetingsWords.line("recorder.pause"), resume: MeetingsWords.line("recorder.resume"), stop: MeetingsWords.line("recorder.stop"), mark: MeetingsWords.line("recorder.mark")))) } private func sentence(_ error: Error) -> String { (error as? LocalizedError)?.errorDescription ?? String(describing: error) } } /// What a recording is (meeting or memo) and the moments marked in it, in a /// small file beside its audio, so a recording the app never finished keeps /// both. struct MeetingsMarks: Codable, Equatable { var kind: MeetingKind var marks: [Int] /// `.marks.json`, beside it: the core's recordings share /// one folder, so each take's file is named for its own audio. static func url(besideAudio audio: String) -> URL { let file = URL(fileURLWithPath: audio) return file.deletingLastPathComponent().appending(path: file.deletingPathExtension().lastPathComponent + ".marks.json") } static func write(_ held: MeetingsMarks, besideAudio audio: String) { guard let data = try? JSONEncoder().encode(held) else { return } try? data.write(to: url(besideAudio: audio), options: .atomic) } /// The file holds a kind and the marks' offsets, written by this app: /// read through a handle, no further than `largest` bytes. static let largest = 64 * 1024 static func read(besideAudio audio: String) -> MeetingsMarks? { guard let handle = try? FileHandle(forReadingFrom: url(besideAudio: audio)) else { return nil } defer { try? handle.close() } guard let data = try? handle.read(upToCount: largest), data.count < largest else { return nil } return try? JSONDecoder().decode(MeetingsMarks.self, from: data) } static func remove(besideAudio audio: String) { try? FileManager.default.removeItem(at: url(besideAudio: audio)) } } #endif