// Transcribing on this phone (voice plan, 17 Nov 2026): one of the// swappable steps with one interface (audio in, the transcript out: timed// lines with speaker labels), run while the phone is CHARGING; the Mac does// it sooner when it is on. Every rule is the core's (`apps/meetings/CORE.md`):// `meetings.next` names the next waiting recording, the object is asked for// it (`meeting_claim { id, by: phone }`, a 409 when the Mac holds it drops// the job), `meetings.next { id }` hands this phone that one,// `meetings.windows` cuts it into overlapping windows, each window is heard// by the plan's engine, `meetings.merge` makes them one transcript and// `meetings.transcribed` lands it.//// THE ENGINE is the voice engine layer's (`CottonVoice`):// the second-pass engine `voice.plan` names for the meeting's language, a// sherpa model from the shared store or `apple.speech`, fed 16 kHz mono// samples, answering timed words. Lines are cut from the words at a pause// or a sentence's end. No speaker separation runs on the phone yet, so a// window's lines are all S1 and `meetings.merge` keeps them one speaker.#if os(iOS)import AVFoundationimportCottonKitimportCottonVoiceimportFoundation/// The step's engine seam: a window of 16 kHz samples in, timed words out.protocolMeetingWindowHearing: Sendable {/// `<where>:<engine>`, as `transcribed_by` says it.var by: String { get }func hear(_ samples: [Float], offsetMs: Int) asyncthrows -> VoiceHearing}/// The plan's second-pass engine.structPlannedHearing: MeetingWindowHearing {let by: Stringlet engine: any SecondVoiceEnginefunc hear(_ samples: [Float], offsetMs: Int) asyncthrows -> VoiceHearing {tryawait engine.transcribe(samples, offsetMs: offsetMs) }/// The engine `voice.plan` names for this meeting. @MainActorstaticfunc planned(core: any CottonCalling, meeting: String) asyncthrows -> (PlannedHearing, [String]) {let plan = tryawait core.call(CottonMethod.voicePlan,VoicePlanRequest(surface: "meeting", table: MeetingsTable.meeting, record: meeting, mode: .dictate),as: VoicePlan.self)var choice = plan.second ?? plan.livelet store = VoiceModelStore.currentawait store.attach(core)let engine: any SecondVoiceEnginedo { engine = tryawaitVoiceEngines.second(choice, language: plan.languages.first, store: store) } catchwhere choice.engine != VoiceEngineChoice.appleSpeech {// The plan's model is not on this phone yet: the phone's own// recogniser reads it now rather than leaving the meeting waiting.Log.warn("meetings: phone step: \(choice.engine) is not here (\(error)); the phone's own recogniser reads it") choice = VoiceEngineChoice(engine: VoiceEngineChoice.appleSpeech) engine = tryawaitVoiceEngines.second(choice, language: plan.languages.first, store: store) }tryawait engine.prepare()return (PlannedHearing(by: "phone:\(choice.engine)", engine: engine), plan.languages) }}@MainActorfinalclassMeetingsPhoneStep {staticlet shared = MeetingsPhoneStep()/// The meeting this phone is transcribing now, for its card to say so.private(set) var current: String?privatevar running = false/// A test's engine in place of the plan's.var hearing: (any MeetingWindowHearing)?/// Where the step notes the meeting it holds, so a step the system ended/// mid-way is said at the next start rather than left `transcribing`.var notes: UserDefaults = .standardstaticlet holdingKey = "meetings.phone-step.holding"staticlet claimedKey = "meetings.phone-step.claimed"/// A meeting a step that was ended still held: failed with its why (the/// page offers Try again), and the object's claim let go. The core keeps/// no holder on a `transcribing` row, so only this phone's own note can/// tell its step from the Mac's.func settleInterrupted(core: any CottonCalling) async {guard !running, let held = notes.string(forKey: Self.holdingKey) else { return }let claimed = notes.bool(forKey: Self.claimedKey)Log.warn("meetings: phone step: \(held) was held by a step that was ended")let meetings = MeetingsCore(core: core)try? await meetings.transcriptionFailed(held, why: "engine_failed")if claimed { await meetings.giveUp(held, why: "engine_failed") } letGo() }privatefunc hold(_ meeting: String, claimed: Bool) { notes.set(meeting, forKey: Self.holdingKey) notes.set(claimed, forKey: Self.claimedKey) }privatefunc letGo() { notes.removeObject(forKey: Self.holdingKey) notes.removeObject(forKey: Self.claimedKey) }/// Transcribe what the core hands this phone: while charging any, off power what the core says a phone may take/// (`meetings.next` with the battery: a short recording at 30% or more, CONTRACT.md "Recordings"). Answers how/// many transcripts it landed; stops at the first that does not land. @discardableResultfunc drain(core: any CottonCalling, force: Bool = false) async -> Int {guard !running else { return0 }await settleInterrupted(core: core) running = truedefer { running = false; current = nil }var landed = 0whileawait once(core: core, force: force) { landed += 1 }return landed }/// One recording the core hands this phone, transcribed and landed./// False when there is none, or it did not land (and the core was told).func drainOnce(core: any CottonCalling) async -> Bool {guard !running else { returnfalse }await settleInterrupted(core: core) running = truedefer { running = false; current = nil }returnawait once(core: core, force: true) }/// One recording: the core names a candidate (`peek`), the object is/// asked for it (`meeting_claim`) and a 409 drops it for the next, then/// the core hands this phone that one (`next { id }`).privatefunc once(core: any CottonCalling, force: Bool) async -> Bool {let meetings = MeetingsCore(core: core)let charging = force || MeetingsPower.charginglet battery = charging ? nil : MeetingsPower.batteryvar refused: [String] = []whilelet candidate = await meetings.next(charging: charging, battery: battery, peek: true, except: refused) {// A core that named a refused one again has nothing else to give.guard !refused.contains(candidate.meeting) else { returnfalse }let claim = await meetings.claim(candidate.meeting)if claim == .heldByAnother { refused.append(candidate.meeting)continue }guardlet next = await meetings.next(charging: charging, battery: battery, id: candidate.meeting) else { returnfalse } current = next.meeting hold(next.meeting, claimed: claim == .claimed)defer { letGo() }do {tryawait transcribe(next.meeting, audio: next.audio, core: core)returntrue } catch {// Said, rather than left standing claimed by a step that// stopped: the card says why and offers Try again.Log.warn("meetings: phone step: \(next.meeting) was not transcribed: \(error)")try? await meetings.transcriptionFailed(next.meeting, why: "engine_failed")if claim == .claimed { await meetings.giveUp(next.meeting, why: "engine_failed") }returnfalse } }returnfalse }privatefunc transcribe(_ meeting: String, audio: URL, core: any CottonCalling) asyncthrows {let meetings = MeetingsCore(core: core)let hearing: any MeetingWindowHearingvar languages: [String] = []iflet given = self.hearing { hearing = given } else {let planned = tryawaitPlannedHearing.planned(core: core, meeting: meeting) hearing = planned.0 languages = planned.1 }let file = try AVAudioFile(forReading: audio)let durationMs = Int(Double(file.length) / file.processingFormat.sampleRate * 1000)let windows = await meetings.windows(durationMs: durationMs) ?? [MeetingWindow(index: 0, start_ms: 0, end_ms: durationMs)]var heard: [MeetingsCore.HeardWindow] = []for window in windows {let samples = tryMeetingsAudioWindow.samples(of: file, fromMs: window.start_ms, toMs: window.end_ms)let words = tryawait hearing.hear(samples, offsetMs: window.start_ms)let language = words.language ?? languages.first heard.append(.init( index: window.index, start_ms: window.start_ms, end_ms: window.end_ms, language: language, lines: MeetingsLines.cut(words.words, speaker: nil, language: language))) }let merged = tryawait meetings.merge(heard)let transcript = merged.by.isEmpty ? MeetingTranscript(by: hearing.by, languages: merged.languages, speakers: merged.speakers, lines: merged.lines) : mergedtryawait meetings.transcribed(meeting: meeting, transcript) }}/// A window of a recording as 16 kHz mono samples.enumMeetingsAudioWindow {staticlet rate = 16_000.0staticfunc samples(of file: AVAudioFile, fromMs: Int, toMs: Int) throws -> [Float] {let source = file.processingFormatlet first = AVAudioFramePosition(Double(fromMs) / 1000 * source.sampleRate)let count = AVAudioFrameCount(max(0, Double(toMs - fromMs) / 1000 * source.sampleRate))guard count > 0, first < file.length,let input = AVAudioPCMBuffer(pcmFormat: source, frameCapacity: count),let target = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: rate, channels: 1, interleaved: false),let converter = AVAudioConverter(from: source, to: target)else { return [] } file.framePosition = firsttry file.read(into: input, frameCount: min(count, AVAudioFrameCount(file.length - first)))guardlet output = AVAudioPCMBuffer( pcmFormat: target, frameCapacity: AVAudioFrameCount(Double(input.frameLength) * rate / source.sampleRate) + 1024)else { return [] }var fed = falsevar failure: NSError? converter.convert(to: output, error: &failure) { _, status inif fed { status.pointee = .endOfStreamreturnnil } fed = true status.pointee = .haveDatareturn input }iflet failure { throw failure }guardlet channel = output.floatChannelData?[0] else { return [] }returnArray(UnsafeBufferPointer(start: channel, count: Int(output.frameLength))) }}/// Timed words cut into a transcript's lines: at a pause of `pauseMs` or/// more, or after a word that ends a sentence once the line has some length.enumMeetingsLines {staticlet pauseMs = 900staticlet sentenceAfterMs = 4_000staticfunc cut(_ words: [VoiceWord], speaker: String?, language: String?) -> [MeetingTranscript.Line] {var lines: [MeetingTranscript.Line] = []var held: [VoiceWord] = []func close() {guardlet first = held.first, let last = held.last else { return }let text = held.map(\.w).joined(separator: " ").trimmingCharacters(in: .whitespaces)if !text.isEmpty { lines.append(.init(speaker: speaker, start_ms: first.startMs, end_ms: last.endMs, text: text, language: language)) } held = [] }for word in words {iflet last = held.last, word.startMs - last.endMs >= pauseMs { close() } held.append(word)iflet first = held.first, let end = word.w.last, ".?!".contains(end), word.endMs - first.startMs >= sentenceAfterMs { close() } } close()return lines }}#endif