Cotton code
1101 lines · 46.9 KB · SwiftRaw
// 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 AVFoundationimport CottonKitimport CottonSpeechimport Foundationimport Speechimport 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.final class MainActorRelay<Value: Sendable>: @unchecked Sendable {    private let stream: AsyncStream<Value>    private let 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`.    private let lock = NSLock()    private var 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] in            for await 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>? in            let taken = pump            pump = nil            return 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.final class AudioSessionHold: @unchecked Sendable {    private let lock = NSLock()    private var observer: NSObjectProtocol?    private var giveBack: (() -> Void)?    /// Terminal, so a late ``arm(_:)`` cannot resurrect a hold that has already    /// given the microphone back.    private var 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 {            guard self.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)?) in            let taken = (observer, giveBack)            observer = nil            giveBack = nil            released = true            return taken        }        if let 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.final class MeterThrottle: @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.    static let interval: TimeInterval = 0.05    private let lock = NSLock()    private var 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 { return false }            last = now            return true        }    }    /// 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.struct Inbound: 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: Int    let event: Event    enum Event: Sendable {        /// The model is ready and the microphone is ours.        case started        case 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.protocol RecognitionBuffering: 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`.final class HeldAudio: RecognitionBuffering, @unchecked Sendable {    private let lock = NSLock()    private var held: [AVAudioPCMBuffer] = []    private var target: (any RecognitionBuffering)?    func append(_ buffer: AVAudioPCMBuffer) {        lock.lock()        defer { lock.unlock() }        if let target {            target.append(buffer)        } else if let 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.    @discardableResult    func 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.count        for buffer in held { feed.append(buffer) }        held = []        target = feed        return (count, seconds)    }    private static func copy(_ buffer: AVAudioPCMBuffer) -> AVAudioPCMBuffer? {        guard let copy = AVAudioPCMBuffer(pcmFormat: buffer.format, frameCapacity: buffer.frameLength) else { return nil }        copy.frameLength = buffer.frameLength        let frames = Int(buffer.frameLength)        let channels = Int(buffer.format.channelCount)        let planes = buffer.format.isInterleaved ? 1 : channels        let samples = buffer.format.isInterleaved ? frames * channels : frames        if let from = buffer.floatChannelData, let to = copy.floatChannelData {            for plane in 0 ..< planes { to[plane].update(from: from[plane], count: samples) }        } else if let from = buffer.int16ChannelData, let to = copy.int16ChannelData {            for plane in 0 ..< planes { to[plane].update(from: from[plane], count: samples) }        } else if let from = buffer.int32ChannelData, let to = copy.int32ChannelData {            for plane in 0 ..< planes { to[plane].update(from: from[plane], count: samples) }        } else {            return nil        }        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`).final class AudioTapSink: @unchecked Sendable {    private let request: any RecognitionBuffering    private let relay: MainActorRelay<Inbound>    private let throttle: MeterThrottle    /// Stamped onto every reading, so a buffer already in flight when this    /// session ends cannot land in the next one's transcript.    private let session: Int    init(        request: any RecognitionBuffering,        relay: MainActorRelay<Inbound>,        throttle: MeterThrottle,        session: Int    ) {        self.request = request        self.relay = relay        self.throttle = throttle        self.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, *)final class AnalyzerFeed: RecognitionBuffering, @unchecked Sendable {    let stream: AsyncStream<AnalyzerInput>    private let feed: AsyncStream<AnalyzerInput>.Continuation    private let format: AVAudioFormat    private var converter: AVAudioConverter?    init(format: AVAudioFormat) {        self.format = format        (stream, feed) = AsyncStream<AnalyzerInput>.makeStream(bufferingPolicy: .unbounded)    }    func append(_ buffer: AVAudioPCMBuffer) {        guard let 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()    }    private func 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        }        guard let converter else { return nil }        let ratio = format.sampleRate / buffer.format.sampleRate        let capacity = AVAudioFrameCount((Double(buffer.frameLength) * ratio).rounded(.up)) + 1        guard let out = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: capacity) else { return nil }        var given = false        var error: NSError?        let status = converter.convert(to: out, error: &error) { _, state in            if given {                state.pointee = .noDataNow                return nil            }            given = true            state.pointee = .haveData            return buffer        }        guard status != .error, out.frameLength > 0 else { return nil }        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.public enum DictationAudio: Sendable, Equatable {    case microphone    case 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.@MainActorfinal class NoDictation: 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.struct WarmKey: Equatable, Sendable {    let locale: String    let 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`).struct WarmSlot<Payload> {    private var held: (key: WarmKey, payload: Payload)?    func holds(_ key: WarmKey) -> Bool { held?.key == key }    mutating func 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.    mutating func take(for key: WarmKey) -> Payload? {        defer { held = nil }        guard let held, held.key == key else { return nil }        return held.payload    }}/// A model prepared to analyze: everything a session needs before audio.@available(iOS 26.0, macOS 26.0, *)struct WarmModel: @unchecked Sendable {    let transcriber: DictationTranscriber    let analyzer: SpeechAnalyzer    let format: AVAudioFormat    /// The contextual strings it was prepared with.    let groups: [DictationHints.Group]}// MARK: - The recogniser@available(iOS 26.0, macOS 26.0, *)@MainActorfinal class SystemSpeechRecogniser: SpeechRecognizing, AudioLevelSource {    private let audio: DictationAudio    /// The OS, behind the one seam allowed to ask it.    private let 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`.    private var engine: AVAudioEngine?    private let relay = MainActorRelay<Inbound>()    private let throttle = MeterThrottle()    /// Built empty and ARMED with the engine — construction is free.    private let hold = AudioSessionHold()    private var analyzer: SpeechAnalyzer?    private var feed: AnalyzerFeed?    /// The microphone's audio from the tap until the feed exists.    private var held: HeldAudio?    /// The session's model is still coming: a stop now waits for it and    /// finishes on what the microphone held.    private var awaitingModel = false    /// The first words of this session were logged.    private var spoke = false    /// The session's setup, the results reader and (for a file) the player.    private var work: [Task<Void, Never>] = []    private var events: SpeechEventSink?    private var levels: AudioLevelSink?    /// One `ended` per session, whatever raced to end it.    private var ended = true    /// `stop()` was asked for: the input is finished and the results stream's    /// end is the session's.    private var stopping = false    /// Bumped by every ``start(_:)``, stamped onto everything the tap and the    /// reader hand up.    private var 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.    private var 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.    private var sessionActivated = false    /// The interruption observer is armed once, with the first session — never    /// in `init`, where there is no session to interrupt.    private var observing = false    /// The gate said yes; a failure after it is not a refusal.    private var 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.    static var trace: ((String) -> Void)?    private static let 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.    private static var slot = WarmSlot<WarmModel>()    private static var warming: Task<WarmModel?, Never>?    private static var 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.    private var lastHints: DictationHints?    /// When this session's ``start(_:)`` ran, for the log's split of the    /// tap's cost into the model and the microphone.    private var 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 = audio        self.capabilities = capabilities        // Every stored property is set, so the sink may capture `self`.        relay.onValue { [weak self] inbound in self?.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: - SpeechRecognizing    func 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 = true            return .ready        }        let result = await capabilities.gate([.microphone, .speech])        permitted = result.isReady        return 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 = hints        let key = WarmKey(hints)        let path: String        let model: Task<WarmModel?, Never>        if let ready = Self.slot.take(for: key) {            path = "warm"            model = Task { ready }        } else if let coming = Self.warming, Self.warmingKey == key {            path = "warming"            model = coming        } else {            path = "cold"            model = Task { await Self.build(hints) }        }        Self.warming = nil        Self.warmingKey = nil        Self.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``).        if case .microphone = audio {            let held = HeldAudio()            self.held = held            openMicrophone(held, stamp: stamp)            guard !ended else { return }        }        work.append(Task { [weak self] in            guard let prepared = await model.value else {                self?.fail(unavailable: true, stamp: stamp)                return            }            await self?.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 = hints        let key = WarmKey(hints)        guard !Self.slot.holds(key), Self.warmingKey != key else { return }        Self.warmingKey = key        let coming = Task { await Self.build(hints) }        Self.warming = coming        Task {            let prepared = await coming.value            guard Self.warmingKey == key else { return }            Self.warming = nil            Self.warmingKey = nil            if let prepared { Self.slot.fill(key, prepared) }        }    }    /// Everything before the microphone, in the file's one order.    private static func build(_ hints: DictationHints) async -> WarmModel? {        guard let locale = await SpeechModel.locale(DictationTranscriber.self, for: hints.locale) else {            return nil        }        // 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> = []        if let 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 {            try await SpeechModel.install([transcriber])            guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [transcriber])            else { return nil }            try await analyzer.setContext(Self.context(hints))            if let trace {                trace("module \(type(of: transcriber)) locale \(locale.identifier)")                trace("language model \(content.isEmpty ? "none" : String(hints.model?.fingerprint.prefix(12) ?? ""))")            }            try await analyzer.prepareToAnalyze(in: format)            return WarmModel(transcriber: transcriber, analyzer: analyzer, format: format, groups: hints.groups)        } catch {            return nil        }    }    private static func 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.    private func run(_ prepared: WarmModel, hints: DictationHints, stamp: Int) async {        let transcriber = prepared.transcriber        let analyzer = prepared.analyzer        do {            // 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 {                try await analyzer.setContext(Self.context(hints))            }            if let trace = Self.trace {                let held = await analyzer.context.contextualStrings                for 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 = analyzer        self.feed = feed        // The results, read where no actor is inherited and reduced to        // `Sendable` values before they cross.        work.append(Task.detached { [relay] in            do {                for try await 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 {            try await analyzer.start(inputSequence: feed.stream)        } catch {            return fail(unavailable: true, stamp: stamp)        }        if let trace = Self.trace { trace("started; audio follows") }        awaitingModel = false        let 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.    private func 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 = true            let 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.inputNode            let 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 > 0 else {                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()            let open = 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.    private func 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 {            guard let file = try? AVAudioFile(forReading: url) else { return }            let chunk: AVAudioFrameCount = 1024            while !Task.isCancelled {                guard let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: chunk),                      (try? file.read(into: buffer, frameCount: chunk)) != nil,                      buffer.frameLength > 0                else { return }                sink.receive(buffer)                try? await Task.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()        guard let 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: - AudioLevelSource    func onLevel(_ sink: @escaping AudioLevelSink) {        levels = sink    }    // MARK: - What the tap and the reader hand up, in order    func 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()        }    }    private func firstWords(_ text: String) {        guard !spoke, !text.isEmpty else { return }        spoke = true        let ms = Int((CFAbsoluteTimeGetCurrent() - tappedAt) * 1000)        Self.log.notice("listen: tap→first words \(ms, privacy: .public) ms")    }    private func fail(unavailable: Bool, stamp: Int) {        relay.send(Inbound(session: stamp, event: .failed(unavailable: unavailable)))    }    private func failure() -> SpeechFailure {        if !permitted { return .notAllowed }        return .other    }    private func interrupted() {        guard !ended else { return }        emit(.failed(.interrupted))        finished()    }    private func emit(_ event: SpeechEvent) {        events?(event)    }    /// The session is over, however it ended — exactly once.    private func finished() {        guard !ended else { return }        ended = true        if !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.        if let lastHints { prepare(lastHints) }    }    // MARK: - The platform objects, built on first use    private func ensureEngine() -> AVAudioEngine {        if let engine { return engine }        let made = AVAudioEngine()        engine = made        return 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.    private func 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        ) { [weak self] note in            let raw = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt            guard 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.    private func 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        }    }    private func stopMicrophone() {        if let 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.    private func teardown() {        stopMicrophone()        for task in work { task.cancel() }        work = []        feed?.finish()        feed = nil        held = nil        awaitingModel = false        if let analyzer {            Task { await analyzer.cancelAndFinishNow() }        }        analyzer = nil        if sessionActivated {            #if os(iOS)            try? AVAudioSession.sharedInstance().setActive(                false, options: .notifyOthersOnDeactivation)            #endif            sessionActivated = false        }    }}extension HeardWord {    /// The words of a finalised result, each with the model's confidence in it.    @available(iOS 26.0, macOS 26.0, *)    static func read(_ text: AttributedString) -> [HeardWord] {        text.runs.compactMap { run in            let said = String(text[run.range].characters).trimmingCharacters(in: .whitespacesAndNewlines)            guard !said.isEmpty else { return nil }            return HeardWord(text: said, confidence: run.transcriptionConfidence)        }    }}extension DictationLevel {    /// 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.    static func meter(_ buffer: AVAudioPCMBuffer) -> Double {        guard let channel = buffer.floatChannelData?[0], buffer.frameLength > 0 else { return 0 }        let count = Int(buffer.frameLength)        var sum: Double = 0        for frame in 0..<count {            let sample = Double(channel[frame])            sum += sample * sample        }        let rms = (sum / Double(count)).squareRoot()        guard rms > 0 else { return 0 }        return fold(decibels: 20 * log10(rms))    }}