// The real recogniser: Apple's on-device `DictationTranscriber` over// `SpeechAnalyzer` (iOS 26 / macOS 26), fed by `AVAudioEngine`.//// The platform half of `DictationModel` — the speech APIs spoken directly, with// no library wrapping them. It is the ONE file in this family that imports// `Speech` and `AVFoundation`, which is what keeps the engine above it testable// with no microphone, no permission prompt and no simulator. There is no other// engine and no network rung: `SFSpeechRecognizer` is gone (14 Oct 2026), and a// device with no on-device model for the person's language says so// (`dictationUnavailable`) rather than sending audio anywhere.//// The session's settings: the person's language with the device's region// (``DictationHints/language``, resolved by `CottonSpeech.SpeechModel`, the one// place the Mac's meeting transcriber also chooses a locale and fetches a// model), volatile results as the preview, punctuation on, per-word confidence// on, and the hints as `AnalysisContext.contextualStrings`, one tag per group.//// **A LONG DICTATION IS MANY RESULTS, AND THIS FILE IS WHERE THAT IS SEEN.** The// transcriber reports a stretch of audio as VOLATILE results, each restating// the stretch from its own beginning, and then FINALISES it; every volatile// result after that describes the NEXT stretch from empty. So a volatile// result is a ``SpeechEvent/partial(_:)`` and a final one is a// ``SpeechEvent/segment(_:words:)`` — the only chance the model gets to keep// that stretch's words. When the input ends the results stream ends, and that// is the session's ``SpeechEvent/ended``.//// THREE THINGS THIS FILE OWNS://// • **The audio-session interruption.** `AVAudioSession.interruptionNotification`// is the reason a call, Siri or an alarm ENDS a dictation with its words// instead of looping the restart ladder into an empty field (2026-09-04).// • **The meter.** AVFoundation hands over samples, so the tap computes RMS// in dBFS and `DictationLevel.fold(decibels:)` lands it on the 0…1 the// listening line's waveform wants.// • **Giving the microphone back.** `deinit` is the only thing that runs when// a screen goes away without a tap, and it must give the session back or// other apps stay ducked and the orange recording indicator stays lit after// the screen that owned it is gone. See ``AudioSessionHold``.//// It satisfies BOTH seams — `SpeechRecognizing` and `AudioLevelSource` —// because only the object holding the audio tap can measure what is reaching// the microphone. Two objects would mean two taps on one input node, which is// not a thing `AVAudioEngine` allows.//// **CONSTRUCTING ONE OF THESE IS FREE, AND THAT IS A RULE.** It builds no// `AVAudioEngine`, no analyzer, no notification observer and no give-back:// `init` stores where the audio comes from and an authority, and wires the// relay. The reason is a crash. `AVAudioEngine` instantiates and CACHES its// input node's hardware format the first time `inputNode` is touched, and under// the launch-default `.soloAmbient` category that format is 0 Hz and 0 channels// — `AVAudioIONodeImpl` raises an Objective-C exception over it, which Swift// cannot catch and which takes the process down with SIGABRT and no Bugsink// event. So the whole file keeps ONE order://// ask (the gate) → set the category and activate the session → construct// the engine → read the input format → install the tap → start, the audio// held → the model (locale, assets, format) → the held audio, then the rest//// The microphone comes before the model so no word said after the tap waits// on it (``HeldAudio``; owner's phone, 286).//// **AND EVERY BLOCK THIS FILE HANDS AN OS API IS `@Sendable`.** `AVAudioNodeTapBlock`// is a plain ObjC block, so a closure literal written for it inside a// `@MainActor` method inherits main-actor isolation, Swift 6 emits an executor// check in its preamble, and the real-time audio thread trips it with// `EXC_BREAKPOINT` (build 138, the first mic tap of every session). The audio// thread's work lives in ``AudioTapSink``, which has no actor to inherit; the// results are read in a task that has none either.//// **ONE CONSTRUCTOR.** Nothing builds this but ``DictationModel/live(audio:isOnCall:)``// — every microphone in the app goes through it, and a file goes through it// for the accuracy harness (`scripts/voicegate`), so what is measured is what// ships. Guards: `CapabilityGateSweepTests` (the OS is asked in one file, this// object is built in one place and never in an `init`), `CapabilityGateTests`,// `SpeechPermissionIsolationTests`, `DictationTapIsolationTests`.import AVFoundationimportCottonKitimportCottonSpeechimportFoundationimportSpeechimport os// MARK: - The one ordered channel to the main actor/// A serial hand-over from any thread to the main actor.////// **Order is the whole point.** The first cut of this file spawned a fresh/// `Task { @MainActor in … }` per audio buffer (~43 a second) and per/// recognition callback. Unstructured tasks enqueued on an actor are *not*/// order-guaranteed, and a `final` that overtook a trailing `partial` would/// defeat the "an empty final must never erase the partials" rule/// `DictationModel.handle(_:)` implements — with the words as the price. One/// `AsyncStream` drained by ONE task delivers in the order things were sent,/// and costs one task for the object's life rather than forty a second.////// Generic and free of `Speech` so it is unit-testable on its own:/// `DictationModelTests`' "the ordered hand-over" block sends from several/// threads and asserts the sequence that comes out.finalclassMainActorRelay<Value: Sendable>: @unchecked Sendable {privatelet stream: AsyncStream<Value>privatelet feed: AsyncStream<Value>.Continuation/// The drain, under the lock because ``onValue(_:)`` and ``close()`` may be/// called from different threads — the second of them from a `deinit`.privatelet lock = NSLock()privatevar pump: Task<Void, Never>?init() { (stream, feed) = AsyncStream<Value>.makeStream(bufferingPolicy: .unbounded) }/// Start delivering. Everything sent before this call is buffered and/// arrives first, which is what lets the owner attach a sink that captures/// itself weakly after its own stored properties are set.func onValue(_ sink: @escaping @MainActor @Sendable (Value) -> Void) {let started = Task { @MainActor [stream] inforawait value in stream { sink(value) } } lock.withLock { pump = started } }/// Hand a value over. Safe from any thread; delivery is IN THIS ORDER.func send(_ value: Value) { feed.yield(value) }/// Stop delivering. Idempotent, and safe from a `deinit`.func close() { feed.finish()let started = lock.withLock { () -> Task<Void, Never>? inlet taken = pump pump = nilreturn taken } started?.cancel() }deinit { feed.finish() }}// MARK: - What a `deinit` can still reach/// The microphone, held OUTSIDE the actor so a `deinit` can give it back.////// A `@MainActor` class's `deinit` is **nonisolated** under Swift 6: it may not/// touch `engine`, `request` or `task`. But the one case this whole arm exists/// for — a screen dismissed programmatically, a host popped, the model/// deallocated — is exactly the case where nothing else runs. So the/// interruption-observer token and the give-back live here, reached under this/// object's own lock, and `@unchecked Sendable` states that.////// `release()` is TERMINAL and idempotent: it removes the observer and gives/// the audio session back. The per-session teardown is/// `SystemSpeechRecogniser.teardown()`, which must NOT remove the observer —/// the next session still needs to hear an interruption.finalclassAudioSessionHold: @unchecked Sendable {privatelet lock = NSLock()privatevar observer: NSObjectProtocol?privatevar giveBack: (() -> Void)?/// Terminal, so a late ``arm(_:)`` cannot resurrect a hold that has already/// given the microphone back.privatevar released = false/// `giveBack` takes the tap down, stops the engine and deactivates the/// session. It is a closure rather than the engine itself so this type/// carries no `AVFoundation` state and/// `DictationModelTests.testTheAudioSessionHoldGivesTheMicrophoneBackExactlyOnce`/// can prove the once-only rule with a counter.init(giveBack: (() -> Void)? = nil) {self.giveBack = giveBack }/// Arm the give-back after the fact — which is the only way it can be/// armed now.////// The closure closes over an `AVAudioEngine`, and the engine is not built/// until `start(...)` has a granted microphone and an ACTIVE session. There/// is nothing to give back before that, and a hold armed in `init` was/// precisely a `deinit` reaching for an input node no category had ever/// been set on. The FIRST arm wins: a second engine in one object's life is/// a bug rather than a state.func arm(_ giveBack: @escaping () -> Void) { lock.withLock {guardself.giveBack == nil, !released else { return }self.giveBack = giveBack } }func observe(_ token: NSObjectProtocol) { lock.withLock { observer = token } }/// Give the microphone back — once, from any thread.func release() {let (token, work) = lock.withLock { () -> (NSObjectProtocol?, (() -> Void)?) inlet taken = (observer, giveBack) observer = nil giveBack = nil released = truereturn taken }iflet token { NotificationCenter.default.removeObserver(token) } work?() }}/// The meter's throttle.////// The tap fires ~43 times a second and a waveform cannot read faster than/// the display. One reading per ``interval`` reaches the main actor; the rest/// are dropped on the audio thread, where dropping is free.finalclassMeterThrottle: @unchecked Sendable {/// 50 ms — twenty readings a second, comfortably past what the eye reads/// off a dot and comfortably under the tap's own rate.staticlet interval: TimeInterval = 0.05privatelet lock = NSLock()privatevar last: TimeInterval = -.greatestFiniteMagnitude/// `true` when enough time has passed for another reading, and the clock/// moves on the way past.func admits(_ now: TimeInterval) -> Bool { lock.withLock {guard now - last >= MeterThrottle.interval else { returnfalse } last = nowreturntrue } }/// A new session reads immediately rather than waiting out the last one's/// interval.func reset() { lock.withLock { last = -.greatestFiniteMagnitude } }}// MARK: - What crosses from the audio thread/// What the audio thread and the results reader hand up.////// Every case is `Sendable` and already reduced: neither a transcriber result/// nor an `Error` crosses.////// **At FILE scope, not nested in the recogniser.** It is built on the audio/// thread (``AudioTapSink``) and in the results reader; a type nested inside a/// `@MainActor` class is a type whose memberwise init the compiler may isolate/// to that actor, and the one thing this value must never need is the main/// actor.structInbound: Sendable {/// Which session this came from. A buffer already handed to the stream/// when `stop()` ran must never land in the NEXT session's transcript.let session: Intlet event: EventenumEvent: Sendable {/// The model is ready and the microphone is ours.case startedcase level(Double)/// A volatile result: the stretch in progress, restated from its start.case partial(String)/// A finalised result: the stretch is settled and the next starts empty.case settled(String, [HeardWord])/// The results stream ended: every input was finalised.case finished/// The session could not go on. `unavailable` is the device having no/// model for the language at all.case failed(unavailable: Bool) }}/// What the tap hands its buffers to.////// One method. It exists so ``AudioTapSink`` can be driven off the main thread/// by a test that owns no microphone and no analyzer: the thing under test is/// the ISOLATION, and a test that had to build a real `Speech` object to prove/// it would not run on a machine with none.protocolRecognitionBuffering: AnyObject {func append(_ buffer: AVAudioPCMBuffer)}/// The microphone's audio from the tap on, held until the model can take it.////// **The microphone opens at the tap; the model may come later.** A tap on a/// cold or warming model waited for the model before it opened the microphone,/// while the button already said it was listening — and whatever the person/// said in that gap was never heard ("Nothing came through the microphone",/// owner's phone, 286). Now every buffer from the tap on is kept here, copied/// (the engine reuses its own), and handed to the model's feed in the order it/// was heard the moment the feed exists; after that each buffer goes straight/// through.////// Called from the audio thread and from the main actor, so one lock guards/// the queue and the hand-over; the feed it hands to is used under that lock/// only, which keeps `AnalyzerFeed`'s one-thread-at-a-time claim./// Guard: `DictationHeldAudioTests`.finalclassHeldAudio: RecognitionBuffering, @unchecked Sendable {privatelet lock = NSLock()privatevar held: [AVAudioPCMBuffer] = []privatevar target: (any RecognitionBuffering)?func append(_ buffer: AVAudioPCMBuffer) { lock.lock()defer { lock.unlock() }iflet target { target.append(buffer) } elseiflet copy = Self.copy(buffer) { held.append(copy) } }/// The model is ready: everything held goes to it first, in order, and/// every later buffer goes straight through. Answers how many were held. @discardableResultfunc attach(_ feed: any RecognitionBuffering) -> (buffers: Int, seconds: Double) { lock.lock()defer { lock.unlock() }let seconds = held.reduce(0) { $0 + Double($1.frameLength) / $1.format.sampleRate }let count = held.countfor buffer in held { feed.append(buffer) } held = [] target = feedreturn (count, seconds) }privatestaticfunc copy(_ buffer: AVAudioPCMBuffer) -> AVAudioPCMBuffer? {guardlet copy = AVAudioPCMBuffer(pcmFormat: buffer.format, frameCapacity: buffer.frameLength) else { returnnil } copy.frameLength = buffer.frameLengthlet frames = Int(buffer.frameLength)let channels = Int(buffer.format.channelCount)let planes = buffer.format.isInterleaved ? 1 : channelslet samples = buffer.format.isInterleaved ? frames * channels : framesiflet from = buffer.floatChannelData, let to = copy.floatChannelData {for plane in0 ..< planes { to[plane].update(from: from[plane], count: samples) } } elseiflet from = buffer.int16ChannelData, let to = copy.int16ChannelData {for plane in0 ..< planes { to[plane].update(from: from[plane], count: samples) } } elseiflet from = buffer.int32ChannelData, let to = copy.int32ChannelData {for plane in0 ..< planes { to[plane].update(from: from[plane], count: samples) } } else {returnnil }return copy }}/// Everything the audio tap does, in a type that has NO actor.////// **THE TAP BLOCK IS NOT MAIN-ACTOR CODE, AND WRITING IT INLINE MADE IT ONE.**/// See the file header: the body lives here, where it has no isolation to/// inherit, and the block in `start(...)` is written `@Sendable` so it cannot/// acquire one again.////// Guards: `DictationTapIsolationTests` (this object is driven off the main/// thread, and the block is swept for `@Sendable`).finalclassAudioTapSink: @unchecked Sendable {privatelet request: any RecognitionBufferingprivatelet relay: MainActorRelay<Inbound>privatelet throttle: MeterThrottle/// Stamped onto every reading, so a buffer already in flight when this/// session ends cannot land in the next one's transcript.privatelet session: Intinit( request: any RecognitionBuffering, relay: MainActorRelay<Inbound>, throttle: MeterThrottle, session: Int ) {self.request = requestself.relay = relayself.throttle = throttleself.session = session }/// One buffer, from the real-time audio thread.func receive(_ buffer: AVAudioPCMBuffer) { request.append(buffer)// Dropped HERE, on the audio thread, where dropping is free.guard throttle.admits(CFAbsoluteTimeGetCurrent()) else { return } relay.send(Inbound(session: session, event: .level(DictationLevel.meter(buffer)))) }}/// The analyzer's input: buffers in the microphone's (or the file's) format,/// converted to the one the model wants and handed to the analyzer's stream.////// Used from ONE thread at a time — the audio thread for a microphone, the/// reading task for a file — which is the whole of the unchecked claim:/// `AVAudioConverter` is not `Sendable` and needs no lock when only one thread/// ever calls it.@available(iOS 26.0, macOS 26.0, *)finalclassAnalyzerFeed: RecognitionBuffering, @unchecked Sendable {let stream: AsyncStream<AnalyzerInput>privatelet feed: AsyncStream<AnalyzerInput>.Continuationprivatelet format: AVAudioFormatprivatevar converter: AVAudioConverter?init(format: AVAudioFormat) {self.format = format (stream, feed) = AsyncStream<AnalyzerInput>.makeStream(bufferingPolicy: .unbounded) }func append(_ buffer: AVAudioPCMBuffer) {guardlet converted = convert(buffer) else { return } feed.yield(AnalyzerInput(buffer: converted)) }/// No more audio: the analyzer finalises what it has and its results end.func finish() { feed.finish() }privatefunc convert(_ buffer: AVAudioPCMBuffer) -> AVAudioPCMBuffer? {if buffer.format == format { return buffer }if converter == nil || converter?.inputFormat != buffer.format { converter = AVAudioConverter(from: buffer.format, to: format)// The model's own guidance: prime nothing, so the first stretch// starts on the first sample rather than after a primer. converter?.primeMethod = .none }guardlet converter else { returnnil }let ratio = format.sampleRate / buffer.format.sampleRatelet capacity = AVAudioFrameCount((Double(buffer.frameLength) * ratio).rounded(.up)) + 1guardlet out = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: capacity) else { returnnil }var given = falsevar error: NSError?let status = converter.convert(to: out, error: &error) { _, state inif given { state.pointee = .noDataNowreturnnil } given = true state.pointee = .haveDatareturn buffer }guard status != .error, out.frameLength > 0else { returnnil }return out }}/// Where a dictation's audio comes from: the microphone, or — for the accuracy/// harness, which must measure the engine that ships — a recording, played in/// at the pace it was spoken.publicenumDictationAudio: Sendable, Equatable {case microphonecase file(URL)}/// A device whose system has no on-device dictation model (older than iOS 26 //// macOS 26): every dictation is `dictationUnavailable`, said once, at the tap./// It is not an engine — it never hears anything.@MainActorfinalclassNoDictation: SpeechRecognizing {func onEvent(_ sink: @escaping SpeechEventSink) {}func access() async -> CapabilityGateResult { .blocked(.speech, .unavailable) }func prepare(_ hints: DictationHints) {}func start(_ hints: DictationHints) {}func stop() {}func cancel() {}}// MARK: - The warm slot/// What a warm model was prepared FOR: the language and the person's own/// compiled model. The contextual strings are not part of it — they are set/// again on the tap when they moved, which costs nothing like a model load.structWarmKey: Equatable, Sendable {let locale: Stringlet model: String?init(_ hints: DictationHints) { locale = hints.locale.identifier model = hints.model?.fingerprint }}/// The one prepared model a recogniser keeps between taps.////// Pure and generic so the rule it keeps — a tap takes what was prepared for/// its own language and model and nothing else, and takes it once — is tested/// without a microphone (`DictationWarmTests`).structWarmSlot<Payload> {privatevar held: (key: WarmKey, payload: Payload)?func holds(_ key: WarmKey) -> Bool { held?.key == key }mutatingfunc fill(_ key: WarmKey, _ payload: Payload) { held = (key, payload) }/// The prepared payload for this key, emptied on the way out (an analyzer/// runs one session). A slot warmed for another key is dropped.mutatingfunc take(for key: WarmKey) -> Payload? {defer { held = nil }guardlet held, held.key == key else { returnnil }return held.payload }}/// A model prepared to analyze: everything a session needs before audio.@available(iOS 26.0, macOS 26.0, *)structWarmModel: @unchecked Sendable {let transcriber: DictationTranscriberlet analyzer: SpeechAnalyzerlet format: AVAudioFormat/// The contextual strings it was prepared with.let groups: [DictationHints.Group]}// MARK: - The recogniser@available(iOS 26.0, macOS 26.0, *)@MainActorfinalclassSystemSpeechRecogniser: SpeechRecognizing, AudioLevelSource {privatelet audio: DictationAudio/// The OS, behind the one seam allowed to ask it.privatelet capabilities: any CapabilityAuthority/// **Optional, and nil until the first session.** Touching an engine's/// `inputNode` before the audio session has a category is the NSException/// this file's header names; an engine that does not exist cannot be/// touched by a teardown, a `stop()` or a `deinit`.privatevar engine: AVAudioEngine?privatelet relay = MainActorRelay<Inbound>()privatelet throttle = MeterThrottle()/// Built empty and ARMED with the engine — construction is free.privatelet hold = AudioSessionHold()privatevar analyzer: SpeechAnalyzer?privatevar feed: AnalyzerFeed?/// The microphone's audio from the tap until the feed exists.privatevar held: HeldAudio?/// The session's model is still coming: a stop now waits for it and/// finishes on what the microphone held.privatevar awaitingModel = false/// The first words of this session were logged.privatevar spoke = false/// The session's setup, the results reader and (for a file) the player.privatevar work: [Task<Void, Never>] = []privatevar events: SpeechEventSink?privatevar levels: AudioLevelSink?/// One `ended` per session, whatever raced to end it.privatevar ended = true/// `stop()` was asked for: the input is finished and the results stream's/// end is the session's.privatevar stopping = false/// Bumped by every ``start(_:)``, stamped onto everything the tap and the/// reader hand up.privatevar session = 0/// A tap IS installed on the input node. Only a tap that was installed is/// ever removed — `removeTap` is the call that touches `inputNode`, and/// touching it out of order is the crash.privatevar tapInstalled = false/// THIS object activated the audio session. `setActive(false)` is/// process-wide, so an object that never activated one must never/// deactivate it out from under whoever did.privatevar sessionActivated = false/// The interruption observer is armed once, with the first session — never/// in `init`, where there is no session to interrupt.privatevar observing = false/// The gate said yes; a failure after it is not a refusal.privatevar permitted = false/// What the engine was handed, in the order it was handed over: the/// module, the context READ BACK from the analyzer, the start, the first/// audio. Nil in the app; the accuracy harness sets it to prove the hints/// reach the model before a single buffer does.staticvar trace: ((String) -> Void)?privatestaticlet log = Logger(subsystem: "com.cottondb.dictation", category: "listen")/// The model the next tap takes (``prepare(_:)``), and the one coming./// **One for the process, not one per recogniser**: Home warms it, and/// the next microphone takes it, so the voice note is as quick as the/// record button.privatestaticvar slot = WarmSlot<WarmModel>()privatestaticvar warming: Task<WarmModel?, Never>?privatestaticvar warmingKey: WarmKey?/// What the last session listened for: the slot is warmed again for it/// when a session ends, so the tap after this one is warm too.privatevar lastHints: DictationHints?/// When this session's ``start(_:)`` ran, for the log's split of the/// tap's cost into the model and the microphone.privatevar tappedAt: CFAbsoluteTime = 0/// **Free.** No engine, no analyzer, no observer, no give-back: see the/// file header. Built ONLY by ``DictationModel/live(audio:isOnCall:)``.init( audio: DictationAudio = .microphone, capabilities: any CapabilityAuthority = SystemCapabilityAuthority() ) {self.audio = audioself.capabilities = capabilities// Every stored property is set, so the sink may capture `self`. relay.onValue { [weakself] inbound inself?.receive(inbound) } }/// **The only thing that runs when a screen goes away without a tap.**/// Nonisolated, so it touches only the two `Sendable` `let`s a Swift 6/// `deinit` is allowed to read. **On an object that never started, this/// does NOTHING** — the hold is un-armed and holds no observer.deinit { relay.close() hold.release() }// MARK: - SpeechRecognizingfunc onEvent(_ sink: @escaping SpeechEventSink) { events = sink }/// **The gate, and the first step of the file's one order.**////// Microphone first, then speech recognition: the order the two prompts/// appeared in for the owner and the order Apple's own dictation asks in./// `gate` stops at the first refusal. A recording asks for neither — there/// is no microphone to open and nothing leaves the device.func access() async -> CapabilityGateResult {guard audio == .microphone else { permitted = truereturn .ready }let result = await capabilities.gate([.microphone, .speech]) permitted = result.isReadyreturn result }/// **The microphone at the tap, then the model**: the microphone opens/// here and its audio is held (``HeldAudio``) while the model gets its/// locale, assets and format, all asked of the system asynchronously;/// `started` is said when the microphone is genuinely running, and the/// held audio reaches the analyzer the moment it starts. No word said/// after the tap waits on the model (voiceline, 16 Oct 2026).////// **A tap takes the warm slot.** Everything before the microphone — the/// locale, the assets, the format, the context and `prepareToAnalyze` —/// is what made a tap take four seconds (owner, build 280), so/// ``prepare(_:)`` does it when the screen comes up, and the tap only/// opens the microphone. A slot still warming is awaited, never built/// twice; with nothing warm the tap builds cold, and the log says which.func start(_ hints: DictationHints) { teardown() ended = false stopping = false session += 1 throttle.reset()let stamp = session tappedAt = CFAbsoluteTimeGetCurrent() lastHints = hintslet key = WarmKey(hints)let path: Stringlet model: Task<WarmModel?, Never>iflet ready = Self.slot.take(for: key) { path = "warm" model = Task { ready } } elseiflet coming = Self.warming, Self.warmingKey == key { path = "warming" model = coming } else { path = "cold" model = Task { awaitSelf.build(hints) } }Self.warming = nilSelf.warmingKey = nilSelf.log.notice("listen: \(path, privacy: .public) start")Self.trace?("path \(path)") spoke = false awaitingModel = true// The microphone first: what is said from the tap on is held until the// model takes it, so no word waits on the model (``HeldAudio``).ifcase .microphone = audio {let held = HeldAudio()self.held = held openMicrophone(held, stamp: stamp)guard !ended else { return } } work.append(Task { [weakself] inguardlet prepared = await model.value else {self?.fail(unavailable: true, stamp: stamp)return }awaitself?.run(prepared, hints: hints, stamp: stamp) }) }/// Fill the warm slot for these hints, unless it is already warm or/// warming for them. Never touches the microphone or the audio session.func prepare(_ hints: DictationHints) { lastHints = hintslet key = WarmKey(hints)guard !Self.slot.holds(key), Self.warmingKey != key else { return }Self.warmingKey = keylet coming = Task { awaitSelf.build(hints) }Self.warming = comingTask {let prepared = await coming.valueguardSelf.warmingKey == key else { return }Self.warming = nilSelf.warmingKey = niliflet prepared { Self.slot.fill(key, prepared) } } }/// Everything before the microphone, in the file's one order.privatestaticfunc build(_ hints: DictationHints) async -> WarmModel? {guardlet locale = awaitSpeechModel.locale(DictationTranscriber.self, for: hints.locale) else {returnnil }// The person's own compiled model, when it was compiled for exactly// this locale; the contextual strings below stay either way.var content: Set<DictationTranscriber.ContentHint> = []iflet model = hints.model, model.locale == locale.identifier { content.insert(.customizedLanguage(modelConfiguration: SFSpeechLanguageModel.Configuration( languageModel: model.languageModel, vocabulary: model.vocabulary))) }let transcriber = DictationTranscriber( locale: locale, contentHints: content, transcriptionOptions: [.punctuation], reportingOptions: [.volatileResults], attributeOptions: [.transcriptionConfidence] )// The model stays loaded for the process: the next analyzer, after// this one has finished, prepares without loading it again.let analyzer = SpeechAnalyzer( modules: [transcriber], options: SpeechAnalyzer.Options(priority: .userInitiated, modelRetention: .processLifetime))do {tryawaitSpeechModel.install([transcriber])guardlet format = awaitSpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [transcriber])else { returnnil }tryawait analyzer.setContext(Self.context(hints))iflet trace { trace("module \(type(of: transcriber)) locale \(locale.identifier)") trace("language model \(content.isEmpty ? "none" : String(hints.model?.fingerprint.prefix(12) ?? ""))") }tryawait analyzer.prepareToAnalyze(in: format)returnWarmModel(transcriber: transcriber, analyzer: analyzer, format: format, groups: hints.groups) } catch {returnnil } }privatestaticfunc context(_ hints: DictationHints) -> AnalysisContext {let context = AnalysisContext()for group in hints.groups where !group.terms.isEmpty { context.contextualStrings[AnalysisContext.ContextualStringsTag(group.tag)] = group.terms }return context }/// A prepared model, then the microphone.privatefunc run(_ prepared: WarmModel, hints: DictationHints, stamp: Int) async {let transcriber = prepared.transcriberlet analyzer = prepared.analyzerdo {// The words on screen moved since the slot was warmed: the// context is set again, which costs nothing like a model load.if prepared.groups != hints.groups {tryawait analyzer.setContext(Self.context(hints)) }iflet trace = Self.trace {let held = await analyzer.context.contextualStringsfor tag in held.keys.sorted(by: { $0.rawValue < $1.rawValue }) { trace("context \(tag.rawValue): \(held[tag, default: []].joined(separator: ", "))") } } } catch {return fail(unavailable: true, stamp: stamp) }// A cancel while the model was coming up ended this session.guard stamp == session, !ended else {await analyzer.cancelAndFinishNow()return }let feed = AnalyzerFeed(format: prepared.format)self.analyzer = analyzerself.feed = feed// The results, read where no actor is inherited and reduced to// `Sendable` values before they cross. work.append(Task.detached { [relay] indo {fortryawait result in transcriber.results {let text = String(result.text.characters)if result.isFinal { relay.send(Inbound(session: stamp, event: .settled(text, HeardWord.read(result.text)))) } else { relay.send(Inbound(session: stamp, event: .partial(text))) } } relay.send(Inbound(session: stamp, event: .finished)) } catch { relay.send(Inbound(session: stamp, event: .failed(unavailable: false))) } })do {tryawait analyzer.start(inputSequence: feed.stream) } catch {return fail(unavailable: true, stamp: stamp) }iflet trace = Self.trace { trace("started; audio follows") } awaitingModel = falselet ready = Int((CFAbsoluteTimeGetCurrent() - tappedAt) * 1000)switch audio {case .microphone:let caught = held?.attach(feed) ?? (buffers: 0, seconds: 0)Self.log.notice("listen: start→model ready \(ready, privacy: .public) ms, \(caught.seconds, format: .fixed(precision: 2), privacy: .public) s held before it")case .file(let url):Self.log.notice("listen: start→model ready \(ready, privacy: .public) ms") play(url, into: feed, stamp: stamp) }// Stopped while the model was coming up: what was held is all there// is, and the model finishes on it.if stopping { feed.finish()try? await analyzer.finalizeAndFinishThroughEndOfInput() } }/// The category and the activation, then the engine, then the format, then/// the tap, then the start. Nothing above a line may depend on a line below/// it, and that is the rule the whole file exists to keep.privatefunc openMicrophone(_ feed: any RecognitionBuffering, stamp: Int) {do { #if os(iOS)let audio = AVAudioSession.sharedInstance()try audio.setCategory( .playAndRecord, mode: .measurement, options: [.duckOthers, .defaultToSpeaker])try audio.setActive(true, options: .notifyOthersOnDeactivation) #endif// Only now — a live category and an active session — may an engine// exist at all, because constructing one and touching its input// node is the same act as far as the format cache is concerned. sessionActivated = truelet engine = ensureEngine() armInterruptionObserver()// Read IMMEDIATELY before the tap: granting the microphone is a// route change, and a format read earlier may already be stale.let input = engine.inputNodelet format = input.outputFormat(forBus: 0)// A device with NO usable input — a simulator with no microphone, a// route mid-switch — answers zero channels at zero Hz, and// `installTap` raises an NSException over it (2026-09-11).guard format.sampleRate > 0, format.channelCount > 0else {Self.log.notice("listen: no microphone input")return fail(unavailable: false, stamp: stamp) }// `@Sendable` IS THE FIX, not decoration: without it this literal// inherits the enclosing method's `@MainActor` and the audio thread// trips the executor check in its preamble. See ``AudioTapSink``.let sink = AudioTapSink(request: feed, relay: relay, throttle: throttle, session: stamp) input.installTap(onBus: 0, bufferSize: 1024, format: format) { @Sendable buffer, _ in sink.receive(buffer) } tapInstalled = true engine.prepare()try engine.start()letopen = Int((CFAbsoluteTimeGetCurrent() - tappedAt) * 1000)Self.log.notice("listen: start→microphone running \(open, privacy: .public) ms")// A session is genuinely running, so there is finally something to// give back if this object is dropped without a tap on ✓ or ✕. armHold(engine) relay.send(Inbound(session: stamp, event: .started)) } catch { fail(unavailable: false, stamp: stamp) } }/// A recording, played into the analyzer at the pace it was spoken — the/// way a microphone would hand it over — through the same tap sink.privatefunc play(_ url: URL, into feed: AnalyzerFeed, stamp: Int) {let sink = AudioTapSink(request: feed, relay: relay, throttle: throttle, session: stamp) relay.send(Inbound(session: stamp, event: .started)) work.append(Task.detached {guardlet file = try? AVAudioFile(forReading: url) else { return }let chunk: AVAudioFrameCount = 1024while !Task.isCancelled {guardlet buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: chunk), (try? file.read(into: buffer, frameCount: chunk)) != nil, buffer.frameLength > 0else { return } sink.receive(buffer)try? awaitTask.sleep(for: .seconds(Double(buffer.frameLength) / file.processingFormat.sampleRate)) } }) }func stop() {guard !ended else { return } stopping = true// The input ends here; the analyzer finalises what it heard and its// results stream ends, which is the session's `ended`. If that never// comes the model's own guard keeps what was heard — and that guard// calls `cancel()`, which is what runs `teardown()`. stopMicrophone()guardlet feed, let analyzer else {// Stopped while the model was still coming up: it finishes on// what the microphone held (``run``); with no model coming,// nothing was heard.if awaitingModel, held != nil { return }return finished() } feed.finish()Task { try? await analyzer.finalizeAndFinishThroughEndOfInput() } }func cancel() {guard !ended else { return } emit(.failed(.aborted)) finished() }// MARK: - AudioLevelSourcefunc onLevel(_ sink: @escaping AudioLevelSink) { levels = sink }// MARK: - What the tap and the reader hand up, in orderfunc receive(_ inbound: Inbound) {// A session's leftovers never land in the next one, and nothing is// spoken after `ended`.guard inbound.session == session, !ended else { return }switch inbound.event {case .started: emit(.started)case .level(let value): levels?(value)case .partial(let text): firstWords(text) emit(.partial(text))case .settled(let text, let words): firstWords(text) emit(.segment(text, words: words))case .finished:// The stream ends on its own only when the input did: a stop, or a// recording played to its end. Anything else is the analyzer giving// up, which the model's restart ladder answers.if !stopping { emit(.failed(.other)) } finished()case .failed(let unavailable): emit(.failed(unavailable ? .unavailable : failure())) finished() } }privatefunc firstWords(_ text: String) {guard !spoke, !text.isEmpty else { return } spoke = truelet ms = Int((CFAbsoluteTimeGetCurrent() - tappedAt) * 1000)Self.log.notice("listen: tap→first words \(ms, privacy: .public) ms") }privatefunc fail(unavailable: Bool, stamp: Int) { relay.send(Inbound(session: stamp, event: .failed(unavailable: unavailable))) }privatefunc failure() -> SpeechFailure {if !permitted { return .notAllowed }return .other }privatefunc interrupted() {guard !ended else { return } emit(.failed(.interrupted)) finished() }privatefunc emit(_ event: SpeechEvent) { events?(event) }/// The session is over, however it ended — exactly once.privatefunc finished() {guard !ended else { return } ended = trueif !spoke { Self.log.notice("listen: ended with no words") } teardown() emit(.ended)// A finished analyzer cannot be started again: the next one is// prepared now, off the tap.iflet lastHints { prepare(lastHints) } }// MARK: - The platform objects, built on first useprivatefunc ensureEngine() -> AVAudioEngine {iflet engine { return engine }let made = AVAudioEngine() engine = madereturn made }/// Armed with the first session: it exists so a call, Siri or an alarm/// ENDS a dictation with its words, and before the first session there is/// nothing to end.privatefunc armInterruptionObserver() {guard !observing else { return } observing = true// `AVAudioSession` is the phone's: a Mac has no shared session for a// call or Siri to interrupt, so there is nothing to observe. #if os(iOS)let token = NotificationCenter.default.addObserver( forName: AVAudioSession.interruptionNotification, object: AVAudioSession.sharedInstance(), queue: .main ) { [weakself] note inlet raw = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UIntguard raw == AVAudioSession.InterruptionType.began.rawValue else { return }MainActor.assumeIsolated { self?.interrupted() } } hold.observe(token) #endif }/// The terminal give-back, armed once a session is genuinely running.privatefunc armHold(_ engine: AVAudioEngine) { hold.arm { engine.inputNode.removeTap(onBus: 0)if engine.isRunning { engine.stop() } #if os(iOS)try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) #endif } }privatefunc stopMicrophone() {iflet engine {if tapInstalled { engine.inputNode.removeTap(onBus: 0) tapInstalled = false }if engine.isRunning { engine.stop() } } }/// The PER-SESSION give-back. It deliberately leaves the interruption/// observer alone: the next session still has to hear a call arrive./// **A no-op when nothing was ever started**, which is what makes it safe/// as the FIRST line of `start(...)`: no engine is touched until one was/// built, no tap is removed that was not installed, and the session is/// deactivated only by the object that activated it.privatefunc teardown() { stopMicrophone()for task in work { task.cancel() } work = [] feed?.finish() feed = nil held = nil awaitingModel = falseiflet analyzer {Task { await analyzer.cancelAndFinishNow() } } analyzer = nilif sessionActivated { #if os(iOS)try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) #endif sessionActivated = false } }}extensionHeardWord {/// The words of a finalised result, each with the model's confidence in it. @available(iOS 26.0, macOS 26.0, *)staticfunc read(_ text: AttributedString) -> [HeardWord] { text.runs.compactMap { run inlet said = String(text[run.range].characters).trimmingCharacters(in: .whitespacesAndNewlines)guard !said.isEmpty else { returnnil }returnHeardWord(text: said, confidence: run.transcriptionConfidence) } }}extensionDictationLevel {/// One buffer's loudness, as the 0…1 the listening line's waveform reads.////// RMS rather than peak: a peak meter jumps on a consonant and reads as a/// flicker, and what the dot is answering is "is anything reaching the/// microphone at all". Silence is `-.infinity` in dB, which the fold's floor/// already lands on 0 — but the guard is here anyway, because a `log10(0)`/// travelling into a view is a NaN nobody can see the origin of.staticfunc meter(_ buffer: AVAudioPCMBuffer) -> Double {guardlet channel = buffer.floatChannelData?[0], buffer.frameLength > 0else { return0 }let count = Int(buffer.frameLength)var sum: Double = 0for frame in0..<count {let sample = Double(channel[frame]) sum += sample * sample }let rms = (sum / Double(count)).squareRoot()guard rms > 0else { return0 }return fold(decibels: 20 * log10(rms)) }}