Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

270 KB
Raw Blame
// Keep the existing capture lifecycle together during integration.
// swiftlint:disable file_length
import AppKit
@preconcurrency import AVFoundation
import CoreAudio
import CoreMedia
import Foundation
import IOKit.pwr_mgt
import ScreenCaptureKit

nonisolated protocol MeetingCaptureControlling: Sendable {
    /// Any user-facing permission request must complete before the coordinator reserves
    /// the exclusive ASR meeting lease.
    func preflightPermissions() async throws

    func start(
        session: MeetingSession,
        configuration: MeetingCaptureConfiguration,
        sessionDirectory: URL,
        eventHandler: @escaping @Sendable (MeetingCaptureEvent) -> Void,
        liveAudioHandler: (@Sendable (MeetingAudioTrackKind, CMSampleBuffer) -> Void)?
    ) async throws -> MeetingCaptureStartResult

    func stop(sessionID: MeetingSessionID) async throws -> MeetingCaptureStopResult
    func shutdownForTermination() async
}

actor MeetingCaptureEngine: MeetingCaptureControlling {
    private struct ActiveCapture: @unchecked Sendable {
        var sessionID: MeetingSessionID
        var runtime: any MeetingCaptureRuntime
        var writers: [MeetingAudioChunkWriter]
        var comparisonProbe: MeetingAudioComparisonProbe?
    }

    private var activeCapture: ActiveCapture?
    private var startingSessionID: MeetingSessionID?
    private var stopTask: Task<MeetingCaptureStopResult, Error>?
    private var displaySleepAssertionID: IOPMAssertionID?
    private var terminating = false

    func preflightPermissions() async throws {
        try await Self.requestMicrophonePermissionIfNeeded()
    }

    func start(
        session: MeetingSession,
        configuration: MeetingCaptureConfiguration,
        sessionDirectory: URL,
        eventHandler: @escaping @Sendable (MeetingCaptureEvent) -> Void,
        liveAudioHandler: (@Sendable (MeetingAudioTrackKind, CMSampleBuffer) -> Void)? = nil
    ) async throws -> MeetingCaptureStartResult {
        try configuration.validate()
        guard self.activeCapture == nil, self.startingSessionID == nil, self.stopTask == nil else {
            throw MeetingCaptureError.captureAlreadyActive
        }
        self.startingSessionID = session.id
        defer { self.startingSessionID = nil }
        try Self.preflightStorage(
            at: sessionDirectory,
            trackCount: MeetingPCMStoragePolicy.trackCount(for: configuration.mode)
        )
        try Self.verifyMicrophonePermission()

        let comparisonProbe: MeetingAudioComparisonProbe?
        if let expiration = MeetingAudioComparisonProbe.requestExpiration(mode: configuration.mode) {
            let directory = FileManager.default.temporaryDirectory
                .appendingPathComponent("FluidVoice-AudioComparison", isDirectory: true)
                .appendingPathComponent(session.id.uuidString, isDirectory: true)
            comparisonProbe = try? MeetingAudioComparisonProbe(session: session, directory: directory, onUsefulComparison: {
                MeetingAudioComparisonProbe.completeRequest(expiration: expiration)
            })
            DebugLogger.shared.info("Audio comparison probe \(comparisonProbe == nil ? "failed to start" : "armed") at \(directory.path)", source: "MeetingCaptureEngine")
        } else {
            comparisonProbe = nil
        }
        if let comparisonProbe { eventHandler(.audioComparisonProbeStarted(comparisonProbe)) }
        // If setup exits before an active capture owns the probe, still finalize its files.
        var probeOwnedByCapture = false
        defer {
            if !probeOwnedByCapture, let comparisonProbe { Task { await comparisonProbe.stop() } }
        }
        let tracks = Self.makeTracks(session: session, configuration: configuration)
        let writers = try tracks.map { track in
            try MeetingAudioChunkWriter(
                track: track,
                sessionDirectory: sessionDirectory,
                chunkDuration: configuration.chunkDuration,
                eventHandler: eventHandler,
                diagnosticSampleObserver: comparisonProbe.map { probe in
                    let stage: MeetingAudioComparisonProbe.Stage = track.kind == .microphone ? .microphoneOutput : .browser
                    return { sample, epoch in probe.offer(sample, stage: stage, producerEpoch: epoch) }
                }
            )
        }
        let writersByKind = Dictionary(uniqueKeysWithValues: zip(tracks.map(\.kind), writers))

        let runtime: any MeetingCaptureRuntime
        switch configuration.mode {
        case .onlineCall:
            guard let application = configuration.application,
                  let applicationWriter = writersByKind[.applicationAudio],
                  let microphoneWriter = writersByKind[.microphone]
            else { throw MeetingCaptureError.applicationNotSelected }

            let outputRoute = Self.currentOutputRouteSnapshot()
            #if DEBUG
            let forcePairedScreenCaptureKit = MeetingSCKPairedDiagnosticGate.enabled()
            #else
            let forcePairedScreenCaptureKit = false
            #endif
            let preferDirectAEC3 = MeetingDirectAEC3Gate.enabled()
            let decision = MeetingCapturePathDecider.decide(
                mode: configuration.mode,
                microphone: configuration.microphone,
                outputRoute: outputRoute,
                forcePairedScreenCaptureKit: forcePairedScreenCaptureKit,
                preferDirectAEC3: preferDirectAEC3
            )
            switch decision {
            case let .screenCaptureKit(reason):
                if reason == MeetingCapturePathDecider.directAEC3DefaultReason {
                    #if DEBUG
                    DebugLogger.shared.log(
                        "Direct AEC3 selected for the built-in-speaker pre-production path.",
                        source: "MeetingCaptureEngine"
                    )
                    #endif
                } else {
                    let captureDecisionMessage = reason == MeetingCapturePathDecider.diagnosticForceScreenCaptureKitReason
                        ? "C2 diagnostic forced paired ScreenCaptureKit; this is not a production fallback."
                        : "Meeting voice-processing capture declined: \(reason)"
                    DebugLogger.shared.log(
                        captureDecisionMessage,
                        source: "MeetingCaptureEngine"
                    )
                    eventHandler(.interrupted(kind: .voiceProcessingDeclined, trackID: nil, detail: reason))
                }
                try await microphoneWriter.updateTrackMetadata { track in
                    track.captureEras = [MeetingCaptureEra(
                        method: .screenCaptureKit,
                        deviceUID: configuration.microphone.coreAudioUID,
                        deviceName: configuration.microphone.displayName,
                        roleAtElection: configuration.microphone.role,
                        echoProtection: .unprotected,
                        startSeconds: 0
                    )]
                }
                runtime = try await ScreenCaptureMeetingRuntime.make(
                    application: application,
                    microphone: configuration.microphone,
                    includeMicrophone: true,
                    comparisonProbe: comparisonProbe,
                    microphoneEchoProtection: .unprotected,
                    applicationWriter: applicationWriter,
                    microphoneWriter: microphoneWriter,
                    eventHandler: eventHandler,
                    liveAudioHandler: liveAudioHandler
                )
            case .voiceProcessing:
                runtime = try await VoiceProcessingMeetingRuntime.make(
                    application: application,
                    microphone: configuration.microphone,
                    applicationWriter: applicationWriter,
                    microphoneWriter: microphoneWriter,
                    eventHandler: eventHandler,
                    liveAudioHandler: liveAudioHandler
                )
            }
        case .inRoom:
            guard let microphoneWriter = writersByKind[.microphone] else {
                throw MeetingCaptureError.microphoneUnavailable
            }
            runtime = try InRoomMicrophoneCaptureRuntime(
                microphone: configuration.microphone,
                writer: microphoneWriter,
                eventHandler: eventHandler,
                liveAudioHandler: liveAudioHandler
            )
        }

        do {
            try await runtime.start()
        } catch {
            try? await runtime.stop()
            _ = await Self.stopWriters(writers)
            throw error
        }

        // The actor is reentrant across the awaits above; termination may have arrived meanwhile.
        if self.terminating {
            try? await runtime.stop()
            _ = await Self.stopWriters(writers)
            throw MeetingCaptureError.captureStartFailed("The app is shutting down.")
        }
        self.displaySleepAssertionID = Self.acquireDisplaySleepAssertion()
        self.activeCapture = ActiveCapture(
            sessionID: session.id,
            runtime: runtime,
            writers: writers,
            comparisonProbe: comparisonProbe
        )
        probeOwnedByCapture = true
        // Re-snapshot: a VPIO commit during start() promotes provenance on the writer's own track.
        let settledTracks = await withTaskGroup(of: MeetingAudioTrack.self, returning: [MeetingAudioTrack].self) { group in
            for writer in writers {
                group.addTask { await writer.snapshot() }
            }
            var result: [MeetingAudioTrack] = []
            for await track in group {
                result.append(track)
            }
            return result.sorted { $0.kind.rawValue < $1.kind.rawValue }
        }
        return MeetingCaptureStartResult(
            tracks: settledTracks,
            firstPresentationTime: nil,
            captureScope: runtime.captureScope
        )
    }

    func stop(sessionID: MeetingSessionID) async throws -> MeetingCaptureStopResult {
        if let stopTask = self.stopTask {
            return try await stopTask.value
        }
        guard let activeCapture = self.activeCapture else {
            throw MeetingCaptureError.noActiveCapture
        }
        guard activeCapture.sessionID == sessionID else {
            throw MeetingCaptureError.wrongActiveSession
        }

        let task = Task<MeetingCaptureStopResult, Error> {
            #if DEBUG
            AudioTopologyDiagnostics.record(.phaseBegin, owner: .meetingCaptureEngine, queueRole: .actorControl, phase: .runtimeStop)
            #endif
            let runtimeFailure: Error?
            do {
                try await activeCapture.runtime.stop()
                runtimeFailure = nil
                #if DEBUG
                AudioTopologyDiagnostics.record(.phaseEnd, owner: .meetingCaptureEngine, queueRole: .actorControl, phase: .runtimeStop)
                #endif
            } catch {
                runtimeFailure = error
                #if DEBUG
                AudioTopologyDiagnostics.record(.phaseEnd, owner: .meetingCaptureEngine, queueRole: .actorControl, phase: .runtimeStop, status: -1)
                #endif
            }
            #if DEBUG
            AudioTopologyDiagnostics.record(.phaseBegin, owner: .meetingCaptureEngine, queueRole: .actorControl, phase: .writerStop)
            #endif
            let tracks = await Self.stopWriters(activeCapture.writers)
            activeCapture.comparisonProbe?.finishAfterCaptionTeardown()
            #if DEBUG
            AudioTopologyDiagnostics.record(.phaseEnd, owner: .meetingCaptureEngine, queueRole: .actorControl, phase: .writerStop)
            #endif
            let result = MeetingCaptureStopResult(tracks: tracks, stoppedAt: Date())
            if let runtimeFailure {
                throw MeetingCaptureError.captureStopFailed(
                    runtimeFailure.localizedDescription,
                    partialResult: result
                )
            }
            return result
        }
        self.stopTask = task
        do {
            let result = try await task.value
            #if DEBUG
            AudioTopologyDiagnostics.record(.phaseBegin, owner: .meetingCaptureEngine, queueRole: .actorControl, phase: .captureStop)
            #endif
            self.activeCapture = nil
            #if DEBUG
            AudioTopologyDiagnostics.record(.phaseEnd, owner: .meetingCaptureEngine, queueRole: .actorControl, phase: .captureStop)
            #endif
            self.stopTask = nil
            self.releaseDisplaySleepAssertion()
            return result
        } catch {
            #if DEBUG
            AudioTopologyDiagnostics.record(.phaseBegin, owner: .meetingCaptureEngine, queueRole: .actorControl, phase: .captureStop)
            #endif
            self.activeCapture = nil
            #if DEBUG
            AudioTopologyDiagnostics.record(.phaseEnd, owner: .meetingCaptureEngine, queueRole: .actorControl, phase: .captureStop, status: -1)
            #endif
            self.stopTask = nil
            self.releaseDisplaySleepAssertion()
            throw error
        }
    }

    func shutdownForTermination() async {
        self.terminating = true
        guard let sessionID = self.activeCapture?.sessionID else {
            self.releaseDisplaySleepAssertion()
            return
        }
        _ = try? await self.stop(sessionID: sessionID)
    }

    private func releaseDisplaySleepAssertion() {
        guard let assertionID = self.displaySleepAssertionID else { return }
        self.displaySleepAssertionID = nil
        IOPMAssertionRelease(assertionID)
    }

    private nonisolated static func acquireDisplaySleepAssertion() -> IOPMAssertionID? {
        var assertionID: IOPMAssertionID = 0
        let result = IOPMAssertionCreateWithName(
            kIOPMAssertionTypePreventUserIdleDisplaySleep as CFString,
            IOPMAssertionLevel(kIOPMAssertionLevelOn),
            "FluidVoice meeting recording" as CFString,
            &assertionID
        )
        return result == kIOReturnSuccess ? assertionID : nil
    }

    private nonisolated static func stopWriters(_ writers: [MeetingAudioChunkWriter]) async -> [MeetingAudioTrack] {
        await withTaskGroup(of: MeetingAudioTrack.self, returning: [MeetingAudioTrack].self) { group in
            for writer in writers {
                group.addTask { await writer.stop() }
            }
            var tracks: [MeetingAudioTrack] = []
            for await track in group {
                tracks.append(track)
            }
            return tracks.sorted { $0.kind.rawValue < $1.kind.rawValue }
        }
    }

    private nonisolated static func makeTracks(
        session: MeetingSession,
        configuration: MeetingCaptureConfiguration
    ) -> [MeetingAudioTrack] {
        var tracks: [MeetingAudioTrack] = []
        if let application = configuration.application {
            tracks.append(MeetingAudioTrack(
                id: UUID(),
                kind: .applicationAudio,
                sourceIdentifier: application.bundleIdentifier,
                sourceDisplayName: application.displayName,
                format: nil,
                timebase: session.timebase,
                health: .waiting,
                chunks: [],
                captureMethod: .screenCaptureKit
            ))
        }
        tracks.append(MeetingAudioTrack(
            id: UUID(),
            kind: .microphone,
            sourceIdentifier: configuration.microphone.captureDeviceID,
            sourceDisplayName: configuration.microphone.displayName,
            format: nil,
            timebase: session.timebase,
            health: .waiting,
            chunks: [],
            captureMethod: configuration.mode == .onlineCall ? .screenCaptureKit : .avCaptureSession
        ))
        return tracks
    }

    private nonisolated static func requestMicrophonePermissionIfNeeded() async throws {
        switch AVCaptureDevice.authorizationStatus(for: .audio) {
        case .authorized:
            return
        case .notDetermined:
            let granted = await withCheckedContinuation { continuation in
                AVCaptureDevice.requestAccess(for: .audio) { continuation.resume(returning: $0) }
            }
            guard granted else { throw MeetingCaptureError.microphonePermissionDenied }
        case .denied, .restricted:
            throw MeetingCaptureError.microphonePermissionDenied
        @unknown default:
            throw MeetingCaptureError.microphonePermissionDenied
        }
    }

    private nonisolated static func verifyMicrophonePermission() throws {
        guard AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else {
            throw MeetingCaptureError.microphonePermissionDenied
        }
    }

    static func currentOutputRouteSnapshot() -> MeetingOutputRouteSnapshot {
        guard let device = AudioDevice.getDefaultOutputDevice() else {
            return MeetingOutputRouteSnapshot(deviceExists: false, isBluetooth: false, isBuiltIn: false, isHeadphonesDataSource: false)
        }
        return MeetingOutputRouteSnapshot(
            deviceExists: true,
            isBluetooth: device.isBluetooth,
            isBuiltIn: device.isBuiltIn,
            isHeadphonesDataSource: AudioDevice.outputDataSourceIsHeadphones(device.id),
            terminalTypes: Self.outputTerminalTypes(deviceID: device.id)
        )
    }

    private static func outputTerminalTypes(deviceID: AudioObjectID) -> Set<UInt32> {
        var streamsAddress = AudioObjectPropertyAddress(
            mSelector: kAudioDevicePropertyStreams,
            mScope: kAudioObjectPropertyScopeOutput,
            mElement: kAudioObjectPropertyElementMain
        )
        var byteCount: UInt32 = 0
        guard AudioObjectGetPropertyDataSize(deviceID, &streamsAddress, 0, nil, &byteCount) == noErr,
              byteCount >= UInt32(MemoryLayout<AudioStreamID>.size)
        else { return [] }
        var streams = [AudioStreamID](
            repeating: 0,
            count: Int(byteCount) / MemoryLayout<AudioStreamID>.size
        )
        let streamStatus = streams.withUnsafeMutableBytes { bytes in
            // Buffer size and channel topology are validated before this synchronous C call.
            // swiftlint:disable:next force_unwrapping
            AudioObjectGetPropertyData(deviceID, &streamsAddress, 0, nil, &byteCount, bytes.baseAddress!)
        }
        guard streamStatus == noErr else { return [] }
        return Set(streams.compactMap { streamID in
            var terminalAddress = AudioObjectPropertyAddress(
                mSelector: kAudioStreamPropertyTerminalType,
                mScope: kAudioObjectPropertyScopeGlobal,
                mElement: kAudioObjectPropertyElementMain
            )
            var terminalType: UInt32 = kAudioStreamTerminalTypeUnknown
            var terminalSize = UInt32(MemoryLayout<UInt32>.size)
            guard AudioObjectGetPropertyData(
                streamID, &terminalAddress, 0, nil, &terminalSize, &terminalType
            ) == noErr else { return nil }
            return terminalType
        })
    }

    private nonisolated static func preflightStorage(at directory: URL, trackCount: Int) throws {
        let values = try directory.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
        let required = MeetingPCMStoragePolicy.requiredFreeBytes(trackCount: trackCount)
        guard let capacity = values.volumeAvailableCapacityForImportantUsage, capacity >= required else {
            throw MeetingCaptureError.insufficientDiskSpace
        }
    }
}

nonisolated protocol MeetingCaptureRuntime: AnyObject, Sendable {
    /// The ScreenCaptureKit scope actually in effect. `nil` for runtimes with no SCK stream.
    var captureScope: MeetingCaptureScope? { get }
    func start() async throws
    func stop() async throws
}

/// A candidate window for `.window`-scoped capture, in a shape independent of ScreenCaptureKit
/// so the selection logic can be unit tested with plain values.
nonisolated struct MeetingWindowCandidate: Sendable, Equatable {
    var windowID: UInt32
    var title: String?
    var frame: CGRect
    var layer: Int
    /// Index within `SCShareableContent.windows`, which is ordered front-to-back.
    var zOrderIndex: Int
}

/// Pure selection logic for Phase 1c window-scoped capture: excludes panels/menubar items
/// (non-zero layer) and slivers (sub-200x100), then ranks titled-frontmost-largest-stablest.
nonisolated enum MeetingWindowSelector {
    static let minimumWidth: CGFloat = 200
    static let minimumHeight: CGFloat = 100

    /// `preferredWindowID` — typically the window auto-detection found evidence in — wins outright
    /// when it is still among the eligible candidates; otherwise falls back to ranked selection.
    static func selectWindow(from candidates: [MeetingWindowCandidate], preferredWindowID: UInt32? = nil) -> MeetingWindowCandidate? {
        let eligible = candidates
            .filter { $0.layer == 0 && $0.frame.width >= self.minimumWidth && $0.frame.height >= self.minimumHeight }
        if let preferredWindowID, let preferred = eligible.first(where: { $0.windowID == preferredWindowID }) {
            return preferred
        }
        return eligible.sorted(by: self.isRanked).first
    }

    /// True when `lhs` should be preferred over `rhs`: non-empty title, then frontmost
    /// (lower z-order), then larger area, then windowID ascending as the stable tiebreak.
    private static func isRanked(_ lhs: MeetingWindowCandidate, _ rhs: MeetingWindowCandidate) -> Bool {
        let lhsHasTitle = lhs.title?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false
        let rhsHasTitle = rhs.title?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false
        if lhsHasTitle != rhsHasTitle { return lhsHasTitle }
        if lhs.zOrderIndex != rhs.zOrderIndex { return lhs.zOrderIndex < rhs.zOrderIndex }
        let lhsArea = lhs.frame.width * lhs.frame.height
        let rhsArea = rhs.frame.width * rhs.frame.height
        if lhsArea != rhsArea { return lhsArea > rhsArea }
        return lhs.windowID < rhs.windowID
    }
}

/// Health of the CoreAudio listener set backing a route observation. A degraded observation means
/// at least one required listener is missing, so the route can change without any further
/// notification: the owner must fail closed instead of silently operating unlistened.
nonisolated enum MeetingOutputRouteListenerHealth: Equatable, Sendable {
    case healthy
    case degraded
}

/// Identity of the SCK producer the runtime owns, plus the route revision that authorized it.
/// Publication and AEC commit are both gated on this triple, so an in-flight operation can compare
/// the value it captured against the live one without retaining `SCStream`.
nonisolated struct MeetingCaptureStreamOwnership: Equatable, Sendable {
    var streamIdentity: UInt64
    var streamGeneration: UInt64
    var routeRevision: UInt64
}

/// Result of the final pending -> current publication decision.
nonisolated enum MeetingCaptureStreamPublication: Equatable, Sendable {
    /// Ownership matched: publish the candidate.
    case commit
    /// A newer revision or an ordered stop owns the outcome. Quietly abandon — never terminal.
    case superseded
    /// The candidate itself died. This is a real failure and stays terminal.
    case failed
}

/// Commit-time authority shared by stream publication, AEC installation, and route-protection
/// scheduling. Pure so the revision/ownership rules are testable without an `SCStream`.
nonisolated enum MeetingCaptureOwnershipGate {
    /// A newer `outputRouteRevision` is normal supersession, never a failure.
    static func isSuperseded(observedRevision: UInt64, currentRevision: UInt64) -> Bool {
        observedRevision != currentRevision
    }

    /// Queued route-protection work whose revision has already been superseded must not run at
    /// all — not even to pay its debounce sleep.
    static func shouldRunRouteProtection(
        taskRevision: UInt64,
        currentRevision: UInt64,
        stopping: Bool
    ) -> Bool {
        !stopping && !self.isSuperseded(observedRevision: taskRevision, currentRevision: currentRevision)
    }

    /// The replacement may only be published when the runtime still owns exactly the producers the
    /// replacement was built against, under the revision that authorized it.
    static func mayPublishReplacement(
        authorizedRevision: UInt64,
        currentRevision: UInt64,
        stopping: Bool,
        candidateFailed: Bool,
        ownsExpectedOldStream: Bool,
        ownsPendingCandidate: Bool
    ) -> MeetingCaptureStreamPublication {
        guard !stopping else { return .superseded }
        guard !self.isSuperseded(observedRevision: authorizedRevision, currentRevision: currentRevision) else {
            return .superseded
        }
        guard !candidateFailed else { return .failed }
        guard ownsExpectedOldStream, ownsPendingCandidate else { return .superseded }
        return .commit
    }

    // Direct AEC3 may only be committed onto the exact producer generation it was reserved for,
    // while that producer is running and no rebuild owns it.
    // Keep the existing capture/processing contract explicit during integration.
    // swiftlint:disable:next function_parameter_count
    static func mayCommitAEC(
        reserved: MeetingCaptureStreamOwnership,
        current: MeetingCaptureStreamOwnership,
        stopping: Bool,
        rebuilding: Bool,
        currentStreamStopped: Bool,
        routeListenerDegraded: Bool,
        dispositionIsSupportedSpeaker: Bool,
        activationGeneration: UInt64,
        reservationToken: UInt64
    ) -> Bool {
        guard !stopping, !rebuilding, !currentStreamStopped, !routeListenerDegraded else { return false }
        guard dispositionIsSupportedSpeaker else { return false }
        guard activationGeneration == reservationToken else { return false }
        return reserved == current
    }
}

/// Runtime authority for the pre-production direct AEC3 rollout. All build configurations honour
/// the `FLUIDVOICE_DISABLE_AEC3` kill switch. The route classifier and installer both read this
/// function so selection and construction cannot diverge.
nonisolated enum MeetingDirectAEC3Availability {
    static func isAvailable(killSwitchEngaged: Bool) -> Bool {
        !killSwitchEngaged
    }

    static func isAvailable(environment: [String: String] = ProcessInfo.processInfo.environment) -> Bool {
        self.isAvailable(
            killSwitchEngaged: !MeetingDirectAEC3Gate.enabled(environment: environment)
        )
    }
}

private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCaptureRuntime, SCStreamOutput, SCStreamDelegate,
    @unchecked Sendable
{
    private let comparisonProbe: MeetingAudioComparisonProbe?
    private let microphonePCMNormalizer = MeetingMicrophonePCMNormalizer()
    /// HAL notifications can arrive while the default input/output pair is still converging.
    /// Admission stays closed until the latest route revision has settled.
    private static let rawRouteSettleSeconds: Double = 0.75

    private struct BuiltStream {
        let stream: SCStream
        let delegateProxy: ScreenCaptureRuntimeDelegateProxy
        let scope: MeetingCaptureScope
    }

    /// Delays before each of the (up to 3) rebuild attempts following an unexpected stream stop.
    private static let rebuildDelays: [TimeInterval] = [0.5, 1.0, 2.0]

    private let application: MeetingApplicationIdentity
    private let requestedMicrophone: MeetingMicrophoneIdentity
    /// Immutable for the runtime's lifetime: a rebuild never drops/adds the mic.
    private let includeMicrophone: Bool
    private let microphoneTranscriptGate: MeetingMicrophoneTranscriptGate
    private let applicationWriter: MeetingAudioChunkWriter
    private let microphoneWriter: MeetingAudioChunkWriter
    private let eventHandler: @Sendable (MeetingCaptureEvent) -> Void
    private let liveAudioHandler: (@Sendable (MeetingAudioTrackKind, CMSampleBuffer) -> Void)?
    private let callbackQueue = DispatchQueue(
        label: "com.fluidvoice.meeting.screencapture.samples",
        qos: .userInteractive
    )
    private let callbackQueueKey = DispatchSpecificKey<UInt8>()
    #if DEBUG
    private let pairedDiagnosticCollector: MeetingSCKPairedDiagnosticCollector
    // Keep the descriptive diagnostic contract name consistent with its persisted field.
    // swiftlint:disable:next identifier_name
    private var pairedDiagnosticProvenanceFailureReported = false
    private var pairedDiagnosticReportEmitted = false
    #endif
    private let stateLock = NSLock()
    private var stream: SCStream
    /// The device actually bound into the current SCK producer epoch. The requested microphone is
    /// retained separately so a route-driven default-input change is explicit in capture eras.
    private var activeMicrophone: MeetingMicrophoneIdentity
    private var scope: MeetingCaptureScope
    private var delegateProxy: ScreenCaptureRuntimeDelegateProxy?
    private var stopping = false
    /// Explicit rebuild ownership instead of a bare flag. A rebuild holds its token from the moment
    /// it claims the producer until publication, and only the holder may release it, so a rebuild
    /// started by a racing `didStop` can never have its ownership cleared by the loser's `defer`.
    private var rebuildOwner: UInt64?
    private var nextRebuildOwnerToken: UInt64 = 0
    /// Must be read with `stateLock` held.
    private var rebuilding: Bool { self.rebuildOwner != nil }
    /// Unlike `rebuilding`, this records the actual ownership state of `stream`. It lets stop avoid
    /// re-stopping a producer that was deliberately retired even if replacement construction fails.
    private var currentStreamStopped = false
    private var pendingStream: SCStream?
    private var pendingStreamFailed = false
    private var outputRouteListener: MeetingOutputRouteListener?
    /// Sticky: once a required CoreAudio listener is gone, later route observations are unreliable
    /// for the rest of the session, so admission and AEC stay fail-closed.
    private var routeListenerDegraded = false
    private var outputRouteRevision: UInt64 = 0
    private var streamGeneration: UInt64 = 1
    private var aecActivation = MeetingAECActivationController()
    private var aecPipeline: MeetingAECPipeline?
    private var retiredAECCommitters: [MeetingAECOutputCommitter] = []
    private var routeDisposition: MeetingAECOutputRouteDisposition = .ambiguous
    private var captureStarted = false
    private var routeSafetyPersistenceFailed = false
    private let rebuildGroup = DispatchGroup()
    private let routeProtectionTasks = MeetingAsyncTaskChain()

    var captureScope: MeetingCaptureScope? {
        self.stateLock.withLock { self.scope }
    }

    private init(
        stream: SCStream,
        scope: MeetingCaptureScope,
        application: MeetingApplicationIdentity,
        requestedMicrophone: MeetingMicrophoneIdentity,
        activeMicrophone: MeetingMicrophoneIdentity,
        includeMicrophone: Bool,
        comparisonProbe: MeetingAudioComparisonProbe?,
        microphoneEchoProtection: MeetingMicrophoneEchoProtection,
        applicationWriter: MeetingAudioChunkWriter,
        microphoneWriter: MeetingAudioChunkWriter,
        eventHandler: @escaping @Sendable (MeetingCaptureEvent) -> Void,
        liveAudioHandler: (@Sendable (MeetingAudioTrackKind, CMSampleBuffer) -> Void)?
    ) {
        self.comparisonProbe = comparisonProbe
        self.stream = stream
        self.scope = scope
        self.application = application
        self.requestedMicrophone = requestedMicrophone
        self.activeMicrophone = activeMicrophone
        self.includeMicrophone = includeMicrophone
        self.microphoneTranscriptGate = MeetingMicrophoneTranscriptGate(
            includeMicrophone ? .unprotected : microphoneEchoProtection
        )
        self.applicationWriter = applicationWriter
        self.microphoneWriter = microphoneWriter
        self.eventHandler = eventHandler
        self.liveAudioHandler = liveAudioHandler
        #if DEBUG
        self.pairedDiagnosticCollector = MeetingSCKPairedDiagnosticCollector()
        #endif
        super.init()
        self.callbackQueue.setSpecific(key: self.callbackQueueKey, value: 1)
    }

    static func make(
        application: MeetingApplicationIdentity,
        microphone: MeetingMicrophoneIdentity,
        includeMicrophone: Bool = true,
        comparisonProbe: MeetingAudioComparisonProbe? = nil,
        microphoneEchoProtection: MeetingMicrophoneEchoProtection = .unprotected,
        applicationWriter: MeetingAudioChunkWriter,
        microphoneWriter: MeetingAudioChunkWriter,
        eventHandler: @escaping @Sendable (MeetingCaptureEvent) -> Void,
        liveAudioHandler: (@Sendable (MeetingAudioTrackKind, CMSampleBuffer) -> Void)?
    ) async throws -> ScreenCaptureMeetingRuntime {
        // Initial capture honors the microphone shown at confirmation. Route recovery
        // can elect a replacement later, but starting cannot silently switch inputs.
        let resolvedMicrophone = includeMicrophone
            ? try MeetingAVCaptureMicrophoneResolver.resolve(microphone)
            : microphone
        let built = try await Self.buildStream(
            application: application,
            microphone: resolvedMicrophone,
            includeMicrophone: includeMicrophone
        )
        if includeMicrophone {
            try await microphoneWriter.updateTrackMetadata { track in
                guard var eras = track.captureEras, !eras.isEmpty else { return }
                eras[0].deviceUID = resolvedMicrophone.coreAudioUID
                eras[0].deviceName = resolvedMicrophone.displayName
                eras[0].roleAtElection = .unknown
                track.captureEras = eras
            }
        }
        let runtime = ScreenCaptureMeetingRuntime(
            stream: built.stream,
            scope: built.scope,
            application: application,
            requestedMicrophone: microphone,
            activeMicrophone: resolvedMicrophone,
            includeMicrophone: includeMicrophone,
            comparisonProbe: comparisonProbe,
            microphoneEchoProtection: microphoneEchoProtection,
            applicationWriter: applicationWriter,
            microphoneWriter: microphoneWriter,
            eventHandler: eventHandler,
            liveAudioHandler: liveAudioHandler
        )
        built.delegateProxy.owner = runtime
        runtime.delegateProxy = built.delegateProxy
        try runtime.attachOutputs(to: built.stream)
        return runtime
    }

    /// Resolves the shareable content, filter, configuration and stream. Re-invoked both for the
    /// initial `make` and for every rebuild attempt after an unexpected stream stop.
    private static func buildStream(
        application: MeetingApplicationIdentity,
        microphone: MeetingMicrophoneIdentity,
        includeMicrophone: Bool,
        allowApplicationRelaunch: Bool = false
    ) async throws -> BuiltStream {
        let content: SCShareableContent
        do {
            content = try await SCShareableContent.current
        } catch {
            throw MeetingCaptureError.screenCapturePermissionDenied(error.localizedDescription)
        }
        let candidates = content.applications.map {
            MeetingApplicationIdentity(bundleIdentifier: $0.bundleIdentifier, processID: $0.processID, displayName: $0.applicationName)
        }
        var requested = application
        // Only an already-running recording may recover after the app relaunches.
        // Initial capture must use exactly the process the user confirmed.
        if allowApplicationRelaunch, !candidates.contains(where: { $0.processID == application.processID && $0.bundleIdentifier == application.bundleIdentifier }) {
            requested.processID = nil
        }
        let resolved = try MeetingRecordingSourceResolver.resolve(
            mode: .onlineCall, source: MeetingRecordingSource(application: requested), target: nil, applications: candidates
        )
        guard let runningApplication = content.applications.first(where: { $0.processID == resolved?.processID }) else {
            throw MeetingCaptureError.applicationUnavailable(application.displayName)
        }

        let filter: SCContentFilter
        let scope: MeetingCaptureScope
        if let window = Self.selectWindow(for: runningApplication, in: content, preferredWindowID: application.windowID) {
            filter = SCContentFilter(desktopIndependentWindow: window)
            scope = .window
        } else {
            let display = application.displayID.flatMap { displayID in
                content.displays.first(where: { $0.displayID == displayID })
            } ?? content.displays.first
            guard let display else { throw MeetingCaptureError.noCaptureDisplay }
            filter = SCContentFilter(display: display, including: [runningApplication], exceptingWindows: [])
            scope = .display
        }

        let configuration = SCStreamConfiguration()
        configuration.width = 2
        configuration.height = 2
        configuration.minimumFrameInterval = CMTime(value: 1, timescale: 1)
        configuration.queueDepth = 3
        configuration.showsCursor = false
        MeetingScreenCaptureAudioSettings.apply(to: configuration, microphone: microphone, includeMicrophone: includeMicrophone)

        let delegateProxy = ScreenCaptureRuntimeDelegateProxy()
        let stream = SCStream(filter: filter, configuration: configuration, delegate: delegateProxy)
        return BuiltStream(stream: stream, delegateProxy: delegateProxy, scope: scope)
    }

    /// Maps the app's own windows to selection candidates and picks one via `MeetingWindowSelector`.
    /// Deliberately does not require `isOnScreen` (unreliable for other-Space/hidden windows).
    /// Window titles are PII and must never be logged or persisted.
    private static func selectWindow(
        for runningApplication: SCRunningApplication,
        in content: SCShareableContent,
        preferredWindowID: UInt32? = nil
    ) -> SCWindow? {
        let ownedWindows = content.windows.enumerated().filter { _, window in
            window.owningApplication?.processID == runningApplication.processID
        }
        let candidates = ownedWindows.map { index, window in
            MeetingWindowCandidate(
                windowID: window.windowID,
                title: window.title,
                frame: window.frame,
                layer: window.windowLayer,
                zOrderIndex: index
            )
        }
        guard let winner = MeetingWindowSelector.selectWindow(from: candidates, preferredWindowID: preferredWindowID) else { return nil }
        return ownedWindows.first(where: { _, window in window.windowID == winner.windowID })?.element
    }

    private func attachOutputs(to stream: SCStream) throws {
        try stream.addStreamOutput(
            self,
            type: .audio,
            sampleHandlerQueue: self.callbackQueue
        )
        guard self.includeMicrophone else { return }
        try stream.addStreamOutput(
            self,
            type: .microphone,
            sampleHandlerQueue: self.callbackQueue
        )
    }

    func start() async throws {
        var installedListener: MeetingOutputRouteListener?
        if self.includeMicrophone {
            installedListener = await MeetingOutputRouteListener.make { [weak self] health in
                self?.invalidateRawMicrophoneAdmissionAfterRouteChange(listenerHealth: health)
            }
            let baselineRevision = self.stateLock.withLock { () -> UInt64 in
                self.outputRouteListener = installedListener
                return self.outputRouteRevision
            }
            try? await Task.sleep(nanoseconds: UInt64(Self.rawRouteSettleSeconds * 1_000_000_000))
            var firstSnapshot = MeetingCaptureEngine.currentOutputRouteSnapshot()
            try? await Task.sleep(nanoseconds: 100_000_000)
            var secondSnapshot = MeetingCaptureEngine.currentOutputRouteSnapshot()
            var settleAttempts = 1
            while firstSnapshot != secondSnapshot,
                  settleAttempts < 3,
                  self.stateLock.withLock({ self.outputRouteRevision == baselineRevision && !self.stopping })
            {
                settleAttempts += 1
                try? await Task.sleep(nanoseconds: 250_000_000)
                firstSnapshot = MeetingCaptureEngine.currentOutputRouteSnapshot()
                try? await Task.sleep(nanoseconds: 100_000_000)
                secondSnapshot = MeetingCaptureEngine.currentOutputRouteSnapshot()
            }
            let stable = installedListener != nil && self.stateLock.withLock {
                self.outputRouteRevision == baselineRevision && !self.stopping && !self.routeListenerDegraded
            }
            let disposition = MeetingAECOutputRouteClassifier.classify(
                first: firstSnapshot,
                second: secondSnapshot,
                revisionStayedStable: stable,
                debugDisabled: !Self.directAEC3Available
            )
            do {
                try await self.applySettledRouteDisposition(disposition, revision: baselineRevision)
            } catch {
                await installedListener?.stop()
                self.stateLock.withLock { self.outputRouteListener = nil }
                throw error
            }
        }
        let currentStream = self.stateLock.withLock { self.stream }
        let mayStart = self.stateLock.withLock { () -> Bool in
            guard !self.stopping else { return false }
            return self.aecActivation.allowsInitialCaptureStart(hasCandidate: self.aecPipeline != nil)
        }
        guard mayStart else {
            await installedListener?.stop()
            throw MeetingCaptureError.captureStartFailed("The audio route changed during AEC setup.")
        }
        do {
            try await currentStream.startCapture()
        } catch {
            await installedListener?.stop()
            self.stateLock.withLock { self.outputRouteListener = nil }
            throw MeetingCaptureError.captureStartFailed(error.localizedDescription)
        }
        var stalePipeline: MeetingAECPipeline?
        var startupLostStreamOwnership = false
        self.stateLock.withLock {
            self.captureStarted = true
            if !self.stopping,
               !self.rebuilding,
               !self.currentStreamStopped,
               currentStream === self.stream,
               self.aecActivation.armReadyCandidate()
            {
                // The controller now owns the armed/raw first-format handshake.
            } else if self.aecPipeline != nil, self.aecActivation.state != .raw {
                stalePipeline = self.aecPipeline
                self.aecPipeline = nil
                self.aecActivation.invalidate()
            }
            startupLostStreamOwnership = self.stopping
                || self.currentStreamStopped
                || currentStream !== self.stream
        }
        if let stalePipeline {
            let boundary = self.microphoneTranscriptGate.invalidate()
            self.performOnCallbackQueueSynchronously {
                stalePipeline.invalidate(reason: .streamChanged, boundary: boundary)
                self.retainRetiredCommitterIfPending(stalePipeline.committer)
            }
        }
        if startupLostStreamOwnership {
            try? await currentStream.stopCapture()
            throw MeetingCaptureError.captureStartFailed(
                "The initial capture stream lost ownership while it was starting."
            )
        }
    }

    func stop() async throws {
        #if DEBUG
        defer { self.emitPairedDiagnosticReportIfNeeded() }
        #endif
        #if DEBUG
        AudioTopologyDiagnostics.record(.phaseBegin, owner: .screenCapture, queueRole: .actorControl, phase: .screenCaptureStop)
        defer { AudioTopologyDiagnostics.record(.phaseEnd, owner: .screenCapture, queueRole: .actorControl, phase: .screenCaptureStop) }
        #endif
        self.markStopping()
        let boundary = self.microphoneTranscriptGate.invalidate()
        let routeListener = self.stateLock.withLock { () -> MeetingOutputRouteListener? in
            defer { self.outputRouteListener = nil }
            return self.outputRouteListener
        }
        await routeListener?.stop()
        await self.routeProtectionTasks.drain()
        let (currentStream, streamAlreadyDead) = self.stateLock.withLock { (self.stream, self.currentStreamStopped) }
        // Mid-rebuild the current stream already stopped on its own; stopCapture would only time out.
        var stopFailure: String?
        if !streamAlreadyDead {
            let result = await withCheckedContinuation { continuation in
                let completion = MeetingOneShotCompletion(continuation)
                currentStream.stopCapture { error in
                    if let error {
                        completion.resume(.failure(error.localizedDescription))
                    } else {
                        completion.resume(.success)
                    }
                }
                DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 3) {
                    completion.resume(.failure("Timed out while stopping system-audio capture."))
                }
            }
            if case let .failure(detail) = result { stopFailure = detail }
        }
        await withCheckedContinuation { continuation in
            self.rebuildGroup.notify(queue: .global(qos: .userInitiated)) {
                continuation.resume()
            }
        }
        var stoppedPipeline: MeetingAECPipeline?
        self.performOnCallbackQueueSynchronously {
            stoppedPipeline = self.stateLock.withLock { () -> MeetingAECPipeline? in
                defer {
                    self.aecPipeline = nil
                    self.aecActivation.invalidate()
                }
                return self.aecPipeline
            }
            stoppedPipeline?.stop(boundary: boundary)
        }
        let committers = self.stateLock.withLock { () -> [MeetingAECOutputCommitter] in
            defer { self.retiredAECCommitters.removeAll() }
            return self.retiredAECCommitters + (stoppedPipeline.map { [$0.committer] } ?? [])
        }
        for committer in committers {
            await committer.waitForPendingCommits()
        }
        if let stopFailure {
            throw MeetingCaptureRuntimeError.stopFailed(stopFailure)
        }
    }

    private func markStopping() {
        self.stateLock.withLock { self.stopping = true }
    }

    private func performOnCallbackQueueSynchronously(_ operation: () -> Void) {
        if DispatchQueue.getSpecific(key: self.callbackQueueKey) != nil {
            operation()
        } else {
            self.callbackQueue.sync(execute: operation)
        }
    }

    func stream(
        _ stream: SCStream,
        didOutputSampleBuffer sampleBuffer: CMSampleBuffer,
        of outputType: SCStreamOutputType
    ) {
        let callbackState = self.stateLock.withLock {
            () -> (MeetingAECActivationState, MeetingAECPipeline?, MeetingAECStreamToken)? in
            guard !self.stopping, stream === self.stream else { return nil }
            let identity = UInt64(UInt(bitPattern: Unmanaged.passUnretained(stream).toOpaque()))
            return (
                self.aecActivation.state,
                self.aecPipeline,
                MeetingAECStreamToken(generation: self.streamGeneration, identity: identity)
            )
        }
        guard let (aecState, pipeline, streamToken) = callbackState else { return }
        switch outputType {
        case .audio:
            #if DEBUG
            self.recordPairedDiagnostic(sampleBuffer, output: .applicationAudio)
            #endif
            switch aecState {
            case .active:
                pipeline?.consumeRender(sampleBuffer, stream: streamToken)
            case .armed:
                self.validateArmedCallback(
                    sampleBuffer,
                    kind: .render,
                    stream: stream,
                    token: streamToken
                )
            case .raw, .constructing, .ready:
                break
            }
            self.applicationWriter.enqueue(sampleBuffer, producerEpoch: streamToken.generation)
            self.liveAudioHandler?(.applicationAudio, sampleBuffer)
        case .microphone:
            #if DEBUG
            self.recordPairedDiagnostic(sampleBuffer, output: .microphone)
            #endif
            let sampleBuffer = self.microphonePCMNormalizer.normalize(sampleBuffer)
            self.comparisonProbe?.offer(sampleBuffer, stage: .microphoneInput, producerEpoch: streamToken.generation)
            switch aecState {
            case .active:
                pipeline?.consumeCapture(sampleBuffer, stream: streamToken)
            case .armed:
                self.validateArmedCallback(
                    sampleBuffer,
                    kind: .capture,
                    stream: stream,
                    token: streamToken
                )
                self.emitDirectRawMicrophone(sampleBuffer, producerEpoch: streamToken.generation)
            case .raw, .constructing, .ready:
                self.emitDirectRawMicrophone(sampleBuffer, producerEpoch: streamToken.generation)
            }
        case .screen:
            break
        @unknown default:
            break
        }
    }

    /// Single availability authority for this runtime. The route classifier and the AEC installer
    /// both read it, so the classification gate and the construction gate cannot diverge.
    private static var directAEC3Available: Bool {
        MeetingDirectAEC3Availability.isAvailable()
    }

    private func emitDirectRawMicrophone(_ sampleBuffer: CMSampleBuffer, producerEpoch: UInt64) {
        self.microphoneWriter.enqueue(sampleBuffer, producerEpoch: producerEpoch)
        if self.microphoneTranscriptGate.observeAndAdmit(sampleBuffer) {
            self.liveAudioHandler?(.microphone, sampleBuffer)
        }
    }

    /// Armed validation callbacks stay on the raw path. Only a later callback can observe active,
    /// guaranteeing the joiner starts with a fresh pair after both real SCK formats were accepted.
    private func validateArmedCallback(
        _ sampleBuffer: CMSampleBuffer,
        kind: MeetingAECInputKind,
        stream: SCStream,
        token: MeetingAECStreamToken
    ) {
        if self.stateLock.withLock({ self.aecActivation.formatValidationTimedOut() }) {
            self.deactivateAECOnCallbackQueue(reason: .formatValidationTimedOut)
            return
        }
        if let failure = MeetingAECPipeline.firstFormatFailure(sampleBuffer, kind: kind, stream: token) {
            self.deactivateAECOnCallbackQueue(reason: failure)
            return
        }
        self.stateLock.withLock {
            guard !self.stopping, stream === self.stream,
                  case let .armed(generation, _, _) = self.aecActivation.state,
                  generation == self.aecActivation.generation
            else { return }
            self.aecActivation.observeValidatedFormat(kind: kind, token: generation)
        }
    }

    /// Must be called on `callbackQueue`; it clears the shared state before touching/destroying the
    /// detached engine, so no later callback can acquire an object pending reset.
    private func deactivateAECOnCallbackQueue(reason: MeetingAECFailure) {
        let boundary = self.microphoneTranscriptGate.invalidate()
        let detached = self.stateLock.withLock { () -> MeetingAECPipeline? in
            self.aecActivation.invalidate()
            defer { self.aecPipeline = nil }
            return self.aecPipeline
        }
        detached?.invalidate(reason: reason, boundary: boundary)
        if let detached { self.retainRetiredCommitterIfPending(detached.committer) }
        let revision = self.stateLock.withLock { self.outputRouteRevision }
        self.routeProtectionTasks.enqueue { [weak self] in
            guard let self, self.isCurrentRouteRevision(revision) else { return }
            do {
                try await self.resumeDirectMicrophone(.unfiltered, revision: revision)
            } catch {
                self.handleAECTerminalFailure(.metadataPersistence)
            }
        }
    }

    private func applySettledRouteDisposition(
        _ disposition: MeetingAECOutputRouteDisposition,
        revision: UInt64
    ) async throws {
        let stillCurrent = self.stateLock.withLock { () -> Bool in
            guard self.outputRouteRevision == revision, !self.stopping else { return false }
            self.routeDisposition = disposition
            return true
        }
        guard stillCurrent else { return }

        switch disposition {
        case .physicallyClosed:
            try await self.resumeDirectMicrophone(.acousticallyClosed, revision: revision)
        case .supportedSpeaker:
            let start = self.microphoneTranscriptGate.latestObservedSeconds()
            try await self.microphoneWriter.updateTrackMetadataFailClosed { track in
                MeetingAECOutputCommitter.applyEra(
                    to: &track,
                    protection: .unprotected,
                    provenance: nil,
                    startSeconds: start
                )
            }
            _ = self.microphoneTranscriptGate.invalidate()
            do {
                try await self.installAECForSupportedSpeaker(revision: revision)
            } catch {
                try await self.resumeDirectMicrophone(.unfiltered, revision: revision)
            }
        case .ambiguous:
            try await self.resumeDirectMicrophone(.unfiltered, revision: revision)
        }
    }

    /// Echo provenance and live delivery commit together, without changing capture method or
    /// restarting either device. A stale route cannot reopen the gate after a newer invalidation.
    private func resumeDirectMicrophone(_ protection: MeetingMicrophoneEchoProtection, revision: UInt64) async throws {
        guard self.stateLock.withLock({
            self.outputRouteRevision == revision && !self.stopping && !self.rebuilding && !self.currentStreamStopped
        }) else { return }
        let gateEpoch = self.microphoneTranscriptGate.invalidationEpoch
        let start = self.microphoneTranscriptGate.latestObservedSeconds()
        try await self.microphoneWriter.updateTrackMetadataFailClosed { track in
            MeetingAECOutputCommitter.applyEra(to: &track, protection: protection, provenance: nil, startSeconds: start)
        }
        let mayOpen = self.stateLock.withLock {
            self.outputRouteRevision == revision && !self.stopping && !self.rebuilding && !self.currentStreamStopped
        }
        if mayOpen, self.microphoneTranscriptGate.updateIfNotInvalidated(protection, since: gateEpoch) {
            self.eventHandler(.microphoneEchoProtectionChanged(protection))
        } else {
            let unsafeStart = self.microphoneTranscriptGate.invalidate()?.unsafeStartSeconds
            try await self.microphoneWriter.updateTrackMetadataFailClosed { track in
                MeetingAECOutputCommitter.applyEra(to: &track, protection: .unprotected, provenance: nil, startSeconds: unsafeStart)
            }
        }
    }

    private func installAECForSupportedSpeaker(revision: UInt64) async throws {
        // Release must never construct or install direct AEC3; Debug honours the kill switch.
        guard Self.directAEC3Available else { return }
        // Construction is bound to one precise producer: object identity, stream generation, and
        // the route revision that authorized it. Everything below re-checks that exact triple.
        let reserved = self.stateLock.withLock { () -> (ownership: MeetingCaptureStreamOwnership, token: UInt64)? in
            guard !self.stopping,
                  !self.rebuilding,
                  !self.currentStreamStopped,
                  !self.routeListenerDegraded,
                  self.outputRouteRevision == revision,
                  self.routeDisposition == .supportedSpeaker,
                  self.aecPipeline == nil,
                  let token = self.aecActivation.reserveConstruction()
            else { return nil }
            return (self.currentStreamOwnershipLocked(), token)
        }
        guard let reserved else { return }

        let processor: MeetingAECProcessor
        do {
            processor = try MeetingAECProcessor()
        } catch {
            self.stateLock.withLock {
                self.aecActivation.abandonConstruction(reserved.token)
            }
            throw error
        }
        let committer = MeetingAECOutputCommitter(
            writer: self.microphoneWriter,
            producerEpoch: reserved.ownership.streamGeneration,
            transcriptGate: self.microphoneTranscriptGate,
            liveAudioHandler: self.liveAudioHandler,
            protectionChanged: { [eventHandler = self.eventHandler] protection in
                eventHandler(.microphoneEchoProtectionChanged(protection))
            }
        ) { [weak self] failure in
            self?.handleAECTerminalFailure(failure)
        }
        let candidate = MeetingAECPipeline(
            processor: processor,
            committer: committer,
            diagnosticObserver: self.comparisonProbe.map { probe in
                { frame, output, statistics in
                    probe.recordAECFrame(frame, output: output, statistics: statistics)
                }
            }
        )

        let committed = self.stateLock.withLock { () -> Bool in
            let mayCommit = MeetingCaptureOwnershipGate.mayCommitAEC(
                reserved: reserved.ownership,
                current: self.currentStreamOwnershipLocked(),
                stopping: self.stopping,
                rebuilding: self.rebuilding,
                currentStreamStopped: self.currentStreamStopped,
                routeListenerDegraded: self.routeListenerDegraded,
                dispositionIsSupportedSpeaker: self.routeDisposition == .supportedSpeaker,
                activationGeneration: self.aecActivation.generation,
                reservationToken: reserved.token
            )
            guard mayCommit, self.aecActivation.commitCandidate(reserved.token) else {
                // The producer this engine was bound to is gone. Release the reservation so a
                // later generation can construct again instead of being stuck `.constructing`.
                self.aecActivation.abandonConstruction(reserved.token)
                return false
            }
            self.aecPipeline = candidate
            return true
        }
        // The uncommitted candidate is simply dropped: it was never published, never fed a
        // callback, and holds no writer state.
        guard committed else { return }

        // A route-time construction has no startCapture flight. Recheck the same ownership once
        // more and arm it; startup construction remains ready until startCapture itself returns.
        self.stateLock.withLock {
            guard self.captureStarted,
                  !self.stopping,
                  !self.rebuilding,
                  !self.currentStreamStopped,
                  self.outputRouteRevision == revision,
                  self.currentStreamOwnershipLocked() == reserved.ownership,
                  self.aecActivation.generation == reserved.token
            else { return }
            _ = self.aecActivation.armReadyCandidate()
        }
    }

    /// Must be called with `stateLock` held. Pointer identity alone can repeat after a dealloc, so
    /// it is always paired with the monotonic stream generation.
    private func currentStreamOwnershipLocked() -> MeetingCaptureStreamOwnership {
        MeetingCaptureStreamOwnership(
            streamIdentity: UInt64(UInt(bitPattern: Unmanaged.passUnretained(self.stream).toOpaque())),
            streamGeneration: self.streamGeneration,
            routeRevision: self.outputRouteRevision
        )
    }

    /// True while this revision is still the commit-time authority.
    private func isCurrentRouteRevision(_ revision: UInt64) -> Bool {
        self.stateLock.withLock {
            MeetingCaptureOwnershipGate.shouldRunRouteProtection(
                taskRevision: revision,
                currentRevision: self.outputRouteRevision,
                stopping: self.stopping
            )
        }
    }

    /// Must be called with `stateLock` held.
    private func beginRebuildLocked() -> UInt64 {
        self.nextRebuildOwnerToken &+= 1
        self.rebuildOwner = self.nextRebuildOwnerToken
        return self.nextRebuildOwnerToken
    }

    /// Must be called with `stateLock` held. Only the current owner may release ownership.
    @discardableResult
    private func endRebuildLocked(_ token: UInt64) -> Bool {
        guard self.rebuildOwner == token else { return false }
        self.rebuildOwner = nil
        return true
    }

    private func handleAECTerminalFailure(_ failure: MeetingAECFailure) {
        let shouldReport = self.stateLock.withLock { () -> Bool in
            // An ordered user/rebuild stop already closed admission and owns the terminal event.
            guard !self.stopping, !self.routeSafetyPersistenceFailed else { return false }
            self.routeSafetyPersistenceFailed = true
            self.stopping = true
            self.aecActivation.invalidate()
            return true
        }
        guard shouldReport else { return }
        _ = self.microphoneTranscriptGate.invalidate()
        self.eventHandler(.interrupted(
            kind: .captureStoppedUnexpectedly,
            trackID: self.microphoneWriter.trackID,
            detail: "AEC microphone pipeline failed closed (\(failure.rawValue)); recording was stopped to preserve transcript safety."
        ))
    }

    #if DEBUG
    /// Captures only callback-boundary numeric metadata. The selected-app scope assertion is
    /// reconstructed from the active SCK filter; no application identity enters the diagnostic.
    private func recordPairedDiagnostic(_ sampleBuffer: CMSampleBuffer, output: MeetingSCKPairedOutput) {
        guard self.pairedDiagnosticCollector.enabled else { return }
        let scope = self.stateLock.withLock { self.scope }
        let diagnosticScope: MeetingSCKPairedDiagnosticScope
        switch scope {
        case .window: diagnosticScope = .selectedApplicationWindow
        case .display: diagnosticScope = .selectedApplicationDisplay
        }
        let provenance = MeetingSCKPairedDiagnosticProvenance(
            scope: diagnosticScope,
            applicationSelectionConfirmed: true
        )
        let accepted = self.pairedDiagnosticCollector.record(
            sampleBuffer: sampleBuffer,
            output: output,
            provenance: provenance
        )
        guard !accepted else { return }
        let shouldReport = self.stateLock.withLock { () -> Bool in
            guard !self.pairedDiagnosticProvenanceFailureReported else { return false }
            self.pairedDiagnosticProvenanceFailureReported = true
            return true
        }
        if shouldReport {
            let message = "SCK paired diagnostic callback rejected due to scope/provenance change."
            Task { @MainActor in
                DebugLogger.shared.warning(message, source: "MeetingSCKPairedDiagnostics")
            }
        }
    }

    private func emitPairedDiagnosticReportIfNeeded() {
        guard self.pairedDiagnosticCollector.enabled else { return }
        let shouldEmit = self.stateLock.withLock { () -> Bool in
            guard !self.pairedDiagnosticReportEmitted else { return false }
            self.pairedDiagnosticReportEmitted = true
            return true
        }
        guard shouldEmit else { return }
        do {
            let data = try self.pairedDiagnosticCollector.report().jsonData()
            // Diagnostic JSON is emitted as UTF-8; decoding keeps the report output nonoptional.
            // swiftlint:disable:next optional_data_string_conversion
            let json = String(decoding: data, as: UTF8.self)
            let message = "SCK paired diagnostic report " + json
            Task { @MainActor in
                DebugLogger.shared.log(message, source: "MeetingSCKPairedDiagnostics")
            }
        } catch {
            let message = "SCK paired diagnostic report serialization failed."
            Task { @MainActor in
                DebugLogger.shared.warning(message, source: "MeetingSCKPairedDiagnostics")
            }
        }
    }
    #endif

    /// Route observation closes the live gate and publishes `.raw` synchronously. The shared SCK
    /// queue then resets/detaches the old engine and orders the conservative era before later raw
    /// callbacks. Settling always starts from two fresh snapshots.
    private func invalidateRawMicrophoneAdmissionAfterRouteChange(
        listenerHealth: MeetingOutputRouteListenerHealth = .healthy
    ) {
        let revision = self.stateLock.withLock { () -> UInt64? in
            if listenerHealth == .degraded { self.routeListenerDegraded = true }
            guard !self.stopping else { return nil }
            self.outputRouteRevision &+= 1
            self.aecActivation.invalidate()
            self.routeDisposition = .ambiguous
            return self.outputRouteRevision
        }
        guard let revision else { return }
        let boundary = self.microphoneTranscriptGate.invalidate()
        self.performOnCallbackQueueSynchronously {
            let detached = self.stateLock.withLock { () -> MeetingAECPipeline? in
                defer { self.aecPipeline = nil }
                return self.aecPipeline
            }
            if let detached {
                detached.invalidate(reason: .streamChanged, boundary: boundary)
                self.retainRetiredCommitterIfPending(detached.committer)
            } else {
                self.microphoneWriter.enqueueMetadata(
                    failClosed: true,
                    mutate: { track in
                        MeetingAECOutputCommitter.applyEra(
                            to: &track,
                            protection: .unprotected,
                            provenance: nil,
                            startSeconds: boundary?.unsafeStartSeconds
                        )
                    }
                ) { [weak self] result in
                    if case .failure = result {
                        self?.handleAECTerminalFailure(.metadataPersistence)
                    }
                }
            }
        }
        self.routeProtectionTasks.enqueue { [weak self] in
            guard let self else { return }
            if self.stateLock.withLock({ self.routeListenerDegraded }) {
                do {
                    try await self.resumeDirectMicrophone(.unfiltered, revision: revision)
                } catch {
                    self.handleAECTerminalFailure(.metadataPersistence)
                }
                return
            }
            guard let settled = await self.settleRouteAndInput(revision: revision) else { return }
            var disposition = settled.disposition
            var inputDetail: String?
            var replacementMicrophone: MeetingMicrophoneIdentity?
            switch settled.inputTransition {
            case .unavailable:
                disposition = .ambiguous
                inputDetail = "The current default microphone could not be resolved; microphone transcript admission remains disabled."
                replacementMicrophone = self.stateLock.withLock {
                    self.currentStreamStopped ? self.activeMicrophone : nil
                }
            case let .unchanged(election):
                inputDetail = "The capture microphone remained \(election.identity.displayName)."
                replacementMicrophone = self.stateLock.withLock {
                    self.currentStreamStopped ? election.identity : nil
                }
            case let .changed(election):
                replacementMicrophone = election.identity
            }
            if let replacementMicrophone {
                guard await self.waitForInitialCaptureStart(revision: revision) else { return }
                do {
                    let publication = try await self.replaceStreamForRouteChange(
                        with: replacementMicrophone,
                        revision: revision
                    )
                    guard publication == .commit else { return }
                    inputDetail = "Capture moved to the settled microphone \(replacementMicrophone.displayName)."
                } catch {
                    self.reportRouteReplacementFailure(error)
                    return
                }
            }
            do {
                try await self.applySettledRouteDisposition(disposition, revision: revision)
            } catch {
                self.handleAECTerminalFailure(.metadataPersistence)
                return
            }
            self.eventHandler(.interrupted(
                kind: .microphoneChanged,
                trackID: self.microphoneWriter.trackID,
                detail: inputDetail ?? (disposition == .physicallyClosed
                    ? "Microphone transcript admission resumed on a positively identified closed output route."
                    : disposition == .supportedSpeaker
                    ? "Speaker-route AEC restarted unprotected and is awaiting clock attestation and warm-up."
                    : "Microphone transcript admission remains disabled because the output route is ambiguous.")
            ))
        }
    }

    /// Route callbacks are live during initial AEC/stream setup. They may close admission
    /// immediately, but must not retire the initial stream until its start flight has committed.
    private func waitForInitialCaptureStart(revision: UInt64) async -> Bool {
        while true {
            let state = self.stateLock.withLock {
                (started: self.captureStarted, stale: self.stopping || self.outputRouteRevision != revision)
            }
            if state.stale { return false }
            if state.started { return true }
            try? await Task.sleep(nanoseconds: 10_000_000)
        }
    }

    /// Requires two observations taken after the debounce delay. If CoreAudio is still converging,
    /// retry the same revision rather than accepting a mixed pre/post-change pair.
    private func settleRouteAndInput(
        revision: UInt64
    ) async -> (disposition: MeetingAECOutputRouteDisposition, inputTransition: MeetingCaptureDeviceTransition)? {
        // Serialized stale callbacks must not each pay the debounce delay. This check also keeps a
        // listener-health failure sticky: without a complete listener set no later observation can
        // safely reopen transcript admission.
        guard self.isCurrentRouteRevision(revision),
              !self.stateLock.withLock({ self.routeListenerDegraded })
        else { return nil }
        let ownerBusy = self.stateLock.withLock { self.rebuilding }
        if ownerBusy {
            await withCheckedContinuation { continuation in
                self.rebuildGroup.notify(queue: .global(qos: .userInitiated)) {
                    continuation.resume()
                }
            }
            guard self.isCurrentRouteRevision(revision) else { return nil }
        }
        var attempt = 0
        while true {
            guard self.isCurrentRouteRevision(revision) else { return nil }
            let delay = attempt == 0 ? Self.rawRouteSettleSeconds : 0.25
            try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
            guard self.stateLock.withLock({ self.outputRouteRevision == revision && !self.stopping }) else { return nil }
            let first = MeetingCaptureEngine.currentOutputRouteSnapshot()
            try? await Task.sleep(nanoseconds: 100_000_000)
            let second = MeetingCaptureEngine.currentOutputRouteSnapshot()
            guard self.stateLock.withLock({ self.outputRouteRevision == revision && !self.stopping }) else { return nil }
            if first != second {
                attempt += 1
                if attempt < 3 { continue }
            }
            let disposition = MeetingAECOutputRouteClassifier.classify(
                first: first,
                second: second,
                revisionStayedStable: true,
                debugDisabled: !Self.directAEC3Available
            )
            let active = self.stateLock.withLock { self.activeMicrophone }
            let transition = await MeetingCaptureDeviceElection.transition(from: active)
            guard self.stateLock.withLock({ self.outputRouteRevision == revision && !self.stopping }) else { return nil }
            return (disposition, transition)
        }
    }

    /// Performs a route-driven paired-producer handoff with a mandatory gap: the old SCK stream is
    /// fully stopped and its callback queue drained before a replacement is built or started.
    private func replaceStreamForRouteChange(
        with microphone: MeetingMicrophoneIdentity,
        revision: UInt64
    ) async throws -> MeetingCaptureStreamPublication {
        // An unexpected-stop rebuild can win between route settling and acquisition. Wait for its
        // owner rather than turning that benign race into a terminal handoff failure.
        while self.stateLock.withLock({ self.rebuilding }) {
            guard self.isCurrentRouteRevision(revision) else { return .superseded }
            await withCheckedContinuation { continuation in
                self.rebuildGroup.notify(queue: .global(qos: .userInitiated)) {
                    continuation.resume()
                }
            }
        }

        let acquired = self.stateLock.withLock { () -> (stream: SCStream, owner: UInt64)? in
            guard !self.stopping, self.outputRouteRevision == revision, !self.rebuilding else { return nil }
            let owner = self.beginRebuildLocked()
            self.rebuildGroup.enter()
            return (self.stream, owner)
        }
        guard let acquired else { return .superseded }
        let oldStream = acquired.stream
        let owner = acquired.owner
        defer {
            self.stateLock.withLock { _ = self.endRebuildLocked(owner) }
            self.rebuildGroup.leave()
        }

        let stopResult = await Self.stopStream(oldStream)
        guard self.isCurrentRouteRevision(revision) else { return .superseded }
        if case let .failure(detail) = stopResult {
            throw MeetingCaptureRuntimeError.stopFailed(detail)
        }
        self.stateLock.withLock {
            if self.stream === oldStream { self.currentStreamStopped = true }
        }
        guard self.isCurrentRouteRevision(revision) else { return .superseded }
        // Every callback accepted from the retiring producer has now enqueued its writer command.
        self.performOnCallbackQueueSynchronously {}
        async let appBoundary = self.applicationWriter.beginSplice()
        async let microphoneBoundary = self.microphoneWriter.beginSplice()
        _ = await appBoundary
        let boundary = await microphoneBoundary
        guard self.isCurrentRouteRevision(revision) else { return .superseded }

        do {
            try await self.microphoneWriter.updateTrackMetadataFailClosed { track in
                var eras = track.captureEras ?? []
                let start = boundary?.seconds ?? eras.last?.startSeconds ?? 0
                let replacement = MeetingCaptureEra(
                    method: .screenCaptureKit,
                    deviceUID: microphone.coreAudioUID,
                    deviceName: microphone.displayName,
                    roleAtElection: .unknown,
                    echoProtection: .unprotected,
                    startSeconds: start
                )
                if let last = eras.last, start > last.startSeconds {
                    eras.append(replacement)
                } else if eras.isEmpty {
                    eras = [replacement]
                } else {
                    // No samples were committed in the old era; replace its identity at the same edge.
                    eras[eras.count - 1] = replacement
                }
                track.captureEras = eras
                track.captureMethod = .screenCaptureKit
            }
        } catch {
            guard self.isCurrentRouteRevision(revision) else { return .superseded }
            throw error
        }
        guard self.isCurrentRouteRevision(revision) else { return .superseded }

        let resolved: MeetingMicrophoneIdentity
        let built: BuiltStream
        do {
            resolved = try MeetingAVCaptureMicrophoneResolver.resolve(microphone)
            built = try await Self.buildStream(
                application: self.application,
                microphone: resolved,
                includeMicrophone: self.includeMicrophone,
                allowApplicationRelaunch: true
            )
        } catch {
            guard self.isCurrentRouteRevision(revision) else { return .superseded }
            throw error
        }
        guard self.isCurrentRouteRevision(revision) else { return .superseded }
        built.delegateProxy.owner = self
        do {
            try self.attachOutputs(to: built.stream)
        } catch {
            guard self.isCurrentRouteRevision(revision) else { return .superseded }
            throw error
        }
        let candidateRegistered = self.stateLock.withLock { () -> Bool in
            guard !self.stopping,
                  self.outputRouteRevision == revision,
                  self.rebuildOwner == owner,
                  self.stream === oldStream
            else { return false }
            self.pendingStream = built.stream
            self.pendingStreamFailed = false
            return true
        }
        guard candidateRegistered else { return .superseded }
        do {
            try await built.stream.startCapture()
        } catch {
            self.stateLock.withLock {
                if self.pendingStream === built.stream { self.pendingStream = nil }
            }
            guard self.isCurrentRouteRevision(revision) else {
                try? await built.stream.stopCapture()
                return .superseded
            }
            throw error
        }

        var publication = MeetingCaptureStreamPublication.superseded
        self.performOnCallbackQueueSynchronously {
            publication = self.stateLock.withLock { () -> MeetingCaptureStreamPublication in
                let decision = MeetingCaptureOwnershipGate.mayPublishReplacement(
                    authorizedRevision: revision,
                    currentRevision: self.outputRouteRevision,
                    stopping: self.stopping,
                    candidateFailed: self.pendingStreamFailed,
                    ownsExpectedOldStream: self.stream === oldStream && self.rebuildOwner == owner,
                    ownsPendingCandidate: self.pendingStream === built.stream
                )
                guard decision == .commit else {
                    if self.pendingStream === built.stream { self.pendingStream = nil }
                    return decision
                }
                self.stream = built.stream
                self.currentStreamStopped = false
                self.streamGeneration &+= 1
                self.activeMicrophone = resolved
                self.scope = built.scope
                self.delegateProxy = built.delegateProxy
                self.pendingStream = nil
                // Release transition ownership in the same critical section that publishes the
                // candidate. A didStop callback arriving one instruction later can now claim a new
                // rebuild instead of being discarded behind a stale `rebuilding` flag.
                _ = self.endRebuildLocked(owner)
                return .commit
            }
        }
        guard publication == .commit else {
            try? await built.stream.stopCapture()
            if publication == .failed {
                throw MeetingCaptureError.captureStartFailed("The replacement capture stream stopped before commit.")
            }
            return .superseded
        }
        return .commit
    }

    private static func stopStream(_ stream: SCStream) async -> MeetingOneShotResult {
        await withCheckedContinuation { continuation in
            let completion = MeetingOneShotCompletion(continuation)
            stream.stopCapture { error in
                if let error {
                    completion.resume(.failure(error.localizedDescription))
                } else {
                    completion.resume(.success)
                }
            }
            DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 3) {
                completion.resume(.failure("Timed out while retiring the previous capture stream."))
            }
        }
    }

    private func reportRouteReplacementFailure(_ error: Error) {
        let shouldReport = self.stateLock.withLock { () -> Bool in
            guard !self.stopping else { return false }
            self.stopping = true
            self.aecActivation.invalidate()
            return true
        }
        guard shouldReport else { return }
        _ = self.microphoneTranscriptGate.invalidate()
        self.eventHandler(.interrupted(
            kind: .captureStoppedUnexpectedly,
            trackID: nil,
            detail: "Audio-device handoff failed closed: \(error.localizedDescription)"
        ))
    }

    func handleStreamStop(_ stoppedStream: SCStream, error: Error) {
        let rebuildOwner = self.stateLock.withLock { () -> UInt64? in
            if stoppedStream === self.pendingStream {
                self.pendingStreamFailed = true
                return nil
            }
            guard !self.stopping, !self.rebuilding, stoppedStream === self.stream else { return nil }
            let owner = self.beginRebuildLocked()
            self.currentStreamStopped = true
            self.rebuildGroup.enter()
            return owner
        }
        guard let rebuildOwner else { return }
        self.invalidateAECForStreamRebuild()
        self.eventHandler(.interrupted(kind: .sourceLost, trackID: nil, detail: error.localizedDescription))
        self.runRebuildLoop(triggeringError: error, stoppedStream: stoppedStream, owner: rebuildOwner)
    }

    private func invalidateAECForStreamRebuild() {
        let shouldInvalidate = self.stateLock.withLock {
            self.routeDisposition == .supportedSpeaker || self.aecPipeline != nil
        }
        guard shouldInvalidate else { return }
        let boundary = self.microphoneTranscriptGate.invalidate()
        self.stateLock.withLock {
            self.aecActivation.invalidate()
        }
        self.performOnCallbackQueueSynchronously {
            let detached = self.stateLock.withLock { () -> MeetingAECPipeline? in
                defer { self.aecPipeline = nil }
                return self.aecPipeline
            }
            if let detached {
                detached.invalidate(reason: .streamChanged, boundary: boundary)
                self.retainRetiredCommitterIfPending(detached.committer)
            } else {
                self.microphoneWriter.enqueueMetadata(
                    failClosed: true,
                    mutate: { track in
                        MeetingAECOutputCommitter.applyEra(
                            to: &track,
                            protection: .unprotected,
                            provenance: nil,
                            startSeconds: boundary?.unsafeStartSeconds
                        )
                    }
                ) { [weak self] result in
                    if case .failure = result {
                        self?.handleAECTerminalFailure(.metadataPersistence)
                    }
                }
            }
        }
    }

    /// Attempts up to `rebuildDelays.count` rebuilds of the stream, checking `stopping` before and
    /// after each delay so a concurrent user-initiated `stop()` aborts the loop promptly. On success
    /// the stream reference is swapped under the lock and writers keep running untouched (they rotate
    /// chunks on the PTS gap on their own). On exhaustion this reports the terminal failure exactly as
    /// the non-recoverable path did before this change.
    private func runRebuildLoop(triggeringError: Error, stoppedStream: SCStream, owner: UInt64) {
        let rebuildGroup = self.rebuildGroup
        Task { [weak self] in
            defer {
                if let self {
                    self.stateLock.withLock { _ = self.endRebuildLocked(owner) }
                }
                rebuildGroup.leave()
            }
            guard let self else { return }
            var lastError = triggeringError
            for delay in Self.rebuildDelays {
                let mayContinue = self.stateLock.withLock {
                    !self.stopping && self.rebuildOwner == owner
                }
                guard mayContinue else { return }
                try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
                guard self.stateLock.withLock({ !self.stopping && self.rebuildOwner == owner }) else { return }

                do {
                    let microphone = self.stateLock.withLock { self.activeMicrophone }
                    let built = try await Self.buildStream(
                        application: self.application, microphone: microphone, includeMicrophone: self.includeMicrophone, allowApplicationRelaunch: true
                    )
                    guard self.stateLock.withLock({ !self.stopping && self.rebuildOwner == owner }) else { return }
                    built.delegateProxy.owner = self
                    try self.attachOutputs(to: built.stream)
                    let candidateRegistered = self.stateLock.withLock { () -> Bool in
                        guard !self.stopping,
                              self.rebuildOwner == owner,
                              self.stream === stoppedStream
                        else { return false }
                        self.pendingStream = built.stream
                        self.pendingStreamFailed = false
                        return true
                    }
                    guard candidateRegistered else { return }
                    try await built.stream.startCapture()

                    let publication = self.stateLock.withLock { () -> MeetingCaptureStreamPublication in
                        let decision = MeetingCaptureOwnershipGate.mayPublishReplacement(
                            authorizedRevision: self.outputRouteRevision,
                            currentRevision: self.outputRouteRevision,
                            stopping: self.stopping,
                            candidateFailed: self.pendingStreamFailed,
                            ownsExpectedOldStream: self.stream === stoppedStream && self.rebuildOwner == owner,
                            ownsPendingCandidate: self.pendingStream === built.stream
                        )
                        guard decision == .commit else {
                            if self.pendingStream === built.stream { self.pendingStream = nil }
                            return decision
                        }
                        self.stream = built.stream
                        self.currentStreamStopped = false
                        self.streamGeneration &+= 1
                        self.scope = built.scope
                        self.delegateProxy = built.delegateProxy
                        self.pendingStream = nil
                        _ = self.endRebuildLocked(owner)
                        return .commit
                    }
                    guard publication == .commit else {
                        try? await built.stream.stopCapture()
                        if publication == .superseded { return }
                        continue
                    }
                    let committedOwnership = self.stateLock.withLock { self.currentStreamOwnershipLocked() }
                    let shouldRearmAEC = self.stateLock.withLock {
                        self.routeDisposition == .supportedSpeaker
                            && !self.stopping
                            && !self.rebuilding
                            && !self.currentStreamStopped
                            && self.currentStreamOwnershipLocked() == committedOwnership
                    }
                    if shouldRearmAEC {
                        do {
                            try await self.installAECForSupportedSpeaker(revision: committedOwnership.routeRevision)
                        } catch {
                            self.eventHandler(.interrupted(
                                kind: .microphoneChanged,
                                trackID: self.microphoneWriter.trackID,
                                detail: "Speaker-route AEC could not restart after stream recovery; microphone remains unprotected."
                            ))
                        }
                    }
                    let stillRecovered = self.stateLock.withLock {
                        !self.stopping
                            && !self.rebuilding
                            && !self.currentStreamStopped
                            && self.currentStreamOwnershipLocked() == committedOwnership
                    }
                    if stillRecovered {
                        self.eventHandler(.interrupted(kind: .sourceRecovered, trackID: nil, detail: nil))
                    }
                    return
                } catch {
                    self.stateLock.withLock {
                        if self.pendingStream != nil { self.pendingStream = nil }
                    }
                    lastError = error
                    continue
                }
            }
            self.reportRebuildExhausted(triggeringError: lastError, owner: owner)
        }
    }

    /// Keeps only committers that still have writer completions outstanding. Route churn cannot
    /// therefore grow this array monotonically over a long meeting.
    private func retainRetiredCommitterIfPending(_ committer: MeetingAECOutputCommitter) {
        self.stateLock.withLock {
            self.retiredAECCommitters.removeAll { !$0.hasPendingCommits }
            if committer.hasPendingCommits { self.retiredAECCommitters.append(committer) }
        }
    }

    private func reportRebuildExhausted(triggeringError: Error, owner: UInt64) {
        let shouldReport = self.stateLock.withLock { () -> Bool in
            guard self.rebuildOwner == owner else { return false }
            _ = self.endRebuildLocked(owner)
            guard !self.stopping else { return false }
            self.stopping = true
            return true
        }
        guard shouldReport else { return }
        self.eventHandler(.interrupted(
            kind: .captureStoppedUnexpectedly,
            trackID: nil,
            detail: triggeringError.localizedDescription
        ))
    }
}

private final nonisolated class ScreenCaptureRuntimeDelegateProxy: NSObject, SCStreamDelegate, @unchecked Sendable {
    weak var owner: ScreenCaptureMeetingRuntime?

    func stream(_ stream: SCStream, didStopWithError error: Error) {
        self.owner?.handleStreamStop(stream, error: error)
    }
}

private final nonisolated class InRoomMicrophoneCaptureRuntime: NSObject, MeetingCaptureRuntime,
    AVCaptureAudioDataOutputSampleBufferDelegate, @unchecked Sendable
{
    private let microphonePCMNormalizer = MeetingMicrophonePCMNormalizer()
    var captureScope: MeetingCaptureScope? { nil }

    private let session = AVCaptureSession()
    private let output = AVCaptureAudioDataOutput()
    private let writer: MeetingAudioChunkWriter
    private let controlQueue = DispatchQueue(label: "com.fluidvoice.meeting.inroom.control")
    private let stateLock = NSLock()
    private let eventHandler: @Sendable (MeetingCaptureEvent) -> Void
    private let liveAudioHandler: (@Sendable (MeetingAudioTrackKind, CMSampleBuffer) -> Void)?
    private var stopping = false
    private var emittedUnexpectedStop = false
    private var notificationObservers: [NSObjectProtocol] = []

    init(
        microphone: MeetingMicrophoneIdentity,
        writer: MeetingAudioChunkWriter,
        eventHandler: @escaping @Sendable (MeetingCaptureEvent) -> Void,
        liveAudioHandler: (@Sendable (MeetingAudioTrackKind, CMSampleBuffer) -> Void)?
    ) throws {
        self.writer = writer
        self.eventHandler = eventHandler
        self.liveAudioHandler = liveAudioHandler
        super.init()
        let resolvedMicrophone = try MeetingAVCaptureMicrophoneResolver.resolve(microphone)
        guard let captureDeviceID = resolvedMicrophone.avCaptureDeviceID,
              let device = AVCaptureDevice(uniqueID: captureDeviceID)
        else {
            throw MeetingCaptureError.microphoneUnavailable
        }
        let input = try AVCaptureDeviceInput(device: device)
        self.session.beginConfiguration()
        defer { self.session.commitConfiguration() }
        guard self.session.canAddInput(input), self.session.canAddOutput(self.output) else {
            throw MeetingCaptureError.microphoneUnavailable
        }
        self.session.addInput(input)
        self.session.addOutput(self.output)
        self.output.setSampleBufferDelegate(
            self,
            queue: DispatchQueue(label: "com.fluidvoice.meeting.inroom.samples", qos: .userInteractive)
        )
        self.observeSessionLifecycle()
    }

    deinit {
        #if DEBUG
        AudioTopologyDiagnostics.record(.ownerWillDeinit, owner: .avCapture, queueRole: .callbackCurrent, phase: .avCaptureStop)
        #endif
        for observer in self.notificationObservers {
            NotificationCenter.default.removeObserver(observer)
        }
    }

    func start() async throws {
        let started = await withCheckedContinuation { continuation in
            self.controlQueue.async { [session] in
                session.startRunning()
                continuation.resume(returning: session.isRunning)
            }
        }
        guard started else { throw MeetingCaptureError.captureStartFailed("The microphone did not start.") }
    }

    func stop() async throws {
        #if DEBUG
        AudioTopologyDiagnostics.record(.phaseBegin, owner: .avCapture, queueRole: .dedicatedControl, phase: .avCaptureStop)
        defer { AudioTopologyDiagnostics.record(.phaseEnd, owner: .avCapture, queueRole: .dedicatedControl, phase: .avCaptureStop) }
        #endif
        self.stateLock.withLock { self.stopping = true }
        let result = await withCheckedContinuation { continuation in
            let completion = MeetingOneShotCompletion(continuation)
            self.controlQueue.async { [session] in
                if session.isRunning { session.stopRunning() }
                completion.resume(.success)
            }
            DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 3) {
                completion.resume(.failure("Timed out while stopping microphone capture."))
            }
        }
        if case let .failure(detail) = result {
            throw MeetingCaptureRuntimeError.stopFailed(detail)
        }
    }

    func captureOutput(
        _ output: AVCaptureOutput,
        didOutput sampleBuffer: CMSampleBuffer,
        from connection: AVCaptureConnection
    ) {
        self.stateLock.lock()
        let shouldAccept = !self.stopping
        self.stateLock.unlock()
        guard shouldAccept else { return }
        let sampleBuffer = self.microphonePCMNormalizer.normalize(sampleBuffer)
        self.writer.enqueue(sampleBuffer)
        self.liveAudioHandler?(.microphone, sampleBuffer)
    }

    private func observeSessionLifecycle() {
        let center = NotificationCenter.default
        let names: [Notification.Name] = [
            AVCaptureSession.runtimeErrorNotification,
            AVCaptureSession.wasInterruptedNotification,
            AVCaptureSession.didStopRunningNotification,
        ]
        self.notificationObservers = names.map { name in
            center.addObserver(forName: name, object: self.session, queue: nil) { [weak self] notification in
                self?.handleUnexpectedSessionEvent(notification)
            }
        }
    }

    private func handleUnexpectedSessionEvent(_ notification: Notification) {
        let shouldEmit = self.stateLock.withLock { () -> Bool in
            guard !self.stopping, !self.emittedUnexpectedStop else { return false }
            self.emittedUnexpectedStop = true
            return true
        }
        guard shouldEmit else { return }
        let detail = (notification.userInfo?[AVCaptureSessionErrorKey] as? Error)?.localizedDescription
            ?? "Microphone capture stopped unexpectedly."
        self.eventHandler(.interrupted(
            kind: .captureStoppedUnexpectedly,
            trackID: nil,
            detail: detail
        ))
    }
}

/// Single-resume continuation box; resuming twice is a safe no-op.
private final nonisolated class MeetingOneShotValue<T: Sendable>: @unchecked Sendable {
    private let lock = NSLock()
    private var continuation: CheckedContinuation<T, Never>?

    init(_ continuation: CheckedContinuation<T, Never>) {
        self.continuation = continuation
    }

    func resume(_ value: T) {
        let continuation = self.lock.withLock { () -> CheckedContinuation<T, Never>? in
            defer { self.continuation = nil }
            return self.continuation
        }
        continuation?.resume(returning: value)
    }
}

/// Serializes an uninterruptible framework start with its retirement barrier.
/// `stop()` cannot complete until an already-enqueued `start()` has returned and
/// the stop operation has run behind it on the same queue.
final nonisolated class MeetingSerializedCaptureLifecycle: @unchecked Sendable {
    private let queue: DispatchQueue
    private let admissionLock = NSLock()
    private let startOperation: @Sendable () -> Bool
    private let stopOperation: @Sendable () -> Void
    private var nextOrdinal: UInt64 = 0
    private var retirementOrdinal: UInt64?

    init(
        label: String = "com.fluidvoice.meeting.avcapture.control",
        start: @escaping @Sendable () -> Bool,
        stop: @escaping @Sendable () -> Void
    ) {
        self.queue = DispatchQueue(label: label)
        self.startOperation = start
        self.stopOperation = stop
    }

    func start() async -> Bool {
        await withCheckedContinuation { continuation in
            let enqueued = self.admissionLock.withLock { () -> Bool in
                guard self.retirementOrdinal == nil else { return false }
                self.nextOrdinal &+= 1
                let startOrdinal = self.nextOrdinal
                // Enqueue while admission is locked. A competing stop therefore
                // either queues behind this admitted start or seals admission first.
                self.queue.async {
                    let mayRun = self.admissionLock.withLock {
                        self.retirementOrdinal.map { startOrdinal < $0 } ?? true
                    }
                    continuation.resume(returning: mayRun ? self.startOperation() : false)
                }
                return true
            }
            if !enqueued { continuation.resume(returning: false) }
        }
    }

    func stop() async {
        await withCheckedContinuation { continuation in
            self.admissionLock.withLock {
                if self.retirementOrdinal == nil {
                    self.nextOrdinal &+= 1
                    self.retirementOrdinal = self.nextOrdinal
                }
                // The permanent seal and barrier enqueue are one atomic admission
                // operation, so no start can slip behind stopRunning.
                self.queue.async {
                    self.stopOperation()
                    continuation.resume()
                }
            }
        }
    }

    func perform(_ work: @escaping @Sendable () -> Void) async {
        await withCheckedContinuation { continuation in
            self.queue.async {
                work()
                continuation.resume()
            }
        }
    }
}

/// Reusable AVCaptureSession mic component: `wasInterrupted` restarts only if still not running; runtime errors get ONE serialized restart.
final nonisolated class MeetingAVCaptureMicrophoneComponent: NSObject,
    AVCaptureAudioDataOutputSampleBufferDelegate, @unchecked Sendable
{
    private let microphonePCMNormalizer = MeetingMicrophonePCMNormalizer()
    private static let interruptionEndedWaitSeconds: Double = 3

    let deviceUID: String?
    let deviceName: String

    private let session: AVCaptureSession
    private let output: AVCaptureAudioDataOutput
    private let lifecycle: MeetingSerializedCaptureLifecycle
    private let stateLock = NSLock()
    private let onSample: @Sendable (CMSampleBuffer) -> Void
    private let onTerminalStop: @Sendable (String) -> Void
    private var stopping = false
    private var fullyRetired = false
    private var emittedTerminalStop = false
    private var runtimeErrorRestarted = false
    private var didStopRunningRestarted = false
    private var deliveredSampleCount: UInt64 = 0
    private var interruptionEndWaiters: [MeetingOneShotValue<Void>] = []

    init(
        microphone: MeetingMicrophoneIdentity,
        onSample: @escaping @Sendable (CMSampleBuffer) -> Void,
        onTerminalStop: @escaping @Sendable (String) -> Void
    ) throws {
        let session = AVCaptureSession()
        let output = AVCaptureAudioDataOutput()
        self.session = session
        self.output = output
        self.lifecycle = MeetingSerializedCaptureLifecycle(
            start: {
                session.startRunning()
                return session.isRunning
            },
            stop: {
                if session.isRunning { session.stopRunning() }
                // `stopRunning()` only stops delivery; the session still owns its
                // input device until its graph is dismantled. VPIO must never be
                // enabled while those AVFoundation objects retain the device.
                output.setSampleBufferDelegate(nil, queue: nil)
                session.beginConfiguration()
                for sessionOutput in session.outputs {
                    session.removeOutput(sessionOutput)
                }
                for sessionInput in session.inputs {
                    session.removeInput(sessionInput)
                }
                session.commitConfiguration()
            }
        )
        self.deviceUID = microphone.coreAudioUID
        self.deviceName = microphone.displayName
        self.onSample = onSample
        self.onTerminalStop = onTerminalStop
        super.init()
        let resolvedMicrophone = try MeetingAVCaptureMicrophoneResolver.resolve(microphone)
        guard let captureDeviceID = resolvedMicrophone.avCaptureDeviceID,
              let device = AVCaptureDevice(uniqueID: captureDeviceID)
        else {
            throw MeetingCaptureError.microphoneUnavailable
        }
        let input = try AVCaptureDeviceInput(device: device)
        self.session.beginConfiguration()
        defer { self.session.commitConfiguration() }
        guard self.session.canAddInput(input), self.session.canAddOutput(self.output) else {
            throw MeetingCaptureError.microphoneUnavailable
        }
        self.session.addInput(input)
        self.session.addOutput(self.output)
        self.output.setSampleBufferDelegate(
            self,
            queue: DispatchQueue(label: "com.fluidvoice.meeting.avcapture.samples", qos: .userInteractive)
        )
        self.observeSessionLifecycle()
    }

    deinit {
        #if DEBUG
        AudioTopologyDiagnostics.record(.ownerWillDeinit, owner: .avCapture, queueRole: .callbackCurrent, phase: .avCaptureStop)
        #endif
        for observer in self.observers {
            NotificationCenter.default.removeObserver(observer)
        }
    }

    private var observers: [NSObjectProtocol] = []

    /// Runs `startRunning` on the serial control queue. This intentionally has no
    /// detached timeout: a timed-out AVFoundation call could otherwise finish after
    /// meeting ownership was released and collide with dictation.
    func start() async throws {
        for (attempt, delay) in ([0] + Self.startRetryDelays).enumerated() {
            if attempt > 0 { try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) }
            if self.stateLock.withLock({ self.stopping }) { throw CancellationError() }
            if await self.startRunningOnControlQueue() { return }
        }
        throw MeetingCaptureError.captureStartFailed("The microphone did not start.")
    }

    private static let startRetryDelays: [Double] = [0.5, 1.0, 2.0]

    private func startRunningOnControlQueue() async -> Bool {
        await self.lifecycle.start()
    }

    func stop() async throws {
        #if DEBUG
        AudioTopologyDiagnostics.record(.phaseBegin, owner: .avCapture, queueRole: .dedicatedControl, phase: .avCaptureStop)
        defer { AudioTopologyDiagnostics.record(.phaseEnd, owner: .avCapture, queueRole: .dedicatedControl, phase: .avCaptureStop) }
        #endif
        let waiters = self.stateLock.withLock { () -> [MeetingOneShotValue<Void>] in
            self.stopping = true
            defer { self.interruptionEndWaiters = [] }
            return self.interruptionEndWaiters
        }
        waiters.forEach { $0.resume(()) }

        await self.lifecycle.stop()
        let observers = self.stateLock.withLock { () -> [NSObjectProtocol] in
            defer { self.observers.removeAll() }
            return self.observers
        }
        for observer in observers {
            NotificationCenter.default.removeObserver(observer)
        }
        await self.lifecycle.perform { [self] in
            let proven = !self.session.isRunning
                && self.session.inputs.isEmpty
                && self.session.outputs.isEmpty
            self.stateLock.withLock { self.fullyRetired = proven }
        }
    }

    func isFullyRetired() -> Bool {
        self.stateLock.withLock { self.fullyRetired }
    }

    func captureOutput(
        _ output: AVCaptureOutput,
        didOutput sampleBuffer: CMSampleBuffer,
        from connection: AVCaptureConnection
    ) {
        self.stateLock.lock()
        let shouldAccept = !self.stopping
        if shouldAccept { self.deliveredSampleCount &+= 1 }
        self.stateLock.unlock()
        guard shouldAccept else { return }
        self.onSample(self.microphonePCMNormalizer.normalize(sampleBuffer))
    }

    func sampleCount() -> UInt64 {
        self.stateLock.withLock { self.deliveredSampleCount }
    }

    private func observeSessionLifecycle() {
        let center = NotificationCenter.default
        self.observers = [
            center.addObserver(
                forName: AVCaptureSession.wasInterruptedNotification, object: self.session, queue: nil
            ) { [weak self] _ in self?.handleInterruptionBegan() },
            center.addObserver(
                forName: AVCaptureSession.interruptionEndedNotification, object: self.session, queue: nil
            ) { [weak self] _ in self?.handleInterruptionEnded() },
            center.addObserver(
                forName: AVCaptureSession.runtimeErrorNotification, object: self.session, queue: nil
            ) { [weak self] note in self?.handleRuntimeError(note) },
            center.addObserver(
                forName: AVCaptureSession.didStopRunningNotification, object: self.session, queue: nil
            ) { [weak self] _ in self?.handleDidStopRunning() },
        ]
    }

    private func handleInterruptionBegan() {
        Task { [weak self] in
            guard let self else { return }
            await self.waitForInterruptionEnd(timeoutSeconds: Self.interruptionEndedWaitSeconds)
            guard !(self.stateLock.withLock { self.stopping }) else { return }
            if !self.session.isRunning {
                await self.attemptSupervisedRestart(
                    reason: "Route settled after an interruption but the microphone did not resume."
                )
            }
        }
    }

    private func waitForInterruptionEnd(timeoutSeconds: Double) async {
        await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
            let box = MeetingOneShotValue<Void>(continuation)
            self.stateLock.lock()
            self.interruptionEndWaiters.append(box)
            self.stateLock.unlock()
            DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + timeoutSeconds) {
                box.resume(())
            }
        }
    }

    private func handleInterruptionEnded() {
        self.stateLock.lock()
        let waiters = self.interruptionEndWaiters
        self.interruptionEndWaiters = []
        self.stateLock.unlock()
        waiters.forEach { $0.resume(()) }
    }

    private func handleRuntimeError(_ notification: Notification) {
        let shouldRestart = self.stateLock.withLock { () -> Bool in
            guard !self.stopping, !self.runtimeErrorRestarted else { return false }
            self.runtimeErrorRestarted = true
            return true
        }
        let detail = (notification.userInfo?[AVCaptureSessionErrorKey] as? Error)?.localizedDescription
            ?? "Microphone capture reported a runtime error."
        guard shouldRestart else {
            self.emitTerminalStopIfNeeded(detail: detail)
            return
        }
        Task { [weak self] in await self?.attemptSupervisedRestart(reason: detail) }
    }

    private func handleDidStopRunning() {
        let shouldRestart = self.stateLock.withLock { () -> Bool in
            guard !self.stopping, !self.didStopRunningRestarted else { return false }
            self.didStopRunningRestarted = true
            return true
        }
        guard shouldRestart else {
            self.emitTerminalStopIfNeeded(detail: "Microphone capture stopped unexpectedly.")
            return
        }
        Task { [weak self] in
            await self?.attemptSupervisedRestart(reason: "Microphone capture stopped unexpectedly.")
        }
    }

    private func attemptSupervisedRestart(reason: String) async {
        guard !(self.stateLock.withLock { self.stopping }) else { return }
        let restarted = await self.startRunningOnControlQueue()
        guard !restarted, !(self.stateLock.withLock { self.stopping }) else { return }
        self.emitTerminalStopIfNeeded(detail: reason)
    }

    private func emitTerminalStopIfNeeded(detail: String) {
        let shouldEmit = self.stateLock.withLock { () -> Bool in
            guard !self.stopping, !self.emittedTerminalStop else { return false }
            self.emittedTerminalStop = true
            return true
        }
        guard shouldEmit else { return }
        self.onTerminalStop(detail)
    }
}

/// Identity fence for terminal callbacks. A retired candidate from an earlier
/// retry can share the transition generation but must never fail its successor.
final nonisolated class MeetingAVCaptureAttemptToken: @unchecked Sendable {}

nonisolated enum MeetingAVCaptureFailureAdmission {
    static func accepts(
        currentGeneration: UInt64,
        eventGeneration: UInt64,
        activeToken: MeetingAVCaptureAttemptToken?,
        eventToken: MeetingAVCaptureAttemptToken,
        stopRequested: Bool
    ) -> Bool {
        !stopRequested
            && currentGeneration == eventGeneration
            && activeToken === eventToken
    }
}

/// Bounds wall-clock time even when `operation` ignores cancellation; a late operation finishes detached, result discarded.
nonisolated enum MeetingSupervisedTimeout {
    static func run<T: Sendable>(seconds: Double, operation: @escaping @Sendable () async -> T) async -> T? {
        await withCheckedContinuation { (continuation: CheckedContinuation<T?, Never>) in
            let completion = MeetingOneShotValue<T?>(continuation)
            Task {
                let result = await operation()
                completion.resume(result)
            }
            DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + max(0, seconds)) {
                completion.resume(nil)
            }
        }
    }
}

/// Per-era acceptance fence, wrapping each sample callback in `beginSample()`/`defer { endSample() }`.
final nonisolated class MeetingEraAcceptanceFence: @unchecked Sendable {
    private let lock = NSLock()
    private var accepting = true
    private var inFlight = 0
    private var drainWaiters: [MeetingOneShotValue<Void>] = []

    func beginSample() -> Bool {
        self.lock.lock()
        defer { self.lock.unlock() }
        guard self.accepting else { return false }
        self.inFlight += 1
        return true
    }

    func endSample() {
        self.lock.lock()
        self.inFlight -= 1
        let shouldNotify = !self.accepting && self.inFlight == 0
        let waiters = shouldNotify ? self.drainWaiters : []
        if shouldNotify { self.drainWaiters = [] }
        self.lock.unlock()
        waiters.forEach { $0.resume(()) }
    }

    func quiesce() async {
        let alreadyDrained: Bool = self.lock.withLock {
            self.accepting = false
            return self.inFlight == 0
        }
        guard !alreadyDrained else { return }
        await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
            let box = MeetingOneShotValue<Void>(continuation)
            let pending: Bool = self.lock.withLock {
                guard self.inFlight > 0 else { return false }
                self.drainWaiters.append(box)
                return true
            }
            if !pending { box.resume(()) }
        }
    }
}

private nonisolated enum MeetingOneShotResult: Sendable {
    case success
    case failure(String)
}

private final nonisolated class MeetingOneShotCompletion: @unchecked Sendable {
    private let lock = NSLock()
    private var continuation: CheckedContinuation<MeetingOneShotResult, Never>?

    init(_ continuation: CheckedContinuation<MeetingOneShotResult, Never>) {
        self.continuation = continuation
    }

    func resume(_ result: MeetingOneShotResult) {
        let continuation = self.lock.withLock { () -> CheckedContinuation<MeetingOneShotResult, Never>? in
            defer { self.continuation = nil }
            return self.continuation
        }
        continuation?.resume(returning: result)
    }
}

private nonisolated enum MeetingCaptureRuntimeError: LocalizedError {
    case stopFailed(String)

    var errorDescription: String? {
        switch self {
        case let .stopFailed(detail):
            return detail
        }
    }
}

nonisolated enum MeetingCaptureError: LocalizedError {
    case captureAlreadyActive
    case noActiveCapture
    case wrongActiveSession
    case applicationNotSelected
    case applicationUnavailable(String)
    case noCaptureDisplay
    case microphoneUnavailable
    case microphonePermissionDenied
    case screenCapturePermissionDenied(String)
    case insufficientDiskSpace
    case captureStartFailed(String)
    case captureStopFailed(String, partialResult: MeetingCaptureStopResult)
    case unsupportedAudioFormat
    case writerFailed(String)

    var errorDescription: String? {
        switch self {
        case .captureAlreadyActive:
            return "Another meeting recording is already active."
        case .noActiveCapture:
            return "There is no active meeting recording."
        case .wrongActiveSession:
            return "A different meeting recording is active."
        case .applicationNotSelected:
            return "Choose the application that contains the online meeting."
        case let .applicationUnavailable(name):
            return "\(name) is no longer available to record."
        case .noCaptureDisplay:
            return "No display is available for meeting-audio capture."
        case .microphoneUnavailable:
            return "The selected microphone is unavailable."
        case .microphonePermissionDenied:
            return "Microphone permission is required to record this meeting."
        case let .screenCapturePermissionDenied(detail):
            return "Screen & System Audio permission is required. \(detail)"
        case .insufficientDiskSpace:
            return "Not enough free space is available for PCM meeting capture. Free space for at least a one-hour recording and processing workspace, then try again."
        case let .captureStartFailed(detail):
            return "Meeting recording could not start. \(detail)"
        case let .captureStopFailed(detail, _):
            return "Meeting recording could not stop cleanly. \(detail)"
        case .unsupportedAudioFormat:
            return "The selected audio source uses an unsupported format."
        case let .writerFailed(detail):
            return "Meeting audio could not be saved. \(detail)"
        }
    }
}

nonisolated enum MeetingCaptureSourceCatalog {
    static let preferredFallbackBundleIdentifiers = [
        "us.zoom.xos",
        "com.google.Chrome",
        "com.microsoft.teams2",
    ]

    /// Manual setup keeps Zoom/Chrome/Teams fallback. Auto-detect must capture the
    /// detected app or fail — never a different meeting.
    static func resolveApplication(
        from applications: [MeetingApplicationIdentity],
        preferredBundleIdentifier: String?,
        requirePreferredApplication: Bool
    ) throws -> MeetingApplicationIdentity {
        if requirePreferredApplication {
            guard let preferredBundleIdentifier else {
                throw MeetingCaptureError.applicationNotSelected
            }
            guard let match = applications.first(where: { $0.bundleIdentifier == preferredBundleIdentifier }) else {
                throw MeetingCaptureError.applicationUnavailable(preferredBundleIdentifier)
            }
            return match
        }

        let preferredBundleIdentifiers = [preferredBundleIdentifier].compactMap { $0 }
            + Self.preferredFallbackBundleIdentifiers
        if let application = preferredBundleIdentifiers.lazy.compactMap({ bundleIdentifier in
            applications.first(where: { $0.bundleIdentifier == bundleIdentifier })
        }).first ?? applications.first {
            return application
        }
        throw MeetingCaptureError.applicationNotSelected
    }

    static func availableApplications() async throws -> [MeetingApplicationIdentity] {
        let content = try await SCShareableContent.current
        let ownBundleIdentifier = Bundle.main.bundleIdentifier
        return content.applications
            .filter { $0.bundleIdentifier != ownBundleIdentifier }
            .map { application in
                let applicationWindow = content.windows.first {
                    $0.owningApplication?.processID == application.processID
                }
                let displayID = applicationWindow.flatMap { window in
                    content.displays
                        .filter { $0.frame.intersects(window.frame) }
                        .max { lhs, rhs in
                            lhs.frame.intersection(window.frame).area < rhs.frame.intersection(window.frame).area
                        }?.displayID
                }
                return MeetingApplicationIdentity(
                    bundleIdentifier: application.bundleIdentifier,
                    processID: application.processID,
                    displayName: application.applicationName,
                    displayID: displayID
                )
            }
            .sorted { $0.displayName.localizedCaseInsensitiveCompare($1.displayName) == .orderedAscending }
    }

    static func microphoneSnapshot() async -> MeetingMicrophoneCatalogSnapshot {
        await AudioTopologyListenerExecution.perform {
            let identities = AudioDevice.listInputDevicesRefreshingLiveness().compactMap { device -> MeetingMicrophoneIdentity? in
                guard device.isAlive, device.uid.isEmpty == false else { return nil }
                return MeetingMicrophoneIdentity(
                    captureDeviceID: device.uid,
                    coreAudioUID: device.uid,
                    displayName: device.name
                )
            }
            return MeetingMicrophoneCatalogSnapshot(
                identities: identities,
                defaultCoreAudioUID: AudioDevice.getDefaultInputDevice()?.uid
            )
        }
    }

    static func availableMicrophones() async -> [MeetingMicrophoneIdentity] {
        await self.microphoneSnapshot().identities
    }

    static func defaultMicrophone(preferredCoreAudioUID: String? = nil) async throws -> MeetingMicrophoneIdentity {
        let snapshot = await self.microphoneSnapshot()
        let microphones = snapshot.identities
        if let preferredCoreAudioUID,
           let preferred = microphones.first(where: { $0.coreAudioUID == preferredCoreAudioUID })
        {
            return preferred
        }
        guard let defaultUID = snapshot.defaultCoreAudioUID,
              let microphone = microphones.first(where: { $0.coreAudioUID == defaultUID })
        else { throw MeetingCaptureError.microphoneUnavailable }
        return microphone
    }
}

nonisolated struct MeetingMicrophoneCatalogSnapshot: Sendable, Equatable {
    var identities: [MeetingMicrophoneIdentity]
    var defaultCoreAudioUID: String?
}

nonisolated struct MeetingAVCaptureDeviceDescriptor: Equatable, Sendable {
    var uniqueID: String
    var displayName: String
}

/// Pure, fail-closed bridge from FluidVoice's stable Core Audio selection identity
/// to the AVCaptureDevice unique ID required by ScreenCaptureKit/AVCaptureSession.
nonisolated enum MeetingAVCaptureDeviceSelection {
    static func select(
        microphone: MeetingMicrophoneIdentity,
        candidates: [MeetingAVCaptureDeviceDescriptor]
    ) -> String? {
        func exact(_ identifier: String?) -> String? {
            guard let identifier, !identifier.isEmpty else { return nil }
            return candidates.first(where: { $0.uniqueID == identifier })?.uniqueID
        }

        if let explicit = exact(microphone.avCaptureDeviceID) { return explicit }
        if microphone.identitySchemaVersion == nil,
           let legacy = exact(microphone.captureDeviceID)
        {
            return legacy
        }
        if let coreAudio = exact(microphone.coreAudioUID) { return coreAudio }

        let normalizedName = Self.normalize(microphone.displayName)
        guard !normalizedName.isEmpty else { return nil }
        let nameMatches = candidates.filter { Self.normalize($0.displayName) == normalizedName }
        guard nameMatches.count == 1 else { return nil }
        return nameMatches[0].uniqueID
    }

    private static func normalize(_ value: String) -> String {
        value.trimmingCharacters(in: .whitespacesAndNewlines)
            .folding(options: [.caseInsensitive, .diacriticInsensitive], locale: .current)
    }
}

/// AVFoundation discovery is intentionally isolated here. Callers are capture adapters
/// that run only after the ASR meeting lease has drained dictation audio ownership.
nonisolated enum MeetingAVCaptureMicrophoneResolver {
    static func resolve(_ microphone: MeetingMicrophoneIdentity) throws -> MeetingMicrophoneIdentity {
        #if DEBUG
        AudioTopologyDiagnostics.record(.avfDiscoveryBegin, owner: .meetingCatalog, queueRole: .actorControl, phase: .catalog)
        #endif
        let devices = AVCaptureDevice.DiscoverySession(
            deviceTypes: [.microphone, .external],
            mediaType: .audio,
            position: .unspecified
        ).devices
        #if DEBUG
        AudioTopologyDiagnostics.record(.avfDiscoveryEnd, owner: .meetingCatalog, queueRole: .actorControl, phase: .catalog, status: Int32(clamping: devices.count))
        #endif
        let descriptors = devices.map {
            MeetingAVCaptureDeviceDescriptor(uniqueID: $0.uniqueID, displayName: $0.localizedName)
        }
        guard let uniqueID = MeetingAVCaptureDeviceSelection.select(
            microphone: microphone,
            candidates: descriptors
        ) else {
            throw MeetingCaptureError.microphoneUnavailable
        }
        var resolved = microphone
        resolved.avCaptureDeviceID = uniqueID
        return resolved
    }
}

private extension CGRect {
    var area: CGFloat {
        guard !self.isNull, !self.isInfinite else { return 0 }
        return max(0, self.width) * max(0, self.height)
    }
}

nonisolated enum MeetingCapturePathDecision: Sendable, Equatable {
    case voiceProcessing
    case screenCaptureKit(reason: String)
}

/// Stable speaker routes can attempt direct AEC3 after format and clock validation. The escape
/// hatch disables filtering; it does not disable recording or unfiltered transcription.
nonisolated enum MeetingDirectAEC3Gate {
    // TODO: Remove this escape hatch once direct AEC3 has completed real-meeting testing and is stable.
    static let disableEnvironmentKey = "FLUIDVOICE_DISABLE_AEC3"

    static func enabled(environment: [String: String] = ProcessInfo.processInfo.environment) -> Bool {
        environment[self.disableEnvironmentKey] != "1"
    }
}

nonisolated enum MeetingCaptureTransitionPolicy {
    // Keep the descriptive diagnostic contract name consistent with its persisted field.
    // swiftlint:disable:next identifier_name
    static let allowsWithinSessionVoiceProcessingUpgrade = true
    static let maximumRouteRecoveryAttempts = 3
    static let recoveryDwellSeconds: Double = 2

    static func shouldAttemptVoiceProcessingRecovery(
        routeDrivenFallback: Bool,
        attempts: Int,
        microphone: MeetingMicrophoneIdentity,
        outputRoute: MeetingOutputRouteSnapshot
    ) -> Bool {
        MeetingVoiceProcessingUpgradeDwell.shouldArm(
            phaseIsAVCapture: true,
            dwellAlreadyArmed: false,
            quarantined: false,
            stopRequested: false,
            routeDrivenFallback: routeDrivenFallback,
            attempts: attempts,
            microphone: microphone,
            outputRoute: outputRoute
        )
    }
}

nonisolated enum MeetingVoiceProcessingUpgradeDwell {
    static var seconds: Double { MeetingCaptureTransitionPolicy.recoveryDwellSeconds }

    // Keep the existing capture/processing contract explicit during integration.
    // swiftlint:disable:next function_parameter_count
    static func shouldArm(
        phaseIsAVCapture: Bool,
        dwellAlreadyArmed: Bool,
        quarantined: Bool,
        stopRequested: Bool,
        routeDrivenFallback: Bool,
        attempts: Int,
        microphone: MeetingMicrophoneIdentity,
        outputRoute: MeetingOutputRouteSnapshot
    ) -> Bool {
        guard MeetingCaptureTransitionPolicy.allowsWithinSessionVoiceProcessingUpgrade,
              phaseIsAVCapture,
              !dwellAlreadyArmed,
              !quarantined,
              !stopRequested,
              routeDrivenFallback,
              attempts < MeetingCaptureTransitionPolicy.maximumRouteRecoveryAttempts
        else { return false }
        return MeetingCapturePathDecider.decide(
            mode: .onlineCall,
            microphone: microphone,
            outputRoute: outputRoute
        ) == .voiceProcessing
    }
}

nonisolated enum MeetingVoiceProcessingUpgradeOwnership {
    enum Step: Equatable {
        case cancelWatchdog
        case fenceAndQuiesce
        case stopRunning
        case removeObservers
        case removeDelegate
        case removeSessionIO
        case clearRuntimeRef
        case clearLocalRef
        case electAndDecide
        case parkCandidate
        case constructVoiceProcessing
        case startVoiceProcessing
        case awaitFirstBuffer
        case commit
        case startWatchdog
    }

    static let stopOldFirstSequence: [Step] = [
        .cancelWatchdog,
        .fenceAndQuiesce,
        .stopRunning,
        .removeObservers,
        .removeDelegate,
        .removeSessionIO,
        .clearRuntimeRef,
        .clearLocalRef,
        .electAndDecide,
        .constructVoiceProcessing,
        .parkCandidate,
        .startVoiceProcessing,
        .awaitFirstBuffer,
        .commit,
        .startWatchdog,
    ]

    static func mayConstructVoiceProcessing(
        avCaptureRuntimeRef: Bool,
        avCaptureLocalRef: Bool,
        avCaptureRunning: Bool,
        teardownProven: Bool
    ) -> Bool {
        !avCaptureRuntimeRef && !avCaptureLocalRef && !avCaptureRunning && teardownProven
    }

    static func mayPhaseAVCapture(hasComponent: Bool, componentStopped: Bool) -> Bool {
        hasComponent && !componentStopped
    }

    enum TeardownFailureAction: Equatable {
        case quarantineAndFail
    }

    static let actionIfTeardownUnproven = TeardownFailureAction.quarantineAndFail

    enum RollbackStep: Equatable {
        case stopAndReleaseVoiceProcessing
        case elect
        case recreateAVCapture
        case awaitFirstBuffer
        case commitAVCapture
    }

    static let rollbackSequence: [RollbackStep] = [
        .stopAndReleaseVoiceProcessing,
        .elect,
        .recreateAVCapture,
        .awaitFirstBuffer,
        .commitAVCapture,
    ]

    static let watchdogRunsDuringIntentionalGap = false
}

nonisolated enum MeetingVoiceProcessingUpgradeCommit {
    static let publishedCaptureMethod: MeetingAudioTrackCaptureMethod = .voiceProcessing
    static let discardsOverlappingSamples = false

    enum Stage: Equatable {
        case beginSplice
        case appendVoiceProcessingEra
        case setCaptureMethod
        case publishMethodChanged
        case awaitAck
        case flushRing
        case phaseVPIO
        case startWatchdog
    }

    static let orderedStages: [Stage] = [
        .beginSplice,
        .appendVoiceProcessingEra,
        .setCaptureMethod,
        .publishMethodChanged,
        .awaitAck,
        .flushRing,
        .phaseVPIO,
        .startWatchdog,
    ]
}

nonisolated enum MeetingCaptureRouteReplay {
    enum Backend: Equatable {
        case vpio
        case avCapture
    }

    static func shouldReplay(dirty: Bool, stopRequested: Bool, backend: Backend?) -> Bool {
        dirty && !stopRequested && backend != nil
    }

    enum Action: Equatable {
        case downgradeFromVPIO
        case rebindAVCapture
        case none
    }

    static func action(backend: Backend, outputRouteDeclineReason: String?) -> Action {
        switch backend {
        case .vpio:
            return outputRouteDeclineReason == nil ? .none : .downgradeFromVPIO
        case .avCapture:
            return .rebindAVCapture
        }
    }
}

nonisolated enum MeetingVoiceProcessingUpgradeAdmission {
    static func isCurrent(
        currentGeneration: UInt64,
        eventGeneration: UInt64,
        stopRequested: Bool,
        phaseIsTransitioning: Bool
    ) -> Bool {
        !stopRequested && currentGeneration == eventGeneration && phaseIsTransitioning
    }

    static func canCommit(
        currentGeneration: UInt64,
        eventGeneration: UInt64,
        stopRequested: Bool,
        phaseIsTransitioning: Bool
    ) -> Bool {
        self.isCurrent(
            currentGeneration: currentGeneration,
            eventGeneration: eventGeneration,
            stopRequested: stopRequested,
            phaseIsTransitioning: phaseIsTransitioning
        )
    }
}

/// Sticky means the safe AVCapture backend remains selected; it does not mean a
/// disconnected physical microphone remains selected.
nonisolated enum MeetingAVCaptureRebindDecision {
    static func shouldRebind(activeCoreAudioUID: String?, electedCoreAudioUID: String?, forced: Bool) -> Bool {
        if forced { return true }
        guard let electedCoreAudioUID, !electedCoreAudioUID.isEmpty else { return false }
        return activeCoreAudioUID != electedCoreAudioUID
    }
}

/// Output-route facts the decision needs, as a plain value so `decide` is unit-testable headless.
nonisolated struct MeetingOutputRouteSnapshot: Sendable, Equatable {
    var deviceExists: Bool
    var isBluetooth: Bool
    var isBuiltIn: Bool
    var isHeadphonesDataSource: Bool
    var terminalTypes: Set<UInt32> = []
}

nonisolated enum MeetingRawMicrophoneProtection {
    /// Headphones need positive evidence. Other raw routes keep speech with an explicit echo
    /// warning; this classification never pretends the audio was filtered or acoustically closed.
    static func classify(_ route: MeetingOutputRouteSnapshot) -> MeetingMicrophoneEchoProtection {
        guard route.deviceExists else { return .unfiltered }
        if (route.isBuiltIn && route.isHeadphonesDataSource)
            || route.terminalTypes.contains(kAudioStreamTerminalTypeHeadphones)
        {
            return .acousticallyClosed
        }
        return .unfiltered
    }
}

final nonisolated class MeetingMicrophoneTranscriptGate: @unchecked Sendable {
    /// Core Audio notifications are asynchronous relative to the physical route switch. Rewind the
    /// persisted cut slightly so callback latency cannot bless the first speaker-leak buffers.
    static let routeNotificationSafetySeconds: Double = 0.5
    private let lock = NSLock()
    private var protection: MeetingMicrophoneEchoProtection
    private var latestPresentationSeconds: Double?
    /// Bumped by every `invalidate()`. A promotion captured before a route/lifecycle close can
    /// then never reopen admission afterwards, even if it wins the lock race against the close.
    private var invalidationCounter: UInt64 = 0

    init(_ protection: MeetingMicrophoneEchoProtection = .unprotected) {
        self.protection = protection
    }

    func update(_ protection: MeetingMicrophoneEchoProtection) {
        self.lock.withLock { self.protection = protection }
    }

    var invalidationEpoch: UInt64 {
        self.lock.withLock { self.invalidationCounter }
    }

    /// Opens admission only when no invalidation has landed since `epoch` was captured.
    @discardableResult
    func updateIfNotInvalidated(_ protection: MeetingMicrophoneEchoProtection, since epoch: UInt64) -> Bool {
        self.lock.withLock {
            guard self.invalidationCounter == epoch else { return false }
            self.protection = protection
            return true
        }
    }

    func admitsTranscript() -> Bool {
        self.lock.withLock { self.protection.admitsTranscript }
    }

    /// Atomically observes the sample boundary and decides live admission. A route callback taking
    /// the same lock therefore has an exact conservative cut: samples ordered after invalidation
    /// cannot leak into live transcription under the prior route's protection.
    func observeAndAdmit(_ sampleBuffer: CMSampleBuffer, since epoch: UInt64? = nil) -> Bool {
        let time = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
        return self.lock.withLock {
            if time.isValid, time.isNumeric {
                let seconds = CMTimeGetSeconds(time)
                if seconds.isFinite {
                    self.latestPresentationSeconds = max(self.latestPresentationSeconds ?? seconds, seconds)
                }
            }
            return (epoch == nil || epoch == self.invalidationCounter) && self.protection.admitsTranscript
        }
    }

    /// Closes admission first and returns the last observed sample PTS. Using that PTS as the next
    /// era boundary deliberately excludes the final pre-notification buffer as a safety margin.
    struct InvalidationBoundary: Equatable, Sendable {
        let unsafeStartSeconds: Double
        let observedSeconds: Double
    }

    func invalidate() -> InvalidationBoundary? {
        self.lock.withLock {
            self.protection = .unprotected
            self.invalidationCounter &+= 1
            return self.latestPresentationSeconds.map { observed in
                InvalidationBoundary(
                    unsafeStartSeconds: max(0, observed - Self.routeNotificationSafetySeconds),
                    observedSeconds: observed
                )
            }
        }
    }

    func latestObservedSeconds() -> Double? {
        self.lock.withLock { self.latestPresentationSeconds }
    }
}

/// Serializes route-protection manifest updates without ever blocking an audio callback.
final nonisolated class MeetingAsyncTaskChain: @unchecked Sendable {
    private let lock = NSLock()
    private var tail: Task<Void, Never>?
    private var generation: UInt64 = 0

    @discardableResult
    func enqueue(_ operation: @escaping @Sendable () async -> Void) -> Task<Void, Never> {
        self.lock.withLock {
            self.generation &+= 1
            let predecessor = self.tail
            let task = Task {
                await predecessor?.value
                await operation()
            }
            self.tail = task
            return task
        }
    }

    func drain() async {
        while true {
            let snapshot = self.lock.withLock { (self.generation, self.tail) }
            await snapshot.1?.value
            if self.lock.withLock({ self.generation == snapshot.0 }) { return }
        }
    }
}

/// Pure decision table. Capture safety is independent of semantic speaker ownership.
nonisolated enum MeetingCapturePathDecider {
    static let diagnosticForceScreenCaptureKitReason =
        "DEBUG C2 diagnostic forced paired ScreenCaptureKit; not a production fallback."
    static let directAEC3DefaultReason =
        "DEBUG direct AEC3 selected for the built-in-speaker pre-production path."

    static func decide(
        mode: MeetingCaptureMode,
        microphone: MeetingMicrophoneIdentity,
        outputRoute: MeetingOutputRouteSnapshot,
        forcePairedScreenCaptureKit: Bool = false,
        preferDirectAEC3: Bool = false
    ) -> MeetingCapturePathDecision {
        guard mode == .onlineCall else {
            return .screenCaptureKit(reason: "Voice-processing capture only applies to online-call recordings.")
        }
        guard let coreAudioUID = microphone.coreAudioUID, !coreAudioUID.isEmpty else {
            return .screenCaptureKit(reason: "The selected microphone has no CoreAudio device UID.")
        }
        if let reason = Self.outputRouteDeclineReason(outputRoute) {
            return .screenCaptureKit(reason: reason)
        }
        #if DEBUG
        if forcePairedScreenCaptureKit {
            return .screenCaptureKit(reason: Self.diagnosticForceScreenCaptureKitReason)
        }
        #endif
        if preferDirectAEC3 {
            return .screenCaptureKit(reason: Self.directAEC3DefaultReason)
        }
        return .voiceProcessing
    }

    /// Shared with the mid-session output-route listener so the two never diverge.
    static func outputRouteDeclineReason(_ outputRoute: MeetingOutputRouteSnapshot) -> String? {
        guard outputRoute.deviceExists else { return "No default output device is available." }
        guard !outputRoute.isBluetooth else { return "The output device is Bluetooth." }
        guard outputRoute.isBuiltIn else { return "The output device is not the built-in speakers." }
        guard !outputRoute.isHeadphonesDataSource else { return "The output route is headphones." }
        guard !outputRoute.terminalTypes.contains(kAudioStreamTerminalTypeHeadphones) else {
            return "The output stream terminal is headphones."
        }
        return nil
    }
}

nonisolated enum MeetingScreenCaptureAudioSettings {
    static func apply(
        to configuration: SCStreamConfiguration,
        microphone: MeetingMicrophoneIdentity,
        includeMicrophone: Bool
    ) {
        configuration.capturesAudio = true
        configuration.sampleRate = 48_000
        configuration.channelCount = 2
        configuration.excludesCurrentProcessAudio = true
        configuration.captureMicrophone = includeMicrophone
        if includeMicrophone {
            configuration.microphoneCaptureDeviceID = microphone.avCaptureDeviceID
        }
    }
}

/// Buffers mic audio pre-commit; ring-cap exhaustion ABORTS rather than evicting-and-committing.
final nonisolated class MeetingVoiceProcessingCommitGate: @unchecked Sendable {
    enum SampleOutcome { case buffered, passthrough, aborted }

    private enum State { case buffering, flushing, committed, aborted }

    static let defaultRingCapBytes = 1_048_576 // ~5s of mono float32 @ 48kHz

    private let lock = NSLock()
    private var state: State = .buffering
    private var ring: [CMSampleBuffer] = []
    private var ringBytes = 0
    private let ringCapBytes: Int

    init(ringCapBytes: Int = MeetingVoiceProcessingCommitGate.defaultRingCapBytes) {
        self.ringCapBytes = ringCapBytes
    }

    func offer(_ sampleBuffer: CMSampleBuffer) -> SampleOutcome {
        self.lock.lock()
        defer { self.lock.unlock() }
        switch self.state {
        case .committed: return .passthrough
        case .aborted: return .aborted
        case .flushing:
            // Uncapped: aborting mid-flush would strand already-promoted provenance.
            self.ring.append(sampleBuffer)
            return .buffered
        case .buffering:
            // GetTotalSampleSize returns 0 without a per-sample size table; use the block buffer.
            let size = CMSampleBufferGetDataBuffer(sampleBuffer).map(CMBlockBufferGetDataLength) ?? 0
            guard self.ringBytes + size <= self.ringCapBytes else {
                self.state = .aborted
                self.ring.removeAll()
                self.ringBytes = 0
                return .aborted
            }
            self.ring.append(sampleBuffer)
            self.ringBytes += size
            return .buffered
        }
    }

    @discardableResult
    func offerTerminalEventPreCommit() -> Bool {
        self.lock.lock()
        defer { self.lock.unlock() }
        guard self.state == .buffering else { return false }
        self.state = .aborted
        self.ring.removeAll()
        self.ringBytes = 0
        return true
    }

    // Point of no return: after this, terminal events and abort() are no-ops.
    // nil represents unavailable or invalid evidence, distinct from a valid empty collection.
    // swiftlint:disable:next discouraged_optional_collection
    func beginCommitFlush() -> [CMSampleBuffer]? {
        self.lock.lock()
        defer { self.lock.unlock() }
        guard self.state == .buffering else { return nil }
        self.state = .flushing
        return self.takeRing()
    }

    // nil means the ring drained and passthrough is live; else the next batch to flush in order.
    // Serialized handoff: passthrough never starts while older buffers wait, so PTS order holds.
    // nil represents unavailable or invalid evidence, distinct from a valid empty collection.
    // swiftlint:disable:next discouraged_optional_collection
    func continueCommitFlush() -> [CMSampleBuffer]? {
        self.lock.lock()
        defer { self.lock.unlock() }
        guard self.state == .flushing else { return nil }
        if self.ring.isEmpty {
            self.state = .committed
            return nil
        }
        return self.takeRing()
    }

    private func takeRing() -> [CMSampleBuffer] {
        let taken = self.ring
        self.ring.removeAll()
        self.ringBytes = 0
        return taken
    }

    func abort() {
        self.lock.lock()
        defer { self.lock.unlock() }
        guard self.state == .buffering || self.state == .aborted else { return }
        self.state = .aborted
        self.ring.removeAll()
        self.ringBytes = 0
    }

    var isCommitted: Bool { self.lock.withLock { self.state == .committed } }
}

/// Emitted-only progress: dropped/failed buffers deliver no audio, so a dropped run trips this too.
nonisolated enum MeetingVoiceProcessingWatchdog {
    static let stalledThresholdSeconds: Double = 10

    static func isStalled(secondsSinceLastEmittedBuffer: Double) -> Bool {
        secondsSinceLastEmittedBuffer >= self.stalledThresholdSeconds
    }
}

/// Re-evaluates meeting capture on default-input, default-output, or output data-source change.
/// Registration failure at init means VPIO is not viable — fail closed. Re-registers everything on
/// `kAudioHardwarePropertyServiceRestarted`, since CoreAudio discards all prior listeners on reset.
private actor MeetingOutputRouteListener {
    private enum Lifecycle: Equatable {
        case idle
        case starting
        case ready
    }

    private let onChange: @Sendable (MeetingOutputRouteListenerHealth) -> Void
    private var generation: UInt64 = 0
    private var dataSourceEpoch: UInt64 = 0
    private var active = false
    private var lifecycle: Lifecycle = .idle
    private var defaultInputDirty = false
    private var defaultOutputDirty = false
    private var serviceRestartDirty = false
    private var defaultInputToken: AudioObjectPropertyListenerBlock?
    private var defaultOutputToken: AudioObjectPropertyListenerBlock?
    private var serviceRestartedToken: AudioObjectPropertyListenerBlock?
    private var dataSourceToken: AudioObjectPropertyListenerBlock?
    private var dataSourceDeviceID: AudioObjectID?

    private init(onChange: @escaping @Sendable (MeetingOutputRouteListenerHealth) -> Void) {
        self.onChange = onChange
    }

    static func make(
        onChange: @escaping @Sendable (MeetingOutputRouteListenerHealth) -> Void
    ) async -> MeetingOutputRouteListener? {
        let listener = MeetingOutputRouteListener(onChange: onChange)
        guard await listener.start() else { return nil }
        return listener
    }

    private func start() async -> Bool {
        guard !self.active else { return true }
        self.generation &+= 1
        let generation = self.generation
        self.active = true
        self.lifecycle = .starting
        self.defaultInputDirty = false
        self.defaultOutputDirty = false
        self.serviceRestartDirty = false
        guard await self.registerSystemListeners(generation: generation),
              await self.attachDataSourceListener(generation: generation)
        else {
            if self.isCurrent(generation) {
                await self.stop()
            }
            return false
        }
        return await self.finishStarting(generation: generation)
    }

    private func registerSystemListeners(generation: UInt64) async -> Bool {
        let sys = AudioObjectID(kAudioObjectSystemObject)
        let defaultInAddr = AudioObjectPropertyAddress(
            mSelector: kAudioHardwarePropertyDefaultInputDevice,
            mScope: kAudioObjectPropertyScopeGlobal,
            mElement: kAudioObjectPropertyElementMain
        )
        let defaultOutAddr = AudioObjectPropertyAddress(
            mSelector: kAudioHardwarePropertyDefaultOutputDevice,
            mScope: kAudioObjectPropertyScopeGlobal,
            mElement: kAudioObjectPropertyElementMain
        )
        let restartedAddr = AudioObjectPropertyAddress(
            mSelector: kAudioHardwarePropertyServiceRestarted,
            mScope: kAudioObjectPropertyScopeGlobal,
            mElement: kAudioObjectPropertyElementMain
        )
        let defaultInToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
            #if DEBUG
            AudioTopologyDiagnostics.record(
                .callbackBegin,
                owner: .meetingOutputRoute,
                objectID: sys,
                selector: kAudioHardwarePropertyDefaultInputDevice,
                scope: kAudioObjectPropertyScopeGlobal,
                element: kAudioObjectPropertyElementMain,
                queueRole: .mainDelivery
            )
            defer { AudioTopologyDiagnostics.record(
                .callbackEnd,
                owner: .meetingOutputRoute,
                objectID: sys,
                selector: kAudioHardwarePropertyDefaultInputDevice,
                scope: kAudioObjectPropertyScopeGlobal,
                element: kAudioObjectPropertyElementMain,
                queueRole: .mainDelivery
            ) }
            #endif
            MeetingMicrophoneEventExecution.afterHALCallback {
                Task { await self?.handleDefaultInputChanged(generation: generation) }
            }
        }
        let defaultOutToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
            #if DEBUG
            AudioTopologyDiagnostics.record(
                .callbackBegin,
                owner: .meetingOutputRoute,
                objectID: sys,
                selector: kAudioHardwarePropertyDefaultOutputDevice,
                scope: kAudioObjectPropertyScopeGlobal,
                element: kAudioObjectPropertyElementMain,
                queueRole: .mainDelivery
            )
            defer { AudioTopologyDiagnostics.record(
                .callbackEnd,
                owner: .meetingOutputRoute,
                objectID: sys,
                selector: kAudioHardwarePropertyDefaultOutputDevice,
                scope: kAudioObjectPropertyScopeGlobal,
                element: kAudioObjectPropertyElementMain,
                queueRole: .mainDelivery
            ) }
            #endif
            MeetingMicrophoneEventExecution.afterHALCallback {
                Task { await self?.handleDefaultOutputChanged(generation: generation) }
            }
        }
        let restartedToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
            #if DEBUG
            AudioTopologyDiagnostics.record(
                .callbackBegin,
                owner: .meetingOutputRoute,
                objectID: sys,
                selector: kAudioHardwarePropertyServiceRestarted,
                scope: kAudioObjectPropertyScopeGlobal,
                element: kAudioObjectPropertyElementMain,
                queueRole: .mainDelivery
            )
            defer { AudioTopologyDiagnostics.record(
                .callbackEnd,
                owner: .meetingOutputRoute,
                objectID: sys,
                selector: kAudioHardwarePropertyServiceRestarted,
                scope: kAudioObjectPropertyScopeGlobal,
                element: kAudioObjectPropertyElementMain,
                queueRole: .mainDelivery
            ) }
            #endif
            MeetingMicrophoneEventExecution.afterHALCallback {
                Task { await self?.handleServiceRestart(generation: generation) }
            }
        }
        #if DEBUG
        AudioTopologyDiagnostics.record(
            .listenerAddBegin,
            owner: .meetingOutputRoute,
            objectID: sys,
            selector: defaultInAddr.mSelector,
            scope: defaultInAddr.mScope,
            element: defaultInAddr.mElement,
            queueRole: .dedicatedControl,
            phase: .listener
        )
        #endif
        let defaultInputStatus = await AudioTopologyListenerExecution.add(objectID: sys, address: defaultInAddr, token: defaultInToken)
        #if DEBUG
        AudioTopologyDiagnostics.record(
            .listenerAddEnd,
            owner: .meetingOutputRoute,
            objectID: sys,
            selector: defaultInAddr.mSelector,
            scope: defaultInAddr.mScope,
            element: defaultInAddr.mElement,
            queueRole: .dedicatedControl,
            phase: .listener,
            status: defaultInputStatus
        )
        #endif
        guard defaultInputStatus == noErr, self.isCurrent(generation) else {
            if defaultInputStatus == noErr {
                _ = await AudioTopologyListenerExecution.remove(objectID: sys, address: defaultInAddr, token: defaultInToken)
            }
            return false
        }
        self.defaultInputToken = defaultInToken
        #if DEBUG
        AudioTopologyDiagnostics.record(
            .listenerAddBegin,
            owner: .meetingOutputRoute,
            objectID: sys,
            selector: defaultOutAddr.mSelector,
            scope: defaultOutAddr.mScope,
            element: defaultOutAddr.mElement,
            queueRole: .dedicatedControl,
            phase: .listener
        )
        #endif
        let defaultStatus = await AudioTopologyListenerExecution.add(objectID: sys, address: defaultOutAddr, token: defaultOutToken)
        #if DEBUG
        AudioTopologyDiagnostics.record(
            .listenerAddEnd,
            owner: .meetingOutputRoute,
            objectID: sys,
            selector: defaultOutAddr.mSelector,
            scope: defaultOutAddr.mScope,
            element: defaultOutAddr.mElement,
            queueRole: .dedicatedControl,
            phase: .listener,
            status: defaultStatus
        )
        #endif
        guard defaultStatus == noErr else {
            _ = await AudioTopologyListenerExecution.remove(objectID: sys, address: defaultInAddr, token: defaultInToken)
            if self.generation == generation { self.defaultInputToken = nil }
            return false
        }
        guard self.isCurrent(generation) else {
            _ = await AudioTopologyListenerExecution.remove(objectID: sys, address: defaultInAddr, token: defaultInToken)
            _ = await AudioTopologyListenerExecution.remove(objectID: sys, address: defaultOutAddr, token: defaultOutToken)
            return false
        }
        self.defaultOutputToken = defaultOutToken
        #if DEBUG
        AudioTopologyDiagnostics.record(
            .listenerAddBegin,
            owner: .meetingOutputRoute,
            objectID: sys,
            selector: restartedAddr.mSelector,
            scope: restartedAddr.mScope,
            element: restartedAddr.mElement,
            queueRole: .dedicatedControl,
            phase: .listener
        )
        #endif
        let restartedStatus = await AudioTopologyListenerExecution.add(objectID: sys, address: restartedAddr, token: restartedToken)
        #if DEBUG
        AudioTopologyDiagnostics.record(
            .listenerAddEnd,
            owner: .meetingOutputRoute,
            objectID: sys,
            selector: restartedAddr.mSelector,
            scope: restartedAddr.mScope,
            element: restartedAddr.mElement,
            queueRole: .dedicatedControl,
            phase: .listener,
            status: restartedStatus
        )
        #endif
        guard restartedStatus == noErr, self.isCurrent(generation) else {
            #if DEBUG
            AudioTopologyDiagnostics.record(
                .listenerRemoveBegin,
                owner: .meetingOutputRoute,
                objectID: sys,
                selector: defaultOutAddr.mSelector,
                scope: defaultOutAddr.mScope,
                element: defaultOutAddr.mElement,
                queueRole: .dedicatedControl,
                phase: .listener
            )
            #endif
            let cleanupStatus = await AudioTopologyListenerExecution.remove(objectID: sys, address: defaultOutAddr, token: defaultOutToken)
            _ = await AudioTopologyListenerExecution.remove(objectID: sys, address: defaultInAddr, token: defaultInToken)
            #if DEBUG
            AudioTopologyDiagnostics.record(
                .listenerRemoveEnd,
                owner: .meetingOutputRoute,
                objectID: sys,
                selector: defaultOutAddr.mSelector,
                scope: defaultOutAddr.mScope,
                element: defaultOutAddr.mElement,
                queueRole: .dedicatedControl,
                phase: .listener,
                status: cleanupStatus
            )
            #endif
            if self.generation == generation {
                self.defaultInputToken = nil
                self.defaultOutputToken = nil
            }
            if restartedStatus == noErr {
                _ = await AudioTopologyListenerExecution.remove(objectID: sys, address: restartedAddr, token: restartedToken)
            }
            return false
        }
        self.serviceRestartedToken = restartedToken
        return true
    }

    private func handleDefaultInputChanged(generation: UInt64) {
        guard self.isCurrent(generation) else { return }
        // Admission invalidation is the first owner-visible effect of a HAL notification. Listener
        // maintenance may await slow CoreAudio remove/add calls after this point.
        self.onChange(.healthy)
        guard self.lifecycle == .ready else {
            self.defaultInputDirty = true
            return
        }
    }

    private func attachDataSourceListener(generation: UInt64) async -> Bool {
        guard self.isCurrent(generation) else { return false }
        guard let device = AudioDevice.getDefaultOutputDevice() else { return false }
        self.dataSourceEpoch &+= 1
        let epoch = self.dataSourceEpoch
        let address = AudioObjectPropertyAddress(
            mSelector: kAudioDevicePropertyDataSource,
            mScope: kAudioObjectPropertyScopeOutput,
            mElement: kAudioObjectPropertyElementMain
        )
        let token: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
            #if DEBUG
            AudioTopologyDiagnostics.record(
                .callbackBegin,
                owner: .meetingOutputRoute,
                objectID: device.id,
                selector: kAudioDevicePropertyDataSource,
                scope: kAudioObjectPropertyScopeOutput,
                element: kAudioObjectPropertyElementMain,
                queueRole: .mainDelivery
            )
            defer { AudioTopologyDiagnostics.record(
                .callbackEnd,
                owner: .meetingOutputRoute,
                objectID: device.id,
                selector: kAudioDevicePropertyDataSource,
                scope: kAudioObjectPropertyScopeOutput,
                element: kAudioObjectPropertyElementMain,
                queueRole: .mainDelivery
            ) }
            #endif
            MeetingMicrophoneEventExecution.afterHALCallback {
                Task { await self?.handleDataSourceChanged(generation: generation, epoch: epoch) }
            }
        }
        #if DEBUG
        AudioTopologyDiagnostics.record(
            .listenerAddBegin,
            owner: .meetingOutputRoute,
            objectID: device.id,
            selector: address.mSelector,
            scope: address.mScope,
            element: address.mElement,
            queueRole: .dedicatedControl,
            phase: .listener
        )
        #endif
        let status = await AudioTopologyListenerExecution.add(objectID: device.id, address: address, token: token)
        #if DEBUG
        AudioTopologyDiagnostics.record(
            .listenerAddEnd,
            owner: .meetingOutputRoute,
            objectID: device.id,
            selector: address.mSelector,
            scope: address.mScope,
            element: address.mElement,
            queueRole: .dedicatedControl,
            phase: .listener,
            status: status
        )
        #endif
        guard status == noErr else { return false }
        guard self.isCurrent(generation), self.dataSourceEpoch == epoch else {
            _ = await AudioTopologyListenerExecution.remove(objectID: device.id, address: address, token: token)
            return false
        }
        self.dataSourceToken = token
        self.dataSourceDeviceID = device.id
        return true
    }

    private func detachDataSourceListener() async {
        self.dataSourceEpoch &+= 1
        guard let deviceID = self.dataSourceDeviceID, let token = self.dataSourceToken else { return }
        self.dataSourceToken = nil
        self.dataSourceDeviceID = nil
        let address = AudioObjectPropertyAddress(
            mSelector: kAudioDevicePropertyDataSource,
            mScope: kAudioObjectPropertyScopeOutput,
            mElement: kAudioObjectPropertyElementMain
        )
        #if DEBUG
        AudioTopologyDiagnostics.record(
            .listenerRemoveBegin,
            owner: .meetingOutputRoute,
            objectID: deviceID,
            selector: address.mSelector,
            scope: address.mScope,
            element: address.mElement,
            queueRole: .dedicatedControl,
            phase: .listener
        )
        #endif
        let status = await AudioTopologyListenerExecution.remove(objectID: deviceID, address: address, token: token)
        #if DEBUG
        AudioTopologyDiagnostics.record(
            .listenerRemoveEnd,
            owner: .meetingOutputRoute,
            objectID: deviceID,
            selector: address.mSelector,
            scope: address.mScope,
            element: address.mElement,
            queueRole: .dedicatedControl,
            phase: .listener,
            status: status
        )
        #endif
    }

    private func handleDefaultOutputChanged(generation: UInt64) async {
        guard self.isCurrent(generation) else { return }
        self.onChange(.healthy)
        guard self.lifecycle == .ready else {
            self.defaultOutputDirty = true
            return
        }
        await self.detachDataSourceListener()
        guard self.isCurrent(generation) else { return }
        guard await self.attachDataSourceListener(generation: generation) else {
            if self.isCurrent(generation) { self.onChange(.degraded) }
            return
        }
        guard self.isCurrent(generation) else { return }
    }

    private func handleDataSourceChanged(generation: UInt64, epoch: UInt64) {
        guard self.isCurrent(generation), self.dataSourceEpoch == epoch else { return }
        self.onChange(.healthy)
    }

    private func handleServiceRestart(generation: UInt64) async {
        guard self.isCurrent(generation) else { return }
        self.onChange(.healthy)
        guard self.lifecycle == .ready else {
            self.serviceRestartDirty = true
            return
        }
        let oldTokens = self.detachAll(invalidateLifecycle: true)
        let replacementGeneration = self.generation
        self.active = true
        self.lifecycle = .starting
        self.defaultInputDirty = false
        self.defaultOutputDirty = false
        self.serviceRestartDirty = false
        await Self.remove(tokens: oldTokens)
        guard self.isCurrent(replacementGeneration) else { return }
        guard await self.registerSystemListeners(generation: replacementGeneration),
              await self.attachDataSourceListener(generation: replacementGeneration)
        else {
            if self.isCurrent(replacementGeneration) {
                await self.stop()
            }
            self.onChange(.degraded)
            return
        }
        _ = await self.finishStarting(generation: replacementGeneration)
    }

    /// Listener callbacks may arrive after HAL installs a token but before the async add
    /// continuation commits ownership. Latch those callbacks while starting, then replay only
    /// after all three tokens are owned. A service restart takes precedence over a route refresh.
    private func finishStarting(generation: UInt64) async -> Bool {
        guard self.isCurrent(generation), self.lifecycle == .starting else { return false }
        self.lifecycle = .ready
        let restartWasDirty = self.serviceRestartDirty
        let inputWasDirty = self.defaultInputDirty
        let defaultWasDirty = self.defaultOutputDirty
        self.serviceRestartDirty = false
        self.defaultInputDirty = false
        self.defaultOutputDirty = false
        if restartWasDirty {
            await self.handleServiceRestart(generation: generation)
            return self.active && self.lifecycle == .ready
        }
        if inputWasDirty {
            self.handleDefaultInputChanged(generation: generation)
        }
        if defaultWasDirty {
            await self.handleDefaultOutputChanged(generation: generation)
        }
        return self.active && self.lifecycle == .ready
    }

    func stop() async {
        guard self.active || self.defaultInputToken != nil || self.defaultOutputToken != nil || self.serviceRestartedToken != nil || self.dataSourceToken != nil else { return }
        let tokens = self.detachAll(invalidateLifecycle: true)
        self.lifecycle = .idle
        self.defaultInputDirty = false
        self.defaultOutputDirty = false
        self.serviceRestartDirty = false
        await Self.remove(tokens: tokens)
    }

    private struct Tokens: @unchecked Sendable {
        let defaultInput: AudioObjectPropertyListenerBlock?
        let defaultOutput: AudioObjectPropertyListenerBlock?
        let serviceRestarted: AudioObjectPropertyListenerBlock?
        let dataSource: AudioObjectPropertyListenerBlock?
        let dataSourceDeviceID: AudioObjectID?
    }

    private func detachAll(invalidateLifecycle: Bool) -> Tokens {
        if invalidateLifecycle {
            self.active = false
            self.generation &+= 1
        }
        self.dataSourceEpoch &+= 1
        let tokens = Tokens(
            defaultInput: self.defaultInputToken,
            defaultOutput: self.defaultOutputToken,
            serviceRestarted: self.serviceRestartedToken,
            dataSource: self.dataSourceToken,
            dataSourceDeviceID: self.dataSourceDeviceID
        )
        self.defaultInputToken = nil
        self.defaultOutputToken = nil
        self.serviceRestartedToken = nil
        self.dataSourceToken = nil
        self.dataSourceDeviceID = nil
        return tokens
    }

    private static func remove(tokens: Tokens) async {
        let sys = AudioObjectID(kAudioObjectSystemObject)
        let defaultInAddr = AudioObjectPropertyAddress(
            mSelector: kAudioHardwarePropertyDefaultInputDevice,
            mScope: kAudioObjectPropertyScopeGlobal,
            mElement: kAudioObjectPropertyElementMain
        )
        let defaultOutAddr = AudioObjectPropertyAddress(
            mSelector: kAudioHardwarePropertyDefaultOutputDevice,
            mScope: kAudioObjectPropertyScopeGlobal,
            mElement: kAudioObjectPropertyElementMain
        )
        let restartedAddr = AudioObjectPropertyAddress(
            mSelector: kAudioHardwarePropertyServiceRestarted,
            mScope: kAudioObjectPropertyScopeGlobal,
            mElement: kAudioObjectPropertyElementMain
        )
        if let token = tokens.defaultInput {
            let status = await AudioTopologyListenerExecution.remove(objectID: sys, address: defaultInAddr, token: token)
            #if DEBUG
            AudioTopologyDiagnostics.record(
                .listenerRemoveEnd,
                owner: .meetingOutputRoute,
                objectID: sys,
                selector: defaultInAddr.mSelector,
                scope: defaultInAddr.mScope,
                element: defaultInAddr.mElement,
                queueRole: .dedicatedControl,
                phase: .listener,
                status: status
            )
            #endif
        }
        if let token = tokens.defaultOutput {
            #if DEBUG
            AudioTopologyDiagnostics.record(
                .listenerRemoveBegin,
                owner: .meetingOutputRoute,
                objectID: sys,
                selector: defaultOutAddr.mSelector,
                scope: defaultOutAddr.mScope,
                element: defaultOutAddr.mElement,
                queueRole: .dedicatedControl,
                phase: .listener
            )
            #endif
            let status = await AudioTopologyListenerExecution.remove(objectID: sys, address: defaultOutAddr, token: token)
            #if DEBUG
            AudioTopologyDiagnostics.record(
                .listenerRemoveEnd,
                owner: .meetingOutputRoute,
                objectID: sys,
                selector: defaultOutAddr.mSelector,
                scope: defaultOutAddr.mScope,
                element: defaultOutAddr.mElement,
                queueRole: .dedicatedControl,
                phase: .listener,
                status: status
            )
            #endif
        }
        if let token = tokens.serviceRestarted {
            #if DEBUG
            AudioTopologyDiagnostics.record(
                .listenerRemoveBegin,
                owner: .meetingOutputRoute,
                objectID: sys,
                selector: restartedAddr.mSelector,
                scope: restartedAddr.mScope,
                element: restartedAddr.mElement,
                queueRole: .dedicatedControl,
                phase: .listener
            )
            #endif
            let status = await AudioTopologyListenerExecution.remove(objectID: sys, address: restartedAddr, token: token)
            #if DEBUG
            AudioTopologyDiagnostics.record(
                .listenerRemoveEnd,
                owner: .meetingOutputRoute,
                objectID: sys,
                selector: restartedAddr.mSelector,
                scope: restartedAddr.mScope,
                element: restartedAddr.mElement,
                queueRole: .dedicatedControl,
                phase: .listener,
                status: status
            )
            #endif
        }
        if let token = tokens.dataSource, let deviceID = tokens.dataSourceDeviceID {
            let address = AudioObjectPropertyAddress(
                mSelector: kAudioDevicePropertyDataSource,
                mScope: kAudioObjectPropertyScopeOutput,
                mElement: kAudioObjectPropertyElementMain
            )
            _ = await AudioTopologyListenerExecution.remove(objectID: deviceID, address: address, token: token)
        }
    }

    private func isCurrent(_ generation: UInt64) -> Bool {
        self.active && self.generation == generation
    }
}

nonisolated enum MeetingVoiceProcessingDriftSnapshot {
    static func elapsedValidHostSeconds(_ stats: MeetingMicrophoneCaptureStats.Snapshot) -> Double {
        guard let first = stats.firstValidHostSeconds, let last = stats.lastValidHostSeconds, last > first else { return 0 }
        return last - first
    }

    /// Any re-anchor/step/config-change/dropped-run invalidates the single-epoch linear model.
    static func isEligible(_ stats: MeetingMicrophoneCaptureStats.Snapshot) -> Bool {
        stats.resyncCount == 0
            && stats.resyncClampCount == 0
            && stats.divergenceStepEventCount == 0
            && stats.configurationChangeEvents == 0
            && stats.droppedPostCapCount == 0
    }
}

/// Device election for a capture-side swap. Role is retained in the schema for old manifests but
/// never inferred or used by new capture decisions.
nonisolated struct MeetingCaptureDeviceElection: Sendable, Equatable {
    var identity: MeetingMicrophoneIdentity
    var role: MeetingMicrophoneRole

    static func elect(original: MeetingMicrophoneIdentity) async -> MeetingCaptureDeviceElection {
        let snapshot = await MeetingCaptureSourceCatalog.microphoneSnapshot()
        return Self.decide(
            original: original,
            catalog: snapshot.identities,
            defaultInputUID: snapshot.defaultCoreAudioUID
        )
    }

    static func transition(from active: MeetingMicrophoneIdentity) async -> MeetingCaptureDeviceTransition {
        let snapshot = await MeetingCaptureSourceCatalog.microphoneSnapshot()
        return Self.decideTransition(
            from: active,
            catalog: snapshot.identities,
            defaultInputUID: snapshot.defaultCoreAudioUID
        )
    }

    /// Route notifications are not proof that the input changed. A missing or unmatched system
    /// default is explicitly unavailable so callers stay fail-closed instead of silently rebinding
    /// the originally requested device.
    static func decideTransition(
        from active: MeetingMicrophoneIdentity,
        catalog: [MeetingMicrophoneIdentity],
        defaultInputUID: String?
    ) -> MeetingCaptureDeviceTransition {
        guard let defaultInputUID,
              let matched = catalog.first(where: { $0.coreAudioUID == defaultInputUID })
        else { return .unavailable }
        let election = Self.decide(
            original: active,
            catalog: catalog,
            defaultInputUID: defaultInputUID
        )
        let samePhysicalDevice: Bool
        if let activeUID = active.coreAudioUID, !activeUID.isEmpty,
           let electedUID = election.identity.coreAudioUID, !electedUID.isEmpty
        {
            samePhysicalDevice = activeUID == electedUID
        } else {
            samePhysicalDevice = active.captureDeviceID == election.identity.captureDeviceID
        }
        // `matched` is intentionally referenced through `decide`; it proves the default was in the
        // current catalog rather than a stale UID that happened to resemble the active identity.
        _ = matched
        return samePhysicalDevice ? .unchanged(election) : .changed(election)
    }

    /// Pure decision extracted from `elect(original:)` for hardware-free testing.
    static func decide(
        original: MeetingMicrophoneIdentity,
        catalog: [MeetingMicrophoneIdentity],
        defaultInputUID: String?
    ) -> MeetingCaptureDeviceElection {
        guard let defaultInputUID else {
            var neutral = original
            neutral.role = .unknown
            return MeetingCaptureDeviceElection(identity: neutral, role: .unknown)
        }
        guard let matched = catalog.first(where: { $0.coreAudioUID == defaultInputUID }) else {
            var neutral = original
            neutral.role = .unknown
            return MeetingCaptureDeviceElection(identity: neutral, role: .unknown)
        }
        let isSamePhysicalDevice = {
            if let originalUID = original.coreAudioUID, !originalUID.isEmpty,
               let matchedUID = matched.coreAudioUID, !matchedUID.isEmpty
            {
                return originalUID == matchedUID
            }
            return matched.captureDeviceID == original.captureDeviceID
        }()
        if isSamePhysicalDevice {
            var merged = matched
            merged.role = .unknown
            merged.avCaptureDeviceID = original.avCaptureDeviceID
                ?? (original.identitySchemaVersion == nil ? original.captureDeviceID : nil)
            return MeetingCaptureDeviceElection(identity: merged, role: .unknown)
        }
        return MeetingCaptureDeviceElection(
            identity: MeetingMicrophoneIdentity(
                captureDeviceID: matched.captureDeviceID,
                coreAudioUID: matched.coreAudioUID,
                displayName: matched.displayName,
                role: .unknown
            ),
            role: .unknown
        )
    }
}

nonisolated enum MeetingCaptureDeviceTransition: Sendable, Equatable {
    case unchanged(MeetingCaptureDeviceElection)
    case changed(MeetingCaptureDeviceElection)
    case unavailable
}

// Owns a swappable mic component (VPIO or AVCaptureSession) plus an app-audio-only SCStream that never stops across a swap.
// Keep this existing processing state machine intact during integration.
// swiftlint:disable:next type_body_length
private final nonisolated class VoiceProcessingMeetingRuntime: MeetingCaptureRuntime, @unchecked Sendable {
    private static let totalStartDeadlineSeconds: Double = 10
    private static let firstBufferDeadlineSeconds: Double = 2
    private static let downgradeSettleSeconds: Double = 0.75

    private enum Phase: Equatable {
        case starting
        case vpio
        case transitioning
        case committing
        case avCapture
        case failed
    }

    private enum DowngradeCommitDecision {
        case committed
        case stale
        case failed(String)
    }

    private let application: MeetingApplicationIdentity
    private let originalMicrophone: MeetingMicrophoneIdentity
    private let applicationWriter: MeetingAudioChunkWriter
    private let microphoneWriter: MeetingAudioChunkWriter
    private let eventHandler: @Sendable (MeetingCaptureEvent) -> Void
    private let liveAudioHandler: (@Sendable (MeetingAudioTrackKind, CMSampleBuffer) -> Void)?
    private let stateLock = NSLock()

    private var micCapture = MeetingMicrophoneCapture()
    private var gate = MeetingVoiceProcessingCommitGate()
    private var avCaptureComponent: MeetingAVCaptureMicrophoneComponent?
    private var currentFence = MeetingEraAcceptanceFence()
    private var interruptedThisEra = false

    private var appOnlyRuntime: ScreenCaptureMeetingRuntime?
    private var fallbackRuntime: ScreenCaptureMeetingRuntime?
    private var phase: Phase = .starting
    private var watchdogTask: Task<Void, Never>?
    private var outputRouteListener: MeetingOutputRouteListener?
    private var transitionTask: Task<Void, Never>?
    private var transitionGeneration: UInt64 = 0
    private var pendingAVCaptureFailure: (generation: UInt64, detail: String)?
    private var avCaptureFailureToken: MeetingAVCaptureAttemptToken?
    private var routeChangeDirty = false
    private var routeSafetyPersistenceFailed = false
    private var stopRequested = false
    private var routeDrivenFallback = false
    private let routeProtectionTasks = MeetingAsyncTaskChain()
    /// Pessimistically closed as soon as a route change is observed. A producer may reopen live
    /// admission only as part of the same commit that persists its new era.
    private let transcriptGate = MeetingMicrophoneTranscriptGate()
    private var voiceProcessingRecoveryAttempts = 0
    private var recoveryDwellTask: Task<Void, Never>?
    /// Parked before `start()` so stop/supersede can never lose ownership of it.
    private var pendingVoiceProcessingCapture: MeetingMicrophoneCapture?
    private var quarantined = false

    var captureScope: MeetingCaptureScope? {
        if let fallback = self.stateLock.withLock({ self.fallbackRuntime }) { return fallback.captureScope }
        return self.stateLock.withLock { self.appOnlyRuntime?.captureScope }
    }

    private init(
        application: MeetingApplicationIdentity,
        microphone: MeetingMicrophoneIdentity,
        applicationWriter: MeetingAudioChunkWriter,
        microphoneWriter: MeetingAudioChunkWriter,
        eventHandler: @escaping @Sendable (MeetingCaptureEvent) -> Void,
        liveAudioHandler: (@Sendable (MeetingAudioTrackKind, CMSampleBuffer) -> Void)?
    ) {
        self.application = application
        self.originalMicrophone = microphone
        self.applicationWriter = applicationWriter
        self.microphoneWriter = microphoneWriter
        self.eventHandler = eventHandler
        self.liveAudioHandler = liveAudioHandler
    }

    #if DEBUG
    deinit {
        AudioTopologyDiagnostics.record(.ownerWillDeinit, owner: .meetingCaptureEngine, queueRole: .callbackCurrent, phase: .runtimeStop)
    }
    #endif

    static func make(
        application: MeetingApplicationIdentity,
        microphone: MeetingMicrophoneIdentity,
        applicationWriter: MeetingAudioChunkWriter,
        microphoneWriter: MeetingAudioChunkWriter,
        eventHandler: @escaping @Sendable (MeetingCaptureEvent) -> Void,
        liveAudioHandler: (@Sendable (MeetingAudioTrackKind, CMSampleBuffer) -> Void)?
    ) async throws -> VoiceProcessingMeetingRuntime {
        VoiceProcessingMeetingRuntime(
            application: application,
            microphone: microphone,
            applicationWriter: applicationWriter,
            microphoneWriter: microphoneWriter,
            eventHandler: eventHandler,
            liveAudioHandler: liveAudioHandler
        )
    }

    func start() async throws {
        do {
            try await Self.withDeadline(seconds: Self.totalStartDeadlineSeconds) { [self] in
                try await self.runStartSequence()
            }
        } catch {
            // Deadline expiry during the fallback leg fails cleanly; never begin a further attempt.
            await self.cleanupAfterStartFailure()
            throw error
        }
    }

    private func runStartSequence() async throws {
        do {
            try await self.attemptVoiceProcessingStart()
        } catch {
            if error is CancellationError { throw error }
            if self.stateLock.withLock({ self.phase != .starting }) { throw error }
            let (gateToAbort, captureToStop, staleListener) = self.stateLock.withLock {
                () -> (MeetingVoiceProcessingCommitGate, MeetingMicrophoneCapture, MeetingOutputRouteListener?) in
                defer { self.outputRouteListener = nil }
                return (self.gate, self.micCapture, self.outputRouteListener)
            }
            await staleListener?.stop()
            gateToAbort.abort()
            await captureToStop.stop()
            await self.stopAppOnlyIfStarted()
            let fallbackProtection = MeetingRawMicrophoneProtection.classify(
                MeetingCaptureEngine.currentOutputRouteSnapshot()
            )
            let preFallbackTrack = await self.microphoneWriter.snapshot()
            guard preFallbackTrack.chunks.isEmpty,
                  preFallbackTrack.captureEras?.isEmpty != false
            else {
                throw MeetingCaptureError.captureStartFailed(
                    "Voice-processing fallback refused because microphone audio provenance was already committed."
                )
            }
            try await self.microphoneWriter.updateTrackMetadata { track in
                track.captureMethod = .screenCaptureKit
                track.voiceProcessingConfig = nil
                track.captureEras = [MeetingCaptureEra(
                    method: .screenCaptureKit,
                    deviceUID: self.originalMicrophone.coreAudioUID,
                    deviceName: self.originalMicrophone.displayName,
                    roleAtElection: self.originalMicrophone.role,
                    echoProtection: fallbackProtection,
                    startSeconds: 0
                )]
            }
            let fallback = try await ScreenCaptureMeetingRuntime.make(
                application: self.application,
                microphone: self.originalMicrophone,
                includeMicrophone: true,
                microphoneEchoProtection: fallbackProtection,
                applicationWriter: self.applicationWriter,
                microphoneWriter: self.microphoneWriter,
                eventHandler: self.eventHandler,
                liveAudioHandler: self.liveAudioHandler
            )
            // Assigned before start() so a cancelled/failed start can still be found and stopped.
            self.stateLock.withLock { self.fallbackRuntime = fallback }
            try await fallback.start()
        }
    }

    private func attemptVoiceProcessingStart() async throws {
        let microphoneWriter = self.microphoneWriter
        let liveAudioHandler = self.liveAudioHandler
        let transcriptGate = self.transcriptGate
        let gate = self.gate
        let fence = self.currentFence
        let capture = self.stateLock.withLock { self.micCapture }
        let outcome = try await capture.start(
            microphone: self.originalMicrophone,
            onSample: { sample in
                guard fence.beginSample() else { return }
                defer { fence.endSample() }
                switch gate.offer(sample) {
                case .passthrough:
                    microphoneWriter.enqueue(sample)
                    if transcriptGate.observeAndAdmit(sample) { liveAudioHandler?(.microphone, sample) }
                case .buffered, .aborted:
                    break
                }
            },
            onEvent: { [weak self] event in
                self?.handleMicEvent(event, owner: capture)
            }
        )
        if case .unavailable = outcome {
            throw MeetingCaptureError.captureStartFailed("Voice-processing microphone capture was unavailable.")
        }

        guard await self.waitForBufferProgress(timeoutSeconds: Self.firstBufferDeadlineSeconds) else {
            throw MeetingCaptureError.captureStartFailed("No microphone audio was captured within 2s.")
        }

        let appOnly = try await ScreenCaptureMeetingRuntime.make(
            application: self.application,
            microphone: self.originalMicrophone,
            includeMicrophone: false,
            applicationWriter: self.applicationWriter,
            microphoneWriter: self.microphoneWriter,
            eventHandler: self.eventHandler,
            liveAudioHandler: self.liveAudioHandler
        )
        try await appOnly.start()
        self.stateLock.withLock { self.appOnlyRuntime = appOnly }

        guard var batch = self.gate.beginCommitFlush() else {
            throw MeetingCaptureError.captureStartFailed("Voice-processing commit gate aborted before commit.")
        }
        // Promote provenance BEFORE the gate flushes a single VPIO byte; after this point a failure
        // must fail the start outright — falling back would mix provenance on promoted writers.
        self.stateLock.withLock { self.phase = .vpio }
        let settled = await self.micCapture.settledConfiguration()
        try await self.microphoneWriter.updateTrackMetadata { track in
            track.captureMethod = .voiceProcessing
            track.voiceProcessingConfig = settled
            track.captureEras = [MeetingCaptureEra(
                method: .voiceProcessing,
                deviceUID: self.originalMicrophone.coreAudioUID,
                deviceName: self.originalMicrophone.displayName,
                roleAtElection: self.originalMicrophone.role,
                echoProtection: .voiceProcessed,
                startSeconds: 0,
                settledConfig: settled
            )]
        }
        self.transcriptGate.update(.voiceProcessed)
        while true {
            await self.flushBatch(batch)
            guard let next = self.gate.continueCommitFlush() else { break }
            batch = next
        }
        await self.startOutputRouteWatch()
        self.startWatchdog()
    }

    private func stopAppOnlyIfStarted() async {
        if let appOnly = self.stateLock.withLock({ self.appOnlyRuntime }) {
            try? await appOnly.stop()
            self.stateLock.withLock { self.appOnlyRuntime = nil }
        }
    }

    private func cleanupAfterStartFailure() async {
        if let fallback = self.stateLock.withLock({ self.fallbackRuntime }) {
            try? await fallback.stop()
        }
        await self.micCapture.stop()
        await self.stopAppOnlyIfStarted()
    }

    /// Paced flush: the writer's pending budget is 24 slots, a full 5s ring is ~50 buffers.
    private func flushBatch(_ samples: [CMSampleBuffer]) async {
        for (index, sample) in samples.enumerated() {
            self.microphoneWriter.enqueue(sample)
            if self.transcriptGate.observeAndAdmit(sample) {
                self.liveAudioHandler?(.microphone, sample)
            }
            if index % 4 == 3 {
                try? await Task.sleep(nanoseconds: 5_000_000)
            }
        }
    }

    private func waitForBufferProgress(timeoutSeconds: Double, using capture: MeetingMicrophoneCapture? = nil) async -> Bool {
        let capture = capture ?? self.stateLock.withLock { self.micCapture }
        let baseline = await capture.statistics().buffersEmitted
        let deadline = Date().addingTimeInterval(timeoutSeconds)
        while Date() < deadline {
            if await capture.statistics().buffersEmitted > baseline { return true }
            try? await Task.sleep(nanoseconds: 50_000_000)
        }
        return false
    }

    private func waitForBufferProgress(
        timeoutSeconds: Double,
        using component: MeetingAVCaptureMicrophoneComponent
    ) async -> Bool {
        let baseline = component.sampleCount()
        let deadline = Date().addingTimeInterval(timeoutSeconds)
        while Date() < deadline {
            if component.sampleCount() > baseline { return true }
            try? await Task.sleep(nanoseconds: 50_000_000)
        }
        return false
    }

    private func startWatchdog() {
        let task = Task { [weak self] in
            guard let self else { return }
            let capture = self.stateLock.withLock { self.micCapture }
            var lastCount = await capture.statistics().buffersEmitted
            var lastProgress = Date()
            while !Task.isCancelled {
                try? await Task.sleep(nanoseconds: 1_000_000_000)
                if Task.isCancelled { return }
                guard self.stateLock.withLock({ self.phase == .vpio && self.micCapture === capture }) else { return }
                let current = await capture.statistics()
                if current.buffersEmitted != lastCount {
                    lastCount = current.buffersEmitted
                    lastProgress = Date()
                    continue
                }
                if MeetingVoiceProcessingWatchdog.isStalled(secondsSinceLastEmittedBuffer: Date().timeIntervalSince(lastProgress)) {
                    self.beginDowngradeTransition(reason: "No microphone audio emitted for 10s (drops=\(current.droppedPostCapCount), conversionFailures=\(current.conversionFailures)).")
                    return
                }
            }
        }
        self.stateLock.withLock { self.watchdogTask = task }
    }

    private func startAVCaptureWatchdog(
        generation: UInt64,
        component: MeetingAVCaptureMicrophoneComponent
    ) {
        let task = Task { [weak self] in
            guard let self else { return }
            var lastCount = component.sampleCount()
            var lastProgress = Date()
            while !Task.isCancelled {
                try? await Task.sleep(nanoseconds: 1_000_000_000)
                if Task.isCancelled { return }
                let stillOwnsComponent = self.stateLock.withLock {
                    self.phase == .avCapture
                        && self.transitionGeneration == generation
                        && self.avCaptureComponent === component
                }
                guard stillOwnsComponent else { return }
                let current = component.sampleCount()
                if current != lastCount {
                    lastCount = current
                    lastProgress = Date()
                    continue
                }
                if MeetingVoiceProcessingWatchdog.isStalled(
                    secondsSinceLastEmittedBuffer: Date().timeIntervalSince(lastProgress)
                ) {
                    self.beginAVCaptureRebind(
                        detail: "The active microphone stopped delivering audio buffers.",
                        forced: true
                    )
                    return
                }
            }
        }
        self.stateLock.withLock { self.watchdogTask = task }
    }

    /// Registered once: `handleRouteChange()` re-reads `phase` on every fire, so it never needs re-arming.
    private func startOutputRouteWatch() async {
        let listener = await MeetingOutputRouteListener.make { [weak self] health in
            if health == .degraded {
                self?.handleOutputRouteListenerFailure()
            } else {
                self?.handleRouteChange()
            }
        }
        if listener == nil { self.handleOutputRouteListenerFailure() }
        let retained = self.stateLock.withLock { () -> Bool in
            guard !self.stopRequested else { return false }
            self.outputRouteListener = listener
            return true
        }
        if !retained {
            await listener?.stop()
        }
    }

    private func handleOutputRouteListenerFailure() {
        let boundary = self.transcriptGate.invalidate()
        let shouldEmit = self.stateLock.withLock { () -> Bool in
            guard !self.stopRequested,
                  self.phase != .failed,
                  !self.routeSafetyPersistenceFailed
            else { return false }
            self.routeSafetyPersistenceFailed = true
            self.phase = .failed
            self.interruptedThisEra = true
            return true
        }
        guard shouldEmit else { return }
        self.persistRouteInvalidation(boundary)
        self.eventHandler(.interrupted(
            kind: .captureStoppedUnexpectedly,
            trackID: self.microphoneWriter.trackID,
            detail: "Core Audio route observation became unavailable; microphone transcription stopped fail-closed."
        ))
    }

    private func handleRouteChange() {
        enum Action { case evaluateVPIO, evaluateAVCapture, none }
        let outputRoute = MeetingCaptureEngine.currentOutputRouteSnapshot()
        let vpioDeclineReason = MeetingCapturePathDecider.outputRouteDeclineReason(outputRoute)
        let action = self.stateLock.withLock { () -> Action in
            guard !self.stopRequested else { return .none }
            switch self.phase {
            case .vpio:
                // VPIO remains echo-safe across notifications that do not actually make its route
                // unsupported. This filters unrelated/default-device property churn.
                guard vpioDeclineReason != nil else { return .none }
                self.persistRouteInvalidation(self.transcriptGate.invalidate())
                return .evaluateVPIO
            case .avCapture:
                self.persistRouteInvalidation(self.transcriptGate.invalidate())
                // Claim the observation before releasing the lock. If recovery wins
                // the next lock acquisition, finishTransition() will replay it
                // against whichever backend commits.
                self.routeChangeDirty = true
                return .evaluateAVCapture
            case .transitioning, .committing:
                self.persistRouteInvalidation(self.transcriptGate.invalidate())
                self.routeChangeDirty = true
                return .none
            case .starting, .failed:
                return .none
            }
        }
        switch action {
        case .evaluateVPIO:
            if let reason = vpioDeclineReason {
                self.beginDowngradeTransition(
                    reason: "Output route changed: \(reason)",
                    routeDriven: true
                )
            }
        case .evaluateAVCapture:
            // The backend stays sticky, but the physical input must follow the live
            // system default when a headset is attached or removed.
            self.beginAVCaptureRebind(
                detail: "The default microphone route changed.",
                forced: false
            )
        case .none:
            break
        }
    }

    /// Persists the same fail-closed boundary used by live admission. The task chain keeps rapid
    /// attach/detach notifications ordered without blocking the Core Audio notification callback.
    private func persistRouteInvalidation(_ boundary: MeetingMicrophoneTranscriptGate.InvalidationBoundary?) {
        self.routeProtectionTasks.enqueue { [weak self] in
            guard let self else { return }
            do {
                try await self.microphoneWriter.updateTrackMetadataFailClosed { track in
                    guard var eras = track.captureEras, !eras.isEmpty else { return }
                    if let boundary,
                       boundary.unsafeStartSeconds > (eras.last?.startSeconds ?? -.infinity)
                    {
                        var unprotected = eras[eras.index(before: eras.endIndex)]
                        unprotected.echoProtection = .unprotected
                        unprotected.startSeconds = boundary.unsafeStartSeconds
                        unprotected.settledConfig = nil
                        unprotected.clockDrift = nil
                        eras.append(unprotected)
                    } else {
                        eras[eras.index(before: eras.endIndex)].echoProtection = .unprotected
                    }
                    track.captureEras = eras
                }
            } catch {
                let shouldEmit = self.stateLock.withLock { () -> Bool in
                    guard !self.routeSafetyPersistenceFailed else { return false }
                    self.routeSafetyPersistenceFailed = true
                    self.phase = .failed
                    self.interruptedThisEra = true
                    return true
                }
                if shouldEmit {
                    self.eventHandler(.interrupted(
                        kind: .captureStoppedUnexpectedly,
                        trackID: self.microphoneWriter.trackID,
                        detail: "Microphone route safety metadata could not be saved; recording was stopped fail-closed."
                    ))
                }
            }
        }
    }

    /// Reopens a raw era only after a matching protected boundary is durable. The gap between the
    /// rewound invalidation cut and this observation absorbs route-notification latency.
    private func persistRawRouteResume(_ protection: MeetingMicrophoneEchoProtection) async -> Bool {
        guard protection.admitsTranscript,
              let boundarySeconds = self.transcriptGate.latestObservedSeconds()
        else { return false }
        await self.routeProtectionTasks.drain()
        var recorded = false
        try? await self.microphoneWriter.updateTrackMetadata { track in
            guard var eras = track.captureEras, !eras.isEmpty,
                  boundarySeconds > (eras.last?.startSeconds ?? -.infinity)
            else { return }
            var resumed = eras[eras.index(before: eras.endIndex)]
            resumed.echoProtection = protection
            resumed.startSeconds = boundarySeconds
            resumed.settledConfig = nil
            resumed.clockDrift = nil
            eras.append(resumed)
            track.captureEras = eras
            recorded = true
        }
        return recorded
    }

    /// A route event observed during a commit keeps the gate closed; `finishTransition` replays it
    /// against the newly committed backend instead of briefly admitting audio under stale facts.
    private func publishTranscriptProtection(_ protection: MeetingMicrophoneEchoProtection) {
        let mayOpen = self.stateLock.withLock { !self.routeChangeDirty && !self.stopRequested }
        self.transcriptGate.update(mayOpen ? protection : .unprotected)
        if mayOpen { self.eventHandler(.microphoneEchoProtectionChanged(protection)) }
    }

    private func handleMicEvent(_ event: MeetingMicrophoneCaptureEvent, owner: MeetingMicrophoneCapture) {
        let (phase, isOwner) = self.stateLock.withLock { (self.phase, self.micCapture === owner) }
        guard isOwner else { return }
        guard phase != .starting else {
            switch event {
            case .engineStopped:
                self.gate.offerTerminalEventPreCommit()
            case .defaultInputChanged:
                if let requestedUID = self.originalMicrophone.coreAudioUID,
                   AudioDevice.getDefaultInputDevice()?.uid != requestedUID
                {
                    self.gate.offerTerminalEventPreCommit()
                }
            case .configurationChanged, .overload:
                break
            }
            return
        }
        guard phase == .vpio else { return }
        switch event {
        case .configurationChanged:
            self.eventHandler(.interrupted(
                kind: .voiceProcessingConfigurationChanged,
                trackID: nil,
                detail: "Voice-processing engine configuration changed."
            ))
            Task { [weak self] in
                guard let self else { return }
                if await !self.waitForBufferProgress(timeoutSeconds: Self.firstBufferDeadlineSeconds) {
                    self.beginDowngradeTransition(detail: "No microphone audio resumed after a configuration change.")
                }
            }
        case .defaultInputChanged:
            guard let requestedUID = self.originalMicrophone.coreAudioUID else { return }
            if AudioDevice.getDefaultInputDevice()?.uid != requestedUID {
                self.beginDowngradeTransition(
                    reason: "The default input device changed away from the requested microphone.",
                    routeDriven: true
                )
            }
        case .overload:
            self.eventHandler(.interrupted(kind: .voiceProcessingOverload, trackID: nil, detail: "Voice-processing microphone reported an overload."))
        case .engineStopped:
            self.beginDowngradeTransition(reason: "The voice-processing microphone engine stopped unexpectedly.")
        }
    }

    private func handleAVCaptureFailureSignal(
        detail: String,
        generation: UInt64,
        token: MeetingAVCaptureAttemptToken
    ) {
        let shouldEmit = self.stateLock.withLock { () -> Bool in
            guard MeetingAVCaptureFailureAdmission.accepts(
                currentGeneration: self.transitionGeneration,
                eventGeneration: generation,
                activeToken: self.avCaptureFailureToken,
                eventToken: token,
                stopRequested: self.stopRequested
            ) else { return false }
            switch self.phase {
            case .transitioning, .committing:
                if self.pendingAVCaptureFailure == nil {
                    self.pendingAVCaptureFailure = (generation, detail)
                }
                return false
            case .avCapture:
                guard !self.interruptedThisEra else { return false }
                self.interruptedThisEra = true
                self.phase = .failed
                return true
            case .starting, .vpio, .failed:
                return false
            }
        }
        guard shouldEmit else { return }
        self.eventHandler(.interrupted(kind: .captureStoppedUnexpectedly, trackID: nil, detail: detail))
    }

    private func invalidateAVCaptureFailureToken(
        _ token: MeetingAVCaptureAttemptToken,
        generation: UInt64
    ) {
        self.stateLock.withLock {
            guard self.transitionGeneration == generation,
                  self.avCaptureFailureToken === token
            else { return }
            self.avCaptureFailureToken = nil
            if self.pendingAVCaptureFailure?.generation == generation {
                self.pendingAVCaptureFailure = nil
            }
        }
    }

    private func beginDowngradeTransition(reason: String, routeDriven: Bool = false) {
        self.beginDowngradeTransition(detail: reason, routeDriven: routeDriven)
    }

    private func beginDowngradeTransition(detail: String, routeDriven: Bool = false) {
        let watchdog = self.stateLock.withLock { () -> Task<Void, Never>? in
            guard self.phase == .vpio, !self.stopRequested else { return nil }
            self.transcriptGate.update(.unprotected)
            self.phase = .transitioning
            self.transitionGeneration &+= 1
            let generation = self.transitionGeneration
            self.pendingAVCaptureFailure = nil
            self.routeChangeDirty = false
            self.routeDrivenFallback = routeDriven
            let task = Task { [weak self] in
                guard let self else { return }
                await self.runDowngrade(detail: detail, generation: generation)
            }
            self.transitionTask = task
            defer { self.watchdogTask = nil }
            return self.watchdogTask
        }
        watchdog?.cancel()
    }

    private func runDowngrade(detail: String, generation: UInt64) async {
        try? await Task.sleep(nanoseconds: UInt64(Self.downgradeSettleSeconds * 1_000_000_000))
        guard self.ownsDowngradeTransition(generation) else {
            self.finishTransition(generation)
            return
        }

        let oldFence = self.stateLock.withLock { self.currentFence }
        var oldMicCapture: MeetingMicrophoneCapture? = self.stateLock.withLock { self.micCapture }
        await oldFence.quiesce()
        // Owned capture is present here; keep its optional lifetime so rollback releases hardware before replacement.
        // swiftlint:disable:next force_unwrapping
        let statsSnapshot = await oldMicCapture!.statistics()
        let drift = MeetingClockDriftRecord(
            cumulativeAbsorbedSeconds: statsSnapshot.cumulativeAbsorbedCorrectionSeconds,
            elapsedValidHostSeconds: MeetingVoiceProcessingDriftSnapshot.elapsedValidHostSeconds(statsSnapshot),
            eligible: MeetingVoiceProcessingDriftSnapshot.isEligible(statsSnapshot)
        )
        // Hard lifetime barrier: VPIO, its tap, and its Core Audio listeners must be
        // completely gone before any AVFoundation discovery/session construction.
        // Owned capture is present here; keep its optional lifetime so rollback releases hardware before replacement.
        // swiftlint:disable:next force_unwrapping
        await oldMicCapture!.stop()
        self.stateLock.withLock {
            if self.micCapture === oldMicCapture {
                self.micCapture = MeetingMicrophoneCapture()
            }
        }
        oldMicCapture = nil

        guard self.ownsDowngradeTransition(generation) else {
            self.finishTransition(generation)
            return
        }

        let elected = await MeetingCaptureDeviceElection.elect(original: self.originalMicrophone)
        guard self.ownsDowngradeTransition(generation) else {
            self.finishTransition(generation)
            return
        }
        let newFence = MeetingEraAcceptanceFence()
        let newGate = MeetingVoiceProcessingCommitGate()
        let microphoneWriter = self.microphoneWriter
        let liveAudioHandler = self.liveAudioHandler
        let transcriptGate = self.transcriptGate
        let failureToken = MeetingAVCaptureAttemptToken()
        guard self.stateLock.withLock({ () -> Bool in
            guard self.phase == .transitioning,
                  self.transitionGeneration == generation,
                  !self.stopRequested
            else { return false }
            self.avCaptureFailureToken = failureToken
            return true
        }) else {
            self.finishTransition(generation)
            return
        }
        let component: MeetingAVCaptureMicrophoneComponent
        do {
            component = try MeetingAVCaptureMicrophoneComponent(
                microphone: elected.identity,
                onSample: { sample in
                    guard newFence.beginSample() else { return }
                    defer { newFence.endSample() }
                    switch newGate.offer(sample) {
                    case .passthrough:
                        microphoneWriter.enqueue(sample)
                        if transcriptGate.observeAndAdmit(sample) { liveAudioHandler?(.microphone, sample) }
                    case .buffered, .aborted:
                        break
                    }
                },
                onTerminalStop: { [weak self] detail in
                    self?.handleAVCaptureFailureSignal(
                        detail: detail,
                        generation: generation,
                        token: failureToken
                    )
                }
            )
        } catch {
            self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
            self.failPendingDowngrade(
                generation: generation,
                detail: "Microphone unavailable after a route change: \(error.localizedDescription)"
            )
            self.finishTransition(generation)
            return
        }

        do {
            try await component.start()
        } catch {
            // `stop()` is a true control-queue barrier: if startRunning was still
            // executing, retirement cannot finish (or release the meeting lease)
            // until it returns and stopRunning has run behind it.
            self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
            try? await component.stop()
            self.failPendingDowngrade(
                generation: generation,
                detail: "Microphone unavailable after a route change: \(error.localizedDescription)"
            )
            self.finishTransition(generation)
            return
        }

        guard await self.waitForBufferProgress(
            timeoutSeconds: Self.firstBufferDeadlineSeconds,
            using: component
        ) else {
            self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
            try? await component.stop()
            self.failPendingDowngrade(
                generation: generation,
                detail: "The replacement microphone started but delivered no audio buffers."
            )
            self.finishTransition(generation)
            return
        }

        // Promote the bounded gate before the runtime's point of no return. If its
        // cap was exhausted while AVCapture started, fail with no era/event side
        // effects. Once promoted, arrivals are retained uncapped and in order
        // while metadata and the coordinator acknowledgement complete.
        guard var pendingBatch = newGate.beginCommitFlush() else {
            self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
            try? await component.stop()
            self.failPendingDowngrade(
                generation: generation,
                detail: "Microphone buffering overflowed before the route-change handoff could commit."
            )
            self.finishTransition(generation)
            return
        }

        // Point of no return. Before this lock succeeds, stop may cancel the
        // transition with no published method/era. After it succeeds, stop waits
        // for the complete metadata -> acknowledgement -> gate-flush transaction.
        let commitDecision = self.stateLock.withLock { () -> DowngradeCommitDecision in
            guard self.phase == .transitioning,
                  self.transitionGeneration == generation,
                  !self.stopRequested
            else { return .stale }
            if let failure = self.pendingAVCaptureFailure, failure.generation == generation {
                self.pendingAVCaptureFailure = nil
                self.phase = .failed
                return .failed(failure.detail)
            }
            self.currentFence = newFence
            self.avCaptureComponent = component
            self.phase = .committing
            self.interruptedThisEra = false
            return .committed
        }
        switch commitDecision {
        case .stale:
            self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
            try? await component.stop()
            self.finishTransition(generation)
            return
        case let .failed(failureDetail):
            self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
            try? await component.stop()
            self.eventHandler(.interrupted(
                kind: .captureStoppedUnexpectedly, trackID: nil, detail: failureDetail
            ))
            self.finishTransition(generation)
            return
        case .committed:
            break
        }

        await self.routeProtectionTasks.drain()
        let boundary = await self.microphoneWriter.beginSplice()
        let rawProtection = MeetingRawMicrophoneProtection.classify(
            MeetingCaptureEngine.currentOutputRouteSnapshot()
        )

        // A nil or non-monotonic boundary would misattribute audio; skip the era record instead.
        var recordedNewEra = false
        try? await self.microphoneWriter.updateTrackMetadata { [weak self] track in
            guard let self else { return }
            var eras = track.captureEras ?? [self.legacyEra(from: track)]
            if var last = eras.popLast() {
                last.clockDrift = drift
                eras.append(last)
            }
            if let boundary, boundary.seconds > (eras.last?.startSeconds ?? -.infinity) {
                eras.append(MeetingCaptureEra(
                    method: .avCaptureSession,
                    deviceUID: elected.identity.coreAudioUID,
                    deviceName: elected.identity.displayName,
                    roleAtElection: elected.role,
                    echoProtection: rawProtection,
                    startSeconds: boundary.seconds
                ))
                recordedNewEra = true
            }
            track.captureEras = eras
            // Multi-era: a track-level-only reader sees the conservative (AVCapture) value.
            track.captureMethod = .avCaptureSession
            track.clockDrift = drift
        }
        if !recordedNewEra {
            DebugLogger.shared.warning(
                "Meeting downgrade: no valid splice boundary (nil or non-monotonic) — the AVCapture era was not recorded; turns after this point stay attributed to the prior era.",
                source: "MeetingCaptureEngine"
            )
        } else {
            self.publishTranscriptProtection(rawProtection)
        }

        // Ack before flushing: readers must re-arm before any post-boundary sample reaches them.
        let ack = MeetingCaptureMethodChangeAck()
        self.eventHandler(.captureMethodChanged(trackID: self.microphoneWriter.trackID, method: .avCaptureSession, ack: ack))
        await ack.wait()

        while true {
            await self.flushBatch(pendingBatch)
            guard let next = newGate.continueCommitFlush() else { break }
            pendingBatch = next
        }

        let terminalFailure = self.stateLock.withLock { () -> String? in
            guard self.phase == .committing, self.transitionGeneration == generation else { return nil }
            if let failure = self.pendingAVCaptureFailure, failure.generation == generation {
                self.pendingAVCaptureFailure = nil
                self.interruptedThisEra = true
                self.phase = .failed
                return failure.detail
            }
            self.phase = .avCapture
            return nil
        }
        if let terminalFailure {
            self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
            self.eventHandler(.interrupted(
                kind: .captureStoppedUnexpectedly, trackID: nil, detail: terminalFailure
            ))
        } else {
            self.startAVCaptureWatchdog(generation: generation, component: component)
        }

        self.finishTransition(generation)
        if terminalFailure == nil { self.armSafeVoiceProcessingRecoveryIfViable() }
    }

    private func beginAVCaptureRebind(detail: String, forced: Bool) {
        let watchdog = self.stateLock.withLock { () -> Task<Void, Never>? in
            guard self.phase == .avCapture,
                  self.avCaptureComponent != nil,
                  !self.stopRequested
            else { return nil }
            self.transcriptGate.update(.unprotected)
            let previousGeneration = self.transitionGeneration
            self.phase = .transitioning
            self.transitionGeneration &+= 1
            let generation = self.transitionGeneration
            self.pendingAVCaptureFailure = nil
            self.routeChangeDirty = false
            if forced { self.routeDrivenFallback = false }
            let task = Task { [weak self] in
                guard let self else { return }
                await self.runAVCaptureRebind(
                    detail: detail,
                    forced: forced,
                    generation: generation,
                    previousGeneration: previousGeneration
                )
            }
            self.transitionTask = task
            defer { self.watchdogTask = nil }
            return self.watchdogTask
        }
        watchdog?.cancel()
    }

    private func runAVCaptureRebind(
        detail: String,
        forced: Bool,
        generation: UInt64,
        previousGeneration: UInt64
    ) async {
        try? await Task.sleep(nanoseconds: UInt64(Self.downgradeSettleSeconds * 1_000_000_000))
        guard self.ownsDowngradeTransition(generation),
              let oldComponent = self.stateLock.withLock({ self.avCaptureComponent })
        else {
            self.finishTransition(generation)
            return
        }

        // The settle window coalesces everything observed so far. Clear the dirty
        // bit immediately before the snapshot so only changes racing the snapshot
        // or the subsequent handoff need a replay.
        let readyToSnapshot = self.stateLock.withLock { () -> Bool in
            guard self.phase == .transitioning,
                  self.transitionGeneration == generation,
                  !self.stopRequested
            else { return false }
            self.routeChangeDirty = false
            return true
        }
        guard readyToSnapshot else {
            self.finishTransition(generation)
            return
        }
        let elected = await MeetingCaptureDeviceElection.elect(original: self.originalMicrophone)
        guard self.ownsDowngradeTransition(generation) else {
            self.finishTransition(generation)
            return
        }

        guard MeetingAVCaptureRebindDecision.shouldRebind(
            activeCoreAudioUID: oldComponent.deviceUID,
            electedCoreAudioUID: elected.identity.coreAudioUID,
            forced: forced
        ) else {
            let restored = self.stateLock.withLock { () -> (restored: Bool, replay: Bool) in
                guard self.phase == .transitioning,
                      self.transitionGeneration == generation,
                      !self.stopRequested,
                      self.avCaptureComponent === oldComponent
                else { return (false, false) }
                let replay = self.routeChangeDirty
                self.phase = .avCapture
                self.transitionGeneration = previousGeneration
                self.routeChangeDirty = false
                self.transitionTask = nil
                return (true, replay)
            }
            if restored.restored {
                let protection = MeetingRawMicrophoneProtection.classify(
                    MeetingCaptureEngine.currentOutputRouteSnapshot()
                )
                if await self.persistRawRouteResume(protection) {
                    self.publishTranscriptProtection(protection)
                }
                self.startAVCaptureWatchdog(generation: previousGeneration, component: oldComponent)
                if restored.replay { self.handleRouteChange() }
                self.armSafeVoiceProcessingRecoveryIfViable()
            }
            return
        }

        DebugLogger.shared.log(
            "Meeting AVCapture input rebind: \(oldComponent.deviceName) -> \(elected.identity.displayName) (\(detail))",
            source: "MeetingCaptureEngine"
        )

        // This is the same ownership invariant as the VPIO downgrade: retire the
        // old producer completely before AVFoundation discovers or starts another.
        let oldFence = self.stateLock.withLock { self.currentFence }
        await oldFence.quiesce()
        try? await oldComponent.stop()

        guard self.ownsDowngradeTransition(generation) else {
            self.finishTransition(generation)
            return
        }

        let microphoneWriter = self.microphoneWriter
        let liveAudioHandler = self.liveAudioHandler
        let transcriptGate = self.transcriptGate
        var selectedElection: MeetingCaptureDeviceElection?
        var selectedFence: MeetingEraAcceptanceFence?
        var selectedGate: MeetingVoiceProcessingCommitGate?
        var selectedComponent: MeetingAVCaptureMicrophoneComponent?
        var selectedFailureToken: MeetingAVCaptureAttemptToken?
        var lastCandidateFailure = "The replacement microphone was unavailable."

        // CoreAudio and AVFoundation do not settle atomically during Bluetooth
        // removal. Re-elect once after a bounded delay instead of permanently
        // failing the meeting on a transient catalog mismatch.
        for (attempt, retryDelay) in [0.0, 0.75].enumerated() {
            if retryDelay > 0 {
                try? await Task.sleep(nanoseconds: UInt64(retryDelay * 1_000_000_000))
            }
            guard self.ownsDowngradeTransition(generation) else {
                self.finishTransition(generation)
                return
            }
            let candidateElection = attempt == 0
                ? elected
                : await MeetingCaptureDeviceElection.elect(original: self.originalMicrophone)
            guard self.ownsDowngradeTransition(generation) else {
                self.finishTransition(generation)
                return
            }
            self.stateLock.withLock {
                if self.transitionGeneration == generation { self.pendingAVCaptureFailure = nil }
            }

            let candidateFence = MeetingEraAcceptanceFence()
            let candidateGate = MeetingVoiceProcessingCommitGate()
            let failureToken = MeetingAVCaptureAttemptToken()
            let tokenInstalled = self.stateLock.withLock { () -> Bool in
                guard self.phase == .transitioning,
                      self.transitionGeneration == generation,
                      !self.stopRequested
                else { return false }
                self.avCaptureFailureToken = failureToken
                return true
            }
            guard tokenInstalled else {
                self.finishTransition(generation)
                return
            }
            let candidate: MeetingAVCaptureMicrophoneComponent
            do {
                candidate = try MeetingAVCaptureMicrophoneComponent(
                    microphone: candidateElection.identity,
                    onSample: { sample in
                        guard candidateFence.beginSample() else { return }
                        defer { candidateFence.endSample() }
                        switch candidateGate.offer(sample) {
                        case .passthrough:
                            microphoneWriter.enqueue(sample)
                            if transcriptGate.observeAndAdmit(sample) { liveAudioHandler?(.microphone, sample) }
                        case .buffered, .aborted:
                            break
                        }
                    },
                    onTerminalStop: { [weak self] failure in
                        self?.handleAVCaptureFailureSignal(
                            detail: failure,
                            generation: generation,
                            token: failureToken
                        )
                    }
                )
            } catch {
                self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
                lastCandidateFailure = error.localizedDescription
                continue
            }

            do {
                try await candidate.start()
            } catch {
                // Even a failed start is retired through the same serialized
                // barrier before another candidate is constructed.
                self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
                try? await candidate.stop()
                lastCandidateFailure = error.localizedDescription
                continue
            }

            guard await self.waitForBufferProgress(
                timeoutSeconds: Self.firstBufferDeadlineSeconds,
                using: candidate
            ) else {
                self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
                try? await candidate.stop()
                lastCandidateFailure = "The microphone started but delivered no audio buffers."
                continue
            }

            let candidateFailed = self.stateLock.withLock {
                self.pendingAVCaptureFailure?.generation == generation
            }
            if candidateFailed {
                lastCandidateFailure = self.stateLock.withLock {
                    self.pendingAVCaptureFailure?.detail ?? "The microphone stopped before commit."
                }
                self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
                try? await candidate.stop()
                continue
            }

            selectedElection = candidateElection
            selectedFence = candidateFence
            selectedGate = candidateGate
            selectedComponent = candidate
            selectedFailureToken = failureToken
            break
        }

        guard let elected = selectedElection,
              let newFence = selectedFence,
              let newGate = selectedGate,
              let component = selectedComponent,
              let failureToken = selectedFailureToken
        else {
            self.failPendingDowngrade(
                generation: generation,
                detail: "Microphone rebind failed after retry: \(lastCandidateFailure)"
            )
            self.finishTransition(generation)
            return
        }

        guard var pendingBatch = newGate.beginCommitFlush() else {
            self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
            try? await component.stop()
            self.failPendingDowngrade(
                generation: generation,
                detail: "Microphone buffering overflowed before the input rebind could commit."
            )
            self.finishTransition(generation)
            return
        }

        let commitDecision = self.stateLock.withLock { () -> DowngradeCommitDecision in
            guard self.phase == .transitioning,
                  self.transitionGeneration == generation,
                  !self.stopRequested,
                  self.avCaptureComponent === oldComponent,
                  self.avCaptureFailureToken === failureToken
            else { return .stale }
            if let failure = self.pendingAVCaptureFailure, failure.generation == generation {
                self.pendingAVCaptureFailure = nil
                self.phase = .failed
                return .failed(failure.detail)
            }
            self.currentFence = newFence
            self.avCaptureComponent = component
            self.phase = .committing
            self.interruptedThisEra = false
            return .committed
        }
        switch commitDecision {
        case .stale:
            self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
            try? await component.stop()
            self.finishTransition(generation)
            return
        case let .failed(failureDetail):
            self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
            try? await component.stop()
            self.eventHandler(.interrupted(
                kind: .captureStoppedUnexpectedly, trackID: nil, detail: failureDetail
            ))
            self.finishTransition(generation)
            return
        case .committed:
            break
        }

        await self.routeProtectionTasks.drain()
        let boundary = await self.microphoneWriter.beginSplice()
        let rawProtection = MeetingRawMicrophoneProtection.classify(
            MeetingCaptureEngine.currentOutputRouteSnapshot()
        )
        var recordedNewEra = false
        do {
            try await self.microphoneWriter.updateTrackMetadata { track in
                var eras = track.captureEras ?? [self.legacyEra(from: track)]
                if let boundary, boundary.seconds > (eras.last?.startSeconds ?? -.infinity) {
                    eras.append(MeetingCaptureEra(
                        method: .avCaptureSession,
                        deviceUID: elected.identity.coreAudioUID,
                        deviceName: elected.identity.displayName,
                        roleAtElection: elected.role,
                        echoProtection: rawProtection,
                        startSeconds: boundary.seconds
                    ))
                    recordedNewEra = true
                }
                track.captureEras = eras
                track.captureMethod = .avCaptureSession
            }
            if recordedNewEra { self.publishTranscriptProtection(rawProtection) }
        } catch {
            self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
            await newFence.quiesce()
            try? await component.stop()
            let shouldEmit = self.stateLock.withLock { () -> Bool in
                guard self.phase == .committing, self.transitionGeneration == generation else { return false }
                self.phase = .failed
                self.interruptedThisEra = true
                return true
            }
            if shouldEmit {
                self.eventHandler(.interrupted(
                    kind: .captureStoppedUnexpectedly,
                    trackID: nil,
                    detail: "Could not persist the microphone rebind: \(error.localizedDescription)"
                ))
            }
            self.finishTransition(generation)
            return
        }

        // Re-arm live microphone segmentation before any sample from the new
        // physical source is released, even though the backend method is unchanged.
        let ack = MeetingCaptureMethodChangeAck()
        self.eventHandler(.captureMethodChanged(
            trackID: self.microphoneWriter.trackID,
            method: .avCaptureSession,
            ack: ack
        ))
        await ack.wait()

        while true {
            await self.flushBatch(pendingBatch)
            guard let next = newGate.continueCommitFlush() else { break }
            pendingBatch = next
        }

        let terminalFailure = self.stateLock.withLock { () -> String? in
            guard self.phase == .committing, self.transitionGeneration == generation else { return nil }
            if let failure = self.pendingAVCaptureFailure, failure.generation == generation {
                self.pendingAVCaptureFailure = nil
                self.interruptedThisEra = true
                self.phase = .failed
                return failure.detail
            }
            self.phase = .avCapture
            return nil
        }
        if let terminalFailure {
            self.invalidateAVCaptureFailureToken(failureToken, generation: generation)
            self.eventHandler(.interrupted(
                kind: .captureStoppedUnexpectedly, trackID: nil, detail: terminalFailure
            ))
        } else {
            self.startAVCaptureWatchdog(generation: generation, component: component)
        }
        self.finishTransition(generation)
        if terminalFailure == nil { self.armSafeVoiceProcessingRecoveryIfViable() }
    }

    private func legacyEra(from track: MeetingAudioTrack) -> MeetingCaptureEra {
        let method = track.captureMethod ?? .voiceProcessing
        return MeetingCaptureEra(
            method: method,
            deviceUID: self.originalMicrophone.coreAudioUID,
            deviceName: self.originalMicrophone.displayName,
            roleAtElection: self.originalMicrophone.role,
            echoProtection: method == .voiceProcessing ? .voiceProcessed : .legacyUnclassified,
            startSeconds: 0,
            settledConfig: track.voiceProcessingConfig,
            clockDrift: track.clockDrift
        )
    }

    #if false
    // Retained only as source history during the transition rollout. Compiled out so
    // an AVCapture fallback cannot create a second VPIO owner in this meeting.
    /// `dwellArming` reserves the slot in the SAME critical section as the `dwellTask == nil` check.
    private func armUpgradeDwellIfViable() {
        guard MeetingCaptureTransitionPolicy.allowsWithinSessionVoiceProcessingUpgrade else { return }
        guard self.stateLock.withLock({
            guard self.phase == .avCapture, self.dwellTask == nil, !self.dwellArming, !self.quarantined,
                  !self.stopRequested, self.upgradeAttempts < Self.maxUpgradeAttemptsPerSession
            else { return false }
            self.dwellArming = true
            return true
        }) else { return }
        let decision = MeetingCapturePathDecider.decide(
            mode: .onlineCall,
            microphone: self.originalMicrophone,
            outputRoute: MeetingCaptureEngine.currentOutputRouteSnapshot()
        )
        guard case .voiceProcessing = decision else {
            self.stateLock.withLock { self.dwellArming = false }
            return
        }

        let attemptIndex = self.stateLock.withLock { self.upgradeAttempts }
        let backoffSeconds = attemptIndex == 0 ? 0 : Self.upgradeBackoffBaseSeconds * pow(2, Double(attemptIndex - 1))
        let task = Task { [weak self] in
            try? await Task.sleep(nanoseconds: UInt64(backoffSeconds * 1_000_000_000))
            try? await Task.sleep(nanoseconds: UInt64(Self.upgradeDwellSeconds * 1_000_000_000))
            guard let self, !Task.isCancelled else { return }
            self.stateLock.withLock { self.dwellTask = nil }
            guard !(self.stateLock.withLock { self.stopRequested }), self.stateLock.withLock({ self.phase == .avCapture }) else { return }
            let stillViable = MeetingCapturePathDecider.decide(
                mode: .onlineCall,
                microphone: self.originalMicrophone,
                outputRoute: MeetingCaptureEngine.currentOutputRouteSnapshot()
            )
            guard case .voiceProcessing = stillViable else { return }
            await self.attemptUpgrade()
        }
        self.stateLock.withLock { self.dwellTask = task; self.dwellArming = false }
    }

    private func attemptUpgrade() async {
        let shouldStart = self.stateLock.withLock { () -> Bool in
            guard self.phase == .avCapture, !self.stopRequested else { return false }
            self.phase = .transitioning
            self.upgradeAttempts += 1
            return true
        }
        guard shouldStart else { return }
        let task = Task { [weak self] in
            guard let self else { return }
            await self.runUpgrade()
        }
        self.stateLock.withLock { self.transitionTask = task }
        await task.value
    }

    private func runUpgrade() async {
        try? await Task.sleep(nanoseconds: UInt64(Self.upgradeSettleSeconds * 1_000_000_000))
        guard !(self.stateLock.withLock { self.stopRequested }) else {
            self.finishTransition()
            return
        }
        guard case .voiceProcessing = MeetingCapturePathDecider.decide(
            mode: .onlineCall,
            microphone: self.originalMicrophone,
            outputRoute: MeetingCaptureEngine.currentOutputRouteSnapshot()
        ) else {
            self.stateLock.withLock { self.phase = .avCapture }
            self.finishTransition()
            return
        }

        let elected = await MeetingCaptureDeviceElection.elect(original: self.originalMicrophone)
        let candidateMicCapture = MeetingMicrophoneCapture()
        let candidateGate = MeetingVoiceProcessingCommitGate()
        let candidateFence = MeetingEraAcceptanceFence()

        let outcome: MeetingMicrophoneBindingOutcome
        do {
            outcome = try await candidateMicCapture.start(
                microphone: elected.identity,
                onSample: { sample in
                    guard candidateFence.beginSample() else { return }
                    defer { candidateFence.endSample() }
                    _ = candidateGate.offer(sample) // ring-gated: AVCapture stays authoritative
                },
                onEvent: { [weak self] event in
                    self?.handleMicEvent(event, owner: candidateMicCapture)
                }
            )
        } catch {
            self.abortUpgrade(candidateMicCapture: candidateMicCapture, reason: error.localizedDescription)
            return
        }
        if case .unavailable = outcome {
            self.abortUpgrade(candidateMicCapture: candidateMicCapture, reason: "Voice-processing microphone capture was unavailable.")
            return
        }
        guard await self.waitForBufferProgress(timeoutSeconds: Self.firstBufferDeadlineSeconds, using: candidateMicCapture) else {
            self.abortUpgrade(candidateMicCapture: candidateMicCapture, reason: "No microphone audio was captured within 2s.")
            return
        }
        guard !(self.stateLock.withLock { self.stopRequested }) else {
            self.abortUpgrade(candidateMicCapture: candidateMicCapture, reason: nil)
            return
        }
        guard case .voiceProcessing = MeetingCapturePathDecider.decide(
            mode: .onlineCall,
            microphone: self.originalMicrophone,
            outputRoute: MeetingCaptureEngine.currentOutputRouteSnapshot()
        ) else {
            self.abortUpgrade(candidateMicCapture: candidateMicCapture, reason: "Route changed back before the upgrade committed.")
            return
        }

        // Fence AVCapture's own acceptance so exactly one producer feeds the post-boundary chunk.
        let oldFence = self.stateLock.withLock { self.currentFence }
        let oldComponent = self.stateLock.withLock { self.avCaptureComponent }
        await oldFence.quiesce()

        await self.routeProtectionTasks.drain()
        let boundary = await self.microphoneWriter.beginSplice()
        let boundaryTime = boundary.map { CMTime(value: $0.value, timescale: $0.timescale) }

        guard let ring = candidateGate.beginCommitFlush() else {
            self.abortUpgrade(candidateMicCapture: candidateMicCapture, reason: "Voice-processing commit gate aborted before commit.")
            return
        }
        // Discard ring samples at/behind the boundary — else every upgrade duplicates ~2s.
        var pendingRing = MeetingUpgradeRingDiscard.discardingSamples(atOrBehind: boundaryTime, from: ring)

        let settled = await candidateMicCapture.settledConfiguration()
        // A nil or non-monotonic boundary would misattribute audio; skip the era record instead.
        var recordedNewEra = false
        try? await self.microphoneWriter.updateTrackMetadata { track in
            var eras = track.captureEras ?? []
            if let boundary, boundary.seconds > (eras.last?.startSeconds ?? -.infinity) {
                eras.append(MeetingCaptureEra(
                    method: .voiceProcessing,
                    deviceUID: elected.identity.coreAudioUID,
                    deviceName: elected.identity.displayName,
                    roleAtElection: elected.role,
                    echoProtection: .voiceProcessed,
                    startSeconds: boundary.seconds,
                    settledConfig: settled
                ))
                recordedNewEra = true
            }
            track.captureEras = eras
            track.captureMethod = .avCaptureSession // still multi-era: conservative legacy value
            track.voiceProcessingConfig = settled
        }
        if !recordedNewEra {
            DebugLogger.shared.warning(
                "Meeting upgrade: no valid splice boundary (nil or non-monotonic) — the voice-processing era was not recorded; turns after this point stay attributed to the prior era.",
                source: "MeetingCaptureEngine"
            )
        } else {
            self.publishTranscriptProtection(.voiceProcessed)
        }

        // Awaited: the MainActor hop (filter re-arm, history entry) must land before the gate opens.
        let ack = MeetingCaptureMethodChangeAck()
        self.eventHandler(.captureMethodChanged(trackID: self.microphoneWriter.trackID, method: .voiceProcessing, ack: ack))
        await ack.wait()

        self.stateLock.withLock {
            self.currentFence = candidateFence
            self.micCapture = candidateMicCapture
            self.gate = candidateGate
            self.phase = .vpio
            self.interruptedThisEra = false
            self.upgradeAttempts = 0
            self.avCaptureComponent = nil
        }

        while true {
            await self.flushBatch(pendingRing)
            guard let next = candidateGate.continueCommitFlush() else { break }
            pendingRing = next
        }

        self.startWatchdog()

        if let oldComponent {
            oldComponent.stopDetached(supervisedSeconds: Self.oldProducerStopSupervisionSeconds) { [weak self] completedInTime in
                guard let self, !completedInTime else { return }
                self.stateLock.withLock { self.quarantined = true }
            }
        }

        self.finishTransition()
    }

    private func abortUpgrade(candidateMicCapture: MeetingMicrophoneCapture, reason: String?) {
        if let reason {
            DebugLogger.shared.log("Meeting VPIO upgrade aborted: \(reason)", source: "MeetingCaptureEngine")
        }
        // Tracked in `abortedCaptureDrain` so stop() can wait it out instead of leaking it.
        self.abortedCaptureDrain.enter()
        candidateMicCapture.stopDetachedSupervised(seconds: Self.oldProducerStopSupervisionSeconds) { [weak self] _ in
            self?.abortedCaptureDrain.leave()
        }
        self.stateLock.withLock { self.phase = .avCapture }
        self.finishTransition()
        // Sticky fallback intentionally does not schedule another VPIO owner.
    }

    private func drainAbortedCaptures() async {
        await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
            self.abortedCaptureDrain.notify(queue: .global(qos: .userInitiated)) {
                continuation.resume()
            }
        }
    }
    #endif

    // MARK: - Stop-first AVCapture -> VPIO recovery

    private func armSafeVoiceProcessingRecoveryIfViable() {
        let outputRoute = MeetingCaptureEngine.currentOutputRouteSnapshot()
        let task = self.stateLock.withLock { () -> Task<Void, Never>? in
            guard self.phase == .avCapture,
                  self.avCaptureComponent != nil,
                  self.recoveryDwellTask == nil,
                  !self.stopRequested,
                  !self.quarantined,
                  MeetingCaptureTransitionPolicy.shouldAttemptVoiceProcessingRecovery(
                      routeDrivenFallback: self.routeDrivenFallback,
                      attempts: self.voiceProcessingRecoveryAttempts,
                      microphone: self.originalMicrophone,
                      outputRoute: outputRoute
                  )
            else { return nil }
            let task = Task { [weak self] in
                try? await Task.sleep(nanoseconds: UInt64(
                    MeetingVoiceProcessingUpgradeDwell.seconds * 1_000_000_000
                ))
                guard let self, !Task.isCancelled else { return }
                await self.beginSafeVoiceProcessingRecovery()
            }
            self.recoveryDwellTask = task
            return task
        }
        _ = task // retained by runtime; silence the intentional local discard
    }

    private func beginSafeVoiceProcessingRecovery() async {
        let elected = await MeetingCaptureDeviceElection.elect(original: self.originalMicrophone)
        let outputRoute = MeetingCaptureEngine.currentOutputRouteSnapshot()
        let started = self.stateLock.withLock { () -> Bool in
            self.recoveryDwellTask = nil
            guard self.phase == .avCapture,
                  self.avCaptureComponent != nil,
                  !self.stopRequested,
                  !self.quarantined,
                  MeetingCaptureTransitionPolicy.shouldAttemptVoiceProcessingRecovery(
                      routeDrivenFallback: self.routeDrivenFallback,
                      attempts: self.voiceProcessingRecoveryAttempts,
                      microphone: elected.identity,
                      outputRoute: outputRoute
                  )
            else { return false }
            self.transcriptGate.update(.unprotected)
            self.phase = .transitioning
            self.transitionGeneration &+= 1
            let generation = self.transitionGeneration
            self.voiceProcessingRecoveryAttempts += 1
            self.routeChangeDirty = false
            self.pendingAVCaptureFailure = nil
            self.avCaptureFailureToken = nil
            let task = Task { [weak self] in
                guard let self else { return }
                await self.runSafeVoiceProcessingRecovery(generation: generation)
            }
            self.transitionTask = task
            return true
        }
        if started {
            let watchdog = self.stateLock.withLock { () -> Task<Void, Never>? in
                defer { self.watchdogTask = nil }
                return self.watchdogTask
            }
            watchdog?.cancel()
        }
    }

    private func ownsSafeRecovery(_ generation: UInt64) -> Bool {
        self.stateLock.withLock {
            (self.phase == .transitioning || self.phase == .committing)
                && self.transitionGeneration == generation
                && !self.stopRequested
        }
    }

    private func runSafeVoiceProcessingRecovery(generation: UInt64) async {
        guard self.ownsSafeRecovery(generation) else {
            self.finishTransition(generation)
            return
        }

        let oldFence = self.stateLock.withLock { self.currentFence }
        var retiringComponent = self.stateLock.withLock { self.avCaptureComponent }
        guard retiringComponent != nil else {
            self.failPendingDowngrade(
                generation: generation,
                detail: "Voice-processing recovery had no active fallback microphone to retire."
            )
            self.finishTransition(generation)
            return
        }

        await oldFence.quiesce()
        do {
            try await retiringComponent?.stop()
        } catch {
            self.failSafeRecovery(
                generation: generation,
                detail: "Could not retire fallback microphone capture: \(error.localizedDescription)"
            )
            self.finishTransition(generation)
            return
        }
        guard retiringComponent?.isFullyRetired() == true else {
            self.failSafeRecovery(
                generation: generation,
                detail: "Fallback microphone teardown could not be proven; recovery was quarantined."
            )
            self.finishTransition(generation)
            return
        }

        // Remove every runtime strong reference, then drop the final local reference.
        // `MeetingAVCaptureMicrophoneComponent.stop()` has already dismantled the
        // session graph and removed observers on its serialized control queue.
        let cleared = self.stateLock.withLock { () -> Bool in
            guard self.phase == .transitioning,
                  self.transitionGeneration == generation,
                  self.avCaptureComponent === retiringComponent
            else { return false }
            self.avCaptureComponent = nil
            self.avCaptureFailureToken = nil
            self.pendingAVCaptureFailure = nil
            return true
        }
        retiringComponent = nil
        guard cleared, self.ownsSafeRecovery(generation) else {
            self.finishTransition(generation)
            return
        }

        await self.routeProtectionTasks.drain()
        let boundary = await self.microphoneWriter.beginSplice()
        guard self.ownsSafeRecovery(generation) else {
            self.finishTransition(generation)
            return
        }

        // Re-elect only after AVFoundation has released the old physical device.
        let elected = await MeetingCaptureDeviceElection.elect(original: self.originalMicrophone)
        guard self.ownsSafeRecovery(generation),
              MeetingCapturePathDecider.decide(
                  mode: .onlineCall,
                  microphone: elected.identity,
                  outputRoute: MeetingCaptureEngine.currentOutputRouteSnapshot()
              ) == .voiceProcessing
        else {
            await self.restoreAVCaptureAfterRecoveryFailure(
                generation: generation,
                boundary: boundary,
                detail: "The audio route changed before voice processing could restart."
            )
            return
        }

        // Optional by design: every rollback path explicitly drops the final local
        // reference after stop() and before constructing a fresh AVCaptureSession.
        var candidate: MeetingMicrophoneCapture? = MeetingMicrophoneCapture()
        let candidateGate = MeetingVoiceProcessingCommitGate()
        let candidateFence = MeetingEraAcceptanceFence()
        let microphoneWriter = self.microphoneWriter
        let liveAudioHandler = self.liveAudioHandler
        let transcriptGate = self.transcriptGate
        let parked = self.stateLock.withLock { () -> Bool in
            guard self.phase == .transitioning,
                  self.transitionGeneration == generation,
                  !self.stopRequested,
                  self.avCaptureComponent == nil
            else { return false }
            guard let candidate else { return false }
            self.pendingVoiceProcessingCapture = candidate
            self.micCapture = candidate
            return true
        }
        guard parked else {
            await candidate?.stop()
            candidate = nil
            self.finishTransition(generation)
            return
        }

        let outcome: MeetingMicrophoneBindingOutcome
        do {
            // Owned capture is present here; keep its optional lifetime so rollback releases hardware before replacement.
            // swiftlint:disable:next force_unwrapping
            outcome = try await candidate!.start(
                microphone: elected.identity,
                authorizationPreflighted: true,
                onSample: { sample in
                    guard candidateFence.beginSample() else { return }
                    defer { candidateFence.endSample() }
                    switch candidateGate.offer(sample) {
                    case .passthrough:
                        microphoneWriter.enqueue(sample)
                        if transcriptGate.observeAndAdmit(sample) { liveAudioHandler?(.microphone, sample) }
                    case .buffered, .aborted:
                        break
                    }
                },
                onEvent: { [weak self, weak candidate] event in
                    guard let candidate else { return }
                    self?.handleMicEvent(event, owner: candidate)
                }
            )
        } catch {
            await self.retirePendingVoiceProcessingCapture(generation: generation)
            candidate = nil
            await self.restoreAVCaptureAfterRecoveryFailure(
                generation: generation,
                boundary: boundary,
                detail: "Voice processing could not restart: \(error.localizedDescription)"
            )
            return
        }
        if case .unavailable = outcome {
            await self.retirePendingVoiceProcessingCapture(generation: generation)
            candidate = nil
            await self.restoreAVCaptureAfterRecoveryFailure(
                generation: generation,
                boundary: boundary,
                detail: "Voice-processing microphone capture was unavailable."
            )
            return
        }

        guard self.ownsSafeRecovery(generation),
              await self.waitForBufferProgress(
                  timeoutSeconds: Self.firstBufferDeadlineSeconds,
                  // Owned capture is present here; keep its optional lifetime so rollback releases hardware before replacement.
                  // swiftlint:disable:next force_unwrapping
                  using: candidate!
              ),
              self.ownsSafeRecovery(generation),
              MeetingCapturePathDecider.decide(
                  mode: .onlineCall,
                  microphone: elected.identity,
                  outputRoute: MeetingCaptureEngine.currentOutputRouteSnapshot()
              ) == .voiceProcessing
        else {
            await self.retirePendingVoiceProcessingCapture(generation: generation)
            candidate = nil
            await self.restoreAVCaptureAfterRecoveryFailure(
                generation: generation,
                boundary: boundary,
                detail: "Voice processing did not become ready on the settled audio route."
            )
            return
        }

        guard var pendingBatch = candidateGate.beginCommitFlush() else {
            await self.retirePendingVoiceProcessingCapture(generation: generation)
            candidate = nil
            await self.restoreAVCaptureAfterRecoveryFailure(
                generation: generation,
                boundary: boundary,
                detail: "Voice-processing buffering overflowed before recovery could commit."
            )
            return
        }
        let mayCommit = self.stateLock.withLock { () -> Bool in
            guard self.phase == .transitioning,
                  self.transitionGeneration == generation,
                  !self.stopRequested,
                  self.pendingVoiceProcessingCapture === candidate,
                  self.avCaptureComponent == nil,
                  self.pendingAVCaptureFailure == nil
            else { return false }
            self.phase = .committing
            return true
        }
        guard mayCommit else {
            await self.retirePendingVoiceProcessingCapture(generation: generation)
            candidate = nil
            self.finishTransition(generation)
            return
        }

        // Owned capture is present here; keep its optional lifetime so rollback releases hardware before replacement.
        // swiftlint:disable:next force_unwrapping
        let settled = await candidate!.settledConfiguration()
        var recordedNewEra = false
        do {
            try await self.microphoneWriter.updateTrackMetadata { track in
                var eras = track.captureEras ?? [self.legacyEra(from: track)]
                if let boundary, boundary.seconds > (eras.last?.startSeconds ?? -.infinity) {
                    eras.append(MeetingCaptureEra(
                        method: .voiceProcessing,
                        deviceUID: elected.identity.coreAudioUID,
                        deviceName: elected.identity.displayName,
                        roleAtElection: elected.role,
                        echoProtection: .voiceProcessed,
                        startSeconds: boundary.seconds,
                        settledConfig: settled
                    ))
                    recordedNewEra = true
                }
                track.captureEras = eras
                track.captureMethod = .voiceProcessing
                track.voiceProcessingConfig = settled
            }
            if recordedNewEra { self.publishTranscriptProtection(.voiceProcessed) }
        } catch {
            await self.retirePendingVoiceProcessingCapture(generation: generation)
            candidate = nil
            await self.restoreAVCaptureAfterRecoveryFailure(
                generation: generation,
                boundary: boundary,
                detail: "Could not persist voice-processing recovery: \(error.localizedDescription)"
            )
            return
        }

        let ack = MeetingCaptureMethodChangeAck()
        self.eventHandler(.captureMethodChanged(
            trackID: self.microphoneWriter.trackID,
            method: .voiceProcessing,
            ack: ack
        ))
        await ack.wait()
        guard self.ownsSafeRecovery(generation) else {
            await self.retirePendingVoiceProcessingCapture(generation: generation)
            candidate = nil
            self.finishTransition(generation)
            return
        }

        while true {
            await self.flushBatch(pendingBatch)
            guard let next = candidateGate.continueCommitFlush() else { break }
            pendingBatch = next
        }

        let committed = self.stateLock.withLock { () -> Bool in
            guard self.phase == .committing,
                  self.transitionGeneration == generation,
                  !self.stopRequested,
                  self.pendingVoiceProcessingCapture === candidate,
                  self.pendingAVCaptureFailure == nil
            else { return false }
            self.currentFence = candidateFence
            self.gate = candidateGate
            self.pendingVoiceProcessingCapture = nil
            self.phase = .vpio
            self.routeDrivenFallback = false
            self.interruptedThisEra = false
            return true
        }
        guard committed else {
            await self.retirePendingVoiceProcessingCapture(generation: generation)
            candidate = nil
            self.finishTransition(generation)
            return
        }
        DebugLogger.shared.log(
            "Meeting microphone recovered voice processing on \(elected.identity.displayName).",
            source: "MeetingCaptureEngine"
        )
        self.startWatchdog()
        self.finishTransition(generation)
    }

    private func retirePendingVoiceProcessingCapture(generation: UInt64) async {
        let capture = self.stateLock.withLock { self.pendingVoiceProcessingCapture }
        await capture?.stop()
        self.stateLock.withLock {
            guard self.transitionGeneration == generation,
                  self.pendingVoiceProcessingCapture === capture
            else { return }
            self.pendingVoiceProcessingCapture = nil
            self.micCapture = MeetingMicrophoneCapture()
        }
    }

    private func restoreAVCaptureAfterRecoveryFailure(
        generation: UInt64,
        boundary: MeetingMediaTime?,
        detail: String
    ) async {
        guard self.ownsSafeRecovery(generation) else {
            self.finishTransition(generation)
            return
        }
        let elected = await MeetingCaptureDeviceElection.elect(original: self.originalMicrophone)
        guard self.ownsSafeRecovery(generation) else {
            self.finishTransition(generation)
            return
        }

        let fence = MeetingEraAcceptanceFence()
        let gate = MeetingVoiceProcessingCommitGate()
        let token = MeetingAVCaptureAttemptToken()
        let microphoneWriter = self.microphoneWriter
        let liveAudioHandler = self.liveAudioHandler
        let transcriptGate = self.transcriptGate
        let component: MeetingAVCaptureMicrophoneComponent
        let rawProtection = MeetingRawMicrophoneProtection.classify(
            MeetingCaptureEngine.currentOutputRouteSnapshot()
        )
        do {
            component = try MeetingAVCaptureMicrophoneComponent(
                microphone: elected.identity,
                onSample: { sample in
                    guard fence.beginSample() else { return }
                    defer { fence.endSample() }
                    switch gate.offer(sample) {
                    case .passthrough:
                        microphoneWriter.enqueue(sample)
                        if transcriptGate.observeAndAdmit(sample) { liveAudioHandler?(.microphone, sample) }
                    case .buffered, .aborted:
                        break
                    }
                },
                onTerminalStop: { [weak self] failure in
                    self?.handleAVCaptureFailureSignal(
                        detail: failure,
                        generation: generation,
                        token: token
                    )
                }
            )
        } catch {
            self.failSafeRecovery(
                generation: generation,
                detail: "\(detail) Fallback microphone recreation failed: \(error.localizedDescription)"
            )
            self.finishTransition(generation)
            return
        }

        let parked = self.stateLock.withLock { () -> Bool in
            guard self.phase == .transitioning || self.phase == .committing,
                  self.transitionGeneration == generation,
                  !self.stopRequested,
                  self.pendingVoiceProcessingCapture == nil,
                  self.avCaptureComponent == nil
            else { return false }
            self.phase = .transitioning
            self.avCaptureComponent = component
            self.avCaptureFailureToken = token
            self.pendingAVCaptureFailure = nil
            return true
        }
        guard parked else {
            try? await component.stop()
            self.finishTransition(generation)
            return
        }

        do {
            try await component.start()
        } catch {
            self.invalidateAVCaptureFailureToken(token, generation: generation)
            try? await component.stop()
            self.failSafeRecovery(
                generation: generation,
                detail: "\(detail) Fallback microphone could not start: \(error.localizedDescription)"
            )
            self.finishTransition(generation)
            return
        }
        guard self.ownsSafeRecovery(generation),
              await self.waitForBufferProgress(
                  timeoutSeconds: Self.firstBufferDeadlineSeconds,
                  using: component
              ),
              self.ownsSafeRecovery(generation),
              var pendingBatch = gate.beginCommitFlush()
        else {
            self.invalidateAVCaptureFailureToken(token, generation: generation)
            try? await component.stop()
            self.failSafeRecovery(
                generation: generation,
                detail: "\(detail) Fallback microphone delivered no audio."
            )
            self.finishTransition(generation)
            return
        }

        let promotion = self.stateLock.withLock { () -> DowngradeCommitDecision in
            guard self.phase == .transitioning,
                  self.transitionGeneration == generation,
                  !self.stopRequested,
                  self.avCaptureComponent === component,
                  self.avCaptureFailureToken === token
            else { return .stale }
            if let failure = self.pendingAVCaptureFailure, failure.generation == generation {
                return .failed(failure.detail)
            }
            self.phase = .committing
            return .committed
        }
        switch promotion {
        case .committed:
            break
        case .stale:
            self.invalidateAVCaptureFailureToken(token, generation: generation)
            try? await component.stop()
            self.finishTransition(generation)
            return
        case let .failed(failureDetail):
            self.invalidateAVCaptureFailureToken(token, generation: generation)
            try? await component.stop()
            self.failSafeRecovery(generation: generation, detail: failureDetail)
            self.finishTransition(generation)
            return
        }
        var recordedNewEra = false
        do {
            try await self.microphoneWriter.updateTrackMetadata { track in
                var eras = track.captureEras ?? [self.legacyEra(from: track)]
                if let boundary, boundary.seconds > (eras.last?.startSeconds ?? -.infinity) {
                    eras.append(MeetingCaptureEra(
                        method: .avCaptureSession,
                        deviceUID: elected.identity.coreAudioUID,
                        deviceName: elected.identity.displayName,
                        roleAtElection: elected.role,
                        echoProtection: rawProtection,
                        startSeconds: boundary.seconds
                    ))
                    recordedNewEra = true
                }
                track.captureEras = eras
                track.captureMethod = .avCaptureSession
            }
            if recordedNewEra { self.publishTranscriptProtection(rawProtection) }
        } catch {
            self.invalidateAVCaptureFailureToken(token, generation: generation)
            try? await component.stop()
            self.failSafeRecovery(
                generation: generation,
                detail: "\(detail) Fallback microphone metadata could not be saved."
            )
            self.finishTransition(generation)
            return
        }

        let ack = MeetingCaptureMethodChangeAck()
        self.eventHandler(.captureMethodChanged(
            trackID: self.microphoneWriter.trackID,
            method: .avCaptureSession,
            ack: ack
        ))
        await ack.wait()
        guard self.ownsSafeRecovery(generation) else {
            self.invalidateAVCaptureFailureToken(token, generation: generation)
            try? await component.stop()
            self.finishTransition(generation)
            return
        }
        while true {
            await self.flushBatch(pendingBatch)
            guard let next = gate.continueCommitFlush() else { break }
            pendingBatch = next
        }

        let commitDecision = self.stateLock.withLock { () -> DowngradeCommitDecision in
            guard self.phase == .committing,
                  self.transitionGeneration == generation,
                  !self.stopRequested,
                  self.avCaptureComponent === component,
                  self.avCaptureFailureToken === token
            else { return .stale }
            if let failure = self.pendingAVCaptureFailure, failure.generation == generation {
                return .failed(failure.detail)
            }
            self.currentFence = fence
            self.phase = .avCapture
            // Route-driven recovery remains eligible for a bounded retry. The
            // policy's attempt cap prevents churn while allowing transient HAL
            // settling failures after Bluetooth removal to recover echo control.
            self.interruptedThisEra = false
            return .committed
        }
        switch commitDecision {
        case .committed:
            break
        case .stale:
            self.invalidateAVCaptureFailureToken(token, generation: generation)
            try? await component.stop()
            self.finishTransition(generation)
            return
        case let .failed(failureDetail):
            self.invalidateAVCaptureFailureToken(token, generation: generation)
            try? await component.stop()
            self.failSafeRecovery(generation: generation, detail: failureDetail)
            self.finishTransition(generation)
            return
        }
        DebugLogger.shared.warning(
            "\(detail) Continued with fallback microphone capture.",
            source: "MeetingCaptureEngine"
        )
        self.startAVCaptureWatchdog(generation: generation, component: component)
        self.finishTransition(generation)
        self.armSafeVoiceProcessingRecoveryIfViable()
    }

    private func failSafeRecovery(generation: UInt64, detail: String) {
        let shouldEmit = self.stateLock.withLock { () -> Bool in
            guard self.transitionGeneration == generation, !self.stopRequested else { return false }
            self.pendingVoiceProcessingCapture = nil
            self.avCaptureComponent = nil
            self.avCaptureFailureToken = nil
            self.pendingAVCaptureFailure = nil
            self.quarantined = true
            self.phase = .failed
            self.interruptedThisEra = true
            return true
        }
        if shouldEmit {
            self.eventHandler(.interrupted(
                kind: .captureStoppedUnexpectedly,
                trackID: nil,
                detail: detail
            ))
        }
    }

    private func ownsDowngradeTransition(_ generation: UInt64) -> Bool {
        self.stateLock.withLock {
            self.phase == .transitioning
                && self.transitionGeneration == generation
                && !self.stopRequested
        }
    }

    private func failPendingDowngrade(generation: UInt64, detail: String) {
        let shouldEmit = self.stateLock.withLock { () -> Bool in
            guard self.phase == .transitioning,
                  self.transitionGeneration == generation,
                  !self.stopRequested
            else { return false }
            self.pendingAVCaptureFailure = nil
            self.phase = .failed
            self.interruptedThisEra = true
            return true
        }
        if shouldEmit {
            self.eventHandler(.interrupted(
                kind: .captureStoppedUnexpectedly, trackID: nil, detail: detail
            ))
        }
    }

    private func finishTransition(_ generation: UInt64) {
        let shouldReplayRouteChange = self.stateLock.withLock { () -> Bool in
            guard self.transitionGeneration == generation else { return false }
            self.transitionTask = nil
            guard self.phase == .avCapture || self.phase == .vpio,
                  self.routeChangeDirty,
                  !self.stopRequested
            else { return false }
            self.routeChangeDirty = false
            return true
        }
        if shouldReplayRouteChange { self.handleRouteChange() }
    }

    func stop() async throws {
        let recoveryDwell = self.stateLock.withLock { () -> Task<Void, Never>? in
            self.stopRequested = true
            self.avCaptureFailureToken = nil
            self.pendingAVCaptureFailure = nil
            defer { self.recoveryDwellTask = nil }
            return self.recoveryDwellTask
        }
        recoveryDwell?.cancel()

        if let transitionTask = self.stateLock.withLock({ self.transitionTask }) {
            await transitionTask.value
        }
        let (watchdog, staleListener) = self.stateLock.withLock { () -> (Task<Void, Never>?, MeetingOutputRouteListener?) in
            defer { self.watchdogTask = nil; self.outputRouteListener = nil }
            return (self.watchdogTask, self.outputRouteListener)
        }
        watchdog?.cancel()
        await staleListener?.stop()
        await self.routeProtectionTasks.drain()

        if let fallback = self.stateLock.withLock({ self.fallbackRuntime }) {
            try await fallback.stop()
            return
        }

        let phase = self.stateLock.withLock { self.phase }
        guard phase == .vpio || phase == .avCapture else {
            let (gateToAbort, captureToStop) = self.stateLock.withLock { (self.gate, self.micCapture) }
            gateToAbort.abort()
            #if DEBUG
            AudioTopologyDiagnostics.record(.phaseBegin, owner: .meetingMicrophone, queueRole: .actorControl, phase: .microphoneStop)
            #endif
            await captureToStop.stop()
            #if DEBUG
            AudioTopologyDiagnostics.record(.phaseEnd, owner: .meetingMicrophone, queueRole: .actorControl, phase: .microphoneStop)
            #endif
            if let component = self.stateLock.withLock({ self.avCaptureComponent }) {
                try? await component.stop()
            }
            await self.stopAppOnlyIfStarted()
            return
        }

        if phase == .vpio {
            // Quiesce first — stats must not be snapshotted while the tap can still emit.
            let micCapture = self.stateLock.withLock { self.micCapture }
            #if DEBUG
            AudioTopologyDiagnostics.record(.phaseBegin, owner: .meetingMicrophone, queueRole: .actorControl, phase: .microphoneStop)
            #endif
            await micCapture.stop()
            #if DEBUG
            AudioTopologyDiagnostics.record(.phaseEnd, owner: .meetingMicrophone, queueRole: .actorControl, phase: .microphoneStop)
            #endif
            let statsSnapshot = await micCapture.statistics()
            let drift = MeetingClockDriftRecord(
                cumulativeAbsorbedSeconds: statsSnapshot.cumulativeAbsorbedCorrectionSeconds,
                elapsedValidHostSeconds: MeetingVoiceProcessingDriftSnapshot.elapsedValidHostSeconds(statsSnapshot),
                eligible: MeetingVoiceProcessingDriftSnapshot.isEligible(statsSnapshot)
            )
            try? await self.microphoneWriter.updateTrackMetadata { track in
                track.clockDrift = drift
                if var eras = track.captureEras, var last = eras.popLast() {
                    last.clockDrift = drift
                    eras.append(last)
                    track.captureEras = eras
                }
            }
        } else if let component = self.stateLock.withLock({ self.avCaptureComponent }) {
            #if DEBUG
            AudioTopologyDiagnostics.record(.phaseBegin, owner: .avCapture, queueRole: .actorControl, phase: .avCaptureStop)
            #endif
            try? await component.stop()
            #if DEBUG
            AudioTopologyDiagnostics.record(.phaseEnd, owner: .avCapture, queueRole: .actorControl, phase: .avCaptureStop)
            #endif
        }

        if let appOnly = self.stateLock.withLock({ self.appOnlyRuntime }) {
            #if DEBUG
            AudioTopologyDiagnostics.record(.phaseBegin, owner: .screenCapture, queueRole: .actorControl, phase: .screenCaptureStop)
            defer { AudioTopologyDiagnostics.record(.phaseEnd, owner: .screenCapture, queueRole: .actorControl, phase: .screenCaptureStop) }
            #endif
            try await appOnly.stop()
        }
    }

    private static func withDeadline<T>(seconds: Double, operation: @escaping @Sendable () async throws -> T) async throws -> T {
        try await withThrowingTaskGroup(of: T.self) { group in
            group.addTask { try await operation() }
            group.addTask {
                try await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
                throw MeetingCaptureError.captureStartFailed("Voice-processing capture start exceeded \(Int(seconds))s.")
            }
            defer { group.cancelAll() }
            guard let result = try await group.next() else {
                throw MeetingCaptureError.captureStartFailed("Voice-processing capture start produced no result.")
            }
            return result
        }
    }
}