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

chore: satisfy strict lint and validate optional audio values

altic-devef74d20d7073
diff --git a/Sources/Fluid/AppDelegate.swift b/Sources/Fluid/AppDelegate.swift
index 8e44cbe8..50206f24 100644
--- a/Sources/Fluid/AppDelegate.swift
+++ b/Sources/Fluid/AppDelegate.swift
@@ -48,34 +48,34 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele
func applicationDidFinishLaunching(_ notification: Notification) {
AccessibilityMessagingTimeout.configure()
#if DEBUG
- // Stage 0.5, Trial A, and C2 autoruns must return before Core Audio observers,
- // logging, AppServices, and UI startup. Each owns one bounded diagnostic stream.
- if MeetingStage05EvidenceAutorun.startIfRequested() {
- return
- }
- if MeetingExternalReferenceTrialAAutorun.startIfRequested() {
- return
- }
- if MeetingSCKPairedAutorun.startIfRequested() {
- return
- }
- // Must precede every Core Audio observer. Disabled unless explicitly
- // requested through the Phase 0 diagnostics environment.
- AudioTopologyDiagnostics.shared.startIfRequested()
- // App-hosted XCTest otherwise starts the normal UI/audio services alongside the
- // exclusive VPIO hardware probe. Keep that opt-in diagnostic launch isolated.
- if ProcessInfo.processInfo.environment["FLUIDVOICE_MIC_PHASE1"] != nil
- || ProcessInfo.processInfo.environment["FLUIDVOICE_VPIO_ACOUSTIC"] == "1"
- {
- return
- }
+ // Stage 0.5, Trial A, and C2 autoruns must return before Core Audio observers,
+ // logging, AppServices, and UI startup. Each owns one bounded diagnostic stream.
+ if MeetingStage05EvidenceAutorun.startIfRequested() {
+ return
+ }
+ if MeetingExternalReferenceTrialAAutorun.startIfRequested() {
+ return
+ }
+ if MeetingSCKPairedAutorun.startIfRequested() {
+ return
+ }
+ // Must precede every Core Audio observer. Disabled unless explicitly
+ // requested through the Phase 0 diagnostics environment.
+ AudioTopologyDiagnostics.shared.startIfRequested()
+ // App-hosted XCTest otherwise starts the normal UI/audio services alongside the
+ // exclusive VPIO hardware probe. Keep that opt-in diagnostic launch isolated.
+ if ProcessInfo.processInfo.environment["FLUIDVOICE_MIC_PHASE1"] != nil
+ || ProcessInfo.processInfo.environment["FLUIDVOICE_VPIO_ACOUSTIC"] == "1"
+ {
+ return
+ }
#endif
// Bring up file logging + crash handlers immediately during launch.
_ = FileLogger.shared
TypingService.startKeyboardLayoutTracking()
_ = TranscriptionHistoryStore.shared
#if DEBUG
- MeetingDetectorFeasibilityProbe.startIfRequested()
+ MeetingDetectorFeasibilityProbe.startIfRequested()
#endif
// Must be read during the launch callback - the current Apple Event identifies
// login-item launches (used to optionally start silently, see issue #369).
@@ -157,7 +157,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele
self.updateCheckTimer?.invalidate()
self.updateCheckTimer = nil
#if DEBUG
- AudioTopologyDiagnostics.shared.stop()
+ AudioTopologyDiagnostics.shared.stop()
#endif
}
@@ -339,6 +339,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele
}
}
}
+
/// Realize the main window invisibly so ContentView's startup runs, then order it out.
/// Used for login-item launches when "Show window when launched at login" is off.
@discardableResult
diff --git a/Sources/Fluid/Networking/ModelDownloader.swift b/Sources/Fluid/Networking/ModelDownloader.swift
index 4bc506b3..f06ea13b 100644
--- a/Sources/Fluid/Networking/ModelDownloader.swift
+++ b/Sources/Fluid/Networking/ModelDownloader.swift
@@ -208,7 +208,10 @@ final class HuggingFaceModelDownloader {
downloadedBytes += expectedFileBytes
let pct = min(maximumIncompleteProgress, Double(downloadedBytes) / Double(totalBytes))
onProgress?(pct, rel)
- DebugLogger.shared.info(String(format: "[ModelDL] Overall progress: %.1f%% (\(Self.formatBytes(downloadedBytes))/\(Self.formatBytes(totalBytes)))", pct * 100.0), source: "ModelDownloader")
+ DebugLogger.shared.info(
+ String(format: "[ModelDL] Overall progress: %.1f%% (\(Self.formatBytes(downloadedBytes))/\(Self.formatBytes(totalBytes)))", pct * 100.0),
+ source: "ModelDownloader"
+ )
}
}
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index ca7a8475..69fa334d 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -5156,7 +5156,8 @@ final class SettingsStore: ObservableObject {
var isWhisperModel: Bool {
switch self {
- case .parakeetTDT, .parakeetTDTv2, .parakeetRealtime, .qwen3Asr, .cohereTranscribeSixBit, .nemotronOffline, .nemotronStreaming, .nemotronStreaming320, .appleSpeech, .appleSpeechAnalyzer: return false
+ case .parakeetTDT, .parakeetTDTv2, .parakeetRealtime, .qwen3Asr, .cohereTranscribeSixBit, .nemotronOffline, .nemotronStreaming, .nemotronStreaming320, .appleSpeech,
+ .appleSpeechAnalyzer: return false
default: return true
}
}
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 14757442..b7df0a9a 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -415,6 +415,9 @@ nonisolated enum ASRHardwareListenerPolicy {
return pendingIdentityMatches ? .latchUntilInstalled : .ignore
}
+ // Keep the explicit existing capture inputs together.
+
+ // swiftlint:disable:next function_parameter_count
static func selectedDeviceQueryCanApply(
isTerminating: Bool,
capturedLifecycle: UInt64,
@@ -621,9 +624,15 @@ final class ASRService: ObservableObject {
private var meetingAudioHandbackLease: ASRActivityLease?
private var meetingAudioHandbackTask: Task<Void, Never>?
private var meetingAudioHandbackTaskID: UUID?
+ // Keep the existing descriptive state or persisted evidence field name.
+ // swiftlint:disable:next identifier_name
private var meetingHandoffShouldRestorePreparedCapture = false
private var deferredMeetingRouteRecoveryReason: String?
+ // Keep the existing descriptive state or persisted evidence field name.
+ // swiftlint:disable:next identifier_name
private var deferredMeetingRouteRecoveryRequiresPrewarm = false
+ // Keep the existing descriptive state or persisted evidence field name.
+ // swiftlint:disable:next identifier_name
private var deferredMeetingRouteRecoveryReconcilesInput = false
private struct MeetingASRScope {
let id: UUID
@@ -635,10 +644,10 @@ final class ASRService: ObservableObject {
private var meetingASRPreparationOwner: MeetingASRPreparationOwner?
private var activeMeetingASRScope: MeetingASRScope?
private var deferredMeetingActivityLeaseRelease: ASRActivityLease?
-#if DEBUG
+ #if DEBUG
/// Test seam replacing the lazily wired production owner so scope tests use fake providers.
var meetingASRPreparationOwnerForTesting: MeetingASRPreparationOwner?
-#endif
+ #endif
var isRunningOrStarting: Bool {
self.isRunning || self.isStarting
}
@@ -662,8 +671,8 @@ final class ASRService: ObservableObject {
return
}
#if DEBUG
- AudioTopologyDiagnostics.record(.phaseBegin, owner: .asrActivityLease, queueRole: .mainControl, phase: .activityLease)
- defer { AudioTopologyDiagnostics.record(.phaseEnd, owner: .asrActivityLease, queueRole: .mainControl, phase: .activityLease) }
+ AudioTopologyDiagnostics.record(.phaseBegin, owner: .asrActivityLease, queueRole: .mainControl, phase: .activityLease)
+ defer { AudioTopologyDiagnostics.record(.phaseEnd, owner: .asrActivityLease, queueRole: .mainControl, phase: .activityLease) }
#endif
self.activeActivityLease = nil
self.activeExclusiveActivity = nil
@@ -1057,7 +1066,8 @@ final class ASRService: ObservableObject {
}
if let meetingOwner = self.activeMeetingASRPreparationOwner,
let claimToken = meetingOwner.currentClaimToken,
- meetingOwner.isClaimed || meetingOwner.isDraining {
+ meetingOwner.isClaimed || meetingOwner.isDraining
+ {
await meetingOwner.release(claimToken)
}
await self.meetingTranscriptionExecutor.cancelAndAwaitPending()
@@ -1870,7 +1880,10 @@ final class ASRService: ObservableObject {
reason: reason,
recoveringRoute: self.isRecoveringAudioRoute
)
- DebugLogger.shared.debug("CLOSE_DETAIL audioCallerResumed uptime=\(ProcessInfo.processInfo.systemUptime) awaitMs=\((ProcessInfo.processInfo.systemUptime - captureAwaitStartedAt) * 1000)", source: "StopTiming")
+ DebugLogger.shared.debug(
+ "CLOSE_DETAIL audioCallerResumed uptime=\(ProcessInfo.processInfo.systemUptime) awaitMs=\((ProcessInfo.processInfo.systemUptime - captureAwaitStartedAt) * 1000)",
+ source: "StopTiming"
+ )
if report.status != noErr {
DebugLogger.shared.warning(
"Direct Core Audio stop returned OSStatus \(report.status)",
@@ -1924,6 +1937,7 @@ final class ASRService: ObservableObject {
var dictionaryTestAudioPublisher: AnyPublisher<[Float], Never> {
self.dictionaryTestAudioSubject.eraseToAnyPublisher()
}
+
private var lastCompletedAudioSnapshot: DictationAudioSnapshot?
private var lastDictionaryLearningRecording: DictionaryLearningRecording?
private var dictionaryLearningExpiryTask: Task<Void, Never>?
@@ -3654,7 +3668,10 @@ final class ASRService: ObservableObject {
self.recordWordBoostHitIfAny(transcribedText: outputText)
}
DebugLogger.shared.debug("After post-processing: '\(outputText)'", source: "ASRService")
- self.benchmarkLog("stop_end result=success totalMs=\(self.elapsedMilliseconds(since: stopStartedAt)) recordingAgeMs=\(self.elapsedMilliseconds(since: self.benchmarkRecordingStartedAt)) cleanedChars=\(outputText.count)")
+ self
+ .benchmarkLog(
+ "stop_end result=success totalMs=\(self.elapsedMilliseconds(since: stopStartedAt)) recordingAgeMs=\(self.elapsedMilliseconds(since: self.benchmarkRecordingStartedAt)) cleanedChars=\(outputText.count)"
+ )
if !isolatedDictionaryCapture,
SettingsStore.shared.saveTranscriptionHistory,
SettingsStore.shared.saveAudioWithTranscriptionHistory,
@@ -3915,7 +3932,7 @@ final class ASRService: ObservableObject {
private var activeMeetingASRPreparationOwner: MeetingASRPreparationOwner? {
#if DEBUG
- if let injected = self.meetingASRPreparationOwnerForTesting { return injected }
+ if let injected = self.meetingASRPreparationOwnerForTesting { return injected }
#endif
return self.meetingASRPreparationOwner
}
@@ -3927,7 +3944,7 @@ final class ASRService: ObservableObject {
private func meetingASROwner() -> MeetingASRPreparationOwner {
#if DEBUG
- if let injected = self.meetingASRPreparationOwnerForTesting { return injected }
+ if let injected = self.meetingASRPreparationOwnerForTesting { return injected }
#endif
if let existing = self.meetingASRPreparationOwner { return existing }
let owner = MeetingASRPreparationOwner(
@@ -3989,7 +4006,8 @@ final class ASRService: ObservableObject {
if let scope = self.activeMeetingASRScope, scope.lease == lease { return true }
if let owner = self.activeMeetingASRPreparationOwner,
owner.currentClaimToken?.lease == lease,
- owner.isClaimed || owner.isDraining {
+ owner.isClaimed || owner.isDraining
+ {
return true
}
return false
@@ -4642,7 +4660,9 @@ final class ASRService: ObservableObject {
throw NSError(
domain: "ASRService",
code: -1,
- userInfo: [NSLocalizedDescriptionKey: "Audio input format is invalid (\(inFormat.sampleRate)Hz, \(inFormat.channelCount)ch). The microphone may still be initializing after wake from sleep. Please try again in a few seconds."]
+ userInfo: [
+ NSLocalizedDescriptionKey: "Audio input format is invalid (\(inFormat.sampleRate)Hz, \(inFormat.channelCount)ch). The microphone may still be initializing after wake from sleep. Please try again in a few seconds.",
+ ]
)
}
@@ -4756,13 +4776,13 @@ final class ASRService: ObservableObject {
)
self.pendingAudioRouteRecovery = request
#if DEBUG
- AudioTopologyDiagnostics.record(
- .recoveryScheduled,
- owner: .asrDeviceList,
- queueRole: .mainControl,
- phase: .recovery,
- generation: request.generation
- )
+ AudioTopologyDiagnostics.record(
+ .recoveryScheduled,
+ owner: .asrDeviceList,
+ queueRole: .mainControl,
+ phase: .recovery,
+ generation: request.generation
+ )
#endif
self.audioLevelSubject.send(0.0)
@@ -4811,13 +4831,13 @@ final class ASRService: ObservableObject {
private func cancelAudioRouteRecoveryAndWait() async {
self.audioRouteRecoveryGeneration &+= 1
#if DEBUG
- AudioTopologyDiagnostics.record(
- .recoveryCancel,
- owner: .asrDeviceList,
- queueRole: .mainControl,
- phase: .recovery,
- generation: self.audioRouteRecoveryGeneration
- )
+ AudioTopologyDiagnostics.record(
+ .recoveryCancel,
+ owner: .asrDeviceList,
+ queueRole: .mainControl,
+ phase: .recovery,
+ generation: self.audioRouteRecoveryGeneration
+ )
#endif
self.pendingAudioRouteRecovery = nil
let task = self.audioRouteRecoveryTask
@@ -4863,13 +4883,13 @@ final class ASRService: ObservableObject {
self.isRecoveringAudioRoute = true
#if DEBUG
- AudioTopologyDiagnostics.record(
- .recoveryBegin,
- owner: .asrDeviceList,
- queueRole: .mainControl,
- phase: .recovery,
- generation: request.generation
- )
+ AudioTopologyDiagnostics.record(
+ .recoveryBegin,
+ owner: .asrDeviceList,
+ queueRole: .mainControl,
+ phase: .recovery,
+ generation: request.generation
+ )
#endif
defer {
self.finishAudioRouteRecovery(request)
@@ -4898,14 +4918,14 @@ final class ASRService: ObservableObject {
private func finishAudioRouteRecovery(_ completedRequest: AudioRouteRecoveryRequest) {
#if DEBUG
- AudioTopologyDiagnostics.record(
- .recoveryEnd,
- owner: .asrDeviceList,
- queueRole: .mainControl,
- phase: .recovery,
- status: Task.isCancelled ? -1 : noErr,
- generation: completedRequest.generation
- )
+ AudioTopologyDiagnostics.record(
+ .recoveryEnd,
+ owner: .asrDeviceList,
+ queueRole: .mainControl,
+ phase: .recovery,
+ status: Task.isCancelled ? -1 : noErr,
+ generation: completedRequest.generation
+ )
#endif
self.isRecoveringAudioRoute = false
@@ -5279,15 +5299,15 @@ final class ASRService: ObservableObject {
queue: nil
) { [weak self] notification in
#if DEBUG
- AudioTopologyDiagnostics.record(.callbackBegin, owner: .asrEngineConfiguration, queueRole: .callbackCurrent, phase: .engine)
- defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .asrEngineConfiguration, queueRole: .callbackCurrent, phase: .engine) }
+ AudioTopologyDiagnostics.record(.callbackBegin, owner: .asrEngineConfiguration, queueRole: .callbackCurrent, phase: .engine)
+ defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .asrEngineConfiguration, queueRole: .callbackCurrent, phase: .engine) }
#endif
guard let changedEngine = notification.object as? AVAudioEngine else { return }
let changedEngineIdentifier = ObjectIdentifier(changedEngine)
Task { @MainActor [weak self] in
#if DEBUG
- AudioTopologyDiagnostics.record(.mainHopBegin, owner: .asrEngineConfiguration, queueRole: .mainControl, phase: .engine)
- defer { AudioTopologyDiagnostics.record(.mainHopEnd, owner: .asrEngineConfiguration, queueRole: .mainControl, phase: .engine) }
+ AudioTopologyDiagnostics.record(.mainHopBegin, owner: .asrEngineConfiguration, queueRole: .mainControl, phase: .engine)
+ defer { AudioTopologyDiagnostics.record(.mainHopEnd, owner: .asrEngineConfiguration, queueRole: .mainControl, phase: .engine) }
#endif
self?.handleEngineConfigurationChanged(changedEngineIdentifier)
}
@@ -5353,8 +5373,26 @@ final class ASRService: ObservableObject {
{
let inputToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
#if DEBUG
- AudioTopologyDiagnostics.record(.callbackBegin, owner: .asrDefaultInput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDefaultInputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: generation)
- defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .asrDefaultInput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDefaultInputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: generation) }
+ AudioTopologyDiagnostics.record(
+ .callbackBegin,
+ owner: .asrDefaultInput,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDefaultInputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .callbackEnd,
+ owner: .asrDefaultInput,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDefaultInputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ ) }
#endif
// Defer to next runloop pass — CoreAudio may hold an internal lock during
// this callback, and our handler makes synchronous CoreAudio queries that
@@ -5371,14 +5409,39 @@ final class ASRService: ObservableObject {
return
}
#if DEBUG
- AudioTopologyDiagnostics.record(.mainHopBegin, owner: .asrDefaultInput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDefaultInputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainControl)
- defer { AudioTopologyDiagnostics.record(.mainHopEnd, owner: .asrDefaultInput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDefaultInputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainControl) }
+ AudioTopologyDiagnostics.record(
+ .mainHopBegin,
+ owner: .asrDefaultInput,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDefaultInputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainControl
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .mainHopEnd,
+ owner: .asrDefaultInput,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDefaultInputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainControl
+ ) }
#endif
self.handleDefaultInputChanged()
}
}
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .asrDefaultInput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: inputAddress.mSelector, scope: inputAddress.mScope, element: inputAddress.mElement, queueRole: .mainControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .listenerAddBegin,
+ owner: .asrDefaultInput,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: inputAddress.mSelector,
+ scope: inputAddress.mScope,
+ element: inputAddress.mElement,
+ queueRole: .mainControl,
+ phase: .listener
+ )
#endif
self.defaultInputListenerPendingGeneration = generation
Task { @MainActor [weak self] in
@@ -5388,7 +5451,18 @@ final class ASRService: ObservableObject {
token: inputToken
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .asrDefaultInput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: inputAddress.mSelector, scope: inputAddress.mScope, element: inputAddress.mElement, queueRole: .dedicatedControl, phase: .listener, status: inputStatus, generation: generation)
+ AudioTopologyDiagnostics.record(
+ .listenerAddEnd,
+ owner: .asrDefaultInput,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: inputAddress.mSelector,
+ scope: inputAddress.mScope,
+ element: inputAddress.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: inputStatus,
+ generation: generation
+ )
#endif
guard let self else {
if inputStatus == noErr {
@@ -5424,8 +5498,26 @@ final class ASRService: ObservableObject {
{
let outputToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
#if DEBUG
- AudioTopologyDiagnostics.record(.callbackBegin, owner: .asrDefaultOutput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDefaultOutputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: generation)
- defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .asrDefaultOutput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDefaultOutputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: generation) }
+ AudioTopologyDiagnostics.record(
+ .callbackBegin,
+ owner: .asrDefaultOutput,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDefaultOutputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .callbackEnd,
+ owner: .asrDefaultOutput,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDefaultOutputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ ) }
#endif
DispatchQueue.main.async {
guard let self,
@@ -5439,14 +5531,39 @@ final class ASRService: ObservableObject {
return
}
#if DEBUG
- AudioTopologyDiagnostics.record(.mainHopBegin, owner: .asrDefaultOutput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDefaultOutputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainControl)
- defer { AudioTopologyDiagnostics.record(.mainHopEnd, owner: .asrDefaultOutput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDefaultOutputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainControl) }
+ AudioTopologyDiagnostics.record(
+ .mainHopBegin,
+ owner: .asrDefaultOutput,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDefaultOutputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainControl
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .mainHopEnd,
+ owner: .asrDefaultOutput,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDefaultOutputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainControl
+ ) }
#endif
self.handleDefaultOutputChanged()
}
}
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .asrDefaultOutput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: outputAddress.mSelector, scope: outputAddress.mScope, element: outputAddress.mElement, queueRole: .mainControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .listenerAddBegin,
+ owner: .asrDefaultOutput,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: outputAddress.mSelector,
+ scope: outputAddress.mScope,
+ element: outputAddress.mElement,
+ queueRole: .mainControl,
+ phase: .listener
+ )
#endif
self.defaultOutputListenerPendingGeneration = generation
Task { @MainActor [weak self] in
@@ -5456,7 +5573,18 @@ final class ASRService: ObservableObject {
token: outputToken
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .asrDefaultOutput, objectID: AudioObjectID(kAudioObjectSystemObject), selector: outputAddress.mSelector, scope: outputAddress.mScope, element: outputAddress.mElement, queueRole: .dedicatedControl, phase: .listener, status: outputStatus, generation: generation)
+ AudioTopologyDiagnostics.record(
+ .listenerAddEnd,
+ owner: .asrDefaultOutput,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: outputAddress.mSelector,
+ scope: outputAddress.mScope,
+ element: outputAddress.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: outputStatus,
+ generation: generation
+ )
#endif
guard let self else {
if outputStatus == noErr {
@@ -5517,8 +5645,26 @@ final class ASRService: ObservableObject {
let generation = self.audioHardwareListenerLifecycleGeneration
let token: AudioObjectPropertyListenerBlock = { [weak self, weak controller] _, _ in
#if DEBUG
- AudioTopologyDiagnostics.record(.callbackBegin, owner: .asrDeviceList, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDevices, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: generation)
- defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .asrDeviceList, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDevices, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: generation) }
+ AudioTopologyDiagnostics.record(
+ .callbackBegin,
+ owner: .asrDeviceList,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDevices,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .callbackEnd,
+ owner: .asrDeviceList,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDevices,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ ) }
#endif
// Invalidate cached topology immediately without querying HAL from its callback.
controller?.noteHardwareTopologyChanged()
@@ -5542,14 +5688,39 @@ final class ASRService: ObservableObject {
break
}
#if DEBUG
- AudioTopologyDiagnostics.record(.mainHopBegin, owner: .asrDeviceList, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDevices, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainControl)
- defer { AudioTopologyDiagnostics.record(.mainHopEnd, owner: .asrDeviceList, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDevices, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainControl) }
+ AudioTopologyDiagnostics.record(
+ .mainHopBegin,
+ owner: .asrDeviceList,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDevices,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainControl
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .mainHopEnd,
+ owner: .asrDeviceList,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDevices,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainControl
+ ) }
#endif
self.handleDeviceListChanged()
}
}
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .asrDeviceList, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .listenerAddBegin,
+ owner: .asrDeviceList,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .mainControl,
+ phase: .listener
+ )
#endif
self.deviceListListenerPendingGeneration = generation
Task { @MainActor [weak self] in
@@ -5559,7 +5730,18 @@ final class ASRService: ObservableObject {
token: token
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .asrDeviceList, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status, generation: generation)
+ AudioTopologyDiagnostics.record(
+ .listenerAddEnd,
+ owner: .asrDeviceList,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status,
+ generation: generation
+ )
#endif
guard let self else {
if status == noErr {
@@ -5610,8 +5792,26 @@ final class ASRService: ObservableObject {
self.monitoredDeviceListenerPendingEpoch = epoch
let token: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
#if DEBUG
- AudioTopologyDiagnostics.record(.callbackBegin, owner: .asrMonitoredInput, objectID: deviceID, selector: kAudioDevicePropertyDeviceIsAlive, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: epoch)
- defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .asrMonitoredInput, objectID: deviceID, selector: kAudioDevicePropertyDeviceIsAlive, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: epoch) }
+ AudioTopologyDiagnostics.record(
+ .callbackBegin,
+ owner: .asrMonitoredInput,
+ objectID: deviceID,
+ selector: kAudioDevicePropertyDeviceIsAlive,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: epoch
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .callbackEnd,
+ owner: .asrMonitoredInput,
+ objectID: deviceID,
+ selector: kAudioDevicePropertyDeviceIsAlive,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: epoch
+ ) }
#endif
DispatchQueue.main.async {
guard let self else { return }
@@ -5633,8 +5833,24 @@ final class ASRService: ObservableObject {
break
}
#if DEBUG
- AudioTopologyDiagnostics.record(.mainHopBegin, owner: .asrMonitoredInput, objectID: deviceID, selector: kAudioDevicePropertyDeviceIsAlive, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainControl)
- defer { AudioTopologyDiagnostics.record(.mainHopEnd, owner: .asrMonitoredInput, objectID: deviceID, selector: kAudioDevicePropertyDeviceIsAlive, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainControl) }
+ AudioTopologyDiagnostics.record(
+ .mainHopBegin,
+ owner: .asrMonitoredInput,
+ objectID: deviceID,
+ selector: kAudioDevicePropertyDeviceIsAlive,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainControl
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .mainHopEnd,
+ owner: .asrMonitoredInput,
+ objectID: deviceID,
+ selector: kAudioDevicePropertyDeviceIsAlive,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainControl
+ ) }
#endif
self.handleDeviceAvailabilityChanged(
deviceID: deviceID,
@@ -5644,7 +5860,16 @@ final class ASRService: ObservableObject {
}
}
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .asrMonitoredInput, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .listenerAddBegin,
+ owner: .asrMonitoredInput,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .mainControl,
+ phase: .listener
+ )
#endif
Task { @MainActor [weak self] in
let status = await AudioTopologyListenerExecution.add(
@@ -5653,7 +5878,18 @@ final class ASRService: ObservableObject {
token: token
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .asrMonitoredInput, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status, generation: epoch)
+ AudioTopologyDiagnostics.record(
+ .listenerAddEnd,
+ owner: .asrMonitoredInput,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status,
+ generation: epoch
+ )
#endif
guard let self else {
if status == noErr {
@@ -5714,7 +5950,16 @@ final class ASRService: ObservableObject {
self.monitoredDeviceAvailabilityDirtyEpoch = nil
if let token {
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .asrMonitoredInput, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .mainControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveBegin,
+ owner: .asrMonitoredInput,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .mainControl,
+ phase: .listener
+ )
#endif
Task {
let status = await AudioTopologyListenerExecution.remove(
@@ -5723,7 +5968,17 @@ final class ASRService: ObservableObject {
token: token
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .asrMonitoredInput, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveEnd,
+ owner: .asrMonitoredInput,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status
+ )
#endif
}
}
@@ -5758,63 +6013,63 @@ final class ASRService: ObservableObject {
)
else { return }
- let (currentDevices, defaultInputUID) = snapshot
- let cachedUIDs = self.cachedDeviceUIDs
- let cachedDeviceIDsByUID = self.cachedInputDeviceIDsByUID
- let cachedLivenessByUID = self.cachedInputLivenessByUID
- let currentUIDs = Set(currentDevices.map(\.uid))
- let currentDeviceIDsByUID = Dictionary(
- currentDevices.map { ($0.uid, $0.id) },
- uniquingKeysWith: { current, _ in current }
- )
- let currentLivenessByUID = Dictionary(
- currentDevices.map { ($0.uid, $0.isAlive) },
- uniquingKeysWith: { current, _ in current }
- )
+ let (currentDevices, defaultInputUID) = snapshot
+ let cachedUIDs = self.cachedDeviceUIDs
+ let cachedDeviceIDsByUID = self.cachedInputDeviceIDsByUID
+ let cachedLivenessByUID = self.cachedInputLivenessByUID
+ let currentUIDs = Set(currentDevices.map(\.uid))
+ let currentDeviceIDsByUID = Dictionary(
+ currentDevices.map { ($0.uid, $0.id) },
+ uniquingKeysWith: { current, _ in current }
+ )
+ let currentLivenessByUID = Dictionary(
+ currentDevices.map { ($0.uid, $0.isAlive) },
+ uniquingKeysWith: { current, _ in current }
+ )
- DebugLogger.shared.debug("Current input devices: \(currentDevices.map { $0.name }.joined(separator: ", "))", source: "ASRService")
+ DebugLogger.shared.debug("Current input devices: \(currentDevices.map { $0.name }.joined(separator: ", "))", source: "ASRService")
- if currentUIDs != cachedUIDs ||
- currentDeviceIDsByUID != cachedDeviceIDsByUID ||
- currentLivenessByUID != cachedLivenessByUID
- {
- let microphonePreferenceCoordinator =
- AppServices.shared.microphonePreferenceCoordinator
- let migrationPending = microphonePreferenceCoordinator.needsMicrophonePriorityMigration
- let resolvedInput = microphonePreferenceCoordinator.reconcileMicrophoneSelection(
- availableInputs: currentDevices,
- defaultInputUID: defaultInputUID
+ if currentUIDs != cachedUIDs ||
+ currentDeviceIDsByUID != cachedDeviceIDsByUID ||
+ currentLivenessByUID != cachedLivenessByUID
+ {
+ let microphonePreferenceCoordinator =
+ AppServices.shared.microphonePreferenceCoordinator
+ let migrationPending = microphonePreferenceCoordinator.needsMicrophonePriorityMigration
+ let resolvedInput = microphonePreferenceCoordinator.reconcileMicrophoneSelection(
+ availableInputs: currentDevices,
+ defaultInputUID: defaultInputUID
+ )
+ let priorityUIDs = SettingsStore.shared.microphonePriority.map(\.uid)
+ let livenessRequiresRecovery =
+ (
+ self.isRunning &&
+ resolvedInput?.uid != microphonePreferenceCoordinator.confirmedActiveInputUID
+ ) ||
+ (
+ self.hasPreparedAudioCapture &&
+ resolvedInput?.id != self.directAudioLifecycleController.snapshot.deviceID
+ )
+ let shouldReconcileInputSelection = AudioCaptureIdlePolicy.shouldReconcileInputSelection(
+ priorityInputUIDs: priorityUIDs,
+ migrationPending: migrationPending,
+ previousInputUIDs: cachedUIDs,
+ currentInputUIDs: currentUIDs
+ ) || AudioCaptureIdlePolicy.didResolvedPriorityInputIdentityChange(
+ priorityInputUIDs: priorityUIDs,
+ previousInputDeviceIDsByUID: cachedDeviceIDsByUID,
+ currentInputDeviceIDsByUID: currentDeviceIDsByUID
+ ) || livenessRequiresRecovery
+ if shouldReconcileInputSelection {
+ self.scheduleAudioRouteRecovery(
+ reason: "app microphone availability changed",
+ requiresIdlePrewarm: true,
+ reconcilesInputSelection: true
)
- let priorityUIDs = SettingsStore.shared.microphonePriority.map(\.uid)
- let livenessRequiresRecovery =
- (
- self.isRunning &&
- resolvedInput?.uid != microphonePreferenceCoordinator.confirmedActiveInputUID
- ) ||
- (
- self.hasPreparedAudioCapture &&
- resolvedInput?.id != self.directAudioLifecycleController.snapshot.deviceID
- )
- let shouldReconcileInputSelection = AudioCaptureIdlePolicy.shouldReconcileInputSelection(
- priorityInputUIDs: priorityUIDs,
- migrationPending: migrationPending,
- previousInputUIDs: cachedUIDs,
- currentInputUIDs: currentUIDs
- ) || AudioCaptureIdlePolicy.didResolvedPriorityInputIdentityChange(
- priorityInputUIDs: priorityUIDs,
- previousInputDeviceIDsByUID: cachedDeviceIDsByUID,
- currentInputDeviceIDsByUID: currentDeviceIDsByUID
- ) || livenessRequiresRecovery
- if shouldReconcileInputSelection {
- self.scheduleAudioRouteRecovery(
- reason: "app microphone availability changed",
- requiresIdlePrewarm: true,
- reconcilesInputSelection: true
- )
- }
}
+ }
- self.cacheCurrentDeviceList(currentDevices)
+ self.cacheCurrentDeviceList(currentDevices)
}
}
@@ -6752,7 +7007,10 @@ final class ASRService: ObservableObject {
schedulingSessionID: self.streamingSchedulingSessionID
) {
DebugLogger.shared.error("❌ Streaming failed: \(error)", source: "ASRService")
- self.benchmarkLog("chunk_fail index=\(chunkIndex) elapsedMs=\(self.elapsedMilliseconds(since: startedAt)) samples=\(currentSampleCount) inputSamples=\(chunk.count) error=\(error.localizedDescription)")
+ self
+ .benchmarkLog(
+ "chunk_fail index=\(chunkIndex) elapsedMs=\(self.elapsedMilliseconds(since: startedAt)) samples=\(currentSampleCount) inputSamples=\(chunk.count) error=\(error.localizedDescription)"
+ )
self.skipNextChunk = true
} catch {
self.benchmarkLog(
diff --git a/Sources/Fluid/Services/AudioDeviceService.swift b/Sources/Fluid/Services/AudioDeviceService.swift
index 9fae3ed9..57538b89 100644
--- a/Sources/Fluid/Services/AudioDeviceService.swift
+++ b/Sources/Fluid/Services/AudioDeviceService.swift
@@ -283,16 +283,16 @@ nonisolated enum AudioDevice {
var value: UInt32 = 1
var dataSize = UInt32(MemoryLayout<UInt32>.size)
#if DEBUG
- AudioTopologyDiagnostics.record(
- .halQueryBegin,
- owner: diagnosticsOwner.traceOwner,
- objectID: deviceID,
- selector: address.mSelector,
- scope: address.mScope,
- element: address.mElement,
- queueRole: .dedicatedControl,
- phase: .listener
- )
+ AudioTopologyDiagnostics.record(
+ .halQueryBegin,
+ owner: diagnosticsOwner.traceOwner,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener
+ )
#endif
let status = AudioObjectGetPropertyData(
deviceID,
@@ -303,17 +303,17 @@ nonisolated enum AudioDevice {
&value
)
#if DEBUG
- AudioTopologyDiagnostics.record(
- .halQueryEnd,
- owner: diagnosticsOwner.traceOwner,
- objectID: deviceID,
- selector: address.mSelector,
- scope: address.mScope,
- element: address.mElement,
- queueRole: .dedicatedControl,
- phase: .listener,
- status: status
- )
+ AudioTopologyDiagnostics.record(
+ .halQueryEnd,
+ owner: diagnosticsOwner.traceOwner,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status
+ )
#endif
return status != noErr || value != 0
}
@@ -411,7 +411,7 @@ nonisolated enum AudioDevice {
}
/// 'hdpn' — kAudioDevicePropertyDataSource's headphones value, output scope.
- private static let headphonesDataSource: UInt32 = 0x6864_706E
+ private static let headphonesDataSource: UInt32 = 0x6864706e
static func outputDataSourceIsHeadphones(_ deviceID: AudioObjectID) -> Bool {
var address = AudioObjectPropertyAddress(
@@ -503,23 +503,23 @@ nonisolated enum AggregateInputLivenessLedgerPolicy {
}
#if DEBUG
- /// Prior Phase-0 diagnostic switch, broader than the production aggregate exclusion above
- /// (it also drops virtual and unknown transports). Kept for future isolation experiments;
- /// it is not part of the shipped policy and stays opt-in behind an environment flag. It
- /// deliberately classifies from the already captured off-main device snapshot, so the
- /// experiment does not add a Core Audio query during reconciliation.
- nonisolated enum InputLivenessLedgerIsolationPolicy {
- static func permitsListenerForTransientIsolation(transportType: UInt32) -> Bool {
- switch transportType {
- case kAudioDeviceTransportTypeAggregate,
- kAudioDeviceTransportTypeVirtual,
- kAudioDeviceTransportTypeUnknown:
- false
- default:
- true
- }
+/// Prior Phase-0 diagnostic switch, broader than the production aggregate exclusion above
+/// (it also drops virtual and unknown transports). Kept for future isolation experiments;
+/// it is not part of the shipped policy and stays opt-in behind an environment flag. It
+/// deliberately classifies from the already captured off-main device snapshot, so the
+/// experiment does not add a Core Audio query during reconciliation.
+nonisolated enum InputLivenessLedgerIsolationPolicy {
+ static func permitsListenerForTransientIsolation(transportType: UInt32) -> Bool {
+ switch transportType {
+ case kAudioDeviceTransportTypeAggregate,
+ kAudioDeviceTransportTypeVirtual,
+ kAudioDeviceTransportTypeUnknown:
+ false
+ default:
+ true
}
}
+}
#endif
/// Process-wide execution boundary for app-owned Core Audio property listeners.
@@ -610,6 +610,9 @@ nonisolated enum AudioInputAvailabilityListenerPolicy {
registeredUID != desiredUID
}
+ // Keep the explicit existing capture inputs together.
+
+ // swiftlint:disable:next function_parameter_count
static func completionCanInstall(
statusSucceeded: Bool,
ownsPendingMarker: Bool,
@@ -628,6 +631,9 @@ nonisolated enum AudioInputAvailabilityListenerPolicy {
&& reconciliationIsCurrent
}
+ // Keep the explicit existing capture inputs together.
+
+ // swiftlint:disable:next function_parameter_count
static func shouldRetryStaleCompletion(
ownsPendingMarker: Bool,
installed: Bool,
@@ -763,7 +769,9 @@ final class AudioHardwareObserver: ObservableObject {
await registrationTask.value
}
let tasks = Array(self.trackedTopologyTasks.values)
- for task in tasks { await task.value }
+ for task in tasks {
+ await task.value
+ }
// Drains any exact-token cleanup queued by a completion before it returned.
await AudioTopologyListenerExecution.perform {}
await Task.yield()
@@ -846,17 +854,26 @@ final class AudioHardwareObserver: ObservableObject {
let devicesToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
#if DEBUG
- AudioTopologyDiagnostics.record(
- .callbackBegin,
- owner: .audioHardwareObserver,
- objectID: sys,
- selector: kAudioHardwarePropertyDevices,
- scope: kAudioObjectPropertyScopeGlobal,
- element: kAudioObjectPropertyElementMain,
- queueRole: .callbackCurrent,
- generation: generation
- )
- defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .audioHardwareObserver, objectID: sys, selector: kAudioHardwarePropertyDevices, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: generation) }
+ AudioTopologyDiagnostics.record(
+ .callbackBegin,
+ owner: .audioHardwareObserver,
+ objectID: sys,
+ selector: kAudioHardwarePropertyDevices,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .callbackEnd,
+ owner: .audioHardwareObserver,
+ objectID: sys,
+ selector: kAudioHardwarePropertyDevices,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ ) }
#endif
DispatchQueue.main.async { [weak self] in
guard let self, self.installed, self.listenerLifecycleGeneration == generation else { return }
@@ -866,17 +883,26 @@ final class AudioHardwareObserver: ObservableObject {
}
let defaultInToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
#if DEBUG
- AudioTopologyDiagnostics.record(
- .callbackBegin,
- owner: .audioHardwareObserver,
- objectID: sys,
- selector: kAudioHardwarePropertyDefaultInputDevice,
- scope: kAudioObjectPropertyScopeGlobal,
- element: kAudioObjectPropertyElementMain,
- queueRole: .callbackCurrent,
- generation: generation
- )
- defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .audioHardwareObserver, objectID: sys, selector: kAudioHardwarePropertyDefaultInputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: generation) }
+ AudioTopologyDiagnostics.record(
+ .callbackBegin,
+ owner: .audioHardwareObserver,
+ objectID: sys,
+ selector: kAudioHardwarePropertyDefaultInputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .callbackEnd,
+ owner: .audioHardwareObserver,
+ objectID: sys,
+ selector: kAudioHardwarePropertyDefaultInputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ ) }
#endif
DispatchQueue.main.async { [weak self] in
guard let self, self.installed, self.listenerLifecycleGeneration == generation else { return }
@@ -885,17 +911,26 @@ final class AudioHardwareObserver: ObservableObject {
}
let defaultOutToken: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
#if DEBUG
- AudioTopologyDiagnostics.record(
- .callbackBegin,
- owner: .audioHardwareObserver,
- objectID: sys,
- selector: kAudioHardwarePropertyDefaultOutputDevice,
- scope: kAudioObjectPropertyScopeGlobal,
- element: kAudioObjectPropertyElementMain,
- queueRole: .callbackCurrent,
- generation: generation
- )
- defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .audioHardwareObserver, objectID: sys, selector: kAudioHardwarePropertyDefaultOutputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: generation) }
+ AudioTopologyDiagnostics.record(
+ .callbackBegin,
+ owner: .audioHardwareObserver,
+ objectID: sys,
+ selector: kAudioHardwarePropertyDefaultOutputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .callbackEnd,
+ owner: .audioHardwareObserver,
+ objectID: sys,
+ selector: kAudioHardwarePropertyDefaultOutputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ ) }
#endif
DispatchQueue.main.async { [weak self] in
guard let self, self.installed, self.listenerLifecycleGeneration == generation else { return }
@@ -905,11 +940,32 @@ final class AudioHardwareObserver: ObservableObject {
self.registrationTask = Task { @MainActor [weak self] in
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .audioHardwareObserver, objectID: sys, selector: addrDevices.mSelector, scope: addrDevices.mScope, element: addrDevices.mElement, queueRole: .dedicatedControl, phase: .listener, generation: generation)
+ AudioTopologyDiagnostics.record(
+ .listenerAddBegin,
+ owner: .audioHardwareObserver,
+ objectID: sys,
+ selector: addrDevices.mSelector,
+ scope: addrDevices.mScope,
+ element: addrDevices.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ generation: generation
+ )
#endif
let devicesStatus = await AudioTopologyListenerExecution.add(objectID: sys, address: addrDevices, token: devicesToken)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .audioHardwareObserver, objectID: sys, selector: addrDevices.mSelector, scope: addrDevices.mScope, element: addrDevices.mElement, queueRole: .dedicatedControl, phase: .listener, status: devicesStatus, generation: generation)
+ AudioTopologyDiagnostics.record(
+ .listenerAddEnd,
+ owner: .audioHardwareObserver,
+ objectID: sys,
+ selector: addrDevices.mSelector,
+ scope: addrDevices.mScope,
+ element: addrDevices.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: devicesStatus,
+ generation: generation
+ )
#endif
let defaultInStatus = Task.isCancelled
? kAudioHardwareUnspecifiedError
@@ -1002,11 +1058,32 @@ final class AudioHardwareObserver: ObservableObject {
) async {
for (address, token, status) in registrations where status == noErr {
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .audioHardwareObserver, objectID: sys, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, generation: generation)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveBegin,
+ owner: .audioHardwareObserver,
+ objectID: sys,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ generation: generation
+ )
#endif
let removalStatus = await AudioTopologyListenerExecution.remove(objectID: sys, address: address, token: token)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .audioHardwareObserver, objectID: sys, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: removalStatus, generation: generation)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveEnd,
+ owner: .audioHardwareObserver,
+ objectID: sys,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: removalStatus,
+ generation: generation
+ )
#endif
}
}
@@ -1020,26 +1097,26 @@ final class AudioHardwareObserver: ObservableObject {
let generation = self.inputAvailabilityRefreshGeneration
self.launchTrackedTopologyTask { [weak self] in
#if DEBUG
- AudioTopologyDiagnostics.record(
- .enumerationBegin,
- owner: .audioHardwareObserver,
- queueRole: .dedicatedControl,
- phase: .listener,
- generation: generation
- )
+ AudioTopologyDiagnostics.record(
+ .enumerationBegin,
+ owner: .audioHardwareObserver,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ generation: generation
+ )
#endif
let devices = await AudioTopologyListenerExecution.perform {
AudioDevice.listInputDevicesRefreshingLiveness()
}
#if DEBUG
- AudioTopologyDiagnostics.record(
- .enumerationEnd,
- owner: .audioHardwareObserver,
- queueRole: .dedicatedControl,
- phase: .listener,
- status: noErr,
- generation: generation
- )
+ AudioTopologyDiagnostics.record(
+ .enumerationEnd,
+ owner: .audioHardwareObserver,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: noErr,
+ generation: generation
+ )
#endif
guard let self,
self.topologyReconciliationSuspended == false,
@@ -1061,40 +1138,40 @@ final class AudioHardwareObserver: ObservableObject {
liveness: devices.map(\.isAlive)
)
#if DEBUG
- // Phase-0 isolation for the rebase-introduced all-input liveness ledger. The flag is
- // deliberately scoped to this observer: default-device monitoring, ASR's existing
- // selected-device listener, and dictation capture remain active.
- if ProcessInfo.processInfo.environment["FLUIDVOICE_OMIT_INPUT_LIVENESS_LEDGER_ISOLATION"] == "1" {
- AudioTopologyDiagnostics.record(
- .isolationActive,
- owner: .audioHardwareObserver,
- queueRole: .mainControl,
- phase: .listener,
- generation: self.inputAvailabilityRefreshGeneration
- )
- self.removeInputAvailabilityListeners()
- return
- }
+ // Phase-0 isolation for the rebase-introduced all-input liveness ledger. The flag is
+ // deliberately scoped to this observer: default-device monitoring, ASR's existing
+ // selected-device listener, and dictation capture remain active.
+ if ProcessInfo.processInfo.environment["FLUIDVOICE_OMIT_INPUT_LIVENESS_LEDGER_ISOLATION"] == "1" {
+ AudioTopologyDiagnostics.record(
+ .isolationActive,
+ owner: .audioHardwareObserver,
+ queueRole: .mainControl,
+ phase: .listener,
+ generation: self.inputAvailabilityRefreshGeneration
+ )
+ self.removeInputAvailabilityListeners()
+ return
+ }
#endif
#if DEBUG
+ AudioTopologyDiagnostics.record(
+ .replaceBegin,
+ owner: .audioHardwareObserver,
+ queueRole: .mainControl,
+ phase: .listener,
+ generation: self.inputAvailabilityRefreshGeneration
+ )
+ for device in devices {
AudioTopologyDiagnostics.record(
- .replaceBegin,
+ .topologySnapshot,
owner: .audioHardwareObserver,
+ objectID: device.id,
queueRole: .mainControl,
phase: .listener,
+ transport: AudioTopologyDiagnostics.transportClassification(device.transportType),
generation: self.inputAvailabilityRefreshGeneration
)
- for device in devices {
- AudioTopologyDiagnostics.record(
- .topologySnapshot,
- owner: .audioHardwareObserver,
- objectID: device.id,
- queueRole: .mainControl,
- phase: .listener,
- transport: AudioTopologyDiagnostics.transportClassification(device.transportType),
- generation: self.inputAvailabilityRefreshGeneration
- )
- }
+ }
#endif
// Production policy: never register this observer's broad per-input DeviceIsAlive
// ledger for aggregate-transport inputs. See AggregateInputLivenessLedgerPolicy for the
@@ -1104,9 +1181,35 @@ final class AudioHardwareObserver: ObservableObject {
transportType: $0.transportType
)
#if DEBUG
+ if permitted == false {
+ AudioTopologyDiagnostics.record(
+ .policyExcluded,
+ owner: .audioHardwareObserver,
+ objectID: $0.id,
+ queueRole: .mainControl,
+ phase: .listener,
+ transport: AudioTopologyDiagnostics.transportClassification($0.transportType),
+ generation: self.inputAvailabilityRefreshGeneration
+ )
+ }
+ #endif
+ return permitted
+ }
+
+ #if DEBUG
+ // Opt-in diagnostic isolation on top of the production policy above, for future
+ // experiments only; see InputLivenessLedgerIsolationPolicy.
+ let excludesTransientInputs = ProcessInfo.processInfo.environment[
+ "FLUIDVOICE_EXCLUDE_TRANSIENT_INPUT_LIVENESS_ISOLATION"
+ ] == "1"
+ let listenerDevices = excludesTransientInputs
+ ? productionScopedDevices.filter {
+ let permitted = InputLivenessLedgerIsolationPolicy.permitsListenerForTransientIsolation(
+ transportType: $0.transportType
+ )
if permitted == false {
AudioTopologyDiagnostics.record(
- .policyExcluded,
+ .isolationActive,
owner: .audioHardwareObserver,
objectID: $0.id,
queueRole: .mainControl,
@@ -1115,37 +1218,11 @@ final class AudioHardwareObserver: ObservableObject {
generation: self.inputAvailabilityRefreshGeneration
)
}
- #endif
- return permitted
- }
-
- #if DEBUG
- // Opt-in diagnostic isolation on top of the production policy above, for future
- // experiments only; see InputLivenessLedgerIsolationPolicy.
- let excludesTransientInputs = ProcessInfo.processInfo.environment[
- "FLUIDVOICE_EXCLUDE_TRANSIENT_INPUT_LIVENESS_ISOLATION"
- ] == "1"
- let listenerDevices = excludesTransientInputs
- ? productionScopedDevices.filter {
- let permitted = InputLivenessLedgerIsolationPolicy.permitsListenerForTransientIsolation(
- transportType: $0.transportType
- )
- if permitted == false {
- AudioTopologyDiagnostics.record(
- .isolationActive,
- owner: .audioHardwareObserver,
- objectID: $0.id,
- queueRole: .mainControl,
- phase: .listener,
- transport: AudioTopologyDiagnostics.transportClassification($0.transportType),
- generation: self.inputAvailabilityRefreshGeneration
- )
- }
- return permitted
- }
- : productionScopedDevices
+ return permitted
+ }
+ : productionScopedDevices
#else
- let listenerDevices = productionScopedDevices
+ let listenerDevices = productionScopedDevices
#endif
let desiredUIDs = Dictionary(
listenerDevices.map { ($0.id, $0.uid) },
@@ -1161,7 +1238,17 @@ final class AudioHardwareObserver: ObservableObject {
let address = Self.inputAvailabilityAddress
self.inputAvailabilityRegistrations.removeValue(forKey: deviceID)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .audioHardwareObserver, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, generation: self.inputAvailabilityRefreshGeneration)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveBegin,
+ owner: .audioHardwareObserver,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ generation: self.inputAvailabilityRefreshGeneration
+ )
#endif
let generation = self.inputAvailabilityRefreshGeneration
self.launchTrackedTopologyTask {
@@ -1171,7 +1258,18 @@ final class AudioHardwareObserver: ObservableObject {
token: registration.token
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .audioHardwareObserver, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status, generation: generation)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveEnd,
+ owner: .audioHardwareObserver,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status,
+ generation: generation
+ )
#endif
}
}
@@ -1199,17 +1297,26 @@ final class AudioHardwareObserver: ObservableObject {
let pending = PendingInputAvailabilityRegistration(identity: identity)
let token: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
#if DEBUG
- AudioTopologyDiagnostics.record(
- .callbackBegin,
- owner: .audioHardwareObserver,
- objectID: deviceID,
- selector: kAudioDevicePropertyDeviceIsAlive,
- scope: kAudioObjectPropertyScopeGlobal,
- element: kAudioObjectPropertyElementMain,
- queueRole: .callbackCurrent,
- generation: reconciliationGeneration
- )
- defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .audioHardwareObserver, objectID: deviceID, selector: kAudioDevicePropertyDeviceIsAlive, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: reconciliationGeneration) }
+ AudioTopologyDiagnostics.record(
+ .callbackBegin,
+ owner: .audioHardwareObserver,
+ objectID: deviceID,
+ selector: kAudioDevicePropertyDeviceIsAlive,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: reconciliationGeneration
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .callbackEnd,
+ owner: .audioHardwareObserver,
+ objectID: deviceID,
+ selector: kAudioDevicePropertyDeviceIsAlive,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: reconciliationGeneration
+ ) }
#endif
// First reject callbacks from replaced registrations on main, then query Core Audio
// off-main. Validate the same registration again before publishing the result.
@@ -1231,8 +1338,26 @@ final class AudioHardwareObserver: ObservableObject {
AudioDevice.listInputDevicesRefreshingLiveness()
}
#if DEBUG
- AudioTopologyDiagnostics.record(.mainHopBegin, owner: .audioHardwareObserver, objectID: deviceID, selector: kAudioDevicePropertyDeviceIsAlive, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainControl, generation: reconciliationGeneration)
- defer { AudioTopologyDiagnostics.record(.mainHopEnd, owner: .audioHardwareObserver, objectID: deviceID, selector: kAudioDevicePropertyDeviceIsAlive, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainControl, generation: reconciliationGeneration) }
+ AudioTopologyDiagnostics.record(
+ .mainHopBegin,
+ owner: .audioHardwareObserver,
+ objectID: deviceID,
+ selector: kAudioDevicePropertyDeviceIsAlive,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainControl,
+ generation: reconciliationGeneration
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .mainHopEnd,
+ owner: .audioHardwareObserver,
+ objectID: deviceID,
+ selector: kAudioDevicePropertyDeviceIsAlive,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainControl,
+ generation: reconciliationGeneration
+ ) }
#endif
guard let self,
self.topologyReconciliationSuspended == false,
@@ -1260,12 +1385,35 @@ final class AudioHardwareObserver: ObservableObject {
}
self.pendingInputAvailabilityRegistrations[deviceID] = pending
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .audioHardwareObserver, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, transport: AudioTopologyDiagnostics.transportClassification(device.transportType), generation: reconciliationGeneration)
+ AudioTopologyDiagnostics.record(
+ .listenerAddBegin,
+ owner: .audioHardwareObserver,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ transport: AudioTopologyDiagnostics.transportClassification(device.transportType),
+ generation: reconciliationGeneration
+ )
#endif
self.launchTrackedTopologyTask { [weak self] in
let status = await AudioTopologyListenerExecution.add(objectID: deviceID, address: address, token: token)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .audioHardwareObserver, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, transport: AudioTopologyDiagnostics.transportClassification(device.transportType), status: status, generation: reconciliationGeneration)
+ AudioTopologyDiagnostics.record(
+ .listenerAddEnd,
+ owner: .audioHardwareObserver,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ transport: AudioTopologyDiagnostics.transportClassification(device.transportType),
+ status: status,
+ generation: reconciliationGeneration
+ )
#endif
guard let self else {
if status == noErr {
@@ -1323,14 +1471,14 @@ final class AudioHardwareObserver: ObservableObject {
}
}
#if DEBUG
- AudioTopologyDiagnostics.record(
- .replaceEnd,
- owner: .audioHardwareObserver,
- queueRole: .mainControl,
- phase: .listener,
- status: noErr,
- generation: self.inputAvailabilityRefreshGeneration
- )
+ AudioTopologyDiagnostics.record(
+ .replaceEnd,
+ owner: .audioHardwareObserver,
+ queueRole: .mainControl,
+ phase: .listener,
+ status: noErr,
+ generation: self.inputAvailabilityRefreshGeneration
+ )
#endif
}
@@ -1343,7 +1491,17 @@ final class AudioHardwareObserver: ObservableObject {
for (deviceID, registration) in registrations {
let address = Self.inputAvailabilityAddress
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .audioHardwareObserver, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, generation: generation)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveBegin,
+ owner: .audioHardwareObserver,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ generation: generation
+ )
#endif
self.launchTrackedTopologyTask {
let status = await AudioTopologyListenerExecution.remove(
@@ -1352,7 +1510,18 @@ final class AudioHardwareObserver: ObservableObject {
token: registration.token
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .audioHardwareObserver, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status, generation: generation)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveEnd,
+ owner: .audioHardwareObserver,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status,
+ generation: generation
+ )
#endif
}
}
diff --git a/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift b/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift
index 01f29833..2d11ceef 100644
--- a/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift
+++ b/Sources/Fluid/Services/AutomaticDictionaryCorrectionTracker.swift
@@ -527,7 +527,8 @@ final class AutomaticDictionaryCorrectionTracker {
self.evidencePreparationTask = Task { @MainActor [weak self, context] in
let observedText = candidate.heardText
let evidence = await Task.detached(priority: .utility) {
- guard DictionaryMatcherExperiment.sharedFeaturesEnabled, pronunciationGeneration == DictionaryMatcherExperiment.generation, let context else { return DictionaryLearningAudioEvidence?.none }
+ guard DictionaryMatcherExperiment.sharedFeaturesEnabled, pronunciationGeneration == DictionaryMatcherExperiment.generation,
+ let context else { return DictionaryLearningAudioEvidence?.none }
return try? DictionaryLearningAlignmentResolver.resolve(
recording: context.recording,
deliveredTextBeforeEdit: context.deliveredTextBeforeEdit,
diff --git a/Sources/Fluid/Services/DictionaryTrainingEndpointMonitor.swift b/Sources/Fluid/Services/DictionaryTrainingEndpointMonitor.swift
index ee43aa1e..59c9a993 100644
--- a/Sources/Fluid/Services/DictionaryTrainingEndpointMonitor.swift
+++ b/Sources/Fluid/Services/DictionaryTrainingEndpointMonitor.swift
@@ -70,7 +70,8 @@ final class DictionaryTrainingEndpointMonitor {
var cursor = DictionaryTrainingAudioCursor(generation: asr.dictionaryTrainingAudioGeneration)
while !Task.isCancelled {
- guard DictionaryMatcherExperiment.sharedFeaturesEnabled, generation == DictionaryMatcherExperiment.generation, asr.isRunning, asr.dictionaryCaptureToken == captureToken else { return }
+ guard DictionaryMatcherExperiment.sharedFeaturesEnabled, generation == DictionaryMatcherExperiment.generation, asr.isRunning,
+ asr.dictionaryCaptureToken == captureToken else { return }
cursor.synchronize(generation: asr.dictionaryTrainingAudioGeneration)
let chunk = asr.dictionaryTrainingAudioChunk(
diff --git a/Sources/Fluid/Services/DirectCoreAudioInput.swift b/Sources/Fluid/Services/DirectCoreAudioInput.swift
index eafaf943..c1d49edd 100644
--- a/Sources/Fluid/Services/DirectCoreAudioInput.swift
+++ b/Sources/Fluid/Services/DirectCoreAudioInput.swift
@@ -1503,17 +1503,26 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
let block = Self.makeDevicePropertyListener(objectID: objectID) { [weak self, weak input] objectID in
#if DEBUG
- AudioTopologyDiagnostics.record(
- .callbackBegin,
- owner: .directCoreAudio,
- objectID: objectID,
- selector: selector,
- scope: scope,
- element: kAudioObjectPropertyElementMain,
- queueRole: .dedicatedDelivery,
- generation: generation
- )
- defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .directCoreAudio, objectID: objectID, selector: selector, scope: scope, element: kAudioObjectPropertyElementMain, queueRole: .dedicatedDelivery, generation: generation) }
+ AudioTopologyDiagnostics.record(
+ .callbackBegin,
+ owner: .directCoreAudio,
+ objectID: objectID,
+ selector: selector,
+ scope: scope,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .dedicatedDelivery,
+ generation: generation
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .callbackEnd,
+ owner: .directCoreAudio,
+ objectID: objectID,
+ selector: selector,
+ scope: scope,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .dedicatedDelivery,
+ generation: generation
+ ) }
#endif
let deviceIsAlive =
name == "device_is_alive"
@@ -1539,7 +1548,17 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
)
}
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .directCoreAudio, objectID: objectID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, generation: generation)
+ AudioTopologyDiagnostics.record(
+ .listenerAddBegin,
+ owner: .directCoreAudio,
+ objectID: objectID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ generation: generation
+ )
#endif
let status = AudioObjectAddPropertyListenerBlock(
objectID,
@@ -1548,7 +1567,18 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
block
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .directCoreAudio, objectID: objectID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status, generation: generation)
+ AudioTopologyDiagnostics.record(
+ .listenerAddEnd,
+ owner: .directCoreAudio,
+ objectID: objectID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status,
+ generation: generation
+ )
#endif
guard status == noErr else {
if policy != .optional {
@@ -1690,7 +1720,16 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
var isAlive: UInt32 = 0
var size = UInt32(MemoryLayout<UInt32>.size)
#if DEBUG
- AudioTopologyDiagnostics.record(.halQueryBegin, owner: .directCoreAudio, objectID: objectID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedDelivery, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .halQueryBegin,
+ owner: .directCoreAudio,
+ objectID: objectID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedDelivery,
+ phase: .listener
+ )
#endif
let status = AudioObjectGetPropertyData(
objectID,
@@ -1701,7 +1740,17 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
&isAlive
)
#if DEBUG
- AudioTopologyDiagnostics.record(.halQueryEnd, owner: .directCoreAudio, objectID: objectID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedDelivery, phase: .listener, status: status)
+ AudioTopologyDiagnostics.record(
+ .halQueryEnd,
+ owner: .directCoreAudio,
+ objectID: objectID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedDelivery,
+ phase: .listener,
+ status: status
+ )
#endif
// An object removed from HAL is gone; other unreadable results are
// unknown and must not authorize replacement after failed teardown.
@@ -1767,7 +1816,16 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
for registration in registrations {
var address = registration.address
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .directCoreAudio, objectID: registration.objectID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveBegin,
+ owner: .directCoreAudio,
+ objectID: registration.objectID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener
+ )
#endif
let status = AudioObjectRemovePropertyListenerBlock(
registration.objectID,
@@ -1776,7 +1834,17 @@ final nonisolated class DirectCoreAudioLifecycleController: @unchecked Sendable
registration.block
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .directCoreAudio, objectID: registration.objectID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveEnd,
+ owner: .directCoreAudio,
+ objectID: registration.objectID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status
+ )
#endif
if status != noErr, status != kAudioHardwareBadObjectError {
Self.log(
diff --git a/Sources/Fluid/Services/GlobalHotkeyManager.swift b/Sources/Fluid/Services/GlobalHotkeyManager.swift
index 1ccd4145..75000fb5 100644
--- a/Sources/Fluid/Services/GlobalHotkeyManager.swift
+++ b/Sources/Fluid/Services/GlobalHotkeyManager.swift
@@ -2542,6 +2542,9 @@ private extension GlobalHotkeyManager {
func traceStopUnlocked(since startedAt: TimeInterval) {
self.isProcessingStop = false
- DebugLogger.shared.debug("CLOSE_DETAIL shortcutUnlocked uptime=\(ProcessInfo.processInfo.systemUptime) heldMs=\((ProcessInfo.processInfo.systemUptime - startedAt) * 1000)", source: "StopTiming")
+ DebugLogger.shared.debug(
+ "CLOSE_DETAIL shortcutUnlocked uptime=\(ProcessInfo.processInfo.systemUptime) heldMs=\((ProcessInfo.processInfo.systemUptime - startedAt) * 1000)",
+ source: "StopTiming"
+ )
}
}
diff --git a/Sources/Fluid/Services/LLMClient.swift b/Sources/Fluid/Services/LLMClient.swift
index e2f9ee44..d559a36e 100644
--- a/Sources/Fluid/Services/LLMClient.swift
+++ b/Sources/Fluid/Services/LLMClient.swift
@@ -834,7 +834,10 @@ final nonisolated class LLMClient: @unchecked Sendable {
DebugLogger.shared.debug("LLMClient: Parsed tool call: \(name)", source: "LLMClient")
}
- DebugLogger.shared.debug("LLMClient: Returning response. Content length: \(contentText.count), Has thinking: \(thinkingText.isEmpty ? "No" : "Yes (\(thinkingText.count) chars)")", source: "LLMClient")
+ DebugLogger.shared.debug(
+ "LLMClient: Returning response. Content length: \(contentText.count), Has thinking: \(thinkingText.isEmpty ? "No" : "Yes (\(thinkingText.count) chars)")",
+ source: "LLMClient"
+ )
let parsed = Response(
thinking: thinkingText.isEmpty ? nil : thinkingText,
diff --git a/Sources/Fluid/Services/Meeting/AEC/MeetingAECModels.swift b/Sources/Fluid/Services/Meeting/AEC/MeetingAECModels.swift
index c320c9f9..173617c7 100644
--- a/Sources/Fluid/Services/Meeting/AEC/MeetingAECModels.swift
+++ b/Sources/Fluid/Services/Meeting/AEC/MeetingAECModels.swift
@@ -142,7 +142,7 @@ nonisolated enum MeetingAECConstants {
static let attestationFrames = 200
static let maximumBlocksPerInput = 64
static let maximumSamplesPerInput = 24_000
- static let maximumCaptureWaitSamples = 4_800
+ static let maximumCaptureWaitSamples = 4800
static let maximumClockResidualSamples: Int64 = 1
static let provenance = MeetingAECProvenance(
diff --git a/Sources/Fluid/Services/Meeting/AEC/MeetingAECPCMAdapter.swift b/Sources/Fluid/Services/Meeting/AEC/MeetingAECPCMAdapter.swift
index 3fc5794e..35fdb17f 100644
--- a/Sources/Fluid/Services/Meeting/AEC/MeetingAECPCMAdapter.swift
+++ b/Sources/Fluid/Services/Meeting/AEC/MeetingAECPCMAdapter.swift
@@ -113,7 +113,9 @@ nonisolated enum MeetingAECPCMAdapter {
}
if channels > 1 {
let divisor = Float(channels)
- for index in mono.indices { mono[index] /= divisor }
+ for index in mono.indices {
+ mono[index] /= divisor
+ }
}
guard mono.allSatisfy(\.isFinite) else { return .failure(.nonFiniteSamples) }
diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingAnalysisManifest.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingAnalysisManifest.swift
index a700f242..46ff46d0 100644
--- a/Sources/Fluid/Services/Meeting/Backend/MeetingAnalysisManifest.swift
+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingAnalysisManifest.swift
@@ -105,22 +105,22 @@ nonisolated extension MeetingCodecPriming {
let container = try decoder.container(keyedBy: CodingKeys.self)
if container.contains(.measuredFrames) {
if let value = try? container.nestedContainer(keyedBy: AssociatedValueKeys.self, forKey: .measuredFrames) {
- self = .measuredFrames(try value.decode(Int.self, forKey: ._0))
+ self = try .measuredFrames(value.decode(Int.self, forKey: ._0))
} else {
// Be liberal for any interim build that emitted a direct scalar.
- self = .measuredFrames(try container.decode(Int.self, forKey: .measuredFrames))
+ self = try .measuredFrames(container.decode(Int.self, forKey: .measuredFrames))
}
} else if container.contains(.unknown) {
if let value = try? container.nestedContainer(keyedBy: AssociatedValueKeys.self, forKey: .unknown) {
- self = .unknown(try value.decode(MeetingCodecPrimingUnknownReason.self, forKey: ._0))
+ self = try .unknown(value.decode(MeetingCodecPrimingUnknownReason.self, forKey: ._0))
} else {
- self = .unknown(try container.decode(MeetingCodecPrimingUnknownReason.self, forKey: .unknown))
+ self = try .unknown(container.decode(MeetingCodecPrimingUnknownReason.self, forKey: .unknown))
}
} else if container.contains(.notApplicable) {
if let value = try? container.nestedContainer(keyedBy: AssociatedValueKeys.self, forKey: .notApplicable) {
- self = .notApplicable(try value.decode(MeetingAudioEncoding.self, forKey: ._0))
+ self = try .notApplicable(value.decode(MeetingAudioEncoding.self, forKey: ._0))
} else {
- self = .notApplicable(try container.decode(MeetingAudioEncoding.self, forKey: .notApplicable))
+ self = try .notApplicable(container.decode(MeetingAudioEncoding.self, forKey: .notApplicable))
}
} else {
throw DecodingError.dataCorruptedError(
@@ -568,7 +568,8 @@ nonisolated struct MeetingAnalysisChunkIdentity: Codable, Equatable, Hashable {
if let asset = chunk.captureAnalysisAsset,
asset.presence == .ready,
asset.role == .captureAnalysis,
- asset.encoding == .linearPCMFloat32CAFV1 {
+ asset.encoding == .linearPCMFloat32CAFV1
+ {
self.relativeFilePath = asset.relativeFilePath
self.storedByteCount = asset.byteCount
self.storedSHA256 = asset.sha256 ?? ""
@@ -968,6 +969,8 @@ nonisolated enum MeetingAnalysisManifestError: LocalizedError, Equatable {
case invalidDecodedFacts(spanID: String)
case decodedDurationInconsistent(spanID: String)
case primingFramesExceedDecodedFrames(spanID: String)
+ // Keep the existing descriptive state or persisted evidence field name.
+ // swiftlint:disable:next identifier_name
case sourceLocalIntervalDisagreesWithRecordedPiece(spanID: String)
case analysisDurationDisagreesWithSource(spanID: String)
case analysisTimeNotGapRemoved(trackID: MeetingAudioTrackID)
@@ -1337,7 +1340,7 @@ nonisolated extension MeetingAnalysisManifest {
}
}
- // MARK: Spans
+ // MARK: - Spans
private func validateSpan(
_ span: MeetingAnalysisSpan,
@@ -1593,7 +1596,7 @@ nonisolated extension MeetingAnalysisManifest {
}
}
- // MARK: Gaps
+ // MARK: - Gaps
private func validateGap(
_ gap: MeetingAnalysisGap,
@@ -1658,7 +1661,7 @@ nonisolated extension MeetingAnalysisManifest {
}
}
- // MARK: Shared piece checks
+ // MARK: - Shared piece checks
private func plannedChunk(
for identity: MeetingAnalysisChunkIdentity,
@@ -1707,7 +1710,7 @@ nonisolated extension MeetingAnalysisManifest {
return planned[index - 1]
}
- // MARK: Coverage
+ // MARK: - Coverage
/// Exactly-once coverage, in both directions: every planned chunk is covered by pieces that
/// tile its recorded interval with no hole and no overlap, and nothing outside the plan is
@@ -1772,7 +1775,7 @@ nonisolated extension MeetingAnalysisManifest {
}
}
- // MARK: Epochs
+ // MARK: - Epochs
private func validateEpochRecords(of track: MeetingAnalysisTrackManifest) throws {
let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds
@@ -1931,7 +1934,7 @@ nonisolated extension MeetingAnalysisManifest {
].first(where: causes.contains)
}
- // MARK: Timeline
+ // MARK: - Timeline
/// Analysis time is per track: it starts at zero, concatenates its spans with no gaps at all,
/// and never runs backwards.
diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingAnalysisManifestBuilder.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingAnalysisManifestBuilder.swift
index 392a8142..1f096be1 100644
--- a/Sources/Fluid/Services/Meeting/Backend/MeetingAnalysisManifestBuilder.swift
+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingAnalysisManifestBuilder.swift
@@ -231,6 +231,9 @@ nonisolated struct MeetingAnalysisManifestBuilder {
}
}
+ // Keep the explicit existing capture inputs together.
+
+ // swiftlint:disable:next function_parameter_count
private func appendPiece(
_ piece: MeetingAnalysisInterval,
pieceIndex: Int,
diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingAudioFilePCMChunkSink.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingAudioFilePCMChunkSink.swift
index fb962694..fae4d533 100644
--- a/Sources/Fluid/Services/Meeting/Backend/MeetingAudioFilePCMChunkSink.swift
+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingAudioFilePCMChunkSink.swift
@@ -22,6 +22,7 @@ final nonisolated class MeetingAudioFilePCMChunkSink: MeetingAudioChunkSink, @un
let layout: Data?
let contract: MeetingPCMFormatContract
}
+
private struct Paths { let final: URL; let partial: URL }
private struct Identity { let dev: dev_t; let ino: ino_t; let size: off_t }
private let sessionDirectory: URL
@@ -35,7 +36,7 @@ final nonisolated class MeetingAudioFilePCMChunkSink: MeetingAudioChunkSink, @un
var partialRelativeFilePath: String? {
guard let partial = paths?.partial else { return nil }
- let root = sessionDirectory.path.hasSuffix("/") ? sessionDirectory.path : sessionDirectory.path + "/"
+ let root = self.sessionDirectory.path.hasSuffix("/") ? self.sessionDirectory.path : self.sessionDirectory.path + "/"
guard partial.path.hasPrefix(root) else { return nil }
return String(partial.path.dropFirst(root.count))
}
@@ -46,17 +47,15 @@ final nonisolated class MeetingAudioFilePCMChunkSink: MeetingAudioChunkSink, @un
func begin(relativeFilePath: String, format: AVAudioFormat) throws {
let contract: MeetingPCMFormatContract
- do { contract = try MeetingPCMFormatContract(audioFormat: format) }
- catch { throw MeetingPCMSinkError.unsupportedClientFormat(error.localizedDescription) }
- try begin(relativeFilePath: relativeFilePath, format: format, contract: contract)
+ do { contract = try MeetingPCMFormatContract(audioFormat: format) } catch { throw MeetingPCMSinkError.unsupportedClientFormat(error.localizedDescription) }
+ try self.begin(relativeFilePath: relativeFilePath, format: format, contract: contract)
}
func begin(relativeFilePath: String, format: AVAudioFormat, contract: MeetingPCMFormatContract) throws {
- guard state == .idle else { throw MeetingPCMSinkError.alreadyBegun }
+ guard self.state == .idle else { throw MeetingPCMSinkError.alreadyBegun }
let inputASBD = format.streamDescription.pointee
let derivedContract: MeetingPCMFormatContract
- do { derivedContract = try MeetingPCMFormatContract(audioFormat: format) }
- catch { throw MeetingPCMSinkError.unsupportedClientFormat(error.localizedDescription) }
+ do { derivedContract = try MeetingPCMFormatContract(audioFormat: format) } catch { throw MeetingPCMSinkError.unsupportedClientFormat(error.localizedDescription) }
guard derivedContract == contract else {
throw MeetingPCMSinkError.formatMismatch(expected: contract.description, actual: derivedContract.description)
}
@@ -72,6 +71,8 @@ final nonisolated class MeetingAudioFilePCMChunkSink: MeetingAudioChunkSink, @un
}
if let layout {
let setStatus = layout.withUnsafeBytes {
+ // Buffer size and channel topology are validated before this synchronous C call.
+ // swiftlint:disable:next force_unwrapping
AudioFileSetProperty(file, kAudioFilePropertyChannelLayout, UInt32($0.count), $0.baseAddress!)
}
guard setStatus == noErr else {
@@ -89,11 +90,11 @@ final nonisolated class MeetingAudioFilePCMChunkSink: MeetingAudioChunkSink, @un
}
func append(_ sampleBuffer: CMSampleBuffer) throws -> MeetingPCMAppendReceipt {
- guard state == .open, let file = audioFile, let format, let expectedASBD = fileASBD else {
- if state == .idle { throw MeetingPCMSinkError.notBegun }
+ guard self.state == .open, let file = audioFile, let format, let expectedASBD = fileASBD else {
+ if self.state == .idle { throw MeetingPCMSinkError.notBegun }
throw MeetingPCMSinkError.alreadyFinalizedOrCancelled
}
- guard !poisoned else { throw MeetingPCMSinkError.finalizationVerificationFailed("sink is poisoned") }
+ guard !self.poisoned else { throw MeetingPCMSinkError.finalizationVerificationFailed("sink is poisoned") }
guard CMSampleBufferIsValid(sampleBuffer), CMSampleBufferDataIsReady(sampleBuffer) else {
throw MeetingPCMSinkError.invalidSampleBuffer("invalid or unready sample buffer")
}
@@ -105,15 +106,14 @@ final nonisolated class MeetingAudioFilePCMChunkSink: MeetingAudioChunkSink, @un
let incoming = CMAudioFormatDescriptionGetStreamBasicDescription(desc)?.pointee
else { throw MeetingPCMSinkError.invalidSampleBuffer("missing audio format description") }
let incomingContract: MeetingPCMFormatContract
- do { incomingContract = try MeetingPCMFormatContract(formatDescription: desc) }
- catch {
- poisoned = true
- closeOpenFile()
+ do { incomingContract = try MeetingPCMFormatContract(formatDescription: desc) } catch {
+ self.poisoned = true
+ self.closeOpenFile()
throw MeetingPCMSinkError.unsupportedClientFormat(error.localizedDescription)
}
guard incomingContract == format.contract else {
- poisoned = true
- closeOpenFile()
+ self.poisoned = true
+ self.closeOpenFile()
throw MeetingPCMSinkError.formatMismatch(expected: format.contract.description, actual: incomingContract.description)
}
guard incoming.mSampleRate == format.rate,
@@ -122,8 +122,8 @@ final nonisolated class MeetingAudioFilePCMChunkSink: MeetingAudioChunkSink, @un
(incoming.mFormatFlags & kAudioFormatFlagIsFloat) != 0,
(incoming.mFormatFlags & kAudioFormatFlagIsSignedInteger) == 0
else {
- poisoned = true
- closeOpenFile()
+ self.poisoned = true
+ self.closeOpenFile()
throw MeetingPCMSinkError.formatMismatch(expected: format.contract.description, actual: Self.describe(incoming, layout: Self.layoutData(desc)))
}
let frames = CMSampleBufferGetNumSamples(sampleBuffer)
@@ -133,29 +133,31 @@ final nonisolated class MeetingAudioFilePCMChunkSink: MeetingAudioChunkSink, @un
let expectedBytes = try Self.checkedMultiply(Int64(frames), Int64(expectedASBD.mBytesPerFrame))
guard Int64(packed.count) == expectedBytes else { throw MeetingPCMSinkError.invalidSampleBuffer("packed size mismatch") }
var packetCount = try Self.checkedUInt32(Int64(frames))
- let packetOffset = try Self.checkedInt64(writtenPackets)
+ let packetOffset = try Self.checkedInt64(self.writtenPackets)
let byteCount = try Self.checkedUInt32(Int64(packed.count))
let status = packed.withUnsafeBytes { bytes in
+ // Buffer size and channel topology are validated before this synchronous C call.
+ // swiftlint:disable:next force_unwrapping
AudioFileWritePackets(file, false, byteCount, nil, packetOffset, &packetCount, bytes.baseAddress!)
}
let actual = Int64(packetCount)
- guard status == noErr else { poisoned = true; closeOpenFile(); throw MeetingPCMSinkError.writeFailed(status) }
- guard actual == Int64(frames) else { poisoned = true; closeOpenFile(); throw MeetingPCMSinkError.shortWrite(expectedFrames: Int64(frames), writtenFrames: actual) }
- writtenPackets = try Self.checkedAdd(writtenPackets, actual)
+ guard status == noErr else { self.poisoned = true; self.closeOpenFile(); throw MeetingPCMSinkError.writeFailed(status) }
+ guard actual == Int64(frames) else { self.poisoned = true; self.closeOpenFile(); throw MeetingPCMSinkError.shortWrite(expectedFrames: Int64(frames), writtenFrames: actual) }
+ self.writtenPackets = try Self.checkedAdd(self.writtenPackets, actual)
let duration = CMTime(seconds: Double(frames) / format.rate, preferredTimescale: 1_000_000_000)
return MeetingPCMAppendReceipt(framesAccepted: Int64(frames), framesWritten: actual, presentationStart: pts, presentationDuration: duration)
}
func finalize() -> Result<MeetingPCMFinalization, MeetingPCMSinkError> {
- guard state == .open, let paths, let format else { return .failure(state == .idle ? .notBegun : .alreadyFinalizedOrCancelled) }
- guard !poisoned else { removePartialAndClose(); return .failure(.finalizationVerificationFailed("sink is poisoned")) }
- guard writtenPackets > 0 else { removePartialAndClose(); state = .cancelled; return .failure(.finalizationVerificationFailed("CAF contains no written frames")) }
+ guard self.state == .open, let paths, let format else { return .failure(self.state == .idle ? .notBegun : .alreadyFinalizedOrCancelled) }
+ guard !self.poisoned else { self.removePartialAndClose(); return .failure(.finalizationVerificationFailed("sink is poisoned")) }
+ guard self.writtenPackets > 0 else { self.removePartialAndClose(); self.state = .cancelled; return .failure(.finalizationVerificationFailed("CAF contains no written frames")) }
if let file = audioFile {
let status = AudioFileClose(file); audioFile = nil
- guard status == noErr else { try? FileManager.default.removeItem(at: paths.partial); state = .cancelled; return .failure(.writeFailed(status)) }
+ guard status == noErr else { try? FileManager.default.removeItem(at: paths.partial); self.state = .cancelled; return .failure(.writeFailed(status)) }
}
do {
- let check = try Self.verify(paths.partial, format: format, expectedPackets: writtenPackets)
+ let check = try Self.verify(paths.partial, format: format, expectedPackets: self.writtenPackets)
let identity = try Self.identity(paths.partial)
guard !FileManager.default.fileExists(atPath: paths.final.path) else { throw MeetingPCMSinkError.finalPathAlreadyExists(paths.final.path) }
try Self.fullSync(paths.partial)
@@ -168,35 +170,46 @@ final nonisolated class MeetingAudioFilePCMChunkSink: MeetingAudioChunkSink, @un
throw MeetingPCMSinkError.underlyingFileError("atomic rename failed: errno \(errno)")
}
try Self.syncDirectory(paths.final.deletingLastPathComponent())
- state = .finalized
- return .success(MeetingPCMFinalization(relativeFilePath: try relativePath(paths.final), byteCount: check.bytes, sha256: check.hash,
- sampleRate: check.rate, channelCount: check.channels, frameCount: check.frames))
+ self.state = .finalized
+ return try .success(MeetingPCMFinalization(
+ relativeFilePath: self.relativePath(paths.final),
+ byteCount: check.bytes,
+ sha256: check.hash,
+ sampleRate: check.rate,
+ channelCount: check.channels,
+ frameCount: check.frames
+ ))
} catch let error as MeetingPCMSinkError {
state = .cancelled; try? FileManager.default.removeItem(at: paths.partial); return .failure(error)
- } catch { state = .cancelled; try? FileManager.default.removeItem(at: paths.partial); return .failure(.underlyingFileError(error.localizedDescription)) }
+ } catch { self.state = .cancelled; try? FileManager.default.removeItem(at: paths.partial); return .failure(.underlyingFileError(error.localizedDescription)) }
}
- func cancel() { guard state == .open || state == .idle else { return }; removePartialAndClose(); state = .cancelled }
+ func cancel() { guard self.state == .open || self.state == .idle else { return }; self.removePartialAndClose(); self.state = .cancelled }
+
+ // MARK: - Path / format helpers
- // MARK: Path / format helpers
private func resolvePaths(_ relative: String) throws -> Paths {
guard !relative.isEmpty, !relative.hasPrefix("/"), !relative.contains("\\"), relative.hasSuffix(".caf") else { throw MeetingPCMSinkError.invalidRelativePath(relative) }
let components = relative.split(separator: "/", omittingEmptySubsequences: false).map(String.init)
- guard !components.isEmpty, components.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }), !components.last!.contains(".partial.") else { throw MeetingPCMSinkError.invalidRelativePath(relative) }
- try Self.rejectSymlink(sessionDirectory)
- var parent = sessionDirectory
+ guard let filename = components.last, components.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }),
+ !filename.contains(".partial.") else { throw MeetingPCMSinkError.invalidRelativePath(relative) }
+ try Self.rejectSymlink(self.sessionDirectory)
+ var parent = self.sessionDirectory
for component in components.dropLast() {
parent.appendPathComponent(component, isDirectory: true)
- if FileManager.default.fileExists(atPath: parent.path) { try Self.rejectSymlink(parent) }
- else { try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: false, attributes: [.posixPermissions: NSNumber(value: Int16(0o700))]) }
+ if FileManager.default.fileExists(atPath: parent.path) { try Self.rejectSymlink(parent) } else { try FileManager.default.createDirectory(
+ at: parent,
+ withIntermediateDirectories: false,
+ attributes: [.posixPermissions: NSNumber(value: Int16(0o700))]
+ ) }
guard FileManager.default.fileExists(atPath: parent.path, isDirectory: nil) else { throw MeetingPCMSinkError.underlyingFileError("parent does not exist") }
guard chmod(parent.path, mode_t(0o700)) == 0 else {
throw MeetingPCMSinkError.underlyingFileError("could not set directory permissions: \(parent.path)")
}
}
- let final = parent.appendingPathComponent(components.last!)
+ let final = parent.appendingPathComponent(filename)
if FileManager.default.fileExists(atPath: final.path) { try Self.rejectSymlink(final); throw MeetingPCMSinkError.finalPathAlreadyExists(relative) }
- let partial = parent.appendingPathComponent(String(components.last!.dropLast(4)) + ".\(UUID().uuidString).partial.caf")
+ let partial = parent.appendingPathComponent(String(filename.dropLast(4)) + ".\(UUID().uuidString).partial.caf")
if FileManager.default.fileExists(atPath: partial.path) { throw MeetingPCMSinkError.partialPathAlreadyExists(partial.path) }
return Paths(final: final, partial: partial)
}
@@ -209,58 +222,116 @@ final nonisolated class MeetingAudioFilePCMChunkSink: MeetingAudioChunkSink, @un
private static func canonicalASBD(rate: Double, channels: UInt32) throws -> AudioStreamBasicDescription {
let (bytes, overflow) = channels.multipliedReportingOverflow(by: 4)
guard !overflow else { throw MeetingPCMSinkError.unsupportedClientFormat("channel byte size overflow") }
- return AudioStreamBasicDescription(mSampleRate: rate, mFormatID: kAudioFormatLinearPCM, mFormatFlags: kAudioFormatFlagsNativeFloatPacked,
- mBytesPerPacket: bytes, mFramesPerPacket: 1, mBytesPerFrame: bytes,
- mChannelsPerFrame: channels, mBitsPerChannel: 32, mReserved: 0)
+ return AudioStreamBasicDescription(
+ mSampleRate: rate,
+ mFormatID: kAudioFormatLinearPCM,
+ mFormatFlags: kAudioFormatFlagsNativeFloatPacked,
+ mBytesPerPacket: bytes,
+ mFramesPerPacket: 1,
+ mBytesPerFrame: bytes,
+ mChannelsPerFrame: channels,
+ mBitsPerChannel: 32,
+ mReserved: 0
+ )
}
- // MARK: ABL and checked arithmetic
+ // MARK: - ABL and checked arithmetic
+
private final class AudioList {
let pointer: UnsafeMutablePointer<AudioBufferList>; let retained: CMBlockBuffer?
init(sampleBuffer: CMSampleBuffer) throws {
var size = 0
- let first = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampleBuffer, bufferListSizeNeededOut: &size, bufferListOut: nil, bufferListSize: 0, blockBufferAllocator: nil, blockBufferMemoryAllocator: nil, flags: 0, blockBufferOut: nil)
+ let first = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
+ sampleBuffer,
+ bufferListSizeNeededOut: &size,
+ bufferListOut: nil,
+ bufferListSize: 0,
+ blockBufferAllocator: nil,
+ blockBufferMemoryAllocator: nil,
+ flags: 0,
+ blockBufferOut: nil
+ )
guard first == noErr, size > 0 else { throw MeetingPCMSinkError.invalidSampleBuffer("ABL size unavailable") }
- pointer = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: MemoryLayout<AudioBufferList>.alignment).assumingMemoryBound(to: AudioBufferList.self)
+ self.pointer = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: MemoryLayout<AudioBufferList>.alignment).assumingMemoryBound(to: AudioBufferList.self)
var block: CMBlockBuffer?
- let second = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampleBuffer, bufferListSizeNeededOut: &size, bufferListOut: pointer, bufferListSize: size, blockBufferAllocator: nil, blockBufferMemoryAllocator: nil, flags: kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, blockBufferOut: &block)
- guard second == noErr else { pointer.deallocate(); throw MeetingPCMSinkError.invalidSampleBuffer("ABL unavailable") }
- retained = block
+ let second = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
+ sampleBuffer,
+ bufferListSizeNeededOut: &size,
+ bufferListOut: self.pointer,
+ bufferListSize: size,
+ blockBufferAllocator: nil,
+ blockBufferMemoryAllocator: nil,
+ flags: kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment,
+ blockBufferOut: &block
+ )
+ guard second == noErr else { self.pointer.deallocate(); throw MeetingPCMSinkError.invalidSampleBuffer("ABL unavailable") }
+ self.retained = block
}
+
deinit { pointer.deallocate() }
func interleavedFloat32(frames: Int, channels: Int, inputASBD: AudioStreamBasicDescription) throws -> Data {
let buffers = UnsafeMutableAudioBufferListPointer(pointer)
let nonInterleaved = (inputASBD.mFormatFlags & kAudioFormatFlagIsNonInterleaved) != 0
- guard (nonInterleaved ? buffers.count == channels : buffers.count == 1), buffers.allSatisfy({ $0.mData != nil && $0.mNumberChannels == (nonInterleaved ? 1 : UInt32(channels)) }) else { throw MeetingPCMSinkError.invalidSampleBuffer("ABL topology mismatch") }
+ guard nonInterleaved ? buffers.count == channels : buffers.count == 1,
+ buffers.allSatisfy({ $0.mData != nil && $0.mNumberChannels == (nonInterleaved ? 1 : UInt32(channels)) })
+ else { throw MeetingPCMSinkError.invalidSampleBuffer("ABL topology mismatch") }
let bytesPerChannel = try MeetingAudioFilePCMChunkSink.checkedMultiply(Int64(frames), 4)
let expectedBytes = try MeetingAudioFilePCMChunkSink.checkedMultiply(bytesPerChannel, nonInterleaved ? 1 : Int64(channels))
guard buffers.allSatisfy({ Int64($0.mDataByteSize) == expectedBytes }) else { throw MeetingPCMSinkError.invalidSampleBuffer("ABL byte count mismatch") }
let count = try MeetingAudioFilePCMChunkSink.checkedMultiply(Int64(frames), Int64(channels))
- var output = Data(count: try Int(MeetingAudioFilePCMChunkSink.checkedMultiply(count, 4)))
+ var output = try Data(count: Int(MeetingAudioFilePCMChunkSink.checkedMultiply(count, 4)))
output.withUnsafeMutableBytes { out in
+ // Buffer size and channel topology are validated before this synchronous C call.
+ // swiftlint:disable:next force_unwrapping
let dst = out.baseAddress!.assumingMemoryBound(to: Float.self)
if nonInterleaved {
+ // Buffer size and channel topology are validated before this synchronous C call.
+ // swiftlint:disable:next force_unwrapping
let src = buffers.map { $0.mData!.assumingMemoryBound(to: Float.self) }
- for frame in 0..<frames { for channel in 0..<channels { dst[frame * channels + channel] = src[channel][frame] } }
+ for frame in 0..<frames {
+ for channel in 0..<channels {
+ dst[frame * channels + channel] = src[channel][frame]
+ }
+ }
} else {
+ // Buffer size and channel topology are validated before this synchronous C call.
+ // swiftlint:disable:next force_unwrapping
let src = buffers[0].mData!.assumingMemoryBound(to: Float.self)
- for i in 0..<Int(count) { dst[i] = src[i] }
+ for i in 0..<Int(count) {
+ dst[i] = src[i]
+ }
}
}
- for value in output.withUnsafeBytes({ $0.bindMemory(to: Float.self) }) where !value.isFinite { throw MeetingPCMSinkError.nonFiniteSample }
+ for value in output.withUnsafeBytes({ $0.bindMemory(to: Float.self) }) where !value.isFinite {
+ throw MeetingPCMSinkError.nonFiniteSample
+ }
return output
}
}
- private static func checkedMultiply(_ a: Int64, _ b: Int64) throws -> Int64 { let (v, o) = a.multipliedReportingOverflow(by: b); if o || v < 0 { throw MeetingPCMSinkError.invalidSampleBuffer("integer overflow") }; return v }
- private static func checkedAdd(_ a: Int64, _ b: Int64) throws -> Int64 { let (v, o) = a.addingReportingOverflow(b); if o || v < 0 { throw MeetingPCMSinkError.invalidSampleBuffer("integer overflow") }; return v }
- private static func checkedUInt32(_ value: Int64) throws -> UInt32 { guard value >= 0, value <= Int64(UInt32.max) else { throw MeetingPCMSinkError.invalidSampleBuffer("packet count overflow") }; return UInt32(value) }
+ private static func checkedMultiply(
+ _ a: Int64,
+ _ b: Int64
+ ) throws -> Int64 { let (v, o) = a.multipliedReportingOverflow(by: b); if o || v < 0 { throw MeetingPCMSinkError.invalidSampleBuffer("integer overflow") }; return v }
+ private static func checkedAdd(
+ _ a: Int64,
+ _ b: Int64
+ ) throws -> Int64 { let (v, o) = a.addingReportingOverflow(b); if o || v < 0 { throw MeetingPCMSinkError.invalidSampleBuffer("integer overflow") }; return v }
+ private static func checkedUInt32(_ value: Int64) throws -> UInt32 { guard value >= 0,
+ value <= Int64(UInt32.max)
+ else { throw MeetingPCMSinkError.invalidSampleBuffer("packet count overflow") }; return UInt32(value)
+ }
+
private static func checkedInt64(_ value: Int64) throws -> Int64 { guard value >= 0 else { throw MeetingPCMSinkError.invalidSampleBuffer("negative packet offset") }; return value }
- // MARK: Verification / durability
+ // MARK: - Verification / durability
+
private struct Check { let bytes: Int64; let hash: String; let rate: Double; let channels: Int; let frames: Int64 }
private static func verify(_ url: URL, format: Format, expectedPackets: Int64) throws -> Check {
- var file: AudioFileID?; let open = AudioFileOpenURL(url as CFURL, .readPermission, 0, &file); guard open == noErr, let file else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF reopen failed") }; defer { AudioFileClose(file) }
+ var file: AudioFileID?; let open = AudioFileOpenURL(url as CFURL, .readPermission, 0, &file); guard open == noErr,
+ let file
+ else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF reopen failed")
+ }; defer { AudioFileClose(file) }
var asbd = AudioStreamBasicDescription(); var size = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
let canonical = try Self.canonicalASBD(rate: format.rate, channels: format.channels)
guard AudioFileGetProperty(file, kAudioFilePropertyDataFormat, &size, &asbd) == noErr,
@@ -274,22 +345,62 @@ final nonisolated class MeetingAudioFilePCMChunkSink: MeetingAudioChunkSink, @un
asbd.mBitsPerChannel == canonical.mBitsPerChannel
else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF ASBD mismatch") }
let layout = try Self.fileLayout(file); guard layout == format.layout else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF channel layout mismatch") }
- var packets: Int64 = 0; size = UInt32(MemoryLayout<Int64>.size); guard AudioFileGetProperty(file, kAudioFilePropertyAudioDataPacketCount, &size, &packets) == noErr, packets == expectedPackets else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF packet count mismatch") }
- var bytesCount: Int64 = 0; size = UInt32(MemoryLayout<Int64>.size); guard AudioFileGetProperty(file, kAudioFilePropertyAudioDataByteCount, &size, &bytesCount) == noErr else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF byte count unavailable") }
- let expectedBytes = try checkedMultiply(packets, Int64(asbd.mBytesPerFrame)); guard bytesCount == expectedBytes else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF data bytes mismatch") }
- let attrs = try FileManager.default.attributesOfItem(atPath: url.path); let actualSize = (attrs[.size] as? NSNumber)?.int64Value ?? -1; guard actualSize > 0 else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF is empty") }
- var hasher = SHA256(); let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() }; while true { let data = try handle.read(upToCount: 1 << 20) ?? Data(); if data.isEmpty { break }; hasher.update(data: data) }
+ var packets: Int64 = 0; size = UInt32(MemoryLayout<Int64>.size); guard AudioFileGetProperty(file, kAudioFilePropertyAudioDataPacketCount, &size, &packets) == noErr,
+ packets == expectedPackets else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF packet count mismatch") }
+ var bytesCount: Int64 = 0; size = UInt32(MemoryLayout<Int64>.size); guard AudioFileGetProperty(file, kAudioFilePropertyAudioDataByteCount, &size, &bytesCount) == noErr
+ else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF byte count unavailable") }
+ let expectedBytes = try checkedMultiply(packets, Int64(asbd.mBytesPerFrame)); guard bytesCount == expectedBytes
+ else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF data bytes mismatch") }
+ let attrs = try FileManager.default.attributesOfItem(atPath: url.path); let actualSize = (attrs[.size] as? NSNumber)?.int64Value ?? -1; guard actualSize > 0
+ else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF is empty") }
+ var hasher = SHA256(); let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() }; while true {
+ let data = try handle.read(upToCount: 1 << 20) ?? Data(); if data.isEmpty { break }; hasher.update(data: data)
+ }
return Check(bytes: actualSize, hash: hasher.finalize().map { String(format: "%02x", $0) }.joined(), rate: asbd.mSampleRate, channels: Int(asbd.mChannelsPerFrame), frames: packets)
}
- private static func fileLayout(_ file: AudioFileID) throws -> Data? { var size: UInt32 = 0; let query = AudioFileGetPropertyInfo(file, kAudioFilePropertyChannelLayout, &size, nil); guard query == noErr else { return nil }; guard size > 0 else { return nil }; var data = Data(count: Int(size)); let status = data.withUnsafeMutableBytes { AudioFileGetProperty(file, kAudioFilePropertyChannelLayout, &size, $0.baseAddress!) }; guard status == noErr else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF layout read failed") }; return data }
- private static func identity(_ url: URL) throws -> Identity { var st = stat(); guard lstat(url.path, &st) == 0 else { throw MeetingPCMSinkError.finalizationVerificationFailed("staged file disappeared") }; return Identity(dev: st.st_dev, ino: st.st_ino, size: st.st_size) }
- private static func fullSync(_ url: URL) throws { let fd = open(url.path, O_RDONLY); guard fd >= 0 else { throw MeetingPCMSinkError.underlyingFileError("open for sync failed") }; defer { close(fd) }; guard fcntl(fd, F_FULLFSYNC) == 0 else { throw MeetingPCMSinkError.underlyingFileError("F_FULLFSYNC failed") } }
- private static func syncDirectory(_ url: URL) throws { let fd = open(url.path, O_RDONLY | O_DIRECTORY); guard fd >= 0 else { throw MeetingPCMSinkError.underlyingFileError("open parent for sync failed") }; defer { close(fd) }; guard fsync(fd) == 0 else { throw MeetingPCMSinkError.underlyingFileError("parent fsync failed") } }
+
+ private static func fileLayout(_ file: AudioFileID) throws -> Data? { var size: UInt32 = 0; let query = AudioFileGetPropertyInfo(file, kAudioFilePropertyChannelLayout, &size, nil); guard query ==
+ noErr else { return nil }; guard size > 0 else { return nil }; var data = Data(count: Int(size)); let status = data.withUnsafeMutableBytes { AudioFileGetProperty(
+ file,
+ kAudioFilePropertyChannelLayout,
+ &size,
+ // Buffer size and channel topology are validated before this synchronous C call.
+ // swiftlint:disable:next force_unwrapping
+ $0.baseAddress!
+ ) }; guard status == noErr else { throw MeetingPCMSinkError.finalizationVerificationFailed("CAF layout read failed") }; return data
+ }
+
+ private static func identity(_ url: URL) throws -> Identity { var st = stat(); guard lstat(url.path, &st) == 0
+ else { throw MeetingPCMSinkError.finalizationVerificationFailed("staged file disappeared") }; return Identity(
+ dev: st.st_dev,
+ ino: st.st_ino,
+ size: st.st_size
+ )
+ }
+
+ private static func fullSync(_ url: URL) throws {
+ let fd = open(url.path, O_RDONLY); guard fd >= 0 else { throw MeetingPCMSinkError.underlyingFileError("open for sync failed") }; defer { close(fd) }; guard fcntl(
+ fd,
+ F_FULLFSYNC
+ ) == 0 else { throw MeetingPCMSinkError.underlyingFileError("F_FULLFSYNC failed") }
+ }
+
+ private static func syncDirectory(_ url: URL) throws {
+ let fd = open(url.path, O_RDONLY | O_DIRECTORY); guard fd >= 0 else { throw MeetingPCMSinkError.underlyingFileError("open parent for sync failed") }; defer { close(fd) }; guard fsync(fd) == 0
+ else { throw MeetingPCMSinkError.underlyingFileError("parent fsync failed") }
+ }
+
private static func layoutData(_ layout: AVAudioChannelLayout?) -> Data? { MeetingPCMFormatContract.layoutData(layout) }
private static func layoutData(_ desc: CMFormatDescription) -> Data? { MeetingPCMFormatContract.layoutData(desc) }
private static func describe(_ format: Format) -> String { "rate=\(format.rate), channels=\(format.channels), layoutBytes=\(format.layout?.count ?? 0)" }
- private static func describe(_ asbd: AudioStreamBasicDescription, layout: Data?) -> String { "rate=\(asbd.mSampleRate), channels=\(asbd.mChannelsPerFrame), flags=\(asbd.mFormatFlags), layoutBytes=\(layout?.count ?? 0)" }
- private func relativePath(_ url: URL) throws -> String { let root = sessionDirectory.path.hasSuffix("/") ? sessionDirectory.path : sessionDirectory.path + "/"; guard url.path.hasPrefix(root) else { throw MeetingPCMSinkError.finalizationVerificationFailed("published path escaped session") }; return String(url.path.dropFirst(root.count)) }
- private func closeOpenFile() { if let file = audioFile { AudioFileClose(file); audioFile = nil } }
- private func removePartialAndClose() { closeOpenFile(); if let partial = paths?.partial { try? FileManager.default.removeItem(at: partial) } }
+ private static func describe(
+ _ asbd: AudioStreamBasicDescription,
+ layout: Data?
+ ) -> String { "rate=\(asbd.mSampleRate), channels=\(asbd.mChannelsPerFrame), flags=\(asbd.mFormatFlags), layoutBytes=\(layout?.count ?? 0)" }
+ private func relativePath(_ url: URL) throws -> String { let root = self.sessionDirectory.path.hasSuffix("/") ? self.sessionDirectory.path : self.sessionDirectory.path + "/"; guard url.path
+ .hasPrefix(root) else { throw MeetingPCMSinkError.finalizationVerificationFailed("published path escaped session") }; return String(url.path.dropFirst(root.count))
+ }
+
+ private func closeOpenFile() { if let file = audioFile { AudioFileClose(file); self.audioFile = nil } }
+ private func removePartialAndClose() { self.closeOpenFile(); if let partial = paths?.partial { try? FileManager.default.removeItem(at: partial) } }
}
diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingEpochAudioMaterializer.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingEpochAudioMaterializer.swift
index 165f2b57..46ed694c 100644
--- a/Sources/Fluid/Services/Meeting/Backend/MeetingEpochAudioMaterializer.swift
+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingEpochAudioMaterializer.swift
@@ -120,7 +120,7 @@ nonisolated struct MeetingEpochAudioMaterializer: MeetingEpochAudioMaterializing
guard let span = spansByID[spanID] else {
throw MeetingEpochMaterializationError.unknownSpan(spanID: spanID)
}
- sourceSlices.append(try self.readSpanAudio(span, sessionDirectory: sessionDirectory))
+ try sourceSlices.append(self.readSpanAudio(span, sessionDirectory: sessionDirectory))
}
var samples: [Float] = []
@@ -130,7 +130,8 @@ nonisolated struct MeetingEpochAudioMaterializer: MeetingEpochAudioMaterializing
while runStart < sourceSlices.count {
var runEnd = runStart + 1
while runEnd < sourceSlices.count,
- sourceSlices[runEnd].conversionKey == sourceSlices[runStart].conversionKey {
+ sourceSlices[runEnd].conversionKey == sourceSlices[runStart].conversionKey
+ {
runEnd += 1
}
let run = Array(sourceSlices[runStart..<runEnd])
@@ -190,15 +191,16 @@ nonisolated struct MeetingEpochAudioMaterializer: MeetingEpochAudioMaterializing
private func convert(_ run: [SourceSlice]) throws -> ConvertedRun {
guard let first = run.first,
let format = AVAudioFormat(
- commonFormat: .pcmFormatFloat32,
- sampleRate: first.sampleRate,
- channels: 1,
- interleaved: false
+ commonFormat: .pcmFormatFloat32,
+ sampleRate: first.sampleRate,
+ channels: 1,
+ interleaved: false
),
let buffer = AVAudioPCMBuffer(
- pcmFormat: format,
- frameCapacity: AVAudioFrameCount(run.reduce(0) { $0 + $1.samples.count })
- ) else {
+ pcmFormat: format,
+ frameCapacity: AVAudioFrameCount(run.reduce(0) { $0 + $1.samples.count })
+ )
+ else {
throw MeetingEpochMaterializationError.emptySlice(spanID: run.first?.spanID ?? "unknown")
}
let values = run.flatMap(\.samples)
@@ -207,10 +209,12 @@ nonisolated struct MeetingEpochAudioMaterializer: MeetingEpochAudioMaterializing
throw MeetingEpochMaterializationError.emptySlice(spanID: first.spanID)
}
values.withUnsafeBufferPointer { source in
+ // Buffer size and channel topology are validated before this synchronous C call.
+ // swiftlint:disable:next force_unwrapping
destination.update(from: source.baseAddress!, count: source.count)
}
do {
- return ConvertedRun(samples: try AudioBufferConverter.monoSamples(
+ return try ConvertedRun(samples: AudioBufferConverter.monoSamples(
from: buffer,
targetSampleRate: self.sampleRate
))
@@ -338,14 +342,18 @@ nonisolated struct MeetingEpochAudioMaterializer: MeetingEpochAudioMaterializing
let channelCount = Int(format.channelCount)
for frame in 0..<mono.count {
var value: Float = 0
- for channel in 0..<channelCount { value += source[frame * channelCount + channel] }
+ for channel in 0..<channelCount {
+ value += source[frame * channelCount + channel]
+ }
mono[frame] = value / Float(channelCount)
}
} else {
let channelCount = Int(format.channelCount)
for frame in 0..<mono.count {
var value: Float = 0
- for channel in 0..<channelCount { value += channels[channel][frame] }
+ for channel in 0..<channelCount {
+ value += channels[channel][frame]
+ }
mono[frame] = value / Float(channelCount)
}
}
diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingParakeetNemotronBackend.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingParakeetNemotronBackend.swift
index fcc248ee..443f481a 100644
--- a/Sources/Fluid/Services/Meeting/Backend/MeetingParakeetNemotronBackend.swift
+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingParakeetNemotronBackend.swift
@@ -125,7 +125,7 @@ final class MeetingParakeetNemotronBackend: MeetingTranscriptionBackend {
/// Per-attempt cache for the PCM-first path. The cache is intentionally scoped to this
/// detached attempt and bounded by the materializer's conservative sample limit; a future
/// production implementation should replace it with a hashed immutable disk working store.
- private nonisolated final class MaterializationCache: @unchecked Sendable {
+ private final nonisolated class MaterializationCache: @unchecked Sendable {
private let lock = NSLock()
private var values: [MeetingAnalysisEpochID: MeetingMaterializedEpoch] = [:]
private var totalSampleCount = 0
@@ -501,6 +501,8 @@ final class MeetingParakeetNemotronBackend: MeetingTranscriptionBackend {
start: TimeInterval,
end: TimeInterval,
spans: [MeetingAnalysisSpan]
+ // nil means unavailable; an empty result means available with no values.
+ // swiftlint:disable:next discouraged_optional_collection
) -> [String]? {
let tolerance = MeetingAnalysisManifestSchema.mappingToleranceSeconds
let ids = spans.filter {
@@ -711,7 +713,7 @@ final class MeetingParakeetNemotronBackend: MeetingTranscriptionBackend {
let otherOnsets = activity.compactMap { entry -> TimeInterval? in
guard entry.token == other,
min(entry.end, end) - max(entry.start, start)
- > MeetingAnalysisManifestSchema.mappingToleranceSeconds
+ > MeetingAnalysisManifestSchema.mappingToleranceSeconds
else { return nil }
return entry.start
}
@@ -754,7 +756,10 @@ final class MeetingParakeetNemotronBackend: MeetingTranscriptionBackend {
DebugLogger.shared.info(
String(
format: "[speakerCoverage] duration=%.3fs candidates=%d overlaps=[%@] decision=%@",
- duration, candidateCoverageSeconds.count, overlaps, decisionLabel
+ duration,
+ candidateCoverageSeconds.count,
+ overlaps,
+ decisionLabel
),
source: "MeetingParakeetNemotronBackend"
)
diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingProductionParakeetNemotronRuntime.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingProductionParakeetNemotronRuntime.swift
index e8d50514..e91d63b2 100644
--- a/Sources/Fluid/Services/Meeting/Backend/MeetingProductionParakeetNemotronRuntime.swift
+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingProductionParakeetNemotronRuntime.swift
@@ -1,8 +1,8 @@
import Foundation
#if arch(arm64)
- import CoreML
- import FluidAudio
+import CoreML
+import FluidAudio
#endif
// Stage E of `MEETING_TRANSCRIPTION_IMPLEMENTATION_PLAN.md`: the production runtime behind
@@ -30,172 +30,172 @@ nonisolated enum MeetingParakeetNemotronRuntimeError: LocalizedError, Equatable
#if arch(arm64)
- /// Shared-weight Nemotron factory: one `SortformerModels` load, fresh streaming state per
- /// epoch. Slots can never merge across epochs because each epoch's diarizer is a new instance.
- private final nonisolated class NemotronDiarizerFactory: MeetingNemotronDiarizerFactory, @unchecked Sendable {
- let config: SortformerConfig
- let models: SortformerModels
- private let lock = NSLock()
- private var created: [SortformerDiarizer] = []
-
- init(config: SortformerConfig, models: SortformerModels) {
- self.config = config
- self.models = models
- }
+/// Shared-weight Nemotron factory: one `SortformerModels` load, fresh streaming state per
+/// epoch. Slots can never merge across epochs because each epoch's diarizer is a new instance.
+private final nonisolated class NemotronDiarizerFactory: MeetingNemotronDiarizerFactory, @unchecked Sendable {
+ let config: SortformerConfig
+ let models: SortformerModels
+ private let lock = NSLock()
+ private var created: [SortformerDiarizer] = []
+
+ init(config: SortformerConfig, models: SortformerModels) {
+ self.config = config
+ self.models = models
+ }
- func makeDiarizer(epoch _: MeetingAnalysisEpochID) async throws -> any MeetingNemotronDiarizerSession {
- try Task.checkCancellation()
- let diarizer = SortformerDiarizer(config: self.config)
- diarizer.initialize(models: self.models)
- self.lock.withLock { self.created.append(diarizer) }
- return NemotronDiarizerSession(diarizer: diarizer)
- }
+ func makeDiarizer(epoch _: MeetingAnalysisEpochID) async throws -> any MeetingNemotronDiarizerSession {
+ try Task.checkCancellation()
+ let diarizer = SortformerDiarizer(config: self.config)
+ diarizer.initialize(models: self.models)
+ self.lock.withLock { self.created.append(diarizer) }
+ return NemotronDiarizerSession(diarizer: diarizer)
+ }
- func cleanup() {
- let diarizers = self.lock.withLock {
- let pending = self.created
- self.created.removeAll()
- return pending
- }
- for diarizer in diarizers {
- diarizer.cleanup()
- }
+ func cleanup() {
+ let diarizers = self.lock.withLock {
+ let pending = self.created
+ self.created.removeAll()
+ return pending
+ }
+ for diarizer in diarizers {
+ diarizer.cleanup()
}
}
+}
- private nonisolated struct NemotronDiarizerSession: MeetingNemotronDiarizerSession, @unchecked Sendable {
- // The diarizer is used strictly serially: one epoch, one caller, one call.
- let diarizer: SortformerDiarizer
-
- func diarize(samples: [Float]) async throws -> [MeetingNemotronSpeakerSegment] {
- try Task.checkCancellation()
- let timeline = try self.diarizer.processComplete(
- samples,
- sourceSampleRate: nil,
- keepingEnrolledSpeakers: false,
- finalizeOnCompletion: true
- )
- try Task.checkCancellation()
- return timeline.speakers
- .sorted { $0.key < $1.key }
- .flatMap { index, speaker in
- speaker.finalizedSegments.compactMap { segment in
- guard segment.isFinalized, segment.endTime > segment.startTime else { return nil }
- return MeetingNemotronSpeakerSegment(
- slotIndex: index,
- start: TimeInterval(segment.startTime),
- end: TimeInterval(segment.endTime)
- )
- }
+private nonisolated struct NemotronDiarizerSession: MeetingNemotronDiarizerSession, @unchecked Sendable {
+ // The diarizer is used strictly serially: one epoch, one caller, one call.
+ let diarizer: SortformerDiarizer
+
+ func diarize(samples: [Float]) async throws -> [MeetingNemotronSpeakerSegment] {
+ try Task.checkCancellation()
+ let timeline = try self.diarizer.processComplete(
+ samples,
+ sourceSampleRate: nil,
+ keepingEnrolledSpeakers: false,
+ finalizeOnCompletion: true
+ )
+ try Task.checkCancellation()
+ return timeline.speakers
+ .sorted { $0.key < $1.key }
+ .flatMap { index, speaker in
+ speaker.finalizedSegments.compactMap { segment in
+ guard segment.isFinalized, segment.endTime > segment.startTime else { return nil }
+ return MeetingNemotronSpeakerSegment(
+ slotIndex: index,
+ start: TimeInterval(segment.startTime),
+ end: TimeInterval(segment.endTime)
+ )
}
- }
+ }
}
+}
- /// The prepared Parakeet session. Both references are only ever exercised through ASRService's
- /// own main-actor scope and meeting executor, never from the caller's context directly.
- private nonisolated struct PreparedParakeetASRSession: MeetingParakeetASRSession, @unchecked Sendable {
- let asrService: ASRService
- let provider: any TranscriptionProvider
+/// The prepared Parakeet session. Both references are only ever exercised through ASRService's
+/// own main-actor scope and meeting executor, never from the caller's context directly.
+private nonisolated struct PreparedParakeetASRSession: MeetingParakeetASRSession, @unchecked Sendable {
+ let asrService: ASRService
+ let provider: any TranscriptionProvider
- func transcribeWithTimings(
- _ samples: [Float]
- ) async throws -> (result: ASRTranscriptionResult, words: [ASRWordTiming]) {
- try await self.asrService.transcribeMeetingSamplesWithTimings(samples, provider: self.provider)
- }
+ func transcribeWithTimings(
+ _ samples: [Float]
+ ) async throws -> (result: ASRTranscriptionResult, words: [ASRWordTiming]) {
+ try await self.asrService.transcribeMeetingSamplesWithTimings(samples, provider: self.provider)
}
+}
- final nonisolated class MeetingParakeetNemotronRuntime: MeetingParakeetNemotronRunning {
- private let asrServiceProvider: @MainActor () -> ASRService
- private let modelLocator: any MeetingNemotronModelLocating
+final nonisolated class MeetingParakeetNemotronRuntime: MeetingParakeetNemotronRunning {
+ private let asrServiceProvider: @MainActor () -> ASRService
+ private let modelLocator: any MeetingNemotronModelLocating
- init(
- asrServiceProvider: @escaping @MainActor () -> ASRService,
- modelLocator: any MeetingNemotronModelLocating
- ) {
- self.asrServiceProvider = asrServiceProvider
- self.modelLocator = modelLocator
- }
+ init(
+ asrServiceProvider: @escaping @MainActor () -> ASRService,
+ modelLocator: any MeetingNemotronModelLocating
+ ) {
+ self.asrServiceProvider = asrServiceProvider
+ self.modelLocator = modelLocator
+ }
- func withNemotronDiarization(
- artifact: MeetingNemotronModelArtifact,
- _ body: @escaping @Sendable (any MeetingNemotronDiarizerFactory) async throws -> MeetingNemotronPhaseResult
- ) async throws -> MeetingNemotronPhaseResult {
- // Recheck at open time: the artifact located at plan/readiness time is validated again
- // before CoreML touches it (plan §5).
- let artifact = try self.modelLocator.recheck(artifact)
- // Reference Nemotron streaming configuration (conversion script cadence, kept exact by
- // the FluidAudio factory; it validates instead of clamping).
- let config = try SortformerConfig.nemotron(
- spkcacheUpdatePeriod: 300,
- spkcacheSilFramesPerSpk: 3,
- predScoreThreshold: 0.25
- )
- let mlConfiguration = MLModelConfiguration()
- mlConfiguration.computeUnits = .cpuAndGPU
- let models = try await SortformerModels.load(
- config: config,
- mainModelPath: artifact.packageURL,
- configuration: mlConfiguration
- )
- let factory = NemotronDiarizerFactory(config: config, models: models)
- do {
- let result = try await body(factory)
- factory.cleanup()
- return result
- } catch {
- factory.cleanup()
- throw error
- }
+ func withNemotronDiarization(
+ artifact: MeetingNemotronModelArtifact,
+ _ body: @escaping @Sendable (any MeetingNemotronDiarizerFactory) async throws -> MeetingNemotronPhaseResult
+ ) async throws -> MeetingNemotronPhaseResult {
+ // Recheck at open time: the artifact located at plan/readiness time is validated again
+ // before CoreML touches it (plan §5).
+ let artifact = try self.modelLocator.recheck(artifact)
+ // Reference Nemotron streaming configuration (conversion script cadence, kept exact by
+ // the FluidAudio factory; it validates instead of clamping).
+ let config = try SortformerConfig.nemotron(
+ spkcacheUpdatePeriod: 300,
+ spkcacheSilFramesPerSpk: 3,
+ predScoreThreshold: 0.25
+ )
+ let mlConfiguration = MLModelConfiguration()
+ mlConfiguration.computeUnits = .cpuAndGPU
+ let models = try await SortformerModels.load(
+ config: config,
+ mainModelPath: artifact.packageURL,
+ configuration: mlConfiguration
+ )
+ let factory = NemotronDiarizerFactory(config: config, models: models)
+ do {
+ let result = try await body(factory)
+ factory.cleanup()
+ return result
+ } catch {
+ factory.cleanup()
+ throw error
}
+ }
- func withPreparedASR(
- attemptID: UUID,
- configuration: MeetingFinalProcessingConfiguration,
- body: @escaping @Sendable (any MeetingParakeetASRSession) async throws -> MeetingParakeetPhaseResult
- ) async throws -> MeetingParakeetPhaseResult {
- let asrService = await self.asrServiceProvider()
- return try await asrService.withPreparedMeetingASR(
- attemptID: attemptID,
- configuration: configuration
- ) { provider in
- let session = PreparedParakeetASRSession(asrService: asrService, provider: provider)
- // ASRService runs this scope body on the main actor; the attempt's epoch loop
- // (materialization + model calls) must not live there. Cancellation of the scope
- // cancels this bridging await, which cancels the detached body.
- let work = Task.detached(priority: .userInitiated) { try await body(session) }
- return try await withTaskCancellationHandler {
- try await work.value
- } onCancel: {
- work.cancel()
- }
+ func withPreparedASR(
+ attemptID: UUID,
+ configuration: MeetingFinalProcessingConfiguration,
+ body: @escaping @Sendable (any MeetingParakeetASRSession) async throws -> MeetingParakeetPhaseResult
+ ) async throws -> MeetingParakeetPhaseResult {
+ let asrService = await self.asrServiceProvider()
+ return try await asrService.withPreparedMeetingASR(
+ attemptID: attemptID,
+ configuration: configuration
+ ) { provider in
+ let session = PreparedParakeetASRSession(asrService: asrService, provider: provider)
+ // ASRService runs this scope body on the main actor; the attempt's epoch loop
+ // (materialization + model calls) must not live there. Cancellation of the scope
+ // cancels this bridging await, which cancels the detached body.
+ let work = Task.detached(priority: .userInitiated) { try await body(session) }
+ return try await withTaskCancellationHandler {
+ try await work.value
+ } onCancel: {
+ work.cancel()
}
}
}
+}
#else
- /// Non-Apple-Silicon stub: the FluidAudio runtime stack is arm64-only in this app, so the
- /// capability refuses rather than partially working.
- final nonisolated class MeetingParakeetNemotronRuntime: MeetingParakeetNemotronRunning {
- init(
- asrServiceProvider _: @escaping @MainActor () -> ASRService,
- modelLocator _: any MeetingNemotronModelLocating
- ) {}
-
- func withNemotronDiarization(
- artifact _: MeetingNemotronModelArtifact,
- _: @escaping @Sendable (any MeetingNemotronDiarizerFactory) async throws -> MeetingNemotronPhaseResult
- ) async throws -> MeetingNemotronPhaseResult {
- throw MeetingParakeetNemotronRuntimeError.unsupportedArchitecture
- }
+/// Non-Apple-Silicon stub: the FluidAudio runtime stack is arm64-only in this app, so the
+/// capability refuses rather than partially working.
+final nonisolated class MeetingParakeetNemotronRuntime: MeetingParakeetNemotronRunning {
+ init(
+ asrServiceProvider _: @escaping @MainActor () -> ASRService,
+ modelLocator _: any MeetingNemotronModelLocating
+ ) {}
+
+ func withNemotronDiarization(
+ artifact _: MeetingNemotronModelArtifact,
+ _: @escaping @Sendable (any MeetingNemotronDiarizerFactory) async throws -> MeetingNemotronPhaseResult
+ ) async throws -> MeetingNemotronPhaseResult {
+ throw MeetingParakeetNemotronRuntimeError.unsupportedArchitecture
+ }
- func withPreparedASR(
- attemptID _: UUID,
- configuration _: MeetingFinalProcessingConfiguration,
- body _: @escaping @Sendable (any MeetingParakeetASRSession) async throws -> MeetingParakeetPhaseResult
- ) async throws -> MeetingParakeetPhaseResult {
- throw MeetingParakeetNemotronRuntimeError.unsupportedArchitecture
- }
+ func withPreparedASR(
+ attemptID _: UUID,
+ configuration _: MeetingFinalProcessingConfiguration,
+ body _: @escaping @Sendable (any MeetingParakeetASRSession) async throws -> MeetingParakeetPhaseResult
+ ) async throws -> MeetingParakeetPhaseResult {
+ throw MeetingParakeetNemotronRuntimeError.unsupportedArchitecture
}
+}
#endif
diff --git a/Sources/Fluid/Services/Meeting/Backend/MeetingUnitEchoVerdictProvider.swift b/Sources/Fluid/Services/Meeting/Backend/MeetingUnitEchoVerdictProvider.swift
index 66b988a7..dfebd96d 100644
--- a/Sources/Fluid/Services/Meeting/Backend/MeetingUnitEchoVerdictProvider.swift
+++ b/Sources/Fluid/Services/Meeting/Backend/MeetingUnitEchoVerdictProvider.swift
@@ -24,8 +24,6 @@ nonisolated protocol MeetingUnitEchoVerdictProviding: Sendable {
/// with `missingEchoVerdict`, so canonical online output can never be published on absent echo
/// evidence.
nonisolated struct MeetingFailClosedEchoVerdictProvider: MeetingUnitEchoVerdictProviding {
- init() {}
-
func echoVerdicts(
for _: MeetingFinalTranscriptEvidence,
manifest _: MeetingAnalysisManifest,
@@ -113,7 +111,7 @@ nonisolated struct MeetingTextOverlapEchoVerdictProvider: MeetingUnitEchoVerdict
let micContext = microphoneUnits.filter {
$0.unit.trackID == mic.unit.trackID
&& min($0.presentation.end, context.end)
- - max($0.presentation.start, context.start) > self.tolerance
+ - max($0.presentation.start, context.start) > self.tolerance
}.sorted {
($0.presentation.start, $0.presentation.end, $0.unit.id)
< ($1.presentation.start, $1.presentation.end, $1.unit.id)
@@ -144,5 +142,4 @@ nonisolated struct MeetingTextOverlapEchoVerdictProvider: MeetingUnitEchoVerdict
}
return verdicts
}
-
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingASRPreparationOwner.swift b/Sources/Fluid/Services/Meeting/MeetingASRPreparationOwner.swift
index ea627671..bfae9271 100644
--- a/Sources/Fluid/Services/Meeting/MeetingASRPreparationOwner.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingASRPreparationOwner.swift
@@ -68,10 +68,10 @@ final class MeetingASRPreparationOwner {
@escaping (ModelPreparationProgress) -> Void
) async throws -> Void
private let drainExecutor: @MainActor (ASRActivityLease) async -> Void
-#if DEBUG
+ #if DEBUG
var didMarkReadyForTesting: (@MainActor () -> Void)?
var didBeginWaitingForTesting: (@MainActor () -> Void)?
-#endif
+ #endif
private var slot: Slot?
private var drainTask: Task<Void, Never>?
@@ -137,7 +137,8 @@ final class MeetingASRPreparationOwner {
guard self.drainTask == nil,
self.isActiveLease(lease),
self.slot?.claimToken == token,
- self.slot?.task?.isCancelled == false else {
+ self.slot?.task?.isCancelled == false
+ else {
throw CancellationError()
}
return provider
@@ -157,7 +158,7 @@ final class MeetingASRPreparationOwner {
lease: lease, operationID: operationID, progress: progress
)
let token = MeetingASRPreparationClaimToken(lease: lease, operationID: operationID)
- let task = Task { @MainActor [weak self] () throws -> Void in
+ let task = Task { @MainActor [weak self] () throws in
guard let self else { throw CancellationError() }
try await self.performPreparation(
lease: lease,
@@ -190,9 +191,9 @@ final class MeetingASRPreparationOwner {
) async throws -> any TranscriptionProvider {
do {
try await withTaskCancellationHandler {
-#if DEBUG
+ #if DEBUG
self.didBeginWaitingForTesting?()
-#endif
+ #endif
try await task.value
} onCancel: {
task.cancel()
@@ -230,9 +231,9 @@ final class MeetingASRPreparationOwner {
try self.recheck(lease: lease, operationID: operationID)
guard self.slot?.operationID == operationID else { throw CancellationError() }
self.markReady(operationID: operationID)
-#if DEBUG
+ #if DEBUG
self.didMarkReadyForTesting?()
-#endif
+ #endif
}
private func recheck(lease: ASRActivityLease, operationID: UUID) throws {
diff --git a/Sources/Fluid/Services/Meeting/MeetingAudioAsset.swift b/Sources/Fluid/Services/Meeting/MeetingAudioAsset.swift
index 68ede981..ab57ef29 100644
--- a/Sources/Fluid/Services/Meeting/MeetingAudioAsset.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingAudioAsset.swift
@@ -8,14 +8,19 @@ nonisolated enum MeetingAudioAssetRole: Equatable, Sendable {
case unknown(String)
var rawValue: String {
- switch self { case .captureAnalysis: return "captureAnalysis"; case .playbackArchive: return "playbackArchive"; case let .unknown(raw): return raw }
+ switch self {
+ case .captureAnalysis: return "captureAnalysis"
+ case .playbackArchive: return "playbackArchive"
+ case let .unknown(raw): return raw
+ }
}
+
init(rawValue: String) { self = rawValue == "captureAnalysis" ? .captureAnalysis : rawValue == "playbackArchive" ? .playbackArchive : .unknown(rawValue) }
}
nonisolated extension MeetingAudioAssetRole: Codable {
- init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }
- func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }
+ init(from decoder: Decoder) throws { try self.init(rawValue: decoder.singleValueContainer().decode(String.self)) }
+ func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(self.rawValue) }
}
nonisolated enum MeetingAudioEncoding: Equatable, Hashable, Sendable {
@@ -25,16 +30,30 @@ nonisolated enum MeetingAudioEncoding: Equatable, Hashable, Sendable {
case unknown(String)
var rawValue: String {
- switch self { case .linearPCMFloat32CAFV1: return "linearPCMFloat32CAFV1"; case .aacLCM4AV1: return "aacLCM4AV1"; case .legacyAACUnknownPrimingV1: return "legacyAACUnknownPrimingV1"; case let .unknown(raw): return raw }
+ switch self {
+ case .linearPCMFloat32CAFV1: return "linearPCMFloat32CAFV1"
+ case .aacLCM4AV1: return "aacLCM4AV1"
+ case .legacyAACUnknownPrimingV1: return "legacyAACUnknownPrimingV1"
+ case let .unknown(
+ raw
+ ): return raw
+ }
}
+
init(rawValue: String) {
- switch rawValue { case "linearPCMFloat32CAFV1": self = .linearPCMFloat32CAFV1; case "aacLCM4AV1": self = .aacLCM4AV1; case "legacyAACUnknownPrimingV1": self = .legacyAACUnknownPrimingV1; default: self = .unknown(rawValue) }
+ switch rawValue {
+ case "linearPCMFloat32CAFV1": self = .linearPCMFloat32CAFV1
+ case "aacLCM4AV1": self = .aacLCM4AV1
+ case "legacyAACUnknownPrimingV1": self = .legacyAACUnknownPrimingV1
+ default: self =
+ .unknown(rawValue)
+ }
}
}
nonisolated extension MeetingAudioEncoding: Codable {
- init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }
- func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }
+ init(from decoder: Decoder) throws { try self.init(rawValue: decoder.singleValueContainer().decode(String.self)) }
+ func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(self.rawValue) }
}
nonisolated enum MeetingAudioAssetPresence: Equatable, Sendable {
@@ -45,16 +64,29 @@ nonisolated enum MeetingAudioAssetPresence: Equatable, Sendable {
case unknown(String)
var rawValue: String {
- switch self { case .partial: return "partial"; case .ready: return "ready"; case .evicted: return "evicted"; case .failed: return "failed"; case let .unknown(raw): return raw }
+ switch self {
+ case .partial: return "partial"
+ case .ready: return "ready"
+ case .evicted: return "evicted"
+ case .failed: return "failed"
+ case let .unknown(raw): return raw
+ }
}
+
init(rawValue: String) {
- switch rawValue { case "partial": self = .partial; case "ready": self = .ready; case "evicted": self = .evicted; case "failed": self = .failed; default: self = .unknown(rawValue) }
+ switch rawValue {
+ case "partial": self = .partial
+ case "ready": self = .ready
+ case "evicted": self = .evicted
+ case "failed": self = .failed
+ default: self = .unknown(rawValue)
+ }
}
}
nonisolated extension MeetingAudioAssetPresence: Codable {
- init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }
- func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }
+ init(from decoder: Decoder) throws { try self.init(rawValue: decoder.singleValueContainer().decode(String.self)) }
+ func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(self.rawValue) }
}
nonisolated struct MeetingAudioAsset: Codable, Equatable, Sendable {
@@ -69,9 +101,18 @@ nonisolated struct MeetingAudioAsset: Codable, Equatable, Sendable {
var frameCount: Int64?
var sourceAssetSHA256: String?
- init(role: MeetingAudioAssetRole, encoding: MeetingAudioEncoding, presence: MeetingAudioAssetPresence,
- relativeFilePath: String, byteCount: Int64, sha256: String? = nil, sampleRate: Double? = nil,
- channelCount: Int? = nil, frameCount: Int64? = nil, sourceAssetSHA256: String? = nil) {
+ init(
+ role: MeetingAudioAssetRole,
+ encoding: MeetingAudioEncoding,
+ presence: MeetingAudioAssetPresence,
+ relativeFilePath: String,
+ byteCount: Int64,
+ sha256: String? = nil,
+ sampleRate: Double? = nil,
+ channelCount: Int? = nil,
+ frameCount: Int64? = nil,
+ sourceAssetSHA256: String? = nil
+ ) {
self.role = role; self.encoding = encoding; self.presence = presence; self.relativeFilePath = relativeFilePath; self.byteCount = byteCount
self.sha256 = sha256; self.sampleRate = sampleRate; self.channelCount = channelCount; self.frameCount = frameCount; self.sourceAssetSHA256 = sourceAssetSHA256
}
@@ -84,9 +125,9 @@ nonisolated struct MeetingAudioAsset: Codable, Equatable, Sendable {
if case let .unknown(raw) = encoding { issues.append(.unknownEncoding(raw)) }
if case let .unknown(raw) = presence { issues.append(.unknownPresence(raw)) }
guard issues.isEmpty else { return issues }
- if relativeFilePath.isEmpty { issues.append(.emptyRelativeFilePath) }
- if byteCount < 0 { issues.append(.negativeByteCount) }
- switch (role, encoding) {
+ if self.relativeFilePath.isEmpty { issues.append(.emptyRelativeFilePath) }
+ if self.byteCount < 0 { issues.append(.negativeByteCount) }
+ switch (self.role, self.encoding) {
case (.captureAnalysis, .linearPCMFloat32CAFV1): break
case (.playbackArchive, .aacLCM4AV1): break
case (.playbackArchive, .legacyAACUnknownPrimingV1): break
@@ -94,13 +135,13 @@ nonisolated struct MeetingAudioAsset: Codable, Equatable, Sendable {
case (.playbackArchive, .linearPCMFloat32CAFV1): issues.append(.encodingRoleContradiction)
default: break
}
- if presence == .ready {
- if byteCount <= 0 { issues.append(.readyAssetMissingBytes) }
- if encoding == .legacyAACUnknownPrimingV1 { return issues }
- if sha256?.isEmpty != false { issues.append(.readyAssetMissingHash) }
- if sampleRate == nil || !(sampleRate?.isFinite ?? false) || (sampleRate ?? 0) <= 0 { issues.append(.readyAssetMissingSampleRate) }
- if channelCount == nil || (channelCount ?? 0) <= 0 { issues.append(.readyAssetMissingChannelCount) }
- if frameCount == nil || (frameCount ?? 0) <= 0 { issues.append(.readyAssetMissingFrameCount) }
+ if self.presence == .ready {
+ if self.byteCount <= 0 { issues.append(.readyAssetMissingBytes) }
+ if self.encoding == .legacyAACUnknownPrimingV1 { return issues }
+ if self.sha256?.isEmpty != false { issues.append(.readyAssetMissingHash) }
+ if self.sampleRate == nil || !(self.sampleRate?.isFinite ?? false) || (self.sampleRate ?? 0) <= 0 { issues.append(.readyAssetMissingSampleRate) }
+ if self.channelCount == nil || (self.channelCount ?? 0) <= 0 { issues.append(.readyAssetMissingChannelCount) }
+ if self.frameCount == nil || (self.frameCount ?? 0) <= 0 { issues.append(.readyAssetMissingFrameCount) }
}
return issues
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingAudioChunkLedger.swift b/Sources/Fluid/Services/Meeting/MeetingAudioChunkLedger.swift
index 8bcf0edd..b04aaeb7 100644
--- a/Sources/Fluid/Services/Meeting/MeetingAudioChunkLedger.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingAudioChunkLedger.swift
@@ -28,13 +28,20 @@ nonisolated enum MeetingAudioChunkLedgerTerminalStatus: Equatable, Sendable {
case failed
case unknown(String)
- var rawValue: String { switch self { case .ready: return "ready"; case .failed: return "failed"; case let .unknown(raw): return raw } }
+ var rawValue: String {
+ switch self {
+ case .ready: return "ready"
+ case .failed: return "failed"
+ case let .unknown(raw): return raw
+ }
+ }
+
init(rawValue: String) { self = rawValue == "ready" ? .ready : rawValue == "failed" ? .failed : .unknown(rawValue) }
}
nonisolated extension MeetingAudioChunkLedgerTerminalStatus: Codable {
- init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }
- func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }
+ init(from decoder: Decoder) throws { try self.init(rawValue: decoder.singleValueContainer().decode(String.self)) }
+ func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(self.rawValue) }
}
nonisolated struct MeetingAudioChunkLedgerTerminal: Codable, Equatable, Sendable {
@@ -58,22 +65,22 @@ nonisolated enum MeetingAudioChunkLedgerError: Error, Equatable, Sendable {
/// be called by a real-time callback. Intent is immutable/no-overwrite; checkpoints are atomic
/// replacements; terminal status is immutable/no-overwrite. Every record is fsynced before its
/// rename and the containing directory is fsynced after publication.
-nonisolated final class MeetingAudioChunkLedgerStore: @unchecked Sendable {
+final nonisolated class MeetingAudioChunkLedgerStore: @unchecked Sendable {
let sessionDirectory: URL
private let ledgerDirectoryName = "chunk-ledger"
init(sessionDirectory: URL) { self.sessionDirectory = sessionDirectory.standardizedFileURL }
func writeIntent(_ intent: MeetingAudioChunkLedgerIntent) throws {
- try validate(intent.partialRelativeFilePath)
- try ensureLedgerDirectory()
+ try self.validate(intent.partialRelativeFilePath)
+ try self.ensureLedgerDirectory()
let url = try recordURL(chunkID: intent.chunkID, suffix: "intent")
- try writeImmutable(try encode(intent), to: url, conflict: .conflictingIntent)
+ try self.writeImmutable(self.encode(intent), to: url, conflict: .conflictingIntent)
}
func writeCheckpoint(_ checkpoint: MeetingAudioChunkLedgerCheckpoint, for chunkID: MeetingAudioChunkID) throws {
guard checkpoint.chunkID == chunkID else { throw MeetingAudioChunkLedgerError.invalidChunkID }
- guard try readIntent(for: chunkID) != nil else {
+ guard try self.readIntent(for: chunkID) != nil else {
throw MeetingAudioChunkLedgerError.durabilityFailure("checkpoint has no intent")
}
guard checkpoint.expectedFrames >= 0, checkpoint.writtenFrames >= 0,
@@ -87,13 +94,13 @@ nonisolated final class MeetingAudioChunkLedgerStore: @unchecked Sendable {
Self.isNondecreasing(previous.lastCanonicalPTS, checkpoint.lastCanonicalPTS)
else { throw MeetingAudioChunkLedgerError.checkpointRegression }
}
- try ensureLedgerDirectory()
- try writeReplacing(try encode(checkpoint), to: try recordURL(chunkID: chunkID, suffix: "checkpoint"))
+ try self.ensureLedgerDirectory()
+ try self.writeReplacing(self.encode(checkpoint), to: self.recordURL(chunkID: chunkID, suffix: "checkpoint"))
}
func writeTerminal(_ terminal: MeetingAudioChunkLedgerTerminal, for chunkID: MeetingAudioChunkID) throws {
guard terminal.chunkID == chunkID else { throw MeetingAudioChunkLedgerError.invalidChunkID }
- guard try readIntent(for: chunkID) != nil else {
+ guard try self.readIntent(for: chunkID) != nil else {
throw MeetingAudioChunkLedgerError.durabilityFailure("terminal has no intent")
}
if terminal.status == .ready {
@@ -102,28 +109,39 @@ nonisolated final class MeetingAudioChunkLedgerStore: @unchecked Sendable {
checkpoint.expectedFrames == checkpoint.writtenFrames
else { throw MeetingAudioChunkLedgerError.incompleteReadyTerminal }
}
- try ensureLedgerDirectory()
- try writeImmutable(try encode(terminal), to: try recordURL(chunkID: chunkID, suffix: "terminal"), conflict: .terminalAlreadyExists)
+ try self.ensureLedgerDirectory()
+ try self.writeImmutable(self.encode(terminal), to: self.recordURL(chunkID: chunkID, suffix: "terminal"), conflict: .terminalAlreadyExists)
}
- func readIntent(for chunkID: MeetingAudioChunkID) throws -> MeetingAudioChunkLedgerIntent? { try read(MeetingAudioChunkLedgerIntent.self, at: try recordURL(chunkID: chunkID, suffix: "intent")) }
- func readCheckpoint(for chunkID: MeetingAudioChunkID) throws -> MeetingAudioChunkLedgerCheckpoint? { try read(MeetingAudioChunkLedgerCheckpoint.self, at: try recordURL(chunkID: chunkID, suffix: "checkpoint")) }
- func readTerminal(for chunkID: MeetingAudioChunkID) throws -> MeetingAudioChunkLedgerTerminal? { try read(MeetingAudioChunkLedgerTerminal.self, at: try recordURL(chunkID: chunkID, suffix: "terminal")) }
+ func readIntent(for chunkID: MeetingAudioChunkID) throws -> MeetingAudioChunkLedgerIntent? { try self.read(
+ MeetingAudioChunkLedgerIntent.self,
+ at: self.recordURL(chunkID: chunkID, suffix: "intent")
+ ) }
+ func readCheckpoint(for chunkID: MeetingAudioChunkID) throws -> MeetingAudioChunkLedgerCheckpoint? { try self.read(
+ MeetingAudioChunkLedgerCheckpoint.self,
+ at: self.recordURL(chunkID: chunkID, suffix: "checkpoint")
+ ) }
+ func readTerminal(for chunkID: MeetingAudioChunkID) throws -> MeetingAudioChunkLedgerTerminal? { try self.read(
+ MeetingAudioChunkLedgerTerminal.self,
+ at: self.recordURL(chunkID: chunkID, suffix: "terminal")
+ ) }
private func validate(_ relative: String) throws {
let parts = relative.split(separator: "/", omittingEmptySubsequences: false)
guard !relative.isEmpty, !relative.hasPrefix("/"), !parts.isEmpty, parts.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }) else { throw MeetingAudioChunkLedgerError.pathRejected }
}
+
private func recordURL(chunkID: UUID, suffix: String) throws -> URL {
- let directory = sessionDirectory.appendingPathComponent(ledgerDirectoryName, isDirectory: true)
+ let directory = self.sessionDirectory.appendingPathComponent(self.ledgerDirectoryName, isDirectory: true)
return directory.appendingPathComponent("\(chunkID.uuidString).\(suffix).json")
}
+
private func ensureLedgerDirectory() throws {
var rootInfo = stat()
- guard lstat(sessionDirectory.path, &rootInfo) == 0,
+ guard lstat(self.sessionDirectory.path, &rootInfo) == 0,
(rootInfo.st_mode & S_IFMT) == S_IFDIR
else { throw MeetingAudioChunkLedgerError.pathRejected }
- let directory = sessionDirectory.appendingPathComponent(ledgerDirectoryName, isDirectory: true)
+ let directory = self.sessionDirectory.appendingPathComponent(self.ledgerDirectoryName, isDirectory: true)
var directoryInfo = stat()
if lstat(directory.path, &directoryInfo) == 0 {
guard (directoryInfo.st_mode & S_IFMT) == S_IFDIR else {
@@ -141,21 +159,33 @@ nonisolated final class MeetingAudioChunkLedgerStore: @unchecked Sendable {
throw MeetingAudioChunkLedgerError.durabilityFailure("chmod directory")
}
}
+
private static func isNondecreasing(_ previous: MeetingMediaTime?, _ next: MeetingMediaTime?) -> Bool {
guard let previous else { return true }
guard let next else { return false }
return next.seconds >= previous.seconds
}
- private func encode<T: Encodable>(_ value: T) throws -> Data { let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .iso8601; encoder.outputFormatting = [.sortedKeys]; return try encoder.encode(value) }
- private func read<T: Decodable>(_ type: T.Type, at url: URL) throws -> T? { guard FileManager.default.fileExists(atPath: url.path) else { return nil }; let decoder = JSONDecoder(); decoder.dateDecodingStrategy = .iso8601; return try decoder.decode(type, from: Data(contentsOf: url, options: .mappedIfSafe)) }
+
+ private func encode<T: Encodable>(_ value: T) throws -> Data { let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .iso8601; encoder.outputFormatting = [.sortedKeys]; return try encoder
+ .encode(value)
+ }
+
+ private func read<T: Decodable>(_ type: T.Type, at url: URL) throws -> T? { guard FileManager.default.fileExists(atPath: url.path)
+ else { return nil }; let decoder = JSONDecoder(); decoder.dateDecodingStrategy = .iso8601; return try decoder.decode(
+ type,
+ from: Data(contentsOf: url, options: .mappedIfSafe)
+ )
+ }
+
private func writeImmutable(_ data: Data, to destination: URL, conflict: MeetingAudioChunkLedgerError) throws {
if FileManager.default.fileExists(atPath: destination.path) {
guard (try? Data(contentsOf: destination)) == data else { throw conflict }
return
}
- try writeTemp(data, destination: destination, exclusive: true, conflict: conflict)
+ try self.writeTemp(data, destination: destination, exclusive: true, conflict: conflict)
}
- private func writeReplacing(_ data: Data, to destination: URL) throws { try writeTemp(data, destination: destination, exclusive: false) }
+
+ private func writeReplacing(_ data: Data, to destination: URL) throws { try self.writeTemp(data, destination: destination, exclusive: false) }
private func writeTemp(_ data: Data, destination: URL, exclusive: Bool, conflict: MeetingAudioChunkLedgerError? = nil) throws {
let temp = destination.deletingLastPathComponent().appendingPathComponent(".\(destination.lastPathComponent).\(UUID().uuidString).tmp")
try data.write(to: temp, options: [])
@@ -163,7 +193,13 @@ nonisolated final class MeetingAudioChunkLedgerStore: @unchecked Sendable {
let fd = open(temp.path, O_RDONLY); guard fd >= 0 else { try? FileManager.default.removeItem(at: temp); throw MeetingAudioChunkLedgerError.durabilityFailure("open") }; defer { close(fd) }
guard fcntl(fd, F_FULLFSYNC) == 0 else { try? FileManager.default.removeItem(at: temp); throw MeetingAudioChunkLedgerError.durabilityFailure("F_FULLFSYNC") }
let flags = exclusive ? UInt32(RENAME_EXCL) : 0
- guard renameatx_np(AT_FDCWD, temp.path, AT_FDCWD, destination.path, flags) == 0 else { let e = errno; try? FileManager.default.removeItem(at: temp); if exclusive && e == EEXIST { throw conflict ?? .terminalAlreadyExists }; throw MeetingAudioChunkLedgerError.durabilityFailure("rename errno \(e)") }
- let dirFD = open(destination.deletingLastPathComponent().path, O_RDONLY | O_DIRECTORY); guard dirFD >= 0 else { throw MeetingAudioChunkLedgerError.durabilityFailure("open directory") }; defer { close(dirFD) }; guard fsync(dirFD) == 0 else { throw MeetingAudioChunkLedgerError.durabilityFailure("directory fsync") }
+ guard renameatx_np(AT_FDCWD, temp.path, AT_FDCWD, destination.path, flags) == 0
+ else { let e = errno; try? FileManager.default.removeItem(at: temp); if exclusive,
+ e == EEXIST { throw conflict ?? .terminalAlreadyExists }; throw MeetingAudioChunkLedgerError
+ .durabilityFailure("rename errno \(e)")
+ }
+ let dirFD = open(destination.deletingLastPathComponent().path, O_RDONLY | O_DIRECTORY); guard dirFD >= 0
+ else { throw MeetingAudioChunkLedgerError.durabilityFailure("open directory") }; defer { close(dirFD) }; guard fsync(dirFD) == 0
+ else { throw MeetingAudioChunkLedgerError.durabilityFailure("directory fsync") }
}
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift b/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift
index b31cb70c..f0e90151 100644
--- a/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingAutoDetectSignals.swift
@@ -87,6 +87,8 @@ nonisolated struct AudioProcessActivitySnapshot: Sendable, Equatable {
/// only when the live executable is contained in the owning app bundle after symlink resolution.
/// Ambiguous, missing, or malformed data is deliberately rejected.
nonisolated enum MeetingAudioProcessResolver {
+ // nil means unavailable; an empty result means available with no values.
+ // swiftlint:disable:next discouraged_optional_collection
static func activeOwnerInputByPID(snapshot: AudioProcessActivitySnapshot) -> [Int32: Bool]? {
guard snapshot.queryState == .valid else { return nil }
var matches: [Int32: Bool] = [:]
@@ -214,7 +216,9 @@ final class WorkspaceEventsMonitor: WorkspaceEventsProviding {
func stop() {
let center = NSWorkspace.shared.notificationCenter
- for observer in self.observers { center.removeObserver(observer) }
+ for observer in self.observers {
+ center.removeObserver(observer)
+ }
self.observers = []
}
@@ -289,7 +293,7 @@ final class CoreAudioMicActivitySignal: MicActivitySignalProviding {
}
}
- nonisolated private static var devicesAddress: AudioObjectPropertyAddress {
+ private nonisolated static var devicesAddress: AudioObjectPropertyAddress {
AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDevices,
mScope: kAudioObjectPropertyScopeGlobal,
@@ -297,7 +301,7 @@ final class CoreAudioMicActivitySignal: MicActivitySignalProviding {
)
}
- nonisolated private static var runningSomewhereAddress: AudioObjectPropertyAddress {
+ private nonisolated static var runningSomewhereAddress: AudioObjectPropertyAddress {
AudioObjectPropertyAddress(
mSelector: kAudioDevicePropertyDeviceIsRunningSomewhere,
mScope: kAudioObjectPropertyScopeGlobal,
@@ -305,7 +309,7 @@ final class CoreAudioMicActivitySignal: MicActivitySignalProviding {
)
}
- nonisolated private static var serviceRestartedAddress: AudioObjectPropertyAddress {
+ private nonisolated static var serviceRestartedAddress: AudioObjectPropertyAddress {
AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyServiceRestarted,
mScope: kAudioObjectPropertyScopeGlobal,
@@ -327,8 +331,24 @@ final class CoreAudioMicActivitySignal: MicActivitySignalProviding {
let address = Self.devicesAddress
let token: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
#if DEBUG
- AudioTopologyDiagnostics.record(.callbackBegin, owner: .meetingDetector, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDevices, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainDelivery)
- defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .meetingDetector, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDevices, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainDelivery) }
+ AudioTopologyDiagnostics.record(
+ .callbackBegin,
+ owner: .meetingDetector,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDevices,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainDelivery
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .callbackEnd,
+ owner: .meetingDetector,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDevices,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainDelivery
+ ) }
#endif
guard let signal = self else { return }
MeetingMicrophoneEventExecution.afterHALCallback {
@@ -365,13 +385,32 @@ final class CoreAudioMicActivitySignal: MicActivitySignalProviding {
}
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .meetingDetector, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .listenerAddBegin,
+ owner: .meetingDetector,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener
+ )
#endif
let status = await AudioTopologyListenerExecution.add(
objectID: AudioObjectID(kAudioObjectSystemObject), address: address, token: token
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .meetingDetector, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status)
+ AudioTopologyDiagnostics.record(
+ .listenerAddEnd,
+ owner: .meetingDetector,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status
+ )
#endif
if status == noErr, self.isCurrent(generation) {
self.deviceListToken = token
@@ -429,13 +468,31 @@ final class CoreAudioMicActivitySignal: MicActivitySignalProviding {
else { return }
self.listenerEpoch &+= 1
let identity = ListenerIdentity(
- deviceID: device.id, uid: device.uid,
- listenerEpoch: self.listenerEpoch, lifecycleGeneration: generation
+ deviceID: device.id,
+ uid: device.uid,
+ listenerEpoch: self.listenerEpoch,
+ lifecycleGeneration: generation
)
let token: AudioObjectPropertyListenerBlock = { [weak self] _, _ in
#if DEBUG
- AudioTopologyDiagnostics.record(.callbackBegin, owner: .meetingDetector, objectID: device.id, selector: kAudioDevicePropertyDeviceIsRunningSomewhere, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainDelivery)
- defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .meetingDetector, objectID: device.id, selector: kAudioDevicePropertyDeviceIsRunningSomewhere, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .mainDelivery) }
+ AudioTopologyDiagnostics.record(
+ .callbackBegin,
+ owner: .meetingDetector,
+ objectID: device.id,
+ selector: kAudioDevicePropertyDeviceIsRunningSomewhere,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainDelivery
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .callbackEnd,
+ owner: .meetingDetector,
+ objectID: device.id,
+ selector: kAudioDevicePropertyDeviceIsRunningSomewhere,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .mainDelivery
+ ) }
#endif
guard let signal = self else { return }
MeetingMicrophoneEventExecution.afterHALCallback {
@@ -445,13 +502,32 @@ final class CoreAudioMicActivitySignal: MicActivitySignalProviding {
}
}
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .meetingDetector, objectID: device.id, selector: Self.runningSomewhereAddress.mSelector, scope: Self.runningSomewhereAddress.mScope, element: Self.runningSomewhereAddress.mElement, queueRole: .dedicatedControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .listenerAddBegin,
+ owner: .meetingDetector,
+ objectID: device.id,
+ selector: Self.runningSomewhereAddress.mSelector,
+ scope: Self.runningSomewhereAddress.mScope,
+ element: Self.runningSomewhereAddress.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener
+ )
#endif
let status = await AudioTopologyListenerExecution.add(
objectID: device.id, address: Self.runningSomewhereAddress, token: token
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .meetingDetector, objectID: device.id, selector: Self.runningSomewhereAddress.mSelector, scope: Self.runningSomewhereAddress.mScope, element: Self.runningSomewhereAddress.mElement, queueRole: .dedicatedControl, phase: .listener, status: status)
+ AudioTopologyDiagnostics.record(
+ .listenerAddEnd,
+ owner: .meetingDetector,
+ objectID: device.id,
+ selector: Self.runningSomewhereAddress.mSelector,
+ scope: Self.runningSomewhereAddress.mScope,
+ element: Self.runningSomewhereAddress.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status
+ )
#endif
guard status == noErr else { continue }
guard self.isCurrent(generation), self.reconciliationEpoch == reconciliation,
@@ -491,11 +567,30 @@ final class CoreAudioMicActivitySignal: MicActivitySignalProviding {
var value: UInt32 = 0
var size = UInt32(MemoryLayout<UInt32>.size)
#if DEBUG
- AudioTopologyDiagnostics.record(.halQueryBegin, owner: .meetingDetector, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .halQueryBegin,
+ owner: .meetingDetector,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener
+ )
#endif
let status = AudioObjectGetPropertyData(deviceID, &address, 0, nil, &size, &value)
#if DEBUG
- AudioTopologyDiagnostics.record(.halQueryEnd, owner: .meetingDetector, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status)
+ AudioTopologyDiagnostics.record(
+ .halQueryEnd,
+ owner: .meetingDetector,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status
+ )
#endif
return status == noErr && value != 0
}
@@ -527,7 +622,7 @@ final class CoreAudioMicActivitySignal: MicActivitySignalProviding {
if let deviceListToken {
_ = await AudioTopologyListenerExecution.remove(
objectID: AudioObjectID(kAudioObjectSystemObject),
- address: Self.devicesAddress,
+ address: self.devicesAddress,
token: deviceListToken
)
}
@@ -590,7 +685,7 @@ final class CoreAudioProcessActivityProvider: AudioProcessActivityProviding {
}
}
- nonisolated private static func processID(for objectID: AudioObjectID) -> Int32? {
+ private nonisolated static func processID(for objectID: AudioObjectID) -> Int32? {
var address = AudioObjectPropertyAddress(mSelector: kAudioProcessPropertyPID, mScope: kAudioObjectPropertyScopeGlobal, mElement: kAudioObjectPropertyElementMain)
var pid: pid_t = 0
var size = UInt32(MemoryLayout<pid_t>.size)
@@ -598,14 +693,17 @@ final class CoreAudioProcessActivityProvider: AudioProcessActivityProviding {
return Int32(pid)
}
- nonisolated private static func executablePath(for pid: Int32) -> String? {
+ private nonisolated static func executablePath(for pid: Int32) -> String? {
var buffer = [CChar](repeating: 0, count: Int(PATH_MAX))
let length = proc_pidpath(pid, &buffer, UInt32(buffer.count))
guard length > 0 else { return nil }
return String(cString: buffer)
}
- nonisolated private static func processObjectIDs() -> [AudioObjectID]? {
+ // nil means unavailable; an empty result means available with no values.
+
+ // swiftlint:disable:next discouraged_optional_collection
+ private nonisolated static func processObjectIDs() -> [AudioObjectID]? {
var address = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyProcessObjectList,
mScope: kAudioObjectPropertyScopeGlobal,
@@ -614,27 +712,65 @@ final class CoreAudioProcessActivityProvider: AudioProcessActivityProviding {
var size: UInt32 = 0
let systemObject = AudioObjectID(kAudioObjectSystemObject)
#if DEBUG
- AudioTopologyDiagnostics.record(.halQueryBegin, owner: .meetingDetector, objectID: systemObject, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .halQueryBegin,
+ owner: .meetingDetector,
+ objectID: systemObject,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener
+ )
#endif
let sizeStatus = AudioObjectGetPropertyDataSize(systemObject, &address, 0, nil, &size)
#if DEBUG
- AudioTopologyDiagnostics.record(.halQueryEnd, owner: .meetingDetector, objectID: systemObject, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: sizeStatus)
+ AudioTopologyDiagnostics.record(
+ .halQueryEnd,
+ owner: .meetingDetector,
+ objectID: systemObject,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: sizeStatus
+ )
#endif
guard sizeStatus == noErr, size % UInt32(MemoryLayout<AudioObjectID>.size) == 0 else { return nil }
guard size > 0 else { return [] }
var processIDs = Array(repeating: AudioObjectID(), count: Int(size) / MemoryLayout<AudioObjectID>.size)
#if DEBUG
- AudioTopologyDiagnostics.record(.halQueryBegin, owner: .meetingDetector, objectID: systemObject, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .halQueryBegin,
+ owner: .meetingDetector,
+ objectID: systemObject,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener
+ )
#endif
let dataStatus = AudioObjectGetPropertyData(systemObject, &address, 0, nil, &size, &processIDs)
#if DEBUG
- AudioTopologyDiagnostics.record(.halQueryEnd, owner: .meetingDetector, objectID: systemObject, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: dataStatus)
+ AudioTopologyDiagnostics.record(
+ .halQueryEnd,
+ owner: .meetingDetector,
+ objectID: systemObject,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: dataStatus
+ )
#endif
guard dataStatus == noErr, size % UInt32(MemoryLayout<AudioObjectID>.size) == 0 else { return nil }
return Array(processIDs.prefix(Int(size) / MemoryLayout<AudioObjectID>.size))
}
- nonisolated private static func bundleIdentifier(for processID: AudioObjectID) -> String? {
+ private nonisolated static func bundleIdentifier(for processID: AudioObjectID) -> String? {
var address = AudioObjectPropertyAddress(
mSelector: kAudioProcessPropertyBundleID,
mScope: kAudioObjectPropertyScopeGlobal,
@@ -643,17 +779,36 @@ final class CoreAudioProcessActivityProvider: AudioProcessActivityProviding {
var value: CFString = "" as CFString
var size = UInt32(MemoryLayout<CFString>.size)
#if DEBUG
- AudioTopologyDiagnostics.record(.halQueryBegin, owner: .meetingDetector, objectID: processID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .halQueryBegin,
+ owner: .meetingDetector,
+ objectID: processID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener
+ )
#endif
let status = AudioObjectGetPropertyData(processID, &address, 0, nil, &size, &value)
#if DEBUG
- AudioTopologyDiagnostics.record(.halQueryEnd, owner: .meetingDetector, objectID: processID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status)
+ AudioTopologyDiagnostics.record(
+ .halQueryEnd,
+ owner: .meetingDetector,
+ objectID: processID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status
+ )
#endif
guard status == noErr else { return nil }
return value as String
}
- nonisolated private static func isRunning(_ processID: AudioObjectID, selector: AudioObjectPropertySelector) -> Bool? {
+ private nonisolated static func isRunning(_ processID: AudioObjectID, selector: AudioObjectPropertySelector) -> Bool? {
var address = AudioObjectPropertyAddress(
mSelector: selector,
mScope: kAudioObjectPropertyScopeGlobal,
@@ -662,11 +817,30 @@ final class CoreAudioProcessActivityProvider: AudioProcessActivityProviding {
var value: UInt32 = 0
var size = UInt32(MemoryLayout<UInt32>.size)
#if DEBUG
- AudioTopologyDiagnostics.record(.halQueryBegin, owner: .meetingDetector, objectID: processID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .halQueryBegin,
+ owner: .meetingDetector,
+ objectID: processID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener
+ )
#endif
let status = AudioObjectGetPropertyData(processID, &address, 0, nil, &size, &value)
#if DEBUG
- AudioTopologyDiagnostics.record(.halQueryEnd, owner: .meetingDetector, objectID: processID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener, status: status)
+ AudioTopologyDiagnostics.record(
+ .halQueryEnd,
+ owner: .meetingDetector,
+ objectID: processID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status
+ )
#endif
guard status == noErr, size == MemoryLayout<UInt32>.size else { return nil }
return value != 0
@@ -675,8 +849,8 @@ final class CoreAudioProcessActivityProvider: AudioProcessActivityProviding {
@MainActor
final class CGWindowSnapshotProvider: WindowSnapshotProviding {
- nonisolated private static let axTimeout: Float = 0.25
- nonisolated private static let maxAXWindows = 8
+ private nonisolated static let axTimeout: Float = 0.25
+ private nonisolated static let maxAXWindows = 8
private let axQueue = DispatchQueue(label: "com.fluidvoice.meeting.autodetect.ax-title", qos: .utility)
func snapshot(interestPIDs: Set<Int32>) -> [WindowSnapshot] {
@@ -706,7 +880,8 @@ final class CGWindowSnapshotProvider: WindowSnapshotProviding {
for window in windows.prefix(Self.maxAXWindows) {
var titleValue: CFTypeRef?
if AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleValue) == .success,
- let title = titleValue as? String {
+ let title = titleValue as? String
+ {
titles.append(title)
}
}
@@ -728,7 +903,7 @@ final class AXBrowserTabReader: BrowserTabReading {
private static let maxChildrenPerLevel = 24
/// Upper bound on elements visited per read; keeps a sprawling window from stalling the poll loop.
private static let maxVisitedElements = 300
- nonisolated private static let skippedRoles: Set<String> = ["AXToolbar", "AXMenuBar", "AXMenu", "AXPopUpButton", "AXButton", "AXTextField", "AXStaticText", "AXImage"]
+ private nonisolated static let skippedRoles: Set<String> = ["AXToolbar", "AXMenuBar", "AXMenu", "AXPopUpButton", "AXButton", "AXTextField", "AXStaticText", "AXImage"]
private static let circuitBreakerThreshold = 2
private let queue = DispatchQueue(label: "com.fluidvoice.meeting.autodetect.ax", qos: .utility)
@@ -774,7 +949,7 @@ final class AXBrowserTabReader: BrowserTabReading {
}
/// Off-main: all work here is plain AX API calls bounded by the messaging timeout below.
- nonisolated private static func readFrontmostTabURL(processID: Int32) -> ReadOutcome {
+ private nonisolated static func readFrontmostTabURL(processID: Int32) -> ReadOutcome {
let appElement = AXUIElementCreateApplication(processID)
_ = AXUIElementSetMessagingTimeout(appElement, Self.messagingTimeoutSeconds)
@@ -799,8 +974,8 @@ final class AXBrowserTabReader: BrowserTabReading {
}
/// Depth-first over container roles only; each level checks its own children for a web area first.
- nonisolated private static func findWebAreaURL(root: AXUIElement, depth: Int, budget: inout Int, timedOut: inout Bool) -> BrowserTabURL? {
- guard depth < Self.maxDepth, budget > 0 else { return nil }
+ private nonisolated static func findWebAreaURL(root: AXUIElement, depth: Int, budget: inout Int, timedOut: inout Bool) -> BrowserTabURL? {
+ guard depth < self.maxDepth, budget > 0 else { return nil }
var childrenValue: CFTypeRef?
let status = AXUIElementCopyAttributeValue(root, kAXChildrenAttribute as CFString, &childrenValue)
if status == .cannotComplete { timedOut = true; return nil }
@@ -828,7 +1003,7 @@ final class AXBrowserTabReader: BrowserTabReading {
return nil
}
- nonisolated private static func stringAttribute(_ element: AXUIElement, attribute: String) -> String? {
+ private nonisolated static func stringAttribute(_ element: AXUIElement, attribute: String) -> String? {
var value: CFTypeRef?
let status = AXUIElementCopyAttributeValue(element, attribute as CFString, &value)
guard status == .success else { return nil }
@@ -837,7 +1012,7 @@ final class AXBrowserTabReader: BrowserTabReading {
return nil
}
- nonisolated private static func parse(_ urlString: String) -> BrowserTabURL? {
+ private nonisolated static func parse(_ urlString: String) -> BrowserTabURL? {
guard let components = URLComponents(string: urlString), let host = components.host else { return nil }
return BrowserTabURL(host: host, path: components.path)
}
@@ -879,7 +1054,7 @@ nonisolated enum MeetingStorageReadiness {
static func hasSufficientFreeSpace() -> Bool {
guard let applicationSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first,
let capacity = try? applicationSupport.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
- .volumeAvailableCapacityForImportantUsage
+ .volumeAvailableCapacityForImportantUsage
else { return false }
// Auto-detection can arm an online-call capture, so budget for the largest supported
// topology until the user chooses an explicit in-room mode.
diff --git a/Sources/Fluid/Services/Meeting/MeetingAutoDetector.swift b/Sources/Fluid/Services/Meeting/MeetingAutoDetector.swift
index e0b9864b..d3400371 100644
--- a/Sources/Fluid/Services/Meeting/MeetingAutoDetector.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingAutoDetector.swift
@@ -8,7 +8,7 @@ import Foundation
/// Every ambiguity resolves to no prompt: a false negative here is free, a false positive is not.
@MainActor
final class MeetingAutoDetector {
- // MARK: Tunables (Phase A plan v2)
+ // MARK: - Tunables (Phase A plan v2)
static let coincidenceWindowSeconds: TimeInterval = 30
static let confirmDeadlineSeconds: TimeInterval = 30
@@ -152,7 +152,7 @@ final class MeetingAutoDetector {
self.isBrowserDetectionEnabled = isBrowserDetectionEnabled
}
- // MARK: Lifecycle
+ // MARK: - Lifecycle
func start() {
guard self.pollTask == nil else { return }
@@ -227,7 +227,7 @@ final class MeetingAutoDetector {
for (pid, record) in self.records where record.tier == .browserTier2 {
guard self.isCurrentRun(runGeneration), self.isBrowserDetectionEnabled() else { return }
let lastPoll = self.lastBrowserPollAt[pid]
- guard lastPoll == nil || now.timeIntervalSince(lastPoll!) >= 2 else { continue }
+ guard lastPoll.map { now.timeIntervalSince($0) >= 2 } ?? true else { continue }
let url = await self.browserTabReader.frontmostTabURL(bundleIdentifier: record.bundleIdentifier, processID: pid)
guard self.isCurrentRun(runGeneration), self.isBrowserDetectionEnabled(),
self.records[pid]?.incarnation == record.incarnation
@@ -237,7 +237,7 @@ final class MeetingAutoDetector {
}
}
- // MARK: Workspace events
+ // MARK: - Workspace events
func handleWorkspaceEvent(_ event: WorkspaceEvent, at now: Date) {
guard let tier = MeetingAppRegistry.tier(forBundleIdentifier: event.bundleIdentifier) else { return }
@@ -279,18 +279,16 @@ final class MeetingAutoDetector {
DebugLogger.shared.log("record-armed bundle=\(bundleIdentifier)", source: "MeetingAutoDetector")
}
- // MARK: Mic activity
+ // MARK: - Mic activity
func handleMicEdge(_ edge: MicActivityEdge, at now: Date) {
guard edge.isActive else {
self.lastMicReleaseAt = now
- for pid in self.records.keys {
- if self.records[pid]?.audioEvidenceSource == .device {
- self.records[pid]?.audioEvidenceAt = nil
- self.records[pid]?.audioEvidenceSource = nil
- if let bundleIdentifier = self.records[pid]?.bundleIdentifier {
- DebugLogger.shared.log("audio-evidence-end path=device bundle=\(bundleIdentifier)", source: "MeetingAutoDetector")
- }
+ for pid in self.records.keys where self.records[pid]?.audioEvidenceSource == .device {
+ self.records[pid]?.audioEvidenceAt = nil
+ self.records[pid]?.audioEvidenceSource = nil
+ if let bundleIdentifier = self.records[pid]?.bundleIdentifier {
+ DebugLogger.shared.log("audio-evidence-end path=device bundle=\(bundleIdentifier)", source: "MeetingAutoDetector")
}
}
return
@@ -407,7 +405,7 @@ final class MeetingAutoDetector {
return delta >= -5 && delta <= Self.frontmostLeadSeconds
}
- // MARK: Window evidence (Tier 1)
+ // MARK: - Window evidence (Tier 1)
func handleWindowSnapshot(_ snapshots: [WindowSnapshot], at now: Date) {
for pid in self.records.keys where self.records[pid]?.tier == .nativeTier1 {
@@ -488,7 +486,7 @@ final class MeetingAutoDetector {
self.onHealthChanged?(health)
}
- // MARK: Browser evidence (Tier 2)
+ // MARK: - Browser evidence (Tier 2)
func handleBrowserTabURL(_ url: BrowserTabURL?, pid: Int32, bundleIdentifier: String, at now: Date) {
guard let url, MeetingInCallURLMatcher.isInCallURL(host: url.host, path: url.path) else {
@@ -514,7 +512,7 @@ final class MeetingAutoDetector {
self.attemptConfirm(pid: pid, at: now)
}
- // MARK: Confirm + episode lifecycle
+ // MARK: - Confirm + episode lifecycle
private func attemptConfirm(pid: Int32, at now: Date) {
guard let record = self.records[pid],
@@ -579,7 +577,14 @@ final class MeetingAutoDetector {
DebugLogger.shared.log("confirm-accepted bundle=\(record.bundleIdentifier)", source: "MeetingAutoDetector")
DebugLogger.shared.log("prompt-requested bundle=\(record.bundleIdentifier)", source: "MeetingAutoDetector")
let cta: PromptCTA = readiness == .ready ? .record : .setup
- self.onPromptRequested?(PromptRequest(episodeID: episode.id, bundleIdentifier: episode.bundleIdentifier, pid: pid, tier: episode.tier, cta: cta, serviceName: Self.serviceName(forEvidenceKey: evidenceKey)))
+ self.onPromptRequested?(PromptRequest(
+ episodeID: episode.id,
+ bundleIdentifier: episode.bundleIdentifier,
+ pid: pid,
+ tier: episode.tier,
+ cta: cta,
+ serviceName: Self.serviceName(forEvidenceKey: evidenceKey)
+ ))
}
private func logConfirmRejected(_ reason: String, bundleIdentifier: String) {
@@ -594,7 +599,7 @@ final class MeetingAutoDetector {
}
}
- // MARK: Prompt outcomes
+ // MARK: - Prompt outcomes
enum StartError: LocalizedError, Equatable {
case cannotStart
@@ -686,7 +691,7 @@ final class MeetingAutoDetector {
self.episodesByKey[key] = episode
}
- // MARK: Tick — grace, release, episode teardown, still-recording nudge
+ // MARK: - Tick — grace, release, episode teardown, still-recording nudge
func tick(at now: Date) {
defer { self.publishAutomaticTarget() }
@@ -747,7 +752,7 @@ final class MeetingAutoDetector {
self.onStillRecordingNudge?()
}
- // MARK: Disarm on lock / sleep / fast-user-switch — mic bits are unreliable across these.
+ // MARK: - Disarm on lock / sleep / fast-user-switch — mic bits are unreliable across these.
func disarmAndClearTransientState() {
self.audioQueryUnknown = false
diff --git a/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift b/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift
index 6166aa75..f04b8ee6 100644
--- a/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingCaptureEngine.swift
@@ -1,3 +1,5 @@
+// Keep the existing capture lifecycle together during integration.
+// swiftlint:disable file_length
import AppKit
@preconcurrency import AVFoundation
import CoreAudio
@@ -79,11 +81,11 @@ actor MeetingCaptureEngine: MeetingCaptureControlling {
else { throw MeetingCaptureError.applicationNotSelected }
let outputRoute = Self.currentOutputRouteSnapshot()
-#if DEBUG
+ #if DEBUG
let forcePairedScreenCaptureKit = MeetingSCKPairedDiagnosticGate.enabled()
-#else
+ #else
let forcePairedScreenCaptureKit = false
-#endif
+ #endif
let preferDirectAEC3 = MeetingDirectAEC3Gate.enabled()
let decision = MeetingCapturePathDecider.decide(
mode: configuration.mode,
@@ -95,12 +97,12 @@ actor MeetingCaptureEngine: MeetingCaptureControlling {
switch decision {
case let .screenCaptureKit(reason):
if reason == MeetingCapturePathDecider.directAEC3DefaultReason {
-#if DEBUG
+ #if DEBUG
DebugLogger.shared.log(
"Direct AEC3 selected for the built-in-speaker pre-production path.",
source: "MeetingCaptureEngine"
)
-#endif
+ #endif
} else {
let captureDecisionMessage = reason == MeetingCapturePathDecider.diagnosticForceScreenCaptureKitReason
? "C2 diagnostic forced paired ScreenCaptureKit; this is not a production fallback."
@@ -179,7 +181,9 @@ actor MeetingCaptureEngine: MeetingCaptureControlling {
group.addTask { await writer.snapshot() }
}
var result: [MeetingAudioTrack] = []
- for await track in group { result.append(track) }
+ for await track in group {
+ result.append(track)
+ }
return result.sorted { $0.kind.rawValue < $1.kind.rawValue }
}
return MeetingCaptureStartResult(
@@ -381,6 +385,8 @@ actor MeetingCaptureEngine: MeetingCaptureControlling {
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 [] }
@@ -499,7 +505,7 @@ nonisolated enum MeetingCaptureOwnershipGate {
currentRevision: UInt64,
stopping: Bool
) -> Bool {
- !stopping && !Self.isSuperseded(observedRevision: taskRevision, currentRevision: currentRevision)
+ !stopping && !self.isSuperseded(observedRevision: taskRevision, currentRevision: currentRevision)
}
/// The replacement may only be published when the runtime still owns exactly the producers the
@@ -513,7 +519,7 @@ nonisolated enum MeetingCaptureOwnershipGate {
ownsPendingCandidate: Bool
) -> MeetingCaptureStreamPublication {
guard !stopping else { return .superseded }
- guard !Self.isSuperseded(observedRevision: authorizedRevision, currentRevision: currentRevision) else {
+ guard !self.isSuperseded(observedRevision: authorizedRevision, currentRevision: currentRevision) else {
return .superseded
}
guard !candidateFailed else { return .failed }
@@ -521,8 +527,10 @@ nonisolated enum MeetingCaptureOwnershipGate {
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.
+ // 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,
@@ -550,7 +558,7 @@ nonisolated enum MeetingDirectAEC3Availability {
}
static func isAvailable(environment: [String: String] = ProcessInfo.processInfo.environment) -> Bool {
- Self.isAvailable(
+ self.isAvailable(
killSwitchEngaged: !MeetingDirectAEC3Gate.enabled(environment: environment)
)
}
@@ -586,11 +594,13 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa
qos: .userInteractive
)
private let callbackQueueKey = DispatchSpecificKey<UInt8>()
-#if DEBUG
+ #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
+ #endif
private let stateLock = NSLock()
private var stream: SCStream
/// The device actually bound into the current SCK producer epoch. The requested microphone is
@@ -656,9 +666,9 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa
self.microphoneWriter = microphoneWriter
self.eventHandler = eventHandler
self.liveAudioHandler = liveAudioHandler
-#if DEBUG
+ #if DEBUG
self.pairedDiagnosticCollector = MeetingSCKPairedDiagnosticCollector()
-#endif
+ #endif
super.init()
self.callbackQueue.setSpecific(key: self.callbackQueueKey, value: 1)
}
@@ -891,9 +901,9 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa
}
func stop() async throws {
-#if DEBUG
+ #if DEBUG
defer { self.emitPairedDiagnosticReportIfNeeded() }
-#endif
+ #endif
#if DEBUG
AudioTopologyDiagnostics.record(.phaseBegin, owner: .screenCapture, queueRole: .actorControl, phase: .screenCaptureStop)
defer { AudioTopologyDiagnostics.record(.phaseEnd, owner: .screenCapture, queueRole: .actorControl, phase: .screenCaptureStop) }
@@ -945,7 +955,9 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa
defer { self.retiredAECCommitters.removeAll() }
return self.retiredAECCommitters + (stoppedPipeline.map { [$0.committer] } ?? [])
}
- for committer in committers { await committer.waitForPendingCommits() }
+ for committer in committers {
+ await committer.waitForPendingCommits()
+ }
if let stopFailure {
throw MeetingCaptureRuntimeError.stopFailed(stopFailure)
}
@@ -981,9 +993,9 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa
guard let (aecState, pipeline, streamToken) = callbackState else { return }
switch outputType {
case .audio:
-#if DEBUG
+ #if DEBUG
self.recordPairedDiagnostic(sampleBuffer, output: .applicationAudio)
-#endif
+ #endif
switch aecState {
case .active:
pipeline?.consumeRender(sampleBuffer, stream: streamToken)
@@ -1000,9 +1012,9 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa
self.applicationWriter.enqueue(sampleBuffer, producerEpoch: streamToken.generation)
self.liveAudioHandler?(.applicationAudio, sampleBuffer)
case .microphone:
-#if DEBUG
+ #if DEBUG
self.recordPairedDiagnostic(sampleBuffer, output: .microphone)
-#endif
+ #endif
switch aecState {
case .active:
pipeline?.consumeCapture(sampleBuffer, stream: streamToken)
@@ -1280,7 +1292,7 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa
))
}
-#if DEBUG
+ #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) {
@@ -1324,6 +1336,8 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa
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
@@ -1336,7 +1350,7 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa
}
}
}
-#endif
+ #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
@@ -1427,8 +1441,8 @@ private final nonisolated class ScreenCaptureMeetingRuntime: NSObject, MeetingCa
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.")
+ ? "Speaker-route AEC restarted unprotected and is awaiting clock attestation and warm-up."
+ : "Microphone transcript admission remains disabled because the output route is ambiguous.")
))
}
}
@@ -2148,8 +2162,12 @@ final nonisolated class MeetingAVCaptureMicrophoneComponent: NSObject,
// 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) }
+ for sessionOutput in session.outputs {
+ session.removeOutput(sessionOutput)
+ }
+ for sessionInput in session.inputs {
+ session.removeInput(sessionInput)
+ }
session.commitConfiguration()
}
)
@@ -2183,7 +2201,9 @@ final nonisolated class MeetingAVCaptureMicrophoneComponent: NSObject,
#if DEBUG
AudioTopologyDiagnostics.record(.ownerWillDeinit, owner: .avCapture, queueRole: .callbackCurrent, phase: .avCaptureStop)
#endif
- for observer in self.observers { NotificationCenter.default.removeObserver(observer) }
+ for observer in self.observers {
+ NotificationCenter.default.removeObserver(observer)
+ }
}
private var observers: [NSObjectProtocol] = []
@@ -2223,7 +2243,9 @@ final nonisolated class MeetingAVCaptureMicrophoneComponent: NSObject,
defer { self.observers.removeAll() }
return self.observers
}
- for observer in observers { NotificationCenter.default.removeObserver(observer) }
+ for observer in observers {
+ NotificationCenter.default.removeObserver(observer)
+ }
await self.lifecycle.perform { [self] in
let proven = !self.session.isRunning
&& self.session.inputs.isEmpty
@@ -2275,7 +2297,7 @@ final nonisolated class MeetingAVCaptureMicrophoneComponent: NSObject,
Task { [weak self] in
guard let self else { return }
await self.waitForInterruptionEnd(timeoutSeconds: Self.interruptionEndedWaitSeconds)
- guard !(self.stateLock.withLock({ self.stopping })) else { return }
+ 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."
@@ -2335,9 +2357,9 @@ final nonisolated class MeetingAVCaptureMicrophoneComponent: NSObject,
}
private func attemptSupervisedRestart(reason: String) async {
- guard !(self.stateLock.withLock({ self.stopping })) else { return }
+ guard !(self.stateLock.withLock { self.stopping }) else { return }
let restarted = await self.startRunningOnControlQueue()
- guard !restarted, !(self.stateLock.withLock({ self.stopping })) else { return }
+ guard !restarted, !(self.stateLock.withLock { self.stopping }) else { return }
self.emitTerminalStopIfNeeded(detail: reason)
}
@@ -2702,11 +2724,13 @@ nonisolated enum MeetingDirectAEC3Gate {
static let disableEnvironmentKey = "FLUIDVOICE_DISABLE_AEC3"
static func enabled(environment: [String: String] = ProcessInfo.processInfo.environment) -> Bool {
- environment[Self.disableEnvironmentKey] != "1"
+ 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
@@ -2733,6 +2757,8 @@ nonisolated enum MeetingCaptureTransitionPolicy {
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,
@@ -3075,11 +3101,11 @@ nonisolated enum MeetingCapturePathDecider {
if let reason = Self.outputRouteDeclineReason(outputRoute) {
return .screenCaptureKit(reason: reason)
}
-#if DEBUG
+ #if DEBUG
if forcePairedScreenCaptureKit {
return .screenCaptureKit(reason: Self.diagnosticForceScreenCaptureKitReason)
}
-#endif
+ #endif
if preferDirectAEC3 {
return .screenCaptureKit(reason: Self.directAEC3DefaultReason)
}
@@ -3170,7 +3196,9 @@ final nonisolated class MeetingVoiceProcessingCommitGate: @unchecked Sendable {
return true
}
- /// Point of no return: after this, terminal events and abort() are no-ops.
+ // 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() }
@@ -3179,8 +3207,10 @@ final nonisolated class MeetingVoiceProcessingCommitGate: @unchecked Sendable {
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 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() }
@@ -3216,7 +3246,7 @@ nonisolated enum MeetingVoiceProcessingWatchdog {
static let stalledThresholdSeconds: Double = 10
static func isStalled(secondsSinceLastEmittedBuffer: Double) -> Bool {
- secondsSinceLastEmittedBuffer >= Self.stalledThresholdSeconds
+ secondsSinceLastEmittedBuffer >= self.stalledThresholdSeconds
}
}
@@ -3295,8 +3325,24 @@ private actor MeetingOutputRouteListener {
)
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) }
+ 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) }
@@ -3304,8 +3350,24 @@ private actor MeetingOutputRouteListener {
}
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) }
+ 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) }
@@ -3313,19 +3375,54 @@ private actor MeetingOutputRouteListener {
}
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) }
+ 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)
+ 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)
+ 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 {
@@ -3335,11 +3432,30 @@ private actor MeetingOutputRouteListener {
}
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)
+ 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)
+ 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)
@@ -3353,20 +3469,58 @@ private actor MeetingOutputRouteListener {
}
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)
+ 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)
+ 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)
+ 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)
+ 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
@@ -3404,19 +3558,54 @@ private actor MeetingOutputRouteListener {
)
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) }
+ 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)
+ 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)
+ 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 {
@@ -3439,11 +3628,30 @@ private actor MeetingOutputRouteListener {
mElement: kAudioObjectPropertyElementMain
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .meetingOutputRoute, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .dedicatedControl, phase: .listener)
+ 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)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveEnd,
+ owner: .meetingOutputRoute,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .dedicatedControl,
+ phase: .listener,
+ status: status
+ )
#endif
}
@@ -3580,25 +3788,73 @@ private actor MeetingOutputRouteListener {
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)
+ 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)
+ 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)
+ 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)
+ 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)
+ 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 {
@@ -3632,7 +3888,6 @@ nonisolated enum MeetingVoiceProcessingDriftSnapshot {
}
}
-
/// 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 {
@@ -3736,7 +3991,9 @@ nonisolated enum MeetingCaptureDeviceTransition: Sendable, Equatable {
case unavailable
}
-/// Owns a swappable mic component (VPIO or AVCaptureSession) plus an app-audio-only SCStream that never stops across a swap.
+// 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
@@ -4276,7 +4533,8 @@ private final nonisolated class VoiceProcessingMeetingRuntime: MeetingCaptureRun
switch event {
case .configurationChanged:
self.eventHandler(.interrupted(
- kind: .voiceProcessingConfigurationChanged, trackID: nil,
+ kind: .voiceProcessingConfigurationChanged,
+ trackID: nil,
detail: "Voice-processing engine configuration changed."
))
Task { [weak self] in
@@ -4382,6 +4640,8 @@ private final nonisolated class VoiceProcessingMeetingRuntime: MeetingCaptureRun
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,
@@ -4390,6 +4650,8 @@ private final nonisolated class VoiceProcessingMeetingRuntime: MeetingCaptureRun
)
// 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 {
@@ -5034,7 +5296,7 @@ private final nonisolated class VoiceProcessingMeetingRuntime: MeetingCaptureRun
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 }
+ guard !(self.stateLock.withLock { self.stopRequested }), self.stateLock.withLock({ self.phase == .avCapture }) else { return }
let stillViable = MeetingCapturePathDecider.decide(
mode: .onlineCall,
microphone: self.originalMicrophone,
@@ -5064,12 +5326,13 @@ private final nonisolated class VoiceProcessingMeetingRuntime: MeetingCaptureRun
private func runUpgrade() async {
try? await Task.sleep(nanoseconds: UInt64(Self.upgradeSettleSeconds * 1_000_000_000))
- guard !(self.stateLock.withLock({ self.stopRequested })) else {
+ guard !(self.stateLock.withLock { self.stopRequested }) else {
self.finishTransition()
return
}
guard case .voiceProcessing = MeetingCapturePathDecider.decide(
- mode: .onlineCall, microphone: self.originalMicrophone,
+ mode: .onlineCall,
+ microphone: self.originalMicrophone,
outputRoute: MeetingCaptureEngine.currentOutputRouteSnapshot()
) else {
self.stateLock.withLock { self.phase = .avCapture }
@@ -5107,12 +5370,13 @@ private final nonisolated class VoiceProcessingMeetingRuntime: MeetingCaptureRun
self.abortUpgrade(candidateMicCapture: candidateMicCapture, reason: "No microphone audio was captured within 2s.")
return
}
- guard !(self.stateLock.withLock({ self.stopRequested })) else {
+ guard !(self.stateLock.withLock { self.stopRequested }) else {
self.abortUpgrade(candidateMicCapture: candidateMicCapture, reason: nil)
return
}
guard case .voiceProcessing = MeetingCapturePathDecider.decide(
- mode: .onlineCall, microphone: self.originalMicrophone,
+ mode: .onlineCall,
+ microphone: self.originalMicrophone,
outputRoute: MeetingCaptureEngine.currentOutputRouteSnapshot()
) else {
self.abortUpgrade(candidateMicCapture: candidateMicCapture, reason: "Route changed back before the upgrade committed.")
@@ -5407,6 +5671,8 @@ private final nonisolated class VoiceProcessingMeetingRuntime: MeetingCaptureRun
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,
@@ -5450,6 +5716,8 @@ private final nonisolated class VoiceProcessingMeetingRuntime: MeetingCaptureRun
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),
@@ -5497,6 +5765,8 @@ private final nonisolated class VoiceProcessingMeetingRuntime: MeetingCaptureRun
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 {
@@ -5866,7 +6136,7 @@ private final nonisolated class VoiceProcessingMeetingRuntime: MeetingCaptureRun
let shouldReplayRouteChange = self.stateLock.withLock { () -> Bool in
guard self.transitionGeneration == generation else { return false }
self.transitionTask = nil
- guard (self.phase == .avCapture || self.phase == .vpio),
+ guard self.phase == .avCapture || self.phase == .vpio,
self.routeChangeDirty,
!self.stopRequested
else { return false }
diff --git a/Sources/Fluid/Services/Meeting/MeetingDetectorFeasibilityProbe.swift b/Sources/Fluid/Services/Meeting/MeetingDetectorFeasibilityProbe.swift
index 852ee033..2811e5e1 100644
--- a/Sources/Fluid/Services/Meeting/MeetingDetectorFeasibilityProbe.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingDetectorFeasibilityProbe.swift
@@ -1,672 +1,675 @@
#if DEBUG
- import CoreAudio
- import CoreGraphics
- import CryptoKit
- import Foundation
-
- /// Ephemeral DEBUG-only feasibility probe for CoreAudio process-tap meeting detection.
- /// Runs at most once per process when FLUIDVOICE_MEETING_PROBE_DURATION_SECONDS is 5...300.
- /// Writes a closed-schema JSONL file to the temp dir; emits no raw IDs, names, paths, or errors.
- nonisolated enum MeetingDetectorFeasibilityProbe {
- private static let gate = ProbeOnceGate()
-
- static func startIfRequested() {
- guard let raw = ProcessInfo.processInfo.environment["FLUIDVOICE_MEETING_PROBE_DURATION_SECONDS"],
- let duration = Int(raw),
- ProbeLimits.validDurations.contains(duration)
- else { return }
- guard gate.checkAndSet() else { return }
- ProbeSession(durationSeconds: duration).start()
- }
- }
-
- private nonisolated enum ProbeLimits {
- static let validDurations = 5 ... 300
- static let maxObjectCount = 4096
- static let maxBufferCount = 4096
- static let maxStreamConfigBytes = 65_536
- static let tokenDigestBytes = 16
- static let saltBytes = 16
- }
-
- private nonisolated enum ProbeEvent: String, Codable, Sendable {
- case start
- case sample
- case terminal
+import CoreAudio
+import CoreGraphics
+import CryptoKit
+import Foundation
+
+/// Ephemeral DEBUG-only feasibility probe for CoreAudio process-tap meeting detection.
+/// Runs at most once per process when FLUIDVOICE_MEETING_PROBE_DURATION_SECONDS is 5...300.
+/// Writes a closed-schema JSONL file to the temp dir; emits no raw IDs, names, paths, or errors.
+nonisolated enum MeetingDetectorFeasibilityProbe {
+ private static let gate = ProbeOnceGate()
+
+ static func startIfRequested() {
+ guard let raw = ProcessInfo.processInfo.environment["FLUIDVOICE_MEETING_PROBE_DURATION_SECONDS"],
+ let duration = Int(raw),
+ ProbeLimits.validDurations.contains(duration)
+ else { return }
+ guard self.gate.checkAndSet() else { return }
+ ProbeSession(durationSeconds: duration).start()
}
-
- private nonisolated enum TerminalReason: String, Codable, Sendable {
- case completed
- case deadlineExceeded
- case cancelled
- case encodingFailure
- case writeFailure
- case validationFailure
- case setupFailure
+}
+
+private nonisolated enum ProbeLimits {
+ static let validDurations = 5...300
+ static let maxObjectCount = 4096
+ static let maxBufferCount = 4096
+ static let maxStreamConfigBytes = 65_536
+ static let tokenDigestBytes = 16
+ static let saltBytes = 16
+}
+
+private nonisolated enum ProbeEvent: String, Codable, Sendable {
+ case start
+ case sample
+ case terminal
+}
+
+private nonisolated enum TerminalReason: String, Codable, Sendable {
+ case completed
+ case deadlineExceeded
+ case cancelled
+ case encodingFailure
+ case writeFailure
+ case validationFailure
+ case setupFailure
+}
+
+private nonisolated enum ProbeNote: String, Codable, Sendable {
+ case tempMayBePurged
+}
+
+private nonisolated enum ProbeReadStatus: String, Codable, Sendable {
+ case ok
+ case readError
+ case unsupported
+ case invalidLayout
+}
+
+private nonisolated enum ProbeStreamState: String, Codable, Sendable {
+ case active
+ case inactive
+ case readError
+ case unsupported
+}
+
+private nonisolated enum ProbeRunningState: String, Codable, Sendable {
+ case running
+ case notRunning
+ case readError
+ case unsupported
+}
+
+private nonisolated enum ProbeFamily: String, Codable, Sendable {
+ case zoom
+ case teams
+ case webex
+ case selfProcess
+ case other
+}
+
+private nonisolated enum ProbeTransport: String, Codable, Sendable {
+ case builtIn
+ case bluetooth
+ case usb
+ case virtual
+ case aggregate
+ case other
+ case unknown
+}
+
+private nonisolated struct ProbeStartLine: Codable, Sendable {
+ var schemaVersion: Int
+ var event: ProbeEvent
+ var durationSeconds: Int
+ var note: ProbeNote
+}
+
+private nonisolated struct ProbeTerminalLine: Codable, Sendable {
+ var schemaVersion: Int
+ var event: ProbeEvent
+ var monotonicOffsetMs: Int
+ var reason: TerminalReason
+ var recordCount: Int
+}
+
+private nonisolated struct ProbeSampleLine: Codable, Sendable {
+ var schemaVersion: Int
+ var event: ProbeEvent
+ var monotonicOffsetMs: Int
+ var processListStatus: ProbeReadStatus
+ var processCount: Int
+ var deviceListStatus: ProbeReadStatus
+ var deviceCount: Int
+ var hardwareDeviceCount: Int
+ var classificationFailureCount: Int
+ var windowListSuccess: Bool
+ var windowListCount: Int
+ var windowListLatencyMs: Int
+ var processes: [ProcessEntry]
+ var devices: [DeviceEntry]
+}
+
+private nonisolated struct ProcessEntry: Codable, Sendable {
+ var family: ProbeFamily
+ var input: ProbeStreamState
+ var output: ProbeStreamState
+}
+
+private nonisolated struct DeviceEntry: Codable, Sendable {
+ var token: String?
+ var inputChannels: Int
+ var streamStatus: ProbeReadStatus
+ var transport: ProbeTransport
+ var running: ProbeRunningState
+}
+
+/// NSLock-guarded one-run check-and-set; the only Swift 6 Sendable escape hatch this file needs.
+private final nonisolated class ProbeOnceGate: @unchecked Sendable {
+ private let lock = NSLock()
+ private var hasRun = false
+
+ func checkAndSet() -> Bool {
+ self.lock.lock()
+ defer { lock.unlock() }
+ if self.hasRun { return false }
+ self.hasRun = true
+ return true
}
-
- private nonisolated enum ProbeNote: String, Codable, Sendable {
- case tempMayBePurged
+}
+
+private nonisolated enum AudioListReadResult {
+ case ok([AudioObjectID])
+ case readError
+ case unsupported
+ case invalidLayout
+}
+
+private final nonisolated class ProbeSession: @unchecked Sendable {
+ private let durationSeconds: Int
+ private let baseInstant = ContinuousClock.now
+ private let salt: [UInt8]
+ private let samplingQueue = DispatchQueue(label: "com.fluidvoice.meetingprobe.sampling", qos: .utility)
+ // Sole owner of encoder, fileHandle, deadlineTimer, terminalReason, recordCount, outputPath, sampleInFlight.
+ private let controlQueue = DispatchQueue(label: "com.fluidvoice.meetingprobe.control")
+
+ private let encoder = JSONEncoder()
+ private var fileHandle: FileHandle?
+ private var deadlineTimer: DispatchSourceTimer?
+ private var terminalReason: TerminalReason?
+ private var recordCount = 0
+ private var outputPath = ""
+ private var sampleInFlight = false
+
+ private var deadlineMs: Int { self.durationSeconds * 1000 }
+
+ init(durationSeconds: Int) {
+ self.durationSeconds = durationSeconds
+ var generator = SystemRandomNumberGenerator()
+ self.salt = (0..<ProbeLimits.saltBytes).map { _ in UInt8.random(in: .min ... .max, using: &generator) }
}
- private nonisolated enum ProbeReadStatus: String, Codable, Sendable {
- case ok
- case readError
- case unsupported
- case invalidLayout
+ func start() {
+ self.controlQueue.async { self.setup() }
}
- private nonisolated enum ProbeStreamState: String, Codable, Sendable {
- case active
- case inactive
- case readError
- case unsupported
+ func cancel() {
+ self.controlQueue.async { self.finalize(.cancelled) }
}
- private nonisolated enum ProbeRunningState: String, Codable, Sendable {
- case running
- case notRunning
- case readError
- case unsupported
- }
+ // MARK: - Control queue
- private nonisolated enum ProbeFamily: String, Codable, Sendable {
- case zoom
- case teams
- case webex
- case selfProcess
- case other
- }
-
- private nonisolated enum ProbeTransport: String, Codable, Sendable {
- case builtIn
- case bluetooth
- case usb
- case virtual
- case aggregate
- case other
- case unknown
- }
-
- private nonisolated struct ProbeStartLine: Codable, Sendable {
- var schemaVersion: Int
- var event: ProbeEvent
- var durationSeconds: Int
- var note: ProbeNote
- }
-
- private nonisolated struct ProbeTerminalLine: Codable, Sendable {
- var schemaVersion: Int
- var event: ProbeEvent
- var monotonicOffsetMs: Int
- var reason: TerminalReason
- var recordCount: Int
- }
+ private func setup() {
+ guard self.terminalReason == nil else { return }
+ guard Self.validateSchema() else {
+ self.finalize(.validationFailure)
+ return
+ }
- private nonisolated struct ProbeSampleLine: Codable, Sendable {
- var schemaVersion: Int
- var event: ProbeEvent
- var monotonicOffsetMs: Int
- var processListStatus: ProbeReadStatus
- var processCount: Int
- var deviceListStatus: ProbeReadStatus
- var deviceCount: Int
- var hardwareDeviceCount: Int
- var classificationFailureCount: Int
- var windowListSuccess: Bool
- var windowListCount: Int
- var windowListLatencyMs: Int
- var processes: [ProcessEntry]
- var devices: [DeviceEntry]
- }
+ let tempDir = FileManager.default.temporaryDirectory.standardizedFileURL
+ let candidate = tempDir.appendingPathComponent("fluidvoice-meeting-probe-\(UUID().uuidString).jsonl").standardizedFileURL
+ guard candidate.path.hasPrefix(tempDir.path + "/") else {
+ self.finalize(.setupFailure)
+ return
+ }
+ guard FileManager.default.createFile(
+ atPath: candidate.path,
+ contents: nil,
+ attributes: [.posixPermissions: 0o600]
+ ) else {
+ self.finalize(.setupFailure)
+ return
+ }
+ self.outputPath = candidate.path
+ do {
+ self.fileHandle = try FileHandle(forWritingTo: candidate)
+ } catch {
+ try? FileManager.default.removeItem(at: candidate)
+ self.outputPath = ""
+ self.finalize(.setupFailure)
+ return
+ }
- private nonisolated struct ProcessEntry: Codable, Sendable {
- var family: ProbeFamily
- var input: ProbeStreamState
- var output: ProbeStreamState
- }
+ let startLine = ProbeStartLine(
+ schemaVersion: 1,
+ event: .start,
+ durationSeconds: durationSeconds,
+ note: .tempMayBePurged
+ )
+ guard self.writeLine(startLine) else { return }
+
+ let timer = DispatchSource.makeTimerSource(queue: self.controlQueue)
+ timer.schedule(deadline: .now() + .seconds(self.durationSeconds))
+ timer.setEventHandler { [self] in
+ self.finalize(self.sampleInFlight ? .deadlineExceeded : .completed)
+ }
+ self.deadlineTimer = timer
+ timer.resume()
- private nonisolated struct DeviceEntry: Codable, Sendable {
- var token: String?
- var inputChannels: Int
- var streamStatus: ProbeReadStatus
- var transport: ProbeTransport
- var running: ProbeRunningState
+ self.scheduleTick(after: 0)
}
- /// NSLock-guarded one-run check-and-set; the only Swift 6 Sendable escape hatch this file needs.
- private final nonisolated class ProbeOnceGate: @unchecked Sendable {
- private let lock = NSLock()
- private var hasRun = false
-
- func checkAndSet() -> Bool {
- lock.lock()
- defer { lock.unlock() }
- if hasRun { return false }
- hasRun = true
- return true
+ private func scheduleTick(after seconds: Int) {
+ self.sampleInFlight = true
+ self.samplingQueue.asyncAfter(deadline: .now() + .seconds(seconds)) { [self] in
+ let snapshot = self.captureSnapshot()
+ self.controlQueue.async { [self] in
+ self.sampleInFlight = false
+ guard self.terminalReason == nil else { return }
+ guard Self.milliseconds(from: self.baseInstant) < self.deadlineMs else {
+ self.finalize(.deadlineExceeded)
+ return
+ }
+ guard self.writeLine(snapshot) else { return }
+ if Self.milliseconds(from: self.baseInstant) + 1000 < self.deadlineMs {
+ self.scheduleTick(after: 1)
+ }
+ }
}
}
- private nonisolated enum AudioListReadResult {
- case ok([AudioObjectID])
- case readError
- case unsupported
- case invalidLayout
- }
-
- private final nonisolated class ProbeSession: @unchecked Sendable {
- private let durationSeconds: Int
- private let baseInstant = ContinuousClock.now
- private let salt: [UInt8]
- private let samplingQueue = DispatchQueue(label: "com.fluidvoice.meetingprobe.sampling", qos: .utility)
- // Sole owner of encoder, fileHandle, deadlineTimer, terminalReason, recordCount, outputPath, sampleInFlight.
- private let controlQueue = DispatchQueue(label: "com.fluidvoice.meetingprobe.control")
-
- private let encoder = JSONEncoder()
- private var fileHandle: FileHandle?
- private var deadlineTimer: DispatchSourceTimer?
- private var terminalReason: TerminalReason?
- private var recordCount = 0
- private var outputPath = ""
- private var sampleInFlight = false
-
- private var deadlineMs: Int { durationSeconds * 1000 }
-
- init(durationSeconds: Int) {
- self.durationSeconds = durationSeconds
- var generator = SystemRandomNumberGenerator()
- self.salt = (0 ..< ProbeLimits.saltBytes).map { _ in UInt8.random(in: .min ... .max, using: &generator) }
+ private func writeLine(_ line: some Codable) -> Bool {
+ guard let handle = fileHandle else {
+ self.finalize(.setupFailure)
+ return false
}
-
- func start() {
- controlQueue.async { self.setup() }
+ let payload: Data
+ do {
+ payload = try self.encoder.encode(line)
+ } catch {
+ self.finalize(.encodingFailure)
+ return false
}
-
- func cancel() {
- controlQueue.async { self.finalize(.cancelled) }
+ var framed = payload
+ framed.append(0x0a)
+ do {
+ try handle.write(contentsOf: framed)
+ } catch {
+ self.finalize(.writeFailure)
+ return false
}
+ self.recordCount += 1
+ return true
+ }
- // MARK: - Control queue
-
- private func setup() {
- guard terminalReason == nil else { return }
- guard Self.validateSchema() else {
- finalize(.validationFailure)
- return
- }
-
- let tempDir = FileManager.default.temporaryDirectory.standardizedFileURL
- let candidate = tempDir.appendingPathComponent("fluidvoice-meeting-probe-\(UUID().uuidString).jsonl").standardizedFileURL
- guard candidate.path.hasPrefix(tempDir.path + "/") else {
- finalize(.setupFailure)
- return
- }
- guard FileManager.default.createFile(
- atPath: candidate.path,
- contents: nil,
- attributes: [.posixPermissions: 0o600]
- ) else {
- finalize(.setupFailure)
- return
- }
- outputPath = candidate.path
- do {
- fileHandle = try FileHandle(forWritingTo: candidate)
- } catch {
- try? FileManager.default.removeItem(at: candidate)
- outputPath = ""
- finalize(.setupFailure)
- return
- }
-
- let startLine = ProbeStartLine(
+ private func finalize(_ reason: TerminalReason) {
+ guard self.terminalReason == nil else { return }
+ self.terminalReason = reason
+ self.deadlineTimer?.cancel()
+ self.deadlineTimer = nil
+ var outcome = reason
+ if let handle = fileHandle {
+ let terminal = ProbeTerminalLine(
schemaVersion: 1,
- event: .start,
- durationSeconds: durationSeconds,
- note: .tempMayBePurged
+ event: .terminal,
+ monotonicOffsetMs: Self.milliseconds(from: self.baseInstant),
+ reason: reason,
+ recordCount: self.recordCount
)
- guard writeLine(startLine) else { return }
-
- let timer = DispatchSource.makeTimerSource(queue: controlQueue)
- timer.schedule(deadline: .now() + .seconds(durationSeconds))
- timer.setEventHandler { [self] in
- finalize(sampleInFlight ? .deadlineExceeded : .completed)
- }
- deadlineTimer = timer
- timer.resume()
-
- scheduleTick(after: 0)
- }
-
- private func scheduleTick(after seconds: Int) {
- sampleInFlight = true
- samplingQueue.asyncAfter(deadline: .now() + .seconds(seconds)) { [self] in
- let snapshot = captureSnapshot()
- controlQueue.async { [self] in
- sampleInFlight = false
- guard terminalReason == nil else { return }
- guard Self.milliseconds(from: baseInstant) < deadlineMs else {
- finalize(.deadlineExceeded)
- return
- }
- guard writeLine(snapshot) else { return }
- if Self.milliseconds(from: baseInstant) + 1000 < deadlineMs {
- scheduleTick(after: 1)
- }
- }
- }
- }
-
- private func writeLine(_ line: some Codable) -> Bool {
- guard let handle = fileHandle else {
- finalize(.setupFailure)
- return false
- }
- let payload: Data
- do {
- payload = try encoder.encode(line)
- } catch {
- finalize(.encodingFailure)
- return false
- }
- var framed = payload
- framed.append(0x0A)
do {
+ var framed = try encoder.encode(terminal)
+ framed.append(0x0a)
try handle.write(contentsOf: framed)
+ } catch is EncodingError {
+ outcome = .encodingFailure
} catch {
- finalize(.writeFailure)
- return false
+ outcome = .writeFailure
}
- recordCount += 1
- return true
+ try? handle.close()
+ self.fileHandle = nil
}
-
- private func finalize(_ reason: TerminalReason) {
- guard terminalReason == nil else { return }
- terminalReason = reason
- deadlineTimer?.cancel()
- deadlineTimer = nil
- var outcome = reason
- if let handle = fileHandle {
- let terminal = ProbeTerminalLine(
- schemaVersion: 1,
- event: .terminal,
- monotonicOffsetMs: Self.milliseconds(from: baseInstant),
- reason: reason,
- recordCount: recordCount
- )
- do {
- var framed = try encoder.encode(terminal)
- framed.append(0x0A)
- try handle.write(contentsOf: framed)
- } catch is EncodingError {
- outcome = .encodingFailure
- } catch {
- outcome = .writeFailure
- }
- try? handle.close()
- fileHandle = nil
- }
- terminalReason = outcome
- let message = "terminal=\(outcome.rawValue) records=\(recordCount) output=\(outputPath)"
- DispatchQueue.main.async {
- DebugLogger.shared.info(message, source: "MeetingProbe")
- }
+ self.terminalReason = outcome
+ let message = "terminal=\(outcome.rawValue) records=\(self.recordCount) output=\(self.outputPath)"
+ DispatchQueue.main.async {
+ DebugLogger.shared.info(message, source: "MeetingProbe")
}
+ }
- // MARK: - Sampling queue
-
- private func captureSnapshot() -> ProbeSampleLine {
- var processes: [ProcessEntry] = []
- let processListStatus: ProbeReadStatus
- var processCount = 0
- switch readAudioObjectIDList(kAudioHardwarePropertyProcessObjectList) {
- case let .ok(ids):
- processListStatus = .ok
- processCount = ids.count
- for id in ids {
- let family = Self.meetingFamily(for: readProcessBundleID(id))
- guard family != .other else { continue }
- processes.append(ProcessEntry(
- family: family,
- input: readProcessRunning(id, selector: kAudioProcessPropertyIsRunningInput),
- output: readProcessRunning(id, selector: kAudioProcessPropertyIsRunningOutput)
- ))
- }
- case .readError: processListStatus = .readError
- case .unsupported: processListStatus = .unsupported
- case .invalidLayout: processListStatus = .invalidLayout
+ // MARK: - Sampling queue
+
+ private func captureSnapshot() -> ProbeSampleLine {
+ var processes: [ProcessEntry] = []
+ let processListStatus: ProbeReadStatus
+ var processCount = 0
+ switch self.readAudioObjectIDList(kAudioHardwarePropertyProcessObjectList) {
+ case let .ok(ids):
+ processListStatus = .ok
+ processCount = ids.count
+ for id in ids {
+ let family = Self.meetingFamily(for: self.readProcessBundleID(id))
+ guard family != .other else { continue }
+ processes.append(ProcessEntry(
+ family: family,
+ input: self.readProcessRunning(id, selector: kAudioProcessPropertyIsRunningInput),
+ output: self.readProcessRunning(id, selector: kAudioProcessPropertyIsRunningOutput)
+ ))
}
+ case .readError: processListStatus = .readError
+ case .unsupported: processListStatus = .unsupported
+ case .invalidLayout: processListStatus = .invalidLayout
+ }
- var devices: [DeviceEntry] = []
- let deviceListStatus: ProbeReadStatus
- var hardwareDeviceCount = 0
- var classificationFailureCount = 0
- switch readAudioObjectIDList(kAudioHardwarePropertyDevices) {
- case let .ok(ids):
- deviceListStatus = .ok
- hardwareDeviceCount = ids.count
- for id in ids {
- let stream = readInputChannels(id)
- guard stream.status == .ok else {
- classificationFailureCount += 1
- continue
- }
- guard stream.channels > 0 else { continue }
- devices.append(DeviceEntry(
- token: readDeviceUID(id).map(saltedToken(for:)),
- inputChannels: stream.channels,
- streamStatus: stream.status,
- transport: readTransport(id),
- running: readRunningSomewhere(id)
- ))
+ var devices: [DeviceEntry] = []
+ let deviceListStatus: ProbeReadStatus
+ var hardwareDeviceCount = 0
+ var classificationFailureCount = 0
+ switch self.readAudioObjectIDList(kAudioHardwarePropertyDevices) {
+ case let .ok(ids):
+ deviceListStatus = .ok
+ hardwareDeviceCount = ids.count
+ for id in ids {
+ let stream = self.readInputChannels(id)
+ guard stream.status == .ok else {
+ classificationFailureCount += 1
+ continue
}
- case .readError: deviceListStatus = .readError
- case .unsupported: deviceListStatus = .unsupported
- case .invalidLayout: deviceListStatus = .invalidLayout
+ guard stream.channels > 0 else { continue }
+ devices.append(DeviceEntry(
+ token: self.readDeviceUID(id).map(self.saltedToken(for:)),
+ inputChannels: stream.channels,
+ streamStatus: stream.status,
+ transport: self.readTransport(id),
+ running: self.readRunningSomewhere(id)
+ ))
}
-
- let window = captureWindowList()
- return ProbeSampleLine(
- schemaVersion: 1,
- event: .sample,
- monotonicOffsetMs: Self.milliseconds(from: baseInstant),
- processListStatus: processListStatus,
- processCount: processCount,
- deviceListStatus: deviceListStatus,
- deviceCount: devices.count,
- hardwareDeviceCount: hardwareDeviceCount,
- classificationFailureCount: classificationFailureCount,
- windowListSuccess: window.success,
- windowListCount: window.count,
- windowListLatencyMs: window.latencyMs,
- processes: processes,
- devices: devices
- )
+ case .readError: deviceListStatus = .readError
+ case .unsupported: deviceListStatus = .unsupported
+ case .invalidLayout: deviceListStatus = .invalidLayout
}
- private static let selfBundleID: String? = Bundle.main.bundleIdentifier
+ let window = self.captureWindowList()
+ return ProbeSampleLine(
+ schemaVersion: 1,
+ event: .sample,
+ monotonicOffsetMs: Self.milliseconds(from: self.baseInstant),
+ processListStatus: processListStatus,
+ processCount: processCount,
+ deviceListStatus: deviceListStatus,
+ deviceCount: devices.count,
+ hardwareDeviceCount: hardwareDeviceCount,
+ classificationFailureCount: classificationFailureCount,
+ windowListSuccess: window.success,
+ windowListCount: window.count,
+ windowListLatencyMs: window.latencyMs,
+ processes: processes,
+ devices: devices
+ )
+ }
- private static func meetingFamily(for bundleID: String?) -> ProbeFamily {
- if let selfBundleID, bundleID == selfBundleID { return .selfProcess }
- switch bundleID {
- case "us.zoom.xos", "us.zoom.caphost": return .zoom
- case "com.microsoft.teams2", "com.microsoft.teams": return .teams
- case "com.cisco.webexmeetingsapp", "Cisco-Systems.Spark": return .webex
- default: return .other
- }
- }
+ private static let selfBundleID: String? = Bundle.main.bundleIdentifier
- private func saltedToken(for uid: String) -> String {
- var hasher = SHA256()
- hasher.update(data: Data(salt))
- hasher.update(data: Data(uid.utf8))
- return hasher.finalize().prefix(ProbeLimits.tokenDigestBytes).map { String(format: "%02x", $0) }.joined()
+ private static func meetingFamily(for bundleID: String?) -> ProbeFamily {
+ if let selfBundleID, bundleID == selfBundleID { return .selfProcess }
+ switch bundleID {
+ case "us.zoom.xos", "us.zoom.caphost": return .zoom
+ case "com.microsoft.teams2", "com.microsoft.teams": return .teams
+ case "com.cisco.webexmeetingsapp", "Cisco-Systems.Spark": return .webex
+ default: return .other
}
+ }
- private static func milliseconds(from instant: ContinuousClock.Instant) -> Int {
- Int((ContinuousClock.now - instant) / .milliseconds(1))
- }
+ private func saltedToken(for uid: String) -> String {
+ var hasher = SHA256()
+ hasher.update(data: Data(self.salt))
+ hasher.update(data: Data(uid.utf8))
+ return hasher.finalize().prefix(ProbeLimits.tokenDigestBytes).map { String(format: "%02x", $0) }.joined()
+ }
- // MARK: - CoreAudio reads
+ private static func milliseconds(from instant: ContinuousClock.Instant) -> Int {
+ Int((ContinuousClock.now - instant) / .milliseconds(1))
+ }
- private func readAudioObjectIDList(_ selector: AudioObjectPropertySelector) -> AudioListReadResult {
- var address = AudioObjectPropertyAddress(
- mSelector: selector,
- mScope: kAudioObjectPropertyScopeGlobal,
- mElement: kAudioObjectPropertyElementMain
- )
- let systemObject = AudioObjectID(kAudioObjectSystemObject)
- guard AudioObjectHasProperty(systemObject, &address) else { return .unsupported }
- let stride = MemoryLayout<AudioObjectID>.stride
-
- var lastWasChurn = false
- for _ in 0 ..< 2 {
- var size: UInt32 = 0
- guard AudioObjectGetPropertyDataSize(systemObject, &address, 0, nil, &size) == noErr else {
- lastWasChurn = false
- continue
- }
- if size == 0 { return .ok([]) }
- guard size % UInt32(stride) == 0,
- Int(size) / stride <= ProbeLimits.maxObjectCount
- else { return .invalidLayout }
-
- var dataSize = size
- var buffer = [UInt8](repeating: 0, count: Int(size))
- let status = buffer.withUnsafeMutableBytes { raw -> OSStatus in
- guard let base = raw.baseAddress else { return -1 }
- return AudioObjectGetPropertyData(systemObject, &address, 0, nil, &dataSize, base)
- }
- guard status == noErr else {
- lastWasChurn = false
- continue
- }
- guard dataSize <= size,
- dataSize % UInt32(stride) == 0,
- Int(dataSize) / stride <= ProbeLimits.maxObjectCount
- else {
- lastWasChurn = true
- continue
- }
+ // MARK: - CoreAudio reads
+
+ private func readAudioObjectIDList(_ selector: AudioObjectPropertySelector) -> AudioListReadResult {
+ var address = AudioObjectPropertyAddress(
+ mSelector: selector,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ let systemObject = AudioObjectID(kAudioObjectSystemObject)
+ guard AudioObjectHasProperty(systemObject, &address) else { return .unsupported }
+ let stride = MemoryLayout<AudioObjectID>.stride
+
+ var lastWasChurn = false
+ for _ in 0..<2 {
+ var size: UInt32 = 0
+ guard AudioObjectGetPropertyDataSize(systemObject, &address, 0, nil, &size) == noErr else {
+ lastWasChurn = false
+ continue
+ }
+ if size == 0 { return .ok([]) }
+ guard size % UInt32(stride) == 0,
+ Int(size) / stride <= ProbeLimits.maxObjectCount
+ else { return .invalidLayout }
+
+ var dataSize = size
+ var buffer = [UInt8](repeating: 0, count: Int(size))
+ let status = buffer.withUnsafeMutableBytes { raw -> OSStatus in
+ guard let base = raw.baseAddress else { return -1 }
+ return AudioObjectGetPropertyData(systemObject, &address, 0, nil, &dataSize, base)
+ }
+ guard status == noErr else {
+ lastWasChurn = false
+ continue
+ }
+ guard dataSize <= size,
+ dataSize % UInt32(stride) == 0,
+ Int(dataSize) / stride <= ProbeLimits.maxObjectCount
+ else {
+ lastWasChurn = true
+ continue
+ }
- let count = Int(dataSize) / stride
- var result = [AudioObjectID](repeating: 0, count: count)
- buffer.withUnsafeBytes { raw in
- result.withUnsafeMutableBytes { destination in
- destination.copyBytes(from: raw.prefix(count * stride))
- }
+ let count = Int(dataSize) / stride
+ var result = [AudioObjectID](repeating: 0, count: count)
+ buffer.withUnsafeBytes { raw in
+ result.withUnsafeMutableBytes { destination in
+ destination.copyBytes(from: raw.prefix(count * stride))
}
- return .ok(result)
}
- return lastWasChurn ? .invalidLayout : .readError
+ return .ok(result)
}
+ return lastWasChurn ? .invalidLayout : .readError
+ }
- private func readProcessBundleID(_ objectID: AudioObjectID) -> String? {
- readStringProperty(objectID, selector: kAudioProcessPropertyBundleID)
- }
+ private func readProcessBundleID(_ objectID: AudioObjectID) -> String? {
+ self.readStringProperty(objectID, selector: kAudioProcessPropertyBundleID)
+ }
- private func readProcessRunning(_ objectID: AudioObjectID, selector: AudioObjectPropertySelector) -> ProbeStreamState {
- var address = AudioObjectPropertyAddress(
- mSelector: selector,
- mScope: kAudioObjectPropertyScopeGlobal,
- mElement: kAudioObjectPropertyElementMain
- )
- guard AudioObjectHasProperty(objectID, &address) else { return .unsupported }
- var value: UInt32 = 0
- var size = UInt32(MemoryLayout<UInt32>.stride)
- guard AudioObjectGetPropertyData(objectID, &address, 0, nil, &size, &value) == noErr else {
- return .readError
- }
- return value != 0 ? .active : .inactive
+ private func readProcessRunning(_ objectID: AudioObjectID, selector: AudioObjectPropertySelector) -> ProbeStreamState {
+ var address = AudioObjectPropertyAddress(
+ mSelector: selector,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ guard AudioObjectHasProperty(objectID, &address) else { return .unsupported }
+ var value: UInt32 = 0
+ var size = UInt32(MemoryLayout<UInt32>.stride)
+ guard AudioObjectGetPropertyData(objectID, &address, 0, nil, &size, &value) == noErr else {
+ return .readError
}
+ return value != 0 ? .active : .inactive
+ }
- private func readDeviceUID(_ objectID: AudioObjectID) -> String? {
- readStringProperty(objectID, selector: kAudioDevicePropertyDeviceUID)
- }
+ private func readDeviceUID(_ objectID: AudioObjectID) -> String? {
+ self.readStringProperty(objectID, selector: kAudioDevicePropertyDeviceUID)
+ }
- private func readStringProperty(_ objectID: AudioObjectID, selector: AudioObjectPropertySelector) -> String? {
- var address = AudioObjectPropertyAddress(
- mSelector: selector,
- mScope: kAudioObjectPropertyScopeGlobal,
- mElement: kAudioObjectPropertyElementMain
- )
- guard AudioObjectHasProperty(objectID, &address) else { return nil }
- // CoreAudio returns a +1 retained CFString; takeRetainedValue() transfers ownership.
- var value: Unmanaged<CFString>?
- var size = UInt32(MemoryLayout<Unmanaged<CFString>?>.size)
- guard AudioObjectGetPropertyData(objectID, &address, 0, nil, &size, &value) == noErr else { return nil }
- return value?.takeRetainedValue() as String?
- }
+ private func readStringProperty(_ objectID: AudioObjectID, selector: AudioObjectPropertySelector) -> String? {
+ var address = AudioObjectPropertyAddress(
+ mSelector: selector,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ guard AudioObjectHasProperty(objectID, &address) else { return nil }
+ // CoreAudio returns a +1 retained CFString; takeRetainedValue() transfers ownership.
+ var value: Unmanaged<CFString>?
+ var size = UInt32(MemoryLayout<Unmanaged<CFString>?>.size)
+ guard AudioObjectGetPropertyData(objectID, &address, 0, nil, &size, &value) == noErr else { return nil }
+ return value?.takeRetainedValue() as String?
+ }
- private func readInputChannels(_ objectID: AudioObjectID) -> (channels: Int, status: ProbeReadStatus) {
- var address = AudioObjectPropertyAddress(
- mSelector: kAudioDevicePropertyStreamConfiguration,
- mScope: kAudioDevicePropertyScopeInput,
- mElement: kAudioObjectPropertyElementMain
- )
- guard AudioObjectHasProperty(objectID, &address) else { return (0, .unsupported) }
- let headerOffset = MemoryLayout<AudioBufferList>.stride - MemoryLayout<AudioBuffer>.stride
- let bufferStride = MemoryLayout<AudioBuffer>.stride
-
- for _ in 0 ..< 2 {
- var size: UInt32 = 0
- guard AudioObjectGetPropertyDataSize(objectID, &address, 0, nil, &size) == noErr else { continue }
- guard size > 0, size <= ProbeLimits.maxStreamConfigBytes else { return (0, .invalidLayout) }
-
- var dataSize = size
- var buffer = [UInt8](repeating: 0, count: Int(size))
- let status = buffer.withUnsafeMutableBytes { raw -> OSStatus in
- guard let base = raw.baseAddress else { return -1 }
- return AudioObjectGetPropertyData(objectID, &address, 0, nil, &dataSize, base)
- }
- guard status == noErr else { continue }
- guard dataSize <= size else { continue }
- guard Int(dataSize) >= headerOffset else { return (0, .invalidLayout) }
-
- var parsed: Int?
- buffer.withUnsafeBytes { raw in
- let byteCount = Int(dataSize)
- let declared = Int(raw.loadUnaligned(fromByteOffset: 0, as: UInt32.self))
- guard declared <= ProbeLimits.maxBufferCount,
- headerOffset + declared * bufferStride <= byteCount
- else { return }
- var channels = 0
- for index in 0 ..< declared {
- let audioBuffer = raw.loadUnaligned(
- fromByteOffset: headerOffset + index * bufferStride,
- as: AudioBuffer.self
- )
- let (sum, overflow) = channels.addingReportingOverflow(Int(audioBuffer.mNumberChannels))
- guard !overflow else { return }
- channels = sum
- }
- parsed = channels
+ private func readInputChannels(_ objectID: AudioObjectID) -> (channels: Int, status: ProbeReadStatus) {
+ var address = AudioObjectPropertyAddress(
+ mSelector: kAudioDevicePropertyStreamConfiguration,
+ mScope: kAudioDevicePropertyScopeInput,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ guard AudioObjectHasProperty(objectID, &address) else { return (0, .unsupported) }
+ let headerOffset = MemoryLayout<AudioBufferList>.stride - MemoryLayout<AudioBuffer>.stride
+ let bufferStride = MemoryLayout<AudioBuffer>.stride
+
+ for _ in 0..<2 {
+ var size: UInt32 = 0
+ guard AudioObjectGetPropertyDataSize(objectID, &address, 0, nil, &size) == noErr else { continue }
+ guard size > 0, size <= ProbeLimits.maxStreamConfigBytes else { return (0, .invalidLayout) }
+
+ var dataSize = size
+ var buffer = [UInt8](repeating: 0, count: Int(size))
+ let status = buffer.withUnsafeMutableBytes { raw -> OSStatus in
+ guard let base = raw.baseAddress else { return -1 }
+ return AudioObjectGetPropertyData(objectID, &address, 0, nil, &dataSize, base)
+ }
+ guard status == noErr else { continue }
+ guard dataSize <= size else { continue }
+ guard Int(dataSize) >= headerOffset else { return (0, .invalidLayout) }
+
+ var parsed: Int?
+ buffer.withUnsafeBytes { raw in
+ let byteCount = Int(dataSize)
+ let declared = Int(raw.loadUnaligned(fromByteOffset: 0, as: UInt32.self))
+ guard declared <= ProbeLimits.maxBufferCount,
+ headerOffset + declared * bufferStride <= byteCount
+ else { return }
+ var channels = 0
+ for index in 0..<declared {
+ let audioBuffer = raw.loadUnaligned(
+ fromByteOffset: headerOffset + index * bufferStride,
+ as: AudioBuffer.self
+ )
+ let (sum, overflow) = channels.addingReportingOverflow(Int(audioBuffer.mNumberChannels))
+ guard !overflow else { return }
+ channels = sum
}
- guard let channels = parsed else { return (0, .invalidLayout) }
- return (channels, .ok)
+ parsed = channels
}
- return (0, .readError)
+ guard let channels = parsed else { return (0, .invalidLayout) }
+ return (channels, .ok)
}
+ return (0, .readError)
+ }
- private func readTransport(_ objectID: AudioObjectID) -> ProbeTransport {
- var address = AudioObjectPropertyAddress(
- mSelector: kAudioDevicePropertyTransportType,
- mScope: kAudioObjectPropertyScopeGlobal,
- mElement: kAudioObjectPropertyElementMain
- )
- guard AudioObjectHasProperty(objectID, &address) else { return .unknown }
- var value: UInt32 = 0
- var size = UInt32(MemoryLayout<UInt32>.stride)
- guard AudioObjectGetPropertyData(objectID, &address, 0, nil, &size, &value) == noErr else {
- return .unknown
- }
- switch value {
- case UInt32(kAudioDeviceTransportTypeBuiltIn): return .builtIn
- case UInt32(kAudioDeviceTransportTypeBluetooth), UInt32(kAudioDeviceTransportTypeBluetoothLE): return .bluetooth
- case UInt32(kAudioDeviceTransportTypeUSB): return .usb
- case UInt32(kAudioDeviceTransportTypeVirtual): return .virtual
- case UInt32(kAudioDeviceTransportTypeAggregate): return .aggregate
- case UInt32(kAudioDeviceTransportTypeUnknown): return .unknown
- default: return .other
- }
+ private func readTransport(_ objectID: AudioObjectID) -> ProbeTransport {
+ var address = AudioObjectPropertyAddress(
+ mSelector: kAudioDevicePropertyTransportType,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ guard AudioObjectHasProperty(objectID, &address) else { return .unknown }
+ var value: UInt32 = 0
+ var size = UInt32(MemoryLayout<UInt32>.stride)
+ guard AudioObjectGetPropertyData(objectID, &address, 0, nil, &size, &value) == noErr else {
+ return .unknown
}
-
- private func readRunningSomewhere(_ objectID: AudioObjectID) -> ProbeRunningState {
- var address = AudioObjectPropertyAddress(
- mSelector: kAudioDevicePropertyDeviceIsRunningSomewhere,
- mScope: kAudioObjectPropertyScopeGlobal,
- mElement: kAudioObjectPropertyElementMain
- )
- guard AudioObjectHasProperty(objectID, &address) else { return .unsupported }
- var value: UInt32 = 0
- var size = UInt32(MemoryLayout<UInt32>.stride)
- guard AudioObjectGetPropertyData(objectID, &address, 0, nil, &size, &value) == noErr else {
- return .readError
- }
- return value != 0 ? .running : .notRunning
+ switch value {
+ case UInt32(kAudioDeviceTransportTypeBuiltIn): return .builtIn
+ case UInt32(kAudioDeviceTransportTypeBluetooth), UInt32(kAudioDeviceTransportTypeBluetoothLE): return .bluetooth
+ case UInt32(kAudioDeviceTransportTypeUSB): return .usb
+ case UInt32(kAudioDeviceTransportTypeVirtual): return .virtual
+ case UInt32(kAudioDeviceTransportTypeAggregate): return .aggregate
+ case UInt32(kAudioDeviceTransportTypeUnknown): return .unknown
+ default: return .other
}
+ }
- // MARK: - Window list
-
- private func captureWindowList() -> (success: Bool, count: Int, latencyMs: Int) {
- autoreleasepool {
- let started = ContinuousClock.now
- let list = CGWindowListCopyWindowInfo([.optionAll, .excludeDesktopElements], kCGNullWindowID)
- let latencyMs = Int((ContinuousClock.now - started) / .milliseconds(1))
- guard let list else { return (false, 0, latencyMs) }
- return (true, CFArrayGetCount(list), latencyMs)
- }
+ private func readRunningSomewhere(_ objectID: AudioObjectID) -> ProbeRunningState {
+ var address = AudioObjectPropertyAddress(
+ mSelector: kAudioDevicePropertyDeviceIsRunningSomewhere,
+ mScope: kAudioObjectPropertyScopeGlobal,
+ mElement: kAudioObjectPropertyElementMain
+ )
+ guard AudioObjectHasProperty(objectID, &address) else { return .unsupported }
+ var value: UInt32 = 0
+ var size = UInt32(MemoryLayout<UInt32>.stride)
+ guard AudioObjectGetPropertyData(objectID, &address, 0, nil, &size, &value) == noErr else {
+ return .readError
}
+ return value != 0 ? .running : .notRunning
+ }
+
+ // MARK: - Window list
- // MARK: - Schema validation
-
- private static let allowedStartKeys: Set<String> = ["schemaVersion", "event", "durationSeconds", "note"]
- private static let allowedSampleKeys: Set<String> = [
- "schemaVersion", "event", "monotonicOffsetMs",
- "processListStatus", "processCount", "deviceListStatus", "deviceCount",
- "hardwareDeviceCount", "classificationFailureCount",
- "windowListSuccess", "windowListCount", "windowListLatencyMs",
- "processes", "devices",
- ]
- private static let allowedTerminalKeys: Set<String> = ["schemaVersion", "event", "monotonicOffsetMs", "reason", "recordCount"]
- private static let allowedProcessKeys: Set<String> = ["family", "input", "output"]
- private static let allowedDeviceKeys: Set<String> = ["token", "inputChannels", "streamStatus", "transport", "running"]
-
- private static func encodedDictionary(_ record: some Codable) -> [String: Any]? {
- guard let data = try? JSONEncoder().encode(record),
- let dict = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
- else { return nil }
- return dict
+ private func captureWindowList() -> (success: Bool, count: Int, latencyMs: Int) {
+ autoreleasepool {
+ let started = ContinuousClock.now
+ let list = CGWindowListCopyWindowInfo([.optionAll, .excludeDesktopElements], kCGNullWindowID)
+ let latencyMs = Int((ContinuousClock.now - started) / .milliseconds(1))
+ guard let list else { return (false, 0, latencyMs) }
+ return (true, CFArrayGetCount(list), latencyMs)
}
+ }
- private static func validateSchema() -> Bool {
- let start = ProbeStartLine(schemaVersion: 1, event: .start, durationSeconds: 5, note: .tempMayBePurged)
- guard let startDict = encodedDictionary(start),
- Set(startDict.keys) == allowedStartKeys
- else { return false }
+ // MARK: - Schema validation
+
+ private static let allowedStartKeys: Set<String> = ["schemaVersion", "event", "durationSeconds", "note"]
+ private static let allowedSampleKeys: Set<String> = [
+ "schemaVersion", "event", "monotonicOffsetMs",
+ "processListStatus", "processCount", "deviceListStatus", "deviceCount",
+ "hardwareDeviceCount", "classificationFailureCount",
+ "windowListSuccess", "windowListCount", "windowListLatencyMs",
+ "processes", "devices",
+ ]
+ private static let allowedTerminalKeys: Set<String> = ["schemaVersion", "event", "monotonicOffsetMs", "reason", "recordCount"]
+ private static let allowedProcessKeys: Set<String> = ["family", "input", "output"]
+ private static let allowedDeviceKeys: Set<String> = ["token", "inputChannels", "streamStatus", "transport", "running"]
+
+ // nil means unavailable; an empty result means available with no values.
+
+ // swiftlint:disable:next discouraged_optional_collection
+ private static func encodedDictionary(_ record: some Codable) -> [String: Any]? {
+ guard let data = try? JSONEncoder().encode(record),
+ let dict = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
+ else { return nil }
+ return dict
+ }
- let process = ProcessEntry(family: .zoom, input: .active, output: .inactive)
- let device = DeviceEntry(token: "00", inputChannels: 2, streamStatus: .ok, transport: .builtIn, running: .running)
- let sample = ProbeSampleLine(
- schemaVersion: 1,
- event: .sample,
- monotonicOffsetMs: 0,
- processListStatus: .ok,
- processCount: 1,
- deviceListStatus: .ok,
- deviceCount: 1,
- hardwareDeviceCount: 1,
- classificationFailureCount: 0,
- windowListSuccess: true,
- windowListCount: 1,
- windowListLatencyMs: 0,
- processes: [process],
- devices: [device]
- )
- guard let sampleDict = encodedDictionary(sample),
- Set(sampleDict.keys) == allowedSampleKeys,
- let processes = sampleDict["processes"] as? [[String: Any]],
- processes.count == 1,
- Set(processes[0].keys) == allowedProcessKeys,
- let devices = sampleDict["devices"] as? [[String: Any]],
- devices.count == 1,
- Set(devices[0].keys) == allowedDeviceKeys
- else { return false }
-
- let tokenAbsent = DeviceEntry(token: nil, inputChannels: 1, streamStatus: .ok, transport: .usb, running: .notRunning)
- guard let tokenAbsentDict = encodedDictionary(tokenAbsent),
- Set(tokenAbsentDict.keys) == allowedDeviceKeys.subtracting(["token"])
- else { return false }
-
- let terminal = ProbeTerminalLine(schemaVersion: 1, event: .terminal, monotonicOffsetMs: 0, reason: .completed, recordCount: 0)
- guard let terminalDict = encodedDictionary(terminal),
- Set(terminalDict.keys) == allowedTerminalKeys
- else { return false }
- return true
- }
+ private static func validateSchema() -> Bool {
+ let start = ProbeStartLine(schemaVersion: 1, event: .start, durationSeconds: 5, note: .tempMayBePurged)
+ guard let startDict = encodedDictionary(start),
+ Set(startDict.keys) == allowedStartKeys
+ else { return false }
+
+ let process = ProcessEntry(family: .zoom, input: .active, output: .inactive)
+ let device = DeviceEntry(token: "00", inputChannels: 2, streamStatus: .ok, transport: .builtIn, running: .running)
+ let sample = ProbeSampleLine(
+ schemaVersion: 1,
+ event: .sample,
+ monotonicOffsetMs: 0,
+ processListStatus: .ok,
+ processCount: 1,
+ deviceListStatus: .ok,
+ deviceCount: 1,
+ hardwareDeviceCount: 1,
+ classificationFailureCount: 0,
+ windowListSuccess: true,
+ windowListCount: 1,
+ windowListLatencyMs: 0,
+ processes: [process],
+ devices: [device]
+ )
+ guard let sampleDict = encodedDictionary(sample),
+ Set(sampleDict.keys) == allowedSampleKeys,
+ let processes = sampleDict["processes"] as? [[String: Any]],
+ processes.count == 1,
+ Set(processes[0].keys) == allowedProcessKeys,
+ let devices = sampleDict["devices"] as? [[String: Any]],
+ devices.count == 1,
+ Set(devices[0].keys) == allowedDeviceKeys
+ else { return false }
+
+ let tokenAbsent = DeviceEntry(token: nil, inputChannels: 1, streamStatus: .ok, transport: .usb, running: .notRunning)
+ guard let tokenAbsentDict = encodedDictionary(tokenAbsent),
+ Set(tokenAbsentDict.keys) == allowedDeviceKeys.subtracting(["token"])
+ else { return false }
+
+ let terminal = ProbeTerminalLine(schemaVersion: 1, event: .terminal, monotonicOffsetMs: 0, reason: .completed, recordCount: 0)
+ guard let terminalDict = encodedDictionary(terminal),
+ Set(terminalDict.keys) == allowedTerminalKeys
+ else { return false }
+ return true
}
+}
#endif
diff --git a/Sources/Fluid/Services/Meeting/MeetingEchoSignalScorer.swift b/Sources/Fluid/Services/Meeting/MeetingEchoSignalScorer.swift
index 0304fe9a..f194928d 100644
--- a/Sources/Fluid/Services/Meeting/MeetingEchoSignalScorer.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingEchoSignalScorer.swift
@@ -186,8 +186,11 @@ nonisolated enum MeetingEchoSignalScorer {
}
for range in blockRanges where range.count >= self.minimumFramesPerBlock {
self.scoreBlock(
- micFrameRMS: micFrameRMS, micSpectra: micSpectra, refSpectra: refSpectra,
- range: range, into: &result
+ micFrameRMS: micFrameRMS,
+ micSpectra: micSpectra,
+ refSpectra: refSpectra,
+ range: range,
+ into: &result
)
}
return EchoFrameScores(fractions: result, hopSeconds: hopSeconds)
@@ -320,7 +323,9 @@ nonisolated enum MeetingEchoSignalScorer {
private static func nextPowerOfTwo(_ value: Int) -> Int {
var power = 1
- while power < value { power <<= 1 }
+ while power < value {
+ power <<= 1
+ }
return power
}
@@ -349,8 +354,12 @@ nonisolated enum MeetingEchoSignalScorer {
var spectrum: Spectrum?
real.withUnsafeMutableBufferPointer { realPtr in
imag.withUnsafeMutableBufferPointer { imagPtr in
+ // Buffer size and channel topology are validated before this synchronous C call.
+ // swiftlint:disable:next force_unwrapping
var split = DSPSplitComplex(realp: realPtr.baseAddress!, imagp: imagPtr.baseAddress!)
signal.withUnsafeBufferPointer { signalPtr in
+ // Buffer size and channel topology are validated before this synchronous C call.
+ // swiftlint:disable:next force_unwrapping
signalPtr.baseAddress!.withMemoryRebound(to: DSPComplex.self, capacity: fftSize / 2) { complexPtr in
vDSP_ctoz(complexPtr, 2, &split, 1, vDSP_Length(fftSize / 2))
}
@@ -393,9 +402,13 @@ nonisolated enum MeetingEchoSignalScorer {
var result = [Float](repeating: 0, count: fftSize)
crossReal.withUnsafeMutableBufferPointer { realPtr in
crossImag.withUnsafeMutableBufferPointer { imagPtr in
+ // Buffer size and channel topology are validated before this synchronous C call.
+ // swiftlint:disable:next force_unwrapping
var split = DSPSplitComplex(realp: realPtr.baseAddress!, imagp: imagPtr.baseAddress!)
vDSP_fft_zrip(setup, &split, 1, log2n, FFTDirection(FFT_INVERSE))
result.withUnsafeMutableBufferPointer { resultPtr in
+ // Buffer size and channel topology are validated before this synchronous C call.
+ // swiftlint:disable:next force_unwrapping
resultPtr.baseAddress!.withMemoryRebound(to: DSPComplex.self, capacity: halfN) { complexPtr in
vDSP_ztoc(&split, 1, complexPtr, 2, vDSP_Length(halfN))
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingExternalReferenceTrialA.swift b/Sources/Fluid/Services/Meeting/MeetingExternalReferenceTrialA.swift
index 3cfa055a..9db933b2 100644
--- a/Sources/Fluid/Services/Meeting/MeetingExternalReferenceTrialA.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingExternalReferenceTrialA.swift
@@ -1,7 +1,7 @@
#if DEBUG
-import AppKit
import Accelerate
+import AppKit
import AVFoundation
import CoreAudio
import CoreMedia
@@ -24,12 +24,12 @@ nonisolated enum MeetingExternalReferenceTrialAGate {
static let stimulusWindowPlayingMarker = "PLAYING"
static func enabled(environment: [String: String]) -> Bool {
- environment[Self.environmentKey] == "1"
- && environment[Self.targetBundleIDEnvironmentKey] == Self.requiredTargetBundleID
+ environment[self.environmentKey] == "1"
+ && environment[self.targetBundleIDEnvironmentKey] == self.requiredTargetBundleID
}
static func autorunEnabled(environment: [String: String]) -> Bool {
- self.enabled(environment: environment) && environment[Self.autorunEnvironmentKey] == "1"
+ self.enabled(environment: environment) && environment[self.autorunEnvironmentKey] == "1"
}
static func stimulusWindowIsPlaying(title: String?) -> Bool {
@@ -43,11 +43,15 @@ nonisolated enum MeetingExternalReferenceTrialAGate {
}
}
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
nonisolated struct MeetingExternalReferenceTrialADisplayCandidate: Equatable, Sendable {
let displayID: UInt32
let frame: CGRect
}
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
nonisolated struct MeetingExternalReferenceTrialAWindowCandidate: Equatable, Sendable {
let windowID: UInt32
let owningBundleIdentifier: String?
@@ -55,6 +59,8 @@ nonisolated struct MeetingExternalReferenceTrialAWindowCandidate: Equatable, Sen
let title: String?
}
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
nonisolated enum MeetingExternalReferenceTrialAWindowSelector {
/// The owning window is the source of truth for readiness. Application lists can contain
/// duplicate/stale records for one bundle, so selecting an arbitrary bundle record first can
@@ -73,6 +79,8 @@ nonisolated enum MeetingExternalReferenceTrialAWindowSelector {
}
}
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
nonisolated enum MeetingExternalReferenceTrialADisplaySelector {
/// Selects the display containing the matched stimulus window. A zero-area intersection or a
/// tie is ambiguous and fails closed; choosing `displays.first` can silently capture the wrong
@@ -94,6 +102,8 @@ nonisolated enum MeetingExternalReferenceTrialADisplaySelector {
}
}
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
nonisolated struct MeetingExternalReferenceTrialATrackSample: Equatable, Sendable {
let presentationSeconds: Double
let durationSeconds: Double
@@ -130,6 +140,8 @@ nonisolated struct MeetingExternalReferenceTrialATrackSample: Equatable, Sendabl
}
}
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
nonisolated struct MeetingExternalReferenceTrialATrackReport: Codable, Equatable, Sendable {
let callbackCount: Int
let droppedFrameCount: Int
@@ -178,7 +190,7 @@ nonisolated struct MeetingExternalReferenceTrialATrackReport: Codable, Equatable
&& sample.channelCount > 0 && sample.rms.isFinite && sample.rms >= 0
&& sample.peak.isFinite && sample.peak >= 0 && sample.peak <= 1
&& abs(Double(sample.frameCount) / sample.sampleRateHz - sample.durationSeconds)
- <= max(1.5 / sample.sampleRateHz, 0.001)
+ <= max(1.5 / sample.sampleRateHz, 0.001)
if validTiming { valid.append(sample) } else { invalid += 1 }
}
var first: Double?
@@ -292,6 +304,8 @@ nonisolated struct MeetingExternalReferenceTrialATrackReport: Codable, Equatable
}
}
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
nonisolated struct MeetingExternalReferenceTrialAClockReport: Codable, Equatable, Sendable {
let sharedClockEstablished: Bool
let acousticDelaySeconds: Double?
@@ -336,7 +350,7 @@ nonisolated struct MeetingExternalReferenceTrialAReport: Codable, Equatable, Sen
/// Backward-compatible summary used by the offline diagnostic tests. Trial A can report
/// capture health while remaining invalid as an acoustic measurement until clock mapping is
/// established.
- var valid: Bool { acousticMeasurementValid }
+ var valid: Bool { self.acousticMeasurementValid }
}
/// Lock-protected PCM collector. `reportAndRelease` computes numbers and then drops every sample
@@ -364,12 +378,20 @@ final nonisolated class MeetingExternalReferenceTrialACollector: @unchecked Send
let duration = CMTimeGetSeconds(CMSampleBufferGetDuration(sampleBuffer))
let callbackFrames = CMSampleBufferGetNumSamples(sampleBuffer)
guard let copied = MeetingLiveSampleCopy.copy(sampleBuffer),
- let channel = copied.buffer.floatChannelData?[0] else {
+ let channel = copied.buffer.floatChannelData?[0]
+ else {
self.lock.lock(); defer { self.lock.unlock() }
- self.samples.append(.init(presentationSeconds: pts, durationSeconds: duration,
- frameCount: callbackFrames, sampleRateHz: .nan,
- channelCount: 0, synthesizedTiming: synthesizedTiming,
- rms: .nan, peak: .nan, arrivalSeconds: arrival))
+ self.samples.append(.init(
+ presentationSeconds: pts,
+ durationSeconds: duration,
+ frameCount: callbackFrames,
+ sampleRateHz: .nan,
+ channelCount: 0,
+ synthesizedTiming: synthesizedTiming,
+ rms: .nan,
+ peak: .nan,
+ arrivalSeconds: arrival
+ ))
return
}
let frameCount = Int(copied.buffer.frameLength)
@@ -379,10 +401,16 @@ final nonisolated class MeetingExternalReferenceTrialACollector: @unchecked Send
vDSP_svesq(channel, 1, &sum, vDSP_Length(frameCount))
let rms = frameCount > 0 ? sqrt(Double(sum) / Double(frameCount)) : .nan
let sample = MeetingExternalReferenceTrialATrackSample(
- presentationSeconds: pts, durationSeconds: duration, frameCount: frameCount,
+ presentationSeconds: pts,
+ durationSeconds: duration,
+ frameCount: frameCount,
sampleRateHz: copied.buffer.format.sampleRate,
channelCount: Int(copied.buffer.format.channelCount),
- synthesizedTiming: synthesizedTiming, rms: rms, peak: Double(peak), arrivalSeconds: arrival)
+ synthesizedTiming: synthesizedTiming,
+ rms: rms,
+ peak: Double(peak),
+ arrivalSeconds: arrival
+ )
self.lock.lock(); defer { self.lock.unlock() }
guard self.retainedFrames + frameCount <= self.maximumFrames else {
self.droppedFrameCount += frameCount
@@ -409,9 +437,13 @@ final nonisolated class MeetingExternalReferenceTrialACollector: @unchecked Send
self.captureCloseArrivalSeconds = nil
self.lock.unlock()
return MeetingExternalReferenceTrialATrackReport.analyze(
- samples, requestedDurationSeconds: requestedDurationSeconds,
- droppedFrameCount: droppedFrameCount, callbackCount: callbackCount,
- captureOpenArrivalSeconds: open, captureCloseArrivalSeconds: close)
+ samples,
+ requestedDurationSeconds: requestedDurationSeconds,
+ droppedFrameCount: droppedFrameCount,
+ callbackCount: callbackCount,
+ captureOpenArrivalSeconds: open,
+ captureCloseArrivalSeconds: close
+ )
}
func reset() {
@@ -433,6 +465,8 @@ final nonisolated class MeetingExternalReferenceTrialACollector: @unchecked Send
}
}
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
nonisolated enum MeetingExternalReferenceTrialAOfflineHarness {
static func analyze(
reference: [MeetingExternalReferenceTrialATrackSample],
@@ -440,34 +474,50 @@ nonisolated enum MeetingExternalReferenceTrialAOfflineHarness {
requestedDurationSeconds: Double = 5
) -> MeetingExternalReferenceTrialAReport {
let referenceReport = MeetingExternalReferenceTrialATrackReport.analyze(
- reference, requestedDurationSeconds: requestedDurationSeconds)
+ reference, requestedDurationSeconds: requestedDurationSeconds
+ )
let microphoneReport = MeetingExternalReferenceTrialATrackReport.analyze(
- microphone, requestedDurationSeconds: requestedDurationSeconds)
+ microphone, requestedDurationSeconds: requestedDurationSeconds
+ )
let clock = MeetingExternalReferenceTrialAClockReport(
- sharedClockEstablished: false, acousticDelaySeconds: nil,
+ sharedClockEstablished: false,
+ acousticDelaySeconds: nil,
relationship: "independent PTS origins; no defensible clock mapping",
- reason: "acoustic delay and AEC measurement are unknown")
+ reason: "acoustic delay and AEC measurement are unknown"
+ )
return MeetingExternalReferenceTrialAReport(
schemaVersion: MeetingExternalReferenceTrialAReport.currentSchemaVersion,
targetBundleID: MeetingExternalReferenceTrialAGate.requiredTargetBundleID,
- targetProcessID: 0, targetProcessStable: false,
+ targetProcessID: 0,
+ targetProcessStable: false,
selectionConfirmed: false,
- microphoneDeviceID: nil, defaultInputDeviceID: nil,
- outputDeviceID: nil, defaultOutputDeviceID: nil,
+ microphoneDeviceID: nil,
+ defaultInputDeviceID: nil,
+ outputDeviceID: nil,
+ defaultOutputDeviceID: nil,
builtInRouteConfirmed: false,
- postCaptureRouteConfirmed: false, outputVolume: nil,
+ postCaptureRouteConfirmed: false,
+ outputVolume: nil,
postCaptureOutputVolume: nil,
- outputVolumeReadable: false, outputVolumeUnchanged: false,
- combinedPeakBound: nil, measuredCombinedPeak: nil,
+ outputVolumeReadable: false,
+ outputVolumeUnchanged: false,
+ combinedPeakBound: nil,
+ measuredCombinedPeak: nil,
referenceExcitationConfirmed: false,
streamErrorCount: 0,
stopErrorCount: 0,
- reference: referenceReport, microphone: microphoneReport, clock: clock,
+ reference: referenceReport,
+ microphone: microphoneReport,
+ clock: clock,
voiceProcessingReadback: nil,
- appOwnedPlayback: false, rawPCMRetained: false,
- transcriptRetained: false, persisted: false,
- captureValid: false, acousticMeasurementValid: false,
- reasons: ["offline harness", "independent clocks; result is unknown"])
+ appOwnedPlayback: false,
+ rawPCMRetained: false,
+ transcriptRetained: false,
+ persisted: false,
+ captureValid: false,
+ acousticMeasurementValid: false,
+ reasons: ["offline harness", "independent clocks; result is unknown"]
+ )
}
}
@@ -492,7 +542,8 @@ nonisolated enum MeetingExternalReferenceTrialAAutorun {
Darwin.exit(1)
}
DispatchQueue.global(qos: .userInitiated).asyncAfter(
- deadline: .now() + Self.hardWatchdogSeconds, execute: watchdog)
+ deadline: .now() + Self.hardWatchdogSeconds, execute: watchdog
+ )
Task { @MainActor in
let outcome: Outcome
do {
@@ -515,31 +566,34 @@ nonisolated enum MeetingExternalReferenceTrialAAutorun {
private enum RunError: Error { case timeout }
private final class CompletionGate: @unchecked Sendable {
private let lock = NSLock(); private var done = false
- func claim() -> Bool { lock.lock(); defer { lock.unlock() }; guard !done else { return false }; done = true; return true }
+ func claim() -> Bool { self.lock.lock(); defer { lock.unlock() }; guard !self.done else { return false }; self.done = true; return true }
}
@MainActor
private static func run(environment: [String: String]) async -> Outcome {
- guard CGPreflightScreenCaptureAccess() else { return Self.failure("screen recording access is not authorized") }
- guard AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else { return Self.failure("microphone access is not authorized") }
+ guard CGPreflightScreenCaptureAccess() else { return self.failure("screen recording access is not authorized") }
+ guard AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else { return self.failure("microphone access is not authorized") }
guard let targetBundleID = environment[MeetingExternalReferenceTrialAGate.targetBundleIDEnvironmentKey],
- targetBundleID == MeetingExternalReferenceTrialAGate.requiredTargetBundleID else { return Self.failure("Trial A target must be Chrome") }
+ targetBundleID == MeetingExternalReferenceTrialAGate.requiredTargetBundleID else { return self.failure("Trial A target must be Chrome") }
guard let microphoneDevice = try? await MeetingCaptureSourceCatalog.defaultMicrophone(),
let inputDevice = AudioDevice.listInputDevices().first(where: { $0.uid == microphoneDevice.coreAudioUID }),
inputDevice.isAlive, inputDevice.isBuiltIn,
- AudioDevice.getDefaultInputDevice()?.uid == microphoneDevice.coreAudioUID else {
+ AudioDevice.getDefaultInputDevice()?.uid == microphoneDevice.coreAudioUID
+ else {
return Self.failure("default live built-in microphone preflight failed")
}
let preRoute = MeetingCaptureEngine.currentOutputRouteSnapshot()
guard MeetingCapturePathDecider.outputRouteDeclineReason(preRoute) == nil,
- let outputDevice = AudioDevice.getDefaultOutputDevice(), outputDevice.isAlive else {
+ let outputDevice = AudioDevice.getDefaultOutputDevice(), outputDevice.isAlive
+ else {
return Self.failure("default live built-in speaker preflight failed")
}
let volume = Self.readOutputVolume(outputDevice.id)
let combinedPeakBound = volume.map { Double($0) * 0.08 }
guard let volume, volume.isFinite, volume > 0, volume <= 0.6,
- let combinedPeakBound, combinedPeakBound <= 0.15 else {
+ let combinedPeakBound, combinedPeakBound <= 0.15
+ else {
return Self.failure("output volume or combined peak safety preflight failed")
}
@@ -551,23 +605,28 @@ nonisolated enum MeetingExternalReferenceTrialAAutorun {
windowID: window.windowID,
owningBundleIdentifier: owner.bundleIdentifier,
owningProcessID: owner.processID,
- title: window.title)
+ title: window.title
+ )
}
guard let selectedWindow = MeetingExternalReferenceTrialAWindowSelector.selectPlayingWindow(
- from: windowCandidates, targetBundleIdentifier: targetBundleID),
- let stimulusWindow = content.windows.first(where: { $0.windowID == selectedWindow.windowID }),
- let application = stimulusWindow.owningApplication,
- application.bundleIdentifier == targetBundleID,
- application.processID > 0,
- NSRunningApplication(processIdentifier: application.processID)?.isTerminated == false else {
+ from: windowCandidates, targetBundleIdentifier: targetBundleID
+ ),
+ let stimulusWindow = content.windows.first(where: { $0.windowID == selectedWindow.windowID }),
+ let application = stimulusWindow.owningApplication,
+ application.bundleIdentifier == targetBundleID,
+ application.processID > 0,
+ NSRunningApplication(processIdentifier: application.processID)?.isTerminated == false
+ else {
return Self.failure("controlled Chrome PLAYING window is absent, stale, or ambiguous")
}
let displayCandidates = content.displays.map {
MeetingExternalReferenceTrialADisplayCandidate(displayID: $0.displayID, frame: $0.frame)
}
guard let displayID = MeetingExternalReferenceTrialADisplaySelector.selectDisplayID(
- windowFrame: stimulusWindow.frame, displays: displayCandidates),
- let display = content.displays.first(where: { $0.displayID == displayID }) else {
+ windowFrame: stimulusWindow.frame, displays: displayCandidates
+ ),
+ let display = content.displays.first(where: { $0.displayID == displayID })
+ else {
return Self.failure("controlled Chrome stimulus window does not intersect exactly one display")
}
let referenceCollector = MeetingExternalReferenceTrialACollector()
@@ -584,7 +643,8 @@ nonisolated enum MeetingExternalReferenceTrialAAutorun {
onSample: { _ in },
onSampleMetadata: { sampleBuffer, synthesized, _ in
microphoneCollector.ingest(sampleBuffer, synthesizedTiming: synthesized)
- })
+ }
+ )
let filter = SCContentFilter(display: display, including: [application], exceptingWindows: [])
let configuration = SCStreamConfiguration()
@@ -601,8 +661,10 @@ nonisolated enum MeetingExternalReferenceTrialAAutorun {
let output = TrialAStreamOutput(collector: referenceCollector)
streamOutput = output
try newStream.addStreamOutput(
- output, type: .audio,
- sampleHandlerQueue: DispatchQueue(label: "fluidvoice.trial-a.reference", qos: .userInteractive))
+ output,
+ type: .audio,
+ sampleHandlerQueue: DispatchQueue(label: "fluidvoice.trial-a.reference", qos: .userInteractive)
+ )
try await Self.withTimeout(seconds: Self.operationTimeoutSeconds) { try await newStream.startCapture() }
// VPIO must start first to establish its hardware graph, but only samples after this
// shared capture-open boundary belong to Trial A's bounded five-second window.
@@ -612,8 +674,7 @@ nonisolated enum MeetingExternalReferenceTrialAAutorun {
try Task.checkCancellation()
} catch {
if let stream {
- do { try await Self.withTimeout(seconds: Self.operationTimeoutSeconds) { try await stream.stopCapture() } }
- catch { stopErrorCount += 1 }
+ do { try await Self.withTimeout(seconds: Self.operationTimeoutSeconds) { try await stream.stopCapture() } } catch { stopErrorCount += 1 }
if let streamOutput { try? await stream.removeStreamOutput(streamOutput, type: .audio) }
}
await capture.stopForPhase1Probe()
@@ -625,17 +686,16 @@ nonisolated enum MeetingExternalReferenceTrialAAutorun {
microphoneCollector.markCaptureClosed()
let voiceProcessingReadback = await capture.voiceProcessingProbeReadback()
if let stream {
- do { try await Self.withTimeout(seconds: Self.operationTimeoutSeconds) { try await stream.stopCapture() } }
- catch { stopErrorCount += 1 }
+ do { try await Self.withTimeout(seconds: Self.operationTimeoutSeconds) { try await stream.stopCapture() } } catch { stopErrorCount += 1 }
if let streamOutput {
- do { try await stream.removeStreamOutput(streamOutput, type: .audio) }
- catch { stopErrorCount += 1 }
+ do { try await stream.removeStreamOutput(streamOutput, type: .audio) } catch { stopErrorCount += 1 }
}
}
// Observe the route and volume while the VPIO generation is still live; teardown may
// legitimately release the transient I/O unit and would hide a capture-time route change.
let postCaptureRouteConfirmed = Self.routeIsStillSafe(
- microphoneUID: microphoneDevice.coreAudioUID, outputDeviceID: outputDevice.id)
+ microphoneUID: microphoneDevice.coreAudioUID, outputDeviceID: outputDevice.id
+ )
let postCaptureOutputVolume = Self.readOutputVolume(
AudioDevice.getDefaultOutputDevice()?.id ?? kAudioObjectUnknown).map(Double.init)
await capture.stopForPhase1Probe()
@@ -649,7 +709,8 @@ nonisolated enum MeetingExternalReferenceTrialAAutorun {
}
let targetProcessStable = NSRunningApplication(processIdentifier: application.processID)?.isTerminated == false
let voiceProcessingReadbackValid = Self.voiceProcessingReadbackIsValid(
- voiceProcessingReadback, inputDeviceID: inputDevice.id, outputDeviceID: outputDevice.id)
+ voiceProcessingReadback, inputDeviceID: inputDevice.id, outputDeviceID: outputDevice.id
+ )
let captureValid = reference.timingValid && microphoneReport.timingValid
&& postCaptureRouteConfirmed && volumeUnchanged
&& (measuredCombinedPeak ?? .infinity) <= 0.15
@@ -659,31 +720,42 @@ nonisolated enum MeetingExternalReferenceTrialAAutorun {
&& targetProcessStable
&& voiceProcessingReadbackValid
let clock = MeetingExternalReferenceTrialAClockReport(
- sharedClockEstablished: false, acousticDelaySeconds: nil,
+ sharedClockEstablished: false,
+ acousticDelaySeconds: nil,
relationship: "independent PTS origins; no defensible clock mapping",
- reason: "per-buffer PTS cannot establish an acoustic capture/reference mapping")
+ reason: "per-buffer PTS cannot establish an acoustic capture/reference mapping"
+ )
let report = MeetingExternalReferenceTrialAReport(
schemaVersion: MeetingExternalReferenceTrialAReport.currentSchemaVersion,
- targetBundleID: targetBundleID, targetProcessID: application.processID,
+ targetBundleID: targetBundleID,
+ targetProcessID: application.processID,
targetProcessStable: targetProcessStable,
selectionConfirmed: true,
microphoneDeviceID: inputDevice.id,
defaultInputDeviceID: AudioDevice.getDefaultInputDevice()?.id,
- outputDeviceID: outputDevice.id, defaultOutputDeviceID: AudioDevice.getDefaultOutputDevice()?.id,
+ outputDeviceID: outputDevice.id,
+ defaultOutputDeviceID: AudioDevice.getDefaultOutputDevice()?.id,
builtInRouteConfirmed: true,
postCaptureRouteConfirmed: postCaptureRouteConfirmed,
- outputVolume: Double(volume), postCaptureOutputVolume: postCaptureOutputVolume,
- outputVolumeReadable: true, outputVolumeUnchanged: volumeUnchanged,
+ outputVolume: Double(volume),
+ postCaptureOutputVolume: postCaptureOutputVolume,
+ outputVolumeReadable: true,
+ outputVolumeUnchanged: volumeUnchanged,
combinedPeakBound: combinedPeakBound,
measuredCombinedPeak: measuredCombinedPeak,
referenceExcitationConfirmed: (reference.peak ?? 0) >= 0.001,
streamErrorCount: streamDelegate.errorCount,
stopErrorCount: stopErrorCount,
- reference: reference, microphone: microphoneReport,
- clock: clock, voiceProcessingReadback: voiceProcessingReadback,
- appOwnedPlayback: false, rawPCMRetained: false,
- transcriptRetained: false, persisted: false,
- captureValid: captureValid, acousticMeasurementValid: false,
+ reference: reference,
+ microphone: microphoneReport,
+ clock: clock,
+ voiceProcessingReadback: voiceProcessingReadback,
+ appOwnedPlayback: false,
+ rawPCMRetained: false,
+ transcriptRetained: false,
+ persisted: false,
+ captureValid: captureValid,
+ acousticMeasurementValid: false,
reasons: ["diagnostic-only", "no app-owned playback", "independent clocks; acoustic delay unknown"]
+ ((reference.peak ?? 0) >= 0.001 ? [] : ["reference below excitation floor"])
+ (postCaptureRouteConfirmed ? [] : ["capture-time route changed or became unreadable"])
@@ -693,9 +765,12 @@ nonisolated enum MeetingExternalReferenceTrialAAutorun {
+ (streamDelegate.errorCount == 0 ? [] : ["ScreenCaptureKit stream stopped with error"])
+ (stopErrorCount == 0 ? [] : ["stream stop or output cleanup failed"])
+ (targetProcessStable ? [] : ["target process became unstable"])
- + (voiceProcessingReadbackValid ? [] : ["VPIO engine/voice-processing device readback was not verified"]))
+ + (voiceProcessingReadbackValid ? [] : ["VPIO engine/voice-processing device readback was not verified"])
+ )
do {
let data = try JSONEncoder.sorted.encode(report)
+ // Diagnostic JSON is emitted as UTF-8; decoding keeps the report output nonoptional.
+ // swiftlint:disable:next optional_data_string_conversion
return Self.success(String(decoding: data, as: UTF8.self))
} catch { return Self.failure("numeric Trial A report serialization failed") }
}
@@ -720,7 +795,8 @@ nonisolated enum MeetingExternalReferenceTrialAAutorun {
output.id == outputDeviceID,
MeetingCapturePathDecider.outputRouteDeclineReason(
MeetingCaptureEngine.currentOutputRouteSnapshot()) == nil,
- let volume = Self.readOutputVolume(output.id), volume > 0, volume <= 0.6 else {
+ let volume = readOutputVolume(output.id), volume > 0, volume <= 0.6
+ else {
return false
}
return true
@@ -743,7 +819,8 @@ nonisolated enum MeetingExternalReferenceTrialAAutorun {
snapshot.bypassVoiceProcessing.status == noErr,
snapshot.bypassVoiceProcessing.value == 0,
snapshot.voiceProcessingAGCEnabled.status == noErr,
- snapshot.voiceProcessingAGCEnabled.value == 1 else {
+ snapshot.voiceProcessingAGCEnabled.value == 1
+ else {
return false
}
return true
@@ -752,29 +829,37 @@ nonisolated enum MeetingExternalReferenceTrialAAutorun {
private static func success(_ reportJSON: String) -> Outcome {
guard let data = reportJSON.data(using: .utf8),
let report = try? JSONSerialization.jsonObject(with: data),
- let line = Self.jsonLine(["exitStatus": 0, "report": report, "status": "success"]) else {
- return Self.failure("numeric Trial A report serialization failed")
+ let line = jsonLine(["exitStatus": 0, "report": report, "status": "success"])
+ else {
+ return self.failure("numeric Trial A report serialization failed")
}
return Outcome(exitStatus: 0, line: line)
}
+
private static func failure(_ reason: String) -> Outcome {
let line = Self.jsonLine(["exitStatus": 1, "reason": reason, "status": "failure"])
?? "{\"exitStatus\":1,\"status\":\"failure\"}"
return Outcome(exitStatus: 1, line: line)
}
+
private static func jsonLine(_ object: [String: Any]) -> String? {
guard JSONSerialization.isValidJSONObject(object),
- let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) else {
+ let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])
+ else {
return nil
}
+ // Diagnostic JSON is emitted as UTF-8; decoding keeps the report output nonoptional.
+ // swiftlint:disable:next optional_data_string_conversion
return String(decoding: data, as: UTF8.self)
}
+
private static func withTimeout<T: Sendable>(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 RunError.timeout }
defer { group.cancelAll() }
- return try await group.next()!
+ guard let result = try await group.next() else { throw RunError.timeout }
+ return result
}
}
}
@@ -791,9 +876,9 @@ private final class TrialAStreamOutput: NSObject, SCStreamOutput, @unchecked Sen
private final class TrialAStreamDelegate: NSObject, SCStreamDelegate, @unchecked Sendable {
private let lock = NSLock()
private var stoppedWithErrorCount = 0
- var errorCount: Int { lock.lock(); defer { lock.unlock() }; return stoppedWithErrorCount }
+ var errorCount: Int { self.lock.lock(); defer { lock.unlock() }; return self.stoppedWithErrorCount }
func stream(_ stream: SCStream, didStopWithError error: Error) {
- lock.lock(); stoppedWithErrorCount += 1; lock.unlock()
+ self.lock.lock(); self.stoppedWithErrorCount += 1; self.lock.unlock()
}
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingMicrophoneCapture.swift b/Sources/Fluid/Services/Meeting/MeetingMicrophoneCapture.swift
index da5a6225..97ae5d7e 100644
--- a/Sources/Fluid/Services/Meeting/MeetingMicrophoneCapture.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingMicrophoneCapture.swift
@@ -106,7 +106,7 @@ nonisolated struct MeetingMicrophonePTSClock {
if self.firstValidHostSeconds == nil { self.firstValidHostSeconds = actualSeconds }
self.lastValidHostSeconds = actualSeconds
- if self.anchorHostSeconds == nil || wasDropping {
+ guard let anchorHostSeconds = self.anchorHostSeconds, !wasDropping else {
// A backlogged invalid burst can synthesize more timeline than elapsed host time;
// anchoring behind emitted audio would trip the writer's backwards check.
var resyncSeconds = actualSeconds
@@ -122,7 +122,7 @@ nonisolated struct MeetingMicrophonePTSClock {
return .emitted(pts: pts, synthesized: false, anchorCorrected: wasDropping, resynced: wasDropping)
}
- let expectedSeconds = self.anchorHostSeconds! + Double(self.framesSinceAnchor) / self.sampleRate
+ let expectedSeconds = anchorHostSeconds + Double(self.framesSinceAnchor) / self.sampleRate
let divergence = actualSeconds - expectedSeconds
self.maxAbsDivergenceSeconds = max(self.maxAbsDivergenceSeconds, abs(divergence))
let step = abs(divergence - self.lastDivergenceSeconds)
@@ -138,7 +138,7 @@ nonisolated struct MeetingMicrophonePTSClock {
var corrected = false
if abs(divergence) > 1.0 / self.sampleRate {
// += divergence; using the post-increment count latches one window off (97% bug).
- self.anchorHostSeconds! += divergence
+ self.anchorHostSeconds = anchorHostSeconds + divergence
self.cumulativeAbsorbedCorrectionSeconds += divergence
self.lastDivergenceSeconds = 0
corrected = true
@@ -201,6 +201,8 @@ nonisolated func meetingMicrophoneSynthesizeSampleBuffer(
} else {
guard let channelData = buffer.floatChannelData else { return nil }
interleaved.withUnsafeMutableBytes { destination in
+ // Buffer size and channel topology are validated before this synchronous C call.
+ // swiftlint:disable:next force_unwrapping
let output = destination.baseAddress!.assumingMemoryBound(to: Float.self)
for frame in 0..<frameCount {
for channel in 0..<channelCount {
@@ -226,6 +228,8 @@ nonisolated func meetingMicrophoneSynthesizeSampleBuffer(
let copyStatus = interleaved.withUnsafeBytes { bytes in
CMBlockBufferReplaceDataBytes(
+ // Buffer size and channel topology are validated before this synchronous C call.
+ // swiftlint:disable:next force_unwrapping
with: bytes.baseAddress!,
blockBuffer: blockBuffer,
offsetIntoDestination: 0,
@@ -277,11 +281,11 @@ extension MeetingMicrophoneBindingOutcome: Codable {
let container = try decoder.container(keyedBy: CodingKeys.self)
switch try container.decode(Kind.self, forKey: .kind) {
case .boundVerified:
- self = .boundVerified(try container.decode(AudioObjectID.self, forKey: .deviceID))
+ self = try .boundVerified(container.decode(AudioObjectID.self, forKey: .deviceID))
case .defaultMatchesRequested:
self = .defaultMatchesRequested
case .unavailable:
- self = .unavailable(reason: try container.decode(String.self, forKey: .reason))
+ self = try .unavailable(reason: container.decode(String.self, forKey: .reason))
}
}
@@ -528,13 +532,15 @@ final nonisolated class MeetingVPIOAcousticRenderTapCollector: @unchecked Sendab
let frames = Int(buffer.frameLength)
let channelsCount = max(1, Int(buffer.format.channelCount))
let rate = buffer.format.sampleRate
- let hostStart = time?.isHostTimeValid == true ? MeetingVPIOAcousticHostClock.seconds(time!.hostTime) : nil
+ let hostStart = time.flatMap { $0.isHostTimeValid ? MeetingVPIOAcousticHostClock.seconds($0.hostTime) : nil }
var sumSquares = 0.0
var peak = 0.0
var firstActivityHostSeconds: Double?
for index in 0..<frames {
var value = 0.0
- for channel in 0..<channelsCount { value += Double(channels[channel][index]) }
+ for channel in 0..<channelsCount {
+ value += Double(channels[channel][index])
+ }
value /= Double(channelsCount)
sumSquares += value * value
peak = max(peak, abs(value))
@@ -669,7 +675,7 @@ final class MeetingMicrophoneCaptureStats: @unchecked Sendable {
var callbackDurations: [Double] = []
}
- private static let maxTrackedDurations = 4_096
+ private static let maxTrackedDurations = 4096
private let lock = OSAllocatedUnfairLock(initialState: State())
@@ -721,7 +727,7 @@ private final class MeetingMicrophoneGenerationBox: @unchecked Sendable {
private final class MeetingMicrophoneTapState: @unchecked Sendable {
/// Tap delivers ~10.7 ms buffers; emitting each would 10x the writer's tuned 24-slot budget.
- private static let accumulationFrameThreshold = 4_800 // 100 ms @ 48 kHz
+ private static let accumulationFrameThreshold = 4800 // 100 ms @ 48 kHz
private let statsBox: MeetingMicrophoneCaptureStats
private let canonicalFormat: AVAudioFormat
@@ -791,6 +797,8 @@ private final class MeetingMicrophoneTapState: @unchecked Sendable {
}
pcmBuffer.frameLength = AVAudioFrameCount(frameCount)
samples.withUnsafeBufferPointer { source in
+ // Buffer size and channel topology are validated before this synchronous C call.
+ // swiftlint:disable:next force_unwrapping
pcmBuffer.floatChannelData?[0].update(from: source.baseAddress!, count: frameCount)
}
@@ -840,7 +848,9 @@ private final class MeetingMicrophoneTapState: @unchecked Sendable {
}
}
- /// Resample first, then downmix explicitly — converter channel mapping may drop, not mix.
+ // Resample first, then downmix explicitly — converter channel mapping may drop, not mix.
+ // nil represents unavailable or invalid evidence, distinct from a valid empty collection.
+ // swiftlint:disable:next discouraged_optional_collection
private func convertToMono(_ buffer: AVAudioPCMBuffer) -> [Float]? {
let sourceFormat = buffer.format
guard sourceFormat.sampleRate > 0, sourceFormat.channelCount > 0 else { return nil }
@@ -916,6 +926,8 @@ actor MeetingMicrophoneCapture {
private static let canonicalFormat = AVAudioFormat(
commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 1, interleaved: false
+ // Fixed Float32 PCM format with positive sample rate and channels is valid by construction.
+ // swiftlint:disable:next force_unwrapping
)!
private static let formatRetryLimit = 5
private static let formatRetryDelayNanoseconds: UInt64 = 100_000_000
@@ -950,20 +962,27 @@ actor MeetingMicrophoneCapture {
self.activeGeneration = currentGeneration
#if DEBUG
- var diagnosticsPhaseEnded = false
- AudioTopologyDiagnostics.record(.phaseBegin, owner: .meetingMicrophone, queueRole: .actorControl, phase: .handoff, generation: currentGeneration)
- AudioTopologyDiagnostics.record(.avfAuthorizationBegin, owner: .meetingMicrophone, queueRole: .actorControl, phase: .catalog, generation: currentGeneration)
- defer {
- if diagnosticsPhaseEnded == false {
- AudioTopologyDiagnostics.record(.phaseEnd, owner: .meetingMicrophone, queueRole: .actorControl, phase: .handoff, status: -1, generation: currentGeneration)
- }
+ var diagnosticsPhaseEnded = false
+ AudioTopologyDiagnostics.record(.phaseBegin, owner: .meetingMicrophone, queueRole: .actorControl, phase: .handoff, generation: currentGeneration)
+ AudioTopologyDiagnostics.record(.avfAuthorizationBegin, owner: .meetingMicrophone, queueRole: .actorControl, phase: .catalog, generation: currentGeneration)
+ defer {
+ if diagnosticsPhaseEnded == false {
+ AudioTopologyDiagnostics.record(.phaseEnd, owner: .meetingMicrophone, queueRole: .actorControl, phase: .handoff, status: -1, generation: currentGeneration)
}
+ }
#endif
let authorizationStatus: AVAuthorizationStatus = authorizationPreflighted
? .authorized
: AVCaptureDevice.authorizationStatus(for: .audio)
#if DEBUG
- AudioTopologyDiagnostics.record(.avfAuthorizationEnd, owner: .meetingMicrophone, queueRole: .actorControl, phase: .catalog, status: Int32(authorizationStatus.rawValue), generation: currentGeneration)
+ AudioTopologyDiagnostics.record(
+ .avfAuthorizationEnd,
+ owner: .meetingMicrophone,
+ queueRole: .actorControl,
+ phase: .catalog,
+ status: Int32(authorizationStatus.rawValue),
+ generation: currentGeneration
+ )
#endif
guard authorizationStatus == .authorized else {
return self.fail(microphone: microphone, reason: "Microphone permission is not granted.", generation: currentGeneration)
@@ -981,16 +1000,24 @@ actor MeetingMicrophoneCapture {
// VPIO replaces the I/O unit: enable before any format read or device bind.
#if DEBUG
- AudioTopologyDiagnostics.record(.vpioEnableBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .vpio, generation: currentGeneration)
+ AudioTopologyDiagnostics.record(.vpioEnableBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .vpio, generation: currentGeneration)
#endif
do {
try input.setVoiceProcessingEnabled(true)
#if DEBUG
- AudioTopologyDiagnostics.record(.vpioEnableEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .vpio, status: noErr, generation: currentGeneration)
+ AudioTopologyDiagnostics.record(
+ .vpioEnableEnd,
+ owner: .meetingMicrophone,
+ objectID: requestedDeviceID,
+ queueRole: .actorControl,
+ phase: .vpio,
+ status: noErr,
+ generation: currentGeneration
+ )
#endif
} catch {
#if DEBUG
- AudioTopologyDiagnostics.record(.vpioEnableEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .vpio, status: -1, generation: currentGeneration)
+ AudioTopologyDiagnostics.record(.vpioEnableEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .vpio, status: -1, generation: currentGeneration)
#endif
return self.fail(microphone: microphone, reason: "Voice processing could not be enabled: \(error.localizedDescription)", generation: currentGeneration)
}
@@ -1005,11 +1032,19 @@ actor MeetingMicrophoneCapture {
// TODO(probe): bind order is a Phase-1 measurement; this hard-codes one attempt.
#if DEBUG
- AudioTopologyDiagnostics.record(.audioUnitBindBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .vpio, generation: currentGeneration)
+ AudioTopologyDiagnostics.record(.audioUnitBindBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .vpio, generation: currentGeneration)
#endif
let bindStatus = Self.bindInputDevice(audioUnit, to: requestedDeviceID)
#if DEBUG
- AudioTopologyDiagnostics.record(.audioUnitBindEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .vpio, status: bindStatus, generation: currentGeneration)
+ AudioTopologyDiagnostics.record(
+ .audioUnitBindEnd,
+ owner: .meetingMicrophone,
+ objectID: requestedDeviceID,
+ queueRole: .actorControl,
+ phase: .vpio,
+ status: bindStatus,
+ generation: currentGeneration
+ )
#endif
// Tap before start(): added afterwards it sits on an inactive node — measured as
@@ -1026,29 +1061,53 @@ actor MeetingMicrophoneCapture {
)
self.tapState = tapState
let generationBox = self.generationBox
- input.installTap(onBus: 0, bufferSize: 4_800, format: preStartFormat) { buffer, time in
+ input.installTap(onBus: 0, bufferSize: 4800, format: preStartFormat) { buffer, time in
guard generationBox.isCurrent(currentGeneration) else { return }
tapState.handle(buffer: buffer, time: time)
}
#if DEBUG
- AudioTopologyDiagnostics.record(.enginePrepareBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, generation: currentGeneration)
+ AudioTopologyDiagnostics.record(.enginePrepareBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, generation: currentGeneration)
#endif
engine.prepare()
#if DEBUG
- AudioTopologyDiagnostics.record(.enginePrepareEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, status: noErr, generation: currentGeneration)
+ AudioTopologyDiagnostics.record(
+ .enginePrepareEnd,
+ owner: .meetingMicrophone,
+ objectID: requestedDeviceID,
+ queueRole: .actorControl,
+ phase: .engine,
+ status: noErr,
+ generation: currentGeneration
+ )
#endif
#if DEBUG
- AudioTopologyDiagnostics.record(.engineStartBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, generation: currentGeneration)
+ AudioTopologyDiagnostics.record(.engineStartBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, generation: currentGeneration)
#endif
do {
try engine.start()
#if DEBUG
- AudioTopologyDiagnostics.record(.engineStartEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, status: noErr, generation: currentGeneration)
+ AudioTopologyDiagnostics.record(
+ .engineStartEnd,
+ owner: .meetingMicrophone,
+ objectID: requestedDeviceID,
+ queueRole: .actorControl,
+ phase: .engine,
+ status: noErr,
+ generation: currentGeneration
+ )
#endif
} catch {
#if DEBUG
- AudioTopologyDiagnostics.record(.engineStartEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, status: -1, generation: currentGeneration)
+ AudioTopologyDiagnostics.record(
+ .engineStartEnd,
+ owner: .meetingMicrophone,
+ objectID: requestedDeviceID,
+ queueRole: .actorControl,
+ phase: .engine,
+ status: -1,
+ generation: currentGeneration
+ )
#endif
input.removeTap(onBus: 0)
return self.fail(microphone: microphone, reason: "AVAudioEngine failed to start: \(error.localizedDescription)", generation: currentGeneration)
@@ -1095,7 +1154,7 @@ actor MeetingMicrophoneCapture {
if sourceFormat != preStartFormat {
// Post-start renegotiation (HAL settling): reattach at the settled format.
input.removeTap(onBus: 0)
- input.installTap(onBus: 0, bufferSize: 4_800, format: sourceFormat) { buffer, time in
+ input.installTap(onBus: 0, bufferSize: 4800, format: sourceFormat) { buffer, time in
guard generationBox.isCurrent(currentGeneration) else { return }
tapState.handle(buffer: buffer, time: time)
}
@@ -1126,9 +1185,9 @@ actor MeetingMicrophoneCapture {
throw MeetingMicrophoneCaptureError.lifecycleInterrupted
}
#if DEBUG
- AudioTopologyDiagnostics.record(.readiness, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, status: noErr, generation: currentGeneration)
- AudioTopologyDiagnostics.record(.phaseEnd, owner: .meetingMicrophone, queueRole: .actorControl, phase: .handoff, status: noErr, generation: currentGeneration)
- diagnosticsPhaseEnded = true
+ AudioTopologyDiagnostics.record(.readiness, owner: .meetingMicrophone, objectID: requestedDeviceID, queueRole: .actorControl, phase: .engine, status: noErr, generation: currentGeneration)
+ AudioTopologyDiagnostics.record(.phaseEnd, owner: .meetingMicrophone, queueRole: .actorControl, phase: .handoff, status: noErr, generation: currentGeneration)
+ diagnosticsPhaseEnded = true
#endif
return outcome
}
@@ -1140,11 +1199,11 @@ actor MeetingMicrophoneCapture {
/// DEBUG diagnostic teardown that leaves the VPIO unit to process-boundary cleanup. This is
/// used only by isolated acoustic probes because explicit unit replacement can crash on some
/// macOS 26 audio stacks after a live output read-back.
-#if DEBUG
+ #if DEBUG
func stopForPhase1Probe() async {
await self.stop(teardownVoiceProcessingUnit: false)
}
-#endif
+ #endif
private func stop(teardownVoiceProcessingUnit: Bool) async {
guard self.activeGeneration != nil else { return }
@@ -1182,7 +1241,7 @@ actor MeetingMicrophoneCapture {
}
oldEngine.inputNode.removeTap(onBus: 0)
#if DEBUG
- AudioTopologyDiagnostics.record(.engineStopBegin, owner: .meetingMicrophone, queueRole: .actorControl, phase: .engine, generation: stopGeneration)
+ AudioTopologyDiagnostics.record(.engineStopBegin, owner: .meetingMicrophone, queueRole: .actorControl, phase: .engine, generation: stopGeneration)
#endif
oldEngine.stop()
// Explicitly tear down the VPIO Audio Unit. Relying on AVAudioEngine
@@ -1192,7 +1251,7 @@ actor MeetingMicrophoneCapture {
try? oldEngine.inputNode.setVoiceProcessingEnabled(false)
}
#if DEBUG
- AudioTopologyDiagnostics.record(.engineStopEnd, owner: .meetingMicrophone, queueRole: .actorControl, phase: .engine, status: noErr, generation: stopGeneration)
+ AudioTopologyDiagnostics.record(.engineStopEnd, owner: .meetingMicrophone, queueRole: .actorControl, phase: .engine, status: noErr, generation: stopGeneration)
#endif
}
await Self.removeEventObservers(
@@ -1288,7 +1347,7 @@ actor MeetingMicrophoneCapture {
)
}
-#if DEBUG
+ #if DEBUG
/// Read-only safety check for the local Trial B render. The system volume is never changed;
/// unsupported or unexpectedly loud routes are reported as numeric refusal reasons.
func acousticOutputPreflight(samplePeak: Double, volume: Float) -> MeetingVPIOAcousticOutputPreflight {
@@ -1339,7 +1398,8 @@ actor MeetingMicrophoneCapture {
let safePlayerVolume = volume.isFinite ? min(max(Double(volume), 0), Double(MeetingVPIOAcousticStimulus.maximumRenderVolume)) : 0
let combinedPeak = outputVolume.map { safeDigitalPeak * safePlayerVolume * Double($0) }
if let outputVolume,
- Double(outputVolume) <= 0 || Double(outputVolume) > MeetingVPIOAcousticGate.maximumSystemVolume {
+ Double(outputVolume) <= 0 || Double(outputVolume) > MeetingVPIOAcousticGate.maximumSystemVolume
+ {
reasons.append(.outputLevelUnsafe)
}
if let combinedPeak, combinedPeak > MeetingVPIOAcousticGate.maximumCombinedPeak {
@@ -1388,11 +1448,11 @@ actor MeetingMicrophoneCapture {
}
return nil
}
-#endif
+ #endif
/// Probe-only mutation. The environment gate prevents production callers from changing VPIO
/// processing state through this diagnostic surface.
-#if DEBUG
+ #if DEBUG
func setVoiceProcessingBypassedForProbe(_ bypassed: Bool) -> Bool? {
guard MeetingVPIOAcousticGate.isEnabled else {
return nil
@@ -1411,14 +1471,14 @@ actor MeetingMicrophoneCapture {
input.isVoiceProcessingAGCEnabled = enabled
return input.isVoiceProcessingAGCEnabled
}
-#else
+ #else
func setVoiceProcessingBypassedForProbe(_ bypassed: Bool) -> Bool? { nil }
func setVoiceProcessingAGCEnabledForProbe(_ enabled: Bool) -> Bool? { nil }
-#endif
+ #endif
/// Render known local PCM through this same VPIO engine. This is Trial B only; it cannot route
/// another application's audio and is never reachable without the acoustic-probe environment.
-#if DEBUG
+ #if DEBUG
func playVoiceProcessingProbePCM(
_ samples: [Float],
sampleRate: Double,
@@ -1466,16 +1526,16 @@ actor MeetingMicrophoneCapture {
)
}
guard let format = AVAudioFormat(
- commonFormat: .pcmFormatFloat32,
- sampleRate: sampleRate,
- channels: 1,
- interleaved: false
- ),
- let buffer = AVAudioPCMBuffer(
- pcmFormat: format,
- frameCapacity: AVAudioFrameCount(samples.count)
- ),
- let channel = buffer.floatChannelData?[0]
+ commonFormat: .pcmFormatFloat32,
+ sampleRate: sampleRate,
+ channels: 1,
+ interleaved: false
+ ),
+ let buffer = AVAudioPCMBuffer(
+ pcmFormat: format,
+ frameCapacity: AVAudioFrameCount(samples.count)
+ ),
+ let channel = buffer.floatChannelData?[0]
else {
throw MeetingVoiceProcessingProbeError.invalidPlaybackFormat
}
@@ -1499,7 +1559,7 @@ actor MeetingMicrophoneCapture {
}
if tapInstalled { mixer.removeTap(onBus: 0) }
}
- mixer.installTap(onBus: 0, bufferSize: 4_800, format: nil) { buffer, time in
+ mixer.installTap(onBus: 0, bufferSize: 4800, format: nil) { buffer, time in
tapCollector.ingest(buffer: buffer, time: time)
}
tapInstalled = true
@@ -1558,7 +1618,7 @@ actor MeetingMicrophoneCapture {
)
return report
}
-#else
+ #else
func playVoiceProcessingProbePCM(
_ samples: [Float],
sampleRate: Double,
@@ -1566,7 +1626,7 @@ actor MeetingMicrophoneCapture {
) async throws {
throw MeetingVoiceProcessingProbeError.disabled
}
-#endif
+ #endif
private func ownsGeneration(_ generation: UInt64, engine: AVAudioEngine) -> Bool {
self.activeGeneration == generation
@@ -1679,8 +1739,26 @@ actor MeetingMicrophoneCapture {
)
let token: AudioObjectPropertyListenerBlock = { _, _ in
#if DEBUG
- AudioTopologyDiagnostics.record(.callbackBegin, owner: .meetingMicrophone, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDefaultInputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: generation)
- defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .meetingMicrophone, objectID: AudioObjectID(kAudioObjectSystemObject), selector: kAudioHardwarePropertyDefaultInputDevice, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: generation) }
+ AudioTopologyDiagnostics.record(
+ .callbackBegin,
+ owner: .meetingMicrophone,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDefaultInputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .callbackEnd,
+ owner: .meetingMicrophone,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: kAudioHardwarePropertyDefaultInputDevice,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ ) }
#endif
MeetingMicrophoneEventExecution.afterHALCallback {
guard generationBox.isCurrent(generation) else { return }
@@ -1689,7 +1767,16 @@ actor MeetingMicrophoneCapture {
}
}
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .meetingMicrophone, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .listenerAddBegin,
+ owner: .meetingMicrophone,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .actorControl,
+ phase: .listener
+ )
#endif
let status = await AudioTopologyListenerExecution.add(
objectID: AudioObjectID(kAudioObjectSystemObject),
@@ -1697,7 +1784,17 @@ actor MeetingMicrophoneCapture {
token: token
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .meetingMicrophone, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener, status: status)
+ AudioTopologyDiagnostics.record(
+ .listenerAddEnd,
+ owner: .meetingMicrophone,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .actorControl,
+ phase: .listener,
+ status: status
+ )
#endif
if status == noErr, self.isRunning, self.generationBox.isCurrent(generation) {
self.defaultInputListenerToken = token
@@ -1718,8 +1815,26 @@ actor MeetingMicrophoneCapture {
)
let token: AudioObjectPropertyListenerBlock = { _, _ in
#if DEBUG
- AudioTopologyDiagnostics.record(.callbackBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, selector: kAudioDeviceProcessorOverload, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: generation)
- defer { AudioTopologyDiagnostics.record(.callbackEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, selector: kAudioDeviceProcessorOverload, scope: kAudioObjectPropertyScopeGlobal, element: kAudioObjectPropertyElementMain, queueRole: .callbackCurrent, generation: generation) }
+ AudioTopologyDiagnostics.record(
+ .callbackBegin,
+ owner: .meetingMicrophone,
+ objectID: requestedDeviceID,
+ selector: kAudioDeviceProcessorOverload,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ )
+ defer { AudioTopologyDiagnostics.record(
+ .callbackEnd,
+ owner: .meetingMicrophone,
+ objectID: requestedDeviceID,
+ selector: kAudioDeviceProcessorOverload,
+ scope: kAudioObjectPropertyScopeGlobal,
+ element: kAudioObjectPropertyElementMain,
+ queueRole: .callbackCurrent,
+ generation: generation
+ ) }
#endif
MeetingMicrophoneEventExecution.afterHALCallback {
guard generationBox.isCurrent(generation) else { return }
@@ -1728,7 +1843,16 @@ actor MeetingMicrophoneCapture {
}
}
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddBegin, owner: .meetingMicrophone, objectID: requestedDeviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .listenerAddBegin,
+ owner: .meetingMicrophone,
+ objectID: requestedDeviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .actorControl,
+ phase: .listener
+ )
#endif
let status = await AudioTopologyListenerExecution.add(
objectID: requestedDeviceID,
@@ -1736,7 +1860,17 @@ actor MeetingMicrophoneCapture {
token: token
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerAddEnd, owner: .meetingMicrophone, objectID: requestedDeviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener, status: status)
+ AudioTopologyDiagnostics.record(
+ .listenerAddEnd,
+ owner: .meetingMicrophone,
+ objectID: requestedDeviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .actorControl,
+ phase: .listener,
+ status: status
+ )
#endif
if status == noErr, self.isRunning, self.generationBox.isCurrent(generation) {
self.overloadListenerToken = token
@@ -1764,7 +1898,16 @@ actor MeetingMicrophoneCapture {
mElement: kAudioObjectPropertyElementMain
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .meetingMicrophone, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveBegin,
+ owner: .meetingMicrophone,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .actorControl,
+ phase: .listener
+ )
#endif
let status = await AudioTopologyListenerExecution.remove(
objectID: AudioObjectID(kAudioObjectSystemObject),
@@ -1772,7 +1915,17 @@ actor MeetingMicrophoneCapture {
token: token
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .meetingMicrophone, objectID: AudioObjectID(kAudioObjectSystemObject), selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener, status: status)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveEnd,
+ owner: .meetingMicrophone,
+ objectID: AudioObjectID(kAudioObjectSystemObject),
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .actorControl,
+ phase: .listener,
+ status: status
+ )
#endif
}
if let token = overloadToken, let deviceID = overloadDeviceID {
@@ -1782,7 +1935,16 @@ actor MeetingMicrophoneCapture {
mElement: kAudioObjectPropertyElementMain
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveBegin, owner: .meetingMicrophone, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveBegin,
+ owner: .meetingMicrophone,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .actorControl,
+ phase: .listener
+ )
#endif
let status = await AudioTopologyListenerExecution.remove(
objectID: deviceID,
@@ -1790,7 +1952,17 @@ actor MeetingMicrophoneCapture {
token: token
)
#if DEBUG
- AudioTopologyDiagnostics.record(.listenerRemoveEnd, owner: .meetingMicrophone, objectID: deviceID, selector: address.mSelector, scope: address.mScope, element: address.mElement, queueRole: .actorControl, phase: .listener, status: status)
+ AudioTopologyDiagnostics.record(
+ .listenerRemoveEnd,
+ owner: .meetingMicrophone,
+ objectID: deviceID,
+ selector: address.mSelector,
+ scope: address.mScope,
+ element: address.mElement,
+ queueRole: .actorControl,
+ phase: .listener,
+ status: status
+ )
#endif
}
}
@@ -1813,7 +1985,7 @@ actor MeetingMicrophoneCapture {
}
private static func readBackBoundDevice(_ audioUnit: AudioUnit) -> AudioObjectID? {
- Self.currentDevice(audioUnit, element: Self.inputElement)
+ self.currentDevice(audioUnit, element: self.inputElement)
}
static func currentDevice(_ audioUnit: AudioUnit, element: AudioUnitElement) -> AudioObjectID? {
@@ -1877,9 +2049,9 @@ enum MeetingMicrophonePhase1Probe {
var outcome: MeetingMicrophoneBindingOutcome
var settled: MeetingMicrophoneSettledConfig?
var voiceProcessingReadback: MeetingVoiceProcessingProbeSnapshot?
-#if DEBUG
+ #if DEBUG
var acousticTrialB: MeetingVPIOAcousticTrialBReport?
-#endif
+ #endif
var stats: MeetingMicrophoneCaptureStats.Snapshot
var writerDiscontinuities: Int
var writerRotationCount: Int
@@ -1935,9 +2107,9 @@ enum MeetingMicrophonePhase1Probe {
var deliveredSourceFormat = "(none delivered)"
let capturedFormat = OSAllocatedUnfairLock<String?>(initialState: nil)
let tapTelemetry = OSAllocatedUnfairLock<(nilCopies: Int, peak: Float)>(initialState: (0, 0))
-#if DEBUG
+ #if DEBUG
let acousticCollector = MeetingVPIOAcousticCaptureCollector()
-#endif
+ #endif
let capture = MeetingMicrophoneCapture()
let outcome: MeetingMicrophoneBindingOutcome
@@ -1945,30 +2117,30 @@ enum MeetingMicrophonePhase1Probe {
outcome = try await capture.start(
microphone: microphone,
onSample: { sampleBuffer in
- if let description = CMSampleBufferGetFormatDescription(sampleBuffer),
- let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(description)?.pointee
- {
- capturedFormat.withLock { $0 = "\(asbd.mSampleRate)Hz \(asbd.mChannelsPerFrame)ch" }
- }
- let copied = MeetingLiveSampleCopy.copy(sampleBuffer)
- let bufferPeak: Float = copied.flatMap { sample -> Float? in
- guard let channel = sample.buffer.floatChannelData?[0] else { return nil }
- var peak: Float = 0
- vDSP_maxmgv(channel, 1, &peak, vDSP_Length(sample.buffer.frameLength))
- return peak
- } ?? 0
- tapTelemetry.withLock {
- if copied == nil { $0.nilCopies += 1 }
- $0.peak = max($0.peak, bufferPeak)
- }
- writer.enqueue(sampleBuffer)
+ if let description = CMSampleBufferGetFormatDescription(sampleBuffer),
+ let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(description)?.pointee
+ {
+ capturedFormat.withLock { $0 = "\(asbd.mSampleRate)Hz \(asbd.mChannelsPerFrame)ch" }
+ }
+ let copied = MeetingLiveSampleCopy.copy(sampleBuffer)
+ let bufferPeak: Float = copied.flatMap { sample -> Float? in
+ guard let channel = sample.buffer.floatChannelData?[0] else { return nil }
+ var peak: Float = 0
+ vDSP_maxmgv(channel, 1, &peak, vDSP_Length(sample.buffer.frameLength))
+ return peak
+ } ?? 0
+ tapTelemetry.withLock {
+ if copied == nil { $0.nilCopies += 1 }
+ $0.peak = max($0.peak, bufferPeak)
+ }
+ writer.enqueue(sampleBuffer)
},
onSampleMetadata: { sampleBuffer, synthesized, resynced in
-#if DEBUG
+ #if DEBUG
acousticCollector.ingest(sampleBuffer, synthesized: synthesized, resynced: resynced)
- #else
+ #else
_ = (sampleBuffer, synthesized, resynced)
- #endif
+ #endif
}
)
} catch {
@@ -1976,11 +2148,11 @@ enum MeetingMicrophonePhase1Probe {
throw error
}
-#if DEBUG
+ #if DEBUG
let acousticTrialB = await MeetingVPIOAcousticTrialB.run(
capture: capture, collector: acousticCollector, sampleRate: 48_000
)
-#endif
+ #endif
do {
try await Task.sleep(nanoseconds: UInt64(minutes * 60 * 1_000_000_000))
@@ -1988,11 +2160,11 @@ enum MeetingMicrophonePhase1Probe {
// Cancellation after the engine was published must stop this exact generation and
// close the writer before the probe task exits; otherwise callbacks can outlive the
// diagnostic and retain a live input route.
-#if DEBUG
+ #if DEBUG
await capture.stopForPhase1Probe()
-#else
+ #else
await capture.stop()
-#endif
+ #endif
_ = await writer.stop()
throw error
}
@@ -2000,16 +2172,16 @@ enum MeetingMicrophonePhase1Probe {
// The app-hosted diagnostic process exits after this one test. Avoid the explicit VPIO
// replacement during teardown here: on macOS 26.6 that replacement crashes inside
// AVAudioIONode after a live output-node read-back. Normal product teardown is unchanged.
-#if DEBUG
+ #if DEBUG
await capture.stopForPhase1Probe()
-#else
+ #else
await capture.stop()
-#endif
+ #endif
let finishedTrack = await writer.stop()
deliveredSourceFormat = capturedFormat.withLock { $0 } ?? deliveredSourceFormat
let telemetry = tapTelemetry.withLock { $0 }
-#if DEBUG
+ #if DEBUG
return Result(
minutes: minutes,
outcome: outcome,
@@ -2025,7 +2197,7 @@ enum MeetingMicrophonePhase1Probe {
deliveredSourceFormat: deliveredSourceFormat,
peakAmplitude: telemetry.peak
)
-#else
+ #else
return Result(
minutes: minutes,
outcome: outcome,
@@ -2040,6 +2212,6 @@ enum MeetingMicrophonePhase1Probe {
deliveredSourceFormat: deliveredSourceFormat,
peakAmplitude: telemetry.peak
)
-#endif
+ #endif
}
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingMicrophoneEvidence.swift b/Sources/Fluid/Services/Meeting/MeetingMicrophoneEvidence.swift
index e9326791..e255a2ae 100644
--- a/Sources/Fluid/Services/Meeting/MeetingMicrophoneEvidence.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingMicrophoneEvidence.swift
@@ -47,7 +47,7 @@ nonisolated struct MeetingMicrophoneEvidence: Equatable, Sendable {
init?(sessionID: UUID, chunkID: UUID, turnIndex: Int, captureEpoch: UInt64, observation: Observation) {
guard turnIndex >= 0 else { return nil }
- if case .clusterLabel(let label) = observation, label.isEmpty { return nil }
+ if case let .clusterLabel(label) = observation, label.isEmpty { return nil }
self.sessionID = sessionID
self.chunkID = chunkID
self.turnIndex = turnIndex
@@ -55,10 +55,10 @@ nonisolated struct MeetingMicrophoneEvidence: Equatable, Sendable {
self.observation = observation
}
- var turnKey: String { "microphone:\(chunkID.uuidString):\(turnIndex)" }
+ var turnKey: String { "microphone:\(self.chunkID.uuidString):\(self.turnIndex)" }
var observationKey: String? {
- guard case .clusterLabel(let label) = observation else { return nil }
- return "microphone:\(chunkID.uuidString):\(label)"
+ guard case let .clusterLabel(label) = observation else { return nil }
+ return "microphone:\(self.chunkID.uuidString):\(label)"
}
}
@@ -79,6 +79,7 @@ nonisolated struct MeetingMicrophoneEvidence: Equatable, Sendable {
enum State: Equatable, Sendable {
case insufficientEvidence, observing, duplicateCandidate, duplicateSupported
}
+
let state: State
let identity: Identity
let interval: Interval
@@ -103,15 +104,17 @@ nonisolated struct MeetingMicrophoneEvidence: Equatable, Sendable {
/// Compatibility projection only; detailed unknown reasons survive in the evidence itself.
var legacySignalVerdict: TurnEchoVerdict {
- guard case .measured(let verdict) = signalVerdict else { return .unknown }
+ guard case let .measured(verdict) = signalVerdict else { return .unknown }
return verdict
}
}
/// Stage A seam; the only implementation is a test fake. Stage B owns real paired-audio analysis.
nonisolated protocol MeetingPlaybackDuplicateEvidenceSource: Sendable {
- func evidence(for identity: MeetingMicrophoneEvidence.Identity,
- interval: MeetingMicrophoneEvidence.Interval) -> MeetingMicrophoneEvidence.Measurement<MeetingMicrophoneEvidence.TemporalDuplicate>
+ func evidence(
+ for identity: MeetingMicrophoneEvidence.Identity,
+ interval: MeetingMicrophoneEvidence.Interval
+ ) -> MeetingMicrophoneEvidence.Measurement<MeetingMicrophoneEvidence.TemporalDuplicate>
}
/// Test-only caller contract: no runtime enablement flag or production invocation in Stage A.
@@ -121,11 +124,13 @@ nonisolated enum MeetingMicrophoneShadowPolicy {
enum ProposedOutcome: Equatable, Sendable {
case uncertainCandidate
}
+
enum Reason: Equatable, Sendable {
case legacyRescueDisagreement, playbackDuplicateCandidate, speechActivityIsNotNearEndProof
case negativeActivityIsNotSpeechAbsenceProof, insufficientEvidence
case staleTemporalEvidence, invalidTemporalEvidence, missingPlaybackContext
}
+
struct Evaluation: Equatable, Sendable {
let outcome: ProposedOutcome = .uncertainCandidate
let experimental = true
@@ -139,18 +144,22 @@ nonisolated enum MeetingMicrophoneShadowPolicy {
static func evaluate(_ evidence: MeetingMicrophoneEvidence) -> Evaluation {
func result(_ reason: Reason) -> Evaluation {
let unknown: MeetingMicrophoneEvidence.UnknownReason?
- if case .unavailable(let why) = evidence.signalVerdict { unknown = why } else { unknown = nil }
- return Evaluation(reason: reason, identity: evidence.identity, interval: evidence.interval,
- signalUnknownReason: unknown)
+ if case let .unavailable(why) = evidence.signalVerdict { unknown = why } else { unknown = nil }
+ return Evaluation(
+ reason: reason,
+ identity: evidence.identity,
+ interval: evidence.interval,
+ signalUnknownReason: unknown
+ )
}
- if case .measured(let temporal) = evidence.temporalDuplicate {
+ if case let .measured(temporal) = evidence.temporalDuplicate {
guard temporal.identity == evidence.identity,
temporal.interval == evidence.interval else { return result(.staleTemporalEvidence) }
guard temporal.supportingWindows >= 0 else { return result(.invalidTemporalEvidence) }
- if case .measured(let lag) = temporal.microphoneDelaySeconds, !lag.isFinite {
+ if case let .measured(lag) = temporal.microphoneDelaySeconds, !lag.isFinite {
return result(.invalidTemporalEvidence)
}
- if case .measured(let spread) = temporal.lagSpreadSeconds, !spread.isFinite || spread < 0 {
+ if case let .measured(spread) = temporal.lagSpreadSeconds, !spread.isFinite || spread < 0 {
return result(.invalidTemporalEvidence)
}
if temporal.state == .duplicateSupported {
@@ -169,7 +178,7 @@ nonisolated enum MeetingMicrophoneShadowPolicy {
if evidence.signalVerdict == .measured(.echo) || evidence.textEcho == .measured(true) {
return result(.playbackDuplicateCandidate)
}
- if case .measured(let temporal) = evidence.temporalDuplicate, temporal.state == .duplicateSupported {
+ if case let .measured(temporal) = evidence.temporalDuplicate, temporal.state == .duplicateSupported {
return result(.playbackDuplicateCandidate)
}
switch evidence.speechActivity {
diff --git a/Sources/Fluid/Services/Meeting/MeetingModels.swift b/Sources/Fluid/Services/Meeting/MeetingModels.swift
index 0f2181fa..483ae9b4 100644
--- a/Sources/Fluid/Services/Meeting/MeetingModels.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingModels.swift
@@ -608,13 +608,15 @@ nonisolated struct MeetingAudioTrack: Identifiable, Equatable, Sendable {
var timebase: MeetingTimebaseMetadata
var health: MeetingTrackHealth
var chunks: [MeetingAudioChunk]
- var captureMethod: MeetingAudioTrackCaptureMethod? = nil
- var voiceProcessingConfig: MeetingMicrophoneSettledConfig? = nil
- var clockDrift: MeetingClockDriftRecord? = nil
- /// Ordered. PERSISTED startSeconds mixes domains: index 0 stores 0, eras 1+ store raw PTS
- /// seconds — readers must go through the pipeline's microphoneEras(for:origin:), which
- /// normalizes to origin-relative. Absence means single-era legacy.
- var captureEras: [MeetingCaptureEra]? = nil
+ var captureMethod: MeetingAudioTrackCaptureMethod?
+ var voiceProcessingConfig: MeetingMicrophoneSettledConfig?
+ var clockDrift: MeetingClockDriftRecord?
+ // Ordered. PERSISTED startSeconds mixes domains: index 0 stores 0, eras 1+ store raw PTS
+ // seconds — readers must go through the pipeline's microphoneEras(for:origin:), which
+ // normalizes to origin-relative. Absence means single-era legacy.
+ // nil means unavailable; an empty result means available with no values.
+ // swiftlint:disable:next discouraged_optional_collection
+ var captureEras: [MeetingCaptureEra]?
init(
id: MeetingAudioTrackID,
@@ -628,6 +630,8 @@ nonisolated struct MeetingAudioTrack: Identifiable, Equatable, Sendable {
captureMethod: MeetingAudioTrackCaptureMethod? = nil,
voiceProcessingConfig: MeetingMicrophoneSettledConfig? = nil,
clockDrift: MeetingClockDriftRecord? = nil,
+ // nil means unavailable; an empty result means available with no values.
+ // swiftlint:disable:next discouraged_optional_collection
captureEras: [MeetingCaptureEra]? = nil
) {
self.id = id
@@ -673,6 +677,8 @@ extension MeetingAudioTrack: Codable {
private static func decodeTolerantCaptureEras(
container: KeyedDecodingContainer<CodingKeys>,
key: CodingKeys
+ // nil means unavailable; an empty result means available with no values.
+ // swiftlint:disable:next discouraged_optional_collection
) throws -> [MeetingCaptureEra]? {
guard container.contains(key) else { return nil }
var unkeyed = try container.nestedUnkeyedContainer(forKey: key)
@@ -871,7 +877,9 @@ nonisolated struct MeetingSession: Codable, Identifiable, Equatable, Sendable {
var audioTracks: [MeetingAudioTrack]
var speakers: [MeetingSessionSpeaker]
var transcriptSegments: [MeetingTranscriptSegment]
- /// Audio intervals intentionally excluded from the transcript. Optional for schema-1 sessions.
+ // Audio intervals intentionally excluded from the transcript. Optional for schema-1 sessions.
+ // nil means unavailable; an empty result means available with no values.
+ // swiftlint:disable:next discouraged_optional_collection
var transcriptCoverageGaps: [MeetingTranscriptCoverageGap]? = nil
/// Verified reference to the canonical attempt's durable result sidecar inside this session's
/// directory. Optional and backward compatible: sessions written before canonical publication
diff --git a/Sources/Fluid/Services/Meeting/MeetingPCMStoragePolicy.swift b/Sources/Fluid/Services/Meeting/MeetingPCMStoragePolicy.swift
index fcd82f28..f145d68a 100644
--- a/Sources/Fluid/Services/Meeting/MeetingPCMStoragePolicy.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingPCMStoragePolicy.swift
@@ -22,7 +22,7 @@ nonisolated enum MeetingPCMStoragePolicy {
/// mono. The count is intentionally bounded to the supported topology.
static func pcmBytesPerSecond(trackCount: Int) -> Int64 {
let channels = trackCount >= 2 ? 3 : 1
- return sampleRate * bytesPerSample * Int64(channels)
+ return self.sampleRate * self.bytesPerSample * Int64(channels)
}
static func estimatedPCMBytes(
@@ -31,7 +31,7 @@ nonisolated enum MeetingPCMStoragePolicy {
) -> Int64 {
guard duration.isFinite, duration > 0 else { return 0 }
let seconds = Int64(ceil(duration))
- return pcmBytesPerSecond(trackCount: trackCount) * seconds
+ return self.pcmBytesPerSecond(trackCount: trackCount) * seconds
}
/// Free-space floor required before starting a capture. The safety multiplier covers file
@@ -42,13 +42,13 @@ nonisolated enum MeetingPCMStoragePolicy {
duration: TimeInterval = Self.defaultMeetingDuration
) -> Int64 {
let pcm = Double(estimatedPCMBytes(trackCount: trackCount, duration: duration))
- let protectedPCM = Int64(ceil(pcm * safetyMultiplier))
- return protectedPCM + materializationHeadroomBytes + stagingHeadroomBytes
+ let protectedPCM = Int64(ceil(pcm * self.safetyMultiplier))
+ return protectedPCM + self.materializationHeadroomBytes + self.stagingHeadroomBytes
}
static func requiredFreeSpaceDescription(trackCount: Int) -> String {
let formatter = ByteCountFormatter()
formatter.countStyle = .file
- return formatter.string(fromByteCount: requiredFreeBytes(trackCount: trackCount))
+ return formatter.string(fromByteCount: self.requiredFreeBytes(trackCount: trackCount))
}
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingPlaybackDuplicateDetector.swift b/Sources/Fluid/Services/Meeting/MeetingPlaybackDuplicateDetector.swift
index edccce2f..e0d9f03c 100644
--- a/Sources/Fluid/Services/Meeting/MeetingPlaybackDuplicateDetector.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingPlaybackDuplicateDetector.swift
@@ -6,14 +6,14 @@ import Foundation
/// Correlation is not a speech detector and cannot rule out quiet double talk.
nonisolated struct MeetingPlaybackDuplicateDetector {
static let version = "temporal-shadow-b1-v1"
- static let sampleRate = 2_000.0
+ static let sampleRate = 2000.0
struct Configuration: Codable, Sendable {
// Exploratory engineering constants, not calibrated admission thresholds.
var minimumCorrelation = 0.25
var minimumControlMargin = 0.08
var minimumPeakMargin = 0.025
- var minimumRMS = 0.00001
+ var minimumRMS = 0.00_001
var stableLagSeconds = 0.012
var supportWindows = 3
var budgetSeconds = 0.5
@@ -41,11 +41,13 @@ nonisolated struct MeetingPlaybackDuplicateDetector {
enum State: String, Codable, Sendable {
case insufficientEvidence, observing, duplicateCandidate, duplicateSupported
}
+
enum Reason: String, Codable, Sendable {
case referenceUnavailable, controlUnavailable, invalidInput, unscoredCoverage, insufficientEnergy
case ambiguousPeak, scoredInconclusive, accumulating, stableSupport, released
case overBudget, detectorUnavailable
}
+
struct Result: Codable, Sendable {
let start: Double
let end: Double
@@ -70,8 +72,10 @@ nonisolated struct MeetingPlaybackDuplicateDetector {
private var budgetFailures = 0
private var disabled = false
- init(configuration: Configuration = .init(),
- clock: @escaping @Sendable () -> Double = { ProcessInfo.processInfo.systemUptime }) {
+ init(
+ configuration: Configuration = .init(),
+ clock: @escaping @Sendable () -> Double = { ProcessInfo.processInfo.systemUptime }
+ ) {
self.configuration = configuration
self.clock = clock
}
@@ -80,29 +84,39 @@ nonisolated struct MeetingPlaybackDuplicateDetector {
/// No release hangover in v1: failed support immediately removes supported evidence. This
/// conservative zero-hold choice must be measured before introducing a nonzero hold period.
mutating func process(_ window: Window) -> Result {
- let began = clock()
+ let began = self.clock()
// Failure latch is attempt-local; a new recording gets a fresh budget allowance.
- if sessionID != window.sessionID { budgetFailures = 0; disabled = false }
- sessionID = window.sessionID
+ if self.sessionID != window.sessionID { self.budgetFailures = 0; self.disabled = false }
+ self.sessionID = window.sessionID
let newScope = "\(window.sessionID):\(window.epoch):\(window.routeID)"
- if scope != newScope || lastEnd.map({ abs($0 - window.start) > 0.00025 }) != false {
- lags.removeAll()
+ if self.scope != newScope || self.lastEnd.map({ abs($0 - window.start) > 0.00_025 }) != false {
+ self.lags.removeAll()
}
- scope = newScope
- lastEnd = window.start + 2
- func result(_ reason: Reason, _ state: State = .insufficientEvidence,
- _ correlation: Double? = nil, _ control: Double? = nil,
- _ delay: Double? = nil) -> Result {
- Result(start: window.start.isFinite ? window.start : 0,
- end: window.start.isFinite ? window.start + 2 : 0,
- epoch: window.epoch, state: state, reason: reason,
- supportingWindows: lags.count, correlation: correlation,
- controlCorrelation: control, microphoneDelaySeconds: delay,
- lagSpreadSeconds: lags.isEmpty ? nil : lags.max()! - lags.min()!,
- elapsedSeconds: max(0, clock() - began))
+ self.scope = newScope
+ self.lastEnd = window.start + 2
+ func result(
+ _ reason: Reason,
+ _ state: State = .insufficientEvidence,
+ _ correlation: Double? = nil,
+ _ control: Double? = nil,
+ _ delay: Double? = nil
+ ) -> Result {
+ Result(
+ start: window.start.isFinite ? window.start : 0,
+ end: window.start.isFinite ? window.start + 2 : 0,
+ epoch: window.epoch,
+ state: state,
+ reason: reason,
+ supportingWindows: self.lags.count,
+ correlation: correlation,
+ controlCorrelation: control,
+ microphoneDelaySeconds: delay,
+ lagSpreadSeconds: self.lags.max().flatMap { maximum in self.lags.min().map { maximum - $0 } },
+ elapsedSeconds: max(0, self.clock() - began)
+ )
}
- if disabled { lags.removeAll(); return result(.detectorUnavailable) }
- let c = configuration
+ if self.disabled { self.lags.removeAll(); return result(.detectorUnavailable) }
+ let c = self.configuration
guard window.start.isFinite, window.start >= 0, !window.routeID.isEmpty,
c.minimumCorrelation.isFinite, (0...1).contains(c.minimumCorrelation),
c.minimumControlMargin.isFinite, (0...1).contains(c.minimumControlMargin),
@@ -110,34 +124,38 @@ nonisolated struct MeetingPlaybackDuplicateDetector {
c.minimumRMS.isFinite, c.minimumRMS > 0,
c.stableLagSeconds.isFinite, (0...0.5).contains(c.stableLagSeconds),
(2...16).contains(c.supportWindows), c.budgetSeconds.isFinite, c.budgetSeconds > 0,
- (1...10).contains(c.maximumConsecutiveBudgetFailures) else {
- lags.removeAll(); return result(.invalidInput)
+ (1...10).contains(c.maximumConsecutiveBudgetFailures)
+ else {
+ self.lags.removeAll(); return result(.invalidInput)
}
guard let reference = window.reference else {
- lags.removeAll(); budgetFailures = 0; return result(.referenceUnavailable)
+ self.lags.removeAll(); self.budgetFailures = 0; return result(.referenceUnavailable)
}
guard let control = window.mismatchedReference else {
- lags.removeAll(); budgetFailures = 0; return result(.controlUnavailable)
+ self.lags.removeAll(); self.budgetFailures = 0; return result(.controlUnavailable)
}
// Validate sizes before allocating aligned arrays. ±0.5s search needs a 3-second halo.
+ // nil represents unavailable or invalid evidence, distinct from a valid empty collection.
+ // swiftlint:disable:next discouraged_optional_collection
func aligned(_ pcm: PCM, halo: Int) -> [Double]? {
guard pcm.start.isFinite, pcm.samples.count == pcm.valid.count,
pcm.samples.count <= 16_000 else { return nil }
let offset = (window.start - pcm.start) * Self.sampleRate - Double(halo)
guard offset.isFinite, offset >= 0, offset <= Double(pcm.samples.count),
abs(offset - offset.rounded()) < 0.001 else { return nil }
- let first = Int(offset.rounded()), count = 4_000 + 2 * halo
+ let first = Int(offset.rounded()), count = 4000 + 2 * halo
guard first <= pcm.samples.count - count else { return nil }
let range = first..<(first + count)
guard range.allSatisfy({ pcm.valid[$0] && pcm.samples[$0].isFinite }) else { return nil }
return range.map { Double(pcm.samples[$0]) }
}
guard let mic = aligned(window.microphone, halo: 0),
- let ref = aligned(reference, halo: 1_000),
- let null = aligned(control, halo: 1_000) else {
- lags.removeAll(); budgetFailures = 0; return result(.unscoredCoverage)
+ let ref = aligned(reference, halo: 1000),
+ let null = aligned(control, halo: 1000)
+ else {
+ self.lags.removeAll(); self.budgetFailures = 0; return result(.unscoredCoverage)
}
- let mean = mic.reduce(0, +) / 4_000
+ let mean = mic.reduce(0, +) / 4000
let centered = mic.map { $0 - mean }
let energy = centered.reduce(0) { $0 + $1 * $1 }
func usableEnergy(_ samples: [Double]) -> Bool {
@@ -145,57 +163,66 @@ nonisolated struct MeetingPlaybackDuplicateDetector {
return samples.reduce(0) { $0 + ($1 - average) * ($1 - average) }
/ Double(samples.count) >= c.minimumRMS * c.minimumRMS
}
- guard energy / 4_000 >= c.minimumRMS * c.minimumRMS,
- usableEnergy(ref), usableEnergy(null) else {
- lags.removeAll(); budgetFailures = 0; return result(.insufficientEnergy)
+ guard energy / 4000 >= c.minimumRMS * c.minimumRMS,
+ usableEnergy(ref), usableEnergy(null)
+ else {
+ self.lags.removeAll(); self.budgetFailures = 0; return result(.insufficientEnergy)
}
// Search at 1 ms resolution. Peak ambiguity excludes a ±12ms neighborhood.
+ // nil represents unavailable or invalid evidence, distinct from a valid empty collection.
+ // swiftlint:disable:next discouraged_optional_collection
func scores(_ samples: [Double]) -> [(lag: Int, score: Double)]? {
var output: [(Int, Double)] = []
- for lag in stride(from: -1_000, through: 1_000, by: 2) {
- if clock() - began > c.budgetSeconds { return nil }
- let first = 1_000 - lag
+ for lag in stride(from: -1000, through: 1000, by: 2) {
+ if self.clock() - began > c.budgetSeconds { return nil }
+ let first = 1000 - lag
var sum = 0.0, squared = 0.0, cross = 0.0
- for i in 0..<4_000 {
+ for i in 0..<4000 {
let value = samples[first + i]
sum += value; squared += value * value; cross += centered[i] * value
}
- let refEnergy = max(0, squared - sum * sum / 4_000)
- let score = refEnergy / 4_000 >= c.minimumRMS * c.minimumRMS
+ let refEnergy = max(0, squared - sum * sum / 4000)
+ let score = refEnergy / 4000 >= c.minimumRMS * c.minimumRMS
? min(1, abs(cross) / sqrt(energy * refEnergy)) : 0
output.append((lag, score))
}
return output
}
- guard let matches = scores(ref), let controls = scores(null) else {
- lags.removeAll(); budgetFailures += 1
- disabled = budgetFailures >= c.maximumConsecutiveBudgetFailures
+ guard let matches = scores(ref), let controls = scores(null),
+ let peak = matches.max(by: { $0.score < $1.score }),
+ let nullPeak = controls.map(\.score).max()
+ else {
+ self.lags.removeAll(); self.budgetFailures += 1
+ self.disabled = self.budgetFailures >= c.maximumConsecutiveBudgetFailures
return result(.overBudget)
}
- budgetFailures = 0
- let peak = matches.max { $0.score < $1.score }!
- let nullPeak = controls.map(\.score).max()!
+ self.budgetFailures = 0
let secondary = matches.filter { abs($0.lag - peak.lag) > 24 }.map(\.score).max() ?? 0
let lag = Double(peak.lag) / Self.sampleRate
- let wasSupported = lags.count >= c.supportWindows
+ let wasSupported = self.lags.count >= c.supportWindows
guard peak.score >= c.minimumCorrelation, peak.score - nullPeak >= c.minimumControlMargin else {
- lags.removeAll()
+ self.lags.removeAll()
return result(wasSupported ? .released : .scoredInconclusive, .observing, peak.score, nullPeak, lag)
}
- guard peak.score - secondary >= c.minimumPeakMargin, abs(peak.lag) < 1_000 else {
- lags.removeAll(); return result(.ambiguousPeak, .observing, peak.score, nullPeak, lag)
+ guard peak.score - secondary >= c.minimumPeakMargin, abs(peak.lag) < 1000 else {
+ self.lags.removeAll(); return result(.ambiguousPeak, .observing, peak.score, nullPeak, lag)
}
// Compare quantized sample offsets so an exact 12ms spread cannot become
// 0.012000000000000004 and spuriously reset support.
if let low = lags.min(), let high = lags.max(),
Int(((max(high, lag) - min(low, lag)) * Self.sampleRate).rounded())
- > Int((c.stableLagSeconds * Self.sampleRate).rounded(.down)) {
- lags.removeAll()
+ > Int((c.stableLagSeconds * Self.sampleRate).rounded(.down))
+ {
+ self.lags.removeAll()
}
- lags.append(lag)
- if lags.count > c.supportWindows { lags.removeFirst() }
- return result(lags.count >= c.supportWindows ? .stableSupport : .accumulating,
- lags.count >= c.supportWindows ? .duplicateSupported : .duplicateCandidate,
- peak.score, nullPeak, lag)
+ self.lags.append(lag)
+ if self.lags.count > c.supportWindows { self.lags.removeFirst() }
+ return result(
+ self.lags.count >= c.supportWindows ? .stableSupport : .accumulating,
+ self.lags.count >= c.supportWindows ? .duplicateSupported : .duplicateCandidate,
+ peak.score,
+ nullPeak,
+ lag
+ )
}
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift b/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift
index 668d5b86..43078787 100644
--- a/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingProcessingPipeline.swift
@@ -196,24 +196,6 @@ nonisolated struct MeetingGlobalSpeakerStitcher {
let embedding: [Float]
let quality: Float
let effectiveSpeechDuration: TimeInterval
-
- init(
- key: String,
- chunkKey: String,
- trackKind: MeetingAudioTrackKind,
- localLabel: String,
- embedding: [Float],
- quality: Float,
- effectiveSpeechDuration: TimeInterval
- ) {
- self.key = key
- self.chunkKey = chunkKey
- self.trackKind = trackKind
- self.localLabel = localLabel
- self.embedding = embedding
- self.quality = quality
- self.effectiveSpeechDuration = effectiveSpeechDuration
- }
}
nonisolated struct Prototype: Equatable {
@@ -430,8 +412,8 @@ nonisolated struct MeetingGlobalSpeakerStitcher {
distance <= self.configuration.coreMaximumDistance
else { continue }
let candidate = (left, right, distance)
- if best == nil || distance < best!.distance
- || (distance == best!.distance && Self.pairPrecedes(candidate, best!, clusters: clusters))
+ if best.map({ distance < $0.distance
+ || (distance == $0.distance && Self.pairPrecedes(candidate, $0, clusters: clusters)) }) ?? true
{
best = candidate
}
@@ -495,6 +477,8 @@ nonisolated struct MeetingGlobalSpeakerStitcher {
return left < right
}
+ // nil represents unavailable or invalid evidence, distinct from a valid empty collection.
+ // swiftlint:disable:next discouraged_optional_collection
private static func normalized(_ embedding: [Float]) -> [Float]? {
guard let distance = MeetingSpeakerEmbeddingIndex.cosineDistance(embedding, embedding), distance.isFinite else { return nil }
let magnitude = sqrt(embedding.reduce(Float.zero) { $0 + $1 * $1 })
@@ -517,6 +501,8 @@ nonisolated enum MeetingTurnSelection {
/// Drops empty-text turns; nil when all were empty (caller falls back to whole-chunk).
static func keepingNonEmpty<T>(
_ turns: [(index: Int, turn: T, text: String)]
+ // nil represents unavailable or invalid evidence, distinct from a valid empty collection.
+ // swiftlint:disable:next discouraged_optional_collection
) -> [(index: Int, turn: T, text: String)]? {
let nonEmpty = turns.filter { !$0.text.isEmpty }
return nonEmpty.isEmpty ? nil : nonEmpty
@@ -653,6 +639,8 @@ private final class MeetingProviderLanguagePin {
}
@MainActor
+// Keep this existing processing state machine intact during integration.
+// swiftlint:disable:next type_body_length
final class MeetingProcessingPipeline: MeetingProcessingControlling {
/// Bump whenever classification rules change so a resumed run can't mix rules mid-session.
/// Era-awareness did NOT bump this: the mic pass re-runs every time, and multi-era tracks cannot predate this build.
@@ -678,6 +666,8 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
/// On speakers nearly everything overlaps, so overlap cannot identify the mic's owner.
/// What can: speech that is not the far end coming back.
nonisolated static func localSpeakerEvidence(
+ // Keep this existing grouped state result intact during integration.
+ // swiftlint:disable:next large_tuple
from turns: [(
clusterID: SessionSpeakerID, start: TimeInterval, end: TimeInterval,
overlapsRemote: Bool, echoScored: Bool, isEcho: Bool
@@ -736,6 +726,8 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
captureMethod: MeetingAudioTrackCaptureMethod?,
// `unscoredOverlap` pins to 0.0s under VPIO; this carries the widening delta instead.
widenedIndices: Set<Int> = [],
+ // nil represents unavailable or invalid evidence, distinct from a valid empty collection.
+ // swiftlint:disable:next discouraged_optional_collection
captureEras: [MeetingCaptureEra]? = nil
) {
let widenedSeconds = widenedIndices.reduce(0.0) { total, offset in
@@ -762,7 +754,12 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
let proto = prototypeSpeakerIDs.contains(id) ? "yes" : "NO"
return String(
format: "%@ supporting=%.1fs echoed=%.1fs unscoredOverlap=%.1fs prototype=%@ netEvidence=%@",
- id.uuidString.prefix(8).description, s, e, k, proto, s > e ? "counts" : "DROPPED"
+ id.uuidString.prefix(8).description,
+ s,
+ e,
+ k,
+ proto,
+ s > e ? "counts" : "DROPPED"
)
}
.sorted()
@@ -781,8 +778,10 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
else { continue }
distances.append(String(
format: "%@↔%@ cosineDistance=%.3f (mergeThreshold=%.2f) %@",
- left.uuidString.prefix(8).description, right.uuidString.prefix(8).description,
- distance, index.maximumCosineDistance,
+ left.uuidString.prefix(8).description,
+ right.uuidString.prefix(8).description,
+ distance,
+ index.maximumCosineDistance,
distance <= index.maximumCosineDistance ? "SAME VOICE" : "different"
))
}
@@ -834,7 +833,11 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
DebugLogger.shared.info(
String(
format: "Near-field gate: era %d dropped %.1fs of %d microphone turns below reference %.5f RMS − %.0f dB",
- eraIndex, eraRejectedSeconds, eraTurns.count, reference ?? 0, MeetingNearFieldGate.rejectionDepthDB
+ eraIndex,
+ eraRejectedSeconds,
+ eraTurns.count,
+ reference ?? 0,
+ MeetingNearFieldGate.rejectionDepthDB
),
source: "MeetingProcessingPipeline"
)
@@ -1100,9 +1103,14 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
DebugLogger.shared.info(
String(
format: "[echoframes] turn=[%.1f-%.1f] %.1fs median=%.2f scoreable=%.0f%% lowRun=%.2fs (%.1f%% of turn) verdict=%@",
- turnStart, turnEnd, turnSeconds, median,
+ turnStart,
+ turnEnd,
+ turnSeconds,
+ median,
100 * Double(scoreable.count) / Double(scores.fractions.count),
- lowRunSeconds, 100 * lowRunSeconds / turnSeconds, String(describing: verdict)
+ lowRunSeconds,
+ 100 * lowRunSeconds / turnSeconds,
+ String(describing: verdict)
),
source: "MeetingProcessingPipeline"
)
@@ -1156,9 +1164,11 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
var delayConfidence: Double? = nil
}
- /// Every failure here (missing/corrupt reference audio, decode errors, bad timing math, ...)
- /// degrades to `.unknown` rather than propagating: a sick application-audio track must never
- /// take down an otherwise-healthy microphone chunk.
+ // Every failure here (missing/corrupt reference audio, decode errors, bad timing math, ...)
+ // degrades to `.unknown` rather than propagating: a sick application-audio track must never
+ // take down an otherwise-healthy microphone chunk.
+ // Keep the existing capture/processing contract explicit during integration.
+ // swiftlint:disable:next function_parameter_count
nonisolated static func computeEchoVerdicts(
micChunk: MeetingAudioChunk,
micChunkURL: URL,
@@ -1699,7 +1709,7 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
private nonisolated static func joinTranscriptText(_ left: String, _ right: String) -> String {
guard let first = right.first else { return left }
- if CharacterSet.punctuationCharacters.contains(first.unicodeScalars.first!) {
+ if let scalar = first.unicodeScalars.first, CharacterSet.punctuationCharacters.contains(scalar) {
return left + right
}
return left + " " + right
@@ -2285,6 +2295,8 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
)
}
+ // Keep the existing capture/processing contract explicit during integration.
+ // swiftlint:disable:next function_parameter_count
private func processMicrophoneChunk(
_ chunk: MeetingAudioChunk,
track: MeetingAudioTrack,
@@ -2636,8 +2648,11 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
DebugLogger.shared.info(
String(
format: "Echo scorer monitor: verdicts[%@] scoreableSeconds=%.1f delayLock=%d/%d bestConfidence=%.2f",
- verdictDescription, monitor.scoreableSeconds, monitor.lockedChunkCount,
- monitor.scoredChunkCount, monitor.bestDelayConfidence
+ verdictDescription,
+ monitor.scoreableSeconds,
+ monitor.lockedChunkCount,
+ monitor.scoredChunkCount,
+ monitor.bestDelayConfidence
),
source: "MeetingProcessingPipeline"
)
@@ -2830,6 +2845,8 @@ final class MeetingProcessingPipeline: MeetingProcessingControlling {
trackKind: MeetingAudioTrackKind,
fileURL: URL,
context: ProcessingContext
+ // nil represents unavailable or invalid evidence, distinct from a valid empty collection.
+ // swiftlint:disable:next discouraged_optional_collection
) async throws -> [(index: Int, turn: SpeakerDiarizationService.SpeakerTurn, text: String)]? {
let samples = try await Task.detached(priority: .userInitiated) {
try Self.readSamples(fileURL: fileURL, startSeconds: 0, endSeconds: nil)
diff --git a/Sources/Fluid/Services/Meeting/MeetingReferenceAttributionContracts.swift b/Sources/Fluid/Services/Meeting/MeetingReferenceAttributionContracts.swift
index 4f862c63..cd791988 100644
--- a/Sources/Fluid/Services/Meeting/MeetingReferenceAttributionContracts.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingReferenceAttributionContracts.swift
@@ -65,12 +65,16 @@ nonisolated enum MeetingReferenceAttributionSpeechState: String, Codable, CaseIt
case mixedSpeech
}
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
nonisolated enum MeetingReferenceAttributionResidualVariant: String, Codable, CaseIterable, Hashable, Sendable {
case originalMicrophone
case linearResidual
case suppressedResidual
}
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
nonisolated enum MeetingReferenceAttributionReferenceScope: String, Codable, CaseIterable, Hashable, Sendable {
case selectedWindow
case selectedApplication
@@ -83,7 +87,7 @@ nonisolated enum MeetingReferenceAttributionFallback: String, Codable, CaseItera
case originalMicrophone
}
-nonisolated private enum MeetingReferenceAttributionCanonical {
+private nonisolated enum MeetingReferenceAttributionCanonical {
// Malformed programmatic values remain visibly invalid rather than becoming plausible evidence.
static let fallbackLogicalIdentifier = "invalid/"
static let fallbackOpaqueHash = "invalid"
@@ -104,7 +108,7 @@ nonisolated private enum MeetingReferenceAttributionCanonical {
}
static func isLogicalIdentifier(_ value: String) -> Bool {
- let value = normalized(value)
+ let value = self.normalized(value)
guard !value.isEmpty, value != ".", value != "..",
!value.hasPrefix("~"), !value.contains("/"), !value.contains("\\"),
!value.contains("://") else { return false }
@@ -116,11 +120,11 @@ nonisolated private enum MeetingReferenceAttributionCanonical {
static func logicalIdentifier(_ value: String) -> String {
let normalized = normalized(value)
- return isLogicalIdentifier(normalized) ? normalized : Self.fallbackLogicalIdentifier
+ return self.isLogicalIdentifier(normalized) ? normalized : Self.fallbackLogicalIdentifier
}
static func isOpaqueHash(_ value: String) -> Bool {
- let value = normalized(value)
+ let value = self.normalized(value)
guard !value.isEmpty, value != "invalid", !value.contains("/"), !value.contains("\\") else { return false }
return value.unicodeScalars.allSatisfy { scalar in
!CharacterSet.controlCharacters.contains(scalar)
@@ -130,11 +134,11 @@ nonisolated private enum MeetingReferenceAttributionCanonical {
static func opaqueHash(_ value: String) -> String {
let normalized = normalized(value)
- return isOpaqueHash(normalized) ? normalized : Self.fallbackOpaqueHash
+ return self.isOpaqueHash(normalized) ? normalized : Self.fallbackOpaqueHash
}
static func isConfigurationHash(_ value: String) -> Bool {
- let value = normalized(value)
+ let value = self.normalized(value)
guard value.count == 64 else { return false }
return value.unicodeScalars.allSatisfy { scalar in
(scalar.value >= 48 && scalar.value <= 57)
@@ -144,13 +148,13 @@ nonisolated private enum MeetingReferenceAttributionCanonical {
static func configurationHash(_ value: String) -> String {
let normalized = normalized(value)
- return isConfigurationHash(normalized) ? normalized : Self.fallbackConfigurationHash
+ return self.isConfigurationHash(normalized) ? normalized : Self.fallbackConfigurationHash
}
static func string(_ value: String) -> String {
let normalized = value.precomposedStringWithCanonicalMapping
// Logical identities may not smuggle local paths or URLs into a sidecar.
- guard isLogicalIdentifier(normalized) else { return Self.fallbackLogicalIdentifier }
+ guard self.isLogicalIdentifier(normalized) else { return Self.fallbackLogicalIdentifier }
return normalized
}
@@ -189,18 +193,24 @@ nonisolated struct MeetingReferenceAttributionSourceHash: Codable, Equatable, Se
let name = try container.decode(String.self, forKey: .name)
let hash = try container.decode(String.self, forKey: .hash)
guard MeetingReferenceAttributionCanonical.isLogicalIdentifier(name),
- MeetingReferenceAttributionCanonical.isOpaqueHash(hash) else {
- throw DecodingError.dataCorruptedError(forKey: .name, in: container,
- debugDescription: "Invalid source hash identity")
+ MeetingReferenceAttributionCanonical.isOpaqueHash(hash)
+ else {
+ throw DecodingError.dataCorruptedError(
+ forKey: .name,
+ in: container,
+ debugDescription: "Invalid source hash identity"
+ )
}
self.name = MeetingReferenceAttributionCanonical.normalized(name)
self.hash = MeetingReferenceAttributionCanonical.normalized(hash)
}
}
-/// Explicit engine provenance. Hashes are opaque strings so this contract can represent a git
-/// revision, source digest, static artifact digest, or a dependency lock digest without guessing
-/// its spelling. Callers must provide logical names, not absolute paths.
+// Explicit engine provenance. Hashes are opaque strings so this contract can represent a git
+// revision, source digest, static artifact digest, or a dependency lock digest without guessing
+// its spelling. Callers must provide logical names, not absolute paths.
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
nonisolated struct MeetingReferenceAttributionEngineIdentity: Codable, Equatable, Sendable {
let schemaVersion: Int
let engineID: String
@@ -233,9 +243,13 @@ nonisolated struct MeetingReferenceAttributionEngineIdentity: Codable, Equatable
buildHash: String? = nil,
configurationHash: String
) {
- self.init(engineID: engineID, engineVersion: engineVersion,
- sourceHashes: sourceHashes.map { .init(name: $0.key, hash: $0.value) },
- buildHash: buildHash, configurationHash: configurationHash)
+ self.init(
+ engineID: engineID,
+ engineVersion: engineVersion,
+ sourceHashes: sourceHashes.map { .init(name: $0.key, hash: $0.value) },
+ buildHash: buildHash,
+ configurationHash: configurationHash
+ )
}
private enum CodingKeys: String, CodingKey {
@@ -254,10 +268,14 @@ nonisolated struct MeetingReferenceAttributionEngineIdentity: Codable, Equatable
MeetingReferenceAttributionCanonical.isLogicalIdentifier(engineID),
MeetingReferenceAttributionCanonical.isLogicalIdentifier(engineVersion),
sourceHashes.map(\.name).count == Set(sourceHashes.map(\.name)).count,
- buildHash == nil || MeetingReferenceAttributionCanonical.isOpaqueHash(buildHash!),
- MeetingReferenceAttributionCanonical.isConfigurationHash(configurationHash) else {
- throw DecodingError.dataCorruptedError(forKey: .schemaVersion, in: container,
- debugDescription: "Invalid engine provenance")
+ buildHash.map(MeetingReferenceAttributionCanonical.isOpaqueHash) ?? true,
+ MeetingReferenceAttributionCanonical.isConfigurationHash(configurationHash)
+ else {
+ throw DecodingError.dataCorruptedError(
+ forKey: .schemaVersion,
+ in: container,
+ debugDescription: "Invalid engine provenance"
+ )
}
self.schemaVersion = schemaVersion
self.engineID = MeetingReferenceAttributionCanonical.normalized(engineID)
@@ -274,14 +292,18 @@ nonisolated struct MeetingReferenceAttributionEngineIdentity: Codable, Equatable
buildHash: String? = nil,
configuration: MeetingReferenceAttributionConfiguration
) {
- self.init(engineID: engineID, engineVersion: engineVersion,
- sourceHashes: sourceHashes, buildHash: buildHash,
- configurationHash: configuration.configurationHash)
+ self.init(
+ engineID: engineID,
+ engineVersion: engineVersion,
+ sourceHashes: sourceHashes,
+ buildHash: buildHash,
+ configurationHash: configuration.configurationHash
+ )
}
/// Stable across source-hash insertion order and JSON encoder formatting.
var stableIdentity: String { MeetingReferenceAttributionCanonical.hash(self) }
- var identityHash: String { stableIdentity }
+ var identityHash: String { self.stableIdentity }
}
/// Configuration for an offline fixed-frame engine. Invalid floating-point values are omitted
@@ -328,20 +350,28 @@ nonisolated struct MeetingReferenceAttributionConfiguration: Codable, Equatable,
let candidateID = try container.decode(String.self, forKey: .candidateID)
guard schemaVersion == MeetingReferenceAttributionSchema.protocolVersion,
sampleRateHz > 0, frameDuration > 0, hopDuration > 0,
- maximumProcessing == nil || (maximumProcessing!.isFinite && maximumProcessing! >= 0),
- maximumMemory == nil || maximumMemory! >= 0,
- MeetingReferenceAttributionCanonical.isLogicalIdentifier(candidateID) else {
- throw DecodingError.dataCorruptedError(forKey: .schemaVersion, in: container,
- debugDescription: "Invalid attribution configuration")
+ (maximumProcessing.map { $0.isFinite && $0 >= 0 } ?? true),
+ (maximumMemory.map { $0 >= 0 } ?? true),
+ MeetingReferenceAttributionCanonical.isLogicalIdentifier(candidateID)
+ else {
+ throw DecodingError.dataCorruptedError(
+ forKey: .schemaVersion,
+ in: container,
+ debugDescription: "Invalid attribution configuration"
+ )
}
- self.init(sampleRateHz: sampleRateHz, frameDurationMilliseconds: frameDuration,
- hopDurationMilliseconds: hopDuration,
- maximumProcessingMillisecondsPerFrame: maximumProcessing,
- maximumMemoryBytes: maximumMemory, candidateID: candidateID)
+ self.init(
+ sampleRateHz: sampleRateHz,
+ frameDurationMilliseconds: frameDuration,
+ hopDurationMilliseconds: hopDuration,
+ maximumProcessingMillisecondsPerFrame: maximumProcessing,
+ maximumMemoryBytes: maximumMemory,
+ candidateID: candidateID
+ )
}
var stableIdentity: String { MeetingReferenceAttributionCanonical.hash(self) }
- var configurationHash: String { stableIdentity }
+ var configurationHash: String { self.stableIdentity }
}
/// A frame input is intentionally not Codable: it may carry PCM to an offline implementation, but
@@ -356,10 +386,10 @@ nonisolated struct MeetingReferenceAttributionPCMFrame: Sendable {
}
var hasValidShape: Bool {
- samples.count == valid.count && !samples.isEmpty
+ self.samples.count == self.valid.count && !self.samples.isEmpty
}
- var containsOnlyFiniteSamples: Bool { samples.allSatisfy(\.isFinite) }
+ var containsOnlyFiniteSamples: Bool { self.samples.allSatisfy(\.isFinite) }
}
nonisolated struct MeetingReferenceAttributionFrame: Sendable {
@@ -389,10 +419,10 @@ nonisolated struct MeetingReferenceAttributionFrame: Sendable {
self.referenceScope = referenceScope
}
- var endSeconds: Double { startSeconds + durationSeconds }
+ var endSeconds: Double { self.startSeconds + self.durationSeconds }
var hasValidTiming: Bool {
- startSeconds.isFinite && startSeconds >= 0 && durationSeconds.isFinite && durationSeconds > 0
- && endSeconds.isFinite
+ self.startSeconds.isFinite && self.startSeconds >= 0 && self.durationSeconds.isFinite && self.durationSeconds > 0
+ && self.endSeconds.isFinite
}
/// Validation is explicit because PCM frames are intentionally not Codable. A caller may still
@@ -400,10 +430,10 @@ nonisolated struct MeetingReferenceAttributionFrame: Sendable {
/// process it as measured audio.
var validationReasons: [MeetingReferenceAttributionReasonCode] {
var reasons = [MeetingReferenceAttributionReasonCode]()
- if frameIndex < 0 || !hasValidTiming { reasons.append(.invalidInput) }
- if !microphone.hasValidShape || !microphone.containsOnlyFiniteSamples {
+ if self.frameIndex < 0 || !self.hasValidTiming { reasons.append(.invalidInput) }
+ if !self.microphone.hasValidShape || !self.microphone.containsOnlyFiniteSamples {
reasons.append(.invalidInput)
- if !microphone.containsOnlyFiniteSamples { reasons.append(.nonFiniteInput) }
+ if !self.microphone.containsOnlyFiniteSamples { reasons.append(.nonFiniteInput) }
}
if let reference {
if !reference.hasValidShape || !reference.containsOnlyFiniteSamples {
@@ -414,15 +444,17 @@ nonisolated struct MeetingReferenceAttributionFrame: Sendable {
return Array(Set(reasons)).sorted { $0.rawValue < $1.rawValue }
}
- var isValid: Bool { validationReasons.isEmpty }
+ var isValid: Bool { self.validationReasons.isEmpty }
func validate() throws {
- guard isValid else {
- throw MeetingReferenceAttributionFrameValidationError(reasons: validationReasons)
+ guard self.isValid else {
+ throw MeetingReferenceAttributionFrameValidationError(reasons: self.validationReasons)
}
}
}
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
nonisolated struct MeetingReferenceAttributionFrameValidationError: Error, Equatable, Sendable {
let reasons: [MeetingReferenceAttributionReasonCode]
}
@@ -513,32 +545,57 @@ nonisolated struct MeetingReferenceAttributionMetrics: Codable, Equatable, Senda
let ratio = try container.decodeIfPresent(Double.self, forKey: .residualToOriginalEnergyRatio)
let processing = try container.decodeIfPresent(Double.self, forKey: .processingMilliseconds)
let peakMemory = try container.decodeIfPresent(Int.self, forKey: .peakMemoryBytes)
- let finite = [delay, delayJitter, convergence, erl, erle, candidateScore, controlMargin,
- originalEnergy, residualEnergy, ratio, processing].compactMap { $0 }
+ let finite = [
+ delay,
+ delayJitter,
+ convergence,
+ erl,
+ erle,
+ candidateScore,
+ controlMargin,
+ originalEnergy,
+ residualEnergy,
+ ratio,
+ processing,
+ ].compactMap { $0 }
guard resetCount >= 0, finite.allSatisfy(\.isFinite),
- delayJitter == nil || delayJitter! >= 0,
- convergence == nil || (0...1).contains(convergence!),
- candidateScore == nil || (0...1).contains(candidateScore!),
- originalEnergy == nil || originalEnergy! >= 0,
- residualEnergy == nil || residualEnergy! >= 0,
- ratio == nil || ratio! >= 0,
- processing == nil || processing! >= 0,
- peakMemory == nil || peakMemory! >= 0 else {
- throw DecodingError.dataCorruptedError(forKey: .resetCount, in: container,
- debugDescription: "Invalid attribution metric")
+ (delayJitter.map { $0 >= 0 } ?? true),
+ (convergence.map { (0...1).contains($0) } ?? true),
+ (candidateScore.map { (0...1).contains($0) } ?? true),
+ (originalEnergy.map { $0 >= 0 } ?? true),
+ (residualEnergy.map { $0 >= 0 } ?? true),
+ (ratio.map { $0 >= 0 } ?? true),
+ (processing.map { $0 >= 0 } ?? true),
+ (peakMemory.map { $0 >= 0 } ?? true)
+ else {
+ throw DecodingError.dataCorruptedError(
+ forKey: .resetCount,
+ in: container,
+ debugDescription: "Invalid attribution metric"
+ )
}
- self.init(delaySeconds: delay, delayJitterSeconds: delayJitter, convergence: convergence,
- resetCount: resetCount, erlDB: erl, erleDB: erle, candidateScore: candidateScore,
- controlMargin: controlMargin, originalEnergy: originalEnergy,
- residualEnergy: residualEnergy, residualToOriginalEnergyRatio: ratio,
- processingMilliseconds: processing, peakMemoryBytes: peakMemory)
+ self.init(
+ delaySeconds: delay,
+ delayJitterSeconds: delayJitter,
+ convergence: convergence,
+ resetCount: resetCount,
+ erlDB: erl,
+ erleDB: erle,
+ candidateScore: candidateScore,
+ controlMargin: controlMargin,
+ originalEnergy: originalEnergy,
+ residualEnergy: residualEnergy,
+ residualToOriginalEnergyRatio: ratio,
+ processingMilliseconds: processing,
+ peakMemoryBytes: peakMemory
+ )
}
static let unavailable = Self()
- var residualEnergyRatio: Double? { residualToOriginalEnergyRatio }
- var echoReturnLossDB: Double? { erlDB }
- var echoReturnLossEnhancementDB: Double? { erleDB }
+ var residualEnergyRatio: Double? { self.residualToOriginalEnergyRatio }
+ var echoReturnLossDB: Double? { self.erlDB }
+ var echoReturnLossEnhancementDB: Double? { self.erleDB }
}
nonisolated struct MeetingReferenceAttributionFrameResult: Codable, Equatable, Sendable {
@@ -569,7 +626,8 @@ nonisolated struct MeetingReferenceAttributionFrameResult: Codable, Equatable, S
var finalOutcome = outcome
var finalReasons = Set(reasons)
if speechState == .unknown,
- outcome == .likelyPlaybackOnly || outcome == .acceptedNearEndSpeech {
+ outcome == .likelyPlaybackOnly || outcome == .acceptedNearEndSpeech
+ {
finalOutcome = .unscored
finalReasons.insert(.unknownSpeechState)
}
@@ -577,14 +635,15 @@ nonisolated struct MeetingReferenceAttributionFrameResult: Codable, Equatable, S
// speech evidence must degrade to an explicitly uncertain result rather than remain
// eligible for suppression or profile exclusion as playback-only.
if outcome == .likelyPlaybackOnly,
- speechState == .nearEndSpeech || speechState == .mixedSpeech {
+ speechState == .nearEndSpeech || speechState == .mixedSpeech
+ {
finalOutcome = .mixedOrUncertain
finalReasons.insert(.mixedEvidence)
}
let validTiming = frameIndex >= 0 && startSeconds.isFinite && startSeconds >= 0
&& durationSeconds.isFinite && durationSeconds > 0
&& (startSeconds + durationSeconds).isFinite
- if outcome == .acceptedNearEndSpeech && speechState != .nearEndSpeech {
+ if outcome == .acceptedNearEndSpeech, speechState != .nearEndSpeech {
finalOutcome = .unscored
finalReasons.insert(.invalidInput)
}
@@ -646,56 +705,94 @@ nonisolated struct MeetingReferenceAttributionFrameResult: Codable, Equatable, S
&& startSeconds.isFinite && startSeconds >= 0 && durationSeconds == 0
&& reasons.contains(.invalidInput)
guard schemaVersion == MeetingReferenceAttributionSchema.sidecarVersion,
- standardTiming || invalidFailOpenTiming else {
- throw DecodingError.dataCorruptedError(forKey: .schemaVersion, in: container,
- debugDescription: "Invalid frame schema or timing")
+ standardTiming || invalidFailOpenTiming
+ else {
+ throw DecodingError.dataCorruptedError(
+ forKey: .schemaVersion,
+ in: container,
+ debugDescription: "Invalid frame schema or timing"
+ )
}
guard Set(reasons).count == reasons.count else {
- throw DecodingError.dataCorruptedError(forKey: .reasons, in: container,
- debugDescription: "Duplicate frame reason")
+ throw DecodingError.dataCorruptedError(
+ forKey: .reasons,
+ in: container,
+ debugDescription: "Duplicate frame reason"
+ )
}
guard reasons == reasons.sorted(by: { $0.rawValue < $1.rawValue }) else {
- throw DecodingError.dataCorruptedError(forKey: .reasons, in: container,
- debugDescription: "Non-canonical frame reason ordering")
+ throw DecodingError.dataCorruptedError(
+ forKey: .reasons,
+ in: container,
+ debugDescription: "Non-canonical frame reason ordering"
+ )
}
let knownSpeechState = speechState != .unknown
guard (outcome != .likelyPlaybackOnly && outcome != .acceptedNearEndSpeech) || knownSpeechState else {
- throw DecodingError.dataCorruptedError(forKey: .speechState, in: container,
- debugDescription: "Scored outcome requires known speech state")
+ throw DecodingError.dataCorruptedError(
+ forKey: .speechState,
+ in: container,
+ debugDescription: "Scored outcome requires known speech state"
+ )
}
if outcome == .acceptedNearEndSpeech && speechState != .nearEndSpeech {
- throw DecodingError.dataCorruptedError(forKey: .speechState, in: container,
- debugDescription: "Accepted speech outcome requires near-end state")
+ throw DecodingError.dataCorruptedError(
+ forKey: .speechState,
+ in: container,
+ debugDescription: "Accepted speech outcome requires near-end state"
+ )
}
if outcome == .likelyPlaybackOnly
- && (speechState == .nearEndSpeech || speechState == .mixedSpeech) {
- throw DecodingError.dataCorruptedError(forKey: .speechState, in: container,
- debugDescription: "Playback-only outcome conflicts with speech evidence")
+ && (speechState == .nearEndSpeech || speechState == .mixedSpeech)
+ {
+ throw DecodingError.dataCorruptedError(
+ forKey: .speechState,
+ in: container,
+ debugDescription: "Playback-only outcome conflicts with speech evidence"
+ )
}
guard outcome == .unscored || !reasons.contains(.unknownSpeechState) else {
- throw DecodingError.dataCorruptedError(forKey: .reasons, in: container,
- debugDescription: "Scored frame cannot carry unknown speech reason")
+ throw DecodingError.dataCorruptedError(
+ forKey: .reasons,
+ in: container,
+ debugDescription: "Scored frame cannot carry unknown speech reason"
+ )
}
- if outcome == .scopeLimited && !reasons.contains(.referenceScopeLimited) {
- throw DecodingError.dataCorruptedError(forKey: .reasons, in: container,
- debugDescription: "Scope-limited outcome requires scope reason")
+ if outcome == .scopeLimited, !reasons.contains(.referenceScopeLimited) {
+ throw DecodingError.dataCorruptedError(
+ forKey: .reasons,
+ in: container,
+ debugDescription: "Scope-limited outcome requires scope reason"
+ )
}
if outcome == .unscored {
guard speechState == .unknown else {
- throw DecodingError.dataCorruptedError(forKey: .speechState, in: container,
- debugDescription: "Unscored frame must have unknown speech state")
+ throw DecodingError.dataCorruptedError(
+ forKey: .speechState,
+ in: container,
+ debugDescription: "Unscored frame must have unknown speech state"
+ )
}
guard fallback == .originalMicrophone, reasons.contains(.fallbackToOriginal) else {
- throw DecodingError.dataCorruptedError(forKey: .fallback, in: container,
- debugDescription: "Unscored frame must fall back to original microphone")
+ throw DecodingError.dataCorruptedError(
+ forKey: .fallback,
+ in: container,
+ debugDescription: "Unscored frame must fall back to original microphone"
+ )
}
guard residualVariant == nil else {
- throw DecodingError.dataCorruptedError(forKey: .residualVariant, in: container,
- debugDescription: "Unscored frame cannot expose residual variant")
+ throw DecodingError.dataCorruptedError(
+ forKey: .residualVariant,
+ in: container,
+ debugDescription: "Unscored frame cannot expose residual variant"
+ )
}
} else if fallback == .originalMicrophone {
- throw DecodingError.dataCorruptedError(forKey: .fallback, in: container,
- debugDescription: "Scored frame cannot use original fallback")
+ throw DecodingError.dataCorruptedError(
+ forKey: .fallback,
+ in: container,
+ debugDescription: "Scored frame cannot use original fallback"
+ )
}
self.schemaVersion = schemaVersion
self.frameIndex = frameIndex
@@ -714,17 +811,26 @@ nonisolated struct MeetingReferenceAttributionFrameResult: Codable, Equatable, S
frame: MeetingReferenceAttributionFrame,
reason: MeetingReferenceAttributionReasonCode
) -> Self {
- Self(frameIndex: frame.frameIndex, epoch: frame.epoch,
- startSeconds: frame.startSeconds, durationSeconds: frame.durationSeconds,
- outcome: .unscored, speechState: .unknown, residualVariant: nil,
- reasons: [reason, .unknownSpeechState, .fallbackToOriginal],
- metrics: .unavailable, fallback: .originalMicrophone)
+ Self(
+ frameIndex: frame.frameIndex,
+ epoch: frame.epoch,
+ startSeconds: frame.startSeconds,
+ durationSeconds: frame.durationSeconds,
+ outcome: .unscored,
+ speechState: .unknown,
+ residualVariant: nil,
+ reasons: [reason, .unknownSpeechState, .fallbackToOriginal],
+ metrics: .unavailable,
+ fallback: .originalMicrophone
+ )
}
- var endSeconds: Double { startSeconds + durationSeconds }
- var isKnownSpeechState: Bool { speechState != .unknown }
+ var endSeconds: Double { self.startSeconds + self.durationSeconds }
+ var isKnownSpeechState: Bool { self.speechState != .unknown }
}
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
nonisolated struct MeetingReferenceAttributionWouldChangeCounts: Codable, Equatable, Sendable {
let words: Int
let segments: Int
@@ -732,8 +838,13 @@ nonisolated struct MeetingReferenceAttributionWouldChangeCounts: Codable, Equata
let unknownIntervals: Int
let legacyDisagreements: Int
- init(words: Int = 0, segments: Int = 0, profileObservations: Int = 0,
- unknownIntervals: Int = 0, legacyDisagreements: Int = 0) {
+ init(
+ words: Int = 0,
+ segments: Int = 0,
+ profileObservations: Int = 0,
+ unknownIntervals: Int = 0,
+ legacyDisagreements: Int = 0
+ ) {
self.words = MeetingReferenceAttributionCanonical.nonNegativeInt(words)
self.segments = MeetingReferenceAttributionCanonical.nonNegativeInt(segments)
self.profileObservations = MeetingReferenceAttributionCanonical.nonNegativeInt(profileObservations)
@@ -754,14 +865,22 @@ nonisolated struct MeetingReferenceAttributionWouldChangeCounts: Codable, Equata
container.decode(Int.self, forKey: .segments),
container.decode(Int.self, forKey: .profileObservations),
container.decode(Int.self, forKey: .unknownIntervals),
- container.decode(Int.self, forKey: .legacyDisagreements)
+ container.decode(Int.self, forKey: .legacyDisagreements),
]
guard values.allSatisfy({ $0 >= 0 }) else {
- throw DecodingError.dataCorruptedError(forKey: .words, in: container,
- debugDescription: "Negative would-change count")
+ throw DecodingError.dataCorruptedError(
+ forKey: .words,
+ in: container,
+ debugDescription: "Negative would-change count"
+ )
}
- self.init(words: values[0], segments: values[1], profileObservations: values[2],
- unknownIntervals: values[3], legacyDisagreements: values[4])
+ self.init(
+ words: values[0],
+ segments: values[1],
+ profileObservations: values[2],
+ unknownIntervals: values[3],
+ legacyDisagreements: values[4]
+ )
}
}
@@ -800,17 +919,22 @@ nonisolated struct MeetingReferenceAttributionCoverage: Codable, Equatable, Send
unscoredDurationSeconds: Double,
frameCount: Int
) {
- let values = [totalDurationSeconds, scoredDurationSeconds,
- likelyPlaybackOnlyDurationSeconds, acceptedNearEndSpeechDurationSeconds,
- mixedOrUncertainDurationSeconds, scopeLimitedDurationSeconds,
- unscoredDurationSeconds]
+ let values = [
+ totalDurationSeconds,
+ scoredDurationSeconds,
+ likelyPlaybackOnlyDurationSeconds,
+ acceptedNearEndSpeechDurationSeconds,
+ mixedOrUncertainDurationSeconds,
+ scopeLimitedDurationSeconds,
+ unscoredDurationSeconds,
+ ]
guard values.allSatisfy({ $0.isFinite && $0 >= 0 }), frameCount >= 0,
abs(scoredDurationSeconds - (likelyPlaybackOnlyDurationSeconds
- + acceptedNearEndSpeechDurationSeconds + mixedOrUncertainDurationSeconds)) <= 1e-9,
+ + acceptedNearEndSpeechDurationSeconds + mixedOrUncertainDurationSeconds)) <= 1e-9,
scoredDurationSeconds + unscoredDurationSeconds <= totalDurationSeconds + 1e-9,
abs((likelyPlaybackOnlyDurationSeconds + acceptedNearEndSpeechDurationSeconds
- + mixedOrUncertainDurationSeconds + scopeLimitedDurationSeconds
- + unscoredDurationSeconds) - totalDurationSeconds) <= 1e-9 else { return nil }
+ + mixedOrUncertainDurationSeconds + scopeLimitedDurationSeconds
+ + unscoredDurationSeconds) - totalDurationSeconds) <= 1e-9 else { return nil }
self.totalDurationSeconds = totalDurationSeconds
self.scoredDurationSeconds = scoredDurationSeconds
self.likelyPlaybackOnlyDurationSeconds = likelyPlaybackOnlyDurationSeconds
@@ -821,8 +945,8 @@ nonisolated struct MeetingReferenceAttributionCoverage: Codable, Equatable, Send
self.frameCount = frameCount
}
- var scoredFraction: Double { totalDurationSeconds > 0 ? scoredDurationSeconds / totalDurationSeconds : 0 }
- var unscoredFraction: Double { totalDurationSeconds > 0 ? unscoredDurationSeconds / totalDurationSeconds : 0 }
+ var scoredFraction: Double { self.totalDurationSeconds > 0 ? self.scoredDurationSeconds / self.totalDurationSeconds : 0 }
+ var unscoredFraction: Double { self.totalDurationSeconds > 0 ? self.unscoredDurationSeconds / self.totalDurationSeconds : 0 }
private enum CodingKeys: String, CodingKey {
case totalDurationSeconds, scoredDurationSeconds, likelyPlaybackOnlyDurationSeconds,
@@ -840,14 +964,21 @@ nonisolated struct MeetingReferenceAttributionCoverage: Codable, Equatable, Send
let scope = try container.decode(Double.self, forKey: .scopeLimitedDurationSeconds)
let unscored = try container.decode(Double.self, forKey: .unscoredDurationSeconds)
let frameCount = try container.decode(Int.self, forKey: .frameCount)
- guard let value = Self(totalDurationSeconds: total, scoredDurationSeconds: scored,
- likelyPlaybackOnlyDurationSeconds: playback,
- acceptedNearEndSpeechDurationSeconds: nearEnd,
- mixedOrUncertainDurationSeconds: mixed,
- scopeLimitedDurationSeconds: scope,
- unscoredDurationSeconds: unscored, frameCount: frameCount) else {
- throw DecodingError.dataCorruptedError(forKey: .totalDurationSeconds, in: container,
- debugDescription: "Invalid attribution coverage")
+ guard let value = Self(
+ totalDurationSeconds: total,
+ scoredDurationSeconds: scored,
+ likelyPlaybackOnlyDurationSeconds: playback,
+ acceptedNearEndSpeechDurationSeconds: nearEnd,
+ mixedOrUncertainDurationSeconds: mixed,
+ scopeLimitedDurationSeconds: scope,
+ unscoredDurationSeconds: unscored,
+ frameCount: frameCount
+ ) else {
+ throw DecodingError.dataCorruptedError(
+ forKey: .totalDurationSeconds,
+ in: container,
+ debugDescription: "Invalid attribution coverage"
+ )
}
self = value
}
@@ -860,9 +991,13 @@ nonisolated struct MeetingReferenceAttributionResourceCost: Codable, Equatable,
let overBudget: Bool
let fallback: MeetingReferenceAttributionFallback
- init(processingMilliseconds: Double? = nil, peakMemoryBytes: Int? = nil,
- derivedSidecarBytes: Int? = nil, overBudget: Bool = false,
- fallback: MeetingReferenceAttributionFallback = .none) {
+ init(
+ processingMilliseconds: Double? = nil,
+ peakMemoryBytes: Int? = nil,
+ derivedSidecarBytes: Int? = nil,
+ overBudget: Bool = false,
+ fallback: MeetingReferenceAttributionFallback = .none
+ ) {
self.processingMilliseconds = MeetingReferenceAttributionCanonical.nonNegative(processingMilliseconds)
self.peakMemoryBytes = peakMemoryBytes.flatMap { $0 >= 0 ? $0 : nil }
self.derivedSidecarBytes = derivedSidecarBytes.flatMap { $0 >= 0 ? $0 : nil }
@@ -881,24 +1016,37 @@ nonisolated struct MeetingReferenceAttributionResourceCost: Codable, Equatable,
let sidecar = try container.decodeIfPresent(Int.self, forKey: .derivedSidecarBytes)
let overBudget = try container.decode(Bool.self, forKey: .overBudget)
let fallback = try container.decode(MeetingReferenceAttributionFallback.self, forKey: .fallback)
- guard processing == nil || (processing!.isFinite && processing! >= 0),
- memory == nil || memory! >= 0,
- sidecar == nil || sidecar! >= 0,
- !overBudget || fallback == .originalMicrophone else {
- throw DecodingError.dataCorruptedError(forKey: .overBudget, in: container,
- debugDescription: "Invalid attribution resource cost")
+ guard (processing.map { $0.isFinite && $0 >= 0 } ?? true),
+ (memory.map { $0 >= 0 } ?? true),
+ (sidecar.map { $0 >= 0 } ?? true),
+ !overBudget || fallback == .originalMicrophone
+ else {
+ throw DecodingError.dataCorruptedError(
+ forKey: .overBudget,
+ in: container,
+ debugDescription: "Invalid attribution resource cost"
+ )
}
- self.init(processingMilliseconds: processing, peakMemoryBytes: memory,
- derivedSidecarBytes: sidecar, overBudget: overBudget, fallback: fallback)
+ self.init(
+ processingMilliseconds: processing,
+ peakMemoryBytes: memory,
+ derivedSidecarBytes: sidecar,
+ overBudget: overBudget,
+ fallback: fallback
+ )
}
}
-nonisolated private struct MeetingReferenceAttributionOutcomeCountEntry: Codable {
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
+private nonisolated struct MeetingReferenceAttributionOutcomeCountEntry: Codable {
let outcome: MeetingReferenceAttributionOutcome
let count: Int
}
-nonisolated private struct MeetingReferenceAttributionReasonCountEntry: Codable {
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
+private nonisolated struct MeetingReferenceAttributionReasonCountEntry: Codable {
let reason: MeetingReferenceAttributionReasonCode
let count: Int
}
@@ -954,7 +1102,9 @@ nonisolated struct MeetingReferenceAttributionAggregate: Codable, Equatable, Sen
total = nextTotal
durations[result.outcome] = nextBucket
outcomeCounts[result.outcome, default: 0] += 1
- for reason in result.reasons { reasonCounts[reason, default: 0] += 1 }
+ for reason in result.reasons {
+ reasonCounts[reason, default: 0] += 1
+ }
}
let scored = durations[.likelyPlaybackOnly, default: 0]
+ durations[.acceptedNearEndSpeech, default: 0]
@@ -984,25 +1134,42 @@ nonisolated struct MeetingReferenceAttributionAggregate: Codable, Equatable, Sen
let container = try decoder.container(keyedBy: CodingKeys.self)
let version = try container.decode(Int.self, forKey: .schemaVersion)
guard version == MeetingReferenceAttributionSchema.sidecarVersion else {
- throw DecodingError.dataCorruptedError(forKey: .schemaVersion, in: container,
- debugDescription: "Unsupported attribution aggregate schema")
+ throw DecodingError.dataCorruptedError(
+ forKey: .schemaVersion,
+ in: container,
+ debugDescription: "Unsupported attribution aggregate schema"
+ )
}
- let outcomes = try container.decode([MeetingReferenceAttributionOutcomeCountEntry].self,
- forKey: .outcomeCounts)
- let reasons = try container.decode([MeetingReferenceAttributionReasonCountEntry].self,
- forKey: .reasonCounts)
+ let outcomes = try container.decode(
+ [MeetingReferenceAttributionOutcomeCountEntry].self,
+ forKey: .outcomeCounts
+ )
+ let reasons = try container.decode(
+ [MeetingReferenceAttributionReasonCountEntry].self,
+ forKey: .reasonCounts
+ )
var outcomeCounts = [MeetingReferenceAttributionOutcome: Int]()
for entry in outcomes {
+ // count is a numeric decoded tally, not a collection.
+ // swiftlint:disable:next empty_count
guard entry.count >= 0, outcomeCounts.updateValue(entry.count, forKey: entry.outcome) == nil else {
- throw DecodingError.dataCorruptedError(forKey: .outcomeCounts, in: container,
- debugDescription: "Duplicate or negative outcome count")
+ throw DecodingError.dataCorruptedError(
+ forKey: .outcomeCounts,
+ in: container,
+ debugDescription: "Duplicate or negative outcome count"
+ )
}
}
var reasonCounts = [MeetingReferenceAttributionReasonCode: Int]()
for entry in reasons {
+ // count is a numeric decoded tally, not a collection.
+ // swiftlint:disable:next empty_count
guard entry.count >= 0, reasonCounts.updateValue(entry.count, forKey: entry.reason) == nil else {
- throw DecodingError.dataCorruptedError(forKey: .reasonCounts, in: container,
- debugDescription: "Duplicate or negative reason count")
+ throw DecodingError.dataCorruptedError(
+ forKey: .reasonCounts,
+ in: container,
+ debugDescription: "Duplicate or negative reason count"
+ )
}
}
self.schemaVersion = version
@@ -1016,19 +1183,19 @@ nonisolated struct MeetingReferenceAttributionAggregate: Codable, Equatable, Sen
nonisolated func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
- try container.encode(schemaVersion, forKey: .schemaVersion)
- try container.encode(coverage, forKey: .coverage)
- let outcomes = outcomeCounts.keys.sorted { $0.rawValue < $1.rawValue }.map {
- MeetingReferenceAttributionOutcomeCountEntry(outcome: $0, count: outcomeCounts[$0] ?? 0)
+ try container.encode(self.schemaVersion, forKey: .schemaVersion)
+ try container.encode(self.coverage, forKey: .coverage)
+ let outcomes = self.outcomeCounts.keys.sorted { $0.rawValue < $1.rawValue }.map {
+ MeetingReferenceAttributionOutcomeCountEntry(outcome: $0, count: self.outcomeCounts[$0] ?? 0)
}
- let reasons = reasonCounts.keys.sorted { $0.rawValue < $1.rawValue }.map {
- MeetingReferenceAttributionReasonCountEntry(reason: $0, count: reasonCounts[$0] ?? 0)
+ let reasons = self.reasonCounts.keys.sorted { $0.rawValue < $1.rawValue }.map {
+ MeetingReferenceAttributionReasonCountEntry(reason: $0, count: self.reasonCounts[$0] ?? 0)
}
try container.encode(outcomes, forKey: .outcomeCounts)
try container.encode(reasons, forKey: .reasonCounts)
- try container.encode(wouldChange, forKey: .wouldChange)
- try container.encode(metrics, forKey: .metrics)
- try container.encode(resourceCost, forKey: .resourceCost)
+ try container.encode(self.wouldChange, forKey: .wouldChange)
+ try container.encode(self.metrics, forKey: .metrics)
+ try container.encode(self.resourceCost, forKey: .resourceCost)
}
}
@@ -1076,16 +1243,17 @@ nonisolated struct MeetingReferenceAttributionSidecar: Codable, Equatable, Senda
/// errors so a corrupt sidecar cannot be treated as measured evidence.
var validationError: ValidationError? {
let resultEpochs = Set(frameResults.map(\.epoch))
- let epochValues = epochs.map(\.epoch)
- let canonicalFrames = frameResults.sorted {
+ let epochValues = self.epochs.map(\.epoch)
+ let canonicalFrames = self.frameResults.sorted {
$0.epoch == $1.epoch ? $0.frameIndex < $1.frameIndex : $0.epoch < $1.epoch
}
- guard frameResults.map({ "\($0.epoch):\($0.frameIndex)" })
- == canonicalFrames.map({ "\($0.epoch):\($0.frameIndex)" }) else {
+ guard self.frameResults.map({ "\($0.epoch):\($0.frameIndex)" })
+ == canonicalFrames.map({ "\($0.epoch):\($0.frameIndex)" })
+ else {
return .invalid("non-canonical frame ordering")
}
var frameKeys = Set<String>()
- for frame in frameResults {
+ for frame in self.frameResults {
guard frameKeys.insert("\(frame.epoch):\(frame.frameIndex)").inserted else {
return .invalid("duplicate epoch/frame key")
}
@@ -1097,44 +1265,43 @@ nonisolated struct MeetingReferenceAttributionSidecar: Codable, Equatable, Senda
guard Set(epochValues) == resultEpochs else { return .invalid("incomplete epoch/frame keys") }
// Epochs are reset markers, not permission to move backwards in the session timeline.
// Validate the canonical global order so a later epoch cannot overlap an earlier one.
- guard zip(frameResults, frameResults.dropFirst()).allSatisfy({ previous, next in
+ guard zip(self.frameResults, self.frameResults.dropFirst()).allSatisfy({ previous, next in
next.startSeconds + 1e-9 >= previous.endSeconds
}) else { return .invalid("non-monotonic frame timing") }
- guard MeetingReferenceAttributionCanonical.isLogicalIdentifier(engineIdentity.engineID),
- MeetingReferenceAttributionCanonical.isLogicalIdentifier(engineIdentity.engineVersion),
- engineIdentity.sourceHashes.allSatisfy({
+ guard MeetingReferenceAttributionCanonical.isLogicalIdentifier(self.engineIdentity.engineID),
+ MeetingReferenceAttributionCanonical.isLogicalIdentifier(self.engineIdentity.engineVersion),
+ self.engineIdentity.sourceHashes.allSatisfy({
MeetingReferenceAttributionCanonical.isLogicalIdentifier($0.name)
- && MeetingReferenceAttributionCanonical.isOpaqueHash($0.hash)
+ && MeetingReferenceAttributionCanonical.isOpaqueHash($0.hash)
}),
- Set(engineIdentity.sourceHashes.map(\.name)).count == engineIdentity.sourceHashes.count,
- engineIdentity.buildHash == nil
- || MeetingReferenceAttributionCanonical.isOpaqueHash(engineIdentity.buildHash!),
- MeetingReferenceAttributionCanonical.isLogicalIdentifier(configuration.candidateID),
- configuration.sampleRateHz > 0,
- configuration.frameDurationMilliseconds > 0,
- configuration.hopDurationMilliseconds > 0,
- configuration.maximumProcessingMillisecondsPerFrame == nil
- || (configuration.maximumProcessingMillisecondsPerFrame!.isFinite
- && configuration.maximumProcessingMillisecondsPerFrame! >= 0),
- configuration.maximumMemoryBytes == nil || configuration.maximumMemoryBytes! >= 0,
- engineIdentity.configurationHash == configuration.configurationHash else {
+ Set(self.engineIdentity.sourceHashes.map(\.name)).count == self.engineIdentity.sourceHashes.count,
+ self.engineIdentity.buildHash.map(MeetingReferenceAttributionCanonical.isOpaqueHash) ?? true,
+ MeetingReferenceAttributionCanonical.isLogicalIdentifier(self.configuration.candidateID),
+ self.configuration.sampleRateHz > 0,
+ self.configuration.frameDurationMilliseconds > 0,
+ self.configuration.hopDurationMilliseconds > 0,
+ (self.configuration.maximumProcessingMillisecondsPerFrame.map { $0.isFinite && $0 >= 0 } ?? true),
+ (self.configuration.maximumMemoryBytes.map { $0 >= 0 } ?? true),
+ self.engineIdentity.configurationHash == self.configuration.configurationHash
+ else {
return .invalid("engine/configuration hash mismatch")
}
- guard MeetingReferenceAttributionCanonical.isConfigurationHash(engineIdentity.configurationHash),
- MeetingReferenceAttributionCanonical.isConfigurationHash(configuration.configurationHash) else {
+ guard MeetingReferenceAttributionCanonical.isConfigurationHash(self.engineIdentity.configurationHash),
+ MeetingReferenceAttributionCanonical.isConfigurationHash(self.configuration.configurationHash)
+ else {
return .invalid("invalid engine/configuration provenance hash")
}
let expected = MeetingReferenceAttributionAggregate(
frameResults: frameResults,
wouldChange: aggregate.wouldChange,
- metrics: aggregate.metrics,
- resourceCost: aggregate.resourceCost
+ metrics: self.aggregate.metrics,
+ resourceCost: self.aggregate.resourceCost
)
- guard expected == aggregate else { return .invalid("aggregate mismatch") }
+ guard expected == self.aggregate else { return .invalid("aggregate mismatch") }
return nil
}
- var isValid: Bool { validationError == nil }
+ var isValid: Bool { self.validationError == nil }
private enum CodingKeys: String, CodingKey {
case schemaVersion, engineIdentity, configuration, epochs, frameResults, aggregate
@@ -1149,8 +1316,11 @@ nonisolated struct MeetingReferenceAttributionSidecar: Codable, Equatable, Senda
let frameResults = try container.decode([MeetingReferenceAttributionFrameResult].self, forKey: .frameResults)
let aggregate = try container.decode(MeetingReferenceAttributionAggregate.self, forKey: .aggregate)
guard schemaVersion == MeetingReferenceAttributionSchema.sidecarVersion else {
- throw DecodingError.dataCorruptedError(forKey: .schemaVersion, in: container,
- debugDescription: "Unsupported attribution sidecar schema")
+ throw DecodingError.dataCorruptedError(
+ forKey: .schemaVersion,
+ in: container,
+ debugDescription: "Unsupported attribution sidecar schema"
+ )
}
self.schemaVersion = schemaVersion
self.engineIdentity = engineIdentity
@@ -1159,8 +1329,11 @@ nonisolated struct MeetingReferenceAttributionSidecar: Codable, Equatable, Senda
self.frameResults = frameResults
self.aggregate = aggregate
if let validationError {
- throw DecodingError.dataCorruptedError(forKey: .aggregate, in: container,
- debugDescription: "Invalid attribution sidecar: \(validationError)")
+ throw DecodingError.dataCorruptedError(
+ forKey: .aggregate,
+ in: container,
+ debugDescription: "Invalid attribution sidecar: \(validationError)"
+ )
}
}
}
@@ -1178,6 +1351,6 @@ nonisolated protocol MeetingReferenceAttributionEngine: Sendable {
nonisolated extension MeetingReferenceAttributionEngine {
mutating func process(frame: MeetingReferenceAttributionFrame) -> MeetingReferenceAttributionFrameResult {
- process(frame)
+ self.process(frame)
}
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingReferenceSynchronizer.swift b/Sources/Fluid/Services/Meeting/MeetingReferenceSynchronizer.swift
index dbcddf79..f108d825 100644
--- a/Sources/Fluid/Services/Meeting/MeetingReferenceSynchronizer.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingReferenceSynchronizer.swift
@@ -3,26 +3,26 @@ import Foundation
/// The source clocks intentionally remain distinct until the synchronizer derives a
/// session timeline. This type is offline-only: it accepts completed in-memory PCM
/// fixtures and performs no callback, file, or engine work.
-nonisolated public enum MeetingSynchronizerTimeline: String, Sendable {
+public nonisolated enum MeetingSynchronizerTimeline: String, Sendable {
case microphoneSource
case referencePTS
case sessionMonotonic
}
-nonisolated public enum MeetingReferenceScope: String, Sendable {
+public nonisolated enum MeetingReferenceScope: String, Sendable {
case selectedWindow
case selectedApplication
case authorizedFullMix
}
-nonisolated public enum MeetingReferenceCompleteness: String, Sendable {
+public nonisolated enum MeetingReferenceCompleteness: String, Sendable {
case measuredComplete
case unobservable
}
/// These are the only reasons by which a synchronizer result is unknown. In
/// particular, an absent/masked sample is never represented as measured silence.
-nonisolated public enum MeetingSynchronizerUnknownReason: String, CaseIterable, Hashable, Sendable {
+public nonisolated enum MeetingSynchronizerUnknownReason: String, CaseIterable, Hashable, Sendable {
case referenceAbsent
case referenceGap
case referenceScopeLimited
@@ -34,7 +34,7 @@ nonisolated public enum MeetingSynchronizerUnknownReason: String, CaseIterable,
case engineUnavailable
}
-nonisolated public struct MeetingMicrophonePCMFrame: Equatable, Sendable {
+public nonisolated struct MeetingMicrophonePCMFrame: Equatable, Sendable {
public let sequenceNumber: Int
public let sampleTime: Int64
public let hostTime: Double?
@@ -65,7 +65,7 @@ nonisolated public struct MeetingMicrophonePCMFrame: Equatable, Sendable {
}
}
-nonisolated public struct MeetingReferencePCMFrame: Equatable, Sendable {
+public nonisolated struct MeetingReferencePCMFrame: Equatable, Sendable {
public let sequenceNumber: Int
/// PTS in the reference's own clock. It is deliberately not assumed to be host time.
public let presentationTime: Double
@@ -91,7 +91,9 @@ nonisolated public struct MeetingReferencePCMFrame: Equatable, Sendable {
}
}
-nonisolated public struct MeetingSynchronizerConverterConfiguration: Equatable, Sendable {
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
+public nonisolated struct MeetingSynchronizerConverterConfiguration: Equatable, Sendable {
public let version: String
/// Algorithmic delay is removed from the converted timeline, not hidden in the samples.
public let algorithmicDelaySeconds: Double
@@ -102,7 +104,9 @@ nonisolated public struct MeetingSynchronizerConverterConfiguration: Equatable,
}
}
-nonisolated public struct MeetingReferenceSynchronizerConfiguration: Equatable, Sendable {
+// Keep the subsystem-qualified name distinct from other capture and analysis contracts.
+// swiftlint:disable:next type_name
+public nonisolated struct MeetingReferenceSynchronizerConfiguration: Equatable, Sendable {
public static let defaultFrameDuration: Double = 0.010
public let analysisSampleRate: Double
public let frameDuration: Double
@@ -162,7 +166,7 @@ nonisolated public struct MeetingReferenceSynchronizerConfiguration: Equatable,
}
}
-nonisolated public struct MeetingSynchronizedFrame: Equatable, Sendable {
+public nonisolated struct MeetingSynchronizedFrame: Equatable, Sendable {
public let index: Int
public let sessionStartTime: Double
public let sessionEndTime: Double
@@ -209,11 +213,12 @@ nonisolated public struct MeetingSynchronizedFrame: Equatable, Sendable {
self.resynchronizationBoundary = resynchronizationBoundary
self.lagSeconds = lagSeconds
self.timelines = timelines ?? MeetingSynchronizerFrameTimelines(
- microphoneSourceTime: nil, referencePTSTime: nil, sessionMonotonicTime: sessionStartTime)
+ microphoneSourceTime: nil, referencePTSTime: nil, sessionMonotonicTime: sessionStartTime
+ )
}
}
-nonisolated public struct MeetingSynchronizerDiagnostics: Equatable, Sendable {
+public nonisolated struct MeetingSynchronizerDiagnostics: Equatable, Sendable {
public let inputFrameCount: Int
public let droppedFrameCount: Int
public let epochCount: Int
@@ -229,7 +234,7 @@ nonisolated public struct MeetingSynchronizerDiagnostics: Equatable, Sendable {
/// The three clock domains are carried with every emitted pair. Values are seconds in
/// their respective domains; `sessionMonotonicTime` is the only timeline consumers may
/// use for pairing. A nil source value means that domain had no valid sample in the pair.
-nonisolated public struct MeetingSynchronizerFrameTimelines: Equatable, Sendable {
+public nonisolated struct MeetingSynchronizerFrameTimelines: Equatable, Sendable {
/// Sample-count time from the microphone source (seconds, in its own domain).
public let microphoneSourceTime: Double?
/// The original reference PTS domain (seconds); codec priming is reflected by the
@@ -241,9 +246,13 @@ nonisolated public struct MeetingSynchronizerFrameTimelines: Equatable, Sendable
public let microphoneHostTime: Double?
public init(microphoneSourceTime: Double?, referencePTSTime: Double?, sessionMonotonicTime: Double) {
- self.init(microphoneSourceTime: microphoneSourceTime, microphoneSampleTime: nil,
- microphoneHostTime: nil, referencePTSTime: referencePTSTime,
- sessionMonotonicTime: sessionMonotonicTime)
+ self.init(
+ microphoneSourceTime: microphoneSourceTime,
+ microphoneSampleTime: nil,
+ microphoneHostTime: nil,
+ referencePTSTime: referencePTSTime,
+ sessionMonotonicTime: sessionMonotonicTime
+ )
}
public init(
@@ -256,10 +265,9 @@ nonisolated public struct MeetingSynchronizerFrameTimelines: Equatable, Sendable
self.referencePTSTime = referencePTSTime
self.sessionMonotonicTime = sessionMonotonicTime
}
-
}
-nonisolated public struct MeetingSynchronizationResult: Equatable, Sendable {
+public nonisolated struct MeetingSynchronizationResult: Equatable, Sendable {
public let frames: [MeetingSynchronizedFrame]
public let failedOpen: Bool
public let failureReason: MeetingSynchronizerUnknownReason?
@@ -280,7 +288,7 @@ nonisolated public struct MeetingSynchronizationResult: Equatable, Sendable {
/// Deterministic first-slice synchronizer. The implementation is intentionally a pure
/// function over bounded arrays so fixtures can be replayed byte-for-byte in tests.
-nonisolated public struct MeetingReferenceSynchronizer: Sendable {
+public nonisolated struct MeetingReferenceSynchronizer: Sendable {
public let configuration: MeetingReferenceSynchronizerConfiguration
public init(configuration: MeetingReferenceSynchronizerConfiguration = .init()) {
@@ -306,16 +314,16 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
totalSamples = overflow ? Int.max : sum
inputArithmeticOverflow = inputArithmeticOverflow || overflow
}
- let invalidBudgets = configuration.maximumInputFrameCount <= 0
- || configuration.maximumInputSampleCount <= 0
- || configuration.maximumOutputFrameCount <= 0
- let overBudget = !configuration.engineAvailable || invalidBudgets || inputArithmeticOverflow
- || microphone.count > configuration.maximumInputFrameCount
- || reference.count > configuration.maximumInputFrameCount
- || totalFrames > configuration.maximumInputFrameCount
- || totalSamples > configuration.maximumInputSampleCount
- let converterVersions = [configuration.microphoneConverter.version, configuration.referenceConverter.version]
- let converterDelays = [configuration.microphoneConverter.algorithmicDelaySeconds, configuration.referenceConverter.algorithmicDelaySeconds]
+ let invalidBudgets = self.configuration.maximumInputFrameCount <= 0
+ || self.configuration.maximumInputSampleCount <= 0
+ || self.configuration.maximumOutputFrameCount <= 0
+ let overBudget = !self.configuration.engineAvailable || invalidBudgets || inputArithmeticOverflow
+ || microphone.count > self.configuration.maximumInputFrameCount
+ || reference.count > self.configuration.maximumInputFrameCount
+ || totalFrames > self.configuration.maximumInputFrameCount
+ || totalSamples > self.configuration.maximumInputSampleCount
+ let converterVersions = [configuration.microphoneConverter.version, self.configuration.referenceConverter.version]
+ let converterDelays = [configuration.microphoneConverter.algorithmicDelaySeconds, self.configuration.referenceConverter.algorithmicDelaySeconds]
let emptyDiagnostics = MeetingSynchronizerDiagnostics(
inputFrameCount: totalFrames,
droppedFrameCount: 0,
@@ -326,28 +334,28 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
boundedResourceFailure: overBudget,
converterVersions: converterVersions,
converterDelays: converterDelays,
- referenceClockDriftPPM: finite(configuration.referenceClockDriftPPM) ? configuration.referenceClockDriftPPM : nil
+ referenceClockDriftPPM: finite(configuration.referenceClockDriftPPM) ? self.configuration.referenceClockDriftPPM : nil
)
guard !overBudget else {
return MeetingSynchronizationResult(frames: [], failedOpen: true, failureReason: .engineUnavailable, diagnostics: emptyDiagnostics)
}
- guard finite(configuration.maximumClockDriftPPM), configuration.maximumClockDriftPPM >= 0,
- finite(configuration.referenceClockDriftPPM),
- abs(configuration.referenceClockDriftPPM) <= configuration.maximumClockDriftPPM
+ guard self.finite(self.configuration.maximumClockDriftPPM), self.configuration.maximumClockDriftPPM >= 0,
+ self.finite(self.configuration.referenceClockDriftPPM),
+ abs(self.configuration.referenceClockDriftPPM) <= self.configuration.maximumClockDriftPPM
else {
return MeetingSynchronizationResult(frames: [], failedOpen: true, failureReason: .clockDriftUnstable, diagnostics: emptyDiagnostics)
}
- let referenceTimelineScale = 1 + configuration.referenceClockDriftPPM / 1_000_000
- guard finite(referenceTimelineScale), referenceTimelineScale > 0 else {
+ let referenceTimelineScale = 1 + self.configuration.referenceClockDriftPPM / 1_000_000
+ guard self.finite(referenceTimelineScale), referenceTimelineScale > 0 else {
return MeetingSynchronizationResult(frames: [], failedOpen: true, failureReason: .clockDriftUnstable, diagnostics: emptyDiagnostics)
}
- guard finite(configuration.analysisSampleRate), configuration.analysisSampleRate > 0,
- finite(configuration.frameDuration), configuration.frameDuration > 0,
- finite(configuration.microphoneConverter.algorithmicDelaySeconds),
- finite(configuration.referenceConverter.algorithmicDelaySeconds),
- finite(configuration.referenceToMicrophoneOffsetSeconds),
- finite(configuration.editListOffsetSeconds),
- configuration.codecPrimingSamples >= 0, configuration.codecRemainderSamples >= 0
+ guard self.finite(self.configuration.analysisSampleRate), self.configuration.analysisSampleRate > 0,
+ self.finite(self.configuration.frameDuration), self.configuration.frameDuration > 0,
+ self.finite(self.configuration.microphoneConverter.algorithmicDelaySeconds),
+ self.finite(self.configuration.referenceConverter.algorithmicDelaySeconds),
+ self.finite(self.configuration.referenceToMicrophoneOffsetSeconds),
+ self.finite(self.configuration.editListOffsetSeconds),
+ self.configuration.codecPrimingSamples >= 0, self.configuration.codecRemainderSamples >= 0
else {
return MeetingSynchronizationResult(frames: [], failedOpen: true, failureReason: .engineUnavailable, diagnostics: emptyDiagnostics)
}
@@ -355,24 +363,29 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
var dropped = 0
var duplicateOrLate = 0
var nonFinite = 0
- let micTrack = buildMicrophoneTrack(microphone, dropped: &dropped, duplicateOrLate: &duplicateOrLate, nonFinite: &nonFinite)
- let refTrack = buildReferenceTrack(reference, dropped: &dropped, duplicateOrLate: &duplicateOrLate, nonFinite: &nonFinite)
+ let micTrack = self.buildMicrophoneTrack(microphone, dropped: &dropped, duplicateOrLate: &duplicateOrLate, nonFinite: &nonFinite)
+ let refTrack = self.buildReferenceTrack(reference, dropped: &dropped, duplicateOrLate: &duplicateOrLate, nonFinite: &nonFinite)
let tracks = [micTrack, refTrack]
guard let firstTime = tracks.compactMap(\.firstTime).min(),
let lastTime = tracks.compactMap(\.lastTime).max(), lastTime > firstTime
else {
let diagnostics = MeetingSynchronizerDiagnostics(
- inputFrameCount: totalFrames, droppedFrameCount: dropped, epochCount: 0,
+ inputFrameCount: totalFrames,
+ droppedFrameCount: dropped,
+ epochCount: 0,
synthesizedMicrophoneFrameCount: micTrack.synthesizedFrameCount,
- duplicateOrLateFrameCount: duplicateOrLate, nonFiniteSampleCount: nonFinite,
- boundedResourceFailure: false, converterVersions: converterVersions,
- converterDelays: converterDelays, referenceClockDriftPPM: configuration.referenceClockDriftPPM
+ duplicateOrLateFrameCount: duplicateOrLate,
+ nonFiniteSampleCount: nonFinite,
+ boundedResourceFailure: false,
+ converterVersions: converterVersions,
+ converterDelays: converterDelays,
+ referenceClockDriftPPM: self.configuration.referenceClockDriftPPM
)
return MeetingSynchronizationResult(frames: [], failedOpen: false, failureReason: nil, diagnostics: diagnostics)
}
- let frameProduct = configuration.analysisSampleRate * configuration.frameDuration
- guard finite(frameProduct), frameProduct > 0, frameProduct < Double(Int.max) else {
+ let frameProduct = self.configuration.analysisSampleRate * self.configuration.frameDuration
+ guard self.finite(frameProduct), frameProduct > 0, frameProduct < Double(Int.max) else {
return MeetingSynchronizationResult(frames: [], failedOpen: true, failureReason: .engineUnavailable, diagnostics: emptyDiagnostics)
}
let frameSizeDouble = frameProduct.rounded()
@@ -380,79 +393,96 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
return MeetingSynchronizationResult(frames: [], failedOpen: true, failureReason: .engineUnavailable, diagnostics: emptyDiagnostics)
}
let frameSize = Int(frameSizeDouble)
- let spanSamples = (lastTime - firstTime) * configuration.analysisSampleRate
- guard finite(spanSamples), spanSamples > 0 else {
+ let spanSamples = (lastTime - firstTime) * self.configuration.analysisSampleRate
+ guard self.finite(spanSamples), spanSamples > 0 else {
return MeetingSynchronizationResult(frames: [], failedOpen: true, failureReason: .engineUnavailable, diagnostics: emptyDiagnostics)
}
let frameCountDouble = ceil(spanSamples / Double(frameSize) - 1e-10)
- guard finite(frameCountDouble), frameCountDouble >= 1,
- frameCountDouble <= Double(configuration.maximumOutputFrameCount),
- frameCountDouble < Double(Int.max) else {
+ guard self.finite(frameCountDouble), frameCountDouble >= 1,
+ frameCountDouble <= Double(self.configuration.maximumOutputFrameCount),
+ frameCountDouble < Double(Int.max)
+ else {
let diagnostics = MeetingSynchronizerDiagnostics(
- inputFrameCount: totalFrames, droppedFrameCount: dropped, epochCount: 0,
+ inputFrameCount: totalFrames,
+ droppedFrameCount: dropped,
+ epochCount: 0,
synthesizedMicrophoneFrameCount: micTrack.synthesizedFrameCount,
- duplicateOrLateFrameCount: duplicateOrLate, nonFiniteSampleCount: nonFinite,
- boundedResourceFailure: true, converterVersions: converterVersions,
- converterDelays: converterDelays, referenceClockDriftPPM: configuration.referenceClockDriftPPM)
+ duplicateOrLateFrameCount: duplicateOrLate,
+ nonFiniteSampleCount: nonFinite,
+ boundedResourceFailure: true,
+ converterVersions: converterVersions,
+ converterDelays: converterDelays,
+ referenceClockDriftPPM: self.configuration.referenceClockDriftPPM
+ )
return MeetingSynchronizationResult(frames: [], failedOpen: true, failureReason: .engineUnavailable, diagnostics: diagnostics)
}
let frameCount = Int(frameCountDouble)
guard frameCount <= Int.max / frameSize else {
let diagnostics = MeetingSynchronizerDiagnostics(
- inputFrameCount: totalFrames, droppedFrameCount: dropped, epochCount: 0,
+ inputFrameCount: totalFrames,
+ droppedFrameCount: dropped,
+ epochCount: 0,
synthesizedMicrophoneFrameCount: micTrack.synthesizedFrameCount,
- duplicateOrLateFrameCount: duplicateOrLate, nonFiniteSampleCount: nonFinite,
- boundedResourceFailure: true, converterVersions: converterVersions,
- converterDelays: converterDelays, referenceClockDriftPPM: configuration.referenceClockDriftPPM)
+ duplicateOrLateFrameCount: duplicateOrLate,
+ nonFiniteSampleCount: nonFinite,
+ boundedResourceFailure: true,
+ converterVersions: converterVersions,
+ converterDelays: converterDelays,
+ referenceClockDriftPPM: self.configuration.referenceClockDriftPPM
+ )
return MeetingSynchronizationResult(frames: [], failedOpen: true, failureReason: .engineUnavailable, diagnostics: diagnostics)
}
let outputCount = frameCount * frameSize
- let outputDuration = Double(outputCount) / configuration.analysisSampleRate
+ let outputDuration = Double(outputCount) / self.configuration.analysisSampleRate
guard outputDuration.isFinite, (firstTime + outputDuration).isFinite else {
let diagnostics = MeetingSynchronizerDiagnostics(
- inputFrameCount: totalFrames, droppedFrameCount: dropped, epochCount: 0,
+ inputFrameCount: totalFrames,
+ droppedFrameCount: dropped,
+ epochCount: 0,
synthesizedMicrophoneFrameCount: micTrack.synthesizedFrameCount,
- duplicateOrLateFrameCount: duplicateOrLate, nonFiniteSampleCount: nonFinite,
- boundedResourceFailure: true, converterVersions: converterVersions,
- converterDelays: converterDelays, referenceClockDriftPPM: configuration.referenceClockDriftPPM)
+ duplicateOrLateFrameCount: duplicateOrLate,
+ nonFiniteSampleCount: nonFinite,
+ boundedResourceFailure: true,
+ converterVersions: converterVersions,
+ converterDelays: converterDelays,
+ referenceClockDriftPPM: self.configuration.referenceClockDriftPPM
+ )
return MeetingSynchronizationResult(frames: [], failedOpen: true, failureReason: .engineUnavailable, diagnostics: diagnostics)
}
- let micGrid = makeGrid(track: micTrack, origin: firstTime, frameSize: frameSize, outputCount: outputCount)
- let refGrid = makeGrid(track: refTrack, origin: firstTime, frameSize: frameSize, outputCount: outputCount)
- let epochEvents = deduplicatedEpochEvents(micTrack.epochEvents + refTrack.epochEvents)
+ let micGrid = self.makeGrid(track: micTrack, origin: firstTime, frameSize: frameSize, outputCount: outputCount)
+ let refGrid = self.makeGrid(track: refTrack, origin: firstTime, frameSize: frameSize, outputCount: outputCount)
+ let epochEvents = self.deduplicatedEpochEvents(micTrack.epochEvents + refTrack.epochEvents)
let resyncEvents = Set((micTrack.resynchronizationEvents + refTrack.resynchronizationEvents).map {
// Round to the nearest fixed frame index so binary floating-point representation of
// a 10 ms boundary cannot pin an event to the preceding frame.
- safeRoundedInt(($0 - firstTime) / (Double(frameSize) / configuration.analysisSampleRate))
+ self.safeRoundedInt(($0 - firstTime) / (Double(frameSize) / self.configuration.analysisSampleRate))
}.compactMap { $0 })
var output: [MeetingSynchronizedFrame] = []
output.reserveCapacity(frameCount)
for frameIndex in 0..<frameCount {
- let start = firstTime + Double(frameIndex * frameSize) / configuration.analysisSampleRate
- let end = start + Double(frameSize) / configuration.analysisSampleRate
+ let start = firstTime + Double(frameIndex * frameSize) / self.configuration.analysisSampleRate
+ let end = start + Double(frameSize) / self.configuration.analysisSampleRate
let range = frameIndex * frameSize..<(frameIndex + 1) * frameSize
let micValues = Array(micGrid.samples[range])
let refValues = Array(refGrid.samples[range])
let micMask = Array(micGrid.valid[range])
let refMask = Array(refGrid.valid[range])
var reasons: [MeetingSynchronizerUnknownReason] = []
- if reference.isEmpty { reasons.append(.referenceAbsent) }
- else if refTrack.hasInternalGap(in: start..<end) { reasons.append(.referenceGap) }
- if !micMask.contains(true) { reasons.append(.captureGap) }
- else if micTrack.hasInternalGap(in: start..<end) { reasons.append(.captureGap) }
+ if reference.isEmpty { reasons.append(.referenceAbsent) } else if refTrack.hasInternalGap(in: start..<end) { reasons.append(.referenceGap) }
+ if !micMask.contains(true) { reasons.append(.captureGap) } else if micTrack.hasInternalGap(in: start..<end) { reasons.append(.captureGap) }
if micTrack.hasSynthesized(in: start..<end) { reasons.append(.captureTimingSynthesized) }
if !reference.isEmpty {
- if configuration.referenceScope != .authorizedFullMix { reasons.append(.referenceScopeLimited) }
- if configuration.referenceCompleteness == .unobservable { reasons.append(.referenceCompletenessUnobservable) }
+ if self.configuration.referenceScope != .authorizedFullMix { reasons.append(.referenceScopeLimited) }
+ if self.configuration.referenceCompleteness == .unobservable { reasons.append(.referenceCompletenessUnobservable) }
// This offline fixture has no shared-clock/acoustic calibration. Its
// configured alignment remains useful for deterministic tests, but is
// never presented as a measured delay.
reasons.append(.delayUnresolved)
}
if !refMask.contains(true) && !reference.isEmpty { reasons.append(.referenceGap) }
- if abs(configuration.referenceClockDriftPPM) > configuration.maximumClockDriftPPM * 0.75 { reasons.append(.clockDriftUnstable) }
+ if abs(self.configuration.referenceClockDriftPPM) > self.configuration.maximumClockDriftPPM * 0.75 { reasons.append(.clockDriftUnstable) }
if !micMask.contains(true) || (!reference.isEmpty && !refMask.contains(true)) { reasons.append(.delayUnresolved) }
- reasons = orderedUnique(reasons)
+ reasons = self.orderedUnique(reasons)
let anySynth = micTrack.hasSynthesized(in: start..<end)
let epoch = epochEvents.filter { $0 <= start + 1e-9 }.count
let micSourceTime = micGrid.sourceTimes[range].compactMap { $0 }.first
@@ -460,14 +490,14 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
let microphoneSampleTime = micGrid.microphoneSampleTimes[range].compactMap { $0 }.first
let microphoneHostTime = micGrid.microphoneHostTimes[range].compactMap { $0 }.first
let resynchronizationBoundary = resyncEvents.contains(frameIndex)
-#if DEBUG
+ #if DEBUG
let coverageIncomplete = !micMask.allSatisfy { $0 } || !refMask.allSatisfy { $0 }
let adaptationFrozen = anySynth || coverageIncomplete || resynchronizationBoundary
-#else
+ #else
// The Stage 0.5 adapter behavior is deliberately absent from Release until a
// later production integration phase is separately reviewed and authorized.
let adaptationFrozen = anySynth
-#endif
+ #endif
let lag: Double? = {
guard !anySynth else { return nil }
guard micSourceTime != nil, referenceSourceTime != nil else { return nil }
@@ -481,32 +511,45 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
return micStart - referenceStart
}()
output.append(MeetingSynchronizedFrame(
- index: frameIndex, sessionStartTime: start - firstTime, sessionEndTime: end - firstTime,
- epochID: epoch, renderSamples: refValues, captureSamples: micValues,
- renderValidMask: refMask, captureValidMask: micMask, unknownReasons: reasons,
+ index: frameIndex,
+ sessionStartTime: start - firstTime,
+ sessionEndTime: end - firstTime,
+ epochID: epoch,
+ renderSamples: refValues,
+ captureSamples: micValues,
+ renderValidMask: refMask,
+ captureValidMask: micMask,
+ unknownReasons: reasons,
adaptationFrozen: adaptationFrozen,
- resynchronizationBoundary: resynchronizationBoundary, lagSeconds: lag,
+ resynchronizationBoundary: resynchronizationBoundary,
+ lagSeconds: lag,
timelines: MeetingSynchronizerFrameTimelines(
microphoneSourceTime: micSourceTime,
microphoneSampleTime: microphoneSampleTime,
microphoneHostTime: microphoneHostTime,
referencePTSTime: referenceSourceTime,
- sessionMonotonicTime: start - firstTime)
+ sessionMonotonicTime: start - firstTime
+ )
))
}
let diagnostics = MeetingSynchronizerDiagnostics(
- inputFrameCount: totalFrames, droppedFrameCount: dropped, epochCount: max(1, epochEvents.count + 1),
+ inputFrameCount: totalFrames,
+ droppedFrameCount: dropped,
+ epochCount: max(1, epochEvents.count + 1),
synthesizedMicrophoneFrameCount: micTrack.synthesizedFrameCount,
- duplicateOrLateFrameCount: duplicateOrLate, nonFiniteSampleCount: nonFinite,
- boundedResourceFailure: false, converterVersions: converterVersions,
- converterDelays: converterDelays, referenceClockDriftPPM: configuration.referenceClockDriftPPM
+ duplicateOrLateFrameCount: duplicateOrLate,
+ nonFiniteSampleCount: nonFinite,
+ boundedResourceFailure: false,
+ converterVersions: converterVersions,
+ converterDelays: converterDelays,
+ referenceClockDriftPPM: self.configuration.referenceClockDriftPPM
)
return MeetingSynchronizationResult(frames: output, failedOpen: false, failureReason: nil, diagnostics: diagnostics)
}
- // MARK: Track normalization
+ // MARK: - Track normalization
- nonisolated private struct TrackGrid {
+ private nonisolated struct TrackGrid {
var segments: [TimedSegment]
var sourceOrigin: Double?
var firstTime: Double?
@@ -517,40 +560,40 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
var synthesizedFrameCount: Int
func hasInternalGap(in range: Range<Double>) -> Bool {
-#if DEBUG
+ #if DEBUG
// Treat ranges that only meet at a boundary as disjoint. Callback PTS and
// fixed analysis-hop arithmetic can differ by a few binary floating-point
// ulps; without the epsilon, the first fully covered hop after a gap can be
// mislabeled as still containing that gap.
- gapRanges.contains {
+ self.gapRanges.contains {
$0.lowerBound < range.upperBound - 1e-9
&& $0.upperBound > range.lowerBound + 1e-9
}
-#else
- return gapRanges.contains {
+ #else
+ return self.gapRanges.contains {
$0.lowerBound < range.upperBound && $0.upperBound > range.lowerBound
}
-#endif
+ #endif
}
func hasSynthesized(in range: Range<Double>) -> Bool {
-#if DEBUG
- segments.contains { segment in
+ #if DEBUG
+ self.segments.contains { segment in
segment.synthesized && segment.start < range.upperBound - 1e-9
&& segment.start + Double(segment.values.count) / segment.sessionSampleRate
- > range.lowerBound + 1e-9
+ > range.lowerBound + 1e-9
}
-#else
- return segments.contains { segment in
+ #else
+ return self.segments.contains { segment in
segment.synthesized && segment.start < range.upperBound
&& segment.start + Double(segment.values.count) / segment.sessionSampleRate
- > range.lowerBound
+ > range.lowerBound
}
-#endif
+ #endif
}
}
- nonisolated private struct TimedSegment {
+ private nonisolated struct TimedSegment {
let start: Double
let sourceStart: Double
/// Untransformed source-clock coordinate used for per-frame provenance.
@@ -564,7 +607,7 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
let synthesized: Bool
}
- nonisolated private struct Grid {
+ private nonisolated struct Grid {
var samples: [Float]
var valid: [Bool]
var sourceTimes: [Double?]
@@ -584,6 +627,8 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
var previousRate: Double?
var previousRoute: String?
var hadSynthesized = false
+ // Keep this existing grouped state result intact during integration.
+ // swiftlint:disable:next large_tuple
var normalized: [(frame: MeetingMicrophonePCMFrame, start: Double, sourceStart: Double, sourceSampleTime: Int64, hostTime: Double?, values: [Float], synthesized: Bool)] = []
var firstValidSample: Int64?
for frame in frames {
@@ -600,15 +645,15 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
return delta / frame.sampleRate
}()
let sequenceGapDetected = previousSequence.map { frame.sequenceNumber > $0 + 1 } ?? false
- guard frame.channelCount > 0, finite(frame.sampleRate), frame.sampleRate > 0 else {
+ guard frame.channelCount > 0, self.finite(frame.sampleRate), frame.sampleRate > 0 else {
dropped += 1
if normalized.last != nil {
let gapStart = normalized.last.map { $0.start + Double($0.values.count) / $0.frame.sampleRate } ?? nominalStart
let gapDuration = frame.sampleRate.isFinite && frame.sampleRate > 0
? Double(max(1, frame.samples.count / max(frame.channelCount, 1))) / frame.sampleRate
- : configuration.frameDuration
- appendEpochEvent(gapStart, to: &epochEvents)
- appendGap(gapStart..<gapStart + gapDuration, to: &gaps)
+ : self.configuration.frameDuration
+ self.appendEpochEvent(gapStart, to: &epochEvents)
+ self.appendGap(gapStart..<gapStart + gapDuration, to: &gaps)
}
previousSequence = frame.sequenceNumber
continue
@@ -619,14 +664,14 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
// Once a valid block exists, its finite timestamp locates one configured
// hop of unknown coverage without creating a second reset marker.
if let firstValidSample {
- let start = safeSampleDelta(frame.sampleTime, firstValidSample).map {
- $0 / frame.sampleRate - configuration.microphoneConverter.algorithmicDelaySeconds
+ let start = self.safeSampleDelta(frame.sampleTime, firstValidSample).map {
+ $0 / frame.sampleRate - self.configuration.microphoneConverter.algorithmicDelaySeconds
}
if let start, start.isFinite, normalized.last != nil {
let duration = normalized.last.map { Double($0.values.count) / $0.frame.sampleRate }
- ?? configuration.frameDuration
- appendGap(start..<start + max(duration, configuration.frameDuration), to: &gaps)
- appendEpochEvent(start, to: &epochEvents)
+ ?? self.configuration.frameDuration
+ self.appendGap(start..<start + max(duration, self.configuration.frameDuration), to: &gaps)
+ self.appendEpochEvent(start, to: &epochEvents)
}
}
if normalized.last != nil { previousSampleTime = frame.sampleTime }
@@ -639,8 +684,8 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
// origin. Once the track is anchored, its finite timing locates the
// midstream missing interval without using malformed audio as coverage.
if normalized.last != nil {
- appendEpochEvent(nominalStart, to: &epochEvents)
- appendGap(nominalStart..<(nominalStart + Double(frame.samples.count) / Double(frame.channelCount) / frame.sampleRate), to: &gaps)
+ self.appendEpochEvent(nominalStart, to: &epochEvents)
+ self.appendGap(nominalStart..<(nominalStart + Double(frame.samples.count) / Double(frame.channelCount) / frame.sampleRate), to: &gaps)
}
if normalized.last != nil { previousSampleTime = frame.sampleTime }
previousSequence = frame.sequenceNumber
@@ -652,8 +697,8 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
let gapStart = normalized.last.map { $0.start + Double($0.values.count) / $0.frame.sampleRate } ?? nominalStart
let gapDuration = Double(frame.samples.count / frame.channelCount) / frame.sampleRate
if normalized.last != nil {
- appendGap(gapStart..<gapStart + gapDuration, to: &gaps)
- appendEpochEvent(gapStart, to: &epochEvents)
+ self.appendGap(gapStart..<gapStart + gapDuration, to: &gaps)
+ self.appendEpochEvent(gapStart, to: &epochEvents)
}
if normalized.last != nil { previousSampleTime = frame.sampleTime }
previousSequence = frame.sequenceNumber
@@ -678,7 +723,7 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
continue
}
let nominalStartFromOrigin = sampleDelta / frame.sampleRate
- let sourceStart = nominalStartFromOrigin - configuration.microphoneConverter.algorithmicDelaySeconds
+ let sourceStart = nominalStartFromOrigin - self.configuration.microphoneConverter.algorithmicDelaySeconds
guard sourceStart.isFinite else {
dropped += 1
duplicateOrLate += 1
@@ -686,7 +731,8 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
continue
}
if let previousEnd = normalized.last.map({ $0.start + Double($0.values.count) / $0.frame.sampleRate }),
- sourceStart < previousEnd - 1e-9 {
+ sourceStart < previousEnd - 1e-9
+ {
dropped += 1
duplicateOrLate += 1
previousSequence = frame.sequenceNumber
@@ -695,35 +741,36 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
if sequenceGapDetected {
let previousEnd = normalized.last.map { $0.start + Double($0.values.count) / $0.frame.sampleRate }
if let previousEnd, sourceStart > previousEnd + 1e-9 {
- appendGap(previousEnd..<sourceStart, to: &gaps)
+ self.appendGap(previousEnd..<sourceStart, to: &gaps)
}
- appendEpochEvent(sourceStart, to: &epochEvents)
+ self.appendEpochEvent(sourceStart, to: &epochEvents)
resynchronizationEvents.append(sourceStart)
}
- let expected = previousSampleTime.flatMap { safeInt64Delta(frame.sampleTime, $0) }
+ let expected = previousSampleTime.flatMap { self.safeInt64Delta(frame.sampleTime, $0) }
// A rejected pre-origin frame may supply a timing cursor, but with no
// accepted segment there is no prior payload length to compare against.
let expectedSamples: Int64? = normalized.last.map { Int64($0.values.count) }
if !sequenceGapDetected,
- let expected, expected < 0 || (expectedSamples != nil && expected != expectedSamples!) || frame.discontinuity
- || previousRate != nil && frame.sampleRate != previousRate!
- || previousRoute != nil && frame.routeIdentifier != previousRoute!
- || (previousHost != nil && frame.hostTime != nil && frame.hostTime! <= previousHost!) {
- appendEpochEvent(sourceStart, to: &epochEvents)
+ let expected, expected < 0 || (expectedSamples.map { expected != $0 } ?? false) || frame.discontinuity
+ || (previousRate.map { frame.sampleRate != $0 } ?? false)
+ || (previousRoute.map { frame.routeIdentifier != $0 } ?? false)
+ || (previousHost.flatMap { previous in frame.hostTime.map { $0 <= previous } } ?? false)
+ {
+ self.appendEpochEvent(sourceStart, to: &epochEvents)
// Any microphone timing/route discontinuity requires the AEC-facing
// consumer to reset before it can use samples in the new epoch. This is
// independent of whether the discontinuity also contains a coverage gap.
-#if DEBUG
+ #if DEBUG
resynchronizationEvents.append(sourceStart)
-#endif
+ #endif
let previousEnd = normalized.last.map { $0.start + Double($0.values.count) / $0.frame.sampleRate } ?? sourceStart
- if sourceStart > previousEnd { appendGap(previousEnd..<sourceStart, to: &gaps) }
+ if sourceStart > previousEnd { self.appendGap(previousEnd..<sourceStart, to: &gaps) }
}
- let validHost = frame.hostTime.map(finite) ?? false
+ let validHost = frame.hostTime.map(self.finite) ?? false
let synthesized = !validHost
if validHost && hadSynthesized {
resynchronizationEvents.append(sourceStart)
- appendEpochEvent(sourceStart, to: &epochEvents)
+ self.appendEpochEvent(sourceStart, to: &epochEvents)
hadSynthesized = false
}
if synthesized { synthCount += 1; hadSynthesized = true }
@@ -732,27 +779,50 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
previousSequence = frame.sequenceNumber
previousRate = frame.sampleRate
previousRoute = frame.routeIdentifier
- normalized.append((frame, sourceStart, Double(frame.sampleTime) / frame.sampleRate,
- frame.sampleTime, frame.hostTime,
- downmix(frame.samples, channels: frame.channelCount), synthesized))
+ normalized.append((
+ frame,
+ sourceStart,
+ Double(frame.sampleTime) / frame.sampleRate,
+ frame.sampleTime,
+ frame.hostTime,
+ self.downmix(frame.samples, channels: frame.channelCount),
+ synthesized
+ ))
}
- let segments = normalized.map { TimedSegment(start: $0.start, sourceStart: $0.sourceStart,
+ let segments = normalized.map { TimedSegment(
+ start: $0.start,
+ sourceStart: $0.sourceStart,
sourceTimelineStart: Double($0.frame.sampleTime) / $0.frame.sampleRate,
- sourceSampleTime: $0.sourceSampleTime, hostTime: $0.hostTime,
- sourceSampleRate: $0.frame.sampleRate, sessionSampleRate: $0.frame.sampleRate, timelineScale: 1,
- values: $0.values, synthesized: $0.synthesized) }
- return makeTrackGrid(segments: segments, sourceOrigin: normalized.first?.sourceStart, firstTime: normalized.map { $0.start }.min(), epochEvents: epochEvents, resynchronizationEvents: resynchronizationEvents, gaps: gaps, synthesizedFrameCount: synthCount)
+ sourceSampleTime: $0.sourceSampleTime,
+ hostTime: $0.hostTime,
+ sourceSampleRate: $0.frame.sampleRate,
+ sessionSampleRate: $0.frame.sampleRate,
+ timelineScale: 1,
+ values: $0.values,
+ synthesized: $0.synthesized
+ ) }
+ return self.makeTrackGrid(
+ segments: segments,
+ sourceOrigin: normalized.first?.sourceStart,
+ firstTime: normalized.map { $0.start }.min(),
+ epochEvents: epochEvents,
+ resynchronizationEvents: resynchronizationEvents,
+ gaps: gaps,
+ synthesizedFrameCount: synthCount
+ )
}
private func buildReferenceTrack(_ frames: [MeetingReferencePCMFrame], dropped: inout Int, duplicateOrLate: inout Int, nonFinite: inout Int) -> TrackGrid {
var seen = Set<Int>()
+ // Keep this existing grouped state result intact during integration.
+ // swiftlint:disable:next large_tuple
var normalized: [(frame: MeetingReferencePCMFrame, start: Double, sourceStart: Double, sourceSampleTime: Int64?, hostTime: Double?, values: [Float], synthesized: Bool)] = []
var previousPTS: Double?
var previousSequence: Int?
var previousRate: Double?
var referenceAnchorPTS: Double?
var previousRejectedEnd: Double?
- var primingRemaining = configuration.codecPrimingSamples
+ var primingRemaining = self.configuration.codecPrimingSamples
var epochEvents: [Double] = []
var resyncEvents: [Double] = []
var gaps: [Range<Double>] = []
@@ -765,20 +835,21 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
}
seen.insert(frame.sequenceNumber)
let sequenceGapDetected = previousSequence.map { frame.sequenceNumber > $0 + 1 } ?? false
- guard frame.channelCount > 0, finite(frame.sampleRate), frame.sampleRate > 0,
- finite(frame.presentationTime) else {
+ guard frame.channelCount > 0, self.finite(frame.sampleRate), frame.sampleRate > 0,
+ self.finite(frame.presentationTime)
+ else {
dropped += 1
if normalized.last != nil || referenceAnchorPTS != nil {
let gapStart = previousRejectedEnd ?? normalized.last.map {
- $0.start + referenceSessionDuration(Double($0.values.count) / $0.frame.sampleRate)
+ $0.start + self.referenceSessionDuration(Double($0.values.count) / $0.frame.sampleRate)
} ?? (frame.presentationTime.isFinite
- ? referenceSessionTime(sourceTime: frame.presentationTime - (referenceAnchorPTS ?? frame.presentationTime))
+ ? self.referenceSessionTime(sourceTime: frame.presentationTime - (referenceAnchorPTS ?? frame.presentationTime))
: 0)
let gapDuration = frame.sampleRate.isFinite && frame.sampleRate > 0
- ? referenceSessionDuration(Double(max(1, frame.samples.count / max(frame.channelCount, 1))) / frame.sampleRate)
- : configuration.frameDuration
- appendEpochEvent(gapStart, to: &epochEvents)
- appendGap(gapStart..<gapStart + gapDuration, to: &gaps)
+ ? self.referenceSessionDuration(Double(max(1, frame.samples.count / max(frame.channelCount, 1))) / frame.sampleRate)
+ : self.configuration.frameDuration
+ self.appendEpochEvent(gapStart, to: &epochEvents)
+ self.appendGap(gapStart..<gapStart + gapDuration, to: &gaps)
if referenceAnchorPTS != nil { previousRejectedEnd = gapStart + gapDuration }
}
if normalized.last != nil || referenceAnchorPTS != nil { previousPTS = frame.presentationTime }
@@ -788,14 +859,14 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
if frame.samples.isEmpty {
dropped += 1
if let anchor = referenceAnchorPTS {
- let start = referenceSessionTime(sourceTime: frame.presentationTime - anchor)
+ let start = self.referenceSessionTime(sourceTime: frame.presentationTime - anchor)
if start.isFinite, normalized.last != nil {
let duration = normalized.last.map {
- referenceSessionDuration(Double($0.values.count) / $0.frame.sampleRate)
- } ?? configuration.frameDuration
- appendEpochEvent(start, to: &epochEvents)
- appendGap(start..<start + max(duration, configuration.frameDuration), to: &gaps)
- previousRejectedEnd = start + max(duration, configuration.frameDuration)
+ self.referenceSessionDuration(Double($0.values.count) / $0.frame.sampleRate)
+ } ?? self.configuration.frameDuration
+ self.appendEpochEvent(start, to: &epochEvents)
+ self.appendGap(start..<start + max(duration, self.configuration.frameDuration), to: &gaps)
+ previousRejectedEnd = start + max(duration, self.configuration.frameDuration)
}
}
if normalized.last != nil || referenceAnchorPTS != nil { previousPTS = frame.presentationTime }
@@ -804,13 +875,13 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
}
guard frame.samples.count % frame.channelCount == 0 else {
dropped += 1
- let malformedStart = referenceSessionTime(
+ let malformedStart = self.referenceSessionTime(
sourceTime: frame.presentationTime - (referenceAnchorPTS ?? frame.presentationTime)
)
if normalized.last != nil || referenceAnchorPTS != nil {
- appendEpochEvent(malformedStart, to: &epochEvents)
- let duration = referenceSessionDuration(Double(frame.samples.count) / Double(frame.channelCount) / frame.sampleRate)
- appendGap(malformedStart..<malformedStart + duration, to: &gaps)
+ self.appendEpochEvent(malformedStart, to: &epochEvents)
+ let duration = self.referenceSessionDuration(Double(frame.samples.count) / Double(frame.channelCount) / frame.sampleRate)
+ self.appendGap(malformedStart..<malformedStart + duration, to: &gaps)
if referenceAnchorPTS != nil { previousRejectedEnd = malformedStart + duration }
}
if normalized.last != nil || referenceAnchorPTS != nil { previousPTS = frame.presentationTime }
@@ -819,13 +890,13 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
}
guard frame.samples.allSatisfy(\.isFinite) else {
nonFinite += frame.samples.filter { !$0.isFinite }.count; dropped += 1
- let invalidStart = referenceSessionTime(
+ let invalidStart = self.referenceSessionTime(
sourceTime: frame.presentationTime - (referenceAnchorPTS ?? frame.presentationTime)
)
- let duration = referenceSessionDuration(Double(frame.samples.count) / Double(frame.channelCount) / frame.sampleRate)
+ let duration = self.referenceSessionDuration(Double(frame.samples.count) / Double(frame.channelCount) / frame.sampleRate)
if normalized.last != nil || referenceAnchorPTS != nil {
- appendGap(invalidStart..<invalidStart + duration, to: &gaps)
- appendEpochEvent(invalidStart, to: &epochEvents)
+ self.appendGap(invalidStart..<invalidStart + duration, to: &gaps)
+ self.appendEpochEvent(invalidStart, to: &epochEvents)
if referenceAnchorPTS != nil { previousRejectedEnd = invalidStart + duration }
}
if normalized.last != nil || referenceAnchorPTS != nil { previousPTS = frame.presentationTime }
@@ -842,12 +913,12 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
previousSequence = frame.sequenceNumber
continue
}
- var values = downmix(frame.samples, channels: frame.channelCount)
+ var values = self.downmix(frame.samples, channels: frame.channelCount)
if referenceAnchorPTS == nil { referenceAnchorPTS = frame.presentationTime }
let leading = min(primingRemaining, values.count)
let candidateSourceStart = frame.presentationTime - (referenceAnchorPTS ?? frame.presentationTime)
+ Double(leading) / frame.sampleRate
- let candidateStart = referenceSessionTime(sourceTime: candidateSourceStart)
+ let candidateStart = self.referenceSessionTime(sourceTime: candidateSourceStart)
guard candidateStart.isFinite else {
dropped += 1
duplicateOrLate += 1
@@ -866,15 +937,15 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
primingRemaining -= leading
let sourceStart = frame.presentationTime - (referenceAnchorPTS ?? frame.presentationTime)
+ Double(leading) / frame.sampleRate
- let start = referenceSessionTime(sourceTime: sourceStart)
+ let start = self.referenceSessionTime(sourceTime: sourceStart)
if sequenceGapDetected {
let previousEnd = previousRejectedEnd ?? normalized.last.map {
- $0.start + referenceSessionDuration(Double($0.values.count) / $0.frame.sampleRate)
+ $0.start + self.referenceSessionDuration(Double($0.values.count) / $0.frame.sampleRate)
}
if let previousEnd, start > previousEnd + 1e-9 {
- appendGap(previousEnd..<start, to: &gaps)
+ self.appendGap(previousEnd..<start, to: &gaps)
}
- appendEpochEvent(start, to: &epochEvents)
+ self.appendEpochEvent(start, to: &epochEvents)
// A sequence boundary is a reset marker even when sample-time coverage is
// contiguous; it must not turn the valid current frame into a gap.
// (The actual missing interval, when any, is recorded above.)
@@ -885,24 +956,24 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
// the stream's initial state, not a transition from an earlier epoch.
if previousPTS != nil {
let previousEnd = previousRejectedEnd ?? normalized.last.map {
- $0.start + referenceSessionDuration(Double($0.values.count) / $0.frame.sampleRate)
+ $0.start + self.referenceSessionDuration(Double($0.values.count) / $0.frame.sampleRate)
} ?? start
- if !sequenceGapDetected && (frame.discontinuity || (previousRate != nil && frame.sampleRate != previousRate!)) {
- appendEpochEvent(start, to: &epochEvents)
-#if DEBUG
+ if !sequenceGapDetected && (frame.discontinuity || (previousRate.map { frame.sampleRate != $0 } ?? false)) {
+ self.appendEpochEvent(start, to: &epochEvents)
+ #if DEBUG
resyncEvents.append(start)
-#endif
+ #endif
}
// A reset marker and a measured positive timing hole are independent:
// a route/rate/discontinuity transition can be contiguous (the common
// case) or can also contain a real missing interval. Preserve the
// latter instead of hiding it behind the epoch marker.
if !sequenceGapDetected && start > previousEnd + 1e-9 {
- appendEpochEvent(start, to: &epochEvents)
- appendGap(previousEnd..<start, to: &gaps)
-#if DEBUG
+ self.appendEpochEvent(start, to: &epochEvents)
+ self.appendGap(previousEnd..<start, to: &gaps)
+ #if DEBUG
resyncEvents.append(start)
-#endif
+ #endif
}
}
previousPTS = frame.presentationTime
@@ -910,22 +981,42 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
previousRate = frame.sampleRate
// Keep the original PTS (including the retained post-priming position) for
// provenance; `start` remains the anchored/transformed session coordinate.
- normalized.append((frame, start, frame.presentationTime + Double(leading) / frame.sampleRate,
- nil, nil, values, false))
+ normalized.append((
+ frame,
+ start,
+ frame.presentationTime + Double(leading) / frame.sampleRate,
+ nil,
+ nil,
+ values,
+ false
+ ))
previousRejectedEnd = nil
}
- if configuration.codecRemainderSamples > 0, let last = normalized.indices.last {
+ if self.configuration.codecRemainderSamples > 0, let last = normalized.indices.last {
let trim = min(configuration.codecRemainderSamples, normalized[last].values.count)
if trim > 0 { normalized[last].values.removeLast(trim) }
}
- let segments = normalized.map { TimedSegment(start: $0.start, sourceStart: $0.sourceStart,
+ let segments = normalized.map { TimedSegment(
+ start: $0.start,
+ sourceStart: $0.sourceStart,
sourceTimelineStart: $0.sourceStart,
- sourceSampleTime: $0.sourceSampleTime, hostTime: $0.hostTime,
+ sourceSampleTime: $0.sourceSampleTime,
+ hostTime: $0.hostTime,
sourceSampleRate: $0.frame.sampleRate,
sessionSampleRate: $0.frame.sampleRate / self.referenceTimelineScale,
timelineScale: self.referenceTimelineScale,
- values: $0.values, synthesized: false) }
- return makeTrackGrid(segments: segments, sourceOrigin: normalized.first?.sourceStart, firstTime: normalized.map { $0.start }.min(), epochEvents: epochEvents, resynchronizationEvents: resyncEvents, gaps: gaps, synthesizedFrameCount: 0)
+ values: $0.values,
+ synthesized: false
+ ) }
+ return self.makeTrackGrid(
+ segments: segments,
+ sourceOrigin: normalized.first?.sourceStart,
+ firstTime: normalized.map { $0.start }.min(),
+ epochEvents: epochEvents,
+ resynchronizationEvents: resyncEvents,
+ gaps: gaps,
+ synthesizedFrameCount: 0
+ )
}
private func makeTrackGrid(
@@ -933,12 +1024,27 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
) -> TrackGrid {
let first = firstTime
let last = segments.map { $0.start + Double($0.values.count) / $0.sessionSampleRate }.max()
- return TrackGrid(segments: segments, sourceOrigin: sourceOrigin, firstTime: first, lastTime: last, epochEvents: epochEvents, resynchronizationEvents: resynchronizationEvents, gapRanges: gaps, synthesizedFrameCount: synthesizedFrameCount)
+ return TrackGrid(
+ segments: segments,
+ sourceOrigin: sourceOrigin,
+ firstTime: first,
+ lastTime: last,
+ epochEvents: epochEvents,
+ resynchronizationEvents: resynchronizationEvents,
+ gapRanges: gaps,
+ synthesizedFrameCount: synthesizedFrameCount
+ )
}
private func makeGrid(track: TrackGrid, origin: Double, frameSize: Int, outputCount: Int) -> Grid {
guard track.firstTime != nil, track.lastTime != nil, outputCount > 0 else {
- return Grid(samples: [Float](repeating: 0, count: outputCount), valid: [Bool](repeating: false, count: outputCount), sourceTimes: [Double?](repeating: nil, count: outputCount), microphoneSampleTimes: [Int64?](repeating: nil, count: outputCount), microphoneHostTimes: [Double?](repeating: nil, count: outputCount))
+ return Grid(
+ samples: [Float](repeating: 0, count: outputCount),
+ valid: [Bool](repeating: false, count: outputCount),
+ sourceTimes: [Double?](repeating: nil, count: outputCount),
+ microphoneSampleTimes: [Int64?](repeating: nil, count: outputCount),
+ microphoneHostTimes: [Double?](repeating: nil, count: outputCount)
+ )
}
// The caller has already bounded `outputCount` after checking all span
// arithmetic. Do not derive a second allocation length from untrusted clock
@@ -949,17 +1055,21 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
var microphoneSampleTimes = [Int64?](repeating: nil, count: outputCount)
var microphoneHostTimes = [Double?](repeating: nil, count: outputCount)
for segment in track.segments {
- let relativeIndex = (segment.start - origin) * configuration.analysisSampleRate
+ let relativeIndex = (segment.start - origin) * self.configuration.analysisSampleRate
guard let roundedIndex = safeRoundedInt(relativeIndex) else { continue }
let startIndex = max(0, roundedIndex)
let segmentEnd = segment.start + Double(segment.values.count) / segment.sessionSampleRate
- let relativeEndIndex = (segmentEnd - origin) * configuration.analysisSampleRate
+ let relativeEndIndex = (segmentEnd - origin) * self.configuration.analysisSampleRate
guard let roundedEndIndex = safeRoundedInt(relativeEndIndex) else { continue }
let (targetCount, targetOverflow) = roundedEndIndex.subtractingReportingOverflow(roundedIndex)
guard !targetOverflow, targetCount > 0 else { continue }
- let converted = resample(segment.values, fromRate: segment.sessionSampleRate,
- toRate: configuration.analysisSampleRate, maximumCount: outputCount,
- targetCount: targetCount)
+ let converted = self.resample(
+ segment.values,
+ fromRate: segment.sessionSampleRate,
+ toRate: self.configuration.analysisSampleRate,
+ maximumCount: outputCount,
+ targetCount: targetCount
+ )
for (offset, value) in converted.enumerated() {
let (index, indexOverflow) = startIndex.addingReportingOverflow(offset)
guard !indexOverflow else { break }
@@ -969,7 +1079,7 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
samples[index] = value
valid[index] = value.isFinite
let sourceOffsetSamples = Double(offset) * segment.sourceSampleRate
- / configuration.analysisSampleRate / segment.timelineScale
+ / self.configuration.analysisSampleRate / segment.timelineScale
sourceTimes[index] = segment.sourceTimelineStart + sourceOffsetSamples / segment.sourceSampleRate
microphoneSampleTimes[index] = segment.sourceSampleTime.flatMap {
let offset = sourceOffsetSamples.rounded()
@@ -983,13 +1093,23 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
}
}
_ = frameSize
- return Grid(samples: samples, valid: valid, sourceTimes: sourceTimes,
- microphoneSampleTimes: microphoneSampleTimes, microphoneHostTimes: microphoneHostTimes)
+ return Grid(
+ samples: samples,
+ valid: valid,
+ sourceTimes: sourceTimes,
+ microphoneSampleTimes: microphoneSampleTimes,
+ microphoneHostTimes: microphoneHostTimes
+ )
}
- private func resample(_ values: [Float], fromRate: Double, toRate: Double,
- maximumCount: Int, targetCount: Int? = nil) -> [Float] {
- guard !values.isEmpty, finite(fromRate), fromRate > 0, finite(toRate), toRate > 0 else { return [] }
+ private func resample(
+ _ values: [Float],
+ fromRate: Double,
+ toRate: Double,
+ maximumCount: Int,
+ targetCount: Int? = nil
+ ) -> [Float] {
+ guard !values.isEmpty, self.finite(fromRate), fromRate > 0, self.finite(toRate), toRate > 0 else { return [] }
guard maximumCount > 0 else { return [] }
let count: Int
if let targetCount {
@@ -1015,9 +1135,9 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
/// silently diverge from the frame grid.
private func referenceSessionTime(sourceTime: Double) -> Double {
let scale = self.referenceTimelineScale
- return sourceTime * scale + configuration.editListOffsetSeconds * scale
- - configuration.referenceConverter.algorithmicDelaySeconds
- + configuration.referenceToMicrophoneOffsetSeconds
+ return sourceTime * scale + self.configuration.editListOffsetSeconds * scale
+ - self.configuration.referenceConverter.algorithmicDelaySeconds
+ + self.configuration.referenceToMicrophoneOffsetSeconds
}
private func referenceSessionDuration(_ sourceDuration: Double) -> Double {
@@ -1025,7 +1145,7 @@ nonisolated public struct MeetingReferenceSynchronizer: Sendable {
}
private var referenceTimelineScale: Double {
- 1 + configuration.referenceClockDriftPPM / 1_000_000
+ 1 + self.configuration.referenceClockDriftPPM / 1_000_000
}
private func downmix(_ samples: [Float], channels: Int) -> [Float] {
diff --git a/Sources/Fluid/Services/Meeting/MeetingSCKPairedAutorun.swift b/Sources/Fluid/Services/Meeting/MeetingSCKPairedAutorun.swift
index 78b563b8..c9ae76b3 100644
--- a/Sources/Fluid/Services/Meeting/MeetingSCKPairedAutorun.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingSCKPairedAutorun.swift
@@ -64,14 +64,15 @@ nonisolated enum MeetingSCKPairedAutorun {
@MainActor
private static func run(environment: [String: String]) async -> Outcome {
guard CGPreflightScreenCaptureAccess() else {
- return Self.failure("screen recording access is not preflight-authorized")
+ return failure("screen recording access is not preflight-authorized")
}
guard AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else {
- return Self.failure("microphone access is not authorized")
+ return failure("microphone access is not authorized")
}
guard let bundleID = environment[MeetingSCKPairedDiagnosticGate.targetBundleIDEnvironmentKey]?
- .trimmingCharacters(in: .whitespacesAndNewlines), !bundleID.isEmpty else {
- return Self.failure("target bundle ID is empty")
+ .trimmingCharacters(in: .whitespacesAndNewlines), !bundleID.isEmpty
+ else {
+ return failure("target bundle ID is empty")
}
guard let microphone = AVCaptureDevice.default(for: .audio), !microphone.uniqueID.isEmpty else {
return Self.failure("no default microphone device is available")
@@ -119,11 +120,13 @@ nonisolated enum MeetingSCKPairedAutorun {
let stream = SCStream(filter: filter, configuration: configuration, delegate: nil)
do {
try stream.addStreamOutput(
- output, type: .audio,
+ output,
+ type: .audio,
sampleHandlerQueue: DispatchQueue(label: "fluidvoice.c2.autorun.application", qos: .userInteractive)
)
try stream.addStreamOutput(
- output, type: .microphone,
+ output,
+ type: .microphone,
sampleHandlerQueue: DispatchQueue(label: "fluidvoice.c2.autorun.microphone", qos: .userInteractive)
)
} catch {
@@ -181,13 +184,15 @@ nonisolated enum MeetingSCKPairedAutorun {
return "one or both paired outputs produced no samples"
}
guard report.application.validTimestampCount == report.application.sampleCount,
- report.microphone.validTimestampCount == report.microphone.sampleCount else {
+ report.microphone.validTimestampCount == report.microphone.sampleCount
+ else {
return "paired output timestamps were malformed"
}
guard report.application.firstPresentationSeconds?.isFinite == true,
report.application.lastPresentationEndSeconds?.isFinite == true,
report.microphone.firstPresentationSeconds?.isFinite == true,
- report.microphone.lastPresentationEndSeconds?.isFinite == true else {
+ report.microphone.lastPresentationEndSeconds?.isFinite == true
+ else {
return "paired output timestamps were non-finite"
}
guard report.application.firstSampleRateHz?.isFinite == true,
@@ -195,7 +200,8 @@ nonisolated enum MeetingSCKPairedAutorun {
(report.application.firstSampleRateHz ?? 0) > 0,
(report.microphone.firstSampleRateHz ?? 0) > 0,
(report.application.firstChannelCount ?? 0) > 0,
- (report.microphone.firstChannelCount ?? 0) > 0 else {
+ (report.microphone.firstChannelCount ?? 0) > 0
+ else {
return "paired output formats were invalid"
}
guard report.acceptedSampleCount == report.application.sampleCount + report.microphone.sampleCount else {
@@ -219,9 +225,12 @@ nonisolated enum MeetingSCKPairedAutorun {
private static func jsonLine(_ object: [String: Any]) -> String? {
guard JSONSerialization.isValidJSONObject(object),
- let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) else {
+ let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])
+ else {
return nil
}
+ // Diagnostic JSON is emitted as UTF-8; decoding keeps the report output nonoptional.
+ // swiftlint:disable:next optional_data_string_conversion
return String(decoding: data, as: UTF8.self)
}
@@ -230,7 +239,7 @@ nonisolated enum MeetingSCKPairedAutorun {
}
private static func stopCaptureBestEffort(_ stream: SCStream) async {
- try? await Self.withTimeout(seconds: Self.operationTimeoutSeconds) {
+ try? await self.withTimeout(seconds: self.operationTimeoutSeconds) {
try await stream.stopCapture()
}
}
@@ -246,7 +255,8 @@ nonisolated enum MeetingSCKPairedAutorun {
throw AutorunError.timeout
}
defer { group.cancelAll() }
- return try await group.next()!
+ guard let result = try await group.next() else { throw AutorunError.timeout }
+ return result
}
}
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingSCKPairedDiagnostics.swift b/Sources/Fluid/Services/Meeting/MeetingSCKPairedDiagnostics.swift
index 83ee37f5..88e620d9 100644
--- a/Sources/Fluid/Services/Meeting/MeetingSCKPairedDiagnostics.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingSCKPairedDiagnostics.swift
@@ -1,7 +1,7 @@
#if DEBUG
-import Foundation
import CoreMedia
+import Foundation
/// Phase 0 C2 is deliberately diagnostic-only. The collector receives metadata from the two
/// outputs of one ScreenCaptureKit stream, but never receives (or retains) PCM, transcript text,
@@ -14,20 +14,20 @@ nonisolated enum MeetingSCKPairedDiagnosticGate {
static let autorunEnvironmentKey = "FLUIDVOICE_C2_AUTORUN"
static func enabled(environment: [String: String] = ProcessInfo.processInfo.environment) -> Bool {
- environment[Self.environmentKey] == "1"
+ environment[self.environmentKey] == "1"
}
static func hardwareEnabled(environment: [String: String] = ProcessInfo.processInfo.environment) -> Bool {
- guard self.enabled(environment: environment), environment[Self.hardwareEnvironmentKey] == "1" else {
+ guard self.enabled(environment: environment), environment[self.hardwareEnvironmentKey] == "1" else {
return false
}
- return !(environment[Self.targetBundleIDEnvironmentKey] ?? "")
+ return !(environment[self.targetBundleIDEnvironmentKey] ?? "")
.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
static func autorunEnabled(environment: [String: String] = ProcessInfo.processInfo.environment) -> Bool {
self.hardwareEnabled(environment: environment)
- && environment[Self.autorunEnvironmentKey] == "1"
+ && environment[self.autorunEnvironmentKey] == "1"
}
}
@@ -124,6 +124,8 @@ nonisolated struct MeetingSCKPairedTrackReport: Codable, Equatable, Sendable {
let maxAbsoluteJitterSeconds: Double?
let malformedMetadataCount: Int
+ // These snapshot helpers are shared by neighboring types within this file only.
+ // swiftlint:disable:next strict_fileprivate
fileprivate init(state: MeetingSCKPairedTrackState) {
self.sampleCount = state.sampleCount
self.validTimestampCount = state.validTimestampCount
@@ -170,6 +172,8 @@ nonisolated struct MeetingSCKPairedCrossTrackReport: Codable, Equatable, Sendabl
let sharedClockEstablished: Bool
let aecEvaluated: Bool
+ // These snapshot helpers are shared by neighboring types within this file only.
+ // swiftlint:disable:next strict_fileprivate
fileprivate init(application: MeetingSCKPairedTrackReport, microphone: MeetingSCKPairedTrackReport) {
if let app = application.firstPresentationSeconds, let mic = microphone.firstPresentationSeconds {
self.firstPresentationOffsetSeconds = mic - app
@@ -182,7 +186,8 @@ nonisolated struct MeetingSCKPairedCrossTrackReport: Codable, Equatable, Sendabl
self.lastPresentationOffsetSeconds = nil
}
if let appSpan = application.timestampSpanSeconds, let micSpan = microphone.timestampSpanSeconds,
- appSpan > 0, micSpan.isFinite {
+ appSpan > 0, micSpan.isFinite
+ {
self.relativeTimestampSpanDifferencePPM = (micSpan / appSpan - 1) * 1_000_000
} else {
self.relativeTimestampSpanDifferencePPM = nil
@@ -212,6 +217,8 @@ nonisolated struct MeetingSCKPairedDiagnosticReport: Codable, Equatable, Sendabl
let failOpen: Bool
let reasons: [String]
+ // These snapshot helpers are shared by neighboring types within this file only.
+ // swiftlint:disable:next strict_fileprivate
fileprivate init(
enabled: Bool,
configuration: MeetingSCKPairedDiagnosticConfiguration,
@@ -239,7 +246,7 @@ nonisolated struct MeetingSCKPairedDiagnosticReport: Codable, Equatable, Sendabl
"diagnostic-only",
"no raw PCM or transcript retention",
"shared clock not established",
- "acoustic delay and AEC not evaluated"
+ "acoustic delay and AEC not evaluated",
]
}
@@ -383,12 +390,14 @@ nonisolated enum MeetingSCKPairedDiagnosticHarness {
environment: [String: String] = ProcessInfo.processInfo.environment
) -> MeetingSCKPairedDiagnosticReport {
let collector = MeetingSCKPairedDiagnosticCollector(configuration: configuration, environment: environment)
- for sample in samples { collector.record(sample) }
+ for sample in samples {
+ collector.record(sample)
+ }
return collector.report()
}
}
-nonisolated private struct MeetingSCKPairedTrackState {
+private nonisolated struct MeetingSCKPairedTrackState {
var sampleCount = 0
var validTimestampCount = 0
var invalidTimestampCount = 0
@@ -418,14 +427,14 @@ nonisolated private struct MeetingSCKPairedTrackState {
let validDuration = sample.durationSeconds.map { $0.isFinite && $0 > 0 } ?? false
let validPTS = sample.presentationSeconds.map(\.isFinite) ?? false
let validFrameGeometry: Bool = {
- guard validFormat, validDuration else { return false }
+ guard validFormat, validDuration, let duration = sample.durationSeconds else { return false }
let frameDuration = Double(sample.frameCount) / sample.sampleRateHz
let tolerance = max(1.5 / sample.sampleRateHz, 0.001)
- return frameDuration.isFinite && abs(frameDuration - sample.durationSeconds!) <= tolerance
+ return frameDuration.isFinite && abs(frameDuration - duration) <= tolerance
}()
let validEnd: Bool = {
- guard validPTS, validDuration else { return false }
- return (sample.presentationSeconds! + sample.durationSeconds!).isFinite
+ guard validPTS, validDuration, let pts = sample.presentationSeconds, let duration = sample.durationSeconds else { return false }
+ return (pts + duration).isFinite
}()
guard validFormat && validDuration && validPTS && validFrameGeometry && validEnd else {
self.invalidTimestampCount += validPTS ? 0 : 1
@@ -433,8 +442,7 @@ nonisolated private struct MeetingSCKPairedTrackState {
return
}
- let pts = sample.presentationSeconds!
- let duration = sample.durationSeconds!
+ guard let pts = sample.presentationSeconds, let duration = sample.durationSeconds else { return }
self.validTimestampCount += 1
self.deliveredDurationSeconds += duration
if self.firstSampleRateHz == nil {
@@ -445,7 +453,8 @@ nonisolated private struct MeetingSCKPairedTrackState {
}
if let previousPTS = self.previousPresentationSeconds,
- let previousDuration = self.previousDurationSeconds {
+ let previousDuration = self.previousDurationSeconds
+ {
let delta = pts - previousPTS
// CMTime-to-Double conversion can perturb an otherwise contiguous boundary by a few
// nanoseconds. Half a sample is a conservative representational tolerance: it ignores
@@ -464,9 +473,10 @@ nonisolated private struct MeetingSCKPairedTrackState {
}
if let arrival = sample.arrivalSeconds, arrival.isFinite,
let previousArrival = self.previousArrivalSeconds,
- let previousDuration = self.previousDurationSeconds {
+ let previousDuration = self.previousDurationSeconds
+ {
let deliveryDelta = arrival - previousArrival
- if deliveryDelta.isFinite && deliveryDelta >= 0 {
+ if deliveryDelta.isFinite, deliveryDelta >= 0 {
let jitter = abs(deliveryDelta - previousDuration)
self.jitterObservationCount += 1
self.jitterAbsoluteSum += jitter
diff --git a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
index 5f7e9395..63bf01ac 100644
--- a/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingSessionCoordinator.swift
@@ -346,8 +346,10 @@ final class MeetingSessionCoordinator: ObservableObject {
(offer.state == .interrupted || offer.state == .failed) ? offer : nil
}
return try await self.performStartRecording(
- configuration: configuration, passiveOffer: passiveOffer,
- resolvingSourceID: resolvingSourceID, reservation: reservation
+ configuration: configuration,
+ passiveOffer: passiveOffer,
+ resolvingSourceID: resolvingSourceID,
+ reservation: reservation
)
}
@@ -1294,11 +1296,11 @@ final class MeetingSessionCoordinator: ObservableObject {
}
guard !viable.isEmpty else { return }
- let active = viable.sorted { lhs, rhs in
+ guard let active = viable.sorted(by: { lhs, rhs in
lhs.startedAt != rhs.startedAt
? lhs.startedAt < rhs.startedAt
: lhs.id.uuidString < rhs.id.uuidString
- }.last!
+ }).last else { return }
for session in viable {
guard session.id == active.id else {
diff --git a/Sources/Fluid/Services/Meeting/MeetingSessionStore.swift b/Sources/Fluid/Services/Meeting/MeetingSessionStore.swift
index 4f908428..03802a36 100644
--- a/Sources/Fluid/Services/Meeting/MeetingSessionStore.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingSessionStore.swift
@@ -444,7 +444,7 @@ actor MeetingSessionStore: MeetingSessionStoring {
var reconciled = inputChunk
if var archive = reconciled.playbackArchiveAsset,
archive.presence == .ready,
- (!archive.validationIssues().isEmpty || !self.assetMatchesDisk(archive, sessionDirectory: sessionDirectory))
+ !archive.validationIssues().isEmpty || !self.assetMatchesDisk(archive, sessionDirectory: sessionDirectory)
{
// The archive is derived and optional. Quarantine only it; authoritative PCM remains
// finalized and retryable for a later archive job.
@@ -462,12 +462,12 @@ actor MeetingSessionStore: MeetingSessionStoring {
relativePath: asset.relativeFilePath,
sessionDirectory: sessionDirectory
), let attributes = try? self.fileSystem.manager.attributesOfItem(atPath: url.path),
- let size = (attributes[.size] as? NSNumber)?.int64Value,
- size == asset.byteCount,
- size > 0,
- let expectedHash = asset.sha256,
- let hash = self.sha256(of: url),
- hash == expectedHash
+ let size = (attributes[.size] as? NSNumber)?.int64Value,
+ size == asset.byteCount,
+ size > 0,
+ let expectedHash = asset.sha256,
+ let hash = self.sha256(of: url),
+ hash == expectedHash
else { return false }
return true
}
@@ -497,8 +497,7 @@ actor MeetingSessionStore: MeetingSessionStoring {
var digest = SHA256()
while true {
let data: Data
- do { data = try handle.read(upToCount: 1 << 20) ?? Data() }
- catch { return nil }
+ do { data = try handle.read(upToCount: 1 << 20) ?? Data() } catch { return nil }
guard !data.isEmpty else { break }
digest.update(data: data)
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingSignalDomainGate.swift b/Sources/Fluid/Services/Meeting/MeetingSignalDomainGate.swift
index 9a52f48a..09099e15 100644
--- a/Sources/Fluid/Services/Meeting/MeetingSignalDomainGate.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingSignalDomainGate.swift
@@ -82,9 +82,17 @@ public struct MeetingSignalDomainGateManifest: Codable, Equatable, Sendable {
public let durationSeconds: Double
public let developmentOnly: Bool
- public init(role: String, relativePath: String, sha256: String, codec: String,
- lossless: Bool, sampleRateHz: Double, channelCount: Int,
- durationSeconds: Double, developmentOnly: Bool = true) {
+ public init(
+ role: String,
+ relativePath: String,
+ sha256: String,
+ codec: String,
+ lossless: Bool,
+ sampleRateHz: Double,
+ channelCount: Int,
+ durationSeconds: Double,
+ developmentOnly: Bool = true
+ ) {
self.role = role
self.relativePath = relativePath
self.sha256 = sha256
@@ -103,8 +111,12 @@ public struct MeetingSignalDomainGateManifest: Codable, Equatable, Sendable {
public let frameCount: Int
public let arrivalSeconds: Double?
- public init(presentationSeconds: Double, durationSeconds: Double, frameCount: Int,
- arrivalSeconds: Double?) {
+ public init(
+ presentationSeconds: Double,
+ durationSeconds: Double,
+ frameCount: Int,
+ arrivalSeconds: Double?
+ ) {
self.presentationSeconds = presentationSeconds; self.durationSeconds = durationSeconds
self.frameCount = frameCount; self.arrivalSeconds = arrivalSeconds
}
@@ -117,8 +129,13 @@ public struct MeetingSignalDomainGateManifest: Codable, Equatable, Sendable {
public let renderTiming: [TimingBlock]
public let captureTiming: [TimingBlock]
- public init(ordinal: Int, render: Artifact, capture: Artifact,
- renderTiming: [TimingBlock], captureTiming: [TimingBlock]) {
+ public init(
+ ordinal: Int,
+ render: Artifact,
+ capture: Artifact,
+ renderTiming: [TimingBlock],
+ captureTiming: [TimingBlock]
+ ) {
self.ordinal = ordinal; self.render = render; self.capture = capture
self.renderTiming = renderTiming; self.captureTiming = captureTiming
}
@@ -135,13 +152,18 @@ public struct MeetingSignalDomainGateManifest: Codable, Equatable, Sendable {
public let provenanceRelativePath: String?
public let provenanceSha256: String?
- public init(schemaVersion: Int = 1, topology: MeetingSignalDomainGateTopology,
- route: MeetingSignalDomainGateRoute,
- referenceScope: MeetingSignalDomainGateReferenceScope,
- referenceCompletenessMeasured: Bool,
- consentConfirmed: Bool, artifacts: [Artifact],
- sessions: [Session] = [], provenanceRelativePath: String? = nil,
- provenanceSha256: String? = nil) {
+ public init(
+ schemaVersion: Int = 1,
+ topology: MeetingSignalDomainGateTopology,
+ route: MeetingSignalDomainGateRoute,
+ referenceScope: MeetingSignalDomainGateReferenceScope,
+ referenceCompletenessMeasured: Bool,
+ consentConfirmed: Bool,
+ artifacts: [Artifact],
+ sessions: [Session] = [],
+ provenanceRelativePath: String? = nil,
+ provenanceSha256: String? = nil
+ ) {
self.schemaVersion = schemaVersion
self.topology = topology
self.route = route
@@ -156,25 +178,26 @@ public struct MeetingSignalDomainGateManifest: Codable, Equatable, Sendable {
public func validationReasons() -> [MeetingSignalDomainGateReason] {
var reasons: [MeetingSignalDomainGateReason] = []
- if (provenanceRelativePath == nil) != (provenanceSha256 == nil) {
+ if (self.provenanceRelativePath == nil) != (self.provenanceSha256 == nil) {
reasons.append(.invalidManifest)
}
if let path = provenanceRelativePath,
- (!Self.isSafeRelativePath(path) || provenanceSha256?.count != 64
- || provenanceSha256 != provenanceSha256?.lowercased()
- || !(provenanceSha256 ?? "").unicodeScalars.allSatisfy(Self.isHex)) {
+ !Self.isSafeRelativePath(path) || provenanceSha256?.count != 64
+ || provenanceSha256 != provenanceSha256?.lowercased()
+ || !(provenanceSha256 ?? "").unicodeScalars.allSatisfy(Self.isHex)
+ {
reasons.append(.invalidManifest)
}
- if schemaVersion != 1 { reasons.append(.invalidManifest) }
- if !consentConfirmed { reasons.append(.missingConsent) }
- if topology != .pairedScreenCaptureKit { reasons.append(.unsupportedTopology) }
- if route != .builtInSpeakerMicrophone { reasons.append(.unsupportedRoute) }
- if referenceScope == .unknown { reasons.append(.referenceScopeLimited) }
- if !referenceCompletenessMeasured { reasons.append(.referenceCompletenessUnobservable) }
- if !sessions.isEmpty {
- if !artifacts.isEmpty { reasons.append(.invalidManifest) }
+ if self.schemaVersion != 1 { reasons.append(.invalidManifest) }
+ if !self.consentConfirmed { reasons.append(.missingConsent) }
+ if self.topology != .pairedScreenCaptureKit { reasons.append(.unsupportedTopology) }
+ if self.route != .builtInSpeakerMicrophone { reasons.append(.unsupportedRoute) }
+ if self.referenceScope == .unknown { reasons.append(.referenceScopeLimited) }
+ if !self.referenceCompletenessMeasured { reasons.append(.referenceCompletenessUnobservable) }
+ if !self.sessions.isEmpty {
+ if !self.artifacts.isEmpty { reasons.append(.invalidManifest) }
var sessionOrdinals = Set<Int>()
- for session in sessions {
+ for session in self.sessions {
if session.ordinal < 0 || !sessionOrdinals.insert(session.ordinal).inserted { reasons.append(.invalidManifest) }
if session.render.role.lowercased() != "render" || session.capture.role.lowercased() != "capture" {
reasons.append(.invalidManifest)
@@ -182,7 +205,8 @@ public struct MeetingSignalDomainGateManifest: Codable, Equatable, Sendable {
if session.render.relativePath == session.capture.relativePath { reasons.append(.invalidManifest) }
if session.render.codec.lowercased() != session.capture.codec.lowercased()
|| session.render.channelCount != session.capture.channelCount
- || abs(session.render.sampleRateHz - session.capture.sampleRateHz) > 1e-6 {
+ || abs(session.render.sampleRateHz - session.capture.sampleRateHz) > 1e-6
+ {
reasons.append(.inconsistentGeometry)
}
for artifact in [session.render, session.capture] {
@@ -202,20 +226,22 @@ public struct MeetingSignalDomainGateManifest: Codable, Equatable, Sendable {
}
return Self.unique(reasons)
}
- guard artifacts.count == 2 else { return reasons + [.invalidManifest] }
+ guard self.artifacts.count == 2 else { return reasons + [.invalidManifest] }
let roles = Set(artifacts.map { $0.role.lowercased() })
if roles != Set(["render", "capture"]) { reasons.append(.invalidManifest) }
- if Set(artifacts.map(\.relativePath)).count != artifacts.count { reasons.append(.invalidManifest) }
- if artifacts.count == 2,
- abs(artifacts[0].sampleRateHz - artifacts[1].sampleRateHz) > 1e-6
- || artifacts[0].channelCount != artifacts[1].channelCount
- || artifacts[0].codec.lowercased() != artifacts[1].codec.lowercased() {
+ if Set(self.artifacts.map(\.relativePath)).count != self.artifacts.count { reasons.append(.invalidManifest) }
+ if self.artifacts.count == 2,
+ abs(self.artifacts[0].sampleRateHz - self.artifacts[1].sampleRateHz) > 1e-6
+ || self.artifacts[0].channelCount != self.artifacts[1].channelCount
+ || self.artifacts[0].codec.lowercased() != self.artifacts[1].codec.lowercased()
+ {
reasons.append(.inconsistentGeometry)
}
- for artifact in artifacts {
+ for artifact in self.artifacts {
if !Self.isSafeRelativePath(artifact.relativePath) || artifact.sha256.count != 64
|| artifact.sha256 != artifact.sha256.lowercased()
- || !artifact.sha256.unicodeScalars.allSatisfy(Self.isHex) {
+ || !artifact.sha256.unicodeScalars.allSatisfy(Self.isHex)
+ {
reasons.append(.invalidManifest)
}
if !artifact.lossless { reasons.append(.nonLossless) }
@@ -230,17 +256,20 @@ public struct MeetingSignalDomainGateManifest: Codable, Equatable, Sendable {
}
private static let losslessCodecs: Set<String> = ["pcm_s16le", "pcm_s24le", "pcm_s32le", "pcm_f32le", "lpcm"]
- nonisolated private static func isHex(_ scalar: Unicode.Scalar) -> Bool {
+ private nonisolated static func isHex(_ scalar: Unicode.Scalar) -> Bool {
(48...57).contains(scalar.value) || (97...102).contains(scalar.value)
}
+
private static func isSafeRelativePath(_ path: String) -> Bool {
guard !path.isEmpty, !path.hasPrefix("/"), !path.hasPrefix("~"), !path.contains("\\") else { return false }
let parts = path.split(separator: "/", omittingEmptySubsequences: false)
return parts.allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." }
}
+
private static func timingReasons(_ blocks: [TimingBlock], artifact: Artifact) -> [MeetingSignalDomainGateReason] {
guard artifact.sampleRateHz.isFinite, artifact.sampleRateHz > 0,
- artifact.durationSeconds.isFinite, artifact.durationSeconds > 0 else {
+ artifact.durationSeconds.isFinite, artifact.durationSeconds > 0
+ else {
return [.invalidTiming]
}
guard !blocks.isEmpty else { return [.metadataOnly] }
@@ -251,7 +280,8 @@ public struct MeetingSignalDomainGateManifest: Codable, Equatable, Sendable {
for block in blocks {
guard block.presentationSeconds.isFinite, block.durationSeconds.isFinite,
block.durationSeconds > 0, block.frameCount > 0,
- block.arrivalSeconds == nil || block.arrivalSeconds!.isFinite else {
+ (block.arrivalSeconds.map { $0.isFinite } ?? true)
+ else {
reasons.append(.invalidTiming); continue
}
let blockRate = Double(block.frameCount) / block.durationSeconds
@@ -273,6 +303,7 @@ public struct MeetingSignalDomainGateManifest: Codable, Equatable, Sendable {
}
return Self.unique(reasons)
}
+
private static func unique(_ reasons: [MeetingSignalDomainGateReason]) -> [MeetingSignalDomainGateReason] {
var seen = Set<MeetingSignalDomainGateReason>()
return reasons.filter { seen.insert($0).inserted }
@@ -298,15 +329,25 @@ public struct MeetingSignalDomainGateThresholds: Codable, Equatable, Sendable {
public let minimumTimingBlockCount: Int
public let maximumPCMSamples: Int
- public init(minimumValidCoverageFraction: Double = 0.99, maximumDriftPPM: Double = 100,
- maximumUncorrectedOffsetSeconds: Double = 0.020, maximumRenderLeadSeconds: Double = 0.100,
- maximumSearchDelaySeconds: Double = 0.500, safetyMarginSeconds: Double = 0.020,
- minimumBandCoherence: Double = 0.10, minimumExcitationRMS: Double = 0.001,
- maximumClippingFraction: Double = 0.010, maximumHeldOutLinearResidualFraction: Double = 0.75,
- maximumIneligibleSessionFraction: Double = 0.25, minimumExposureSeconds: Double = 1.0,
- requireDeliveryJitter: Bool = true, minimumPathStabilityFraction: Double = 0.5,
- minimumDelayObservationCount: Int = 3, minimumTimingBlockCount: Int = 3,
- maximumPCMSamples: Int = 1_000_000) {
+ public init(
+ minimumValidCoverageFraction: Double = 0.99,
+ maximumDriftPPM: Double = 100,
+ maximumUncorrectedOffsetSeconds: Double = 0.020,
+ maximumRenderLeadSeconds: Double = 0.100,
+ maximumSearchDelaySeconds: Double = 0.500,
+ safetyMarginSeconds: Double = 0.020,
+ minimumBandCoherence: Double = 0.10,
+ minimumExcitationRMS: Double = 0.001,
+ maximumClippingFraction: Double = 0.010,
+ maximumHeldOutLinearResidualFraction: Double = 0.75,
+ maximumIneligibleSessionFraction: Double = 0.25,
+ minimumExposureSeconds: Double = 1.0,
+ requireDeliveryJitter: Bool = true,
+ minimumPathStabilityFraction: Double = 0.5,
+ minimumDelayObservationCount: Int = 3,
+ minimumTimingBlockCount: Int = 3,
+ maximumPCMSamples: Int = 1_000_000
+ ) {
self.minimumValidCoverageFraction = minimumValidCoverageFraction
self.maximumDriftPPM = maximumDriftPPM
self.maximumUncorrectedOffsetSeconds = maximumUncorrectedOffsetSeconds
@@ -334,12 +375,14 @@ public struct MeetingSignalDomainGateThresholds: Codable, Equatable, Sendable {
minimumExposureSeconds, requireDeliveryJitter, minimumPathStabilityFraction,
minimumDelayObservationCount, minimumTimingBlockCount, maximumPCMSamples
}
+
private struct DynamicKey: CodingKey {
var stringValue: String
init?(stringValue: String) { self.stringValue = stringValue }
var intValue: Int?
init?(intValue: Int) { return nil }
}
+
public init(from decoder: Decoder) throws {
let dynamic = try decoder.container(keyedBy: DynamicKey.self)
let allowed = Set(CodingKeys.allCases.map(\.rawValue))
@@ -347,42 +390,44 @@ public struct MeetingSignalDomainGateThresholds: Codable, Equatable, Sendable {
throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Unknown threshold key"))
}
let c = try decoder.container(keyedBy: CodingKeys.self)
- self.init(minimumValidCoverageFraction: try c.decodeIfPresent(Double.self, forKey: .minimumValidCoverageFraction) ?? 0.99,
- maximumDriftPPM: try c.decodeIfPresent(Double.self, forKey: .maximumDriftPPM) ?? 100,
- maximumUncorrectedOffsetSeconds: try c.decodeIfPresent(Double.self, forKey: .maximumUncorrectedOffsetSeconds) ?? 0.020,
- maximumRenderLeadSeconds: try c.decodeIfPresent(Double.self, forKey: .maximumRenderLeadSeconds) ?? 0.100,
- maximumSearchDelaySeconds: try c.decodeIfPresent(Double.self, forKey: .maximumSearchDelaySeconds) ?? 0.500,
- safetyMarginSeconds: try c.decodeIfPresent(Double.self, forKey: .safetyMarginSeconds) ?? 0.020,
- minimumBandCoherence: try c.decodeIfPresent(Double.self, forKey: .minimumBandCoherence) ?? 0.10,
- minimumExcitationRMS: try c.decodeIfPresent(Double.self, forKey: .minimumExcitationRMS) ?? 0.001,
- maximumClippingFraction: try c.decodeIfPresent(Double.self, forKey: .maximumClippingFraction) ?? 0.010,
- maximumHeldOutLinearResidualFraction: try c.decodeIfPresent(Double.self, forKey: .maximumHeldOutLinearResidualFraction) ?? 0.75,
- maximumIneligibleSessionFraction: try c.decodeIfPresent(Double.self, forKey: .maximumIneligibleSessionFraction) ?? 0.25,
- minimumExposureSeconds: try c.decodeIfPresent(Double.self, forKey: .minimumExposureSeconds) ?? 1.0,
- requireDeliveryJitter: try c.decodeIfPresent(Bool.self, forKey: .requireDeliveryJitter) ?? true,
- minimumPathStabilityFraction: try c.decodeIfPresent(Double.self, forKey: .minimumPathStabilityFraction) ?? 0.5,
- minimumDelayObservationCount: try c.decodeIfPresent(Int.self, forKey: .minimumDelayObservationCount) ?? 3,
- minimumTimingBlockCount: try c.decodeIfPresent(Int.self, forKey: .minimumTimingBlockCount) ?? 3,
- maximumPCMSamples: try c.decodeIfPresent(Int.self, forKey: .maximumPCMSamples) ?? 1_000_000)
+ try self.init(
+ minimumValidCoverageFraction: c.decodeIfPresent(Double.self, forKey: .minimumValidCoverageFraction) ?? 0.99,
+ maximumDriftPPM: c.decodeIfPresent(Double.self, forKey: .maximumDriftPPM) ?? 100,
+ maximumUncorrectedOffsetSeconds: c.decodeIfPresent(Double.self, forKey: .maximumUncorrectedOffsetSeconds) ?? 0.020,
+ maximumRenderLeadSeconds: c.decodeIfPresent(Double.self, forKey: .maximumRenderLeadSeconds) ?? 0.100,
+ maximumSearchDelaySeconds: c.decodeIfPresent(Double.self, forKey: .maximumSearchDelaySeconds) ?? 0.500,
+ safetyMarginSeconds: c.decodeIfPresent(Double.self, forKey: .safetyMarginSeconds) ?? 0.020,
+ minimumBandCoherence: c.decodeIfPresent(Double.self, forKey: .minimumBandCoherence) ?? 0.10,
+ minimumExcitationRMS: c.decodeIfPresent(Double.self, forKey: .minimumExcitationRMS) ?? 0.001,
+ maximumClippingFraction: c.decodeIfPresent(Double.self, forKey: .maximumClippingFraction) ?? 0.010,
+ maximumHeldOutLinearResidualFraction: c.decodeIfPresent(Double.self, forKey: .maximumHeldOutLinearResidualFraction) ?? 0.75,
+ maximumIneligibleSessionFraction: c.decodeIfPresent(Double.self, forKey: .maximumIneligibleSessionFraction) ?? 0.25,
+ minimumExposureSeconds: c.decodeIfPresent(Double.self, forKey: .minimumExposureSeconds) ?? 1.0,
+ requireDeliveryJitter: c.decodeIfPresent(Bool.self, forKey: .requireDeliveryJitter) ?? true,
+ minimumPathStabilityFraction: c.decodeIfPresent(Double.self, forKey: .minimumPathStabilityFraction) ?? 0.5,
+ minimumDelayObservationCount: c.decodeIfPresent(Int.self, forKey: .minimumDelayObservationCount) ?? 3,
+ minimumTimingBlockCount: c.decodeIfPresent(Int.self, forKey: .minimumTimingBlockCount) ?? 3,
+ maximumPCMSamples: c.decodeIfPresent(Int.self, forKey: .maximumPCMSamples) ?? 1_000_000
+ )
}
public var isValid: Bool {
- minimumValidCoverageFraction.isFinite && (0...1).contains(minimumValidCoverageFraction)
- && maximumDriftPPM.isFinite && maximumDriftPPM >= 0
- && maximumUncorrectedOffsetSeconds.isFinite && maximumUncorrectedOffsetSeconds >= 0
- && maximumRenderLeadSeconds.isFinite && maximumRenderLeadSeconds >= 0
- && maximumSearchDelaySeconds.isFinite && maximumSearchDelaySeconds > 0
- && safetyMarginSeconds.isFinite && safetyMarginSeconds >= 0
- && safetyMarginSeconds < maximumSearchDelaySeconds
- && minimumBandCoherence.isFinite && (0...1).contains(minimumBandCoherence)
- && minimumExcitationRMS.isFinite && minimumExcitationRMS >= 0
- && maximumClippingFraction.isFinite && (0...1).contains(maximumClippingFraction)
- && maximumHeldOutLinearResidualFraction.isFinite && (0...1).contains(maximumHeldOutLinearResidualFraction)
- && maximumIneligibleSessionFraction.isFinite && (0...1).contains(maximumIneligibleSessionFraction)
- && minimumExposureSeconds.isFinite && minimumExposureSeconds > 0
- && minimumPathStabilityFraction.isFinite && (0...1).contains(minimumPathStabilityFraction)
- && minimumDelayObservationCount >= 3 && minimumTimingBlockCount >= 2
- && (1_000...1_000_000).contains(maximumPCMSamples)
+ self.minimumValidCoverageFraction.isFinite && (0...1).contains(self.minimumValidCoverageFraction)
+ && self.maximumDriftPPM.isFinite && self.maximumDriftPPM >= 0
+ && self.maximumUncorrectedOffsetSeconds.isFinite && self.maximumUncorrectedOffsetSeconds >= 0
+ && self.maximumRenderLeadSeconds.isFinite && self.maximumRenderLeadSeconds >= 0
+ && self.maximumSearchDelaySeconds.isFinite && self.maximumSearchDelaySeconds > 0
+ && self.safetyMarginSeconds.isFinite && self.safetyMarginSeconds >= 0
+ && self.safetyMarginSeconds < self.maximumSearchDelaySeconds
+ && self.minimumBandCoherence.isFinite && (0...1).contains(self.minimumBandCoherence)
+ && self.minimumExcitationRMS.isFinite && self.minimumExcitationRMS >= 0
+ && self.maximumClippingFraction.isFinite && (0...1).contains(self.maximumClippingFraction)
+ && self.maximumHeldOutLinearResidualFraction.isFinite && (0...1).contains(self.maximumHeldOutLinearResidualFraction)
+ && self.maximumIneligibleSessionFraction.isFinite && (0...1).contains(self.maximumIneligibleSessionFraction)
+ && self.minimumExposureSeconds.isFinite && self.minimumExposureSeconds > 0
+ && self.minimumPathStabilityFraction.isFinite && (0...1).contains(self.minimumPathStabilityFraction)
+ && self.minimumDelayObservationCount >= 3 && self.minimumTimingBlockCount >= 2
+ && (1000...1_000_000).contains(self.maximumPCMSamples)
}
}
@@ -392,8 +437,12 @@ public struct MeetingSignalDomainGateTrackBlock: Sendable {
public let arrivalSeconds: Double?
public let samples: [Float]
- public init(presentationSeconds: Double, durationSeconds: Double,
- arrivalSeconds: Double? = nil, samples: [Float]) {
+ public init(
+ presentationSeconds: Double,
+ durationSeconds: Double,
+ arrivalSeconds: Double? = nil,
+ samples: [Float]
+ ) {
self.presentationSeconds = presentationSeconds
self.durationSeconds = durationSeconds
self.arrivalSeconds = arrivalSeconds
@@ -415,14 +464,20 @@ public struct MeetingSignalDomainGateSession: Sendable {
public let renderBlocks: [MeetingSignalDomainGateTrackBlock]
public let captureBlocks: [MeetingSignalDomainGateTrackBlock]
- public init(ordinal: Int, topology: MeetingSignalDomainGateTopology = .pairedScreenCaptureKit,
- route: MeetingSignalDomainGateRoute = .builtInSpeakerMicrophone,
- referenceScope: MeetingSignalDomainGateReferenceScope = .selectedApplication,
- referenceCompletenessMeasured: Bool = true, consentConfirmed: Bool = true,
- renderCodec: String = "pcm_s16le", captureCodec: String = "pcm_s16le",
- renderLossless: Bool = true, captureLossless: Bool = true,
- renderBlocks: [MeetingSignalDomainGateTrackBlock],
- captureBlocks: [MeetingSignalDomainGateTrackBlock]) {
+ public init(
+ ordinal: Int,
+ topology: MeetingSignalDomainGateTopology = .pairedScreenCaptureKit,
+ route: MeetingSignalDomainGateRoute = .builtInSpeakerMicrophone,
+ referenceScope: MeetingSignalDomainGateReferenceScope = .selectedApplication,
+ referenceCompletenessMeasured: Bool = true,
+ consentConfirmed: Bool = true,
+ renderCodec: String = "pcm_s16le",
+ captureCodec: String = "pcm_s16le",
+ renderLossless: Bool = true,
+ captureLossless: Bool = true,
+ renderBlocks: [MeetingSignalDomainGateTrackBlock],
+ captureBlocks: [MeetingSignalDomainGateTrackBlock]
+ ) {
self.ordinal = ordinal; self.topology = topology; self.route = route
self.referenceScope = referenceScope; self.referenceCompletenessMeasured = referenceCompletenessMeasured
self.consentConfirmed = consentConfirmed; self.renderCodec = renderCodec; self.captureCodec = captureCodec
@@ -475,11 +530,17 @@ public struct MeetingSignalDomainGateReport: Codable, Equatable, Sendable {
public let transcriptRetained: Bool
public let pathsRetained: Bool
- public init(outcome: MeetingSignalDomainGateOutcome, topology: MeetingSignalDomainGateTopology,
- route: MeetingSignalDomainGateRoute, sessionCount: Int, eligibleSessionCount: Int,
- excludedSessions: [MeetingSignalDomainGateExcludedSession],
- metrics: [MeetingSignalDomainGateSessionMetrics], reasonCounts: [String: Int],
- thresholds: MeetingSignalDomainGateThresholds = .init()) {
+ public init(
+ outcome: MeetingSignalDomainGateOutcome,
+ topology: MeetingSignalDomainGateTopology,
+ route: MeetingSignalDomainGateRoute,
+ sessionCount: Int,
+ eligibleSessionCount: Int,
+ excludedSessions: [MeetingSignalDomainGateExcludedSession],
+ metrics: [MeetingSignalDomainGateSessionMetrics],
+ reasonCounts: [String: Int],
+ thresholds: MeetingSignalDomainGateThresholds = .init()
+ ) {
self.schemaVersion = 1; self.outcome = outcome; self.topology = topology; self.route = route
self.minimumExposureSeconds = thresholds.minimumExposureSeconds
self.maximumIneligibleSessionFraction = thresholds.maximumIneligibleSessionFraction
@@ -528,7 +589,8 @@ public enum MeetingSignalDomainGate {
for component in artifact.relativePath.split(separator: "/") {
cursor.appendPathComponent(String(component))
if FileManager.default.fileExists(atPath: cursor.path),
- (try? FileManager.default.destinationOfSymbolicLink(atPath: cursor.path)) != nil {
+ (try? FileManager.default.destinationOfSymbolicLink(atPath: cursor.path)) != nil
+ {
throw ManifestError.unsafeRelativePath
}
}
@@ -540,12 +602,14 @@ public enum MeetingSignalDomainGate {
guard let hash = try? sha256(of: resolved), hash == artifact.sha256.lowercased() else { throw ManifestError.hashMismatch }
}
if let provenancePath = manifest.provenanceRelativePath, let expected = manifest.provenanceSha256,
- Self.isSafeRelativePath(provenancePath), expected.count == 64 {
+ Self.isSafeRelativePath(provenancePath), expected.count == 64
+ {
var provenanceCursor = canonicalRoot
for component in provenancePath.split(separator: "/") {
provenanceCursor.appendPathComponent(String(component))
if FileManager.default.fileExists(atPath: provenanceCursor.path),
- (try? FileManager.default.destinationOfSymbolicLink(atPath: provenanceCursor.path)) != nil {
+ (try? FileManager.default.destinationOfSymbolicLink(atPath: provenanceCursor.path)) != nil
+ {
throw ManifestError.unsafeRelativePath
}
}
@@ -556,7 +620,8 @@ public enum MeetingSignalDomainGate {
guard url.pathComponents.count > rootComponents.count,
Array(url.pathComponents.prefix(rootComponents.count)) == rootComponents,
FileManager.default.fileExists(atPath: url.path),
- (try? sha256(of: url)) == expected else {
+ (try? self.sha256(of: url)) == expected
+ else {
throw ManifestError.hashMismatch
}
guard let data = try? Data(contentsOf: url),
@@ -588,7 +653,8 @@ public enum MeetingSignalDomainGate {
provenance.renderFrameCount == session.renderTiming.reduce(0, { $0 + $1.frameCount }),
provenance.captureFrameCount == session.captureTiming.reduce(0, { $0 + $1.frameCount }),
provenance.captureConfiguration == "SCStream:48kHz:mono:native-f32le:audio+microphone",
- provenance.route == "builtInSpeakerMicrophone" else {
+ provenance.route == "builtInSpeakerMicrophone"
+ else {
throw ManifestError.invalidManifest
}
}
@@ -643,10 +709,12 @@ public enum MeetingSignalDomainGate {
#endif
}
- public static func evaluate(manifest: MeetingSignalDomainGateManifest,
- sessions: [MeetingSignalDomainGateSession],
- thresholds: MeetingSignalDomainGateThresholds = .init(),
- renderLeadSeconds: Double = 0) -> MeetingSignalDomainGateReport {
+ public static func evaluate(
+ manifest: MeetingSignalDomainGateManifest,
+ sessions: [MeetingSignalDomainGateSession],
+ thresholds: MeetingSignalDomainGateThresholds = .init(),
+ renderLeadSeconds: Double = 0
+ ) -> MeetingSignalDomainGateReport {
var manifestReasons = manifest.validationReasons()
if !manifest.sessions.isEmpty {
let declaredOrdinals = manifest.sessions.map(\.ordinal).sorted()
@@ -661,7 +729,9 @@ public enum MeetingSignalDomainGate {
var metrics: [MeetingSignalDomainGateSessionMetrics] = []
var counts: [String: Int] = [:]
func add(_ reasons: [MeetingSignalDomainGateReason]) {
- for reason in Set(reasons) { counts[reason.rawValue, default: 0] += 1 }
+ for reason in Set(reasons) {
+ counts[reason.rawValue, default: 0] += 1
+ }
}
if !manifestReasons.isEmpty { add(manifestReasons) }
var ordinals = Set<Int>()
@@ -670,7 +740,7 @@ public enum MeetingSignalDomainGate {
let reason: MeetingSignalDomainGateReason = .duplicateOrdinal
excluded.append(.init(ordinal: session.ordinal, reasons: [reason])); add([reason]); continue
}
- let reasons = validate(session: session, thresholds: thresholds, renderLeadSeconds: renderLeadSeconds)
+ let reasons = self.validate(session: session, thresholds: thresholds, renderLeadSeconds: renderLeadSeconds)
if !reasons.isEmpty {
excluded.append(.init(ordinal: session.ordinal, reasons: reasons)); add(reasons); continue
}
@@ -695,7 +765,7 @@ public enum MeetingSignalDomainGate {
.invalidManifest, .missingConsent, .sourceHashMismatch, .invalidTiming,
.duplicateOrdinal, .inconsistentGeometry, .gapDetected, .overlappingBlocks,
.excessiveDrift, .delayNonCausal, .delayOutsideSearchRange, .unstablePath,
- .clipping, .linearPathUnlearnable
+ .clipping, .linearPathUnlearnable,
]
if excluded.contains(where: { !Set($0.reasons).isDisjoint(with: rejectionReasons) }) {
return .rejected
@@ -706,64 +776,86 @@ public enum MeetingSignalDomainGate {
return .proceedToCandidate
}()
if eligible == 0 { counts[MeetingSignalDomainGateReason.noEligibleSessions.rawValue, default: 0] += 1 }
- return .init(outcome: outcome, topology: manifest.topology, route: manifest.route,
- sessionCount: sessions.count, eligibleSessionCount: eligible,
- excludedSessions: excluded, metrics: metrics, reasonCounts: counts, thresholds: thresholds)
+ return .init(
+ outcome: outcome,
+ topology: manifest.topology,
+ route: manifest.route,
+ sessionCount: sessions.count,
+ eligibleSessionCount: eligible,
+ excludedSessions: excluded,
+ metrics: metrics,
+ reasonCounts: counts,
+ thresholds: thresholds
+ )
}
- private static func validate(session: MeetingSignalDomainGateSession,
- thresholds: MeetingSignalDomainGateThresholds,
- renderLeadSeconds: Double) -> [MeetingSignalDomainGateReason] {
+ private static func validate(
+ session: MeetingSignalDomainGateSession,
+ thresholds: MeetingSignalDomainGateThresholds,
+ renderLeadSeconds: Double
+ ) -> [MeetingSignalDomainGateReason] {
var reasons: [MeetingSignalDomainGateReason] = []
if session.topology != .pairedScreenCaptureKit { reasons.append(.unsupportedTopology) }
if session.route != .builtInSpeakerMicrophone { reasons.append(.unsupportedRoute) }
if !session.consentConfirmed { reasons.append(.missingConsent) }
if !session.renderLossless || !session.captureLossless { reasons.append(.nonLossless) }
- for codec in [session.renderCodec.lowercased(), session.captureCodec.lowercased()] where !["pcm_s16le", "pcm_s24le", "pcm_s32le", "pcm_f32le", "lpcm"].contains(codec) { reasons.append(.unsupportedCodec) }
+ for codec in [session.renderCodec.lowercased(), session.captureCodec.lowercased()] where !["pcm_s16le", "pcm_s24le", "pcm_s32le", "pcm_f32le", "lpcm"].contains(codec) {
+ reasons.append(.unsupportedCodec)
+ }
if session.renderBlocks.isEmpty || session.captureBlocks.isEmpty { reasons.append(.metadataOnly) }
if thresholds.requireDeliveryJitter
&& (session.renderBlocks.contains(where: { $0.arrivalSeconds == nil })
- || session.captureBlocks.contains(where: { $0.arrivalSeconds == nil })) {
+ || session.captureBlocks.contains(where: { $0.arrivalSeconds == nil }))
+ {
reasons.append(.missingArrivalMetadata)
}
if thresholds.requireDeliveryJitter
&& (session.renderBlocks.count < thresholds.minimumTimingBlockCount
- || session.captureBlocks.count < thresholds.minimumTimingBlockCount) {
+ || session.captureBlocks.count < thresholds.minimumTimingBlockCount)
+ {
reasons.append(.insufficientTimingObservations)
}
if session.referenceScope == .unknown { reasons.append(.referenceScopeLimited) }
if !session.referenceCompletenessMeasured { reasons.append(.referenceCompletenessUnobservable) }
if renderLeadSeconds > thresholds.maximumRenderLeadSeconds { reasons.append(.invalidTiming) }
let all = session.renderBlocks + session.captureBlocks
- if all.contains(where: { !$0.presentationSeconds.isFinite || !$0.durationSeconds.isFinite || $0.durationSeconds <= 0 || $0.samples.isEmpty || $0.samples.contains(where: { !$0.isFinite }) }) { reasons.append(.invalidTiming) }
+ if all
+ .contains(where: { !$0.presentationSeconds.isFinite || !$0.durationSeconds.isFinite || $0.durationSeconds <= 0 || $0.samples.isEmpty || $0.samples.contains(where: { !$0.isFinite }) })
+ {
+ reasons.append(.invalidTiming)
+ }
if session.renderBlocks.reduce(0, { $0 + $1.samples.count }) > thresholds.maximumPCMSamples
- || session.captureBlocks.reduce(0, { $0 + $1.samples.count }) > thresholds.maximumPCMSamples {
+ || session.captureBlocks.reduce(0, { $0 + $1.samples.count }) > thresholds.maximumPCMSamples
+ {
reasons.append(.analysisResourceLimitExceeded)
}
- if !chronologyIsMonotonic(session.renderBlocks) || !chronologyIsMonotonic(session.captureBlocks) { reasons.append(.invalidTiming) }
+ if !self.chronologyIsMonotonic(session.renderBlocks) || !self.chronologyIsMonotonic(session.captureBlocks) { reasons.append(.invalidTiming) }
// An empty track is metadata-only, not malformed geometry. Keep that case explicitly
// unscored so callers can distinguish absent PCM from a present but inconsistent pair.
let hasBothTracks = !session.renderBlocks.isEmpty && !session.captureBlocks.isEmpty
- if hasBothTracks && (!geometryIsConsistent(session.renderBlocks) || !geometryIsConsistent(session.captureBlocks)) {
+ if hasBothTracks && (!self.geometryIsConsistent(session.renderBlocks) || !self.geometryIsConsistent(session.captureBlocks)) {
reasons.append(.inconsistentGeometry)
}
- let renderContinuity = continuity(of: session.renderBlocks)
- let captureContinuity = continuity(of: session.captureBlocks)
+ let renderContinuity = self.continuity(of: session.renderBlocks)
+ let captureContinuity = self.continuity(of: session.captureBlocks)
if renderContinuity.hasGap || captureContinuity.hasGap { reasons.append(.gapDetected) }
if renderContinuity.hasOverlap || captureContinuity.hasOverlap { reasons.append(.overlappingBlocks) }
if let renderRate = inferredRate(session.renderBlocks), let captureRate = inferredRate(session.captureBlocks),
abs(renderRate - captureRate) > max(1e-6, renderRate * 1e-6) { reasons.append(.inconsistentGeometry) }
if hasBothTracks,
let exposure = [session.renderBlocks, session.captureBlocks].map({ $0.reduce(0) { $0 + $1.durationSeconds } }).min(),
- exposure < thresholds.minimumExposureSeconds {
+ exposure < thresholds.minimumExposureSeconds
+ {
reasons.append(.insufficientCoverage)
}
- return unique(reasons)
+ return self.unique(reasons)
}
- private static func measure(session: MeetingSignalDomainGateSession,
- thresholds: MeetingSignalDomainGateThresholds,
- renderLeadSeconds: Double) -> (metrics: MeetingSignalDomainGateSessionMetrics, reasons: [MeetingSignalDomainGateReason])? {
+ private static func measure(
+ session: MeetingSignalDomainGateSession,
+ thresholds: MeetingSignalDomainGateThresholds,
+ renderLeadSeconds: Double
+ ) -> (metrics: MeetingSignalDomainGateSessionMetrics, reasons: [MeetingSignalDomainGateReason])? {
let render = session.renderBlocks.flatMap(\.samples); let capture = session.captureBlocks.flatMap(\.samples)
guard !render.isEmpty, !capture.isEmpty else { return nil }
let coverage = min(coverage(of: session.renderBlocks), coverage(of: session.captureBlocks))
@@ -771,10 +863,14 @@ public enum MeetingSignalDomainGate {
if coverage < thresholds.minimumValidCoverageFraction { reasons.append(.insufficientCoverage) }
let exposure = min(session.renderBlocks.reduce(0) { $0 + $1.durationSeconds }, session.captureBlocks.reduce(0) { $0 + $1.durationSeconds })
if exposure < thresholds.minimumExposureSeconds { reasons.append(.insufficientCoverage) }
- let sampleRate = inferRate(session.renderBlocks)
+ let sampleRate = self.inferRate(session.renderBlocks)
guard sampleRate.isFinite, sampleRate > 0 else { return nil }
- let delayObservations = delaySamples(render: render, capture: capture, sampleRate: sampleRate,
- maxSeconds: thresholds.maximumSearchDelaySeconds)
+ let delayObservations = self.delaySamples(
+ render: render,
+ capture: capture,
+ sampleRate: sampleRate,
+ maxSeconds: thresholds.maximumSearchDelaySeconds
+ )
guard !delayObservations.isEmpty else { return nil }
let delays = delayObservations.map(\.seconds)
guard let renderOrigin = session.renderBlocks.first?.presentationSeconds,
@@ -784,32 +880,34 @@ public enum MeetingSignalDomainGate {
// origins from silently disappearing into sample zero.
let ptsOriginOffset = captureOrigin - renderOrigin
let signed = delays.map { $0 + ptsOriginOffset + renderLeadSeconds }
- let driftSamples = windowedDriftPPM(delayObservations)
- let drift = percentileOptional(driftSamples, 0.50)
+ let driftSamples = self.windowedDriftPPM(delayObservations)
+ let drift = self.percentileOptional(driftSamples, 0.50)
// Delivery jitter is a within-track property. Do not manufacture a cross-track
// observation by joining the render and capture arrays at an arbitrary boundary.
- let jitter = jitterValues(session.renderBlocks) + jitterValues(session.captureBlocks)
+ let jitter = self.jitterValues(session.renderBlocks) + self.jitterValues(session.captureBlocks)
let medianLagSamples = Int((percentile(delays, 0.50) * sampleRate).rounded())
- let aligned = align(render: render, capture: capture, lag: medianLagSamples)
- let bandMeasurements = bandMeasures(render: aligned.render, capture: aligned.capture, sampleRate: sampleRate)
+ let aligned = self.align(render: render, capture: capture, lag: medianLagSamples)
+ let bandMeasurements = self.bandMeasures(render: aligned.render, capture: aligned.capture, sampleRate: sampleRate)
let coherence = bandMeasurements.coherence
let bandPower = bandMeasurements.power
let rms = sqrt(render.reduce(0) { $0 + Double($1) * Double($1) } / Double(render.count))
let clipping = Double((render + capture).filter { abs($0) >= 0.999 }.count) / Double(render.count + capture.count)
- let firResidual = heldOutLinearResidualFraction(render: aligned.render,
- capture: aligned.capture,
- sampleRate: sampleRate)
- let stability = pathStability(delays)
- let badDelay = percentile(signed, 0.99) > thresholds.maximumSearchDelaySeconds - thresholds.safetyMarginSeconds
- || percentile(signed, 0.01) < -thresholds.safetyMarginSeconds
+ let firResidual = self.heldOutLinearResidualFraction(
+ render: aligned.render,
+ capture: aligned.capture,
+ sampleRate: sampleRate
+ )
+ let stability = self.pathStability(delays)
+ let badDelay = self.percentile(signed, 0.99) > thresholds.maximumSearchDelaySeconds - thresholds.safetyMarginSeconds
+ || self.percentile(signed, 0.01) < -thresholds.safetyMarginSeconds
if delayObservations.count < thresholds.minimumDelayObservationCount { reasons.append(.delayUnresolved) }
if driftSamples.isEmpty { reasons.append(.driftUnscored) }
if driftSamples.contains(where: { abs($0) > thresholds.maximumDriftPPM }) { reasons.append(.excessiveDrift) }
if let firstDelay = delays.first, delays.contains(where: { abs($0 - firstDelay) > thresholds.maximumUncorrectedOffsetSeconds }) { reasons.append(.excessiveDrift) }
if badDelay {
- if percentile(signed, 0.01) < -thresholds.safetyMarginSeconds {
+ if self.percentile(signed, 0.01) < -thresholds.safetyMarginSeconds {
reasons.append(.delayNonCausal)
- } else if percentile(signed, 0.99) > thresholds.maximumSearchDelaySeconds - thresholds.safetyMarginSeconds {
+ } else if self.percentile(signed, 0.99) > thresholds.maximumSearchDelaySeconds - thresholds.safetyMarginSeconds {
reasons.append(.delayOutsideSearchRange)
}
}
@@ -822,8 +920,28 @@ public enum MeetingSignalDomainGate {
reasons.append(.linearPathUnscored)
}
if (stability ?? 0) < thresholds.minimumPathStabilityFraction { reasons.append(.unstablePath) }
- let value = MeetingSignalDomainGateSessionMetrics(sessionOrdinal: session.ordinal, exposureSeconds: exposure, validCoverageFraction: coverage, deliveryJitterP50Seconds: percentileOptional(jitter, 0.50), deliveryJitterP95Seconds: percentileOptional(jitter, 0.95), deliveryJitterP99Seconds: percentileOptional(jitter, 0.99), driftPPM: drift, driftP50PPM: percentileOptional(driftSamples, 0.50), driftP95PPM: percentileOptional(driftSamples, 0.95), driftP99PPM: percentileOptional(driftSamples, 0.99), signedDelayP50Seconds: percentileOptional(signed, 0.50), signedDelayP95Seconds: percentileOptional(signed, 0.95), signedDelayP99Seconds: percentileOptional(signed, 0.99), bandCoherence: coherence, bandPower: bandPower, pathStabilityFraction: stability, clippingFraction: clipping, heldOutLinearResidualFraction: firResidual, delayObservationCount: delayObservations.count)
- return (value, unique(reasons))
+ let value = MeetingSignalDomainGateSessionMetrics(
+ sessionOrdinal: session.ordinal,
+ exposureSeconds: exposure,
+ validCoverageFraction: coverage,
+ deliveryJitterP50Seconds: self.percentileOptional(jitter, 0.50),
+ deliveryJitterP95Seconds: self.percentileOptional(jitter, 0.95),
+ deliveryJitterP99Seconds: self.percentileOptional(jitter, 0.99),
+ driftPPM: drift,
+ driftP50PPM: self.percentileOptional(driftSamples, 0.50),
+ driftP95PPM: self.percentileOptional(driftSamples, 0.95),
+ driftP99PPM: self.percentileOptional(driftSamples, 0.99),
+ signedDelayP50Seconds: self.percentileOptional(signed, 0.50),
+ signedDelayP95Seconds: self.percentileOptional(signed, 0.95),
+ signedDelayP99Seconds: self.percentileOptional(signed, 0.99),
+ bandCoherence: coherence,
+ bandPower: bandPower,
+ pathStabilityFraction: stability,
+ clippingFraction: clipping,
+ heldOutLinearResidualFraction: firResidual,
+ delayObservationCount: delayObservations.count
+ )
+ return (value, self.unique(reasons))
}
private static func coverage(of blocks: [MeetingSignalDomainGateTrackBlock]) -> Double {
@@ -833,10 +951,11 @@ public enum MeetingSignalDomainGate {
guard span > 0 else { return 0 }
return min(1, blocks.reduce(0) { $0 + $1.durationSeconds } / span)
}
+
private static func chronologyIsMonotonic(_ blocks: [MeetingSignalDomainGateTrackBlock]) -> Bool {
- guard blocks.allSatisfy({ $0.arrivalSeconds == nil || $0.arrivalSeconds!.isFinite }) else { return false }
+ guard blocks.allSatisfy({ $0.arrivalSeconds.map(\.isFinite) ?? true }) else { return false }
for pair in zip(blocks.dropFirst(), blocks) {
- let rate = inferredRate(blocks) ?? 1
+ let rate = self.inferredRate(blocks) ?? 1
let tolerance = max(1e-9, 1 / rate)
if pair.0.presentationSeconds - pair.1.presentationSeconds < -tolerance { return false }
if let currentArrival = pair.0.arrivalSeconds, let previousArrival = pair.1.arrivalSeconds,
@@ -844,6 +963,7 @@ public enum MeetingSignalDomainGate {
}
return true
}
+
private struct BlockContinuityFlags { var hasGap = false; var hasOverlap = false }
private static func continuity(of blocks: [MeetingSignalDomainGateTrackBlock]) -> BlockContinuityFlags {
var flags = BlockContinuityFlags()
@@ -855,11 +975,13 @@ public enum MeetingSignalDomainGate {
}
return flags
}
+
private static func inferredRate(_ blocks: [MeetingSignalDomainGateTrackBlock]) -> Double? {
guard let first = blocks.first, first.durationSeconds > 0 else { return nil }
let rate = Double(first.samples.count) / first.durationSeconds
return rate.isFinite && rate > 0 ? rate : nil
}
+
private static func geometryIsConsistent(_ blocks: [MeetingSignalDomainGateTrackBlock]) -> Bool {
guard let expected = inferredRate(blocks) else { return false }
return blocks.allSatisfy { block in
@@ -868,22 +990,27 @@ public enum MeetingSignalDomainGate {
return rate.isFinite && abs(rate - expected) <= max(1e-6, expected * 1e-6)
}
}
+
private static func inferRate(_ blocks: [MeetingSignalDomainGateTrackBlock]) -> Double {
- inferredRate(blocks) ?? .nan
+ self.inferredRate(blocks) ?? .nan
}
+
private static func jitterValues(_ blocks: [MeetingSignalDomainGateTrackBlock]) -> [Double] {
guard blocks.count > 1 else { return [] }; var values: [Double] = []
- for pair in zip(blocks.dropFirst(), blocks) { if let a = pair.0.arrivalSeconds, let b = pair.1.arrivalSeconds, a.isFinite, b.isFinite { values.append(abs((a - b) - pair.1.durationSeconds)) } }
+ for pair in zip(blocks.dropFirst(), blocks) {
+ if let a = pair.0.arrivalSeconds, let b = pair.1.arrivalSeconds, a.isFinite, b.isFinite { values.append(abs((a - b) - pair.1.durationSeconds)) }
+ }
return values
}
+
private static func delaySamples(render: [Float], capture: [Float], sampleRate: Double, maxSeconds: Double) -> [(time: Double, seconds: Double)] {
// Use anti-aliased 1 kHz windows distributed across the complete bounded exposure.
// Decimation depends on source rate, not recording length, so longer recordings retain
// the same delay resolution instead of becoming progressively less measurable.
let n = min(render.count, capture.count); guard n > 8 else { return [] }
- let decimation = max(1, Int(floor(sampleRate / 1_000)))
- let reducedRender = antiAliasedDownsample(Array(render.prefix(n)), factor: decimation)
- let reducedCapture = antiAliasedDownsample(Array(capture.prefix(n)), factor: decimation)
+ let decimation = max(1, Int(floor(sampleRate / 1000)))
+ let reducedRender = self.antiAliasedDownsample(Array(render.prefix(n)), factor: decimation)
+ let reducedCapture = self.antiAliasedDownsample(Array(capture.prefix(n)), factor: decimation)
let reducedRate = sampleRate / Double(decimation)
let maxLag = Int(ceil(maxSeconds * reducedRate))
let window = max(256, maxLag * 2 + 64, Int(ceil(0.5 * reducedRate)))
@@ -905,11 +1032,11 @@ public enum MeetingSignalDomainGate {
let centeredCapture = captureWindow.map { Double($0) - captureMean }
let lower: Int
let upper: Int
- if priorLag == nil || ordinal.isMultiple(of: 4) {
- lower = -maxLag; upper = maxLag
+ if let priorLag, !ordinal.isMultiple(of: 4) {
+ lower = max(-maxLag, priorLag - localRadius)
+ upper = min(maxLag, priorLag + localRadius)
} else {
- lower = max(-maxLag, priorLag! - localRadius)
- upper = min(maxLag, priorLag! + localRadius)
+ lower = -maxLag; upper = maxLag
}
var bestLag = 0; var best = -Double.infinity
for lag in lower...upper {
@@ -924,7 +1051,7 @@ public enum MeetingSignalDomainGate {
let score = er > 0 && ec > 0 ? abs(dot / sqrt(er * ec)) : -Double.infinity
if score > best { best = score; bestLag = lag }
}
- if best.isFinite && best > 0.05 {
+ if best.isFinite, best > 0.05 {
result.append((Double(start + window / 2) / reducedRate, Double(bestLag) / reducedRate))
priorLag = bestLag
}
@@ -957,6 +1084,7 @@ public enum MeetingSignalDomainGate {
let offset = min(-lag, n - 1)
return (Array(render[offset..<n]), Array(capture[..<(n - offset)]))
}
+
private static func windowedDriftPPM(_ observations: [(time: Double, seconds: Double)]) -> [Double] {
guard observations.count > 1 else { return [] }
return zip(observations.dropFirst(), observations).compactMap { current, previous in
@@ -965,10 +1093,11 @@ public enum MeetingSignalDomainGate {
return (current.seconds - previous.seconds) / dt * 1_000_000
}
}
+
private static func bandMeasures(render: [Float], capture: [Float], sampleRate: Double) -> (coherence: [Double], power: [Double]) {
let n = min(render.count, capture.count); guard n > 4 else { return ([0, 0, 0], [0, 0, 0]) }
- let window = 4_096
- let bands: [[Double]] = [[250, 500], [750, 1_000, 1_500], [2_500, 4_000, 6_000]]
+ let window = 4096
+ let bands: [[Double]] = [[250, 500], [750, 1000, 1500], [2500, 4000, 6000]]
return bands.map { frequencies in
var frequencyCoherences: [Double] = [], frequencyPowers: [Double] = []
for frequency in frequencies where frequency < sampleRate / 2 {
@@ -1000,20 +1129,26 @@ public enum MeetingSignalDomainGate {
frequencyPowers.append(renderPower / Double(max(1, n * n)))
}
}
- return (frequencyCoherences.isEmpty ? 0 : frequencyCoherences.reduce(0, +) / Double(frequencyCoherences.count),
- frequencyPowers.isEmpty ? 0 : frequencyPowers.reduce(0, +) / Double(frequencyPowers.count))
+ return (
+ frequencyCoherences.isEmpty ? 0 : frequencyCoherences.reduce(0, +) / Double(frequencyCoherences.count),
+ frequencyPowers.isEmpty ? 0 : frequencyPowers.reduce(0, +) / Double(frequencyPowers.count)
+ )
}.reduce(into: ([Double](), [Double]())) { result, value in result.0.append(value.0); result.1.append(value.1) }
}
+
/// Fits a bounded 64 ms NLMS path on an early window and scores a disjoint late window.
/// A high residual means this bounded linear model did not generalize; it does not prove
/// nonlinear preprocessing. Work is bounded at a 4 kHz analysis rate and 256 taps.
- private static func heldOutLinearResidualFraction(render: [Float], capture: [Float],
- sampleRate: Double) -> Double? {
+ private static func heldOutLinearResidualFraction(
+ render: [Float],
+ capture: [Float],
+ sampleRate: Double
+ ) -> Double? {
let sourceCount = min(render.count, capture.count)
guard sourceCount >= 512, sampleRate.isFinite, sampleRate > 0 else { return nil }
- let factor = max(1, Int(floor(sampleRate / 4_000)))
- let x = antiAliasedDownsample(Array(render.prefix(sourceCount)), factor: factor)
- let y = antiAliasedDownsample(Array(capture.prefix(sourceCount)), factor: factor)
+ let factor = max(1, Int(floor(sampleRate / 4000)))
+ let x = self.antiAliasedDownsample(Array(render.prefix(sourceCount)), factor: factor)
+ let y = self.antiAliasedDownsample(Array(capture.prefix(sourceCount)), factor: factor)
let reducedRate = sampleRate / Double(factor)
let tapCount = min(256, max(16, Int(ceil(0.064 * reducedRate))))
let count = min(x.count, y.count), split = count * 3 / 4
@@ -1027,23 +1162,39 @@ public enum MeetingSignalDomainGate {
prediction += coefficients[tap] * value; norm += value * value
}
let scale = 0.5 * (Double(y[index]) - prediction) / norm
- for tap in 0..<tapCount { coefficients[tap] += scale * Double(x[index - tap]) }
+ for tap in 0..<tapCount {
+ coefficients[tap] += scale * Double(x[index - tap])
+ }
}
let testStart = max(split, count - Int(4 * reducedRate))
var errorEnergy = 0.0, targetEnergy = 0.0, observations = 0
for index in max(testStart, tapCount - 1)..<count {
var prediction = 0.0
- for tap in 0..<tapCount { prediction += coefficients[tap] * Double(x[index - tap]) }
+ for tap in 0..<tapCount {
+ prediction += coefficients[tap] * Double(x[index - tap])
+ }
let target = Double(y[index]), error = target - prediction
errorEnergy += error * error; targetEnergy += target * target; observations += 1
}
guard observations > 64, targetEnergy > 1e-12 else { return nil }
return min(1, max(0, errorEnergy / targetEnergy))
}
- private static func pathStability(_ values: [Double]) -> Double? { guard !values.isEmpty else { return nil }; let median = percentile(values, 0.5); let tolerance = max(1e-4, abs(median) * 0.10); return Double(values.filter { abs($0 - median) <= tolerance }.count) / Double(values.count) }
- private static func percentile(_ values: [Double], _ p: Double) -> Double { let sorted = values.sorted(); guard let first = sorted.first else { return .nan }; if sorted.count == 1 { return first }; let index = min(Double(sorted.count - 1), max(0, p * Double(sorted.count - 1))); let low = Int(index.rounded(.down)); let high = Int(index.rounded(.up)); return sorted[low] + (sorted[high] - sorted[low]) * (index - Double(low)) }
- private static func percentileOptional(_ values: [Double], _ p: Double) -> Double? { values.isEmpty ? nil : percentile(values, p) }
- private static func unique(_ reasons: [MeetingSignalDomainGateReason]) -> [MeetingSignalDomainGateReason] { var seen = Set<MeetingSignalDomainGateReason>(); return reasons.filter { seen.insert($0).inserted } }
+
+ private static func pathStability(_ values: [Double]) -> Double? { guard !values.isEmpty else { return nil }; let median = self.percentile(values, 0.5); let tolerance = max(
+ 1e-4,
+ abs(median) * 0.10
+ ); return Double(values.filter { abs($0 - median) <= tolerance }.count) / Double(values.count) }
+ private static func percentile(_ values: [Double], _ p: Double) -> Double { let sorted = values.sorted(); guard let first = sorted.first
+ else { return .nan }; if sorted.count == 1 { return first }; let index = min(
+ Double(sorted.count - 1),
+ max(0, p * Double(sorted.count - 1))
+ ); let low = Int(index.rounded(.down)); let high = Int(index.rounded(.up)); return sorted[low] + (sorted[high] - sorted[low]) * (index - Double(low))
+ }
+
+ private static func percentileOptional(_ values: [Double], _ p: Double) -> Double? { values.isEmpty ? nil : self.percentile(values, p) }
+ private static func unique(_ reasons: [MeetingSignalDomainGateReason]) -> [MeetingSignalDomainGateReason] { var seen = Set<MeetingSignalDomainGateReason>(); return reasons
+ .filter { seen.insert($0).inserted }
+ }
}
/// Executable representation of the single-owner delay rule. A future engine wrapper can adopt
@@ -1055,23 +1206,27 @@ public struct MeetingAECDelayContract: Codable, Equatable, Sendable {
public let adaptiveDelayOwner: String
public let renderBeforeCapture: Bool
- public init(renderLeadSeconds: Double, boundedEngineHintSeconds: Double? = nil,
- adaptiveDelayOwner: String = "candidateEngine", renderBeforeCapture: Bool = true) {
+ public init(
+ renderLeadSeconds: Double,
+ boundedEngineHintSeconds: Double? = nil,
+ adaptiveDelayOwner: String = "candidateEngine",
+ renderBeforeCapture: Bool = true
+ ) {
self.renderLeadSeconds = renderLeadSeconds; self.boundedEngineHintSeconds = boundedEngineHintSeconds
self.adaptiveDelayOwner = adaptiveDelayOwner; self.renderBeforeCapture = renderBeforeCapture
}
public var isValid: Bool {
- renderLeadSeconds.isFinite && renderLeadSeconds >= 0 && renderLeadSeconds <= 0.100
- && (boundedEngineHintSeconds == nil || (boundedEngineHintSeconds!.isFinite && boundedEngineHintSeconds! >= 0 && boundedEngineHintSeconds! <= 0.500))
- && adaptiveDelayOwner == "candidateEngine" && renderBeforeCapture
+ self.renderLeadSeconds.isFinite && self.renderLeadSeconds >= 0 && self.renderLeadSeconds <= 0.100
+ && (self.boundedEngineHintSeconds.map { $0.isFinite && $0 >= 0 && $0 <= 0.500 } ?? true)
+ && self.adaptiveDelayOwner == "candidateEngine" && self.renderBeforeCapture
}
/// Checks the ordering invariant a future adapter must prove in an executable test. There
/// must be exactly one render and one capture event per frame, with render first; a
/// synchronizer or caller cannot become a second adaptive delay owner.
public func validates(events: [MeetingAECDelayContractEvent]) -> Bool {
- guard isValid, !events.isEmpty else { return false }
+ guard self.isValid, !events.isEmpty else { return false }
let ordered = events.sorted { $0.frameIndex == $1.frameIndex ? $0.kind == .render && $1.kind == .capture : $0.frameIndex < $1.frameIndex }
guard ordered == events else { return false }
var byFrame: [Int: [MeetingAECDelayContractEventKind]] = [:]
@@ -1089,7 +1244,7 @@ public struct MeetingAECDelayContract: Codable, Equatable, Sendable {
/// equal masks/geometry, and a nonnegative frozen lead. The synchronizer remains the sole
/// owner of clock/epoch mapping; adaptive acoustic delay is still reserved for the candidate.
public func validates(synchronizedResult: MeetingSynchronizationResult) -> Bool {
- guard isValid, !synchronizedResult.frames.isEmpty else { return false }
+ guard self.isValid, !synchronizedResult.frames.isEmpty else { return false }
var previousEpoch = 0
for (expectedIndex, frame) in synchronizedResult.frames.enumerated() {
guard frame.index == expectedIndex, frame.epochID >= previousEpoch,
diff --git a/Sources/Fluid/Services/Meeting/MeetingSpeechActivityDetector.swift b/Sources/Fluid/Services/Meeting/MeetingSpeechActivityDetector.swift
index 0bf896ba..4a6c0ce1 100644
--- a/Sources/Fluid/Services/Meeting/MeetingSpeechActivityDetector.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingSpeechActivityDetector.swift
@@ -1,5 +1,5 @@
-import Foundation
import CoreML
+import Foundation
/// Synchronous, single-owner offline seam. Implementations retain only one recurrent state.
nonisolated protocol MeetingSpeechActivityFrameModel {
@@ -19,33 +19,39 @@ nonisolated struct MeetingLocalSileroActivityModel: MeetingSpeechActivityFrameMo
init(modelURL: URL) throws {
let configuration = MLModelConfiguration()
configuration.computeUnits = .cpuOnly
- model = try MLModel(contentsOf: modelURL, configuration: configuration)
+ self.model = try MLModel(contentsOf: modelURL, configuration: configuration)
func matches(_ descriptions: [String: MLFeatureDescription], _ shapes: [String: [Int]]) -> Bool {
Set(descriptions.keys) == Set(shapes.keys) && shapes.allSatisfy { key, shape in
guard let constraint = descriptions[key]?.multiArrayConstraint else { return false }
return constraint.dataType == .float32 && constraint.shape.map(\.intValue) == shape
}
}
- guard matches(model.modelDescription.inputDescriptionsByName,
- ["audio_input": [1, 4160], "hidden_state": [1, 128], "cell_state": [1, 128]]),
- matches(model.modelDescription.outputDescriptionsByName,
- ["vad_output": [1, 1, 1], "new_hidden_state": [1, 128], "new_cell_state": [1, 128]])
+ guard matches(
+ self.model.modelDescription.inputDescriptionsByName,
+ ["audio_input": [1, 4160], "hidden_state": [1, 128], "cell_state": [1, 128]]
+ ),
+ matches(
+ self.model.modelDescription.outputDescriptionsByName,
+ ["vad_output": [1, 1, 1], "new_hidden_state": [1, 128], "new_cell_state": [1, 128]]
+ )
else { throw Failure.schema }
}
mutating func probability(samples: [Float], reset: Bool) throws -> Float {
guard samples.count == 4096, samples.allSatisfy(\.isFinite) else { throw Failure.input }
if reset {
- context = [Float](repeating: 0, count: 64)
- hidden = [Float](repeating: 0, count: 128); cell = hidden
+ self.context = [Float](repeating: 0, count: 64)
+ self.hidden = [Float](repeating: 0, count: 128); self.cell = self.hidden
}
func array(_ values: [Float]) throws -> MLMultiArray {
let array = try MLMultiArray(shape: [1, NSNumber(value: values.count)], dataType: .float32)
- for i in values.indices { array[i] = NSNumber(value: values[i]) }
+ for i in values.indices {
+ array[i] = NSNumber(value: values[i])
+ }
return array
}
let features = try MLDictionaryFeatureProvider(dictionary: [
- "audio_input": array(context + samples), "hidden_state": array(hidden), "cell_state": array(cell)
+ "audio_input": array(context + samples), "hidden_state": array(self.hidden), "cell_state": array(self.cell),
])
let output = try model.prediction(from: features)
func values(_ name: String, count: Int) throws -> [Float] {
@@ -59,7 +65,7 @@ nonisolated struct MeetingLocalSileroActivityModel: MeetingSpeechActivityFrameMo
guard (0...1).contains(p) else { throw Failure.output }
let nextHidden = try values("new_hidden_state", count: 128)
let nextCell = try values("new_cell_state", count: 128)
- hidden = nextHidden; cell = nextCell; context = Array(samples.suffix(64))
+ self.hidden = nextHidden; self.cell = nextCell; self.context = Array(samples.suffix(64))
return p
}
}
@@ -73,8 +79,9 @@ nonisolated struct MeetingSpeechActivityDetector<Model: MeetingSpeechActivityFra
let probability: Float?
let unknown: Unknown?
/// Window-level activity only; not a voiced-duration annotation or near-end decision.
- var active: Bool? { probability.map { $0 >= 0.85 } }
+ var active: Bool? { self.probability.map { $0 >= 0.85 } }
}
+
private var model: Model
private var lastEnd: Double?
private var scope: String?
@@ -85,42 +92,51 @@ nonisolated struct MeetingSpeechActivityDetector<Model: MeetingSpeechActivityFra
init(model: Model, clock: @escaping () -> Double = { ProcessInfo.processInfo.systemUptime }) {
self.model = model; self.clock = clock
}
+
/// Caller supplies exactly 4096 real 16kHz samples and validity flags. No tail padding.
/// A first frame after reset is model warmup and intentionally unmeasured in the sidecar.
/// One prediction cannot be preempted; budget/cancellation are checked before AND after it.
- mutating func process(samples: [Float], valid: [Bool], start: Double, session: UUID,
- epoch: UInt64, route: String, cancelled: () -> Bool = { false }) -> Frame {
- if sessionID != session { failures = 0; needsReset = true }
- sessionID = session
+ mutating func process(
+ samples: [Float],
+ valid: [Bool],
+ start: Double,
+ session: UUID,
+ epoch: UInt64,
+ route: String,
+ cancelled: () -> Bool = { false }
+ ) -> Frame {
+ if self.sessionID != session { self.failures = 0; self.needsReset = true }
+ self.sessionID = session
func unknown(_ reason: Frame.Unknown) -> Frame {
Frame(start: start.isFinite ? start : 0, epoch: epoch, probability: nil, unknown: reason)
}
guard start.isFinite, start >= 0, !route.isEmpty,
samples.count == 4096, valid.count == samples.count,
- samples.allSatisfy(\.isFinite) else {
- needsReset = true; if failures < 3 { failures = 0 }; return unknown(.invalidInput)
+ samples.allSatisfy(\.isFinite)
+ else {
+ self.needsReset = true; if self.failures < 3 { self.failures = 0 }; return unknown(.invalidInput)
}
let nextScope = "\(session):\(epoch):\(route)"
- if scope != nextScope || lastEnd.map({ abs($0 - start) > 1.0 / 32_000 }) != false { needsReset = true }
- scope = nextScope; lastEnd = start + 0.256
- guard !cancelled() else { needsReset = true; if failures < 3 { failures = 0 }; return unknown(.cancelled) }
- guard failures < 3 else { needsReset = true; return unknown(.disabled) }
- guard valid.allSatisfy({ $0 }) else { needsReset = true; failures = 0; return unknown(.unscoredCoverage) }
- let reset = needsReset, began = clock()
+ if self.scope != nextScope || self.lastEnd.map({ abs($0 - start) > 1.0 / 32_000 }) != false { self.needsReset = true }
+ self.scope = nextScope; self.lastEnd = start + 0.256
+ guard !cancelled() else { self.needsReset = true; if self.failures < 3 { self.failures = 0 }; return unknown(.cancelled) }
+ guard self.failures < 3 else { self.needsReset = true; return unknown(.disabled) }
+ guard valid.allSatisfy({ $0 }) else { self.needsReset = true; self.failures = 0; return unknown(.unscoredCoverage) }
+ let reset = self.needsReset, began = self.clock()
do {
let probability = try model.probability(samples: samples, reset: reset)
- guard !cancelled() else { needsReset = true; failures = 0; return unknown(.cancelled) }
- guard clock() - began <= 0.1 else {
- failures += 1; needsReset = true; return unknown(.overBudget)
+ guard !cancelled() else { self.needsReset = true; self.failures = 0; return unknown(.cancelled) }
+ guard self.clock() - began <= 0.1 else {
+ self.failures += 1; self.needsReset = true; return unknown(.overBudget)
}
guard probability.isFinite, (0...1).contains(probability) else {
- failures += 1; needsReset = true; return unknown(.modelFailure)
+ self.failures += 1; self.needsReset = true; return unknown(.modelFailure)
}
- failures = 0; needsReset = false
+ self.failures = 0; self.needsReset = false
if reset { return unknown(.contextWarmup) }
return Frame(start: start, epoch: epoch, probability: probability, unknown: nil)
} catch {
- failures += 1; needsReset = true; return unknown(.modelFailure)
+ self.failures += 1; self.needsReset = true; return unknown(.modelFailure)
}
}
}
@@ -133,6 +149,7 @@ nonisolated enum MeetingSpeechPlaybackShadowPolicy {
case missingSpeechEvidence, mixedOrLeakedActivity, activityWithoutReliablePlaybackMatch
case duplicateWithoutDetectedActivity, negativeActivityIsNotAbsence
}
+
static func reason(activity: Bool?, reliableDuplicate: Bool) -> Reason {
guard let activity else { return .missingSpeechEvidence }
if activity { return reliableDuplicate ? .mixedOrLeakedActivity : .activityWithoutReliablePlaybackMatch }
@@ -142,8 +159,11 @@ nonisolated enum MeetingSpeechPlaybackShadowPolicy {
/// Join by interval overlap, not a single enclosing 2s window: 256ms frames often straddle
/// that grid. All overlapping evidence must cover the frame in the same epoch. Mixed
/// windows stay explicit and never borrow a sibling's supported state.
- static func temporalContext(start: Double, epoch: UInt64,
- windows: [MeetingPlaybackDuplicateDetector.Result]) -> TemporalContext {
+ static func temporalContext(
+ start: Double,
+ epoch: UInt64,
+ windows: [MeetingPlaybackDuplicateDetector.Result]
+ ) -> TemporalContext {
guard start.isFinite, start >= 0 else { return .unavailable }
let end = start + 0.256
let overlapping = windows.filter { $0.end > start && $0.start < end }.sorted { $0.start < $1.start }
diff --git a/Sources/Fluid/Services/Meeting/MeetingStage05EvidenceAutorun.swift b/Sources/Fluid/Services/Meeting/MeetingStage05EvidenceAutorun.swift
index f4e72934..162dcb46 100644
--- a/Sources/Fluid/Services/Meeting/MeetingStage05EvidenceAutorun.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingStage05EvidenceAutorun.swift
@@ -78,7 +78,8 @@ nonisolated enum MeetingStage05StimulusHandshake {
if let playing = controlledPlaying.first {
guard playing.windowID == ready.windowID else { return .failure(.ambiguous) }
guard let remaining = Self.playingRemainingSeconds(playing.title),
- remaining >= Double(Self.minimumRemainingSeconds) else {
+ remaining >= Double(Self.minimumRemainingSeconds)
+ else {
return .failure(.remainingInsufficient)
}
return .success(playing)
@@ -126,6 +127,8 @@ nonisolated struct MeetingStage05LiveAdapterSummary: Codable, Equatable, Sendabl
let synchronizerDroppedFrameCount: Int
let synchronizerDuplicateOrLateFrameCount: Int
let synchronizerNonFiniteSampleCount: Int
+ // Keep the descriptive diagnostic contract name consistent with its persisted field.
+ // swiftlint:disable:next identifier_name
let synchronizerSynthesizedMicrophoneFrameCount: Int
let synchronizerBoundedResourceFailure: Bool
let referenceClockDriftPresent: Bool
@@ -146,18 +149,18 @@ nonisolated struct MeetingStage05LiveAdapterSummary: Codable, Equatable, Sendabl
synchronization: MeetingSynchronizationResult,
seam: MeetingStage05MockAECSeamResult
) -> Self {
- let renderSamples = boundedSum(synchronization.frames.map { $0.renderSamples.count })
- let renderValid = boundedSum(synchronization.frames.map {
+ let renderSamples = self.boundedSum(synchronization.frames.map { $0.renderSamples.count })
+ let renderValid = self.boundedSum(synchronization.frames.map {
$0.renderValidMask.lazy.filter { $0 }.count
})
- let captureSamples = boundedSum(synchronization.frames.map { $0.captureSamples.count })
- let captureValid = boundedSum(synchronization.frames.map {
+ let captureSamples = self.boundedSum(synchronization.frames.map { $0.captureSamples.count })
+ let captureValid = self.boundedSum(synchronization.frames.map {
$0.captureValidMask.lazy.filter { $0 }.count
})
let drift = synchronization.diagnostics.referenceClockDriftPPM.flatMap {
$0.isFinite ? $0 : nil
}
- let orderingValid = eventsAreRenderBeforeCapture(seam)
+ let orderingValid = self.eventsAreRenderBeforeCapture(seam)
let render = drain.renderDiagnostics
let capture = drain.microphoneDiagnostics
let cleanCallbacks = [
@@ -219,7 +222,8 @@ nonisolated struct MeetingStage05LiveAdapterSummary: Codable, Equatable, Sendabl
mockFrozenFrameCount: seam.frozenFrameCount,
mockBoundaryCount: seam.boundaryCount,
renderBeforeCaptureValid: orderingValid,
- eligibleForAECTrial: eligible)
+ eligibleForAECTrial: eligible
+ )
}
var structurallyValid: Bool {
@@ -260,11 +264,13 @@ nonisolated struct MeetingStage05LiveAdapterSummary: Codable, Equatable, Sendabl
|| self.mockBoundaryCount > self.synchronizerOutputFrameCount
|| mockClassifiedOverflow
|| (self.mockAuthorized
- && mockClassifiedCount != self.synchronizerOutputFrameCount) {
+ && mockClassifiedCount != self.synchronizerOutputFrameCount)
+ {
reasons.append("relationships")
}
if !self.referenceClockDriftPPM.isFinite
- || (!self.referenceClockDriftPresent && self.referenceClockDriftPPM != 0) {
+ || (!self.referenceClockDriftPresent && self.referenceClockDriftPPM != 0)
+ {
reasons.append("drift")
}
if self.eligibleForAECTrial != self.derivedEligibility() {
@@ -368,16 +374,16 @@ nonisolated enum MeetingStage05EvidenceAutorun {
}
static func operatorMediaRequested(environment: [String: String]) -> Bool {
- environment[Self.operatorMediaConsentEnvironmentKey] == Self.operatorMediaConsentToken
+ environment[self.operatorMediaConsentEnvironmentKey] == self.operatorMediaConsentToken
}
static func autorunEnabled(environment: [String: String] = ProcessInfo.processInfo.environment) -> Bool {
self.requested(environment: environment)
- && environment[Self.autorunEnvironmentKey] == "1"
+ && environment[self.autorunEnvironmentKey] == "1"
}
static func consentConfirmed(environment: [String: String]) -> Bool {
- environment[Self.consentEnvironmentKey] == Self.consentToken
+ environment[self.consentEnvironmentKey] == self.consentToken
}
static func encodedOutcome(
@@ -392,9 +398,13 @@ nonisolated enum MeetingStage05EvidenceAutorun {
encoder.outputFormatting = [.sortedKeys]
guard validStatus, adapter?.validationReasons().isEmpty ?? true,
let data = try? encoder.encode(MeetingStage05AutorunOutcome(
- exitStatus: exitStatus, status: status, reason: reason, adapter: adapter)) else {
+ exitStatus: exitStatus, status: status, reason: reason, adapter: adapter
+ ))
+ else {
return "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"outcome\"}"
}
+ // Diagnostic JSON is emitted as UTF-8; decoding keeps the report output nonoptional.
+ // swiftlint:disable:next optional_data_string_conversion
return String(decoding: data, as: UTF8.self)
}
@@ -439,11 +449,13 @@ nonisolated enum MeetingStage05EvidenceAutorun {
return "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"consent\"}"
}
guard CGPreflightScreenCaptureAccess(),
- AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else {
+ AVCaptureDevice.authorizationStatus(for: .audio) == .authorized
+ else {
return "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"permission\"}"
}
- guard let rootString = environment[Self.rootEnvironmentKey],
- rootString.hasPrefix("/"), !rootString.isEmpty else {
+ guard let rootString = environment[rootEnvironmentKey],
+ rootString.hasPrefix("/"), !rootString.isEmpty
+ else {
return "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"root\"}"
}
let operatorMedia = Self.operatorMediaRequested(environment: environment)
@@ -452,11 +464,13 @@ nonisolated enum MeetingStage05EvidenceAutorun {
guard let fixtureString = environment[Self.fixturePathEnvironmentKey],
fixtureString.hasPrefix("/"),
let fixtureURL = Self.absoluteRegularFile(URL(fileURLWithPath: fixtureString)),
- (try? SHA256Hex.file(fixtureURL)) == expectedFixtureSHA256 else {
+ (try? SHA256Hex.file(fixtureURL)) == expectedFixtureSHA256
+ else {
return "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"fixture\"}"
}
guard let target = environment[Self.targetBundleIDEnvironmentKey],
- target == Self.requiredTargetBundleID else {
+ target == Self.requiredTargetBundleID
+ else {
return "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"target\"}"
}
guard let input = AudioDevice.getDefaultInputDevice(), input.id != kAudioObjectUnknown, input.isAlive,
@@ -466,7 +480,8 @@ nonisolated enum MeetingStage05EvidenceAutorun {
output.isBuiltIn, !AudioDevice.outputDataSourceIsHeadphones(output.id),
let initialVolume = Self.readOutputVolume(output.id), initialVolume > 0, initialVolume <= 0.25,
MeetingCapturePathDecider.outputRouteDeclineReason(
- MeetingCaptureEngine.currentOutputRouteSnapshot()) == nil else {
+ MeetingCaptureEngine.currentOutputRouteSnapshot()) == nil
+ else {
return "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"route\"}"
}
@@ -487,21 +502,25 @@ nonisolated enum MeetingStage05EvidenceAutorun {
owningProcessID: owner.processID,
frameWidth: window.frame.width,
frameHeight: window.frame.height,
- targetBundleIdentifier: target)
+ targetBundleIdentifier: target
+ )
}
guard eligibleWindows.count == 1,
let source = eligibleWindows.first,
- let owner = source.owningApplication else {
+ let owner = source.owningApplication
+ else {
return "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"stimulusReady\",\"eligibleWindowCount\":\(eligibleWindows.count)}"
}
readyWindow = .init(
windowID: source.windowID,
owningBundleIdentifier: owner.bundleIdentifier,
owningProcessID: owner.processID,
- title: source.title)
+ title: source.title
+ )
} else {
guard let selected = MeetingStage05StimulusHandshake.selectReadyWindow(
- from: windows, targetBundleIdentifier: target) else {
+ from: windows, targetBundleIdentifier: target
+ ) else {
return "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"stimulusReady\"}"
}
readyWindow = selected
@@ -533,19 +552,20 @@ nonisolated enum MeetingStage05EvidenceAutorun {
}
let selectedContent = selectedSnapshot.content
guard let sourceWindow = selectedContent.windows.first(where: {
- $0.windowID == selectedWindow.windowID && $0.title == selectedWindow.title
- }),
- let sourceOwner = sourceWindow.owningApplication,
- sourceOwner.bundleIdentifier == target,
- sourceOwner.processID == selectedWindow.owningProcessID,
- selectedContent.applications.contains(where: {
- $0.bundleIdentifier == target && $0.processID == sourceOwner.processID
- }),
- NSRunningApplication(processIdentifier: sourceOwner.processID)?.isTerminated == false,
- let displayID = MeetingExternalReferenceTrialADisplaySelector.selectDisplayID(
- windowFrame: sourceWindow.frame,
- displays: selectedContent.displays.map { .init(displayID: $0.displayID, frame: $0.frame) }
- ), selectedContent.displays.contains(where: { $0.displayID == displayID }) else {
+ $0.windowID == selectedWindow.windowID && $0.title == selectedWindow.title
+ }),
+ let sourceOwner = sourceWindow.owningApplication,
+ sourceOwner.bundleIdentifier == target,
+ sourceOwner.processID == selectedWindow.owningProcessID,
+ selectedContent.applications.contains(where: {
+ $0.bundleIdentifier == target && $0.processID == sourceOwner.processID
+ }),
+ NSRunningApplication(processIdentifier: sourceOwner.processID)?.isTerminated == false,
+ let displayID = MeetingExternalReferenceTrialADisplaySelector.selectDisplayID(
+ windowFrame: sourceWindow.frame,
+ displays: selectedContent.displays.map { .init(displayID: $0.displayID, frame: $0.frame) }
+ ), selectedContent.displays.contains(where: { $0.displayID == displayID })
+ else {
return "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"display\"}"
}
@@ -564,17 +584,21 @@ nonisolated enum MeetingStage05EvidenceAutorun {
// can therefore never strand a partial artifact in a validated evidence root.
cleanup.set(root: root)
guard let executableURL = Bundle.main.executableURL.flatMap(Self.absoluteRegularFile),
- let executableSHA256 = try? SHA256Hex.file(executableURL) else {
+ let executableSHA256 = try? SHA256Hex.file(executableURL)
+ else {
return "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"build\"}"
}
let collector: MeetingStage05PCMCollector
do {
- collector = try MeetingStage05PCMCollector(root: root, inputUID: input.uid,
- outputUID: output.uid,
- fixtureSHA256: expectedFixtureSHA256,
- executableSHA256: executableSHA256,
- initialOutputVolume: initialVolume,
- targetProcessID: sourceOwner.processID)
+ collector = try MeetingStage05PCMCollector(
+ root: root,
+ inputUID: input.uid,
+ outputUID: output.uid,
+ fixtureSHA256: expectedFixtureSHA256,
+ executableSHA256: executableSHA256,
+ initialOutputVolume: initialVolume,
+ targetProcessID: sourceOwner.processID
+ )
} catch {
return "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"workspace\"}"
}
@@ -595,29 +619,42 @@ nonisolated enum MeetingStage05EvidenceAutorun {
let renderQueue = DispatchQueue(label: "fluidvoice.stage05.render")
let captureQueue = DispatchQueue(label: "fluidvoice.stage05.capture")
do {
- try stream.addStreamOutput(outputHandler, type: .audio,
- sampleHandlerQueue: renderQueue)
- try stream.addStreamOutput(outputHandler, type: .microphone,
- sampleHandlerQueue: captureQueue)
+ try stream.addStreamOutput(
+ outputHandler,
+ type: .audio,
+ sampleHandlerQueue: renderQueue
+ )
+ try stream.addStreamOutput(
+ outputHandler,
+ type: .microphone,
+ sampleHandlerQueue: captureQueue
+ )
try await Self.withTimeout(seconds: 2) { try await stream.startCapture() }
let captureDeadline = ProcessInfo.processInfo.systemUptime + Self.captureSeconds
while ProcessInfo.processInfo.systemUptime < captureDeadline {
let remaining = max(0, captureDeadline - ProcessInfo.processInfo.systemUptime)
try await Task.sleep(nanoseconds: UInt64(min(0.1, remaining) * 1_000_000_000))
- guard Self.routeStillValid(inputUID: input.uid, outputUID: output.uid,
- initialVolume: initialVolume,
- targetProcessID: sourceOwner.processID) else { throw RouteChanged.error }
+ guard Self.routeStillValid(
+ inputUID: input.uid,
+ outputUID: output.uid,
+ initialVolume: initialVolume,
+ targetProcessID: sourceOwner.processID
+ ) else { throw RouteChanged.error }
}
try await Self.withTimeout(seconds: 2) { try await stream.stopCapture() }
renderQueue.sync {} // Drain callbacks before sealing the WAV headers and manifest.
captureQueue.sync {}
- guard Self.routeStillValid(inputUID: input.uid, outputUID: output.uid,
- initialVolume: initialVolume,
- targetProcessID: sourceOwner.processID),
- let finalOutput = AudioDevice.getDefaultOutputDevice(),
- finalOutput.uid == output.uid,
- Self.readOutputVolume(finalOutput.id) != nil,
- streamDelegate.errorCount == 0 else {
+ guard Self.routeStillValid(
+ inputUID: input.uid,
+ outputUID: output.uid,
+ initialVolume: initialVolume,
+ targetProcessID: sourceOwner.processID
+ ),
+ let finalOutput = AudioDevice.getDefaultOutputDevice(),
+ finalOutput.uid == output.uid,
+ Self.readOutputVolume(finalOutput.id) != nil,
+ streamDelegate.errorCount == 0
+ else {
collector.abort()
return "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"routeChanged\"}"
}
@@ -630,25 +667,32 @@ nonisolated enum MeetingStage05EvidenceAutorun {
// synchronize exactly once, then exercise the identity/mock AEC seam exactly once.
let (adapterDrain, synchronization) = adapter.synchronize(configuration: .init(
referenceScope: .selectedWindow,
- referenceCompleteness: .measuredComplete))
+ referenceCompleteness: .measuredComplete
+ ))
let seam = MeetingStage05MockAECSeam().process(synchronization)
let adapterSummary = MeetingStage05LiveAdapterSummary.make(
- drain: adapterDrain, synchronization: synchronization, seam: seam)
+ drain: adapterDrain, synchronization: synchronization, seam: seam
+ )
guard adapterSummary.structurallyValid else {
collector.abort()
return Self.encodedOutcome(
- exitStatus: 1, status: "failure", reason: "adapterGate",
- adapter: adapterSummary.validationReasons().isEmpty ? adapterSummary : nil)
+ exitStatus: 1,
+ status: "failure",
+ reason: "adapterGate",
+ adapter: adapterSummary.validationReasons().isEmpty ? adapterSummary : nil
+ )
}
do {
guard let finalOutput = AudioDevice.getDefaultOutputDevice(),
finalOutput.uid == output.uid,
- let finalVolume = Self.readOutputVolume(finalOutput.id) else {
+ let finalVolume = Self.readOutputVolume(finalOutput.id)
+ else {
throw RouteChanged.error
}
try collector.finish(consentConfirmed: true, finalOutputVolume: finalVolume)
return Self.encodedOutcome(
- exitStatus: 0, status: "success", adapter: adapterSummary)
+ exitStatus: 0, status: "success", adapter: adapterSummary
+ )
} catch let failure as MeetingStage05FinalizeFailure {
// Only completed render/capture timing finalization retains the numeric-only
// timing.json; all other failure categories retain nothing.
@@ -658,20 +702,29 @@ nonisolated enum MeetingStage05EvidenceAutorun {
collector.abort()
}
return Self.encodedOutcome(
- exitStatus: 1, status: "failure", reason: "finalize\(failure.rawValue)",
- adapter: adapterSummary)
+ exitStatus: 1,
+ status: "failure",
+ reason: "finalize\(failure.rawValue)",
+ adapter: adapterSummary
+ )
} catch {
collector.abort()
return Self.encodedOutcome(
- exitStatus: 1, status: "failure", reason: "finalizeUnknown",
- adapter: adapterSummary)
+ exitStatus: 1,
+ status: "failure",
+ reason: "finalizeUnknown",
+ adapter: adapterSummary
+ )
}
}
private static func readOutputVolume(_ deviceID: AudioObjectID) -> Float32? {
for selector in [kAudioHardwareServiceDeviceProperty_VirtualMainVolume, kAudioDevicePropertyVolumeScalar] {
- var address = AudioObjectPropertyAddress(mSelector: selector,
- mScope: kAudioDevicePropertyScopeOutput, mElement: kAudioObjectPropertyElementMain)
+ var address = AudioObjectPropertyAddress(
+ mSelector: selector,
+ mScope: kAudioDevicePropertyScopeOutput,
+ mElement: kAudioObjectPropertyElementMain
+ )
var value: Float32 = 0; var size = UInt32(MemoryLayout<Float32>.size)
if AudioObjectGetPropertyData(deviceID, &address, 0, nil, &size, &value) == noErr,
value.isFinite, (0...1).contains(value) { return value }
@@ -682,8 +735,12 @@ nonisolated enum MeetingStage05EvidenceAutorun {
private static func windowCandidates(from content: SCShareableContent) -> [MeetingExternalReferenceTrialAWindowCandidate] {
content.windows.compactMap { window in
guard let owner = window.owningApplication else { return nil }
- return .init(windowID: window.windowID, owningBundleIdentifier: owner.bundleIdentifier,
- owningProcessID: owner.processID, title: window.title)
+ return .init(
+ windowID: window.windowID,
+ owningBundleIdentifier: owner.bundleIdentifier,
+ owningProcessID: owner.processID,
+ title: window.title
+ )
}
}
@@ -733,12 +790,15 @@ nonisolated enum MeetingStage05EvidenceAutorun {
continue
}
let decision = MeetingStage05StimulusHandshake.decision(
- for: ready, current: Self.windowCandidates(from: content),
+ for: ready,
+ current: Self.windowCandidates(from: content),
targetBundleIdentifier: targetBundleID,
- now: ProcessInfo.processInfo.systemUptime, deadline: deadline)
+ now: ProcessInfo.processInfo.systemUptime,
+ deadline: deadline
+ )
switch decision {
- case .success(let playing): return PlayingSnapshot(candidate: playing, content: content)
- case .failure(let failure): throw failure
+ case let .success(playing): return PlayingSnapshot(candidate: playing, content: content)
+ case let .failure(failure): throw failure
case .waiting:
let remaining = deadline - ProcessInfo.processInfo.systemUptime
guard remaining > 0 else { throw MeetingStage05StimulusHandshake.Failure.timeout }
@@ -758,8 +818,13 @@ nonisolated enum MeetingStage05EvidenceAutorun {
case .timeout: return "stimulusTimeout"
}
}
- private static func routeStillValid(inputUID: String, outputUID: String, initialVolume: Float32,
- targetProcessID: Int32) -> Bool {
+
+ private static func routeStillValid(
+ inputUID: String,
+ outputUID: String,
+ initialVolume: Float32,
+ targetProcessID: Int32
+ ) -> Bool {
guard NSRunningApplication(processIdentifier: targetProcessID)?.isTerminated == false else {
return false
}
@@ -785,6 +850,7 @@ nonisolated enum MeetingStage05EvidenceAutorun {
}
return url
}
+
static func remainingStimulusSeconds(_ title: String?) -> Double? {
guard let value = MeetingStage05StimulusHandshake.playingRemainingSeconds(title),
value >= Double(MeetingStage05StimulusHandshake.minimumRemainingSeconds) else { return nil }
@@ -793,7 +859,7 @@ nonisolated enum MeetingStage05EvidenceAutorun {
private final class CompletionGate: @unchecked Sendable {
private let lock = NSLock(); private var done = false
- func claim() -> Bool { lock.lock(); defer { lock.unlock() }; guard !done else { return false }; done = true; return true }
+ func claim() -> Bool { self.lock.lock(); defer { lock.unlock() }; guard !self.done else { return false }; self.done = true; return true }
}
private final class CleanupBox: @unchecked Sendable {
@@ -816,7 +882,7 @@ nonisolated enum MeetingStage05EvidenceAutorun {
self.lock.unlock()
}
- func run() { lock.lock(); let action = self.action; self.action = nil; lock.unlock(); action?() }
+ func run() { self.lock.lock(); let action = self.action; self.action = nil; self.lock.unlock(); action?() }
}
enum TimeoutError: Error { case timeout }
@@ -831,8 +897,7 @@ nonisolated enum MeetingStage05EvidenceAutorun {
// These are deliberately unstructured. A structured task group waits for a child
// that ignores cancellation, defeating the timeout for ScreenCaptureKit operations.
Task {
- do { race.resolve(.success(try await operation())) }
- catch { race.resolve(.failure(error)) }
+ do { try race.resolve(.success(await operation())) } catch { race.resolve(.failure(error)) }
}
DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + seconds) {
race.resolve(.failure(TimeoutError.timeout))
@@ -875,8 +940,11 @@ final class MeetingStage05StreamOutput: NSObject, SCStreamOutput, @unchecked Sen
self.monotonicNow = monotonicNow
}
- func stream(_ stream: SCStream, didOutputSampleBuffer sampleBuffer: CMSampleBuffer,
- of outputType: SCStreamOutputType) {
+ func stream(
+ _ stream: SCStream,
+ didOutputSampleBuffer sampleBuffer: CMSampleBuffer,
+ of outputType: SCStreamOutputType
+ ) {
self.handle(sampleBuffer, outputType: outputType)
}
@@ -902,8 +970,8 @@ final class MeetingStage05StreamOutput: NSObject, SCStreamOutput, @unchecked Sen
private final class MeetingStage05StreamDelegate: NSObject, SCStreamDelegate, @unchecked Sendable {
private let lock = NSLock(); private var errors = 0
- var errorCount: Int { lock.lock(); defer { lock.unlock() }; return errors }
- func stream(_ stream: SCStream, didStopWithError error: Error) { lock.lock(); errors += 1; lock.unlock() }
+ var errorCount: Int { self.lock.lock(); defer { lock.unlock() }; return self.errors }
+ func stream(_ stream: SCStream, didStopWithError error: Error) { self.lock.lock(); self.errors += 1; self.lock.unlock() }
}
nonisolated struct MeetingStage05NativePCMFormat: Equatable, Sendable {
@@ -986,11 +1054,14 @@ nonisolated struct MeetingStage05TimingFailureRecord: Codable, Equatable, Sendab
captureTiming: [MeetingSignalDomainGateManifest.TimingBlock],
sampleRateHz: Double
) -> Self {
- Self(schema: Self.schema, failure: failure.rawValue,
- track: failure == .renderTiming ? "render" : "capture",
- sampleRateHz: sampleRateHz,
- render: Self.derive(renderTiming, sampleRateHz: sampleRateHz),
- capture: Self.derive(captureTiming, sampleRateHz: sampleRateHz))
+ Self(
+ schema: self.schema,
+ failure: failure.rawValue,
+ track: failure == .renderTiming ? "render" : "capture",
+ sampleRateHz: sampleRateHz,
+ render: self.derive(renderTiming, sampleRateHz: sampleRateHz),
+ capture: self.derive(captureTiming, sampleRateHz: sampleRateHz)
+ )
}
private static func derive(
@@ -1008,30 +1079,36 @@ nonisolated struct MeetingStage05TimingFailureRecord: Codable, Equatable, Sendab
}
// A format change aborts the run before timing finalization, so a retained record
// can only ever observe zero format transitions.
- return Track(blocks: blocks, gapCount: gaps, overlapCount: overlaps,
- backwardCount: backward, formatChangeCount: 0)
+ return Track(
+ blocks: blocks,
+ gapCount: gaps,
+ overlapCount: overlaps,
+ backwardCount: backward,
+ formatChangeCount: 0
+ )
}
func validationReasons() -> [String] {
var reasons: [String] = []
- if schema != Self.schema { reasons.append("schema") }
+ if self.schema != Self.schema { reasons.append("schema") }
let timingFailures: Set<String> = [
MeetingStage05FinalizeFailure.renderTiming.rawValue,
MeetingStage05FinalizeFailure.captureTiming.rawValue,
]
- if !timingFailures.contains(failure) { reasons.append("failure") }
- let expectedTrack = failure == MeetingStage05FinalizeFailure.renderTiming.rawValue
+ if !timingFailures.contains(self.failure) { reasons.append("failure") }
+ let expectedTrack = self.failure == MeetingStage05FinalizeFailure.renderTiming.rawValue
? "render" : "capture"
- if track != expectedTrack { reasons.append("track") }
- if !sampleRateHz.isFinite || sampleRateHz != 48_000 { reasons.append("sampleRateHz") }
- for side in [render, capture] {
- if side.blocks.isEmpty || side.blocks.count > 2_000 { reasons.append("blockCount") }
+ if self.track != expectedTrack { reasons.append("track") }
+ if !self.sampleRateHz.isFinite || self.sampleRateHz != 48_000 { reasons.append("sampleRateHz") }
+ for side in [self.render, self.capture] {
+ if side.blocks.isEmpty || side.blocks.count > 2000 { reasons.append("blockCount") }
var totalFrames = 0
for block in side.blocks {
if !block.presentationSeconds.isFinite || block.presentationSeconds < 0
|| !block.durationSeconds.isFinite || block.durationSeconds <= 0
|| block.frameCount <= 0
- || (block.arrivalSeconds.map { !$0.isFinite || $0 < 0 } ?? false) {
+ || (block.arrivalSeconds.map { !$0.isFinite || $0 < 0 } ?? false)
+ {
reasons.append("block")
break
}
@@ -1042,8 +1119,9 @@ nonisolated struct MeetingStage05TimingFailureRecord: Codable, Equatable, Sendab
if totalFrames > 960_000 { reasons.append("frameCount") }
if side.gapCount < 0 || side.overlapCount < 0 || side.backwardCount < 0
|| side.formatChangeCount < 0 { reasons.append("counts") }
- if sampleRateHz.isFinite, sampleRateHz > 0,
- side != Self.derive(side.blocks, sampleRateHz: sampleRateHz) {
+ if self.sampleRateHz.isFinite, self.sampleRateHz > 0,
+ side != Self.derive(side.blocks, sampleRateHz: self.sampleRateHz)
+ {
reasons.append("derivedCounts")
}
}
@@ -1068,7 +1146,7 @@ final class MeetingStage05PCMCollector: @unchecked Sendable {
private var captureTiming: [MeetingSignalDomainGateManifest.TimingBlock] = []
private var nativeSampleRateHz: Double?
private var appendFailure: MeetingStage05FinalizeFailure?
- private let maxBlocks = 2_000
+ private let maxBlocks = 2000
private let maxFrames = 960_000
init(
@@ -1105,7 +1183,7 @@ final class MeetingStage05PCMCollector: @unchecked Sendable {
}
static func prepareRoot(_ root: URL) throws {
- guard Self.isSafeRoot(root) else { throw Error.workspace }
+ guard self.isSafeRoot(root) else { throw Error.workspace }
let manager = FileManager.default
if manager.fileExists(atPath: root.path) {
guard (try? manager.destinationOfSymbolicLink(atPath: root.path)) == nil,
@@ -1113,13 +1191,17 @@ final class MeetingStage05PCMCollector: @unchecked Sendable {
let mode = (try? manager.attributesOfItem(atPath: root.path)[.posixPermissions] as? NSNumber)?.intValue ?? 0
guard mode & 0o777 == 0o700 else { throw Error.workspace }
} else {
- try manager.createDirectory(at: root, withIntermediateDirectories: true,
- attributes: [.posixPermissions: 0o700])
+ try manager.createDirectory(
+ at: root,
+ withIntermediateDirectories: true,
+ attributes: [.posixPermissions: 0o700]
+ )
}
let rootAttributes = try manager.attributesOfItem(atPath: root.path)
guard rootAttributes[.type] as? FileAttributeType == .typeDirectory,
(rootAttributes[.posixPermissions] as? NSNumber)?.intValue == 0o700,
- (try manager.contentsOfDirectory(atPath: root.path)).isEmpty else {
+ try (manager.contentsOfDirectory(atPath: root.path)).isEmpty
+ else {
throw Error.workspace
}
}
@@ -1144,87 +1226,108 @@ final class MeetingStage05PCMCollector: @unchecked Sendable {
output: Output,
arrivalSeconds: Double? = nil
) {
- lock.lock(); defer { lock.unlock() }
- guard !aborted else { return }
+ self.lock.lock(); defer { lock.unlock() }
+ guard !self.aborted else { return }
let callbackArrival = arrivalSeconds ?? ProcessInfo.processInfo.systemUptime
guard let frame = Self.extract(sampleBuffer, arrivalSeconds: callbackArrival), frame.frameCount > 0,
frame.sampleRateHz > 0, frame.channels == 1,
- frame.frameCount <= maxFrames else { failAppend(.appendInvalidFrame); return }
+ frame.frameCount <= maxFrames else { self.failAppend(.appendInvalidFrame); return }
if let existing = render.format ?? capture.format, existing != frame.format {
- failAppend(.appendFormatChanged); return
+ self.failAppend(.appendFormatChanged); return
}
if let nativeSampleRateHz, abs(nativeSampleRateHz - frame.sampleRateHz) > 1e-6 {
- failAppend(.appendSampleRateChanged); return
+ self.failAppend(.appendSampleRateChanged); return
}
nativeSampleRateHz = frame.sampleRateHz
switch output {
- case .render: if render.frameCount + frame.frameCount > maxFrames { failAppend(.appendFrameLimit); return }
- case .capture: if capture.frameCount + frame.frameCount > maxFrames { failAppend(.appendFrameLimit); return }
+ case .render: if self.render.frameCount + frame.frameCount > self.maxFrames { self.failAppend(.appendFrameLimit); return }
+ case .capture: if self.capture.frameCount + frame.frameCount > self.maxFrames { self.failAppend(.appendFrameLimit); return }
}
let timing = MeetingSignalDomainGateManifest.TimingBlock(
- presentationSeconds: frame.presentationSeconds, durationSeconds: frame.durationSeconds,
- frameCount: frame.frameCount, arrivalSeconds: frame.arrivalSeconds)
+ presentationSeconds: frame.presentationSeconds,
+ durationSeconds: frame.durationSeconds,
+ frameCount: frame.frameCount,
+ arrivalSeconds: frame.arrivalSeconds
+ )
do {
switch output {
case .render:
- guard renderTiming.count < maxBlocks else { failAppend(.appendBlockLimit); return }
- try render.append(frame.data, format: frame.format, sampleRateHz: frame.sampleRateHz, frameCount: frame.frameCount)
- renderTiming.append(timing)
+ guard self.renderTiming.count < self.maxBlocks else { self.failAppend(.appendBlockLimit); return }
+ try self.render.append(frame.data, format: frame.format, sampleRateHz: frame.sampleRateHz, frameCount: frame.frameCount)
+ self.renderTiming.append(timing)
case .capture:
- guard captureTiming.count < maxBlocks else { failAppend(.appendBlockLimit); return }
- try capture.append(frame.data, format: frame.format, sampleRateHz: frame.sampleRateHz, frameCount: frame.frameCount)
- captureTiming.append(timing)
+ guard self.captureTiming.count < self.maxBlocks else { self.failAppend(.appendBlockLimit); return }
+ try self.capture.append(frame.data, format: frame.format, sampleRateHz: frame.sampleRateHz, frameCount: frame.frameCount)
+ self.captureTiming.append(timing)
}
- } catch { failAppend(.appendWrite) }
+ } catch { self.failAppend(.appendWrite) }
}
private func failAppend(_ failure: MeetingStage05FinalizeFailure) {
- if appendFailure == nil { appendFailure = failure }
- aborted = true
+ if self.appendFailure == nil { self.appendFailure = failure }
+ self.aborted = true
}
func finish(consentConfirmed: Bool, finalOutputVolume: Float32) throws {
- lock.lock(); defer { lock.unlock() }
- if aborted { throw appendFailure ?? MeetingStage05FinalizeFailure.appendInvalidFrame }
- guard consentConfirmed, !renderTiming.isEmpty, !captureTiming.isEmpty else {
+ self.lock.lock(); defer { lock.unlock() }
+ if self.aborted { throw self.appendFailure ?? MeetingStage05FinalizeFailure.appendInvalidFrame }
+ guard consentConfirmed, !self.renderTiming.isEmpty, !self.captureTiming.isEmpty else {
throw MeetingStage05FinalizeFailure.missingStream
}
- guard Self.timingIsComplete(renderTiming, frameCount: render.frameCount,
- sampleRateHz: render.sampleRateHz) else {
+ guard Self.timingIsComplete(
+ self.renderTiming,
+ frameCount: self.render.frameCount,
+ sampleRateHz: self.render.sampleRateHz
+ ) else {
throw MeetingStage05FinalizeFailure.renderTiming
}
- guard Self.timingIsComplete(captureTiming, frameCount: capture.frameCount,
- sampleRateHz: capture.sampleRateHz) else {
+ guard Self.timingIsComplete(
+ self.captureTiming,
+ frameCount: self.capture.frameCount,
+ sampleRateHz: self.capture.sampleRateHz
+ ) else {
throw MeetingStage05FinalizeFailure.captureTiming
}
- guard render.peak > 0 else { throw MeetingStage05FinalizeFailure.renderSilent }
- guard render.peak <= 0.15 else { throw MeetingStage05FinalizeFailure.renderOutOfBounds }
- guard capture.peak.isFinite else { throw MeetingStage05FinalizeFailure.captureNonfinite }
- guard capture.peak <= 1 else { throw MeetingStage05FinalizeFailure.captureClipping }
- do { try render.finish() } catch { throw MeetingStage05FinalizeFailure.renderSeal }
- do { try capture.finish() } catch { throw MeetingStage05FinalizeFailure.captureSeal }
+ guard self.render.peak > 0 else { throw MeetingStage05FinalizeFailure.renderSilent }
+ guard self.render.peak <= 0.15 else { throw MeetingStage05FinalizeFailure.renderOutOfBounds }
+ guard self.capture.peak.isFinite else { throw MeetingStage05FinalizeFailure.captureNonfinite }
+ guard self.capture.peak <= 1 else { throw MeetingStage05FinalizeFailure.captureClipping }
+ do { try self.render.finish() } catch { throw MeetingStage05FinalizeFailure.renderSeal }
+ do { try self.capture.finish() } catch { throw MeetingStage05FinalizeFailure.captureSeal }
let renderArtifact: MeetingSignalDomainGateManifest.Artifact
let captureArtifact: MeetingSignalDomainGateManifest.Artifact
do {
- renderArtifact = try Self.artifact(role: "render", url: render.url, writer: render)
- captureArtifact = try Self.artifact(role: "capture", url: capture.url, writer: capture)
+ renderArtifact = try Self.artifact(role: "render", url: self.render.url, writer: self.render)
+ captureArtifact = try Self.artifact(role: "capture", url: self.capture.url, writer: self.capture)
} catch { throw MeetingStage05FinalizeFailure.artifact }
let session = MeetingSignalDomainGateManifest.Session(
- ordinal: 0, render: renderArtifact, capture: captureArtifact,
- renderTiming: renderTiming, captureTiming: captureTiming)
+ ordinal: 0,
+ render: renderArtifact,
+ capture: captureArtifact,
+ renderTiming: self.renderTiming,
+ captureTiming: self.captureTiming
+ )
let provenance = MeetingStage05Provenance(
- renderSHA256: renderArtifact.sha256, captureSHA256: captureArtifact.sha256,
- fixtureSHA256: fixtureSHA256, captureExecutableSHA256: executableSHA256,
- inputUIDSHA256: SHA256Hex.string(inputUID), outputUIDSHA256: SHA256Hex.string(outputUID),
- runOrdinal: 0, targetProcessID: targetProcessID,
- initialOutputVolume: initialOutputVolume, finalOutputVolume: finalOutputVolume,
- renderPeak: render.peak, capturePeak: capture.peak,
- renderBlockCount: renderTiming.count, captureBlockCount: captureTiming.count,
- renderFrameCount: render.frameCount, captureFrameCount: capture.frameCount)
+ renderSHA256: renderArtifact.sha256,
+ captureSHA256: captureArtifact.sha256,
+ fixtureSHA256: self.fixtureSHA256,
+ captureExecutableSHA256: self.executableSHA256,
+ inputUIDSHA256: SHA256Hex.string(self.inputUID),
+ outputUIDSHA256: SHA256Hex.string(self.outputUID),
+ runOrdinal: 0,
+ targetProcessID: self.targetProcessID,
+ initialOutputVolume: self.initialOutputVolume,
+ finalOutputVolume: finalOutputVolume,
+ renderPeak: self.render.peak,
+ capturePeak: self.capture.peak,
+ renderBlockCount: self.renderTiming.count,
+ captureBlockCount: self.captureTiming.count,
+ renderFrameCount: self.render.frameCount,
+ captureFrameCount: self.capture.frameCount
+ )
let provenanceData: Data
- do { provenanceData = try JSONEncoder.sorted.encode(provenance) }
- catch { throw MeetingStage05FinalizeFailure.provenance }
- let provenanceURL = root.appendingPathComponent("provenance.json")
+ do { provenanceData = try JSONEncoder.sorted.encode(provenance) } catch { throw MeetingStage05FinalizeFailure.provenance }
+ let provenanceURL = self.root.appendingPathComponent("provenance.json")
let provenanceDescriptor = Darwin.open(provenanceURL.path, O_WRONLY | O_CREAT | O_EXCL, 0o600)
guard provenanceDescriptor >= 0 else { throw MeetingStage05FinalizeFailure.provenance }
let provenanceHandle = FileHandle(fileDescriptor: provenanceDescriptor, closeOnDealloc: true)
@@ -1233,18 +1336,22 @@ final class MeetingStage05PCMCollector: @unchecked Sendable {
try provenanceHandle.synchronize(); try provenanceHandle.close()
} catch { throw MeetingStage05FinalizeFailure.provenance }
let provenanceHash: String
- do { provenanceHash = try SHA256Hex.file(provenanceURL) }
- catch { throw MeetingStage05FinalizeFailure.provenance }
+ do { provenanceHash = try SHA256Hex.file(provenanceURL) } catch { throw MeetingStage05FinalizeFailure.provenance }
let manifest = MeetingSignalDomainGateManifest(
- topology: .pairedScreenCaptureKit, route: .builtInSpeakerMicrophone,
- referenceScope: .selectedWindow, referenceCompletenessMeasured: true,
- consentConfirmed: consentConfirmed, artifacts: [], sessions: [session],
- provenanceRelativePath: "provenance.json", provenanceSha256: provenanceHash)
+ topology: .pairedScreenCaptureKit,
+ route: .builtInSpeakerMicrophone,
+ referenceScope: .selectedWindow,
+ referenceCompletenessMeasured: true,
+ consentConfirmed: consentConfirmed,
+ artifacts: [],
+ sessions: [session],
+ provenanceRelativePath: "provenance.json",
+ provenanceSha256: provenanceHash
+ )
guard manifest.validationReasons().isEmpty else { throw MeetingStage05FinalizeFailure.manifest }
let data: Data
- do { data = try JSONEncoder.sorted.encode(manifest) }
- catch { throw MeetingStage05FinalizeFailure.manifest }
- let manifestURL = root.appendingPathComponent("manifest.json")
+ do { data = try JSONEncoder.sorted.encode(manifest) } catch { throw MeetingStage05FinalizeFailure.manifest }
+ let manifestURL = self.root.appendingPathComponent("manifest.json")
let descriptor = Darwin.open(manifestURL.path, O_WRONLY | O_CREAT | O_EXCL, 0o600)
guard descriptor >= 0 else { throw MeetingStage05FinalizeFailure.manifest }
let manifestHandle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)
@@ -1255,13 +1362,13 @@ final class MeetingStage05PCMCollector: @unchecked Sendable {
}
func abort() {
- lock.lock(); aborted = true
- render.discard(); capture.discard()
+ self.lock.lock(); self.aborted = true
+ self.render.discard(); self.capture.discard()
let manager = FileManager.default
- try? manager.removeItem(at: root.appendingPathComponent("manifest.json"))
- try? manager.removeItem(at: root.appendingPathComponent("provenance.json"))
- try? manager.removeItem(at: root.appendingPathComponent(MeetingStage05TimingFailureRecord.filename))
- lock.unlock()
+ try? manager.removeItem(at: self.root.appendingPathComponent("manifest.json"))
+ try? manager.removeItem(at: self.root.appendingPathComponent("provenance.json"))
+ try? manager.removeItem(at: self.root.appendingPathComponent(MeetingStage05TimingFailureRecord.filename))
+ self.lock.unlock()
}
/// Retains only the numeric timing-failure record for a completed render/capture timing
@@ -1269,29 +1376,33 @@ final class MeetingStage05PCMCollector: @unchecked Sendable {
/// and unlinked first, so successful WAV evidence and a timing-only failure record are
/// mutually exclusive. Every other failure category retains nothing.
func retainTimingFailureRecord(_ failure: MeetingStage05FinalizeFailure) {
- lock.lock(); defer { lock.unlock() }
- aborted = true
- render.discard(); capture.discard()
+ self.lock.lock(); defer { lock.unlock() }
+ self.aborted = true
+ self.render.discard(); self.capture.discard()
let manager = FileManager.default
- try? manager.removeItem(at: root.appendingPathComponent("manifest.json"))
- try? manager.removeItem(at: root.appendingPathComponent("provenance.json"))
+ try? manager.removeItem(at: self.root.appendingPathComponent("manifest.json"))
+ try? manager.removeItem(at: self.root.appendingPathComponent("provenance.json"))
guard failure == .renderTiming || failure == .captureTiming else {
- try? manager.removeItem(at: root.appendingPathComponent(MeetingStage05TimingFailureRecord.filename))
+ try? manager.removeItem(at: self.root.appendingPathComponent(MeetingStage05TimingFailureRecord.filename))
return
}
let record = MeetingStage05TimingFailureRecord.make(
- failure: failure, renderTiming: renderTiming, captureTiming: captureTiming,
- sampleRateHz: nativeSampleRateHz ?? 48_000)
+ failure: failure,
+ renderTiming: self.renderTiming,
+ captureTiming: self.captureTiming,
+ sampleRateHz: self.nativeSampleRateHz ?? 48_000
+ )
guard record.validationReasons().isEmpty,
- let data = try? JSONEncoder.sorted.encode(record) else {
- Self.emergencyCleanup(at: root)
+ let data = try? JSONEncoder.sorted.encode(record)
+ else {
+ Self.emergencyCleanup(at: self.root)
return
}
- let url = root.appendingPathComponent(MeetingStage05TimingFailureRecord.filename)
+ let url = self.root.appendingPathComponent(MeetingStage05TimingFailureRecord.filename)
let descriptor = Darwin.open(url.path, O_WRONLY | O_CREAT | O_EXCL, 0o600)
guard descriptor >= 0 else {
// A pre-existing record means the root is in an inconsistent state; retain nothing.
- Self.emergencyCleanup(at: root)
+ Self.emergencyCleanup(at: self.root)
return
}
let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)
@@ -1301,19 +1412,24 @@ final class MeetingStage05PCMCollector: @unchecked Sendable {
try handle.close()
} catch {
try? handle.close()
- Self.emergencyCleanup(at: root)
+ Self.emergencyCleanup(at: self.root)
}
}
/// Emergency path intentionally avoids the collector lock. The watchdog has a hard deadline;
/// it unlinks only these fixed private filenames and then terminates the process.
nonisolated func emergencyCleanup() {
- Self.emergencyCleanup(at: root)
+ Self.emergencyCleanup(at: self.root)
}
nonisolated static func emergencyCleanup(at root: URL) {
- for name in ["render.wav", "capture.wav", "manifest.json", "provenance.json",
- MeetingStage05TimingFailureRecord.filename] {
+ for name in [
+ "render.wav",
+ "capture.wav",
+ "manifest.json",
+ "provenance.json",
+ MeetingStage05TimingFailureRecord.filename,
+ ] {
root.appendingPathComponent(name).path.withCString { _ = Darwin.unlink($0) }
}
}
@@ -1321,19 +1437,30 @@ final class MeetingStage05PCMCollector: @unchecked Sendable {
private static func artifact(role: String, url: URL, writer: WAVWriter) throws -> MeetingSignalDomainGateManifest.Artifact {
let hash = try SHA256Hex.file(url)
guard let codec = writer.codec else { throw MeetingStage05PCMCollector.Error.invalidCapture }
- return .init(role: role, relativePath: role + ".wav", sha256: hash, codec: codec,
- lossless: true, sampleRateHz: writer.sampleRateHz, channelCount: 1,
- durationSeconds: Double(writer.frameCount) / writer.sampleRateHz)
+ return .init(
+ role: role,
+ relativePath: role + ".wav",
+ sha256: hash,
+ codec: codec,
+ lossless: true,
+ sampleRateHz: writer.sampleRateHz,
+ channelCount: 1,
+ durationSeconds: Double(writer.frameCount) / writer.sampleRateHz
+ )
}
- private static func timingIsComplete(_ blocks: [MeetingSignalDomainGateManifest.TimingBlock],
- frameCount: Int, sampleRateHz: Double) -> Bool {
+ private static func timingIsComplete(
+ _ blocks: [MeetingSignalDomainGateManifest.TimingBlock],
+ frameCount: Int,
+ sampleRateHz: Double
+ ) -> Bool {
guard blocks.count >= 3, blocks.allSatisfy({ $0.arrivalSeconds != nil }),
blocks.reduce(0, { $0 + $1.frameCount }) == frameCount else { return false }
let tolerance = 1 / sampleRateHz
for pair in zip(blocks.dropFirst(), blocks) {
let difference = pair.0.presentationSeconds - (pair.1.presentationSeconds + pair.1.durationSeconds)
- if abs(difference) > tolerance || pair.0.arrivalSeconds! < pair.1.arrivalSeconds! { return false }
+ guard let laterArrival = pair.0.arrivalSeconds, let earlierArrival = pair.1.arrivalSeconds,
+ abs(difference) <= tolerance, laterArrival >= earlierArrival else { return false }
}
guard let first = blocks.first, let last = blocks.last else { return false }
let span = last.presentationSeconds + last.durationSeconds - first.presentationSeconds
@@ -1351,6 +1478,7 @@ final class MeetingStage05PCMCollector: @unchecked Sendable {
let format: String
let arrivalSeconds: Double
}
+
private static func extract(_ sampleBuffer: CMSampleBuffer, arrivalSeconds: Double) -> Frame? {
guard CMSampleBufferIsValid(sampleBuffer), CMSampleBufferDataIsReady(sampleBuffer),
let formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer),
@@ -1364,18 +1492,29 @@ final class MeetingStage05PCMCollector: @unchecked Sendable {
let byteCount = count * nativeFormat.bytesPerFrame
var requiredSize = 0
guard CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
- sampleBuffer, bufferListSizeNeededOut: &requiredSize, bufferListOut: nil,
- bufferListSize: 0, blockBufferAllocator: nil, blockBufferMemoryAllocator: nil,
- flags: 0, blockBufferOut: nil) == noErr, requiredSize > 0 else { return nil }
+ sampleBuffer,
+ bufferListSizeNeededOut: &requiredSize,
+ bufferListOut: nil,
+ bufferListSize: 0,
+ blockBufferAllocator: nil,
+ blockBufferMemoryAllocator: nil,
+ flags: 0,
+ blockBufferOut: nil
+ ) == noErr, requiredSize > 0 else { return nil }
let raw = UnsafeMutableRawPointer.allocate(byteCount: requiredSize, alignment: MemoryLayout<AudioBufferList>.alignment)
defer { raw.deallocate() }
let list = raw.bindMemory(to: AudioBufferList.self, capacity: 1)
var retained: CMBlockBuffer?
guard CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
- sampleBuffer, bufferListSizeNeededOut: nil, bufferListOut: list,
- bufferListSize: requiredSize, blockBufferAllocator: nil, blockBufferMemoryAllocator: nil,
+ sampleBuffer,
+ bufferListSizeNeededOut: nil,
+ bufferListOut: list,
+ bufferListSize: requiredSize,
+ blockBufferAllocator: nil,
+ blockBufferMemoryAllocator: nil,
flags: UInt32(kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment),
- blockBufferOut: &retained) == noErr else { return nil }
+ blockBufferOut: &retained
+ ) == noErr else { return nil }
let buffers = UnsafeMutableAudioBufferListPointer(list)
guard buffers.count == 1, buffers[0].mNumberChannels == 1,
buffers[0].mDataByteSize == UInt32(byteCount), let pointer = buffers[0].mData else { return nil }
@@ -1383,9 +1522,16 @@ final class MeetingStage05PCMCollector: @unchecked Sendable {
if nativeFormat.codec == "pcm_f32le" {
guard MeetingStage05NativePCMFormat.containsOnlyFiniteFloat32(data) else { return nil }
}
- return .init(data: data, presentationSeconds: pts, durationSeconds: duration,
- frameCount: count, sampleRateHz: asbd.mSampleRate, channels: 1,
- format: nativeFormat.codec, arrivalSeconds: arrivalSeconds)
+ return .init(
+ data: data,
+ presentationSeconds: pts,
+ durationSeconds: duration,
+ frameCount: count,
+ sampleRateHz: asbd.mSampleRate,
+ channels: 1,
+ format: nativeFormat.codec,
+ arrivalSeconds: arrivalSeconds
+ )
}
enum Error: Swift.Error { case workspace, invalidCapture }
@@ -1398,7 +1544,7 @@ private final class WAVWriter {
private(set) var frameCount = 0
private(set) var codec: String?
private(set) var peak: Float = 0
- var format: String? { codec }
+ var format: String? { self.codec }
init(url: URL) throws {
self.url = url
let descriptor = Darwin.open(url.path, O_WRONLY | O_CREAT | O_EXCL, 0o600)
@@ -1406,6 +1552,7 @@ private final class WAVWriter {
self.handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)
try self.handle.write(contentsOf: Data(repeating: 0, count: 44))
}
+
func append(_ data: Data, format: String, sampleRateHz: Double, frameCount: Int) throws {
let bytesPerSample = 4
guard format == "pcm_f32le" else { throw MeetingStage05PCMCollector.Error.invalidCapture }
@@ -1415,17 +1562,22 @@ private final class WAVWriter {
guard values.allSatisfy(\.isFinite) else { throw MeetingStage05PCMCollector.Error.invalidCapture }
self.peak = max(self.peak, values.map { abs($0) }.max() ?? 0)
self.codec = format; self.sampleRateHz = sampleRateHz; self.frameCount += frameCount
- try handle.seekToEnd(); try handle.write(contentsOf: data)
+ try self.handle.seekToEnd(); try self.handle.write(contentsOf: data)
}
+
func finish() throws {
guard let codec else { throw MeetingStage05PCMCollector.Error.invalidCapture }
let (formatTag, bits): (UInt16, UInt16) = (3, 32)
let bytesPerSample = Int(bits / 8)
guard codec == "pcm_f32le" else { throw MeetingStage05PCMCollector.Error.invalidCapture }
- var header = Data(); header.append(contentsOf: Array("RIFF".utf8)); header.appendLE(UInt32(36 + frameCount * bytesPerSample)); header.append(contentsOf: Array("WAVEfmt ".utf8)); header.appendLE(UInt32(16)); header.appendLE(formatTag); header.appendLE(UInt16(1)); header.appendLE(UInt32(sampleRateHz.rounded())); header.appendLE(UInt32(sampleRateHz.rounded() * Double(bytesPerSample))); header.appendLE(UInt16(bytesPerSample)); header.appendLE(bits); header.append(contentsOf: Array("data".utf8)); header.appendLE(UInt32(frameCount * bytesPerSample))
- try handle.seek(toOffset: 0); try handle.write(contentsOf: header); try handle.synchronize(); try handle.close()
+ var header = Data(); header.append(contentsOf: Array("RIFF".utf8)); header.appendLE(UInt32(36 + self.frameCount * bytesPerSample)); header.append(contentsOf: Array("WAVEfmt ".utf8)); header
+ .appendLE(UInt32(16)); header.appendLE(formatTag); header.appendLE(UInt16(1)); header.appendLE(UInt32(self.sampleRateHz.rounded())); header
+ .appendLE(UInt32(self.sampleRateHz.rounded() * Double(bytesPerSample))); header.appendLE(UInt16(bytesPerSample)); header.appendLE(bits); header
+ .append(contentsOf: Array("data".utf8)); header.appendLE(UInt32(self.frameCount * bytesPerSample))
+ try self.handle.seek(toOffset: 0); try self.handle.write(contentsOf: header); try self.handle.synchronize(); try self.handle.close()
}
- func discard() { try? handle.close(); try? FileManager.default.removeItem(at: url) }
+
+ func discard() { try? self.handle.close(); try? FileManager.default.removeItem(at: self.url) }
}
private struct MeetingStage05Provenance: Codable {
diff --git a/Sources/Fluid/Services/Meeting/MeetingStage05MockAECSeam.swift b/Sources/Fluid/Services/Meeting/MeetingStage05MockAECSeam.swift
index bed19614..7f8e14f3 100644
--- a/Sources/Fluid/Services/Meeting/MeetingStage05MockAECSeam.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingStage05MockAECSeam.swift
@@ -31,8 +31,6 @@ nonisolated struct MeetingStage05MockAECSeamResult: Equatable, Sendable {
/// ordering contract, and returns audio arrays unchanged. It performs no echo
/// cancellation: no resampling, delay, scaling, suppression, synthesis, or replacement.
nonisolated struct MeetingStage05MockAECSeam: Sendable {
- init() {}
-
func process(_ result: MeetingSynchronizationResult) -> MeetingStage05MockAECSeamResult {
let structuralContract = MeetingAECDelayContract(renderLeadSeconds: 0)
guard !result.failedOpen,
@@ -42,13 +40,20 @@ nonisolated struct MeetingStage05MockAECSeam: Sendable {
&& frame.renderSamples.allSatisfy(\.isFinite)
&& frame.captureSamples.allSatisfy(\.isFinite)
&& zip(frame.renderSamples, frame.renderValidMask)
- .allSatisfy { $0.1 || $0.0 == 0 }
+ .allSatisfy { $0.1 || $0.0 == 0 }
&& zip(frame.captureSamples, frame.captureValidMask)
- .allSatisfy { $0.1 || $0.0 == 0 }
- }) else {
+ .allSatisfy { $0.1 || $0.0 == 0 }
+ })
+ else {
return MeetingStage05MockAECSeamResult(
- frames: result.frames, events: [], observations: [], processedFrameCount: 0,
- frozenFrameCount: 0, boundaryCount: 0, authorized: false)
+ frames: result.frames,
+ events: [],
+ observations: [],
+ processedFrameCount: 0,
+ frozenFrameCount: 0,
+ boundaryCount: 0,
+ authorized: false
+ )
}
var events: [MeetingAECDelayContractEvent] = []
var observations: [MeetingStage05MockAECObservation] = []
@@ -78,12 +83,15 @@ nonisolated struct MeetingStage05MockAECSeam: Sendable {
&& frame.captureValidMask.allSatisfy { $0 }
let mustFreeze = reset || !complete || frame.adaptationFrozen
observations.append(MeetingStage05MockAECObservation(
- frameIndex: frame.index, epochID: frame.epochID, reset: reset,
+ frameIndex: frame.index,
+ epochID: frame.epochID,
+ reset: reset,
adaptationFrozen: mustFreeze,
resynchronizationBoundary: frame.resynchronizationBoundary,
renderValidCount: frame.renderValidMask.filter { $0 }.count,
captureValidCount: frame.captureValidMask.filter { $0 }.count,
- unknownReasons: frame.unknownReasons))
+ unknownReasons: frame.unknownReasons
+ ))
guard !mustFreeze else {
frozen += 1
continue
@@ -93,9 +101,14 @@ nonisolated struct MeetingStage05MockAECSeam: Sendable {
processed += 1
}
return MeetingStage05MockAECSeamResult(
- frames: result.frames, events: events, observations: observations,
+ frames: result.frames,
+ events: events,
+ observations: observations,
processedFrameCount: processed,
- frozenFrameCount: frozen, boundaryCount: boundaries, authorized: true)
+ frozenFrameCount: frozen,
+ boundaryCount: boundaries,
+ authorized: true
+ )
}
}
diff --git a/Sources/Fluid/Services/Meeting/MeetingStage05SCKFrameAdapter.swift b/Sources/Fluid/Services/Meeting/MeetingStage05SCKFrameAdapter.swift
index a5dd016c..6f377781 100644
--- a/Sources/Fluid/Services/Meeting/MeetingStage05SCKFrameAdapter.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingStage05SCKFrameAdapter.swift
@@ -71,7 +71,7 @@ nonisolated struct MeetingStage05AdapterDrain: Equatable, Sendable {
/// here as diagnostics; nothing is flattened or invented.
final class MeetingStage05SCKFrameAdapter: @unchecked Sendable {
static let supportedSampleRateHz = 48_000.0
- static let maximumBlocksPerTrack = 2_000
+ static let maximumBlocksPerTrack = 2000
static let maximumFramesPerTrack = 960_000
/// Harness-private sample attachment a controller may set to forward an explicit
/// discontinuity. ScreenCaptureKit audio callbacks carry no standard discontinuity
@@ -107,7 +107,7 @@ final class MeetingStage05SCKFrameAdapter: @unchecked Sendable {
case failure(MeetingStage05AdapterRejection)
}
- // MARK: Validation
+ // MARK: - Validation
static func validate(
_ frame: MeetingStage05AdapterFrame,
@@ -119,44 +119,45 @@ final class MeetingStage05SCKFrameAdapter: @unchecked Sendable {
guard frame.presentationSeconds >= 0,
frame.arrivalSeconds.map({ $0 >= 0 }) ?? true else { return .negativeTiming }
guard frame.frameCount > 0, frame.samples.count == frame.frameCount,
- frame.frameCount <= maximumFramesPerTrack else { return .invalidGeometry }
+ frame.frameCount <= self.maximumFramesPerTrack else { return .invalidGeometry }
let nominalDuration = Double(frame.frameCount) / frame.sampleRateHz
guard abs(frame.durationSeconds - nominalDuration) <= 1.5 / frame.sampleRateHz else {
return .durationMismatch
}
- guard frame.sampleRateHz == supportedSampleRateHz else { return .unsupportedSampleRate }
+ guard frame.sampleRateHz == self.supportedSampleRateHz else { return .unsupportedSampleRate }
guard frame.samples.allSatisfy({ $0.isFinite }) else { return .nonFiniteSamples }
- guard acceptedFrames + frame.frameCount <= maximumFramesPerTrack else { return .frameLimit }
+ guard acceptedFrames + frame.frameCount <= self.maximumFramesPerTrack else { return .frameLimit }
return nil
}
- // MARK: Constructed-frame seam (offline tests and pre-extracted callbacks)
+ // MARK: - Constructed-frame seam (offline tests and pre-extracted callbacks)
@discardableResult
func appendRenderFrame(_ frame: MeetingStage05AdapterFrame) -> MeetingStage05AdapterRejection? {
- lock.lock(); defer { lock.unlock() }
+ self.lock.lock(); defer { lock.unlock() }
guard let sequence = reserveSequence(cursor: &renderCursor) else { return .blockLimit }
if let rejection = Self.validate(frame, acceptedFrames: renderCursor.acceptedFrames) {
- recordRejection(rejection, cursor: &renderCursor)
+ self.recordRejection(rejection, cursor: &self.renderCursor)
return rejection
}
- detect(frame, cursor: &renderCursor)
- renderFrames.append(MeetingReferencePCMFrame(
+ self.detect(frame, cursor: &self.renderCursor)
+ self.renderFrames.append(MeetingReferencePCMFrame(
sequenceNumber: sequence,
presentationTime: frame.presentationSeconds,
sampleRate: frame.sampleRateHz,
samples: frame.samples,
- discontinuity: frame.discontinuity))
- advance(frame, cursor: &renderCursor)
+ discontinuity: frame.discontinuity
+ ))
+ self.advance(frame, cursor: &self.renderCursor)
return nil
}
@discardableResult
func appendMicrophoneFrame(_ frame: MeetingStage05AdapterFrame) -> MeetingStage05AdapterRejection? {
- lock.lock(); defer { lock.unlock() }
+ self.lock.lock(); defer { lock.unlock() }
guard let sequence = reserveSequence(cursor: &microphoneCursor) else { return .blockLimit }
if let rejection = Self.validate(frame, acceptedFrames: microphoneCursor.acceptedFrames) {
- recordRejection(rejection, cursor: &microphoneCursor)
+ self.recordRejection(rejection, cursor: &self.microphoneCursor)
return rejection
}
// PTS converted to the sample-rate timescale; never cumulative samples written.
@@ -164,33 +165,35 @@ final class MeetingStage05SCKFrameAdapter: @unchecked Sendable {
let roundedScaled = scaled.rounded()
guard roundedScaled.isFinite,
roundedScaled >= Double(Int64.min),
- roundedScaled < Double(Int64.max) else {
- recordRejection(.nonFiniteTiming, cursor: &microphoneCursor)
+ roundedScaled < Double(Int64.max)
+ else {
+ self.recordRejection(.nonFiniteTiming, cursor: &self.microphoneCursor)
return .nonFiniteTiming
}
- detect(frame, cursor: &microphoneCursor)
- microphoneFrames.append(MeetingMicrophonePCMFrame(
+ self.detect(frame, cursor: &self.microphoneCursor)
+ self.microphoneFrames.append(MeetingMicrophonePCMFrame(
sequenceNumber: sequence,
sampleTime: Int64(roundedScaled),
hostTime: frame.arrivalSeconds,
sampleRate: frame.sampleRateHz,
samples: frame.samples,
- routeIdentifier: routeIdentifier,
- discontinuity: frame.discontinuity))
- advance(frame, cursor: &microphoneCursor)
+ routeIdentifier: self.routeIdentifier,
+ discontinuity: frame.discontinuity
+ ))
+ self.advance(frame, cursor: &self.microphoneCursor)
return nil
}
- // MARK: Live CMSampleBuffer entry points
+ // MARK: - Live CMSampleBuffer entry points
@discardableResult
func appendRender(_ sampleBuffer: CMSampleBuffer, arrivalSeconds: Double) -> MeetingStage05AdapterRejection? {
switch Self.extract(sampleBuffer, arrivalSeconds: arrivalSeconds) {
- case .frame(let frame): return appendRenderFrame(frame)
- case .failure(let rejection):
- lock.lock(); defer { lock.unlock() }
- guard reserveSequence(cursor: &renderCursor) != nil else { return .blockLimit }
- recordRejection(rejection, cursor: &renderCursor)
+ case let .frame(frame): return self.appendRenderFrame(frame)
+ case let .failure(rejection):
+ self.lock.lock(); defer { lock.unlock() }
+ guard self.reserveSequence(cursor: &self.renderCursor) != nil else { return .blockLimit }
+ self.recordRejection(rejection, cursor: &self.renderCursor)
return rejection
}
}
@@ -198,11 +201,11 @@ final class MeetingStage05SCKFrameAdapter: @unchecked Sendable {
@discardableResult
func appendMicrophone(_ sampleBuffer: CMSampleBuffer, arrivalSeconds: Double) -> MeetingStage05AdapterRejection? {
switch Self.extract(sampleBuffer, arrivalSeconds: arrivalSeconds) {
- case .frame(let frame): return appendMicrophoneFrame(frame)
- case .failure(let rejection):
- lock.lock(); defer { lock.unlock() }
- guard reserveSequence(cursor: &microphoneCursor) != nil else { return .blockLimit }
- recordRejection(rejection, cursor: &microphoneCursor)
+ case let .frame(frame): return self.appendMicrophoneFrame(frame)
+ case let .failure(rejection):
+ self.lock.lock(); defer { lock.unlock() }
+ guard self.reserveSequence(cursor: &self.microphoneCursor) != nil else { return .blockLimit }
+ self.recordRejection(rejection, cursor: &self.microphoneCursor)
return rejection
}
}
@@ -218,22 +221,33 @@ final class MeetingStage05SCKFrameAdapter: @unchecked Sendable {
return .failure(.unsupportedFormat)
}
let count = CMSampleBufferGetNumSamples(sampleBuffer)
- guard count > 0, count <= maximumFramesPerTrack else { return .failure(.invalidGeometry) }
+ guard count > 0, count <= self.maximumFramesPerTrack else { return .failure(.invalidGeometry) }
let byteCount = count * nativeFormat.bytesPerFrame
var requiredSize = 0
guard CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
- sampleBuffer, bufferListSizeNeededOut: &requiredSize, bufferListOut: nil,
- bufferListSize: 0, blockBufferAllocator: nil, blockBufferMemoryAllocator: nil,
- flags: 0, blockBufferOut: nil) == noErr, requiredSize > 0 else { return .failure(.invalidGeometry) }
+ sampleBuffer,
+ bufferListSizeNeededOut: &requiredSize,
+ bufferListOut: nil,
+ bufferListSize: 0,
+ blockBufferAllocator: nil,
+ blockBufferMemoryAllocator: nil,
+ flags: 0,
+ blockBufferOut: nil
+ ) == noErr, requiredSize > 0 else { return .failure(.invalidGeometry) }
let raw = UnsafeMutableRawPointer.allocate(byteCount: requiredSize, alignment: MemoryLayout<AudioBufferList>.alignment)
defer { raw.deallocate() }
let list = raw.bindMemory(to: AudioBufferList.self, capacity: 1)
var retained: CMBlockBuffer?
guard CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
- sampleBuffer, bufferListSizeNeededOut: nil, bufferListOut: list,
- bufferListSize: requiredSize, blockBufferAllocator: nil, blockBufferMemoryAllocator: nil,
+ sampleBuffer,
+ bufferListSizeNeededOut: nil,
+ bufferListOut: list,
+ bufferListSize: requiredSize,
+ blockBufferAllocator: nil,
+ blockBufferMemoryAllocator: nil,
flags: UInt32(kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment),
- blockBufferOut: &retained) == noErr else { return .failure(.invalidGeometry) }
+ blockBufferOut: &retained
+ ) == noErr else { return .failure(.invalidGeometry) }
let buffers = UnsafeMutableAudioBufferListPointer(list)
guard buffers.count == 1, buffers[0].mNumberChannels == 1,
buffers[0].mDataByteSize == UInt32(byteCount), let pointer = buffers[0].mData
@@ -247,26 +261,28 @@ final class MeetingStage05SCKFrameAdapter: @unchecked Sendable {
sampleRateHz: asbd.mSampleRate,
arrivalSeconds: arrivalSeconds,
samples: samples,
- discontinuity: hasDiscontinuityAttachment(sampleBuffer)))
+ discontinuity: self.hasDiscontinuityAttachment(sampleBuffer)
+ ))
}
static func hasDiscontinuityAttachment(_ sampleBuffer: CMSampleBuffer) -> Bool {
guard let attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, createIfNecessary: false) as? [NSDictionary],
let first = attachments.first else { return false }
- return (first[discontinuityAttachmentKey] as? Bool) == true
+ return (first[self.discontinuityAttachmentKey] as? Bool) == true
}
- // MARK: Drain and synchronize
+ // MARK: - Drain and synchronize
/// Returns the bounded per-track inputs and diagnostics. Call only after both callback
/// queues have been drained; this method performs no queue work itself.
func drain() -> MeetingStage05AdapterDrain {
- lock.lock(); defer { lock.unlock() }
+ self.lock.lock(); defer { lock.unlock() }
return MeetingStage05AdapterDrain(
- microphone: microphoneFrames,
- reference: renderFrames,
- microphoneDiagnostics: microphoneCursor.diagnostics,
- renderDiagnostics: renderCursor.diagnostics)
+ microphone: self.microphoneFrames,
+ reference: self.renderFrames,
+ microphoneDiagnostics: self.microphoneCursor.diagnostics,
+ renderDiagnostics: self.renderCursor.diagnostics
+ )
}
/// Runs the pure synchronizer over the drained callbacks. No clock drift is estimated
@@ -274,16 +290,19 @@ final class MeetingStage05SCKFrameAdapter: @unchecked Sendable {
func synchronize(
configuration: MeetingReferenceSynchronizerConfiguration = .init()
) -> (MeetingStage05AdapterDrain, MeetingSynchronizationResult) {
- let drained = drain()
- return (drained, MeetingReferenceSynchronizer(configuration: configuration)
- .synchronize(microphone: drained.microphone, reference: drained.reference))
+ let drained = self.drain()
+ return (
+ drained,
+ MeetingReferenceSynchronizer(configuration: configuration)
+ .synchronize(microphone: drained.microphone, reference: drained.reference)
+ )
}
- // MARK: Per-callback observation
+ // MARK: - Per-callback observation
private func reserveSequence(cursor: inout Cursor) -> Int? {
guard cursor.nextSequence < Self.maximumBlocksPerTrack else {
- recordRejection(.blockLimit, cursor: &cursor)
+ self.recordRejection(.blockLimit, cursor: &cursor)
return nil
}
let reserved = cursor.nextSequence
diff --git a/Sources/Fluid/Services/Meeting/MeetingTranscriptExporter.swift b/Sources/Fluid/Services/Meeting/MeetingTranscriptExporter.swift
index 9200224a..22ec41e0 100644
--- a/Sources/Fluid/Services/Meeting/MeetingTranscriptExporter.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingTranscriptExporter.swift
@@ -23,7 +23,7 @@ nonisolated enum MeetingTranscriptExporter {
speakerNames: [SessionSpeakerID: String]
) -> String {
guard let state = segment.attributionState else {
- if let name = Self.resolvedSpeakerName(segment.speakerID, in: session, speakerNames: speakerNames) {
+ if let name = resolvedSpeakerName(segment.speakerID, in: session, speakerNames: speakerNames) {
return name
}
return "Unknown speaker"
diff --git a/Sources/Fluid/Services/Meeting/MeetingVPIOAcousticMetrics.swift b/Sources/Fluid/Services/Meeting/MeetingVPIOAcousticMetrics.swift
index a6b279c3..8998a8a3 100644
--- a/Sources/Fluid/Services/Meeting/MeetingVPIOAcousticMetrics.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingVPIOAcousticMetrics.swift
@@ -1,505 +1,505 @@
#if DEBUG
- import Accelerate
- import Foundation
-
- // MARK: - Metric records
-
- nonisolated struct MeetingVPIOAcousticDelayMetrics: Codable, Equatable, Sendable {
- /// Positive means the captured signal lags the rendered reference on the shared host-time
- /// grid. Negative is physically impossible for an acoustic path and therefore evidence of a
- /// timestamp-domain error rather than of a fast echo.
- var signedSeconds: Double?
- var peakToMedianRatio: Double?
- var firstHalfSignedSeconds: Double?
- var secondHalfSignedSeconds: Double?
- /// Half the split-half spread, floored at the sample quantum. Not a confidence interval.
- var uncertaintySeconds: Double?
- var quantizationSeconds: Double
- var maxLagSeconds: Double
- var resolved: Bool
- var reasons: [MeetingVPIOAcousticReason]
- }
-
- nonisolated struct MeetingVPIOAcousticBandMetrics: Codable, Equatable, Sendable {
- var lowHz: Double
- var highHz: Double
- var binCount: Int
- var frameCount: Int
- var supportedCellCount: Int
- /// Share of (frame, bin) cells where the reference actually excited this band. A band with
- /// no excitation cannot report attenuation, however quiet the capture is.
- var supportFraction: Double
- var coherence: Double?
- /// 10·log10(referenceBandEnergy / capturedBandEnergy). Positive means the captured band is
- /// quieter than the rendered band. Uncalibrated: it mixes the electrical reference with an
- /// acoustic capture, so only differences between variants on one unchanged rig are readable.
- var attenuationDB: Double?
- var referenceEnergyFraction: Double
- var capturedEnergyFraction: Double
- var supported: Bool
- var coherent: Bool
- var reasons: [MeetingVPIOAcousticReason]
- }
-
- nonisolated struct MeetingVPIOAcousticMeasurement: Codable, Equatable, Sendable {
- static let currentSchemaVersion = 1
-
- var schemaVersion: Int
- var sampleRate: Double
- var referenceFrameCount: Int
- var capturedFrameCount: Int
- var analysisStartFrame: Int
- var analysisFrameCount: Int
- var referenceRMS: Double
- var referencePeak: Double
- var capturedRMS: Double
- var capturedPeak: Double
- var capturedNoiseFloorRMS: Double?
- var signalToNoiseFloorDB: Double?
- /// Broadband counterpart of `MeetingVPIOAcousticBandMetrics.attenuationDB`, same caveat.
- var attenuationDB: Double?
- var attenuationUncertaintyDB: Double?
- var delay: MeetingVPIOAcousticDelayMetrics
- var bands: [MeetingVPIOAcousticBandMetrics]
- var supportedBandCount: Int
- var coherentBandCount: Int
- /// True only when the delay resolved *and* enough bands were both excited and coherent.
- /// A false `valid` never means "no echo"; it means this measurement says nothing.
- var valid: Bool
- var reasons: [MeetingVPIOAcousticReason]
- }
-
- // MARK: - Metrics
-
- nonisolated enum MeetingVPIOAcousticMetrics {
- static let frameLength = 1_024
- static let hopLength = 512
- static let maxLagSeconds = 0.5
- static let minimumAnalysisFrames = 4_096
- static let minimumReferenceRMS: Float = 1e-4
- static let minimumCapturedRMS: Float = 1e-5
- static let minimumDelayConfidence = MeetingEchoSignalScorer.minimumDelayConfidence
- static let maximumSplitHalfDisagreementSeconds = 0.005
- static let minimumBandSupportFraction = 0.25
- static let minimumBandCoherence = 0.30
- static let minimumCoherentBandCount = 2
- static let minimumBandFrameCount = 8
- /// Fraction of the reference peak that still counts as excitation when bounding the
- /// analysis window; below it the segment is the stimulus's own silence.
- static let excitationOnsetFraction: Float = 0.005
-
- static let bands: [(lowHz: Double, highHz: Double)] = [
- (180, 400), (400, 900), (900, 1_800), (1_800, 3_600), (3_600, 7_800)
- ]
-
- /// `reference` and `captured` share one index origin: index 0 is the same nominal instant on
- /// the host-time grid. `silencePrefixFrames` marks the leading span the reference is known to
- /// be silent in, used for the captured noise floor.
- static func measure(
- reference: [Float],
- captured: [Float],
- sampleRate: Double,
- silencePrefixFrames: Int
- ) -> MeetingVPIOAcousticMeasurement {
- let quantization = sampleRate > 0 ? 1 / sampleRate : 0
- let emptyDelay = MeetingVPIOAcousticDelayMetrics(
- signedSeconds: nil,
- peakToMedianRatio: nil,
- firstHalfSignedSeconds: nil,
- secondHalfSignedSeconds: nil,
- uncertaintySeconds: nil,
- quantizationSeconds: quantization,
- maxLagSeconds: Self.maxLagSeconds,
- resolved: false,
- reasons: []
- )
- var measurement = MeetingVPIOAcousticMeasurement(
- schemaVersion: MeetingVPIOAcousticMeasurement.currentSchemaVersion,
- sampleRate: sampleRate,
- referenceFrameCount: reference.count,
- capturedFrameCount: captured.count,
- analysisStartFrame: 0,
- analysisFrameCount: 0,
- referenceRMS: Double(MeetingVPIOAcousticStimulus.rms(reference)),
- referencePeak: Double(MeetingVPIOAcousticStimulus.peak(reference)),
- capturedRMS: Double(MeetingVPIOAcousticStimulus.rms(captured)),
- capturedPeak: Double(MeetingVPIOAcousticStimulus.peak(captured)),
- capturedNoiseFloorRMS: nil,
- signalToNoiseFloorDB: nil,
- attenuationDB: nil,
- attenuationUncertaintyDB: nil,
- delay: emptyDelay,
- bands: [],
- supportedBandCount: 0,
- coherentBandCount: 0,
- valid: false,
- reasons: []
- )
-
- guard sampleRate > 0,
- reference.count >= Self.minimumAnalysisFrames,
- captured.count >= Self.minimumAnalysisFrames
- else {
- measurement.reasons.append(.insufficientFrames)
- return measurement
- }
- if Float(measurement.referenceRMS) < Self.minimumReferenceRMS {
- measurement.reasons.append(.referenceBelowExcitationFloor)
- }
- if Float(measurement.capturedRMS) < Self.minimumCapturedRMS {
- measurement.reasons.append(.capturedBelowNoiseFloor)
- }
- guard measurement.reasons.isEmpty else { return measurement }
+import Accelerate
+import Foundation
+
+// MARK: - Metric records
+
+nonisolated struct MeetingVPIOAcousticDelayMetrics: Codable, Equatable, Sendable {
+ /// Positive means the captured signal lags the rendered reference on the shared host-time
+ /// grid. Negative is physically impossible for an acoustic path and therefore evidence of a
+ /// timestamp-domain error rather than of a fast echo.
+ var signedSeconds: Double?
+ var peakToMedianRatio: Double?
+ var firstHalfSignedSeconds: Double?
+ var secondHalfSignedSeconds: Double?
+ /// Half the split-half spread, floored at the sample quantum. Not a confidence interval.
+ var uncertaintySeconds: Double?
+ var quantizationSeconds: Double
+ var maxLagSeconds: Double
+ var resolved: Bool
+ var reasons: [MeetingVPIOAcousticReason]
+}
+
+nonisolated struct MeetingVPIOAcousticBandMetrics: Codable, Equatable, Sendable {
+ var lowHz: Double
+ var highHz: Double
+ var binCount: Int
+ var frameCount: Int
+ var supportedCellCount: Int
+ /// Share of (frame, bin) cells where the reference actually excited this band. A band with
+ /// no excitation cannot report attenuation, however quiet the capture is.
+ var supportFraction: Double
+ var coherence: Double?
+ /// 10·log10(referenceBandEnergy / capturedBandEnergy). Positive means the captured band is
+ /// quieter than the rendered band. Uncalibrated: it mixes the electrical reference with an
+ /// acoustic capture, so only differences between variants on one unchanged rig are readable.
+ var attenuationDB: Double?
+ var referenceEnergyFraction: Double
+ var capturedEnergyFraction: Double
+ var supported: Bool
+ var coherent: Bool
+ var reasons: [MeetingVPIOAcousticReason]
+}
+
+nonisolated struct MeetingVPIOAcousticMeasurement: Codable, Equatable, Sendable {
+ static let currentSchemaVersion = 1
+
+ var schemaVersion: Int
+ var sampleRate: Double
+ var referenceFrameCount: Int
+ var capturedFrameCount: Int
+ var analysisStartFrame: Int
+ var analysisFrameCount: Int
+ var referenceRMS: Double
+ var referencePeak: Double
+ var capturedRMS: Double
+ var capturedPeak: Double
+ var capturedNoiseFloorRMS: Double?
+ var signalToNoiseFloorDB: Double?
+ /// Broadband counterpart of `MeetingVPIOAcousticBandMetrics.attenuationDB`, same caveat.
+ var attenuationDB: Double?
+ var attenuationUncertaintyDB: Double?
+ var delay: MeetingVPIOAcousticDelayMetrics
+ var bands: [MeetingVPIOAcousticBandMetrics]
+ var supportedBandCount: Int
+ var coherentBandCount: Int
+ /// True only when the delay resolved *and* enough bands were both excited and coherent.
+ /// A false `valid` never means "no echo"; it means this measurement says nothing.
+ var valid: Bool
+ var reasons: [MeetingVPIOAcousticReason]
+}
+
+// MARK: - Metrics
+
+nonisolated enum MeetingVPIOAcousticMetrics {
+ static let frameLength = 1024
+ static let hopLength = 512
+ static let maxLagSeconds = 0.5
+ static let minimumAnalysisFrames = 4096
+ static let minimumReferenceRMS: Float = 1e-4
+ static let minimumCapturedRMS: Float = 1e-5
+ static let minimumDelayConfidence = MeetingEchoSignalScorer.minimumDelayConfidence
+ static let maximumSplitHalfDisagreementSeconds = 0.005
+ static let minimumBandSupportFraction = 0.25
+ static let minimumBandCoherence = 0.30
+ static let minimumCoherentBandCount = 2
+ static let minimumBandFrameCount = 8
+ /// Fraction of the reference peak that still counts as excitation when bounding the
+ /// analysis window; below it the segment is the stimulus's own silence.
+ static let excitationOnsetFraction: Float = 0.005
+
+ static let bands: [(lowHz: Double, highHz: Double)] = [
+ (180, 400), (400, 900), (900, 1800), (1800, 3600), (3600, 7800),
+ ]
+
+ /// `reference` and `captured` share one index origin: index 0 is the same nominal instant on
+ /// the host-time grid. `silencePrefixFrames` marks the leading span the reference is known to
+ /// be silent in, used for the captured noise floor.
+ static func measure(
+ reference: [Float],
+ captured: [Float],
+ sampleRate: Double,
+ silencePrefixFrames: Int
+ ) -> MeetingVPIOAcousticMeasurement {
+ let quantization = sampleRate > 0 ? 1 / sampleRate : 0
+ let emptyDelay = MeetingVPIOAcousticDelayMetrics(
+ signedSeconds: nil,
+ peakToMedianRatio: nil,
+ firstHalfSignedSeconds: nil,
+ secondHalfSignedSeconds: nil,
+ uncertaintySeconds: nil,
+ quantizationSeconds: quantization,
+ maxLagSeconds: Self.maxLagSeconds,
+ resolved: false,
+ reasons: []
+ )
+ var measurement = MeetingVPIOAcousticMeasurement(
+ schemaVersion: MeetingVPIOAcousticMeasurement.currentSchemaVersion,
+ sampleRate: sampleRate,
+ referenceFrameCount: reference.count,
+ capturedFrameCount: captured.count,
+ analysisStartFrame: 0,
+ analysisFrameCount: 0,
+ referenceRMS: Double(MeetingVPIOAcousticStimulus.rms(reference)),
+ referencePeak: Double(MeetingVPIOAcousticStimulus.peak(reference)),
+ capturedRMS: Double(MeetingVPIOAcousticStimulus.rms(captured)),
+ capturedPeak: Double(MeetingVPIOAcousticStimulus.peak(captured)),
+ capturedNoiseFloorRMS: nil,
+ signalToNoiseFloorDB: nil,
+ attenuationDB: nil,
+ attenuationUncertaintyDB: nil,
+ delay: emptyDelay,
+ bands: [],
+ supportedBandCount: 0,
+ coherentBandCount: 0,
+ valid: false,
+ reasons: []
+ )
+
+ guard sampleRate > 0,
+ reference.count >= Self.minimumAnalysisFrames,
+ captured.count >= Self.minimumAnalysisFrames
+ else {
+ measurement.reasons.append(.insufficientFrames)
+ return measurement
+ }
+ if Float(measurement.referenceRMS) < Self.minimumReferenceRMS {
+ measurement.reasons.append(.referenceBelowExcitationFloor)
+ }
+ if Float(measurement.capturedRMS) < Self.minimumCapturedRMS {
+ measurement.reasons.append(.capturedBelowNoiseFloor)
+ }
+ guard measurement.reasons.isEmpty else { return measurement }
- measurement.delay = Self.estimateDelay(reference: reference, captured: captured, sampleRate: sampleRate)
- measurement.reasons.append(contentsOf: measurement.delay.reasons)
+ measurement.delay = Self.estimateDelay(reference: reference, captured: captured, sampleRate: sampleRate)
+ measurement.reasons.append(contentsOf: measurement.delay.reasons)
- // Unresolved delay still gets band numbers, at zero lag, so the sidecar shows why the
- // run was rejected instead of showing nothing.
- let delayFrames = Int(((measurement.delay.signedSeconds ?? 0) * sampleRate).rounded())
- let aligned = Self.shift(reference, byFrames: delayFrames, targetCount: captured.count)
+ // Unresolved delay still gets band numbers, at zero lag, so the sidecar shows why the
+ // run was rejected instead of showing nothing.
+ let delayFrames = Int(((measurement.delay.signedSeconds ?? 0) * sampleRate).rounded())
+ let aligned = Self.shift(reference, byFrames: delayFrames, targetCount: captured.count)
- guard let analysis = Self.excitedRange(aligned) else {
- measurement.reasons.append(.emptyAnalysisWindow)
- return measurement
- }
- measurement.analysisStartFrame = analysis.lowerBound
- measurement.analysisFrameCount = analysis.count
-
- let alignedWindow = Array(aligned[analysis])
- let capturedWindow = Array(captured[analysis])
- if let floor = Self.noiseFloorRMS(captured, prefixFrames: min(silencePrefixFrames, analysis.lowerBound)) {
- measurement.capturedNoiseFloorRMS = Double(floor)
- measurement.signalToNoiseFloorDB = Self.decibels(
- numerator: MeetingVPIOAcousticStimulus.rms(capturedWindow),
- denominator: floor
- )
- }
- measurement.attenuationDB = Self.decibels(
- numerator: MeetingVPIOAcousticStimulus.rms(alignedWindow),
- denominator: MeetingVPIOAcousticStimulus.rms(capturedWindow)
- )
- measurement.attenuationUncertaintyDB = Self.splitHalfAttenuationSpreadDB(
- reference: alignedWindow,
- captured: capturedWindow
+ guard let analysis = Self.excitedRange(aligned) else {
+ measurement.reasons.append(.emptyAnalysisWindow)
+ return measurement
+ }
+ measurement.analysisStartFrame = analysis.lowerBound
+ measurement.analysisFrameCount = analysis.count
+
+ let alignedWindow = Array(aligned[analysis])
+ let capturedWindow = Array(captured[analysis])
+ if let floor = Self.noiseFloorRMS(captured, prefixFrames: min(silencePrefixFrames, analysis.lowerBound)) {
+ measurement.capturedNoiseFloorRMS = Double(floor)
+ measurement.signalToNoiseFloorDB = Self.decibels(
+ numerator: MeetingVPIOAcousticStimulus.rms(capturedWindow),
+ denominator: floor
)
+ }
+ measurement.attenuationDB = Self.decibels(
+ numerator: MeetingVPIOAcousticStimulus.rms(alignedWindow),
+ denominator: MeetingVPIOAcousticStimulus.rms(capturedWindow)
+ )
+ measurement.attenuationUncertaintyDB = Self.splitHalfAttenuationSpreadDB(
+ reference: alignedWindow,
+ captured: capturedWindow
+ )
+
+ measurement.bands = Self.bandMetrics(
+ reference: alignedWindow,
+ captured: capturedWindow,
+ sampleRate: sampleRate
+ )
+ measurement.supportedBandCount = measurement.bands.filter { $0.supported }.count
+ measurement.coherentBandCount = measurement.bands.filter { $0.coherent }.count
+ if measurement.coherentBandCount < Self.minimumCoherentBandCount {
+ measurement.reasons.append(.tooFewCoherentBands)
+ }
+ measurement.valid = measurement.delay.resolved && measurement.reasons.isEmpty
+ return measurement
+ }
- measurement.bands = Self.bandMetrics(
- reference: alignedWindow,
- captured: capturedWindow,
- sampleRate: sampleRate
- )
- measurement.supportedBandCount = measurement.bands.filter { $0.supported }.count
- measurement.coherentBandCount = measurement.bands.filter { $0.coherent }.count
- if measurement.coherentBandCount < Self.minimumCoherentBandCount {
- measurement.reasons.append(.tooFewCoherentBands)
- }
- measurement.valid = measurement.delay.resolved && measurement.reasons.isEmpty
- return measurement
+ // MARK: - Delay
+
+ private static func estimateDelay(
+ reference: [Float],
+ captured: [Float],
+ sampleRate: Double
+ ) -> MeetingVPIOAcousticDelayMetrics {
+ let quantization = 1 / sampleRate
+ var metrics = MeetingVPIOAcousticDelayMetrics(
+ signedSeconds: nil,
+ peakToMedianRatio: nil,
+ firstHalfSignedSeconds: nil,
+ secondHalfSignedSeconds: nil,
+ uncertaintySeconds: nil,
+ quantizationSeconds: quantization,
+ maxLagSeconds: Self.maxLagSeconds,
+ resolved: false,
+ reasons: []
+ )
+
+ // Shared with the production echo scorer, including its sign convention: the estimate is
+ // the lag of the first argument relative to the second.
+ guard let full = MeetingEchoSignalScorer.estimateDelay(
+ mic: captured,
+ reference: reference,
+ sampleRate: sampleRate,
+ maxLagSeconds: Self.maxLagSeconds
+ ) else {
+ metrics.reasons.append(.delayUnresolved)
+ return metrics
+ }
+ metrics.signedSeconds = full.seconds
+ metrics.peakToMedianRatio = full.confidence
+ if full.seconds < 0 {
+ metrics.reasons.append(.negativeDelay)
}
- // MARK: Delay
-
- private static func estimateDelay(
- reference: [Float],
- captured: [Float],
- sampleRate: Double
- ) -> MeetingVPIOAcousticDelayMetrics {
- let quantization = 1 / sampleRate
- var metrics = MeetingVPIOAcousticDelayMetrics(
- signedSeconds: nil,
- peakToMedianRatio: nil,
- firstHalfSignedSeconds: nil,
- secondHalfSignedSeconds: nil,
- uncertaintySeconds: nil,
- quantizationSeconds: quantization,
- maxLagSeconds: Self.maxLagSeconds,
- resolved: false,
- reasons: []
+ let halfCount = min(reference.count, captured.count) / 2
+ if halfCount >= MeetingEchoSignalScorer.frameLength {
+ let firstHalf = MeetingEchoSignalScorer.estimateDelay(
+ mic: Array(captured[0..<halfCount]),
+ reference: Array(reference[0..<halfCount]),
+ sampleRate: sampleRate,
+ maxLagSeconds: Self.maxLagSeconds
)
-
- // Shared with the production echo scorer, including its sign convention: the estimate is
- // the lag of the first argument relative to the second.
- guard let full = MeetingEchoSignalScorer.estimateDelay(
- mic: captured,
- reference: reference,
+ let secondHalf = MeetingEchoSignalScorer.estimateDelay(
+ mic: Array(captured[halfCount..<(2 * halfCount)]),
+ reference: Array(reference[halfCount..<(2 * halfCount)]),
sampleRate: sampleRate,
maxLagSeconds: Self.maxLagSeconds
- ) else {
- metrics.reasons.append(.delayUnresolved)
- return metrics
- }
- metrics.signedSeconds = full.seconds
- metrics.peakToMedianRatio = full.confidence
- if full.seconds < 0 {
- metrics.reasons.append(.negativeDelay)
- }
-
- let halfCount = min(reference.count, captured.count) / 2
- if halfCount >= MeetingEchoSignalScorer.frameLength {
- let firstHalf = MeetingEchoSignalScorer.estimateDelay(
- mic: Array(captured[0..<halfCount]),
- reference: Array(reference[0..<halfCount]),
- sampleRate: sampleRate,
- maxLagSeconds: Self.maxLagSeconds
- )
- let secondHalf = MeetingEchoSignalScorer.estimateDelay(
- mic: Array(captured[halfCount..<(2 * halfCount)]),
- reference: Array(reference[halfCount..<(2 * halfCount)]),
- sampleRate: sampleRate,
- maxLagSeconds: Self.maxLagSeconds
- )
- metrics.firstHalfSignedSeconds = firstHalf?.seconds
- metrics.secondHalfSignedSeconds = secondHalf?.seconds
- if let first = firstHalf?.seconds, let second = secondHalf?.seconds {
- let spread = abs(first - second) / 2
- metrics.uncertaintySeconds = max(spread, quantization)
- if abs(first - second) > Self.maximumSplitHalfDisagreementSeconds {
- metrics.reasons.append(.splitHalfDelayDisagreement)
- }
+ )
+ metrics.firstHalfSignedSeconds = firstHalf?.seconds
+ metrics.secondHalfSignedSeconds = secondHalf?.seconds
+ if let first = firstHalf?.seconds, let second = secondHalf?.seconds {
+ let spread = abs(first - second) / 2
+ metrics.uncertaintySeconds = max(spread, quantization)
+ if abs(first - second) > Self.maximumSplitHalfDisagreementSeconds {
+ metrics.reasons.append(.splitHalfDelayDisagreement)
}
}
- if metrics.uncertaintySeconds == nil {
- metrics.uncertaintySeconds = quantization
- }
- if full.confidence < Self.minimumDelayConfidence {
- metrics.reasons.append(.delayConfidenceBelowThreshold)
- }
- metrics.resolved = metrics.reasons.isEmpty
- return metrics
}
+ if metrics.uncertaintySeconds == nil {
+ metrics.uncertaintySeconds = quantization
+ }
+ if full.confidence < Self.minimumDelayConfidence {
+ metrics.reasons.append(.delayConfidenceBelowThreshold)
+ }
+ metrics.resolved = metrics.reasons.isEmpty
+ return metrics
+ }
- // MARK: Bands
-
- private static func bandMetrics(
- reference: [Float],
- captured: [Float],
- sampleRate: Double
- ) -> [MeetingVPIOAcousticBandMetrics] {
- guard let spectra = Self.crossSpectra(reference: reference, captured: captured) else {
- return Self.bands.map { band in
- MeetingVPIOAcousticBandMetrics(
- lowHz: band.lowHz,
- highHz: band.highHz,
- binCount: 0,
- frameCount: 0,
- supportedCellCount: 0,
- supportFraction: 0,
- coherence: nil,
- attenuationDB: nil,
- referenceEnergyFraction: 0,
- capturedEnergyFraction: 0,
- supported: false,
- coherent: false,
- reasons: [.insufficientFrames]
- )
- }
- }
-
- let binWidth = sampleRate / Double(Self.frameLength)
- let totalReferenceEnergy = spectra.referencePower.reduce(0, +)
- let totalCapturedEnergy = spectra.capturedPower.reduce(0, +)
-
- return Self.bands.map { band in
- var referenceEnergy = 0.0
- var capturedEnergy = 0.0
- var weightedCoherence = 0.0
- var coherenceWeight = 0.0
- var binCount = 0
- var supportedCells = 0
-
- // Bin 0 carries DC and Nyquist packed together in vDSP's real FFT; never used.
- for bin in 1..<spectra.binCount {
- let frequency = Double(bin) * binWidth
- guard frequency >= band.lowHz, frequency < band.highHz else { continue }
- binCount += 1
- let referencePower = spectra.referencePower[bin]
- let capturedPower = spectra.capturedPower[bin]
- referenceEnergy += referencePower
- capturedEnergy += capturedPower
- supportedCells += spectra.supportedCells[bin]
- guard referencePower > 0, capturedPower > 0 else { continue }
- let crossMagnitudeSquared = spectra.crossReal[bin] * spectra.crossReal[bin]
- + spectra.crossImaginary[bin] * spectra.crossImaginary[bin]
- let coherence = min(1, crossMagnitudeSquared / (referencePower * capturedPower))
- weightedCoherence += coherence * referencePower
- coherenceWeight += referencePower
- }
+ // MARK: - Bands
- let cellCount = binCount * spectra.frameCount
- let supportFraction = cellCount > 0 ? Double(supportedCells) / Double(cellCount) : 0
- let coherence = coherenceWeight > 0 ? weightedCoherence / coherenceWeight : nil
- let supported = supportFraction >= Self.minimumBandSupportFraction
- && spectra.frameCount >= Self.minimumBandFrameCount
- let attenuation = supported && referenceEnergy > 0 && capturedEnergy > 0
- ? 10 * log10(referenceEnergy / capturedEnergy)
- : nil
- var reasons: [MeetingVPIOAcousticReason] = []
- if !supported { reasons.append(.bandSupportBelowThreshold) }
- let coherent = supported && (coherence ?? 0) >= Self.minimumBandCoherence
- if supported, !coherent { reasons.append(.bandCoherenceBelowFloor) }
-
- return MeetingVPIOAcousticBandMetrics(
+ private static func bandMetrics(
+ reference: [Float],
+ captured: [Float],
+ sampleRate: Double
+ ) -> [MeetingVPIOAcousticBandMetrics] {
+ guard let spectra = crossSpectra(reference: reference, captured: captured) else {
+ return self.bands.map { band in
+ MeetingVPIOAcousticBandMetrics(
lowHz: band.lowHz,
highHz: band.highHz,
- binCount: binCount,
- frameCount: spectra.frameCount,
- supportedCellCount: supportedCells,
- supportFraction: supportFraction,
- coherence: coherence,
- attenuationDB: attenuation,
- referenceEnergyFraction: totalReferenceEnergy > 0 ? referenceEnergy / totalReferenceEnergy : 0,
- capturedEnergyFraction: totalCapturedEnergy > 0 ? capturedEnergy / totalCapturedEnergy : 0,
- supported: supported,
- coherent: coherent,
- reasons: reasons
+ binCount: 0,
+ frameCount: 0,
+ supportedCellCount: 0,
+ supportFraction: 0,
+ coherence: nil,
+ attenuationDB: nil,
+ referenceEnergyFraction: 0,
+ capturedEnergyFraction: 0,
+ supported: false,
+ coherent: false,
+ reasons: [.insufficientFrames]
)
}
}
- private struct CrossSpectra {
- var binCount: Int
- var frameCount: Int
- var referencePower: [Double]
- var capturedPower: [Double]
- var crossReal: [Double]
- var crossImaginary: [Double]
- var supportedCells: [Int]
- }
+ let binWidth = sampleRate / Double(Self.frameLength)
+ let totalReferenceEnergy = spectra.referencePower.reduce(0, +)
+ let totalCapturedEnergy = spectra.capturedPower.reduce(0, +)
+
+ return Self.bands.map { band in
+ var referenceEnergy = 0.0
+ var capturedEnergy = 0.0
+ var weightedCoherence = 0.0
+ var coherenceWeight = 0.0
+ var binCount = 0
+ var supportedCells = 0
+
+ // Bin 0 carries DC and Nyquist packed together in vDSP's real FFT; never used.
+ for bin in 1..<spectra.binCount {
+ let frequency = Double(bin) * binWidth
+ guard frequency >= band.lowHz, frequency < band.highHz else { continue }
+ binCount += 1
+ let referencePower = spectra.referencePower[bin]
+ let capturedPower = spectra.capturedPower[bin]
+ referenceEnergy += referencePower
+ capturedEnergy += capturedPower
+ supportedCells += spectra.supportedCells[bin]
+ guard referencePower > 0, capturedPower > 0 else { continue }
+ let crossMagnitudeSquared = spectra.crossReal[bin] * spectra.crossReal[bin]
+ + spectra.crossImaginary[bin] * spectra.crossImaginary[bin]
+ let coherence = min(1, crossMagnitudeSquared / (referencePower * capturedPower))
+ weightedCoherence += coherence * referencePower
+ coherenceWeight += referencePower
+ }
- /// Welch-style accumulation over Hann frames. Absolute scaling is deliberately not undone:
- /// every published number here is a ratio, so vDSP's real-FFT factor cancels.
- private static func crossSpectra(reference: [Float], captured: [Float]) -> CrossSpectra? {
- let count = min(reference.count, captured.count)
- guard count >= Self.frameLength else { return nil }
- let frameCount = (count - Self.frameLength) / Self.hopLength + 1
- guard frameCount > 0 else { return nil }
-
- let log2n = vDSP_Length(log2(Double(Self.frameLength)))
- guard let setup = vDSP_create_fftsetup(log2n, FFTRadix(kFFTRadix2)) else { return nil }
- defer { vDSP_destroy_fftsetup(setup) }
-
- var window = [Float](repeating: 0, count: Self.frameLength)
- vDSP_hann_window(&window, vDSP_Length(Self.frameLength), Int32(vDSP_HANN_NORM))
- var windowPower: Float = 0
- vDSP_svesq(window, 1, &windowPower, vDSP_Length(window.count))
- // Parseval-consistent floor: the same RMS threshold expressed in accumulated bin units.
- let supportFloor = Double(Self.minimumReferenceRMS * Self.minimumReferenceRMS * windowPower)
-
- let binCount = Self.frameLength / 2
- var spectra = CrossSpectra(
+ let cellCount = binCount * spectra.frameCount
+ let supportFraction = cellCount > 0 ? Double(supportedCells) / Double(cellCount) : 0
+ let coherence = coherenceWeight > 0 ? weightedCoherence / coherenceWeight : nil
+ let supported = supportFraction >= Self.minimumBandSupportFraction
+ && spectra.frameCount >= Self.minimumBandFrameCount
+ let attenuation = supported && referenceEnergy > 0 && capturedEnergy > 0
+ ? 10 * log10(referenceEnergy / capturedEnergy)
+ : nil
+ var reasons: [MeetingVPIOAcousticReason] = []
+ if !supported { reasons.append(.bandSupportBelowThreshold) }
+ let coherent = supported && (coherence ?? 0) >= Self.minimumBandCoherence
+ if supported, !coherent { reasons.append(.bandCoherenceBelowFloor) }
+
+ return MeetingVPIOAcousticBandMetrics(
+ lowHz: band.lowHz,
+ highHz: band.highHz,
binCount: binCount,
- frameCount: frameCount,
- referencePower: [Double](repeating: 0, count: binCount),
- capturedPower: [Double](repeating: 0, count: binCount),
- crossReal: [Double](repeating: 0, count: binCount),
- crossImaginary: [Double](repeating: 0, count: binCount),
- supportedCells: [Int](repeating: 0, count: binCount)
+ frameCount: spectra.frameCount,
+ supportedCellCount: supportedCells,
+ supportFraction: supportFraction,
+ coherence: coherence,
+ attenuationDB: attenuation,
+ referenceEnergyFraction: totalReferenceEnergy > 0 ? referenceEnergy / totalReferenceEnergy : 0,
+ capturedEnergyFraction: totalCapturedEnergy > 0 ? capturedEnergy / totalCapturedEnergy : 0,
+ supported: supported,
+ coherent: coherent,
+ reasons: reasons
)
+ }
+ }
- for frame in 0..<frameCount {
- let start = frame * Self.hopLength
- var referenceFrame = [Float](repeating: 0, count: Self.frameLength)
- var capturedFrame = [Float](repeating: 0, count: Self.frameLength)
- vDSP_vmul(Array(reference[start..<start + Self.frameLength]), 1, window, 1, &referenceFrame, 1, vDSP_Length(Self.frameLength))
- vDSP_vmul(Array(captured[start..<start + Self.frameLength]), 1, window, 1, &capturedFrame, 1, vDSP_Length(Self.frameLength))
-
- guard let referenceSpectrum = Self.forwardFFT(&referenceFrame, setup: setup, log2n: log2n),
- let capturedSpectrum = Self.forwardFFT(&capturedFrame, setup: setup, log2n: log2n)
- else { return nil }
-
- for bin in 1..<binCount {
- let rr = Double(referenceSpectrum.real[bin]), ri = Double(referenceSpectrum.imaginary[bin])
- let cr = Double(capturedSpectrum.real[bin]), ci = Double(capturedSpectrum.imaginary[bin])
- let referencePower = rr * rr + ri * ri
- spectra.referencePower[bin] += referencePower
- spectra.capturedPower[bin] += cr * cr + ci * ci
- spectra.crossReal[bin] += cr * rr + ci * ri
- spectra.crossImaginary[bin] += ci * rr - cr * ri
- if referencePower > supportFloor { spectra.supportedCells[bin] += 1 }
- }
+ private struct CrossSpectra {
+ var binCount: Int
+ var frameCount: Int
+ var referencePower: [Double]
+ var capturedPower: [Double]
+ var crossReal: [Double]
+ var crossImaginary: [Double]
+ var supportedCells: [Int]
+ }
+
+ /// Welch-style accumulation over Hann frames. Absolute scaling is deliberately not undone:
+ /// every published number here is a ratio, so vDSP's real-FFT factor cancels.
+ private static func crossSpectra(reference: [Float], captured: [Float]) -> CrossSpectra? {
+ let count = min(reference.count, captured.count)
+ guard count >= Self.frameLength else { return nil }
+ let frameCount = (count - Self.frameLength) / Self.hopLength + 1
+ guard frameCount > 0 else { return nil }
+
+ let log2n = vDSP_Length(log2(Double(Self.frameLength)))
+ guard let setup = vDSP_create_fftsetup(log2n, FFTRadix(kFFTRadix2)) else { return nil }
+ defer { vDSP_destroy_fftsetup(setup) }
+
+ var window = [Float](repeating: 0, count: Self.frameLength)
+ vDSP_hann_window(&window, vDSP_Length(Self.frameLength), Int32(vDSP_HANN_NORM))
+ var windowPower: Float = 0
+ vDSP_svesq(window, 1, &windowPower, vDSP_Length(window.count))
+ // Parseval-consistent floor: the same RMS threshold expressed in accumulated bin units.
+ let supportFloor = Double(Self.minimumReferenceRMS * Self.minimumReferenceRMS * windowPower)
+
+ let binCount = Self.frameLength / 2
+ var spectra = CrossSpectra(
+ binCount: binCount,
+ frameCount: frameCount,
+ referencePower: [Double](repeating: 0, count: binCount),
+ capturedPower: [Double](repeating: 0, count: binCount),
+ crossReal: [Double](repeating: 0, count: binCount),
+ crossImaginary: [Double](repeating: 0, count: binCount),
+ supportedCells: [Int](repeating: 0, count: binCount)
+ )
+
+ for frame in 0..<frameCount {
+ let start = frame * Self.hopLength
+ var referenceFrame = [Float](repeating: 0, count: Self.frameLength)
+ var capturedFrame = [Float](repeating: 0, count: Self.frameLength)
+ vDSP_vmul(Array(reference[start..<start + Self.frameLength]), 1, window, 1, &referenceFrame, 1, vDSP_Length(Self.frameLength))
+ vDSP_vmul(Array(captured[start..<start + Self.frameLength]), 1, window, 1, &capturedFrame, 1, vDSP_Length(Self.frameLength))
+
+ guard let referenceSpectrum = Self.forwardFFT(&referenceFrame, setup: setup, log2n: log2n),
+ let capturedSpectrum = Self.forwardFFT(&capturedFrame, setup: setup, log2n: log2n)
+ else { return nil }
+
+ for bin in 1..<binCount {
+ let rr = Double(referenceSpectrum.real[bin]), ri = Double(referenceSpectrum.imaginary[bin])
+ let cr = Double(capturedSpectrum.real[bin]), ci = Double(capturedSpectrum.imaginary[bin])
+ let referencePower = rr * rr + ri * ri
+ spectra.referencePower[bin] += referencePower
+ spectra.capturedPower[bin] += cr * cr + ci * ci
+ spectra.crossReal[bin] += cr * rr + ci * ri
+ spectra.crossImaginary[bin] += ci * rr - cr * ri
+ if referencePower > supportFloor { spectra.supportedCells[bin] += 1 }
}
- return spectra
}
+ return spectra
+ }
- private struct Spectrum {
- var real: [Float]
- var imaginary: [Float]
- }
+ private struct Spectrum {
+ var real: [Float]
+ var imaginary: [Float]
+ }
- private static func forwardFFT(_ signal: inout [Float], setup: FFTSetup, log2n: vDSP_Length) -> Spectrum? {
- let halfCount = Self.frameLength / 2
- var real = [Float](repeating: 0, count: halfCount)
- var imaginary = [Float](repeating: 0, count: halfCount)
- var spectrum: Spectrum?
- real.withUnsafeMutableBufferPointer { realPointer in
- imaginary.withUnsafeMutableBufferPointer { imaginaryPointer in
- guard let realBase = realPointer.baseAddress, let imaginaryBase = imaginaryPointer.baseAddress else { return }
- var split = DSPSplitComplex(realp: realBase, imagp: imaginaryBase)
- signal.withUnsafeBufferPointer { signalPointer in
- guard let signalBase = signalPointer.baseAddress else { return }
- signalBase.withMemoryRebound(to: DSPComplex.self, capacity: halfCount) { complexPointer in
- vDSP_ctoz(complexPointer, 2, &split, 1, vDSP_Length(halfCount))
- }
+ private static func forwardFFT(_ signal: inout [Float], setup: FFTSetup, log2n: vDSP_Length) -> Spectrum? {
+ let halfCount = Self.frameLength / 2
+ var real = [Float](repeating: 0, count: halfCount)
+ var imaginary = [Float](repeating: 0, count: halfCount)
+ var spectrum: Spectrum?
+ real.withUnsafeMutableBufferPointer { realPointer in
+ imaginary.withUnsafeMutableBufferPointer { imaginaryPointer in
+ guard let realBase = realPointer.baseAddress, let imaginaryBase = imaginaryPointer.baseAddress else { return }
+ var split = DSPSplitComplex(realp: realBase, imagp: imaginaryBase)
+ signal.withUnsafeBufferPointer { signalPointer in
+ guard let signalBase = signalPointer.baseAddress else { return }
+ signalBase.withMemoryRebound(to: DSPComplex.self, capacity: halfCount) { complexPointer in
+ vDSP_ctoz(complexPointer, 2, &split, 1, vDSP_Length(halfCount))
}
- vDSP_fft_zrip(setup, &split, 1, log2n, FFTDirection(FFT_FORWARD))
- spectrum = Spectrum(real: Array(realPointer), imaginary: Array(imaginaryPointer))
}
+ vDSP_fft_zrip(setup, &split, 1, log2n, FFTDirection(FFT_FORWARD))
+ spectrum = Spectrum(real: Array(realPointer), imaginary: Array(imaginaryPointer))
}
- return spectrum
}
+ return spectrum
+ }
- // MARK: Helpers
+ // MARK: - Helpers
- private static func shift(_ signal: [Float], byFrames frames: Int, targetCount: Int) -> [Float] {
- var result = [Float](repeating: 0, count: targetCount)
- for index in 0..<targetCount {
- let source = index - frames
- guard source >= 0, source < signal.count else { continue }
- result[index] = signal[source]
- }
- return result
+ private static func shift(_ signal: [Float], byFrames frames: Int, targetCount: Int) -> [Float] {
+ var result = [Float](repeating: 0, count: targetCount)
+ for index in 0..<targetCount {
+ let source = index - frames
+ guard source >= 0, source < signal.count else { continue }
+ result[index] = signal[source]
}
+ return result
+ }
- /// Span the reference actually excites, so the RMS ratio is not diluted by the stimulus's
- /// own leading and trailing silence.
- private static func excitedRange(_ signal: [Float]) -> Range<Int>? {
- let peak = MeetingVPIOAcousticStimulus.peak(signal)
- guard peak > 0 else { return nil }
- let threshold = peak * Self.excitationOnsetFraction
- guard let first = signal.firstIndex(where: { abs($0) > threshold }),
- let last = signal.lastIndex(where: { abs($0) > threshold }),
- last > first
- else { return nil }
- return first..<(last + 1)
- }
+ /// Span the reference actually excites, so the RMS ratio is not diluted by the stimulus's
+ /// own leading and trailing silence.
+ private static func excitedRange(_ signal: [Float]) -> Range<Int>? {
+ let peak = MeetingVPIOAcousticStimulus.peak(signal)
+ guard peak > 0 else { return nil }
+ let threshold = peak * Self.excitationOnsetFraction
+ guard let first = signal.firstIndex(where: { abs($0) > threshold }),
+ let last = signal.lastIndex(where: { abs($0) > threshold }),
+ last > first
+ else { return nil }
+ return first..<(last + 1)
+ }
- private static func noiseFloorRMS(_ captured: [Float], prefixFrames: Int) -> Float? {
- guard prefixFrames >= Self.hopLength, prefixFrames <= captured.count else { return nil }
- return MeetingVPIOAcousticStimulus.rms(Array(captured[0..<prefixFrames]))
- }
+ private static func noiseFloorRMS(_ captured: [Float], prefixFrames: Int) -> Float? {
+ guard prefixFrames >= self.hopLength, prefixFrames <= captured.count else { return nil }
+ return MeetingVPIOAcousticStimulus.rms(Array(captured[0..<prefixFrames]))
+ }
- private static func decibels(numerator: Float, denominator: Float) -> Double? {
- guard numerator > 0, denominator > 0 else { return nil }
- return 20 * log10(Double(numerator) / Double(denominator))
- }
+ private static func decibels(numerator: Float, denominator: Float) -> Double? {
+ guard numerator > 0, denominator > 0 else { return nil }
+ return 20 * log10(Double(numerator) / Double(denominator))
+ }
- /// Spread between the two halves of the analysis window. Widens whenever gain drifted
- /// (AGC) or the acoustic path moved mid-stimulus; it is a stability figure, not a CI.
- private static func splitHalfAttenuationSpreadDB(reference: [Float], captured: [Float]) -> Double? {
- let count = min(reference.count, captured.count)
- let half = count / 2
- guard half >= Self.hopLength else { return nil }
- guard let first = Self.decibels(
- numerator: MeetingVPIOAcousticStimulus.rms(Array(reference[0..<half])),
- denominator: MeetingVPIOAcousticStimulus.rms(Array(captured[0..<half]))
- ), let second = Self.decibels(
- numerator: MeetingVPIOAcousticStimulus.rms(Array(reference[half..<(2 * half)])),
- denominator: MeetingVPIOAcousticStimulus.rms(Array(captured[half..<(2 * half)]))
- ) else { return nil }
- return abs(first - second) / 2
- }
+ /// Spread between the two halves of the analysis window. Widens whenever gain drifted
+ /// (AGC) or the acoustic path moved mid-stimulus; it is a stability figure, not a CI.
+ private static func splitHalfAttenuationSpreadDB(reference: [Float], captured: [Float]) -> Double? {
+ let count = min(reference.count, captured.count)
+ let half = count / 2
+ guard half >= Self.hopLength else { return nil }
+ guard let first = Self.decibels(
+ numerator: MeetingVPIOAcousticStimulus.rms(Array(reference[0..<half])),
+ denominator: MeetingVPIOAcousticStimulus.rms(Array(captured[0..<half]))
+ ), let second = Self.decibels(
+ numerator: MeetingVPIOAcousticStimulus.rms(Array(reference[half..<(2 * half)])),
+ denominator: MeetingVPIOAcousticStimulus.rms(Array(captured[half..<(2 * half)]))
+ ) else { return nil }
+ return abs(first - second) / 2
}
+}
#endif
diff --git a/Sources/Fluid/Services/Meeting/MeetingVPIOAcousticStimulus.swift b/Sources/Fluid/Services/Meeting/MeetingVPIOAcousticStimulus.swift
index 6302eef1..9edbc2e7 100644
--- a/Sources/Fluid/Services/Meeting/MeetingVPIOAcousticStimulus.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingVPIOAcousticStimulus.swift
@@ -1,301 +1,301 @@
#if DEBUG
- import Accelerate
- import Foundation
-
- // MARK: - Reason codes
-
- /// Machine-stable reasons. Every unusable number carries one; absence of a reason is never
- /// how a caller learns a metric was skipped.
- nonisolated enum MeetingVPIOAcousticReason: String, Codable, Sendable {
- case insufficientFrames
- case referenceBelowExcitationFloor
- case capturedBelowNoiseFloor
- case delayUnresolved
- case delayConfidenceBelowThreshold
- case splitHalfDelayDisagreement
- case emptyAnalysisWindow
- case bandSupportBelowThreshold
- case bandCoherenceBelowFloor
- case tooFewCoherentBands
- case captureWindowIncomplete
- case renderStartUnresolved
- case renderReadbackSilent
- case controlNotApplied
- case stimulusOutsideSafetyBounds
- case captureNotRunning
- case probeDisabled
- case outputRouteUnavailable
- case outputVolumeUnreadable
- case outputLevelUnsafe
- case renderTimingInvalid
- case playbackTimedOut
- case negativeDelay
- case captureGap
- case captureOverlap
- /// The sample values are present, but their PTS was synthesized while host time was
- /// unavailable. They are not valid evidence for a shared-clock delay measurement.
- case captureTimingSynthesized
- /// A synthesized timing run has not yet reached a valid host-time resynchronization.
- case captureTimingResyncRequired
- case probeCancelled
- }
-
- // MARK: - Stimulus
-
- /// Numeric description of the rendered stimulus. Records what was actually synthesized, not
- /// what was requested: `measuredPeak`/`measuredRMS` are computed from the emitted samples.
- nonisolated struct MeetingVPIOAcousticStimulusDescriptor: Codable, Equatable, Sendable {
- static let currentSchemaVersion = 1
-
- var schemaVersion: Int
- var seed: UInt64
- var sampleRate: Double
- var totalFrameCount: Int
- var leadingSilenceFrameCount: Int
- var chirpFrameCount: Int
- var gapFrameCount: Int
- var speechLikeFrameCount: Int
- var trailingSilenceFrameCount: Int
- var chirpStartHz: Double
- var chirpEndHz: Double
- var speechF0StartHz: Double
- var speechF0EndHz: Double
- var targetPeak: Double
- var measuredPeak: Double
- var measuredRMS: Double
- var safetyPeakLimit: Double
- var safetyMinimumRMS: Double
- var safetyMaximumRMS: Double
- var withinSafetyBounds: Bool
- }
-
- /// Deterministic diagnostic stimulus: a log sweep (alignment-rich, broadband) followed by a
- /// speech-like voiced/fricative segment (representative of what VPIO is tuned for). Identical
- /// bytes for identical `seed` and `sampleRate` so two runs are directly comparable.
- nonisolated enum MeetingVPIOAcousticStimulus {
- static let defaultSeed: UInt64 = 0x5F1D_A00D_C0DE_0001
-
- /// Bounded so a diagnostic can never drive the speaker into an uncomfortable level. The
- /// runner refuses to render a stimulus that lands outside these.
- static let targetPeak: Float = 0.25
- static let safetyPeakLimit: Float = 0.35
- static let safetyMinimumRMS: Float = 0.02
- static let safetyMaximumRMS: Float = 0.15
- /// Player gain applied on top of the already-bounded stimulus.
- static let maximumRenderVolume: Float = 0.6
-
- static let leadingSilenceSeconds = 0.20
- static let chirpSeconds = 1.00
- static let gapSeconds = 0.20
- static let speechLikeSeconds = 1.20
- static let trailingSilenceSeconds = 0.30
-
- static let chirpStartHz = 180.0
- static let chirpEndHz = 7_800.0
- static let speechF0StartHz = 115.0
- static let speechF0EndHz = 145.0
-
- nonisolated struct Generated: Equatable, Sendable {
- var samples: [Float]
- var descriptor: MeetingVPIOAcousticStimulusDescriptor
-
- var totalSeconds: Double {
- self.descriptor.sampleRate > 0
- ? Double(self.descriptor.totalFrameCount) / self.descriptor.sampleRate
- : 0
- }
+import Accelerate
+import Foundation
+
+// MARK: - Reason codes
+
+/// Machine-stable reasons. Every unusable number carries one; absence of a reason is never
+/// how a caller learns a metric was skipped.
+nonisolated enum MeetingVPIOAcousticReason: String, Codable, Sendable {
+ case insufficientFrames
+ case referenceBelowExcitationFloor
+ case capturedBelowNoiseFloor
+ case delayUnresolved
+ case delayConfidenceBelowThreshold
+ case splitHalfDelayDisagreement
+ case emptyAnalysisWindow
+ case bandSupportBelowThreshold
+ case bandCoherenceBelowFloor
+ case tooFewCoherentBands
+ case captureWindowIncomplete
+ case renderStartUnresolved
+ case renderReadbackSilent
+ case controlNotApplied
+ case stimulusOutsideSafetyBounds
+ case captureNotRunning
+ case probeDisabled
+ case outputRouteUnavailable
+ case outputVolumeUnreadable
+ case outputLevelUnsafe
+ case renderTimingInvalid
+ case playbackTimedOut
+ case negativeDelay
+ case captureGap
+ case captureOverlap
+ /// The sample values are present, but their PTS was synthesized while host time was
+ /// unavailable. They are not valid evidence for a shared-clock delay measurement.
+ case captureTimingSynthesized
+ /// A synthesized timing run has not yet reached a valid host-time resynchronization.
+ case captureTimingResyncRequired
+ case probeCancelled
+}
+
+// MARK: - Stimulus
+
+/// Numeric description of the rendered stimulus. Records what was actually synthesized, not
+/// what was requested: `measuredPeak`/`measuredRMS` are computed from the emitted samples.
+nonisolated struct MeetingVPIOAcousticStimulusDescriptor: Codable, Equatable, Sendable {
+ static let currentSchemaVersion = 1
+
+ var schemaVersion: Int
+ var seed: UInt64
+ var sampleRate: Double
+ var totalFrameCount: Int
+ var leadingSilenceFrameCount: Int
+ var chirpFrameCount: Int
+ var gapFrameCount: Int
+ var speechLikeFrameCount: Int
+ var trailingSilenceFrameCount: Int
+ var chirpStartHz: Double
+ var chirpEndHz: Double
+ var speechF0StartHz: Double
+ var speechF0EndHz: Double
+ var targetPeak: Double
+ var measuredPeak: Double
+ var measuredRMS: Double
+ var safetyPeakLimit: Double
+ var safetyMinimumRMS: Double
+ var safetyMaximumRMS: Double
+ var withinSafetyBounds: Bool
+}
+
+/// Deterministic diagnostic stimulus: a log sweep (alignment-rich, broadband) followed by a
+/// speech-like voiced/fricative segment (representative of what VPIO is tuned for). Identical
+/// bytes for identical `seed` and `sampleRate` so two runs are directly comparable.
+nonisolated enum MeetingVPIOAcousticStimulus {
+ static let defaultSeed: UInt64 = 0x5f1da00dc0de0001
+
+ /// Bounded so a diagnostic can never drive the speaker into an uncomfortable level. The
+ /// runner refuses to render a stimulus that lands outside these.
+ static let targetPeak: Float = 0.25
+ static let safetyPeakLimit: Float = 0.35
+ static let safetyMinimumRMS: Float = 0.02
+ static let safetyMaximumRMS: Float = 0.15
+ /// Player gain applied on top of the already-bounded stimulus.
+ static let maximumRenderVolume: Float = 0.6
+
+ static let leadingSilenceSeconds = 0.20
+ static let chirpSeconds = 1.00
+ static let gapSeconds = 0.20
+ static let speechLikeSeconds = 1.20
+ static let trailingSilenceSeconds = 0.30
+
+ static let chirpStartHz = 180.0
+ static let chirpEndHz = 7800.0
+ static let speechF0StartHz = 115.0
+ static let speechF0EndHz = 145.0
+
+ nonisolated struct Generated: Equatable, Sendable {
+ var samples: [Float]
+ var descriptor: MeetingVPIOAcousticStimulusDescriptor
+
+ var totalSeconds: Double {
+ self.descriptor.sampleRate > 0
+ ? Double(self.descriptor.totalFrameCount) / self.descriptor.sampleRate
+ : 0
}
+ }
- static func make(sampleRate: Double, seed: UInt64 = MeetingVPIOAcousticStimulus.defaultSeed) -> Generated? {
- guard sampleRate >= 8_000, sampleRate <= 192_000 else { return nil }
+ static func make(sampleRate: Double, seed: UInt64 = MeetingVPIOAcousticStimulus.defaultSeed) -> Generated? {
+ guard sampleRate >= 8000, sampleRate <= 192_000 else { return nil }
- let lead = Self.frames(Self.leadingSilenceSeconds, sampleRate)
- let chirp = Self.frames(Self.chirpSeconds, sampleRate)
- let gap = Self.frames(Self.gapSeconds, sampleRate)
- let speech = Self.frames(Self.speechLikeSeconds, sampleRate)
- let trail = Self.frames(Self.trailingSilenceSeconds, sampleRate)
+ let lead = Self.frames(Self.leadingSilenceSeconds, sampleRate)
+ let chirp = Self.frames(Self.chirpSeconds, sampleRate)
+ let gap = Self.frames(Self.gapSeconds, sampleRate)
+ let speech = Self.frames(Self.speechLikeSeconds, sampleRate)
+ let trail = Self.frames(Self.trailingSilenceSeconds, sampleRate)
- var samples = [Float](repeating: 0, count: lead + chirp + gap + speech + trail)
- Self.writeLogSweep(into: &samples, at: lead, count: chirp, sampleRate: sampleRate)
- Self.writeSpeechLike(into: &samples, at: lead + chirp + gap, count: speech, sampleRate: sampleRate, seed: seed)
+ var samples = [Float](repeating: 0, count: lead + chirp + gap + speech + trail)
+ Self.writeLogSweep(into: &samples, at: lead, count: chirp, sampleRate: sampleRate)
+ Self.writeSpeechLike(into: &samples, at: lead + chirp + gap, count: speech, sampleRate: sampleRate, seed: seed)
- var peak: Float = 0
- vDSP_maxmgv(samples, 1, &peak, vDSP_Length(samples.count))
- if peak > 0 {
- var scale = Self.targetPeak / peak
- vDSP_vsmul(samples, 1, &scale, &samples, 1, vDSP_Length(samples.count))
- }
- // Belt-and-braces against a future segment change: never emit past the safety ceiling.
- var lowerLimit = -Self.safetyPeakLimit
- var upperLimit = Self.safetyPeakLimit
- vDSP_vclip(samples, 1, &lowerLimit, &upperLimit, &samples, 1, vDSP_Length(samples.count))
-
- let measuredPeak = Self.peak(samples)
- let measuredRMS = Self.rms(samples)
- let withinBounds = measuredPeak <= Self.safetyPeakLimit
- && measuredRMS >= Self.safetyMinimumRMS
- && measuredRMS <= Self.safetyMaximumRMS
-
- return Generated(
- samples: samples,
- descriptor: MeetingVPIOAcousticStimulusDescriptor(
- schemaVersion: MeetingVPIOAcousticStimulusDescriptor.currentSchemaVersion,
- seed: seed,
- sampleRate: sampleRate,
- totalFrameCount: samples.count,
- leadingSilenceFrameCount: lead,
- chirpFrameCount: chirp,
- gapFrameCount: gap,
- speechLikeFrameCount: speech,
- trailingSilenceFrameCount: trail,
- chirpStartHz: Self.chirpStartHz,
- chirpEndHz: Self.chirpEndHz,
- speechF0StartHz: Self.speechF0StartHz,
- speechF0EndHz: Self.speechF0EndHz,
- targetPeak: Double(Self.targetPeak),
- measuredPeak: Double(measuredPeak),
- measuredRMS: Double(measuredRMS),
- safetyPeakLimit: Double(Self.safetyPeakLimit),
- safetyMinimumRMS: Double(Self.safetyMinimumRMS),
- safetyMaximumRMS: Double(Self.safetyMaximumRMS),
- withinSafetyBounds: withinBounds
- )
- )
+ var peak: Float = 0
+ vDSP_maxmgv(samples, 1, &peak, vDSP_Length(samples.count))
+ if peak > 0 {
+ var scale = Self.targetPeak / peak
+ vDSP_vsmul(samples, 1, &scale, &samples, 1, vDSP_Length(samples.count))
}
+ // Belt-and-braces against a future segment change: never emit past the safety ceiling.
+ var lowerLimit = -Self.safetyPeakLimit
+ var upperLimit = Self.safetyPeakLimit
+ vDSP_vclip(samples, 1, &lowerLimit, &upperLimit, &samples, 1, vDSP_Length(samples.count))
+
+ let measuredPeak = Self.peak(samples)
+ let measuredRMS = Self.rms(samples)
+ let withinBounds = measuredPeak <= Self.safetyPeakLimit
+ && measuredRMS >= Self.safetyMinimumRMS
+ && measuredRMS <= Self.safetyMaximumRMS
+
+ return Generated(
+ samples: samples,
+ descriptor: MeetingVPIOAcousticStimulusDescriptor(
+ schemaVersion: MeetingVPIOAcousticStimulusDescriptor.currentSchemaVersion,
+ seed: seed,
+ sampleRate: sampleRate,
+ totalFrameCount: samples.count,
+ leadingSilenceFrameCount: lead,
+ chirpFrameCount: chirp,
+ gapFrameCount: gap,
+ speechLikeFrameCount: speech,
+ trailingSilenceFrameCount: trail,
+ chirpStartHz: Self.chirpStartHz,
+ chirpEndHz: Self.chirpEndHz,
+ speechF0StartHz: Self.speechF0StartHz,
+ speechF0EndHz: Self.speechF0EndHz,
+ targetPeak: Double(Self.targetPeak),
+ measuredPeak: Double(measuredPeak),
+ measuredRMS: Double(measuredRMS),
+ safetyPeakLimit: Double(Self.safetyPeakLimit),
+ safetyMinimumRMS: Double(Self.safetyMinimumRMS),
+ safetyMaximumRMS: Double(Self.safetyMaximumRMS),
+ withinSafetyBounds: withinBounds
+ )
+ )
+ }
- private static func frames(_ seconds: Double, _ sampleRate: Double) -> Int {
- max(0, Int((seconds * sampleRate).rounded()))
- }
+ private static func frames(_ seconds: Double, _ sampleRate: Double) -> Int {
+ max(0, Int((seconds * sampleRate).rounded()))
+ }
- /// Exponential sweep: constant energy per octave, so every analysis band gets excitation
- /// and the autocorrelation peak stays narrow enough to time-align on.
- private static func writeLogSweep(into samples: inout [Float], at offset: Int, count: Int, sampleRate: Double) {
- guard count > 1 else { return }
- let duration = Double(count) / sampleRate
- let ratio = Self.chirpEndHz / Self.chirpStartHz
- let logRatio = log(ratio)
- let fadeFrames = min(count / 4, Self.frames(0.010, sampleRate))
- for i in 0..<count {
- let t = Double(i) / sampleRate
- let phase = 2 * Double.pi * Self.chirpStartHz * duration / logRatio * (pow(ratio, t / duration) - 1)
- let value = sin(phase) * Self.fadeEnvelope(index: i, count: count, fadeFrames: fadeFrames)
- samples[offset + i] = Float(value)
- }
+ /// Exponential sweep: constant energy per octave, so every analysis band gets excitation
+ /// and the autocorrelation peak stays narrow enough to time-align on.
+ private static func writeLogSweep(into samples: inout [Float], at offset: Int, count: Int, sampleRate: Double) {
+ guard count > 1 else { return }
+ let duration = Double(count) / sampleRate
+ let ratio = Self.chirpEndHz / Self.chirpStartHz
+ let logRatio = log(ratio)
+ let fadeFrames = min(count / 4, Self.frames(0.010, sampleRate))
+ for i in 0..<count {
+ let t = Double(i) / sampleRate
+ let phase = 2 * Double.pi * Self.chirpStartHz * duration / logRatio * (pow(ratio, t / duration) - 1)
+ let value = sin(phase) * Self.fadeEnvelope(index: i, count: count, fadeFrames: fadeFrames)
+ samples[offset + i] = Float(value)
}
+ }
- /// Voiced harmonic stack under fixed formants, a syllabic envelope, and two deterministic
- /// fricative bursts. Not speech — a signal whose spectrum and modulation resemble it.
- private static func writeSpeechLike(
- into samples: inout [Float],
- at offset: Int,
- count: Int,
- sampleRate: Double,
- seed: UInt64
- ) {
- guard count > 1 else { return }
- let duration = Double(count) / sampleRate
- let formants: [(center: Double, bandwidth: Double, gain: Double)] = [
- (500, 140, 1.0), (1_500, 220, 0.55), (2_600, 320, 0.30)
- ]
- let fadeFrames = min(count / 4, Self.frames(0.020, sampleRate))
- let nyquist = sampleRate / 2
- var generator = MeetingVPIOAcousticPRNG(seed: seed)
- var previousNoise = 0.0
- var phase = 0.0
-
- for i in 0..<count {
- let t = Double(i) / sampleRate
- let progress = t / duration
- let f0 = Self.speechF0StartHz + (Self.speechF0EndHz - Self.speechF0StartHz) * progress
- phase += 2 * Double.pi * f0 / sampleRate
-
- var voiced = 0.0
- var harmonic = 1
- while Double(harmonic) * f0 < min(nyquist, 8_000) {
- let frequency = Double(harmonic) * f0
- var weight = 0.0
- for formant in formants {
- let offsetHz = (frequency - formant.center) / formant.bandwidth
- weight += formant.gain * exp(-offsetHz * offsetHz)
- }
- // 1/h source tilt on top of the formant envelope.
- voiced += weight * sin(phase * Double(harmonic)) / Double(harmonic)
- harmonic += 1
+ /// Voiced harmonic stack under fixed formants, a syllabic envelope, and two deterministic
+ /// fricative bursts. Not speech — a signal whose spectrum and modulation resemble it.
+ private static func writeSpeechLike(
+ into samples: inout [Float],
+ at offset: Int,
+ count: Int,
+ sampleRate: Double,
+ seed: UInt64
+ ) {
+ guard count > 1 else { return }
+ let duration = Double(count) / sampleRate
+ let formants: [(center: Double, bandwidth: Double, gain: Double)] = [
+ (500, 140, 1.0), (1500, 220, 0.55), (2600, 320, 0.30),
+ ]
+ let fadeFrames = min(count / 4, Self.frames(0.020, sampleRate))
+ let nyquist = sampleRate / 2
+ var generator = MeetingVPIOAcousticPRNG(seed: seed)
+ var previousNoise = 0.0
+ var phase = 0.0
+
+ for i in 0..<count {
+ let t = Double(i) / sampleRate
+ let progress = t / duration
+ let f0 = Self.speechF0StartHz + (Self.speechF0EndHz - Self.speechF0StartHz) * progress
+ phase += 2 * Double.pi * f0 / sampleRate
+
+ var voiced = 0.0
+ var harmonic = 1
+ while Double(harmonic) * f0 < min(nyquist, 8000) {
+ let frequency = Double(harmonic) * f0
+ var weight = 0.0
+ for formant in formants {
+ let offsetHz = (frequency - formant.center) / formant.bandwidth
+ weight += formant.gain * exp(-offsetHz * offsetHz)
}
+ // 1/h source tilt on top of the formant envelope.
+ voiced += weight * sin(phase * Double(harmonic)) / Double(harmonic)
+ harmonic += 1
+ }
- // First-difference tilt turns flat PRNG noise into a fricative-shaped band.
- let white = generator.nextSymmetricUnit()
- let tilted = white - previousNoise
- previousNoise = white
- let fricative = tilted * Self.fricativeEnvelope(progress: progress)
+ // First-difference tilt turns flat PRNG noise into a fricative-shaped band.
+ let white = generator.nextSymmetricUnit()
+ let tilted = white - previousNoise
+ previousNoise = white
+ let fricative = tilted * Self.fricativeEnvelope(progress: progress)
- let syllabic = 0.35 + 0.65 * (0.5 - 0.5 * cos(2 * Double.pi * 3.5 * t))
- let value = (voiced * syllabic + fricative * 0.5)
- * Self.fadeEnvelope(index: i, count: count, fadeFrames: fadeFrames)
- samples[offset + i] = Float(value)
- }
+ let syllabic = 0.35 + 0.65 * (0.5 - 0.5 * cos(2 * Double.pi * 3.5 * t))
+ let value = (voiced * syllabic + fricative * 0.5)
+ * Self.fadeEnvelope(index: i, count: count, fadeFrames: fadeFrames)
+ samples[offset + i] = Float(value)
}
+ }
- /// Two fixed bursts; deterministic in `progress` so the descriptor fully predicts them.
- private static func fricativeEnvelope(progress: Double) -> Double {
- let bursts = [(start: 0.22, end: 0.30), (start: 0.62, end: 0.72)]
- for burst in bursts where progress >= burst.start && progress < burst.end {
- let local = (progress - burst.start) / (burst.end - burst.start)
- return 0.5 - 0.5 * cos(2 * Double.pi * local)
- }
- return 0
+ /// Two fixed bursts; deterministic in `progress` so the descriptor fully predicts them.
+ private static func fricativeEnvelope(progress: Double) -> Double {
+ let bursts = [(start: 0.22, end: 0.30), (start: 0.62, end: 0.72)]
+ for burst in bursts where progress >= burst.start && progress < burst.end {
+ let local = (progress - burst.start) / (burst.end - burst.start)
+ return 0.5 - 0.5 * cos(2 * Double.pi * local)
}
+ return 0
+ }
- private static func fadeEnvelope(index: Int, count: Int, fadeFrames: Int) -> Double {
- guard fadeFrames > 0 else { return 1 }
- if index < fadeFrames {
- return 0.5 - 0.5 * cos(Double.pi * Double(index) / Double(fadeFrames))
- }
- let tail = count - 1 - index
- if tail < fadeFrames {
- return 0.5 - 0.5 * cos(Double.pi * Double(tail) / Double(fadeFrames))
- }
- return 1
+ private static func fadeEnvelope(index: Int, count: Int, fadeFrames: Int) -> Double {
+ guard fadeFrames > 0 else { return 1 }
+ if index < fadeFrames {
+ return 0.5 - 0.5 * cos(Double.pi * Double(index) / Double(fadeFrames))
}
-
- static func rms(_ signal: [Float]) -> Float {
- guard !signal.isEmpty else { return 0 }
- var meanSquare: Float = 0
- vDSP_measqv(signal, 1, &meanSquare, vDSP_Length(signal.count))
- return sqrt(meanSquare)
+ let tail = count - 1 - index
+ if tail < fadeFrames {
+ return 0.5 - 0.5 * cos(Double.pi * Double(tail) / Double(fadeFrames))
}
+ return 1
+ }
- static func peak(_ signal: [Float]) -> Float {
- guard !signal.isEmpty else { return 0 }
- var value: Float = 0
- vDSP_maxmgv(signal, 1, &value, vDSP_Length(signal.count))
- return value
- }
+ static func rms(_ signal: [Float]) -> Float {
+ guard !signal.isEmpty else { return 0 }
+ var meanSquare: Float = 0
+ vDSP_measqv(signal, 1, &meanSquare, vDSP_Length(signal.count))
+ return sqrt(meanSquare)
}
- /// SplitMix64. Foundation's RNG is seeded per-process; a probe stimulus must be reproducible
- /// across processes and machines.
- nonisolated struct MeetingVPIOAcousticPRNG {
- private var state: UInt64
+ static func peak(_ signal: [Float]) -> Float {
+ guard !signal.isEmpty else { return 0 }
+ var value: Float = 0
+ vDSP_maxmgv(signal, 1, &value, vDSP_Length(signal.count))
+ return value
+ }
+}
- init(seed: UInt64) {
- self.state = seed
- }
+/// SplitMix64. Foundation's RNG is seeded per-process; a probe stimulus must be reproducible
+/// across processes and machines.
+nonisolated struct MeetingVPIOAcousticPRNG {
+ private var state: UInt64
- mutating func next() -> UInt64 {
- self.state &+= 0x9E37_79B9_7F4A_7C15
- var z = self.state
- z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
- z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
- return z ^ (z >> 31)
- }
+ init(seed: UInt64) {
+ self.state = seed
+ }
- /// Uniform in [-1, 1].
- mutating func nextSymmetricUnit() -> Double {
- let unit = Double(self.next() >> 11) * (1.0 / 9_007_199_254_740_992.0)
- return unit * 2 - 1
- }
+ mutating func next() -> UInt64 {
+ self.state &+= 0x9e3779b97f4a7c15
+ var z = self.state
+ z = (z ^ (z >> 30)) &* 0xbf58476d1ce4e5b9
+ z = (z ^ (z >> 27)) &* 0x94d049bb133111eb
+ return z ^ (z >> 31)
+ }
+
+ /// Uniform in [-1, 1].
+ mutating func nextSymmetricUnit() -> Double {
+ let unit = Double(self.next() >> 11) * (1.0 / 9_007_199_254_740_992.0)
+ return unit * 2 - 1
}
+}
#endif
diff --git a/Sources/Fluid/Services/Meeting/MeetingVPIOAcousticTrialB.swift b/Sources/Fluid/Services/Meeting/MeetingVPIOAcousticTrialB.swift
index 30420913..daf70e96 100644
--- a/Sources/Fluid/Services/Meeting/MeetingVPIOAcousticTrialB.swift
+++ b/Sources/Fluid/Services/Meeting/MeetingVPIOAcousticTrialB.swift
@@ -1,368 +1,322 @@
#if DEBUG
- import AVFoundation
- import CoreMedia
- import Darwin
- import Foundation
- import os
-
- // MARK: - Gate
-
- /// Trial B renders audio and mutates VPIO controls. It exists only in DEBUG and only when the
- /// explicit dual hardware-probe gate is present: `FLUIDVOICE_VPIO_ACOUSTIC=1` and a finite
- /// `FLUIDVOICE_MIC_PHASE1` duration in the bounded probe interval. No production path can
- /// reach it.
- nonisolated enum MeetingVPIOAcousticGate {
- static let maximumProbeMinutes = 0.25
- static let maximumSystemVolume = 0.6
- static let maximumCombinedPeak = 0.15
-
- static var isEnabled: Bool {
- self.isEnabled(environment: ProcessInfo.processInfo.environment)
- }
-
- static func isEnabled(environment: [String: String]) -> Bool {
- guard environment["FLUIDVOICE_VPIO_ACOUSTIC"] == "1",
- let minutes = environment["FLUIDVOICE_MIC_PHASE1"].flatMap(Double.init),
- minutes > 0,
- minutes <= Self.maximumProbeMinutes,
- minutes.isFinite
- else {
- return false
- }
- return true
- }
+import AVFoundation
+import CoreMedia
+import Darwin
+import Foundation
+import os
+
+// MARK: - Gate
+
+/// Trial B renders audio and mutates VPIO controls. It exists only in DEBUG and only when the
+/// explicit dual hardware-probe gate is present: `FLUIDVOICE_VPIO_ACOUSTIC=1` and a finite
+/// `FLUIDVOICE_MIC_PHASE1` duration in the bounded probe interval. No production path can
+/// reach it.
+nonisolated enum MeetingVPIOAcousticGate {
+ static let maximumProbeMinutes = 0.25
+ static let maximumSystemVolume = 0.6
+ static let maximumCombinedPeak = 0.15
+
+ static var isEnabled: Bool {
+ self.isEnabled(environment: ProcessInfo.processInfo.environment)
}
- /// mach ticks to seconds, matching `MeetingMicrophonePTSClock`'s conversion so render times and
- /// capture presentation stamps live on one grid.
- nonisolated enum MeetingVPIOAcousticHostClock {
- private static let timebase: mach_timebase_info_data_t = {
- var info = mach_timebase_info_data_t()
- mach_timebase_info(&info)
- return info
- }()
-
- static func seconds(_ hostTime: UInt64) -> Double {
- guard self.timebase.denom > 0 else { return Double(hostTime) / 1_000_000_000 }
- return Double(hostTime) * Double(self.timebase.numer) / Double(self.timebase.denom) / 1_000_000_000
+ static func isEnabled(environment: [String: String]) -> Bool {
+ guard environment["FLUIDVOICE_VPIO_ACOUSTIC"] == "1",
+ let minutes = environment["FLUIDVOICE_MIC_PHASE1"].flatMap(Double.init),
+ minutes > 0,
+ minutes <= maximumProbeMinutes,
+ minutes.isFinite
+ else {
+ return false
}
+ return true
}
-
- // MARK: - Report records
-
- /// Evidence that the stimulus actually reached the engine's output path, independent of the
- /// microphone: without it a silent capture cannot be told apart from a silent render.
- nonisolated struct MeetingVPIOAcousticRenderConfirmation: Codable, Equatable, Sendable {
- var scheduledFrameCount: Int
- var sampleRate: Double
- var volume: Double
- var mixerSampleRate: Double
- var mixerChannelCount: Int
- var tapFrameCount: Int
- var tapRMS: Double
- var tapPeak: Double
- var tapInvalidHostTimeCount: Int
- /// Host-time seconds of the first mixer sample above the activity floor. This is after the
- /// stimulus's leading silence; Trial B converts it to stimulus sample-zero before windowing.
- var renderStartHostSeconds: Double?
- /// Independent estimate derived from the player's own sample clock; a large disagreement
- /// with `renderStartHostSeconds` invalidates the delay, it does not average with it.
- var playerDerivedStartHostSeconds: Double?
- var playerRenderedFrameCount: Int?
- var renderStartResolved: Bool
- var outputConnectionCount: Int
- var outputDeviceID: UInt32?
- var defaultOutputDeviceID: UInt32?
- var outputRouteConfirmed: Bool
- var systemVolume: Double?
- var outputVolumeReadable: Bool
- var combinedPeak: Double?
- var reasons: [MeetingVPIOAcousticReason]
- }
-
- /// Read-only safety preflight for a local render. It records only route/volume numbers and
- /// typed refusal reasons; it never changes the system volume or audio-device controls.
- nonisolated struct MeetingVPIOAcousticOutputPreflight: Codable, Equatable, Sendable {
- var outputConnectionCount: Int
- var outputDeviceID: UInt32?
- var defaultOutputDeviceID: UInt32?
- var outputRouteConfirmed: Bool
- var systemVolume: Double?
- var outputVolumeReadable: Bool
- var combinedPeak: Double?
- var reasons: [MeetingVPIOAcousticReason]
-
- var isSafe: Bool { self.reasons.isEmpty }
+}
+
+/// mach ticks to seconds, matching `MeetingMicrophonePTSClock`'s conversion so render times and
+/// capture presentation stamps live on one grid.
+nonisolated enum MeetingVPIOAcousticHostClock {
+ private static let timebase: mach_timebase_info_data_t = {
+ var info = mach_timebase_info_data_t()
+ mach_timebase_info(&info)
+ return info
+ }()
+
+ static func seconds(_ hostTime: UInt64) -> Double {
+ guard self.timebase.denom > 0 else { return Double(hostTime) / 1_000_000_000 }
+ return Double(hostTime) * Double(self.timebase.numer) / Double(self.timebase.denom) / 1_000_000_000
}
-
- nonisolated struct MeetingVPIOAcousticControlState: Codable, Equatable, Sendable {
- var requestedBypass: Bool
- var appliedBypass: Bool?
- var requestedAGCEnabled: Bool
- var appliedAGCEnabled: Bool?
- var readbackBypass: Bool?
- var readbackAGCEnabled: Bool?
- var readbackBypassRawValue: UInt32?
- var readbackAGCRawValue: UInt32?
- var readbackBypassStatus: OSStatus?
- var readbackAGCStatus: OSStatus?
- var applied: Bool
+}
+
+// MARK: - Report records
+
+/// Evidence that the stimulus actually reached the engine's output path, independent of the
+/// microphone: without it a silent capture cannot be told apart from a silent render.
+nonisolated struct MeetingVPIOAcousticRenderConfirmation: Codable, Equatable, Sendable {
+ var scheduledFrameCount: Int
+ var sampleRate: Double
+ var volume: Double
+ var mixerSampleRate: Double
+ var mixerChannelCount: Int
+ var tapFrameCount: Int
+ var tapRMS: Double
+ var tapPeak: Double
+ var tapInvalidHostTimeCount: Int
+ /// Host-time seconds of the first mixer sample above the activity floor. This is after the
+ /// stimulus's leading silence; Trial B converts it to stimulus sample-zero before windowing.
+ var renderStartHostSeconds: Double?
+ /// Independent estimate derived from the player's own sample clock; a large disagreement
+ /// with `renderStartHostSeconds` invalidates the delay, it does not average with it.
+ var playerDerivedStartHostSeconds: Double?
+ var playerRenderedFrameCount: Int?
+ var renderStartResolved: Bool
+ var outputConnectionCount: Int
+ var outputDeviceID: UInt32?
+ var defaultOutputDeviceID: UInt32?
+ var outputRouteConfirmed: Bool
+ var systemVolume: Double?
+ var outputVolumeReadable: Bool
+ var combinedPeak: Double?
+ var reasons: [MeetingVPIOAcousticReason]
+}
+
+/// Read-only safety preflight for a local render. It records only route/volume numbers and
+/// typed refusal reasons; it never changes the system volume or audio-device controls.
+nonisolated struct MeetingVPIOAcousticOutputPreflight: Codable, Equatable, Sendable {
+ var outputConnectionCount: Int
+ var outputDeviceID: UInt32?
+ var defaultOutputDeviceID: UInt32?
+ var outputRouteConfirmed: Bool
+ var systemVolume: Double?
+ var outputVolumeReadable: Bool
+ var combinedPeak: Double?
+ var reasons: [MeetingVPIOAcousticReason]
+
+ var isSafe: Bool { self.reasons.isEmpty }
+}
+
+nonisolated struct MeetingVPIOAcousticControlState: Codable, Equatable, Sendable {
+ var requestedBypass: Bool
+ var appliedBypass: Bool?
+ var requestedAGCEnabled: Bool
+ var appliedAGCEnabled: Bool?
+ var readbackBypass: Bool?
+ var readbackAGCEnabled: Bool?
+ var readbackBypassRawValue: UInt32?
+ var readbackAGCRawValue: UInt32?
+ var readbackBypassStatus: OSStatus?
+ var readbackAGCStatus: OSStatus?
+ var applied: Bool
+}
+
+nonisolated struct MeetingVPIOAcousticCaptureWindow: Codable, Equatable, Sendable {
+ var startHostSeconds: Double
+ var frameCount: Int
+ var writtenFrameCount: Int
+ var coverage: Double
+ var contributingSegmentCount: Int
+ var overlapFrameCount: Int
+ var synthesizedFrameCount: Int
+ var resyncedSegmentCount: Int
+}
+
+nonisolated struct MeetingVPIOAcousticRun: Codable, Equatable, Sendable {
+ var variant: String
+ var control: MeetingVPIOAcousticControlState
+ var render: MeetingVPIOAcousticRenderConfirmation?
+ var captureWindow: MeetingVPIOAcousticCaptureWindow?
+ var measurement: MeetingVPIOAcousticMeasurement?
+ var valid: Bool
+ var reasons: [MeetingVPIOAcousticReason]
+}
+
+nonisolated struct MeetingVPIOAcousticTrialBReport: Codable, Equatable, Sendable {
+ static let currentSchemaVersion = 1
+
+ /// Carried in the sidecar so a reader cannot lift a number out of it as an AEC result.
+ static let interpretationCaveats = [
+ "Trial B renders known local PCM through this process's own VPIO output path; it does not route another application's audio and says nothing about whether Apple's echo reference receives other-process playback.",
+ // Keep the complete diagnostic output string intact.
+ // swiftlint:disable:next line_length
+ "attenuationDB compares an electrical reference against an acoustic capture and is uncalibrated. Only differences between variants measured back-to-back on one unchanged rig are readable, and even those are confounded by speaker level, room, and AGC.",
+ "A single run establishes neither echo cancellation nor its absence. Treat every number as configuration and coupling evidence pending the paired ScreenCaptureKit topology comparison.",
+ ]
+
+ var schemaVersion: Int
+ var stimulus: MeetingVPIOAcousticStimulusDescriptor
+ var renderVolume: Double
+ var preRollSeconds: Double
+ var postRollSeconds: Double
+ var settleSeconds: Double
+ var runs: [MeetingVPIOAcousticRun]
+ var caveats: [String]
+}
+
+// MARK: - Capture collector
+
+/// Holds the probe's already-emitted mono capture in memory for the duration of the trial so
+/// the metrics can be aligned to render time. Nothing here is written to disk, and only numbers
+/// leave it.
+final nonisolated class MeetingVPIOAcousticCaptureCollector: @unchecked Sendable {
+ private nonisolated struct Segment: Sendable {
+ var startSeconds: Double
+ var samples: [Float]
+ var synthesized: Bool
+ var resynced: Bool
}
- nonisolated struct MeetingVPIOAcousticCaptureWindow: Codable, Equatable, Sendable {
- var startHostSeconds: Double
- var frameCount: Int
- var writtenFrameCount: Int
- var coverage: Double
- var contributingSegmentCount: Int
- var overlapFrameCount: Int
- var synthesizedFrameCount: Int
- var resyncedSegmentCount: Int
+ private nonisolated struct State: Sendable {
+ var segments: [Segment] = []
+ var frameCount = 0
}
- nonisolated struct MeetingVPIOAcousticRun: Codable, Equatable, Sendable {
- var variant: String
- var control: MeetingVPIOAcousticControlState
- var render: MeetingVPIOAcousticRenderConfirmation?
- var captureWindow: MeetingVPIOAcousticCaptureWindow?
- var measurement: MeetingVPIOAcousticMeasurement?
- var valid: Bool
- var reasons: [MeetingVPIOAcousticReason]
+ /// 20 s at 48 kHz: enough for every variant window, bounded so a long probe cannot grow
+ /// without limit.
+ private nonisolated static let maximumRetainedFrames = 960_000
+
+ private nonisolated let lock = OSAllocatedUnfairLock(initialState: State())
+
+ nonisolated func ingest(_ sampleBuffer: CMSampleBuffer, synthesized: Bool = false, resynced: Bool = false) {
+ guard let sample = MeetingLiveSampleCopy.copy(sampleBuffer),
+ let channel = sample.buffer.floatChannelData?[0]
+ else { return }
+ let frameCount = Int(sample.buffer.frameLength)
+ guard frameCount > 0, sample.pts.isNumeric else { return }
+ let samples = Array(UnsafeBufferPointer(start: channel, count: frameCount))
+ let segment = Segment(
+ startSeconds: sample.pts.seconds,
+ samples: samples,
+ synthesized: synthesized,
+ resynced: resynced
+ )
+
+ self.lock.withLock { state in
+ state.segments.append(segment)
+ state.frameCount += frameCount
+ while state.frameCount > Self.maximumRetainedFrames, !state.segments.isEmpty {
+ state.frameCount -= state.segments.removeFirst().samples.count
+ }
+ }
}
- nonisolated struct MeetingVPIOAcousticTrialBReport: Codable, Equatable, Sendable {
- static let currentSchemaVersion = 1
-
- /// Carried in the sidecar so a reader cannot lift a number out of it as an AEC result.
- static let interpretationCaveats = [
- "Trial B renders known local PCM through this process's own VPIO output path; it does not route another application's audio and says nothing about whether Apple's echo reference receives other-process playback.",
- "attenuationDB compares an electrical reference against an acoustic capture and is uncalibrated. Only differences between variants measured back-to-back on one unchanged rig are readable, and even those are confounded by speaker level, room, and AGC.",
- "A single run establishes neither echo cancellation nor its absence. Treat every number as configuration and coupling evidence pending the paired ScreenCaptureKit topology comparison.",
- ]
-
- var schemaVersion: Int
- var stimulus: MeetingVPIOAcousticStimulusDescriptor
- var renderVolume: Double
- var preRollSeconds: Double
- var postRollSeconds: Double
- var settleSeconds: Double
- var runs: [MeetingVPIOAcousticRun]
- var caveats: [String]
+ nonisolated func reset() {
+ self.lock.withLock { $0 = State() }
}
- // MARK: - Capture collector
-
- /// Holds the probe's already-emitted mono capture in memory for the duration of the trial so
- /// the metrics can be aligned to render time. Nothing here is written to disk, and only numbers
- /// leave it.
- final nonisolated class MeetingVPIOAcousticCaptureCollector: @unchecked Sendable {
- private nonisolated struct Segment: Sendable {
- var startSeconds: Double
- var samples: [Float]
- var synthesized: Bool
- var resynced: Bool
- }
-
- private nonisolated struct State: Sendable {
- var segments: [Segment] = []
- var frameCount = 0
- }
-
- /// 20 s at 48 kHz: enough for every variant window, bounded so a long probe cannot grow
- /// without limit.
- private nonisolated static let maximumRetainedFrames = 960_000
-
- private nonisolated let lock = OSAllocatedUnfairLock(initialState: State())
-
- nonisolated func ingest(_ sampleBuffer: CMSampleBuffer, synthesized: Bool = false, resynced: Bool = false) {
- guard let sample = MeetingLiveSampleCopy.copy(sampleBuffer),
- let channel = sample.buffer.floatChannelData?[0]
- else { return }
- let frameCount = Int(sample.buffer.frameLength)
- guard frameCount > 0, sample.pts.isNumeric else { return }
- let samples = Array(UnsafeBufferPointer(start: channel, count: frameCount))
- let segment = Segment(
- startSeconds: sample.pts.seconds,
- samples: samples,
- synthesized: synthesized,
- resynced: resynced
- )
-
- self.lock.withLock { state in
- state.segments.append(segment)
- state.frameCount += frameCount
- while state.frameCount > Self.maximumRetainedFrames, !state.segments.isEmpty {
- state.frameCount -= state.segments.removeFirst().samples.count
- }
+ /// Places every retained segment on a host-time grid starting at `startHostSeconds`. Gaps
+ /// stay zero and are reported through `coverage`; a partially covered window is never
+ /// silently treated as a complete one.
+ nonisolated func window(
+ startHostSeconds: Double,
+ frameCount: Int,
+ sampleRate: Double
+ ) -> (samples: [Float], window: MeetingVPIOAcousticCaptureWindow) {
+ let count = max(0, frameCount)
+ var samples = [Float](repeating: 0, count: count)
+ var filled = [Bool](repeating: false, count: count)
+ var overlap = 0
+ var contributing = 0
+ var synthesizedFrameCount = 0
+ var resyncedSegmentCount = 0
+ let segments = self.lock.withLock { $0.segments }
+
+ for segment in segments {
+ let offset = Int(((segment.startSeconds - startHostSeconds) * sampleRate).rounded())
+ let start = max(0, offset)
+ let end = min(count, offset + segment.samples.count)
+ guard start < end else { continue }
+ contributing += 1
+ if segment.resynced { resyncedSegmentCount += 1 }
+ for index in start..<end {
+ if filled[index] { overlap += 1 }
+ let wasFilled = filled[index]
+ filled[index] = true
+ if segment.synthesized, !wasFilled { synthesizedFrameCount += 1 }
+ samples[index] = segment.samples[index - offset]
}
}
-
- nonisolated func reset() {
- self.lock.withLock { $0 = State() }
- }
-
- /// Places every retained segment on a host-time grid starting at `startHostSeconds`. Gaps
- /// stay zero and are reported through `coverage`; a partially covered window is never
- /// silently treated as a complete one.
- nonisolated func window(
- startHostSeconds: Double,
- frameCount: Int,
- sampleRate: Double
- ) -> (samples: [Float], window: MeetingVPIOAcousticCaptureWindow) {
- let count = max(0, frameCount)
- var samples = [Float](repeating: 0, count: count)
- var filled = [Bool](repeating: false, count: count)
- var overlap = 0
- var contributing = 0
- var synthesizedFrameCount = 0
- var resyncedSegmentCount = 0
- let segments = self.lock.withLock { $0.segments }
-
- for segment in segments {
- let offset = Int(((segment.startSeconds - startHostSeconds) * sampleRate).rounded())
- let start = max(0, offset)
- let end = min(count, offset + segment.samples.count)
- guard start < end else { continue }
- contributing += 1
- if segment.resynced { resyncedSegmentCount += 1 }
- for index in start..<end {
- if filled[index] { overlap += 1 }
- let wasFilled = filled[index]
- filled[index] = true
- if segment.synthesized, !wasFilled { synthesizedFrameCount += 1 }
- samples[index] = segment.samples[index - offset]
- }
- }
- let written = filled.filter { $0 }.count
-
- return (
- samples,
- MeetingVPIOAcousticCaptureWindow(
- startHostSeconds: startHostSeconds,
- frameCount: count,
- writtenFrameCount: written,
- coverage: count > 0 ? Double(written) / Double(count) : 0,
- contributingSegmentCount: contributing,
- overlapFrameCount: overlap,
- synthesizedFrameCount: synthesizedFrameCount,
- resyncedSegmentCount: resyncedSegmentCount
- )
+ let written = filled.filter { $0 }.count
+
+ return (
+ samples,
+ MeetingVPIOAcousticCaptureWindow(
+ startHostSeconds: startHostSeconds,
+ frameCount: count,
+ writtenFrameCount: written,
+ coverage: count > 0 ? Double(written) / Double(count) : 0,
+ contributingSegmentCount: contributing,
+ overlapFrameCount: overlap,
+ synthesizedFrameCount: synthesizedFrameCount,
+ resyncedSegmentCount: resyncedSegmentCount
)
- }
+ )
}
+}
- // MARK: - Runner
+// MARK: - Runner
- /// Controlled acoustic Trial B: render a deterministic stimulus through the running VPIO
- /// engine's own output and measure what the VPIO input returns, once per control variant.
- nonisolated enum MeetingVPIOAcousticTrialB {
- struct Variant: Sendable {
- var name: String
- var bypassVoiceProcessing: Bool
- var agcEnabled: Bool
- }
-
- /// Baseline first, then one changed control at a time. Only properties with public setters
- /// are varied; `setVoiceProcessingEnabled` is never touched here (see the teardown note in
- /// `MeetingMicrophoneCapture.stop`).
- static let variants: [Variant] = [
- Variant(name: "vpioActive", bypassVoiceProcessing: false, agcEnabled: true),
- Variant(name: "vpioActiveNoAGC", bypassVoiceProcessing: false, agcEnabled: false),
- Variant(name: "vpioBypassed", bypassVoiceProcessing: true, agcEnabled: true),
- ]
-
- static let renderVolume: Float = 0.5
- static let settleSeconds = 0.35
- static let preRollSeconds = 0.30
- static let postRollSeconds = 0.60
- static let interVariantSeconds = 0.50
- /// The tap emits 100 ms aggregate buffers. Let a reset establish a complete pre-roll
- /// window, with one buffer-period margin for callback/flush scheduling, before playback.
- static let collectorWarmupSeconds = Self.preRollSeconds + 0.15
-
- private static func orderedReasons(_ reasons: [MeetingVPIOAcousticReason]) -> [MeetingVPIOAcousticReason] {
- var seen = Set<MeetingVPIOAcousticReason>()
- return reasons.filter { seen.insert($0).inserted }.sorted { $0.rawValue < $1.rawValue }
- }
+/// Controlled acoustic Trial B: render a deterministic stimulus through the running VPIO
+/// engine's own output and measure what the VPIO input returns, once per control variant.
+nonisolated enum MeetingVPIOAcousticTrialB {
+ struct Variant: Sendable {
+ var name: String
+ var bypassVoiceProcessing: Bool
+ var agcEnabled: Bool
+ }
- /// The mixer tap reports first activity, while the reference array begins at stimulus
- /// sample zero. Keep the conversion explicit so leading silence cannot shift the window
- /// and hide its trailing capture in an otherwise complete run.
- static func stimulusSampleZeroHostSeconds(
- renderActivityStartHostSeconds: Double,
- leadingSilenceFrameCount: Int,
- sampleRate: Double
- ) -> Double? {
- guard renderActivityStartHostSeconds.isFinite,
- leadingSilenceFrameCount >= 0,
- sampleRate.isFinite,
- sampleRate > 0
- else { return nil }
- return renderActivityStartHostSeconds - Double(leadingSilenceFrameCount) / sampleRate
- }
+ /// Baseline first, then one changed control at a time. Only properties with public setters
+ /// are varied; `setVoiceProcessingEnabled` is never touched here (see the teardown note in
+ /// `MeetingMicrophoneCapture.stop`).
+ static let variants: [Variant] = [
+ Variant(name: "vpioActive", bypassVoiceProcessing: false, agcEnabled: true),
+ Variant(name: "vpioActiveNoAGC", bypassVoiceProcessing: false, agcEnabled: false),
+ Variant(name: "vpioBypassed", bypassVoiceProcessing: true, agcEnabled: true),
+ ]
+
+ static let renderVolume: Float = 0.5
+ static let settleSeconds = 0.35
+ static let preRollSeconds = 0.30
+ static let postRollSeconds = 0.60
+ static let interVariantSeconds = 0.50
+ /// The tap emits 100 ms aggregate buffers. Let a reset establish a complete pre-roll
+ /// window, with one buffer-period margin for callback/flush scheduling, before playback.
+ static let collectorWarmupSeconds = Self.preRollSeconds + 0.15
+
+ private static func orderedReasons(_ reasons: [MeetingVPIOAcousticReason]) -> [MeetingVPIOAcousticReason] {
+ var seen = Set<MeetingVPIOAcousticReason>()
+ return reasons.filter { seen.insert($0).inserted }.sorted { $0.rawValue < $1.rawValue }
+ }
- static func isRequested() -> Bool { MeetingVPIOAcousticGate.isEnabled }
-
- static func run(
- capture: MeetingMicrophoneCapture,
- collector: MeetingVPIOAcousticCaptureCollector,
- sampleRate: Double = 48_000
- ) async -> MeetingVPIOAcousticTrialBReport? {
- guard MeetingVPIOAcousticGate.isEnabled else { return nil }
- guard let stimulus = MeetingVPIOAcousticStimulus.make(sampleRate: sampleRate) else { return nil }
-
- var runs: [MeetingVPIOAcousticRun] = []
- guard stimulus.descriptor.withinSafetyBounds else {
- // Refuse to render rather than emit an unbounded level.
- return MeetingVPIOAcousticTrialBReport(
- schemaVersion: MeetingVPIOAcousticTrialBReport.currentSchemaVersion,
- stimulus: stimulus.descriptor,
- renderVolume: Double(Self.renderVolume),
- preRollSeconds: Self.preRollSeconds,
- postRollSeconds: Self.postRollSeconds,
- settleSeconds: Self.settleSeconds,
- runs: [],
- caveats: MeetingVPIOAcousticTrialBReport.interpretationCaveats
- + ["Stimulus fell outside its RMS/peak safety bounds; nothing was rendered."]
- )
- }
+ /// The mixer tap reports first activity, while the reference array begins at stimulus
+ /// sample zero. Keep the conversion explicit so leading silence cannot shift the window
+ /// and hide its trailing capture in an otherwise complete run.
+ static func stimulusSampleZeroHostSeconds(
+ renderActivityStartHostSeconds: Double,
+ leadingSilenceFrameCount: Int,
+ sampleRate: Double
+ ) -> Double? {
+ guard renderActivityStartHostSeconds.isFinite,
+ leadingSilenceFrameCount >= 0,
+ sampleRate.isFinite,
+ sampleRate > 0
+ else { return nil }
+ return renderActivityStartHostSeconds - Double(leadingSilenceFrameCount) / sampleRate
+ }
- let preRunSnapshot = await capture.voiceProcessingProbeReadback()
- guard let preRunControl = preRunSnapshot.flatMap(Self.validatedControlState) else {
- return MeetingVPIOAcousticTrialBReport(
- schemaVersion: MeetingVPIOAcousticTrialBReport.currentSchemaVersion,
- stimulus: stimulus.descriptor,
- renderVolume: Double(Self.renderVolume),
- preRollSeconds: Self.preRollSeconds,
- postRollSeconds: Self.postRollSeconds,
- settleSeconds: Self.settleSeconds,
- runs: [],
- caveats: MeetingVPIOAcousticTrialBReport.interpretationCaveats
- + ["Pre-run VPIO control getter/raw read-backs were unavailable or inconsistent; no variant was rendered."]
- )
- }
- for variant in Self.variants {
- // Cancellation is cooperative: stop starting new variants, then restore the
- // production controls below before this task returns.
- guard !Task.isCancelled else { break }
- runs.append(
- await Self.runVariant(
- variant,
- capture: capture,
- collector: collector,
- stimulus: stimulus,
- sampleRate: sampleRate
- )
- )
- try? await Task.sleep(nanoseconds: UInt64(Self.interVariantSeconds * 1_000_000_000))
- }
+ static func isRequested() -> Bool { MeetingVPIOAcousticGate.isEnabled }
- // Restore the actual pre-run controls. Never assume Apple's defaults and never touch
- // the VPIO enable bit here.
- _ = await capture.setVoiceProcessingBypassedForProbe(preRunControl.bypassed)
- _ = await capture.setVoiceProcessingAGCEnabledForProbe(preRunControl.agcEnabled)
+ static func run(
+ capture: MeetingMicrophoneCapture,
+ collector: MeetingVPIOAcousticCaptureCollector,
+ sampleRate: Double = 48_000
+ ) async -> MeetingVPIOAcousticTrialBReport? {
+ guard MeetingVPIOAcousticGate.isEnabled else { return nil }
+ guard let stimulus = MeetingVPIOAcousticStimulus.make(sampleRate: sampleRate) else { return nil }
+ var runs: [MeetingVPIOAcousticRun] = []
+ guard stimulus.descriptor.withinSafetyBounds else {
+ // Refuse to render rather than emit an unbounded level.
return MeetingVPIOAcousticTrialBReport(
schemaVersion: MeetingVPIOAcousticTrialBReport.currentSchemaVersion,
stimulus: stimulus.descriptor,
@@ -370,196 +324,244 @@
preRollSeconds: Self.preRollSeconds,
postRollSeconds: Self.postRollSeconds,
settleSeconds: Self.settleSeconds,
- runs: runs,
+ runs: [],
caveats: MeetingVPIOAcousticTrialBReport.interpretationCaveats
+ + ["Stimulus fell outside its RMS/peak safety bounds; nothing was rendered."]
)
}
- private static func runVariant(
- _ variant: Variant,
- capture: MeetingMicrophoneCapture,
- collector: MeetingVPIOAcousticCaptureCollector,
- stimulus: MeetingVPIOAcousticStimulus.Generated,
- sampleRate: Double
- ) async -> MeetingVPIOAcousticRun {
- let appliedBypass = await capture.setVoiceProcessingBypassedForProbe(variant.bypassVoiceProcessing)
- let appliedAGC = await capture.setVoiceProcessingAGCEnabledForProbe(variant.agcEnabled)
- try? await Task.sleep(nanoseconds: UInt64(Self.settleSeconds * 1_000_000_000))
-
- let snapshot = await capture.voiceProcessingProbeReadback()
- var control = MeetingVPIOAcousticControlState(
- requestedBypass: variant.bypassVoiceProcessing,
- appliedBypass: appliedBypass,
- requestedAGCEnabled: variant.agcEnabled,
- appliedAGCEnabled: appliedAGC,
- readbackBypass: snapshot?.nodeVoiceProcessingBypassed,
- readbackAGCEnabled: snapshot?.nodeVoiceProcessingAGCEnabled,
- readbackBypassRawValue: snapshot?.bypassVoiceProcessing.value,
- readbackAGCRawValue: snapshot?.voiceProcessingAGCEnabled.value,
- readbackBypassStatus: snapshot?.bypassVoiceProcessing.status,
- readbackAGCStatus: snapshot?.voiceProcessingAGCEnabled.status,
- applied: false
+ let preRunSnapshot = await capture.voiceProcessingProbeReadback()
+ guard let preRunControl = preRunSnapshot.flatMap(Self.validatedControlState) else {
+ return MeetingVPIOAcousticTrialBReport(
+ schemaVersion: MeetingVPIOAcousticTrialBReport.currentSchemaVersion,
+ stimulus: stimulus.descriptor,
+ renderVolume: Double(Self.renderVolume),
+ preRollSeconds: Self.preRollSeconds,
+ postRollSeconds: Self.postRollSeconds,
+ settleSeconds: Self.settleSeconds,
+ runs: [],
+ caveats: MeetingVPIOAcousticTrialBReport.interpretationCaveats
+ + ["Pre-run VPIO control getter/raw read-backs were unavailable or inconsistent; no variant was rendered."]
)
- control.applied = snapshot?.bypassVoiceProcessing.succeeded == true
- && snapshot?.voiceProcessingAGCEnabled.succeeded == true
- && snapshot?.bypassVoiceProcessing.value == UInt32(variant.bypassVoiceProcessing ? 1 : 0)
- && snapshot?.voiceProcessingAGCEnabled.value == UInt32(variant.agcEnabled ? 1 : 0)
- && control.readbackBypass == variant.bypassVoiceProcessing
- && control.readbackAGCEnabled == variant.agcEnabled
-
- var reasons: [MeetingVPIOAcousticReason] = []
- if !control.applied { reasons.append(.controlNotApplied) }
- if Task.isCancelled {
- reasons.append(.probeCancelled)
- return MeetingVPIOAcousticRun(
- variant: variant.name,
- control: control,
- render: nil,
- captureWindow: nil,
- measurement: nil,
- valid: false,
- reasons: Self.orderedReasons(reasons)
+ }
+ for variant in Self.variants {
+ // Cancellation is cooperative: stop starting new variants, then restore the
+ // production controls below before this task returns.
+ guard !Task.isCancelled else { break }
+ runs.append(
+ await Self.runVariant(
+ variant,
+ capture: capture,
+ collector: collector,
+ stimulus: stimulus,
+ sampleRate: sampleRate
)
- }
+ )
+ try? await Task.sleep(nanoseconds: UInt64(Self.interVariantSeconds * 1_000_000_000))
+ }
- collector.reset()
- try? await Task.sleep(nanoseconds: UInt64(Self.collectorWarmupSeconds * 1_000_000_000))
- guard !Task.isCancelled else {
- reasons.append(.probeCancelled)
- return MeetingVPIOAcousticRun(
- variant: variant.name,
- control: control,
- render: nil,
- captureWindow: nil,
- measurement: nil,
- valid: false,
- reasons: Self.orderedReasons(reasons)
- )
- }
- let render: MeetingVPIOAcousticRenderConfirmation
- do {
- render = try await capture.playVoiceProcessingProbePCM(
- stimulus.samples,
- sampleRate: sampleRate,
- volume: Self.renderVolume
- )
- } catch {
- switch error {
- case is CancellationError: reasons.append(.probeCancelled)
- case MeetingVoiceProcessingProbeError.captureNotRunning: reasons.append(.captureNotRunning)
- case MeetingVoiceProcessingProbeError.invalidPlaybackFormat: reasons.append(.insufficientFrames)
- case MeetingVoiceProcessingProbeError.playbackTimedOut: reasons.append(.playbackTimedOut)
- default: reasons.append(.probeDisabled)
- }
- return MeetingVPIOAcousticRun(
- variant: variant.name,
- control: control,
- render: nil,
- captureWindow: nil,
- measurement: nil,
- valid: false,
- reasons: Self.orderedReasons(reasons)
- )
- }
- try? await Task.sleep(nanoseconds: UInt64(Self.postRollSeconds * 1_000_000_000))
-
- reasons.append(contentsOf: render.reasons)
- guard let renderActivityStart = render.renderStartHostSeconds,
- let renderStart = Self.stimulusSampleZeroHostSeconds(
- renderActivityStartHostSeconds: renderActivityStart,
- leadingSilenceFrameCount: stimulus.descriptor.leadingSilenceFrameCount,
- sampleRate: sampleRate
- )
- else {
- reasons.append(.renderTimingInvalid)
- return MeetingVPIOAcousticRun(
- variant: variant.name,
- control: control,
- render: render,
- captureWindow: nil,
- measurement: nil,
- valid: false,
- reasons: Self.orderedReasons(reasons)
- )
- }
+ // Restore the actual pre-run controls. Never assume Apple's defaults and never touch
+ // the VPIO enable bit here.
+ _ = await capture.setVoiceProcessingBypassedForProbe(preRunControl.bypassed)
+ _ = await capture.setVoiceProcessingAGCEnabledForProbe(preRunControl.agcEnabled)
+
+ return MeetingVPIOAcousticTrialBReport(
+ schemaVersion: MeetingVPIOAcousticTrialBReport.currentSchemaVersion,
+ stimulus: stimulus.descriptor,
+ renderVolume: Double(Self.renderVolume),
+ preRollSeconds: Self.preRollSeconds,
+ postRollSeconds: Self.postRollSeconds,
+ settleSeconds: Self.settleSeconds,
+ runs: runs,
+ caveats: MeetingVPIOAcousticTrialBReport.interpretationCaveats
+ )
+ }
- let preRollFrames = Int((Self.preRollSeconds * sampleRate).rounded())
- let tailFrames = Int((Self.postRollSeconds * sampleRate).rounded())
- let windowFrames = preRollFrames + stimulus.samples.count + tailFrames
- let captured = collector.window(
- startHostSeconds: renderStart - Self.preRollSeconds,
- frameCount: windowFrames,
- sampleRate: sampleRate
+ private static func runVariant(
+ _ variant: Variant,
+ capture: MeetingMicrophoneCapture,
+ collector: MeetingVPIOAcousticCaptureCollector,
+ stimulus: MeetingVPIOAcousticStimulus.Generated,
+ sampleRate: Double
+ ) async -> MeetingVPIOAcousticRun {
+ let appliedBypass = await capture.setVoiceProcessingBypassedForProbe(variant.bypassVoiceProcessing)
+ let appliedAGC = await capture.setVoiceProcessingAGCEnabledForProbe(variant.agcEnabled)
+ try? await Task.sleep(nanoseconds: UInt64(Self.settleSeconds * 1_000_000_000))
+
+ let snapshot = await capture.voiceProcessingProbeReadback()
+ var control = MeetingVPIOAcousticControlState(
+ requestedBypass: variant.bypassVoiceProcessing,
+ appliedBypass: appliedBypass,
+ requestedAGCEnabled: variant.agcEnabled,
+ appliedAGCEnabled: appliedAGC,
+ readbackBypass: snapshot?.nodeVoiceProcessingBypassed,
+ readbackAGCEnabled: snapshot?.nodeVoiceProcessingAGCEnabled,
+ readbackBypassRawValue: snapshot?.bypassVoiceProcessing.value,
+ readbackAGCRawValue: snapshot?.voiceProcessingAGCEnabled.value,
+ readbackBypassStatus: snapshot?.bypassVoiceProcessing.status,
+ readbackAGCStatus: snapshot?.voiceProcessingAGCEnabled.status,
+ applied: false
+ )
+ control.applied = snapshot?.bypassVoiceProcessing.succeeded == true
+ && snapshot?.voiceProcessingAGCEnabled.succeeded == true
+ && snapshot?.bypassVoiceProcessing.value == UInt32(variant.bypassVoiceProcessing ? 1 : 0)
+ && snapshot?.voiceProcessingAGCEnabled.value == UInt32(variant.agcEnabled ? 1 : 0)
+ && control.readbackBypass == variant.bypassVoiceProcessing
+ && control.readbackAGCEnabled == variant.agcEnabled
+
+ var reasons: [MeetingVPIOAcousticReason] = []
+ if !control.applied { reasons.append(.controlNotApplied) }
+ if Task.isCancelled {
+ reasons.append(.probeCancelled)
+ return MeetingVPIOAcousticRun(
+ variant: variant.name,
+ control: control,
+ render: nil,
+ captureWindow: nil,
+ measurement: nil,
+ valid: false,
+ reasons: Self.orderedReasons(reasons)
)
- // A Trial B delay is only meaningful on a complete, non-overlapping shared-clock
- // window. Never turn missing or doubly-written capture into zeroes and then score it.
- if captured.window.coverage < 1.0 {
- reasons.append(.captureGap)
- reasons.append(.captureWindowIncomplete)
- }
- if captured.window.overlapFrameCount > 0 {
- reasons.append(.captureOverlap)
- }
- if captured.window.synthesizedFrameCount > 0 {
- reasons.append(.captureTimingSynthesized)
- if captured.window.resyncedSegmentCount == 0 {
- reasons.append(.captureTimingResyncRequired)
- }
- }
- if captured.window.coverage < 1.0 || captured.window.overlapFrameCount > 0
- || captured.window.synthesizedFrameCount > 0
- {
- return MeetingVPIOAcousticRun(
- variant: variant.name,
- control: control,
- render: render,
- captureWindow: captured.window,
- measurement: nil,
- valid: false,
- reasons: Self.orderedReasons(reasons)
- )
- }
-
- // The reference is the stimulus as rendered — scaled by the player's gain — placed at
- // the same pre-roll offset as the capture window.
- var reference = [Float](repeating: 0, count: windowFrames)
- let volume = Float(render.volume)
- for index in 0..<stimulus.samples.count where preRollFrames + index < windowFrames {
- reference[preRollFrames + index] = stimulus.samples[index] * volume
- }
+ }
- let measurement = MeetingVPIOAcousticMetrics.measure(
- reference: reference,
- captured: captured.samples,
+ collector.reset()
+ try? await Task.sleep(nanoseconds: UInt64(Self.collectorWarmupSeconds * 1_000_000_000))
+ guard !Task.isCancelled else {
+ reasons.append(.probeCancelled)
+ return MeetingVPIOAcousticRun(
+ variant: variant.name,
+ control: control,
+ render: nil,
+ captureWindow: nil,
+ measurement: nil,
+ valid: false,
+ reasons: Self.orderedReasons(reasons)
+ )
+ }
+ let render: MeetingVPIOAcousticRenderConfirmation
+ do {
+ render = try await capture.playVoiceProcessingProbePCM(
+ stimulus.samples,
sampleRate: sampleRate,
- silencePrefixFrames: preRollFrames + stimulus.descriptor.leadingSilenceFrameCount
+ volume: Self.renderVolume
+ )
+ } catch {
+ switch error {
+ case is CancellationError: reasons.append(.probeCancelled)
+ case MeetingVoiceProcessingProbeError.captureNotRunning: reasons.append(.captureNotRunning)
+ case MeetingVoiceProcessingProbeError.invalidPlaybackFormat: reasons.append(.insufficientFrames)
+ case MeetingVoiceProcessingProbeError.playbackTimedOut: reasons.append(.playbackTimedOut)
+ default: reasons.append(.probeDisabled)
+ }
+ return MeetingVPIOAcousticRun(
+ variant: variant.name,
+ control: control,
+ render: nil,
+ captureWindow: nil,
+ measurement: nil,
+ valid: false,
+ reasons: Self.orderedReasons(reasons)
+ )
+ }
+ try? await Task.sleep(nanoseconds: UInt64(Self.postRollSeconds * 1_000_000_000))
+
+ reasons.append(contentsOf: render.reasons)
+ guard let renderActivityStart = render.renderStartHostSeconds,
+ let renderStart = Self.stimulusSampleZeroHostSeconds(
+ renderActivityStartHostSeconds: renderActivityStart,
+ leadingSilenceFrameCount: stimulus.descriptor.leadingSilenceFrameCount,
+ sampleRate: sampleRate
+ )
+ else {
+ reasons.append(.renderTimingInvalid)
+ return MeetingVPIOAcousticRun(
+ variant: variant.name,
+ control: control,
+ render: render,
+ captureWindow: nil,
+ measurement: nil,
+ valid: false,
+ reasons: Self.orderedReasons(reasons)
)
+ }
+ let preRollFrames = Int((Self.preRollSeconds * sampleRate).rounded())
+ let tailFrames = Int((Self.postRollSeconds * sampleRate).rounded())
+ let windowFrames = preRollFrames + stimulus.samples.count + tailFrames
+ let captured = collector.window(
+ startHostSeconds: renderStart - Self.preRollSeconds,
+ frameCount: windowFrames,
+ sampleRate: sampleRate
+ )
+ // A Trial B delay is only meaningful on a complete, non-overlapping shared-clock
+ // window. Never turn missing or doubly-written capture into zeroes and then score it.
+ if captured.window.coverage < 1.0 {
+ reasons.append(.captureGap)
+ reasons.append(.captureWindowIncomplete)
+ }
+ if captured.window.overlapFrameCount > 0 {
+ reasons.append(.captureOverlap)
+ }
+ if captured.window.synthesizedFrameCount > 0 {
+ reasons.append(.captureTimingSynthesized)
+ if captured.window.resyncedSegmentCount == 0 {
+ reasons.append(.captureTimingResyncRequired)
+ }
+ }
+ if captured.window.coverage < 1.0 || captured.window.overlapFrameCount > 0
+ || captured.window.synthesizedFrameCount > 0
+ {
return MeetingVPIOAcousticRun(
variant: variant.name,
control: control,
render: render,
captureWindow: captured.window,
- measurement: measurement,
- valid: measurement.valid && reasons.isEmpty,
- reasons: Self.orderedReasons(reasons + measurement.reasons)
+ measurement: nil,
+ valid: false,
+ reasons: Self.orderedReasons(reasons)
)
}
- private static func validatedControlState(
- _ snapshot: MeetingVoiceProcessingProbeSnapshot
- ) -> (bypassed: Bool, agcEnabled: Bool)? {
- guard snapshot.bypassVoiceProcessing.succeeded,
- snapshot.voiceProcessingAGCEnabled.succeeded,
- let rawBypass = snapshot.bypassVoiceProcessing.value,
- let rawAGC = snapshot.voiceProcessingAGCEnabled.value,
- rawBypass <= 1,
- rawAGC <= 1,
- snapshot.nodeVoiceProcessingBypassed == (rawBypass == 1),
- snapshot.nodeVoiceProcessingAGCEnabled == (rawAGC == 1)
- else { return nil }
- return (rawBypass == 1, rawAGC == 1)
+ // The reference is the stimulus as rendered — scaled by the player's gain — placed at
+ // the same pre-roll offset as the capture window.
+ var reference = [Float](repeating: 0, count: windowFrames)
+ let volume = Float(render.volume)
+ for index in 0..<stimulus.samples.count where preRollFrames + index < windowFrames {
+ reference[preRollFrames + index] = stimulus.samples[index] * volume
}
+
+ let measurement = MeetingVPIOAcousticMetrics.measure(
+ reference: reference,
+ captured: captured.samples,
+ sampleRate: sampleRate,
+ silencePrefixFrames: preRollFrames + stimulus.descriptor.leadingSilenceFrameCount
+ )
+
+ return MeetingVPIOAcousticRun(
+ variant: variant.name,
+ control: control,
+ render: render,
+ captureWindow: captured.window,
+ measurement: measurement,
+ valid: measurement.valid && reasons.isEmpty,
+ reasons: Self.orderedReasons(reasons + measurement.reasons)
+ )
+ }
+
+ private static func validatedControlState(
+ _ snapshot: MeetingVoiceProcessingProbeSnapshot
+ ) -> (bypassed: Bool, agcEnabled: Bool)? {
+ guard snapshot.bypassVoiceProcessing.succeeded,
+ snapshot.voiceProcessingAGCEnabled.succeeded,
+ let rawBypass = snapshot.bypassVoiceProcessing.value,
+ let rawAGC = snapshot.voiceProcessingAGCEnabled.value,
+ rawBypass <= 1,
+ rawAGC <= 1,
+ snapshot.nodeVoiceProcessingBypassed == (rawBypass == 1),
+ snapshot.nodeVoiceProcessingAGCEnabled == (rawAGC == 1)
+ else { return nil }
+ return (rawBypass == 1, rawAGC == 1)
}
+}
#endif
diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swift
index 1dfc8a86..b1df27b8 100644
--- a/Sources/Fluid/Services/MenuBarManager.swift
+++ b/Sources/Fluid/Services/MenuBarManager.swift
@@ -686,7 +686,10 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
"menuRefreshUs=\(Int((ProcessInfo.processInfo.systemUptime - windowHideReturnedAt) * 1_000_000))",
source: "StopTiming"
)
- DebugLogger.shared.debug("STOP_TRACE phase=hide_dispatched closingAnimation=\(SettingsStore.shared.overlayClosingAnimationEnabled) elapsedMs=\(Int((ProcessInfo.processInfo.systemUptime - startedAt) * 1000))", source: "StopTiming")
+ DebugLogger.shared.debug(
+ "STOP_TRACE phase=hide_dispatched closingAnimation=\(SettingsStore.shared.overlayClosingAnimationEnabled) elapsedMs=\(Int((ProcessInfo.processInfo.systemUptime - startedAt) * 1000))",
+ source: "StopTiming"
+ )
self.overlayBench(
"finish_hide_dispatched elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - startedAt) * 1000).rounded()))"
)
diff --git a/Sources/Fluid/UI/AISettings/AIProvidersDesignPreview.swift b/Sources/Fluid/UI/AISettings/AIProvidersDesignPreview.swift
index 9f0bcea1..fd71b782 100644
--- a/Sources/Fluid/UI/AISettings/AIProvidersDesignPreview.swift
+++ b/Sources/Fluid/UI/AISettings/AIProvidersDesignPreview.swift
@@ -390,7 +390,10 @@ private struct AIProvidersPresentation: View {
.font(self.theme.typography.bodySmall)
.foregroundStyle(self.supportingText)
Divider()
- ForEach(panel == .manage ? ["Model downloads", "Backend & context", "Startup preferences", "Storage & maintenance"] : ["Connection details", "Model selection", "Verification"], id: \.self) { label in
+ ForEach(
+ panel == .manage ? ["Model downloads", "Backend & context", "Startup preferences", "Storage & maintenance"] : ["Connection details", "Model selection", "Verification"],
+ id: \.self
+ ) { label in
Text(label).font(self.theme.typography.body)
}
}
diff --git a/Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift b/Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift
index 04bb3b3b..ad2860f4 100644
--- a/Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift
+++ b/Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift
@@ -101,7 +101,12 @@ struct FluidIntelligenceLiveSection<Management: View>: View {
Text(self.verificationError ?? "\(self.verifiedModelName) is ready to use on your Mac.")
}
.sheet(isPresented: self.$showsManagement) {
- FluidManagementSheet(title: "Manage Fluid Intelligence", subtitle: "These settings apply to all Fluid Intelligence models.", symbol: "slider.horizontal.3", close: { self.showsManagement = false }) {
+ FluidManagementSheet(
+ title: "Manage Fluid Intelligence",
+ subtitle: "These settings apply to all Fluid Intelligence models.",
+ symbol: "slider.horizontal.3",
+ close: { self.showsManagement = false }
+ ) {
self.management()
FluidManagementGroup(title: "Storage") {
FluidManagementRow(title: "Downloaded models", detail: "View the model files stored on your Mac.") {
diff --git a/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift b/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift
index df7185ec..cd197320 100644
--- a/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift
+++ b/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift
@@ -1915,9 +1915,11 @@ extension AIEnhancementSettingsView {
.font(.fluidSystem(.caption2))
.foregroundStyle(.secondary)
} else if self.promptTest.isActive {
- Text("Press the hotkey to start/stop recording. The transcription will be post-processed using your draft prompt and shown below (nothing will be typed into other apps).")
- .font(.fluidSystem(.caption2))
- .foregroundStyle(.secondary)
+ Text(
+ "Press the hotkey to start/stop recording. The transcription will be post-processed using your draft prompt and shown below (nothing will be typed into other apps)."
+ )
+ .font(.fluidSystem(.caption2))
+ .foregroundStyle(.secondary)
}
if self.promptTest.isActive {
diff --git a/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift b/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift
index b004099c..fb05f607 100644
--- a/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift
+++ b/Sources/Fluid/UI/AISettingsView+SpeechRecognition.swift
@@ -42,7 +42,12 @@ extension VoiceEngineSettingsView {
RoundedRectangle(cornerRadius: 12)
.stroke(self.theme.palette.cardBorder.opacity(0.3), lineWidth: 1)
)
- .shadow(color: self.theme.metrics.cardShadow.color.opacity(self.theme.metrics.cardShadow.opacity), radius: self.theme.metrics.cardShadow.radius, x: self.theme.metrics.cardShadow.x, y: self.theme.metrics.cardShadow.y)
+ .shadow(
+ color: self.theme.metrics.cardShadow.color.opacity(self.theme.metrics.cardShadow.opacity),
+ radius: self.theme.metrics.cardShadow.radius,
+ x: self.theme.metrics.cardShadow.x,
+ y: self.theme.metrics.cardShadow.y
+ )
)
ScrollView(.vertical, showsIndicators: false) {
@@ -118,7 +123,12 @@ extension VoiceEngineSettingsView {
RoundedRectangle(cornerRadius: 12)
.stroke(self.theme.palette.cardBorder.opacity(0.3), lineWidth: 1)
)
- .shadow(color: self.theme.metrics.cardShadow.color.opacity(self.theme.metrics.cardShadow.opacity), radius: self.theme.metrics.cardShadow.radius, x: self.theme.metrics.cardShadow.x, y: self.theme.metrics.cardShadow.y)
+ .shadow(
+ color: self.theme.metrics.cardShadow.color.opacity(self.theme.metrics.cardShadow.opacity),
+ radius: self.theme.metrics.cardShadow.radius,
+ x: self.theme.metrics.cardShadow.x,
+ y: self.theme.metrics.cardShadow.y
+ )
)
}
}
diff --git a/Sources/Fluid/UI/CustomDictionaryView.swift b/Sources/Fluid/UI/CustomDictionaryView.swift
index 5b1fdb9d..e33a4498 100644
--- a/Sources/Fluid/UI/CustomDictionaryView.swift
+++ b/Sources/Fluid/UI/CustomDictionaryView.swift
@@ -1,3 +1,5 @@
+// Existing UI composition; splitting it is outside this integration fix.
+// swiftlint:disable file_length
//
// CustomDictionaryView.swift
// fluid
diff --git a/Sources/Fluid/UI/DictionaryWordWizard.swift b/Sources/Fluid/UI/DictionaryWordWizard.swift
index 3581bbfa..3b143113 100644
--- a/Sources/Fluid/UI/DictionaryWordWizard.swift
+++ b/Sources/Fluid/UI/DictionaryWordWizard.swift
@@ -645,7 +645,11 @@ private struct DictionaryCompletionBloom: View, Animatable {
let centre = CGPoint(x: size.width / 2, y: size.height / 2)
let radius = min(size.width, size.height) * (0.27 + phase * 0.19)
let opacity = sin(phase * .pi)
- context.stroke(Path(ellipseIn: CGRect(x: centre.x - radius, y: centre.y - radius, width: radius * 2, height: radius * 2)), with: .color(self.color.opacity(opacity * 0.5)), lineWidth: 2 * (1 - phase) + 0.5)
+ context.stroke(
+ Path(ellipseIn: CGRect(x: centre.x - radius, y: centre.y - radius, width: radius * 2, height: radius * 2)),
+ with: .color(self.color.opacity(opacity * 0.5)),
+ lineWidth: 2 * (1 - phase) + 0.5
+ )
for index in 0..<16 {
let angle = Double(index) / 16 * .pi * 2
let length = 3 + (1 - phase) * 7
diff --git a/Sources/Fluid/UI/FluidIntelligenceDemoView.swift b/Sources/Fluid/UI/FluidIntelligenceDemoView.swift
index e142d731..4352f0d2 100644
--- a/Sources/Fluid/UI/FluidIntelligenceDemoView.swift
+++ b/Sources/Fluid/UI/FluidIntelligenceDemoView.swift
@@ -35,8 +35,16 @@ struct FluidIntelligenceDemoView: View {
Example(title: "Corrections", spoken: practice[0].spoken, expected: practice[0].expected),
Example(title: "Lists", spoken: practice[1].spoken, expected: practice[1].expected),
Example(title: "Paragraphs", spoken: practice[2].spoken, expected: practice[2].expected),
- Example(title: "Emails", spoken: "Hi Maya, thanks for the update. Could you send the revised plan by Friday? Thanks, Alex.", expected: "Hi Maya,\n\nThanks for the update. Could you send the revised plan by Friday?\n\nThanks,\nAlex"),
- Example(title: "Repetitions", spoken: "I think we should, we should review the plan tomorrow, um, before the meeting.", expected: "I think we should review the plan tomorrow before the meeting."),
+ Example(
+ title: "Emails",
+ spoken: "Hi Maya, thanks for the update. Could you send the revised plan by Friday? Thanks, Alex.",
+ expected: "Hi Maya,\n\nThanks for the update. Could you send the revised plan by Friday?\n\nThanks,\nAlex"
+ ),
+ Example(
+ title: "Repetitions",
+ spoken: "I think we should, we should review the plan tomorrow, um, before the meeting.",
+ expected: "I think we should review the plan tomorrow before the meeting."
+ ),
]
}()
@@ -94,7 +102,8 @@ struct FluidIntelligenceDemoView: View {
}
}
.fluidGlassAction(prominent: true)
- .disabled(self.runningSample || self.stoppingVoice || self.overlay.isProcessing || self.sandbox.isProcessing || self.asr.isStarting || !self.asr.isAsrReady || self.asr.micStatus != .authorized)
+ .disabled(self.runningSample || self.stoppingVoice || self.overlay.isProcessing || self.sandbox.isProcessing || self.asr.isStarting || !self.asr.isAsrReady || self.asr
+ .micStatus != .authorized)
} else {
Button("Set up Fluid Intelligence", action: self.onSetup).fluidGlassAction(prominent: true)
}
diff --git a/Sources/Fluid/UI/FluidOverlayPrimitives.swift b/Sources/Fluid/UI/FluidOverlayPrimitives.swift
index d24b57b4..e7d05580 100644
--- a/Sources/Fluid/UI/FluidOverlayPrimitives.swift
+++ b/Sources/Fluid/UI/FluidOverlayPrimitives.swift
@@ -45,7 +45,7 @@ struct FluidOverlayBorder: View {
var body: some View {
let shape = RoundedRectangle(cornerRadius: self.cornerRadius)
switch self.style {
- case .staticAngular(let angle, let lineWidth):
+ case let .staticAngular(angle, lineWidth):
shape.strokeBorder(
AngularGradient(
stops: FluidOverlayAngularBorderStops.dictationPill,
@@ -54,7 +54,7 @@ struct FluidOverlayBorder: View {
),
lineWidth: lineWidth
)
- case .linear(let topOpacity, let bottomOpacity, let lineWidth):
+ case let .linear(topOpacity, bottomOpacity, lineWidth):
shape.strokeBorder(
LinearGradient(
colors: [
diff --git a/Sources/Fluid/UI/MeetingDetectionPrompt.swift b/Sources/Fluid/UI/MeetingDetectionPrompt.swift
index 8456d298..f2415071 100644
--- a/Sources/Fluid/UI/MeetingDetectionPrompt.swift
+++ b/Sources/Fluid/UI/MeetingDetectionPrompt.swift
@@ -504,7 +504,7 @@ final class MeetingDetectionPromptController: ObservableObject {
static func defaultFrame(panelSize: NSSize, visibleFrame: NSRect) -> NSRect {
NSRect(
x: visibleFrame.midX - panelSize.width / 2,
- y: visibleFrame.maxY - panelSize.height - Self.defaultTopInset,
+ y: visibleFrame.maxY - panelSize.height - self.defaultTopInset,
width: panelSize.width,
height: panelSize.height
)
diff --git a/Sources/Fluid/UI/MeetingOverlayModels.swift b/Sources/Fluid/UI/MeetingOverlayModels.swift
index f910ad7f..493a2a98 100644
--- a/Sources/Fluid/UI/MeetingOverlayModels.swift
+++ b/Sources/Fluid/UI/MeetingOverlayModels.swift
@@ -171,7 +171,7 @@ struct MeetingOverlayPresentationReducer: Equatable, Sendable {
mutating func apply(_ event: MeetingOverlayPresentationEvent) {
switch event {
- case .recordingStarted(let sessionID):
+ case let .recordingStarted(sessionID):
guard self.sessionID != sessionID else { return }
self.sessionID = sessionID
self.presentation = MeetingOverlayPresentation(self.preference)
@@ -180,7 +180,7 @@ struct MeetingOverlayPresentationReducer: Equatable, Sendable {
case .recordingStopped:
self.sessionID = nil
self.presentation = nil
- case .preferenceChanged(let preference):
+ case let .preferenceChanged(preference):
self.preference = preference
case .toggleRequested:
guard self.sessionID != nil, let presentation else { return }
diff --git a/Sources/Fluid/UI/MeetingRecordingPill.swift b/Sources/Fluid/UI/MeetingRecordingPill.swift
index 20c42a4f..82f50108 100644
--- a/Sources/Fluid/UI/MeetingRecordingPill.swift
+++ b/Sources/Fluid/UI/MeetingRecordingPill.swift
@@ -10,6 +10,9 @@ final class MeetingRecordingPillController: ObservableObject {
@Published private(set) var presentation: MeetingOverlayPresentation = .pill
+ // Shared only by cooperating types in this file.
+
+ // swiftlint:disable:next strict_fileprivate
fileprivate static let overlayPadding = MeetingOverlayPadding.uniform(24)
private static let legacyAutosaveName = "MeetingRecordingPill"
private static let anchorCenterXKey = "MeetingRecordingOverlay.visibleAnchor.centerX"
@@ -61,7 +64,7 @@ final class MeetingRecordingPillController: ObservableObject {
private func handleCoordinatorState(_ state: MeetingCoordinatorState, coordinator: MeetingSessionCoordinator) {
switch state {
- case .recording(let sessionID), .recordingDegraded(let sessionID):
+ case let .recording(sessionID), let .recordingDegraded(sessionID):
if self.reducer.sessionID != sessionID {
self.invalidateTransition()
self.reducer.apply(.preferenceChanged(SettingsStore.shared.meetingOverlayPreference))
@@ -334,25 +337,24 @@ struct MeetingRecordingPillContent: View {
MeetingOverlayVisibility.isVisible(for: self.coordinator.state)
}
-
@ObservedObject private var pill = MeetingRecordingPillController.shared
var body: some View {
self.compactPill
- // The panel and its view persist across meetings; re-arm the stop button per recording.
- .onChange(of: self.isRecordingActive) { _, active in
- if active { self.isStopping = false }
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
- .padding(.top, MeetingRecordingPillController.overlayPadding.top)
- .padding(.leading, MeetingRecordingPillController.overlayPadding.left)
- .padding(.bottom, MeetingRecordingPillController.overlayPadding.bottom)
- .padding(.trailing, MeetingRecordingPillController.overlayPadding.right)
- .accessibilityElement(children: .contain)
- .accessibilityLabel("Meeting recording in progress")
- .accessibilityAction(named: "Stop Meeting Recording") {
- self.stopRecording()
- }
+ // The panel and its view persist across meetings; re-arm the stop button per recording.
+ .onChange(of: self.isRecordingActive) { _, active in
+ if active { self.isStopping = false }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
+ .padding(.top, MeetingRecordingPillController.overlayPadding.top)
+ .padding(.leading, MeetingRecordingPillController.overlayPadding.left)
+ .padding(.bottom, MeetingRecordingPillController.overlayPadding.bottom)
+ .padding(.trailing, MeetingRecordingPillController.overlayPadding.right)
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel("Meeting recording in progress")
+ .accessibilityAction(named: "Stop Meeting Recording") {
+ self.stopRecording()
+ }
}
private var compactSurface: some View {
diff --git a/Sources/Fluid/UI/MeetingRollingCaptionView.swift b/Sources/Fluid/UI/MeetingRollingCaptionView.swift
index b1337206..c761a849 100644
--- a/Sources/Fluid/UI/MeetingRollingCaptionView.swift
+++ b/Sources/Fluid/UI/MeetingRollingCaptionView.swift
@@ -35,7 +35,7 @@ struct MeetingRollingCaptionLayout {
let layoutManager: NSLayoutManager
static func inputSuffix(_ text: String) -> String {
- String(text.suffix(Self.maximumInputCharacters))
+ String(text.suffix(self.maximumInputCharacters))
}
static func make(_ text: String, width: CGFloat = contentSize.width, height: CGFloat = contentSize.height, foregroundColor: NSColor = .white) -> MeetingRollingCaptionLayout {
@@ -82,7 +82,14 @@ struct MeetingRollingCaptionLayout {
}
let selected = NSUnionRange(lines[first].glyphRange, lines[lines.count - 1].glyphRange)
let translation = CGPoint(x: -selectedInk.minX, y: height - selectedInk.maxY)
- return Self(attributedText: attributed, textStorage: storage, selectedGlyphRange: selected, translation: translation, inkBounds: selectedInk.offsetBy(dx: translation.x, dy: translation.y), layoutManager: manager)
+ return Self(
+ attributedText: attributed,
+ textStorage: storage,
+ selectedGlyphRange: selected,
+ translation: translation,
+ inkBounds: selectedInk.offsetBy(dx: translation.x, dy: translation.y),
+ layoutManager: manager
+ )
}
// A glyph taller/wider than the entire viewport cannot be shown as a complete line.
return Self(attributedText: attributed, textStorage: storage, selectedGlyphRange: NSRange(location: 0, length: 0), translation: .zero, inkBounds: .zero, layoutManager: manager)
@@ -90,8 +97,8 @@ struct MeetingRollingCaptionLayout {
}
final class MeetingRollingCaptionNSView: NSView {
- var text = "" { didSet { if oldValue != text { invalidateCaption() } } }
- var foregroundColor = NSColor.white { didSet { if !oldValue.isEqual(foregroundColor) { invalidateCaption() } } }
+ var text = "" { didSet { if oldValue != self.text { self.invalidateCaption() } } }
+ var foregroundColor = NSColor.white { didSet { if !oldValue.isEqual(self.foregroundColor) { self.invalidateCaption() } } }
private var cachedText = ""
private var cachedSize: CGSize = .zero
private var cachedColor: NSColor = .clear
@@ -119,16 +126,16 @@ final class MeetingRollingCaptionNSView: NSView {
private var captionLayout: MeetingRollingCaptionLayout {
if let cachedLayout, cachedText == text, cachedSize == bounds.size, cachedColor.isEqual(foregroundColor) { return cachedLayout }
- let value = MeetingRollingCaptionLayout.make(text, width: max(1, bounds.width), height: max(1, bounds.height), foregroundColor: foregroundColor)
- cachedText = text
- cachedSize = bounds.size
- cachedColor = foregroundColor
+ let value = MeetingRollingCaptionLayout.make(self.text, width: max(1, bounds.width), height: max(1, bounds.height), foregroundColor: self.foregroundColor)
+ self.cachedText = self.text
+ self.cachedSize = bounds.size
+ self.cachedColor = self.foregroundColor
cachedLayout = value
return value
}
private func invalidateCaption() {
- cachedLayout = nil
+ self.cachedLayout = nil
needsDisplay = true
}
}
diff --git a/Sources/Fluid/UI/MeetingSpeakerPalette.swift b/Sources/Fluid/UI/MeetingSpeakerPalette.swift
index f117f845..93e951c7 100644
--- a/Sources/Fluid/UI/MeetingSpeakerPalette.swift
+++ b/Sources/Fluid/UI/MeetingSpeakerPalette.swift
@@ -7,12 +7,12 @@ nonisolated enum MeetingSpeakerPalette {
/// Muted in light (pastels wash out on white), lifted in dark. Ordered so neighbouring
/// speakers stay distinguishable to the common forms of colour blindness.
private static let tints: [(light: (Int, Int, Int), dark: (Int, Int, Int))] = [
- (light: (0x33, 0x55, 0x86), dark: (0x84, 0xA9, 0xDA)),
- (light: (0x4C, 0x6C, 0x3D), dark: (0x93, 0xBB, 0x82)),
- (light: (0x8C, 0x4C, 0x33), dark: (0xDB, 0x93, 0x74)),
- (light: (0x5F, 0x42, 0x7C), dark: (0xAE, 0x92, 0xD2)),
- (light: (0x77, 0x5B, 0x18), dark: (0xC9, 0xAD, 0x55)),
- (light: (0x27, 0x62, 0x63), dark: (0x72, 0xB3, 0xB4)),
+ (light: (0x33, 0x55, 0x86), dark: (0x84, 0xa9, 0xda)),
+ (light: (0x4c, 0x6c, 0x3d), dark: (0x93, 0xbb, 0x82)),
+ (light: (0x8c, 0x4c, 0x33), dark: (0xdb, 0x93, 0x74)),
+ (light: (0x5f, 0x42, 0x7c), dark: (0xae, 0x92, 0xd2)),
+ (light: (0x77, 0x5b, 0x18), dark: (0xc9, 0xad, 0x55)),
+ (light: (0x27, 0x62, 0x63), dark: (0x72, 0xb3, 0xb4)),
]
static func rgb(forSpeakerIndex index: Int, isDark: Bool) -> (red: Int, green: Int, blue: Int) {
@@ -52,6 +52,6 @@ nonisolated enum MeetingSpeakerPalette {
}
static func tints(for speakers: [MeetingSessionSpeaker]) -> [SessionSpeakerID: Color] {
- Self.tintIndices(for: speakers).mapValues { Self.tint(forSpeakerIndex: $0) }
+ self.tintIndices(for: speakers).mapValues { Self.tint(forSpeakerIndex: $0) }
}
}
diff --git a/Sources/Fluid/UI/MeetingTranscriptionView.swift b/Sources/Fluid/UI/MeetingTranscriptionView.swift
index 73caabe3..a7256f88 100644
--- a/Sources/Fluid/UI/MeetingTranscriptionView.swift
+++ b/Sources/Fluid/UI/MeetingTranscriptionView.swift
@@ -1961,8 +1961,11 @@ private struct MeetingSetupCanvas: View {
self.sourceEntry("In person · mic only", systemImage: "person.2", selected: self.draft.mode == .inRoom) {
self.draft.mode = .inRoom
}
- self.sourceEntry("Automatic · follows a detected call", systemImage: "wand.and.stars",
- selected: self.draft.mode == .onlineCall && self.draft.usesAutomaticApplication) {
+ self.sourceEntry(
+ "Automatic · follows a detected call",
+ systemImage: "wand.and.stars",
+ selected: self.draft.mode == .onlineCall && self.draft.usesAutomaticApplication
+ ) {
self.draft.mode = .onlineCall
self.draft.usesAutomaticApplication = true
self.draft.selectedApplicationID = nil
@@ -2018,12 +2021,15 @@ private struct MeetingSetupCanvas: View {
private var recordingFooter: some View {
VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
- Label(self.resolvedApplication != nil
- ? "Stays on this Mac. Use headphones for clearer speaker separation."
- : "Stays on this Mac. Place it where everyone can be heard.", systemImage: "lock")
- .font(self.theme.typography.caption)
- .foregroundStyle(self.theme.palette.secondaryText)
- .fixedSize(horizontal: false, vertical: true)
+ Label(
+ self.resolvedApplication != nil
+ ? "Stays on this Mac. Use headphones for clearer speaker separation."
+ : "Stays on this Mac. Place it where everyone can be heard.",
+ systemImage: "lock"
+ )
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .fixedSize(horizontal: false, vertical: true)
if let errorMessage, !errorMessage.isEmpty {
Label(errorMessage, systemImage: "exclamationmark.triangle.fill")
@@ -2054,7 +2060,7 @@ private struct MeetingSetupCanvas: View {
if !self.readiness.isCheckingSources,
self.readiness.showScreenRecordingSettingsAction ||
(!self.canStart && (self.readiness.showMicrophoneSettingsAction ||
- !self.readiness.modelReady || !self.readiness.microphoneReady || self.draft.selectedMicrophoneID == nil))
+ !self.readiness.modelReady || !self.readiness.microphoneReady || self.draft.selectedMicrophoneID == nil))
{
Button(
self.readiness.showMicrophoneSettingsAction ? "Allow microphone access" :
diff --git a/Sources/Fluid/UI/WelcomeView.swift b/Sources/Fluid/UI/WelcomeView.swift
index b37697db..1fbe9644 100644
--- a/Sources/Fluid/UI/WelcomeView.swift
+++ b/Sources/Fluid/UI/WelcomeView.swift
@@ -1914,7 +1914,12 @@ struct OnboardingFlowView: View {
.stroke(accentColor.opacity(ringOpacity), lineWidth: configuration.isHovered && configuration.isEnabled ? 1.4 : 1)
.padding(-2)
)
- .shadow(color: accentColor.opacity(shadowOpacity), radius: configuration.isHovered && configuration.isEnabled ? 16 : 9, x: 0, y: configuration.isHovered && configuration.isEnabled ? 6 : 3)
+ .shadow(
+ color: accentColor.opacity(shadowOpacity),
+ radius: configuration.isHovered && configuration.isEnabled ? 16 : 9,
+ x: 0,
+ y: configuration.isHovered && configuration.isEnabled ? 6 : 3
+ )
)
.contentShape(shape)
}
diff --git a/Sources/Fluid/Views/OverlayCloseDiagnostics.swift b/Sources/Fluid/Views/OverlayCloseDiagnostics.swift
index d563b2f8..a1925d82 100644
--- a/Sources/Fluid/Views/OverlayCloseDiagnostics.swift
+++ b/Sources/Fluid/Views/OverlayCloseDiagnostics.swift
@@ -38,7 +38,10 @@ enum OverlayCloseRunLoopProbe {
let now = ProcessInfo.processInfo.systemUptime
let elapsed = (now - state.previousAt) * 1000
if state.previousPhase != CFRunLoopActivity.beforeWaiting.rawValue, elapsed > 8 {
- DebugLogger.shared.debug("CLOSE_DETAIL runLoop fromPhase=\(state.previousPhase) toPhase=\(activity.rawValue) startUptime=\(state.previousAt) occupiedMs=\(elapsed)", source: "StopTiming")
+ DebugLogger.shared.debug(
+ "CLOSE_DETAIL runLoop fromPhase=\(state.previousPhase) toPhase=\(activity.rawValue) startUptime=\(state.previousAt) occupiedMs=\(elapsed)",
+ source: "StopTiming"
+ )
}
state.previousAt = now
state.previousPhase = activity.rawValue
diff --git a/Sources/Fluid/fluidApp.swift b/Sources/Fluid/fluidApp.swift
index 11f17e75..b64b1c97 100644
--- a/Sources/Fluid/fluidApp.swift
+++ b/Sources/Fluid/fluidApp.swift
@@ -18,18 +18,18 @@ struct FluidApp: App {
var body: some Scene {
WindowGroup(id: "main") {
#if DEBUG
- if MeetingExternalReferenceTrialAGate.autorunEnabled(environment: ProcessInfo.processInfo.environment)
- || MeetingSCKPairedDiagnosticGate.autorunEnabled()
- || MeetingStage05EvidenceAutorun.requested()
- || ProcessInfo.processInfo.environment["FLUIDVOICE_MIC_PHASE1"] != nil
- || ProcessInfo.processInfo.environment["FLUIDVOICE_VPIO_ACOUSTIC"] == "1"
- {
- Color.clear
- } else {
- self.applicationContent
- }
- #else
+ if MeetingExternalReferenceTrialAGate.autorunEnabled(environment: ProcessInfo.processInfo.environment)
+ || MeetingSCKPairedDiagnosticGate.autorunEnabled()
+ || MeetingStage05EvidenceAutorun.requested()
+ || ProcessInfo.processInfo.environment["FLUIDVOICE_MIC_PHASE1"] != nil
+ || ProcessInfo.processInfo.environment["FLUIDVOICE_VPIO_ACOUSTIC"] == "1"
+ {
+ Color.clear
+ } else {
self.applicationContent
+ }
+ #else
+ self.applicationContent
#endif
}
.defaultSize(width: 1000, height: 700)
diff --git a/Tests/DictationDefaultProviderTests.swift b/Tests/DictationDefaultProviderTests.swift
index 160c59db..9c2353da 100644
--- a/Tests/DictationDefaultProviderTests.swift
+++ b/Tests/DictationDefaultProviderTests.swift
@@ -30,8 +30,12 @@ enum DictationDefaultProviderTests {
precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: true, hasAPIKey: false, hasModel: true, isVerified: true, verificationFailed: false) == "API key missing")
precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: false, hasAPIKey: false, hasModel: true, isVerified: true, verificationFailed: false) == nil)
precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: true, hasAPIKey: true, hasModel: false, isVerified: false, verificationFailed: false) == "Choose a model")
- precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: true, hasAPIKey: true, hasModel: true, isVerified: false, verificationFailed: false) == nil, "Optional verification must not block a configured provider")
- precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: true, hasAPIKey: true, hasModel: true, isVerified: false, verificationFailed: true) == "Verification failed")
+ precondition(
+ DictationDefaultProvider.setupIssue(requiresAPIKey: true, hasAPIKey: true, hasModel: true, isVerified: false, verificationFailed: false) == nil,
+ "Optional verification must not block a configured provider"
+ )
+ precondition(DictationDefaultProvider
+ .setupIssue(requiresAPIKey: true, hasAPIKey: true, hasModel: true, isVerified: false, verificationFailed: true) == "Verification failed")
print("PASS: 10 default-provider cases and 5 setup-status cases")
}
}
diff --git a/Tests/DictionaryMatchReportTests.swift b/Tests/DictionaryMatchReportTests.swift
index ef56232f..f670bd6c 100644
--- a/Tests/DictionaryMatchReportTests.swift
+++ b/Tests/DictionaryMatchReportTests.swift
@@ -49,7 +49,15 @@ struct DictionaryMatchReportTests {
precondition(legacy.matchThreshold == nil)
let individual = [Float(0.49), 0.83, 0.62].enumerated().map { index, score in
- DictionaryMatchReport.Candidate(id: "sample-\(index)", word: "ModelOpt", sampleNumber: index + 1, enrollmentCount: 3, eligible: true, score: score, heard: "sample \(index + 1)")
+ DictionaryMatchReport.Candidate(
+ id: "sample-\(index)",
+ word: "ModelOpt",
+ sampleNumber: index + 1,
+ enrollmentCount: 3,
+ eligible: true,
+ score: score,
+ heard: "sample \(index + 1)"
+ )
}
let selected = DictionaryMatchReport.bestCandidates(from: individual)
precondition(selected.count == 1 && selected[0].score == 0.83)
diff --git a/Tests/FluidASRBaselineHost/MeetingReferenceSynchronizerReplayCLI.swift b/Tests/FluidASRBaselineHost/MeetingReferenceSynchronizerReplayCLI.swift
index d6d84788..974c7e93 100644
--- a/Tests/FluidASRBaselineHost/MeetingReferenceSynchronizerReplayCLI.swift
+++ b/Tests/FluidASRBaselineHost/MeetingReferenceSynchronizerReplayCLI.swift
@@ -1,11 +1,11 @@
-import Foundation
import CryptoKit
+import Foundation
/// Codable, local-only input for the offline synchronizer replay command. The schema
/// deliberately contains numeric PCM fixture samples plus timing metadata and enum strings;
/// it never contains transcript text, embeddings, labels, or model artifacts. Raw fixture
/// samples are accepted as input but are never copied into command output.
-nonisolated public struct MeetingSynchronizerReplayFixture: Codable, Equatable, Sendable {
+public nonisolated struct MeetingSynchronizerReplayFixture: Codable, Equatable, Sendable {
public let schemaVersion: Int
public let configuration: MeetingSynchronizerReplayConfiguration
public let microphone: [MeetingSynchronizerReplayMicrophoneFrame]
@@ -24,7 +24,7 @@ nonisolated public struct MeetingSynchronizerReplayFixture: Codable, Equatable,
}
}
-nonisolated public struct MeetingSynchronizerReplayConfiguration: Codable, Equatable, Sendable {
+public nonisolated struct MeetingSynchronizerReplayConfiguration: Codable, Equatable, Sendable {
public var analysisSampleRate: Double
public var frameDuration: Double
public var microphoneAlgorithmicDelaySeconds: Double
@@ -57,7 +57,7 @@ nonisolated public struct MeetingSynchronizerReplayConfiguration: Codable, Equat
editListOffsetSeconds: Double = 0,
maximumInputFrameCount: Int = 16_384,
maximumInputSampleCount: Int = 2_000_000,
- maximumOutputFrameCount: Int = 6_000,
+ maximumOutputFrameCount: Int = 6000,
engineAvailable: Bool = true
) {
self.analysisSampleRate = analysisSampleRate
@@ -78,25 +78,31 @@ nonisolated public struct MeetingSynchronizerReplayConfiguration: Codable, Equat
self.engineAvailable = engineAvailable
}
- fileprivate func makeSynchronizerConfiguration() -> MeetingReferenceSynchronizerConfiguration? {
+ func makeSynchronizerConfiguration() -> MeetingReferenceSynchronizerConfiguration? {
guard let scope = MeetingReferenceScope(rawValue: referenceScope),
let completeness = MeetingReferenceCompleteness(rawValue: referenceCompleteness) else { return nil }
return MeetingReferenceSynchronizerConfiguration(
- analysisSampleRate: analysisSampleRate, frameDuration: frameDuration,
- microphoneConverter: .init(algorithmicDelaySeconds: microphoneAlgorithmicDelaySeconds),
- referenceConverter: .init(algorithmicDelaySeconds: referenceAlgorithmicDelaySeconds),
- referenceToMicrophoneOffsetSeconds: referenceToMicrophoneOffsetSeconds,
- referenceClockDriftPPM: referenceClockDriftPPM, maximumClockDriftPPM: maximumClockDriftPPM,
- referenceScope: scope, referenceCompleteness: completeness,
- codecPrimingSamples: codecPrimingSamples, codecRemainderSamples: codecRemainderSamples,
- editListOffsetSeconds: editListOffsetSeconds,
- maximumInputFrameCount: maximumInputFrameCount,
- maximumInputSampleCount: maximumInputSampleCount,
- maximumOutputFrameCount: maximumOutputFrameCount, engineAvailable: engineAvailable)
+ analysisSampleRate: self.analysisSampleRate,
+ frameDuration: self.frameDuration,
+ microphoneConverter: .init(algorithmicDelaySeconds: self.microphoneAlgorithmicDelaySeconds),
+ referenceConverter: .init(algorithmicDelaySeconds: self.referenceAlgorithmicDelaySeconds),
+ referenceToMicrophoneOffsetSeconds: self.referenceToMicrophoneOffsetSeconds,
+ referenceClockDriftPPM: self.referenceClockDriftPPM,
+ maximumClockDriftPPM: self.maximumClockDriftPPM,
+ referenceScope: scope,
+ referenceCompleteness: completeness,
+ codecPrimingSamples: self.codecPrimingSamples,
+ codecRemainderSamples: self.codecRemainderSamples,
+ editListOffsetSeconds: self.editListOffsetSeconds,
+ maximumInputFrameCount: self.maximumInputFrameCount,
+ maximumInputSampleCount: self.maximumInputSampleCount,
+ maximumOutputFrameCount: self.maximumOutputFrameCount,
+ engineAvailable: self.engineAvailable
+ )
}
}
-nonisolated public struct MeetingSynchronizerReplayMicrophoneFrame: Codable, Equatable, Sendable {
+public nonisolated struct MeetingSynchronizerReplayMicrophoneFrame: Codable, Equatable, Sendable {
public let sequenceNumber: Int
public let sampleTime: Int64
public let hostTime: Double?
@@ -106,22 +112,36 @@ nonisolated public struct MeetingSynchronizerReplayMicrophoneFrame: Codable, Equ
public let routeIdentifier: String
public let discontinuity: Bool
- public init(sequenceNumber: Int, sampleTime: Int64, hostTime: Double?, sampleRate: Double,
- channelCount: Int = 1, samples: [Float], routeIdentifier: String = "default",
- discontinuity: Bool = false) {
+ public init(
+ sequenceNumber: Int,
+ sampleTime: Int64,
+ hostTime: Double?,
+ sampleRate: Double,
+ channelCount: Int = 1,
+ samples: [Float],
+ routeIdentifier: String = "default",
+ discontinuity: Bool = false
+ ) {
self.sequenceNumber = sequenceNumber; self.sampleTime = sampleTime; self.hostTime = hostTime
self.sampleRate = sampleRate; self.channelCount = channelCount; self.samples = samples
self.routeIdentifier = routeIdentifier; self.discontinuity = discontinuity
}
- fileprivate func makeFrame() -> MeetingMicrophonePCMFrame {
- .init(sequenceNumber: sequenceNumber, sampleTime: sampleTime, hostTime: hostTime,
- sampleRate: sampleRate, channelCount: channelCount, samples: samples,
- routeIdentifier: routeIdentifier, discontinuity: discontinuity)
+ func makeFrame() -> MeetingMicrophonePCMFrame {
+ .init(
+ sequenceNumber: self.sequenceNumber,
+ sampleTime: self.sampleTime,
+ hostTime: self.hostTime,
+ sampleRate: self.sampleRate,
+ channelCount: self.channelCount,
+ samples: self.samples,
+ routeIdentifier: self.routeIdentifier,
+ discontinuity: self.discontinuity
+ )
}
}
-nonisolated public struct MeetingSynchronizerReplayReferenceFrame: Codable, Equatable, Sendable {
+public nonisolated struct MeetingSynchronizerReplayReferenceFrame: Codable, Equatable, Sendable {
public let sequenceNumber: Int
public let presentationTime: Double
public let sampleRate: Double
@@ -129,21 +149,32 @@ nonisolated public struct MeetingSynchronizerReplayReferenceFrame: Codable, Equa
public let samples: [Float]
public let discontinuity: Bool
- public init(sequenceNumber: Int, presentationTime: Double, sampleRate: Double,
- channelCount: Int = 1, samples: [Float], discontinuity: Bool = false) {
+ public init(
+ sequenceNumber: Int,
+ presentationTime: Double,
+ sampleRate: Double,
+ channelCount: Int = 1,
+ samples: [Float],
+ discontinuity: Bool = false
+ ) {
self.sequenceNumber = sequenceNumber; self.presentationTime = presentationTime
self.sampleRate = sampleRate; self.channelCount = channelCount; self.samples = samples
self.discontinuity = discontinuity
}
- fileprivate func makeFrame() -> MeetingReferencePCMFrame {
- .init(sequenceNumber: sequenceNumber, presentationTime: presentationTime,
- sampleRate: sampleRate, channelCount: channelCount, samples: samples,
- discontinuity: discontinuity)
+ func makeFrame() -> MeetingReferencePCMFrame {
+ .init(
+ sequenceNumber: self.sequenceNumber,
+ presentationTime: self.presentationTime,
+ sampleRate: self.sampleRate,
+ channelCount: self.channelCount,
+ samples: self.samples,
+ discontinuity: self.discontinuity
+ )
}
}
-nonisolated public struct MeetingSynchronizerReplayOutput: Codable, Equatable, Sendable {
+public nonisolated struct MeetingSynchronizerReplayOutput: Codable, Equatable, Sendable {
public let schemaVersion: Int
public let replayIdentity: String
public let failedOpen: Bool
@@ -164,7 +195,7 @@ nonisolated public struct MeetingSynchronizerReplayOutput: Codable, Equatable, S
public let diagnostics: MeetingSynchronizerReplayDiagnostics
}
-nonisolated public struct MeetingSynchronizerReplayDiagnostics: Codable, Equatable, Sendable {
+public nonisolated struct MeetingSynchronizerReplayDiagnostics: Codable, Equatable, Sendable {
public let inputFrameCount: Int
public let droppedFrameCount: Int
public let duplicateOrLateFrameCount: Int
@@ -177,7 +208,7 @@ nonisolated public struct MeetingSynchronizerReplayDiagnostics: Codable, Equatab
/// Local-only command implementation. It is inert unless the caller supplies the explicit
/// `--offline-synchronizer-replay` argument or `FLUID_ASR_OFFLINE_REPLAY=1` environment gate.
-nonisolated public enum MeetingReferenceSynchronizerReplayCLI {
+public nonisolated enum MeetingReferenceSynchronizerReplayCLI {
public static let argument = "--offline-synchronizer-replay"
public static let environmentKey = "FLUID_ASR_OFFLINE_REPLAY"
@@ -186,51 +217,57 @@ nonisolated public enum MeetingReferenceSynchronizerReplayCLI {
public static let maximumInputBytes = 64 * 1024 * 1024
private static let hardMaximumInputFrames = 50_000
private static let hardMaximumInputSamples = 2_000_000
- private static let hardMaximumOutputFrames = 6_000
+ private static let hardMaximumOutputFrames = 6000
private static let hardMaximumOutputSamples = 1_000_000
private static let hardMaximumSourceSampleRate = 384_000.0
private static let hardMaximumChannelCount = 32
@discardableResult
- public static func run(arguments: [String], environment: [String: String] = ProcessInfo.processInfo.environment,
- inputData stdinData: Data, output: (Data) -> Void) -> Int32 {
- let gate = arguments.contains(argument) || environment[environmentKey] == "1"
- guard gate else { output(errorData(code: "offlineGateRequired")); return 2 }
+ public static func run(
+ arguments: [String],
+ environment: [String: String] = ProcessInfo.processInfo.environment,
+ inputData stdinData: Data,
+ output: (Data) -> Void
+ ) -> Int32 {
+ let gate = arguments.contains(self.argument) || environment[self.environmentKey] == "1"
+ guard gate else { output(self.errorData(code: "offlineGateRequired")); return 2 }
guard let data = inputData(arguments: arguments, stdin: stdinData),
- let fixture = decodeFixture(data), validate(fixture), let config = fixture.configuration.makeSynchronizerConfiguration() else {
- output(errorData(code: "invalidInput")); return 2
+ let fixture = decodeFixture(data), validate(fixture), let config = fixture.configuration.makeSynchronizerConfiguration()
+ else {
+ output(self.errorData(code: "invalidInput")); return 2
}
let result = MeetingReferenceSynchronizer(configuration: config).synchronize(
- microphone: fixture.microphone.map { $0.makeFrame() }, reference: fixture.reference.map { $0.makeFrame() })
+ microphone: fixture.microphone.map { $0.makeFrame() }, reference: fixture.reference.map { $0.makeFrame() }
+ )
guard let canonical = try? canonicalData(fixture) else {
- output(errorData(code: "canonicalEncodingFailed")); return 3
+ output(self.errorData(code: "canonicalEncodingFailed")); return 3
}
let identity = "synchronizer-replay-v1-" + SHA256.hash(data: canonical).map { String(format: "%02x", $0) }.joined()
- let summary = makeOutput(result, identity: identity)
- guard let data = try? encoded(summary) else { output(errorData(code: "outputEncodingFailed")); return 3 }
+ let summary = self.makeOutput(result, identity: identity)
+ guard let data = try? encoded(summary) else { output(self.errorData(code: "outputEncodingFailed")); return 3 }
output(data); return result.failedOpen ? 1 : 0
}
/// Read at most `maximumInputBytes + 1` bytes so oversized stdin cannot be
/// materialized without bound before JSON validation.
public static func readBoundedStandardInput() -> Data? {
- readBounded(FileHandle.standardInput)
+ self.readBounded(FileHandle.standardInput)
}
private static func inputData(arguments: [String], stdin: Data) -> Data? {
guard let index = arguments.firstIndex(of: "--input") else {
- return stdin.count <= maximumInputBytes ? stdin : nil
+ return stdin.count <= self.maximumInputBytes ? stdin : nil
}
guard arguments.indices.contains(index + 1), !arguments[index + 1].isEmpty else { return nil }
guard let handle = try? FileHandle(forReadingFrom: URL(fileURLWithPath: arguments[index + 1])) else { return nil }
defer { try? handle.close() }
- return readBounded(handle)
+ return self.readBounded(handle)
}
private static func readBounded(_ handle: FileHandle) -> Data? {
var result = Data()
while true {
- let remaining = maximumInputBytes - result.count
+ let remaining = self.maximumInputBytes - result.count
guard remaining >= 0 else { return nil }
let chunk: Data
do {
@@ -240,7 +277,7 @@ nonisolated public enum MeetingReferenceSynchronizerReplayCLI {
}
guard !chunk.isEmpty else { return result }
result.append(chunk)
- if result.count > maximumInputBytes { return nil }
+ if result.count > self.maximumInputBytes { return nil }
}
}
@@ -248,29 +285,51 @@ nonisolated public enum MeetingReferenceSynchronizerReplayCLI {
guard let object = try? JSONSerialization.jsonObject(with: data),
let root = object as? [String: Any], strictKeys(root, ["schemaVersion", "configuration", "microphone", "reference"]) else { return nil }
guard let configuration = root["configuration"] as? [String: Any],
- strictKeys(configuration, ["analysisSampleRate", "frameDuration", "microphoneAlgorithmicDelaySeconds", "referenceAlgorithmicDelaySeconds", "referenceToMicrophoneOffsetSeconds", "referenceClockDriftPPM", "maximumClockDriftPPM", "referenceScope", "referenceCompleteness", "codecPrimingSamples", "codecRemainderSamples", "editListOffsetSeconds", "maximumInputFrameCount", "maximumInputSampleCount", "maximumOutputFrameCount", "engineAvailable"]),
+ strictKeys(
+ configuration,
+ [
+ "analysisSampleRate",
+ "frameDuration",
+ "microphoneAlgorithmicDelaySeconds",
+ "referenceAlgorithmicDelaySeconds",
+ "referenceToMicrophoneOffsetSeconds",
+ "referenceClockDriftPPM",
+ "maximumClockDriftPPM",
+ "referenceScope",
+ "referenceCompleteness",
+ "codecPrimingSamples",
+ "codecRemainderSamples",
+ "editListOffsetSeconds",
+ "maximumInputFrameCount",
+ "maximumInputSampleCount",
+ "maximumOutputFrameCount",
+ "engineAvailable",
+ ]
+ ),
let microphone = root["microphone"] as? [[String: Any]],
let reference = root["reference"] as? [[String: Any]],
- microphone.allSatisfy({ strictKeys($0,
+ microphone.allSatisfy({ strictKeys(
+ $0,
required: ["sequenceNumber", "sampleTime", "sampleRate", "channelCount", "samples", "routeIdentifier", "discontinuity"],
- allowed: ["sequenceNumber", "sampleTime", "hostTime", "sampleRate", "channelCount", "samples", "routeIdentifier", "discontinuity"]) }),
+ allowed: ["sequenceNumber", "sampleTime", "hostTime", "sampleRate", "channelCount", "samples", "routeIdentifier", "discontinuity"]
+ ) }),
reference.allSatisfy({ strictKeys($0, ["sequenceNumber", "presentationTime", "sampleRate", "channelCount", "samples", "discontinuity"]) }) else { return nil }
return try? JSONDecoder().decode(MeetingSynchronizerReplayFixture.self, from: data)
}
private static func validate(_ fixture: MeetingSynchronizerReplayFixture) -> Bool {
guard fixture.schemaVersion == 1,
- finitePositive(fixture.configuration.analysisSampleRate), fixture.configuration.analysisSampleRate <= 384_000,
- finitePositive(fixture.configuration.frameDuration), fixture.configuration.frameDuration <= 10,
- finite(fixture.configuration.microphoneAlgorithmicDelaySeconds), finite(fixture.configuration.referenceAlgorithmicDelaySeconds),
- finite(fixture.configuration.referenceToMicrophoneOffsetSeconds), finite(fixture.configuration.editListOffsetSeconds),
- finite(fixture.configuration.referenceClockDriftPPM), finite(fixture.configuration.maximumClockDriftPPM),
+ self.finitePositive(fixture.configuration.analysisSampleRate), fixture.configuration.analysisSampleRate <= 384_000,
+ self.finitePositive(fixture.configuration.frameDuration), fixture.configuration.frameDuration <= 10,
+ self.finite(fixture.configuration.microphoneAlgorithmicDelaySeconds), self.finite(fixture.configuration.referenceAlgorithmicDelaySeconds),
+ self.finite(fixture.configuration.referenceToMicrophoneOffsetSeconds), self.finite(fixture.configuration.editListOffsetSeconds),
+ self.finite(fixture.configuration.referenceClockDriftPPM), self.finite(fixture.configuration.maximumClockDriftPPM),
fixture.configuration.maximumClockDriftPPM >= 0,
abs(fixture.configuration.referenceClockDriftPPM) <= fixture.configuration.maximumClockDriftPPM,
fixture.configuration.codecPrimingSamples >= 0, fixture.configuration.codecRemainderSamples >= 0,
- fixture.configuration.maximumInputFrameCount > 0, fixture.configuration.maximumInputFrameCount <= hardMaximumInputFrames,
- fixture.configuration.maximumInputSampleCount > 0, fixture.configuration.maximumInputSampleCount <= hardMaximumInputSamples,
- fixture.configuration.maximumOutputFrameCount > 0, fixture.configuration.maximumOutputFrameCount <= hardMaximumOutputFrames,
+ fixture.configuration.maximumInputFrameCount > 0, fixture.configuration.maximumInputFrameCount <= self.hardMaximumInputFrames,
+ fixture.configuration.maximumInputSampleCount > 0, fixture.configuration.maximumInputSampleCount <= self.hardMaximumInputSamples,
+ fixture.configuration.maximumOutputFrameCount > 0, fixture.configuration.maximumOutputFrameCount <= self.hardMaximumOutputFrames,
fixture.microphone.count <= fixture.configuration.maximumInputFrameCount,
fixture.reference.count <= fixture.configuration.maximumInputFrameCount else { return false }
let (inputFrames, inputFrameOverflow) = fixture.microphone.count
@@ -278,11 +337,11 @@ nonisolated public enum MeetingReferenceSynchronizerReplayCLI {
guard !inputFrameOverflow, inputFrames <= fixture.configuration.maximumInputFrameCount else { return false }
let frameProduct = fixture.configuration.analysisSampleRate * fixture.configuration.frameDuration
let frameSize = frameProduct.rounded()
- guard frameProduct.isFinite, frameSize >= 1, frameSize <= Double(hardMaximumOutputSamples),
+ guard frameProduct.isFinite, frameSize >= 1, frameSize <= Double(self.hardMaximumOutputSamples),
frameSize < Double(Int.max) else { return false }
let (outputSamples, outputOverflow) = fixture.configuration.maximumOutputFrameCount
.multipliedReportingOverflow(by: Int(frameSize))
- guard !outputOverflow, outputSamples <= hardMaximumOutputSamples else { return false }
+ guard !outputOverflow, outputSamples <= self.hardMaximumOutputSamples else { return false }
var allSamples = 0
for count in fixture.microphone.map(\.samples.count) + fixture.reference.map(\.samples.count) {
let (sum, overflow) = allSamples.addingReportingOverflow(max(0, count))
@@ -290,21 +349,21 @@ nonisolated public enum MeetingReferenceSynchronizerReplayCLI {
allSamples = sum
}
guard allSamples <= fixture.configuration.maximumInputSampleCount else { return false }
- guard fixture.microphone.allSatisfy(validate), fixture.reference.allSatisfy(validate) else { return false }
+ guard fixture.microphone.allSatisfy(self.validate), fixture.reference.allSatisfy(self.validate) else { return false }
return true
}
private static func validate(_ frame: MeetingSynchronizerReplayMicrophoneFrame) -> Bool {
- !frame.samples.isEmpty && frame.channelCount > 0 && frame.channelCount <= hardMaximumChannelCount
- && finitePositive(frame.sampleRate) && frame.sampleRate <= hardMaximumSourceSampleRate
+ !frame.samples.isEmpty && frame.channelCount > 0 && frame.channelCount <= self.hardMaximumChannelCount
+ && self.finitePositive(frame.sampleRate) && frame.sampleRate <= self.hardMaximumSourceSampleRate
&& frame.samples.count % frame.channelCount == 0
- && frame.samples.allSatisfy(\.isFinite) && (frame.hostTime.map(finite) ?? true)
+ && frame.samples.allSatisfy(\.isFinite) && (frame.hostTime.map(self.finite) ?? true)
}
private static func validate(_ frame: MeetingSynchronizerReplayReferenceFrame) -> Bool {
- !frame.samples.isEmpty && frame.channelCount > 0 && frame.channelCount <= hardMaximumChannelCount
- && finitePositive(frame.sampleRate) && frame.sampleRate <= hardMaximumSourceSampleRate
- && finite(frame.presentationTime)
+ !frame.samples.isEmpty && frame.channelCount > 0 && frame.channelCount <= self.hardMaximumChannelCount
+ && self.finitePositive(frame.sampleRate) && frame.sampleRate <= self.hardMaximumSourceSampleRate
+ && self.finite(frame.presentationTime)
&& frame.samples.count % frame.channelCount == 0 && frame.samples.allSatisfy(\.isFinite)
}
@@ -313,32 +372,51 @@ nonisolated public enum MeetingReferenceSynchronizerReplayCLI {
let captureValid = frames.reduce(0) { $0 + $1.captureValidMask.filter { $0 }.count }
let renderValid = frames.reduce(0) { $0 + $1.renderValidMask.filter { $0 }.count }
var reasons: [String: Int] = [:]
- for frame in frames { for reason in frame.unknownReasons { reasons[reason.rawValue, default: 0] += 1 } }
+ for frame in frames {
+ for reason in frame.unknownReasons {
+ reasons[reason.rawValue, default: 0] += 1
+ }
+ }
var epochs = [Int](repeating: 0, count: max(0, (frames.map(\.epochID).max() ?? -1) + 1))
- for frame in frames where frame.epochID >= 0 && frame.epochID < epochs.count { epochs[frame.epochID] += 1 }
+ for frame in frames where frame.epochID >= 0 && frame.epochID < epochs.count {
+ epochs[frame.epochID] += 1
+ }
let sessions = frames.map { ($0.sessionStartTime, $0.sessionEndTime) }
let micTimes = frames.compactMap { $0.timelines.microphoneSourceTime }
let refTimes = frames.compactMap { $0.timelines.referencePTSTime }
- return .init(schemaVersion: 1, replayIdentity: identity, failedOpen: result.failedOpen,
- failureReason: result.failureReason?.rawValue, frameCount: frames.count,
- captureValidSampleCount: captureValid, captureInvalidSampleCount: frames.reduce(0) { $0 + $1.captureValidMask.filter { !$0 }.count },
- renderValidSampleCount: renderValid, renderInvalidSampleCount: frames.reduce(0) { $0 + $1.renderValidMask.filter { !$0 }.count },
- unknownReasonCounts: reasons, epochFrameCounts: epochs,
- sessionStartTime: sessions.map(\.0).min(), sessionEndTime: sessions.map(\.1).max(),
- microphoneSourceObservedMinimumTime: micTimes.min(), microphoneSourceObservedMaximumTime: micTimes.max(),
- referencePTSObservedMinimumTime: refTimes.min(), referencePTSObservedMaximumTime: refTimes.max(),
- diagnostics: .init(inputFrameCount: result.diagnostics.inputFrameCount,
+ return .init(
+ schemaVersion: 1,
+ replayIdentity: identity,
+ failedOpen: result.failedOpen,
+ failureReason: result.failureReason?.rawValue,
+ frameCount: frames.count,
+ captureValidSampleCount: captureValid,
+ captureInvalidSampleCount: frames.reduce(0) { $0 + $1.captureValidMask.filter { !$0 }.count },
+ renderValidSampleCount: renderValid,
+ renderInvalidSampleCount: frames.reduce(0) { $0 + $1.renderValidMask.filter { !$0 }.count },
+ unknownReasonCounts: reasons,
+ epochFrameCounts: epochs,
+ sessionStartTime: sessions.map(\.0).min(),
+ sessionEndTime: sessions.map(\.1).max(),
+ microphoneSourceObservedMinimumTime: micTimes.min(),
+ microphoneSourceObservedMaximumTime: micTimes.max(),
+ referencePTSObservedMinimumTime: refTimes.min(),
+ referencePTSObservedMaximumTime: refTimes.max(),
+ diagnostics: .init(
+ inputFrameCount: result.diagnostics.inputFrameCount,
droppedFrameCount: result.diagnostics.droppedFrameCount,
duplicateOrLateFrameCount: result.diagnostics.duplicateOrLateFrameCount,
nonFiniteSampleCount: result.diagnostics.nonFiniteSampleCount,
epochCount: result.diagnostics.epochCount,
synthesizedMicrophoneFrameCount: result.diagnostics.synthesizedMicrophoneFrameCount,
boundedResourceFailure: result.diagnostics.boundedResourceFailure,
- referenceClockDriftPPM: result.diagnostics.referenceClockDriftPPM))
+ referenceClockDriftPPM: result.diagnostics.referenceClockDriftPPM
+ )
+ )
}
private static func canonicalData(_ fixture: MeetingSynchronizerReplayFixture) throws -> Data {
- try encoded(fixture)
+ try self.encoded(fixture)
}
private static func encoded<T: Encodable>(_ value: T) throws -> Data {
@@ -348,7 +426,7 @@ nonisolated public enum MeetingReferenceSynchronizerReplayCLI {
private static func errorData(code: String) -> Data {
struct ErrorOutput: Encodable { let schemaVersion: Int; let errorCode: String }
- return (try? encoded(ErrorOutput(schemaVersion: 1, errorCode: code)))
+ return (try? self.encoded(ErrorOutput(schemaVersion: 1, errorCode: code)))
?? Data("{\"schemaVersion\":1,\"errorCode\":\"outputEncodingFailed\"}".utf8)
}
diff --git a/Tests/FluidASRBaselineHost/main.swift b/Tests/FluidASRBaselineHost/main.swift
index c0e99adb..1361554d 100644
--- a/Tests/FluidASRBaselineHost/main.swift
+++ b/Tests/FluidASRBaselineHost/main.swift
@@ -2,7 +2,8 @@ import AppKit
import Foundation
if CommandLine.arguments.contains(MeetingReferenceSynchronizerReplayCLI.argument)
- || ProcessInfo.processInfo.environment[MeetingReferenceSynchronizerReplayCLI.environmentKey] == "1" {
+ || ProcessInfo.processInfo.environment[MeetingReferenceSynchronizerReplayCLI.environmentKey] == "1"
+{
let status = MeetingReferenceSynchronizerReplayCLI.run(
arguments: CommandLine.arguments,
// A path-selected replay does not need stdin. Avoid waiting on an attached
@@ -11,8 +12,9 @@ if CommandLine.arguments.contains(MeetingReferenceSynchronizerReplayCLI.argument
? Data() : (MeetingReferenceSynchronizerReplayCLI.readBoundedStandardInput() ?? Data()),
output: { data in
FileHandle.standardOutput.write(data)
- FileHandle.standardOutput.write(Data([0x0A]))
- })
+ FileHandle.standardOutput.write(Data([0x0a]))
+ }
+ )
exit(status)
}
diff --git a/Tests/FluidASRBaselineTests/MeetingLiveP0DiagnosticsTests.swift b/Tests/FluidASRBaselineTests/MeetingLiveP0DiagnosticsTests.swift
index 8b42ceb0..2ec177f5 100644
--- a/Tests/FluidASRBaselineTests/MeetingLiveP0DiagnosticsTests.swift
+++ b/Tests/FluidASRBaselineTests/MeetingLiveP0DiagnosticsTests.swift
@@ -1,6 +1,6 @@
-@testable import FluidASRBaselineHost
import AVFoundation
import CoreMedia
+@testable import FluidASRBaselineHost
import Foundation
import XCTest
@@ -9,8 +9,8 @@ final class MeetingLiveP0DiagnosticsTests: XCTestCase {
private final class Clock: @unchecked Sendable {
private let lock = NSLock()
private var value: Double = 0
- func now() -> Double { lock.lock(); defer { lock.unlock() }; return value }
- func set(_ value: Double) { lock.lock(); defer { lock.unlock() }; self.value = value }
+ func now() -> Double { self.lock.lock(); defer { lock.unlock() }; return self.value }
+ func set(_ value: Double) { self.lock.lock(); defer { lock.unlock() }; self.value = value }
}
private actor Recognizer: MeetingLiveRecognizer {
@@ -20,30 +20,47 @@ final class MeetingLiveP0DiagnosticsTests: XCTestCase {
init(process: @escaping @Sendable () throws -> Void = {}) { self.process = process }
func prepareModels() async throws { XCTFail("P0 deterministic tests must not load models") }
func appendAudio(_ buffer: AVAudioPCMBuffer) async throws {}
- func processBufferedAudio() async throws { processed += 1; try process() }
- func reset() async { resets += 1 }
+ func processBufferedAudio() async throws { self.processed += 1; try self.process() }
+ func reset() async { self.resets += 1 }
func setEouCallback(_ callback: @escaping @Sendable (String) -> Void) async {}
func setPartialTranscriptCallback(_ callback: @escaping @Sendable (String) -> Void) async {}
}
private func sample(at seconds: Double) -> MeetingLiveSampleCopy.Sample {
- let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16_000,
- channels: 1, interleaved: false)!
+ let format = AVAudioFormat(
+ commonFormat: .pcmFormatFloat32,
+ sampleRate: 16_000,
+ channels: 1,
+ interleaved: false
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ )!
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 1600)!
buffer.frameLength = 1600
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
buffer.floatChannelData![0].update(repeating: 0, count: 1600)
- return .init(buffer: buffer, pts: CMTime(seconds: seconds, preferredTimescale: 16_000),
- duration: CMTime(seconds: 0.1, preferredTimescale: 16_000))
+ return .init(
+ buffer: buffer,
+ pts: CMTime(seconds: seconds, preferredTimescale: 16_000),
+ duration: CMTime(seconds: 0.1, preferredTimescale: 16_000)
+ )
}
func testExistingWatchdogCannotRotateBeforeFirstPartial() async {
let clock = Clock()
let recognizer = Recognizer()
- let engine = MeetingLiveTrackEngine(kind: .microphone, recognizer: recognizer,
- uptime: { clock.now() }, diagnosticsEnabled: true)
+ let engine = MeetingLiveTrackEngine(
+ kind: .microphone,
+ recognizer: recognizer,
+ uptime: { clock.now() },
+ diagnosticsEnabled: true
+ )
for index in 0..<400 {
clock.set(Double(index) / 10)
- await engine.diagnosticConsume(sample(at: clock.now()))
+ await engine.diagnosticConsume(self.sample(at: clock.now()))
}
let snapshot = await engine.diagnosticSnapshotValue()
XCTAssertEqual(snapshot.processCompletions, 400)
@@ -57,19 +74,23 @@ final class MeetingLiveP0DiagnosticsTests: XCTestCase {
func testForcedBoundaryThen38SecondsWithoutPartialDoesNotRecover() async {
let clock = Clock()
let recognizer = Recognizer()
- let engine = MeetingLiveTrackEngine(kind: .microphone, recognizer: recognizer,
- uptime: { clock.now() }, diagnosticsEnabled: true)
- await engine.diagnosticConsume(sample(at: 0))
+ let engine = MeetingLiveTrackEngine(
+ kind: .microphone,
+ recognizer: recognizer,
+ uptime: { clock.now() },
+ diagnosticsEnabled: true
+ )
+ await engine.diagnosticConsume(self.sample(at: 0))
await engine.diagnosticPartial("synthetic fixture")
// Advance audio time while keeping wall-clock partial stall below its threshold, so
// the hard duration boundary (not a quiet timeout) initiates the reset.
clock.set(1)
- await engine.diagnosticConsume(sample(at: 21))
+ await engine.diagnosticConsume(self.sample(at: 21))
var snapshot = await engine.diagnosticSnapshotValue()
XCTAssertEqual(snapshot.resetInvocations, 1)
for index in 1...380 {
clock.set(1 + Double(index) / 10)
- await engine.diagnosticConsume(sample(at: 21 + Double(index) / 10))
+ await engine.diagnosticConsume(self.sample(at: 21 + Double(index) / 10))
}
snapshot = await engine.diagnosticSnapshotValue()
XCTAssertEqual(snapshot.processCompletions, 382)
@@ -83,7 +104,7 @@ final class MeetingLiveP0DiagnosticsTests: XCTestCase {
func testDiagnosticsCanBeExplicitlyDisabled() async {
let engine = MeetingLiveTrackEngine(kind: .microphone, recognizer: Recognizer(), diagnosticsEnabled: false)
- await engine.diagnosticConsume(sample(at: 0))
+ await engine.diagnosticConsume(self.sample(at: 0))
let snapshot = await engine.diagnosticSnapshotValue()
XCTAssertEqual(snapshot.processStarts, 0)
XCTAssertEqual(snapshot.convertedBuffers, 0)
@@ -92,9 +113,13 @@ final class MeetingLiveP0DiagnosticsTests: XCTestCase {
func testProcessLatencyUsesInjectedClockWithoutSleeping() async {
let clock = Clock()
let recognizer = Recognizer(process: { clock.set(7) })
- let engine = MeetingLiveTrackEngine(kind: .microphone, recognizer: recognizer,
- uptime: { clock.now() }, diagnosticsEnabled: true)
- await engine.diagnosticConsume(sample(at: 0))
+ let engine = MeetingLiveTrackEngine(
+ kind: .microphone,
+ recognizer: recognizer,
+ uptime: { clock.now() },
+ diagnosticsEnabled: true
+ )
+ await engine.diagnosticConsume(self.sample(at: 0))
let snapshot = await engine.diagnosticSnapshotValue()
XCTAssertEqual(snapshot.appendStarts, 1)
XCTAssertEqual(snapshot.appendCompletions, 1)
@@ -106,9 +131,12 @@ final class MeetingLiveP0DiagnosticsTests: XCTestCase {
func testThrownProcessIsNotCountedAsCompletion() async {
enum FixtureError: Error { case injected }
let recognizer = Recognizer(process: { throw FixtureError.injected })
- let engine = MeetingLiveTrackEngine(kind: .microphone, recognizer: recognizer,
- diagnosticsEnabled: true)
- await engine.diagnosticConsume(sample(at: 0))
+ let engine = MeetingLiveTrackEngine(
+ kind: .microphone,
+ recognizer: recognizer,
+ diagnosticsEnabled: true
+ )
+ await engine.diagnosticConsume(self.sample(at: 0))
let snapshot = await engine.diagnosticSnapshotValue()
XCTAssertEqual(snapshot.processStarts, 1)
XCTAssertEqual(snapshot.processCompletions, 0)
diff --git a/Tests/FluidASRBaselineTests/MeetingMicrophoneAdmissionContractTests.swift b/Tests/FluidASRBaselineTests/MeetingMicrophoneAdmissionContractTests.swift
index a0e4c022..7e3fd79a 100644
--- a/Tests/FluidASRBaselineTests/MeetingMicrophoneAdmissionContractTests.swift
+++ b/Tests/FluidASRBaselineTests/MeetingMicrophoneAdmissionContractTests.swift
@@ -8,27 +8,64 @@ final class MeetingMicrophoneAdmissionContractTests: XCTestCase {
private let chunkID = UUID()
private func identity(index: Int = 0, epoch: UInt64 = 0) -> Evidence.Identity {
- Evidence.Identity(sessionID: sessionID, chunkID: chunkID, turnIndex: index,
- captureEpoch: epoch, observation: .clusterLabel("0"))!
+ Evidence.Identity(
+ sessionID: self.sessionID,
+ chunkID: self.chunkID,
+ turnIndex: index,
+ captureEpoch: epoch,
+ observation: .clusterLabel("0")
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ )!
}
+
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
private var interval: Evidence.Interval { .init(start: 0, end: 2)! }
func testMissingPlaybackContextIsNotInvalidTemporalMeasurement() {
- let temporal = Evidence.TemporalDuplicate(state: .duplicateSupported, identity: identity(), interval: interval,
- supportingWindows: 3, microphoneDelaySeconds: .measured(0.06), lagSpreadSeconds: .measured(0), coverage: .init(1)!)
- XCTAssertEqual(MeetingMicrophoneShadowPolicy.evaluate(evidence(playback: .unknown, temporal: .measured(temporal))).reason, .missingPlaybackContext)
+ let temporal = Evidence.TemporalDuplicate(
+ state: .duplicateSupported,
+ identity: self.identity(),
+ interval: self.interval,
+ supportingWindows: 3,
+ microphoneDelaySeconds: .measured(0.06),
+ lagSpreadSeconds: .measured(0),
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ coverage: .init(1)!
+ )
+ XCTAssertEqual(MeetingMicrophoneShadowPolicy.evaluate(self.evidence(playback: .unknown, temporal: .measured(temporal))).reason, .missingPlaybackContext)
}
func testTemporalBindingDeliberatelyRequiresTheExactEvidenceSnapshot() {
- let changedObservation = Evidence.Identity(sessionID: sessionID, chunkID: chunkID, turnIndex: 0,
- captureEpoch: 0, observation: .unavailable)!
+ let changedObservation = Evidence.Identity(
+ sessionID: self.sessionID,
+ chunkID: self.chunkID,
+ turnIndex: 0,
+ captureEpoch: 0,
+ observation: .unavailable
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ )!
let scopes: [(Evidence.Identity, Evidence.Interval)] = [
- (changedObservation, interval), (identity(), .init(start: 0, end: 2.0.nextUp)!)
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ (changedObservation, self.interval), (self.identity(), .init(start: 0, end: 2.0.nextUp)!),
]
for (scope, range) in scopes {
- let temporal = Evidence.TemporalDuplicate(state: .duplicateSupported, identity: scope, interval: range,
- supportingWindows: 3, microphoneDelaySeconds: .measured(0.06), lagSpreadSeconds: .measured(0), coverage: .init(1)!)
- XCTAssertEqual(MeetingMicrophoneShadowPolicy.evaluate(evidence(playback: .scoreablePlayback, temporal: .measured(temporal))).reason, .staleTemporalEvidence)
+ let temporal = Evidence.TemporalDuplicate(
+ state: .duplicateSupported,
+ identity: scope,
+ interval: range,
+ supportingWindows: 3,
+ microphoneDelaySeconds: .measured(0.06),
+ lagSpreadSeconds: .measured(0),
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ coverage: .init(1)!
+ )
+ XCTAssertEqual(MeetingMicrophoneShadowPolicy.evaluate(self.evidence(playback: .scoreablePlayback, temporal: .measured(temporal))).reason, .staleTemporalEvidence)
}
}
@@ -40,29 +77,48 @@ final class MeetingMicrophoneAdmissionContractTests: XCTestCase {
temporal: Evidence.Measurement<Evidence.TemporalDuplicate> = .unavailable(.notMeasured),
rms: Evidence.Measurement<Double> = .unavailable(.notMeasured)
) -> Evidence {
- Evidence(identity: identity(), interval: interval, playback: playback, signalVerdict: signal,
- textEcho: textEcho, speechActivity: activity, speechCoverage: .unavailable(.notMeasured),
- rms: rms, temporalDuplicate: temporal, embedding: .sharedClusterCentroid)
+ Evidence(
+ identity: self.identity(),
+ interval: self.interval,
+ playback: playback,
+ signalVerdict: signal,
+ textEcho: textEcho,
+ speechActivity: activity,
+ speechCoverage: .unavailable(.notMeasured),
+ rms: rms,
+ temporalDuplicate: temporal,
+ embedding: .sharedClusterCentroid
+ )
}
private func turn(signal: TurnEchoVerdict, textEcho: Bool, index: Int = 0) -> MeetingProcessingPipeline.StagedMicrophoneTurn {
- .init(chunkID: chunkID, index: index, clusterID: UUID(), clusterLabel: "0",
- diarizationObservationKey: identity(index: index).observationKey,
- start: 0, end: 2, text: "synthetic", overlapsRemote: true,
- isLikelyEcho: textEcho, echoScored: true, signalVerdict: signal)
+ .init(
+ chunkID: self.chunkID,
+ index: index,
+ clusterID: UUID(),
+ clusterLabel: "0",
+ diarizationObservationKey: self.identity(index: index).observationKey,
+ start: 0,
+ end: 2,
+ text: "synthetic",
+ overlapsRemote: true,
+ isLikelyEcho: textEcho,
+ echoScored: true,
+ signalVerdict: signal
+ )
}
func testLegacyTruthTableAndShadowInvocationCannotChangeTurns() {
let cases: [(TurnEchoVerdict, Bool, Bool)] = [
(.echo, false, true), (.echo, true, true),
(.unknown, false, false), (.unknown, true, true),
- (.residualNotExplained, false, false), (.residualNotExplained, true, false)
+ (.residualNotExplained, false, false), (.residualNotExplained, true, false),
]
for (signal, textEcho, expected) in cases {
- let original = turn(signal: signal, textEcho: textEcho)
+ let original = self.turn(signal: signal, textEcho: textEcho)
let keysBefore = MeetingProcessingPipeline.trustedMicrophoneObservationKeys(from: [original])
XCTAssertEqual(original.effectiveEcho, expected)
- let shadow = MeetingMicrophoneShadowPolicy.evaluate(evidence(signal: .measured(signal), textEcho: .measured(textEcho)))
+ let shadow = MeetingMicrophoneShadowPolicy.evaluate(self.evidence(signal: .measured(signal), textEcho: .measured(textEcho)))
XCTAssertTrue(shadow.experimental)
XCTAssertEqual(shadow.outcome, .uncertainCandidate)
XCTAssertEqual(original.effectiveEcho, expected)
@@ -90,8 +146,11 @@ final class MeetingMicrophoneAdmissionContractTests: XCTestCase {
func testLegacyTrivialRunDenialRequiresAllConditions() {
func verdict(lowCount: Int, other: Double) -> TurnEchoVerdict {
- MeetingEchoSignalScorer.verdict(.init(fractions: [Double](repeating: 0.1, count: lowCount)
- + [Double](repeating: other, count: 100 - lowCount), hopSeconds: 0.1))
+ MeetingEchoSignalScorer.verdict(.init(
+ fractions: [Double](repeating: 0.1, count: lowCount)
+ + [Double](repeating: other, count: 100 - lowCount),
+ hopSeconds: 0.1
+ ))
}
XCTAssertEqual(verdict(lowCount: 8, other: 0.9), .echo)
XCTAssertEqual(verdict(lowCount: 8, other: 0.7), .residualNotExplained)
@@ -100,40 +159,42 @@ final class MeetingMicrophoneAdmissionContractTests: XCTestCase {
}
func testShadowNamesRescueDisagreementWithoutChangingLegacy() {
- let input = evidence(signal: .measured(.residualNotExplained), textEcho: .measured(true))
+ let input = self.evidence(signal: .measured(.residualNotExplained), textEcho: .measured(true))
XCTAssertEqual(MeetingMicrophoneShadowPolicy.evaluate(input).reason, .legacyRescueDisagreement)
XCTAssertFalse(input.legacySignalVerdict.legacyEffectiveEcho(textEcho: true))
}
func testActivityDoesNotProveNearEndSpeechEvenWithoutPlayback() {
for playback in [Evidence.PlaybackContext.scoreablePlayback, .verifiedNoPlayback, .playbackExpectedButUnscoreable, .unknown] {
- let output = MeetingMicrophoneShadowPolicy.evaluate(evidence(activity: .measured(.detected), playback: playback))
+ let output = MeetingMicrophoneShadowPolicy.evaluate(self.evidence(activity: .measured(.detected), playback: playback))
XCTAssertEqual(output.reason, .speechActivityIsNotNearEndProof)
XCTAssertEqual(output.outcome, .uncertainCandidate)
}
}
func testNegativeActivityAndZeroRMSDoNotProveSpeechAbsence() {
- let missing = evidence(activity: .measured(.notDetected))
- let zero = evidence(activity: .measured(.notDetected), rms: .measured(0))
+ let missing = self.evidence(activity: .measured(.notDetected))
+ let zero = self.evidence(activity: .measured(.notDetected), rms: .measured(0))
XCTAssertNotEqual(missing.rms, zero.rms)
XCTAssertEqual(MeetingMicrophoneShadowPolicy.evaluate(zero).reason, .negativeActivityIsNotSpeechAbsenceProof)
}
func testUnknownReasonsRemainDistinctDespiteLegacyCollapse() {
for reason in [Evidence.UnknownReason.noDelayLock, .referenceUnavailable, .unscoredCoverage, .scoredInconclusive] {
- let input = evidence(signal: .unavailable(reason))
+ let input = self.evidence(signal: .unavailable(reason))
XCTAssertEqual(input.legacySignalVerdict, .unknown)
XCTAssertEqual(MeetingMicrophoneShadowPolicy.evaluate(input).signalUnknownReason, reason)
}
}
func testTurnIdentityPreservesSharedObservationAndEpochDistinctions() {
- XCTAssertNotEqual(identity(index: 0).turnKey, identity(index: 1).turnKey)
- XCTAssertEqual(identity(index: 0).observationKey, identity(index: 1).observationKey)
- XCTAssertNotEqual(identity(epoch: 0), identity(epoch: 1))
- XCTAssertNil(Evidence.Identity(sessionID: sessionID, chunkID: chunkID, turnIndex: -1, captureEpoch: 0, observation: .unavailable))
- let fallback = Evidence.Identity(sessionID: sessionID, chunkID: chunkID, turnIndex: 0, captureEpoch: 0, observation: .unavailable)!
+ XCTAssertNotEqual(self.identity(index: 0).turnKey, self.identity(index: 1).turnKey)
+ XCTAssertEqual(self.identity(index: 0).observationKey, self.identity(index: 1).observationKey)
+ XCTAssertNotEqual(self.identity(epoch: 0), self.identity(epoch: 1))
+ XCTAssertNil(Evidence.Identity(sessionID: self.sessionID, chunkID: self.chunkID, turnIndex: -1, captureEpoch: 0, observation: .unavailable))
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ let fallback = Evidence.Identity(sessionID: self.sessionID, chunkID: self.chunkID, turnIndex: 0, captureEpoch: 0, observation: .unavailable)!
XCTAssertNil(fallback.observationKey)
}
@@ -149,27 +210,54 @@ final class MeetingMicrophoneAdmissionContractTests: XCTestCase {
private struct FakeTemporalDetector: MeetingPlaybackDuplicateEvidenceSource {
let result: Evidence.Measurement<Evidence.TemporalDuplicate>
- func evidence(for identity: Evidence.Identity, interval: Evidence.Interval) -> Evidence.Measurement<Evidence.TemporalDuplicate> { result }
+ func evidence(for identity: Evidence.Identity, interval: Evidence.Interval) -> Evidence.Measurement<Evidence.TemporalDuplicate> { self.result }
}
func testFakeTemporalSourceIsOnlyEvidenceAndRequiresMatchingScope() {
- let stale = Evidence.TemporalDuplicate(state: .duplicateSupported, identity: identity(epoch: 1), interval: interval,
- supportingWindows: 6, microphoneDelaySeconds: .measured(0.06), lagSpreadSeconds: .measured(0.001), coverage: .init(1)!)
+ let stale = Evidence.TemporalDuplicate(
+ state: .duplicateSupported,
+ identity: self.identity(epoch: 1),
+ interval: self.interval,
+ supportingWindows: 6,
+ microphoneDelaySeconds: .measured(0.06),
+ lagSpreadSeconds: .measured(0.001),
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ coverage: .init(1)!
+ )
let fake = FakeTemporalDetector(result: .measured(stale))
- let input = evidence(playback: .scoreablePlayback, temporal: fake.evidence(for: identity(), interval: interval))
+ let input = self.evidence(playback: .scoreablePlayback, temporal: fake.evidence(for: self.identity(), interval: self.interval))
XCTAssertEqual(MeetingMicrophoneShadowPolicy.evaluate(input).reason, .staleTemporalEvidence)
}
func testMalformedTemporalSupportDoesNotBecomeDuplicateEvidence() {
- let invalid = Evidence.TemporalDuplicate(state: .duplicateSupported, identity: identity(), interval: interval,
- supportingWindows: 0, microphoneDelaySeconds: .measured(.nan), lagSpreadSeconds: .measured(0), coverage: .init(0)!)
- XCTAssertEqual(MeetingMicrophoneShadowPolicy.evaluate(evidence(temporal: .measured(invalid))).reason, .invalidTemporalEvidence)
+ let invalid = Evidence.TemporalDuplicate(
+ state: .duplicateSupported,
+ identity: self.identity(),
+ interval: self.interval,
+ supportingWindows: 0,
+ microphoneDelaySeconds: .measured(.nan),
+ lagSpreadSeconds: .measured(0),
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ coverage: .init(0)!
+ )
+ XCTAssertEqual(MeetingMicrophoneShadowPolicy.evaluate(self.evidence(temporal: .measured(invalid))).reason, .invalidTemporalEvidence)
}
func testSupportedDuplicateRemainsExperimentalAndCannotRescueMixedSpeech() {
- let temporal = Evidence.TemporalDuplicate(state: .duplicateSupported, identity: identity(), interval: interval,
- supportingWindows: 6, microphoneDelaySeconds: .measured(0.06), lagSpreadSeconds: .measured(0.001), coverage: .init(1)!)
- let input = evidence(activity: .measured(.detected), playback: .scoreablePlayback, temporal: .measured(temporal))
+ let temporal = Evidence.TemporalDuplicate(
+ state: .duplicateSupported,
+ identity: self.identity(),
+ interval: self.interval,
+ supportingWindows: 6,
+ microphoneDelaySeconds: .measured(0.06),
+ lagSpreadSeconds: .measured(0.001),
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ coverage: .init(1)!
+ )
+ let input = self.evidence(activity: .measured(.detected), playback: .scoreablePlayback, temporal: .measured(temporal))
let result = MeetingMicrophoneShadowPolicy.evaluate(input)
XCTAssertEqual(result.reason, .playbackDuplicateCandidate)
XCTAssertEqual(result.outcome, .uncertainCandidate)
@@ -177,11 +265,13 @@ final class MeetingMicrophoneAdmissionContractTests: XCTestCase {
}
func testSharedCentroidStillCannotProveSpeechInShadow() {
- let input = evidence(signal: .measured(.residualNotExplained))
+ let input = self.evidence(signal: .measured(.residualNotExplained))
XCTAssertEqual(input.embedding, .sharedClusterCentroid)
XCTAssertEqual(MeetingMicrophoneShadowPolicy.evaluate(input).reason, .insufficientEvidence)
// Characterization of the known production gap, not an assertion of desired enforcement.
let siblings = [turn(signal: .echo, textEcho: true), turn(signal: .unknown, textEcho: false, index: 1)]
- XCTAssertEqual(MeetingProcessingPipeline.trustedMicrophoneObservationKeys(from: siblings), [identity().observationKey!])
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ XCTAssertEqual(MeetingProcessingPipeline.trustedMicrophoneObservationKeys(from: siblings), [self.identity().observationKey!])
}
}
diff --git a/Tests/FluidASRBaselineTests/MeetingPlaybackDuplicateDetectorTests.swift b/Tests/FluidASRBaselineTests/MeetingPlaybackDuplicateDetectorTests.swift
index 089853f8..e362a077 100644
--- a/Tests/FluidASRBaselineTests/MeetingPlaybackDuplicateDetectorTests.swift
+++ b/Tests/FluidASRBaselineTests/MeetingPlaybackDuplicateDetectorTests.swift
@@ -10,163 +10,264 @@ final class MeetingPlaybackDuplicateDetectorTests: XCTestCase {
private func noise(_ n: Int, seed: UInt64) -> [Float] {
var state = seed
return (0..<n).map { _ in
- state = state &* 6364136223846793005 &+ 1
+ state = state &* 6_364_136_223_846_793_005 &+ 1
return Float(Double(state >> 32) / Double(UInt32.max) - 0.5)
}
}
- private func window(start: Double = 1, lag: Int = 120, epoch: UInt64 = 0,
- route: String = "test", mode: String = "echo") -> Detector.Window {
- var reference = noise(6_000, seed: UInt64(start * 100) + 1)
- if mode == "periodic" { reference = (0..<6_000).map { sin(Float($0) * 0.1) } }
- var mic = Array(reference[(1_000 - lag)..<(5_000 - lag)])
- if mode == "wrong" { mic = noise(4_000, seed: 92) }
- if mode == "silence" { mic = [Float](repeating: 0, count: 4_000) }
+
+ private func window(
+ start: Double = 1,
+ lag: Int = 120,
+ epoch: UInt64 = 0,
+ route: String = "test",
+ mode: String = "echo"
+ ) -> Detector.Window {
+ var reference = self.noise(6000, seed: UInt64(start * 100) + 1)
+ if mode == "periodic" { reference = (0..<6000).map { sin(Float($0) * 0.1) } }
+ var mic = Array(reference[(1000 - lag)..<(5000 - lag)])
+ if mode == "wrong" { mic = self.noise(4000, seed: 92) }
+ if mode == "silence" { mic = [Float](repeating: 0, count: 4000) }
if mode == "doubleTalk" {
- let local = noise(4_000, seed: 519)
+ let local = self.noise(4000, seed: 519)
mic = zip(mic, local).map { $0 + 0.05 * $1 }
}
func pcm(_ samples: [Float], _ pts: Double) -> Detector.PCM {
.init(start: pts, samples: samples, valid: [Bool](repeating: true, count: samples.count))
}
- return .init(sessionID: session, epoch: epoch, routeID: route, start: start,
- microphone: pcm(mic, start), reference: pcm(reference, start - 0.5),
- mismatchedReference: pcm(noise(6_000, seed: 982), start - 0.5))
+ return .init(
+ sessionID: self.session,
+ epoch: epoch,
+ routeID: route,
+ start: start,
+ microphone: pcm(mic, start),
+ reference: pcm(reference, start - 0.5),
+ mismatchedReference: pcm(self.noise(6000, seed: 982), start - 0.5)
+ )
}
+
private func detector() -> Detector {
var c = Detector.Configuration(); c.budgetSeconds = 10
return Detector(configuration: c)
}
- func testLagSignAndRepeatedSupport() {
+ func testLagSignAndRepeatedSupport() throws {
for lag in [-120, 0, 120] {
- var d = detector()
- XCTAssertEqual(d.process(window(lag: lag)).state, .duplicateCandidate)
- XCTAssertEqual(d.process(window(start: 3, lag: lag)).state, .duplicateCandidate)
- let result = d.process(window(start: 5, lag: lag))
+ var d = self.detector()
+ XCTAssertEqual(d.process(self.window(lag: lag)).state, .duplicateCandidate)
+ XCTAssertEqual(d.process(self.window(start: 3, lag: lag)).state, .duplicateCandidate)
+ let result = d.process(self.window(start: 5, lag: lag))
XCTAssertEqual(result.state, .duplicateSupported)
- XCTAssertEqual(result.microphoneDelaySeconds!, Double(lag) / 2_000, accuracy: 0.001)
+ XCTAssertEqual(try XCTUnwrap(result.microphoneDelaySeconds), Double(lag) / 2000, accuracy: 0.001)
}
}
+
func testWrongAndPeriodicReferencesDoNotLock() {
for mode in ["wrong", "periodic", "silence"] {
- var d = detector()
+ var d = self.detector()
for start in [1.0, 3, 5, 7] {
- XCTAssertNotEqual(d.process(window(start: start, mode: mode)).state, .duplicateSupported)
+ XCTAssertNotEqual(d.process(self.window(start: start, mode: mode)).state, .duplicateSupported)
}
}
}
+
func testGapEpochAndRouteRequireFreshSupport() {
for reset in ["gap", "epoch", "route"] {
- var d = detector()
- for start in [1.0, 3, 5] { _ = d.process(window(start: start)) }
- let result = d.process(window(start: reset == "gap" ? 9 : 7,
- epoch: reset == "epoch" ? 1 : 0,
- route: reset == "route" ? "new" : "test"))
+ var d = self.detector()
+ for start in [1.0, 3, 5] {
+ _ = d.process(self.window(start: start))
+ }
+ let result = d.process(self.window(
+ start: reset == "gap" ? 9 : 7,
+ epoch: reset == "epoch" ? 1 : 0,
+ route: reset == "route" ? "new" : "test"
+ ))
XCTAssertEqual(result.state, .duplicateCandidate)
XCTAssertEqual(result.supportingWindows, 1)
}
}
+
func testMissingAndMaskedReferenceResetImmediately() {
for masked in [true, false] {
- var d = detector()
- for start in [1.0, 3, 5] { _ = d.process(window(start: start)) }
- let w = window(start: 7)
+ var d = self.detector()
+ for start in [1.0, 3, 5] {
+ _ = d.process(self.window(start: start))
+ }
+ let w = self.window(start: 7)
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
var mask = w.reference!.valid; mask[200] = false
- let bad = Detector.Window(sessionID: session, epoch: 0, routeID: "test", start: 7,
- microphone: w.microphone,
- reference: masked ? .init(start: 6.5, samples: w.reference!.samples, valid: mask) : nil,
- mismatchedReference: w.mismatchedReference)
+ let bad = Detector.Window(
+ sessionID: self.session,
+ epoch: 0,
+ routeID: "test",
+ start: 7,
+ microphone: w.microphone,
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ reference: masked ? .init(start: 6.5, samples: w.reference!.samples, valid: mask) : nil,
+ mismatchedReference: w.mismatchedReference
+ )
XCTAssertEqual(d.process(bad).state, .insufficientEvidence)
- XCTAssertEqual(d.process(window(start: 9)).supportingWindows, 1)
+ XCTAssertEqual(d.process(self.window(start: 9)).supportingWindows, 1)
}
}
+
func testReleaseHasNoHoldAndDelayJumpRestarts() {
- var d = detector()
- for start in [1.0, 3, 5] { _ = d.process(window(start: start)) }
- let released = d.process(window(start: 7, mode: "wrong"))
+ var d = self.detector()
+ for start in [1.0, 3, 5] {
+ _ = d.process(self.window(start: start))
+ }
+ let released = d.process(self.window(start: 7, mode: "wrong"))
XCTAssertEqual(released.reason, .released)
XCTAssertEqual(released.supportingWindows, 0)
- for start in [9.0, 11, 13] { _ = d.process(window(start: start)) }
- XCTAssertEqual(d.process(window(start: 15, lag: -120)).supportingWindows, 1)
+ for start in [9.0, 11, 13] {
+ _ = d.process(self.window(start: start))
+ }
+ XCTAssertEqual(d.process(self.window(start: 15, lag: -120)).supportingWindows, 1)
}
+
func testQuietDoubleTalkRemainsAConfoundNotSpeechAbsenceProof() {
- var d = detector()
- for start in [1.0, 3, 5] { _ = d.process(window(start: start)) }
- XCTAssertEqual(d.process(window(start: 7, mode: "doubleTalk")).state, .duplicateSupported,
- "Temporal match survives quiet local audio: NEVER use this alone to suppress speech")
+ var d = self.detector()
+ for start in [1.0, 3, 5] {
+ _ = d.process(self.window(start: start))
+ }
+ XCTAssertEqual(
+ d.process(self.window(start: 7, mode: "doubleTalk")).state,
+ .duplicateSupported,
+ "Temporal match survives quiet local audio: NEVER use this alone to suppress speech"
+ )
}
+
func testControlMatchRejectsEvenPerfectCorrelation() {
- var d = detector(); let w = window()
- let matchingControl = Detector.Window(sessionID: session, epoch: 0, routeID: "test", start: 1,
- microphone: w.microphone, reference: w.reference,
- mismatchedReference: w.reference)
+ var d = self.detector(); let w = self.window()
+ let matchingControl = Detector.Window(
+ sessionID: self.session,
+ epoch: 0,
+ routeID: "test",
+ start: 1,
+ microphone: w.microphone,
+ reference: w.reference,
+ mismatchedReference: w.reference
+ )
XCTAssertEqual(d.process(matchingControl).reason, .scoredInconclusive)
}
+
func testBudgetDisablesAfterBoundedFailures() {
final class Clock: @unchecked Sendable {
let lock = NSLock(); var value = 0.0
- func now() -> Double { lock.lock(); defer { lock.unlock() }; value += 1; return value }
+ func now() -> Double { self.lock.lock(); defer { lock.unlock() }; self.value += 1; return self.value }
}
let clock = Clock()
var d = Detector(clock: { clock.now() })
- for start in [1.0, 3, 5] { XCTAssertEqual(d.process(window(start: start)).reason, .overBudget) }
- XCTAssertEqual(d.process(window(start: 7)).reason, .detectorUnavailable)
- let w = window()
- let newSession = Detector.Window(sessionID: UUID(), epoch: 0, routeID: "test", start: 1,
- microphone: w.microphone, reference: w.reference, mismatchedReference: w.mismatchedReference)
+ for start in [1.0, 3, 5] {
+ XCTAssertEqual(d.process(self.window(start: start)).reason, .overBudget)
+ }
+ XCTAssertEqual(d.process(self.window(start: 7)).reason, .detectorUnavailable)
+ let w = self.window()
+ let newSession = Detector.Window(
+ sessionID: UUID(),
+ epoch: 0,
+ routeID: "test",
+ start: 1,
+ microphone: w.microphone,
+ reference: w.reference,
+ mismatchedReference: w.mismatchedReference
+ )
XCTAssertEqual(d.process(newSession).reason, .overBudget)
}
+
func testMalformedSamplesAndTimestampsDoNotTrap() {
- let w = window()
+ let w = self.window()
for pts in [Double.nan, .infinity, -1, 1e100] {
- var d = detector()
- let bad = Detector.Window(sessionID: session, epoch: 0, routeID: "test", start: pts,
- microphone: w.microphone, reference: w.reference,
- mismatchedReference: w.mismatchedReference)
+ var d = self.detector()
+ let bad = Detector.Window(
+ sessionID: self.session,
+ epoch: 0,
+ routeID: "test",
+ start: pts,
+ microphone: w.microphone,
+ reference: w.reference,
+ mismatchedReference: w.mismatchedReference
+ )
XCTAssertEqual(d.process(bad).state, .insufficientEvidence)
}
- var d = detector(); var samples = w.microphone.samples; samples[4] = .nan
- let bad = Detector.Window(sessionID: session, epoch: 0, routeID: "test", start: 1,
- microphone: .init(start: 1, samples: samples, valid: w.microphone.valid),
- reference: w.reference, mismatchedReference: w.mismatchedReference)
+ var d = self.detector(); var samples = w.microphone.samples; samples[4] = .nan
+ let bad = Detector.Window(
+ sessionID: self.session,
+ epoch: 0,
+ routeID: "test",
+ start: 1,
+ microphone: .init(start: 1, samples: samples, valid: w.microphone.valid),
+ reference: w.reference,
+ mismatchedReference: w.mismatchedReference
+ )
XCTAssertEqual(d.process(bad).reason, .unscoredCoverage)
}
func testReferenceSilenceIsInsufficientNotNegativeEvidence() {
- var d = detector(); let w = window()
- let silent = Detector.PCM(start: 0.5, samples: [Float](repeating: 0, count: 6_000),
- valid: [Bool](repeating: true, count: 6_000))
- let input = Detector.Window(sessionID: session, epoch: 0, routeID: "test", start: 1,
- microphone: w.microphone, reference: silent,
- mismatchedReference: w.mismatchedReference)
+ var d = self.detector(); let w = self.window()
+ let silent = Detector.PCM(
+ start: 0.5,
+ samples: [Float](repeating: 0, count: 6000),
+ valid: [Bool](repeating: true, count: 6000)
+ )
+ let input = Detector.Window(
+ sessionID: self.session,
+ epoch: 0,
+ routeID: "test",
+ start: 1,
+ microphone: w.microphone,
+ reference: silent,
+ mismatchedReference: w.mismatchedReference
+ )
XCTAssertEqual(d.process(input).reason, .insufficientEnergy)
}
func testReferencePTSMovesEstimatedLagInBothDirections() {
for shift in [-0.02, 0.02] {
- var d = detector(); let w = window()
+ var d = self.detector(); let w = self.window()
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let padded = [Float](repeating: 0, count: 200) + w.reference!.samples
+ [Float](repeating: 0, count: 200)
- let ref = Detector.PCM(start: 0.4 + shift, samples: padded,
- valid: [Bool](repeating: true, count: padded.count))
- let input = Detector.Window(sessionID: session, epoch: 0, routeID: "test", start: 1,
- microphone: w.microphone, reference: ref,
- mismatchedReference: w.mismatchedReference)
+ let ref = Detector.PCM(
+ start: 0.4 + shift,
+ samples: padded,
+ valid: [Bool](repeating: true, count: padded.count)
+ )
+ let input = Detector.Window(
+ sessionID: self.session,
+ epoch: 0,
+ routeID: "test",
+ start: 1,
+ microphone: w.microphone,
+ reference: ref,
+ mismatchedReference: w.mismatchedReference
+ )
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
XCTAssertEqual(d.process(input).microphoneDelaySeconds!, 0.06 - shift, accuracy: 0.001)
}
}
func testExactLagSpreadBoundaryRetainsSupport() {
- var d = detector()
- _ = d.process(window(start: 1, lag: 200))
- _ = d.process(window(start: 3, lag: 224))
- XCTAssertEqual(d.process(window(start: 5, lag: 200)).state, .duplicateSupported)
+ var d = self.detector()
+ _ = d.process(self.window(start: 1, lag: 200))
+ _ = d.process(self.window(start: 3, lag: 224))
+ XCTAssertEqual(d.process(self.window(start: 5, lag: 200)).state, .duplicateSupported)
}
func testUnavailableControlIsDistinctFromMissingPlayback() {
- var d = detector(); let w = window()
- let input = Detector.Window(sessionID: session, epoch: 0, routeID: "test", start: 1,
- microphone: w.microphone, reference: w.reference, mismatchedReference: nil)
+ var d = self.detector(); let w = self.window()
+ let input = Detector.Window(
+ sessionID: self.session,
+ epoch: 0,
+ routeID: "test",
+ start: 1,
+ microphone: w.microphone,
+ reference: w.reference,
+ mismatchedReference: nil
+ )
XCTAssertEqual(d.process(input).reason, .controlUnavailable)
}
}
diff --git a/Tests/FluidASRBaselineTests/MeetingReferenceSynchronizerReplayCLITests.swift b/Tests/FluidASRBaselineTests/MeetingReferenceSynchronizerReplayCLITests.swift
index 25cad95c..87d4bf3b 100644
--- a/Tests/FluidASRBaselineTests/MeetingReferenceSynchronizerReplayCLITests.swift
+++ b/Tests/FluidASRBaselineTests/MeetingReferenceSynchronizerReplayCLITests.swift
@@ -3,6 +3,8 @@ import Foundation
import XCTest
@MainActor
+// Match the production component name so its regression suite is easy to find.
+// swiftlint:disable:next type_name
final class MeetingReferenceSynchronizerReplayCLITests: XCTestCase {
private func fixture(
microphone: [MeetingSynchronizerReplayMicrophoneFrame] = [],
@@ -16,15 +18,24 @@ final class MeetingReferenceSynchronizerReplayCLITests: XCTestCase {
hostTime: Double? = 1,
configuration: MeetingSynchronizerReplayConfiguration = .init()
) -> MeetingSynchronizerReplayFixture {
- fixture(
+ self.fixture(
microphone: (0..<3).map {
let index = $0
- return .init(sequenceNumber: index, sampleTime: Int64(index * 160), hostTime: hostTime.map { base in base + Double(index) * 0.01 },
- sampleRate: 16_000, samples: [Float](repeating: Float(index + 1), count: 160))
+ return .init(
+ sequenceNumber: index,
+ sampleTime: Int64(index * 160),
+ hostTime: hostTime.map { base in base + Double(index) * 0.01 },
+ sampleRate: 16_000,
+ samples: [Float](repeating: Float(index + 1), count: 160)
+ )
},
reference: (0..<3).map {
- .init(sequenceNumber: $0, presentationTime: Double($0) * 0.01,
- sampleRate: 16_000, samples: [Float](repeating: 2, count: 160))
+ .init(
+ sequenceNumber: $0,
+ presentationTime: Double($0) * 0.01,
+ sampleRate: 16_000,
+ samples: [Float](repeating: 2, count: 160)
+ )
},
configuration: configuration
)
@@ -38,14 +49,17 @@ final class MeetingReferenceSynchronizerReplayCLITests: XCTestCase {
private func run(_ fixture: MeetingSynchronizerReplayFixture, environment: [String: String] = [:]) throws -> (Int32, Data) {
var output = Data()
- let status = MeetingReferenceSynchronizerReplayCLI.run(
+ let status = try MeetingReferenceSynchronizerReplayCLI.run(
arguments: ["replay", MeetingReferenceSynchronizerReplayCLI.argument],
- environment: environment, inputData: try encoded(fixture), output: { output = $0 })
+ environment: environment,
+ inputData: self.encoded(fixture),
+ output: { output = $0 }
+ )
return (status, output)
}
func testReplayIsDeterministicAndOutputContainsNoPCM() throws {
- let fixture = frameFixture()
+ let fixture = self.frameFixture()
let first = try run(fixture)
let second = try run(fixture)
XCTAssertEqual(first.0, 0)
@@ -59,10 +73,20 @@ final class MeetingReferenceSynchronizerReplayCLITests: XCTestCase {
func testUnknownMasksGapsEpochsAndSynthTimingAreSummarized() throws {
let mic = [
- MeetingSynchronizerReplayMicrophoneFrame(sequenceNumber: 0, sampleTime: 0, hostTime: nil,
- sampleRate: 16_000, samples: [Float](repeating: 1, count: 160)),
- MeetingSynchronizerReplayMicrophoneFrame(sequenceNumber: 2, sampleTime: 320, hostTime: 1.02,
- sampleRate: 16_000, samples: [Float](repeating: 1, count: 160))
+ MeetingSynchronizerReplayMicrophoneFrame(
+ sequenceNumber: 0,
+ sampleTime: 0,
+ hostTime: nil,
+ sampleRate: 16_000,
+ samples: [Float](repeating: 1, count: 160)
+ ),
+ MeetingSynchronizerReplayMicrophoneFrame(
+ sequenceNumber: 2,
+ sampleTime: 320,
+ hostTime: 1.02,
+ sampleRate: 16_000,
+ samples: [Float](repeating: 1, count: 160)
+ ),
]
let (status, data) = try run(fixture(microphone: mic, reference: frameFixture().reference))
XCTAssertEqual(status, 0)
@@ -74,13 +98,15 @@ final class MeetingReferenceSynchronizerReplayCLITests: XCTestCase {
}
func testMalformedSchemaAndNonFiniteInputFailClosedWithoutPathLeak() throws {
- var json = try XCTUnwrap(JSONSerialization.jsonObject(with: encoded(frameFixture())) as? [String: Any])
+ var json = try XCTUnwrap(JSONSerialization.jsonObject(with: self.encoded(self.frameFixture())) as? [String: Any])
json["unexpected"] = "rejected"
let data = try JSONSerialization.data(withJSONObject: json)
var output = Data()
let status = MeetingReferenceSynchronizerReplayCLI.run(
arguments: ["replay", MeetingReferenceSynchronizerReplayCLI.argument],
- inputData: data, output: { output = $0 })
+ inputData: data,
+ output: { output = $0 }
+ )
XCTAssertEqual(status, 2)
let error = try XCTUnwrap(JSONSerialization.jsonObject(with: output) as? [String: Any])
XCTAssertEqual(error["errorCode"] as? String, "invalidInput")
@@ -89,10 +115,11 @@ final class MeetingReferenceSynchronizerReplayCLITests: XCTestCase {
func testResourceBoundsAndOfflineGateAreExplicit() throws {
var output = Data()
- let noGate = MeetingReferenceSynchronizerReplayCLI.run(
- arguments: ["replay"], inputData: try encoded(frameFixture()), output: { output = $0 })
+ let noGate = try MeetingReferenceSynchronizerReplayCLI.run(
+ arguments: ["replay"], inputData: self.encoded(self.frameFixture()), output: { output = $0 }
+ )
XCTAssertEqual(noGate, 2)
- XCTAssertEqual((try JSONSerialization.jsonObject(with: output) as? [String: Any])?["errorCode"] as? String, "offlineGateRequired")
+ XCTAssertEqual(try (JSONSerialization.jsonObject(with: output) as? [String: Any])?["errorCode"] as? String, "offlineGateRequired")
let limited = MeetingSynchronizerReplayConfiguration(maximumOutputFrameCount: 1)
let (status, boundedOutput) = try run(frameFixture(configuration: limited))
@@ -104,47 +131,51 @@ final class MeetingReferenceSynchronizerReplayCLITests: XCTestCase {
let totalFrameLimit = MeetingSynchronizerReplayConfiguration(maximumInputFrameCount: 3)
let (totalFrameStatus, totalFrameData) = try run(frameFixture(configuration: totalFrameLimit))
XCTAssertEqual(totalFrameStatus, 2)
- XCTAssertEqual((try JSONSerialization.jsonObject(with: totalFrameData) as? [String: Any])?["errorCode"] as? String, "invalidInput")
+ XCTAssertEqual(try (JSONSerialization.jsonObject(with: totalFrameData) as? [String: Any])?["errorCode"] as? String, "invalidInput")
}
func testNilHostTimeAndEmptySamplesAreHandledStrictly() throws {
- let nilHost = frameFixture(hostTime: nil)
+ let nilHost = self.frameFixture(hostTime: nil)
let (nilStatus, nilData) = try run(nilHost)
XCTAssertEqual(nilStatus, 0)
XCTAssertNotNil(try JSONSerialization.jsonObject(with: nilData))
let emptyMic = MeetingSynchronizerReplayMicrophoneFrame(
- sequenceNumber: 0, sampleTime: 0, hostTime: 1, sampleRate: 16_000, samples: [])
+ sequenceNumber: 0, sampleTime: 0, hostTime: 1, sampleRate: 16_000, samples: []
+ )
let (emptyStatus, emptyData) = try run(fixture(microphone: [emptyMic], reference: frameFixture().reference))
XCTAssertEqual(emptyStatus, 2)
- XCTAssertEqual((try JSONSerialization.jsonObject(with: emptyData) as? [String: Any])?["errorCode"] as? String, "invalidInput")
+ XCTAssertEqual(try (JSONSerialization.jsonObject(with: emptyData) as? [String: Any])?["errorCode"] as? String, "invalidInput")
}
func testOversizedInputIsRejectedBeforeJSONDecode() throws {
var output = Data()
let oversized = Data(repeating: 0x20, count: MeetingReferenceSynchronizerReplayCLI.maximumInputBytes + 1)
let status = MeetingReferenceSynchronizerReplayCLI.run(
- arguments: ["replay", MeetingReferenceSynchronizerReplayCLI.argument], inputData: oversized,
- output: { output = $0 })
+ arguments: ["replay", MeetingReferenceSynchronizerReplayCLI.argument],
+ inputData: oversized,
+ output: { output = $0 }
+ )
XCTAssertEqual(status, 2)
- XCTAssertEqual((try JSONSerialization.jsonObject(with: output) as? [String: Any])?["errorCode"] as? String, "invalidInput")
+ XCTAssertEqual(try (JSONSerialization.jsonObject(with: output) as? [String: Any])?["errorCode"] as? String, "invalidInput")
}
func testOutputAllocationBudgetHasAnExactFrameCap() throws {
- let accepted = MeetingSynchronizerReplayConfiguration(maximumOutputFrameCount: 6_000)
+ let accepted = MeetingSynchronizerReplayConfiguration(maximumOutputFrameCount: 6000)
let (acceptedStatus, _) = try run(frameFixture(configuration: accepted))
XCTAssertEqual(acceptedStatus, 0)
- let tooManyFrames = MeetingSynchronizerReplayConfiguration(maximumOutputFrameCount: 6_001)
+ let tooManyFrames = MeetingSynchronizerReplayConfiguration(maximumOutputFrameCount: 6001)
let (frameStatus, frameData) = try run(frameFixture(configuration: tooManyFrames))
XCTAssertEqual(frameStatus, 2)
- XCTAssertEqual((try JSONSerialization.jsonObject(with: frameData) as? [String: Any])?["errorCode"] as? String, "invalidInput")
+ XCTAssertEqual(try (JSONSerialization.jsonObject(with: frameData) as? [String: Any])?["errorCode"] as? String, "invalidInput")
let tooLargeFrame = MeetingSynchronizerReplayConfiguration(
- analysisSampleRate: 384_000, frameDuration: 10, maximumOutputFrameCount: 1)
+ analysisSampleRate: 384_000, frameDuration: 10, maximumOutputFrameCount: 1
+ )
let (sampleStatus, sampleData) = try run(frameFixture(configuration: tooLargeFrame))
XCTAssertEqual(sampleStatus, 2)
- XCTAssertEqual((try JSONSerialization.jsonObject(with: sampleData) as? [String: Any])?["errorCode"] as? String, "invalidInput")
+ XCTAssertEqual(try (JSONSerialization.jsonObject(with: sampleData) as? [String: Any])?["errorCode"] as? String, "invalidInput")
}
func testConfiguredFixtureFamiliesReplayWithoutClassificationClaims() throws {
@@ -167,7 +198,7 @@ final class MeetingReferenceSynchronizerReplayCLITests: XCTestCase {
let impulseFIR = firEcho(impulseReference)
let broadbandEcho = firEcho(broadbandReference)
let silent = [Float](repeating: 0, count: sampleCount)
- let lowReference = broadbandReference.map { $0 * 0.00001 }
+ let lowReference = broadbandReference.map { $0 * 0.00_001 }
let families: [(name: String, capture: [Float], reference: [Float])] = [
("impulseFIR", impulseFIR, impulseReference),
("echoOnly", broadbandEcho, broadbandReference),
@@ -183,15 +214,24 @@ final class MeetingReferenceSynchronizerReplayCLITests: XCTestCase {
for family in families {
let mic = (0..<3).map { index in
let slice = Array(family.capture[(index * 160)..<((index + 1) * 160)])
- return MeetingSynchronizerReplayMicrophoneFrame(sequenceNumber: index, sampleTime: Int64(index * 160),
- hostTime: 1 + Double(index) * 0.01, sampleRate: 16_000, samples: slice)
+ return MeetingSynchronizerReplayMicrophoneFrame(
+ sequenceNumber: index,
+ sampleTime: Int64(index * 160),
+ hostTime: 1 + Double(index) * 0.01,
+ sampleRate: 16_000,
+ samples: slice
+ )
}
let ref = (0..<3).map { index in
let slice = Array(family.reference[(index * 160)..<((index + 1) * 160)])
- return MeetingSynchronizerReplayReferenceFrame(sequenceNumber: index, presentationTime: Double(index) * 0.01,
- sampleRate: 16_000, samples: slice)
+ return MeetingSynchronizerReplayReferenceFrame(
+ sequenceNumber: index,
+ presentationTime: Double(index) * 0.01,
+ sampleRate: 16_000,
+ samples: slice
+ )
}
- let replay = fixture(microphone: mic, reference: ref)
+ let replay = self.fixture(microphone: mic, reference: ref)
let (status, data) = try run(replay)
XCTAssertEqual(status, 0)
let object = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
@@ -202,15 +242,28 @@ final class MeetingReferenceSynchronizerReplayCLITests: XCTestCase {
let synchronizer = MeetingReferenceSynchronizer()
let result = synchronizer.synchronize(
microphone: mic.map {
- MeetingMicrophonePCMFrame(sequenceNumber: $0.sequenceNumber, sampleTime: $0.sampleTime,
- hostTime: $0.hostTime, sampleRate: $0.sampleRate, channelCount: $0.channelCount,
- samples: $0.samples, routeIdentifier: $0.routeIdentifier, discontinuity: $0.discontinuity)
+ MeetingMicrophonePCMFrame(
+ sequenceNumber: $0.sequenceNumber,
+ sampleTime: $0.sampleTime,
+ hostTime: $0.hostTime,
+ sampleRate: $0.sampleRate,
+ channelCount: $0.channelCount,
+ samples: $0.samples,
+ routeIdentifier: $0.routeIdentifier,
+ discontinuity: $0.discontinuity
+ )
},
reference: ref.map {
- MeetingReferencePCMFrame(sequenceNumber: $0.sequenceNumber, presentationTime: $0.presentationTime,
- sampleRate: $0.sampleRate, channelCount: $0.channelCount, samples: $0.samples,
- discontinuity: $0.discontinuity)
- })
+ MeetingReferencePCMFrame(
+ sequenceNumber: $0.sequenceNumber,
+ presentationTime: $0.presentationTime,
+ sampleRate: $0.sampleRate,
+ channelCount: $0.channelCount,
+ samples: $0.samples,
+ discontinuity: $0.discontinuity
+ )
+ }
+ )
XCTAssertFalse(result.failedOpen)
XCTAssertEqual(result.frames.count, 3)
XCTAssertTrue(result.frames.allSatisfy { $0.captureValidMask.count == 160 && $0.renderValidMask.count == 160 })
diff --git a/Tests/FluidASRBaselineTests/MeetingReliabilityNegativeScreenTests.swift b/Tests/FluidASRBaselineTests/MeetingReliabilityNegativeScreenTests.swift
index c18f9c9d..4229b6fa 100644
--- a/Tests/FluidASRBaselineTests/MeetingReliabilityNegativeScreenTests.swift
+++ b/Tests/FluidASRBaselineTests/MeetingReliabilityNegativeScreenTests.swift
@@ -46,15 +46,19 @@ final class MeetingReliabilityNegativeScreenTests: XCTestCase {
throw XCTSkip("opt-in: FLUID_RELIABILITY_NEGATIVE_SCREEN=1; default 600 audio seconds per condition/mode")
}
#if arch(arm64)
- try validateHost()
+ try self.validateHost()
let env = ProcessInfo.processInfo.environment
let seconds = try boundedInteger(env["FLUID_RELIABILITY_SECONDS"], default: 600, range: 60...600)
let budgetSeconds = try boundedInteger(env["FLUID_RELIABILITY_WALL_SECONDS"], default: 1200, range: 60...1800)
guard let root = BaselineInputLoader.inputsRoot() else { throw ScreenError.invalidInputs }
let manifest = try BaselineInputLoader.loadManifest(from: root)
let manifestHash = try BaselineHashing.sha256Hex(ofFileAt: root.appendingPathComponent("manifest.json"))
- var report = NegativeScreenReport(manifestSHA256: manifestHash, modelRepository: manifest.modelRepository,
- requestedAudioSecondsPerConditionMode: seconds, wallBudgetSeconds: budgetSeconds)
+ var report = NegativeScreenReport(
+ manifestSHA256: manifestHash,
+ modelRepository: manifest.modelRepository,
+ requestedAudioSecondsPerConditionMode: seconds,
+ wallBudgetSeconds: budgetSeconds
+ )
defer { attach(report) }
var activeManager: AsrManager?
do {
@@ -77,12 +81,15 @@ final class MeetingReliabilityNegativeScreenTests: XCTestCase {
guard !vocabulary.isEmpty else { throw ScreenError.invalidVocabulary }
report.phase = "local_model_load"
let loadStart = Date()
- let models = AsrModels(
- encoder: try MLModel(contentsOf: repository.appendingPathComponent("Encoder.mlmodelc"), configuration: config),
- preprocessor: try MLModel(contentsOf: repository.appendingPathComponent("Preprocessor.mlmodelc"), configuration: preprocessorConfig),
- decoder: try MLModel(contentsOf: repository.appendingPathComponent("Decoder.mlmodelc"), configuration: config),
- joint: try MLModel(contentsOf: repository.appendingPathComponent("JointDecision.mlmodelc"), configuration: config),
- configuration: config, vocabulary: vocabulary, version: .v2)
+ let models = try AsrModels(
+ encoder: MLModel(contentsOf: repository.appendingPathComponent("Encoder.mlmodelc"), configuration: config),
+ preprocessor: MLModel(contentsOf: repository.appendingPathComponent("Preprocessor.mlmodelc"), configuration: preprocessorConfig),
+ decoder: MLModel(contentsOf: repository.appendingPathComponent("Decoder.mlmodelc"), configuration: config),
+ joint: MLModel(contentsOf: repository.appendingPathComponent("JointDecision.mlmodelc"), configuration: config),
+ configuration: config,
+ vocabulary: vocabulary,
+ version: .v2
+ )
let manager = AsrManager()
activeManager = manager
try await manager.initialize(models: models)
@@ -105,12 +112,15 @@ final class MeetingReliabilityNegativeScreenTests: XCTestCase {
let start = clock.now
let result = try await manager.transcribe(samples, source: .microphone)
let elapsed = start.duration(to: clock.now).components
- report.runs.append(.init(condition: noise ? "synthetic_uniform_noise_peak_0.001" : "digital_silence",
- mode: segmentSeconds == 60 ? "whole_chunk_60s" : "short_turn_3s",
- startSample: offset, sampleCount: count,
- nonempty: !result.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
- whitespaceWordCount: ReliabilitySyntheticInput.wordCount(result.text),
- latencySeconds: Double(elapsed.seconds) + Double(elapsed.attoseconds) / 1e18))
+ report.runs.append(.init(
+ condition: noise ? "synthetic_uniform_noise_peak_0.001" : "digital_silence",
+ mode: segmentSeconds == 60 ? "whole_chunk_60s" : "short_turn_3s",
+ startSample: offset,
+ sampleCount: count,
+ nonempty: !result.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
+ whitespaceWordCount: ReliabilitySyntheticInput.wordCount(result.text),
+ latencySeconds: Double(elapsed.seconds) + Double(elapsed.attoseconds) / 1e18
+ ))
offset += count
}
}
@@ -158,13 +168,14 @@ final class MeetingReliabilityNegativeScreenTests: XCTestCase {
guard try BaselineHashing.sha256Hex(ofFileAt: url) == artifact.sha256 else { throw ScreenError.artifactHashMismatch }
}
// Reject unmanifested files too: a partial manifest cannot bless an unverified model.
- guard let enumerator = FileManager.default.enumerator(at: repository, includingPropertiesForKeys: [.isRegularFileKey, .isSymbolicLinkKey]) else { throw ScreenError.artifactEnumerationFailed }
+ guard let enumerator = FileManager.default.enumerator(at: repository, includingPropertiesForKeys: [.isRegularFileKey, .isSymbolicLinkKey])
+ else { throw ScreenError.artifactEnumerationFailed }
var actual = Set<String>()
for case let url as URL in enumerator {
let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey])
guard values.isSymbolicLink != true else { throw ScreenError.symbolicLinkArtifact }
if values.isRegularFile == true {
- actual.insert(manifest.modelRepository + "/" + (try ReliabilitySyntheticInput.relativeArtifactPath(url, under: repository)))
+ try actual.insert(manifest.modelRepository + "/" + (ReliabilitySyntheticInput.relativeArtifactPath(url, under: repository)))
}
}
guard actual == Set(paths) else { throw ScreenError.artifactSetMismatch }
@@ -182,7 +193,7 @@ final class MeetingReliabilityNegativeScreenTests: XCTestCase {
}
}
-nonisolated private enum ScreenError: Error {
+private nonisolated enum ScreenError: Error {
case invalidInputs, invalidConfiguration, unsafeHost, wallBudgetExceeded
case invalidRepository, duplicateArtifactPaths, invalidArtifactPath, artifactHashMismatch
case artifactEnumerationFailed, symbolicLinkArtifact, artifactSetMismatch, invalidVocabulary
@@ -198,14 +209,16 @@ nonisolated enum ReliabilitySyntheticInput {
Array(childParts.prefix(rootParts.count)) == rootParts else { throw ScreenError.invalidArtifactPath }
return childParts.dropFirst(rootParts.count).joined(separator: "/")
}
+
static func samples(count: Int, noise: Bool, seed: UInt64) -> [Float] {
guard noise else { return [Float](repeating: 0, count: count) }
var state = seed
return (0..<count).map { _ in
- state = state &* 6364136223846793005 &+ 1442695040888963407
- return (Float(state >> 40) / Float(0xFFFFFF) * 2 - 1) * 0.001
+ state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407
+ return (Float(state >> 40) / Float(0xffffff) * 2 - 1) * 0.001
}
}
+
static func wordCount(_ text: String) -> Int { text.split(whereSeparator: { $0.isWhitespace }).count }
static func segmentLengths(totalSeconds: Int, segmentSeconds: Int) -> [Int] {
precondition(totalSeconds >= 0 && segmentSeconds > 0)
@@ -213,7 +226,7 @@ nonisolated enum ReliabilitySyntheticInput {
}
}
-nonisolated private struct NegativeScreenReport: Encodable {
+private nonisolated struct NegativeScreenReport: Encodable {
let schemaVersion = 1
let kind = "synthetic_negative_asr_screen_not_meeting_pipeline"
let verdict = "measured_only"
@@ -224,6 +237,8 @@ nonisolated private struct NegativeScreenReport: Encodable {
let seed = "0x46565030; LCG64; top24-bit uniform; peak=0.001 (~-60dBFS)"
let modelProvenance = "Preexisting host-bundled ASRBaselineInputs; exact artifact-set SHA256 verification against manifest; manifest is integrity provenance, not independent publisher authentication"
let networkPolicy = "Direct local CoreML constructors; no downloader; sandbox required and network/audio-input entitlements forbidden"
+ // Keep the exact fixture text or diagnostic output together for comparison.
+ // swiftlint:disable:next line_length
let scope = "No recorded audio read. No VAD, AEC, diarization, speaker profiles, production provider, or live recognizer. Noise is not AEC residual. Whitespace-delimited word counts, not linguistic token accuracy. Repeated silence is deterministic exposure, not independent statistical trials. No emptiness assertion. Wall budget checked between calls; a non-cooperative CoreML call may exceed it."
let notTested = ["real AEC residual", "quiet speech recall", "short spoken acknowledgments", "double talk", "playback leakage", "caption reset recovery"]
let manifestSHA256: String
@@ -243,14 +258,14 @@ nonisolated private struct NegativeScreenReport: Encodable {
let nonempty: Bool
let whitespaceWordCount: Int
let latencySeconds: Double
- var audioSeconds: Double { Double(sampleCount) / 16_000 }
+ var audioSeconds: Double { Double(self.sampleCount) / 16_000 }
enum CodingKeys: CodingKey { case condition, mode, startSample, sampleCount, nonempty, whitespaceWordCount, latencySeconds, audioSeconds }
func encode(to encoder: Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
- try c.encode(condition, forKey: .condition); try c.encode(mode, forKey: .mode)
- try c.encode(startSample, forKey: .startSample); try c.encode(sampleCount, forKey: .sampleCount)
- try c.encode(nonempty, forKey: .nonempty); try c.encode(whitespaceWordCount, forKey: .whitespaceWordCount)
- try c.encode(latencySeconds, forKey: .latencySeconds); try c.encode(audioSeconds, forKey: .audioSeconds)
+ try c.encode(self.condition, forKey: .condition); try c.encode(self.mode, forKey: .mode)
+ try c.encode(self.startSample, forKey: .startSample); try c.encode(self.sampleCount, forKey: .sampleCount)
+ try c.encode(self.nonempty, forKey: .nonempty); try c.encode(self.whitespaceWordCount, forKey: .whitespaceWordCount)
+ try c.encode(self.latencySeconds, forKey: .latencySeconds); try c.encode(self.audioSeconds, forKey: .audioSeconds)
}
}
}
diff --git a/Tests/FluidASRBaselineTests/MeetingSpeechActivityDetectorTests.swift b/Tests/FluidASRBaselineTests/MeetingSpeechActivityDetectorTests.swift
index 2a21afce..c0b24f81 100644
--- a/Tests/FluidASRBaselineTests/MeetingSpeechActivityDetectorTests.swift
+++ b/Tests/FluidASRBaselineTests/MeetingSpeechActivityDetectorTests.swift
@@ -7,53 +7,64 @@ final class MeetingSpeechActivityDetectorTests: XCTestCase {
var p: Float
var probabilityOnReset: Float = 0.1
mutating func probability(samples: [Float], reset: Bool) throws -> Float {
- reset ? probabilityOnReset : p
+ reset ? self.probabilityOnReset : self.p
}
}
+
private let session = UUID()
private let samples = [Float](repeating: 0.1, count: 4096)
private let valid = [Bool](repeating: true, count: 4096)
func testWarmupThenMeasuredActivity() {
var detector = MeetingSpeechActivityDetector(model: Fake(p: 0.9))
- XCTAssertEqual(detector.process(samples: samples, valid: valid, start: 0, session: session, epoch: 0, route: "a").unknown, .contextWarmup)
- let result = detector.process(samples: samples, valid: valid, start: 0.256, session: session, epoch: 0, route: "a")
+ XCTAssertEqual(detector.process(samples: self.samples, valid: self.valid, start: 0, session: self.session, epoch: 0, route: "a").unknown, .contextWarmup)
+ let result = detector.process(samples: self.samples, valid: self.valid, start: 0.256, session: self.session, epoch: 0, route: "a")
XCTAssertEqual(result.active, true); XCTAssertEqual(result.probability, 0.9)
}
+
func testMasksAndGapRequireWarmupAgain() {
var detector = MeetingSpeechActivityDetector(model: Fake(p: 0.9))
- _ = detector.process(samples: samples, valid: valid, start: 0, session: session, epoch: 0, route: "a")
- var masked = valid; masked[10] = false
- XCTAssertEqual(detector.process(samples: samples, valid: masked, start: 0.256, session: session, epoch: 0, route: "a").unknown, .unscoredCoverage)
- XCTAssertEqual(detector.process(samples: samples, valid: valid, start: 0.512, session: session, epoch: 0, route: "a").unknown, .contextWarmup)
- XCTAssertEqual(detector.process(samples: samples, valid: valid, start: 2, session: session, epoch: 0, route: "a").unknown, .contextWarmup)
+ _ = detector.process(samples: self.samples, valid: self.valid, start: 0, session: self.session, epoch: 0, route: "a")
+ var masked = self.valid; masked[10] = false
+ XCTAssertEqual(detector.process(samples: self.samples, valid: masked, start: 0.256, session: self.session, epoch: 0, route: "a").unknown, .unscoredCoverage)
+ XCTAssertEqual(detector.process(samples: self.samples, valid: self.valid, start: 0.512, session: self.session, epoch: 0, route: "a").unknown, .contextWarmup)
+ XCTAssertEqual(detector.process(samples: self.samples, valid: self.valid, start: 2, session: self.session, epoch: 0, route: "a").unknown, .contextWarmup)
}
+
func testEpochAndRouteReset() {
var detector = MeetingSpeechActivityDetector(model: Fake(p: 0.9))
- _ = detector.process(samples: samples, valid: valid, start: 0, session: session, epoch: 0, route: "a")
- XCTAssertEqual(detector.process(samples: samples, valid: valid, start: 0.256, session: session, epoch: 1, route: "a").unknown, .contextWarmup)
- XCTAssertEqual(detector.process(samples: samples, valid: valid, start: 0.512, session: session, epoch: 1, route: "b").unknown, .contextWarmup)
+ _ = detector.process(samples: self.samples, valid: self.valid, start: 0, session: self.session, epoch: 0, route: "a")
+ XCTAssertEqual(detector.process(samples: self.samples, valid: self.valid, start: 0.256, session: self.session, epoch: 1, route: "a").unknown, .contextWarmup)
+ XCTAssertEqual(detector.process(samples: self.samples, valid: self.valid, start: 0.512, session: self.session, epoch: 1, route: "b").unknown, .contextWarmup)
}
+
func testNaNAndPartialFramesAreUnavailable() {
var detector = MeetingSpeechActivityDetector(model: Fake(p: .nan, probabilityOnReset: .nan))
- XCTAssertEqual(detector.process(samples: samples, valid: valid, start: 0, session: session, epoch: 0, route: "a").unknown, .modelFailure)
- XCTAssertEqual(detector.process(samples: [0.1], valid: [true], start: 0.256, session: session, epoch: 0, route: "a").unknown, .invalidInput)
+ XCTAssertEqual(detector.process(samples: self.samples, valid: self.valid, start: 0, session: self.session, epoch: 0, route: "a").unknown, .modelFailure)
+ XCTAssertEqual(detector.process(samples: [0.1], valid: [true], start: 0.256, session: self.session, epoch: 0, route: "a").unknown, .invalidInput)
}
+
func testCancellationBeforeAndAfterPrediction() {
var detector = MeetingSpeechActivityDetector(model: Fake(p: 0.9))
- XCTAssertEqual(detector.process(samples: samples, valid: valid, start: 0, session: session, epoch: 0, route: "a", cancelled: { true }).unknown, .cancelled)
+ XCTAssertEqual(detector.process(samples: self.samples, valid: self.valid, start: 0, session: self.session, epoch: 0, route: "a", cancelled: { true }).unknown, .cancelled)
var calls = 0
- XCTAssertEqual(detector.process(samples: samples, valid: valid, start: 0.256, session: session, epoch: 0, route: "a", cancelled: { calls += 1; return calls > 1 }).unknown, .cancelled)
- XCTAssertEqual(detector.process(samples: samples, valid: valid, start: 0.512, session: session, epoch: 0, route: "a").unknown, .contextWarmup)
+ XCTAssertEqual(
+ detector.process(samples: self.samples, valid: self.valid, start: 0.256, session: self.session, epoch: 0, route: "a", cancelled: { calls += 1; return calls > 1 })
+ .unknown,
+ .cancelled
+ )
+ XCTAssertEqual(detector.process(samples: self.samples, valid: self.valid, start: 0.512, session: self.session, epoch: 0, route: "a").unknown, .contextWarmup)
}
+
func testBudgetFailuresDisableContribution() {
var time = 0.0
var detector = MeetingSpeechActivityDetector(model: Fake(p: 0.9), clock: { time += 1; return time })
for i in 0..<3 {
- XCTAssertEqual(detector.process(samples: samples, valid: valid, start: Double(i) * 0.256, session: session, epoch: 0, route: "a").unknown, .overBudget)
+ XCTAssertEqual(detector.process(samples: self.samples, valid: self.valid, start: Double(i) * 0.256, session: self.session, epoch: 0, route: "a").unknown, .overBudget)
}
- XCTAssertEqual(detector.process(samples: samples, valid: valid, start: 0.768, session: session, epoch: 0, route: "a").unknown, .disabled)
+ XCTAssertEqual(detector.process(samples: self.samples, valid: self.valid, start: 0.768, session: self.session, epoch: 0, route: "a").unknown, .disabled)
}
+
func testCombinedPolicyNeverTreatsActivityAsNearEndOrAbsenceProof() {
XCTAssertEqual(MeetingSpeechPlaybackShadowPolicy.reason(activity: true, reliableDuplicate: true), .mixedOrLeakedActivity)
XCTAssertEqual(MeetingSpeechPlaybackShadowPolicy.reason(activity: true, reliableDuplicate: false), .activityWithoutReliablePlaybackMatch)
@@ -61,6 +72,7 @@ final class MeetingSpeechActivityDetectorTests: XCTestCase {
XCTAssertEqual(MeetingSpeechPlaybackShadowPolicy.reason(activity: false, reliableDuplicate: false), .negativeActivityIsNotAbsence)
XCTAssertEqual(MeetingSpeechPlaybackShadowPolicy.reason(activity: nil, reliableDuplicate: true), .missingSpeechEvidence)
}
+
func testUnavailableModelDoesNotDownload() {
XCTAssertThrowsError(try MeetingLocalSileroActivityModel(modelURL: URL(fileURLWithPath: "/private/tmp/fv-missing-vad-artifact.mlmodelc")))
}
@@ -68,30 +80,50 @@ final class MeetingSpeechActivityDetectorTests: XCTestCase {
func testNewSessionAndUnknownFramesResetFailureAllowance() {
var time = 0.0
var detector = MeetingSpeechActivityDetector(model: Fake(p: 0.9), clock: { time += 1; return time })
- for i in 0..<2 { _ = detector.process(samples: samples, valid: valid, start: Double(i) * 0.256, session: session, epoch: 0, route: "a") }
- var masked = valid; masked[0] = false
- _ = detector.process(samples: samples, valid: masked, start: 0.512, session: session, epoch: 0, route: "a")
- for i in 3..<6 { XCTAssertEqual(detector.process(samples: samples, valid: valid, start: Double(i) * 0.256, session: session, epoch: 0, route: "a").unknown, .overBudget) }
- XCTAssertEqual(detector.process(samples: samples, valid: valid, start: 1.536, session: session, epoch: 0, route: "a").unknown, .disabled)
- XCTAssertEqual(detector.process(samples: samples, valid: valid, start: 0, session: UUID(), epoch: 0, route: "a").unknown, .overBudget)
+ for i in 0..<2 {
+ _ = detector.process(samples: self.samples, valid: self.valid, start: Double(i) * 0.256, session: self.session, epoch: 0, route: "a")
+ }
+ var masked = self.valid; masked[0] = false
+ _ = detector.process(samples: self.samples, valid: masked, start: 0.512, session: self.session, epoch: 0, route: "a")
+ for i in 3..<6 {
+ XCTAssertEqual(detector.process(samples: self.samples, valid: self.valid, start: Double(i) * 0.256, session: self.session, epoch: 0, route: "a").unknown, .overBudget)
+ }
+ XCTAssertEqual(detector.process(samples: self.samples, valid: self.valid, start: 1.536, session: self.session, epoch: 0, route: "a").unknown, .disabled)
+ XCTAssertEqual(detector.process(samples: self.samples, valid: self.valid, start: 0, session: UUID(), epoch: 0, route: "a").unknown, .overBudget)
}
private func temporal(_ start: Double, supported: Bool, epoch: UInt64 = 0) -> MeetingPlaybackDuplicateDetector.Result {
- .init(start: start, end: start + 2, epoch: epoch,
- state: supported ? .duplicateSupported : .observing,
- reason: supported ? .stableSupport : .scoredInconclusive,
- supportingWindows: supported ? 3 : 0, correlation: 0.9, controlCorrelation: 0.1,
- microphoneDelaySeconds: 0.06, lagSpreadSeconds: 0, elapsedSeconds: 0)
+ .init(
+ start: start,
+ end: start + 2,
+ epoch: epoch,
+ state: supported ? .duplicateSupported : .observing,
+ reason: supported ? .stableSupport : .scoredInconclusive,
+ supportingWindows: supported ? 3 : 0,
+ correlation: 0.9,
+ controlCorrelation: 0.1,
+ microphoneDelaySeconds: 0.06,
+ lagSpreadSeconds: 0,
+ elapsedSeconds: 0
+ )
}
+
func testCrossGridFrameUsesBothWindowsWithoutDroppingCoverage() {
let windows = [temporal(0, supported: true), temporal(2, supported: true)]
XCTAssertEqual(MeetingSpeechPlaybackShadowPolicy.temporalContext(start: 1.792, epoch: 0, windows: windows), .supported)
XCTAssertEqual(MeetingSpeechPlaybackShadowPolicy.temporalContext(start: 1.792, epoch: 0, windows: [windows[0]]), .unavailable)
}
+
func testCrossGridMixedOrStaleEvidenceCannotBorrowSupport() {
- XCTAssertEqual(MeetingSpeechPlaybackShadowPolicy.temporalContext(start: 1.792, epoch: 0,
- windows: [temporal(0, supported: true), temporal(2, supported: false)]), .mixed)
- XCTAssertEqual(MeetingSpeechPlaybackShadowPolicy.temporalContext(start: 1.792, epoch: 0,
- windows: [temporal(0, supported: true), temporal(2, supported: true, epoch: 1)]), .unavailable)
+ XCTAssertEqual(MeetingSpeechPlaybackShadowPolicy.temporalContext(
+ start: 1.792,
+ epoch: 0,
+ windows: [self.temporal(0, supported: true), self.temporal(2, supported: false)]
+ ), .mixed)
+ XCTAssertEqual(MeetingSpeechPlaybackShadowPolicy.temporalContext(
+ start: 1.792,
+ epoch: 0,
+ windows: [self.temporal(0, supported: true), self.temporal(2, supported: true, epoch: 1)]
+ ), .unavailable)
}
}
diff --git a/Tests/FluidASRBaselineTests/PairedASRBaselineTests.swift b/Tests/FluidASRBaselineTests/PairedASRBaselineTests.swift
index 7734b949..7a13159f 100644
--- a/Tests/FluidASRBaselineTests/PairedASRBaselineTests.swift
+++ b/Tests/FluidASRBaselineTests/PairedASRBaselineTests.swift
@@ -1,11 +1,11 @@
#if arch(arm64)
import FluidAudio
#endif
-@testable import FluidASRBaselineHost
import AppKit
import AVFoundation
import CryptoKit
import Darwin
+@testable import FluidASRBaselineHost
import XCTest
/// Opt-in paired ASR provider baseline: legacy dictation config vs meeting config, both pinned
@@ -445,7 +445,8 @@ final class PairedASRBaselineTests: XCTestCase {
private static func containsContiguous(_ components: [String], marker: [String]) -> Bool {
guard !marker.isEmpty, marker.count <= components.count else { return false }
for start in 0...(components.count - marker.count)
- where components[start..<(start + marker.count)].elementsEqual(marker) {
+ where components[start..<(start + marker.count)].elementsEqual(marker)
+ {
return true
}
return false
@@ -509,29 +510,29 @@ extension BaselineInputError: LocalizedError {
switch self {
case .missingInputsRoot:
return "ASRBaselineInputs not found in host bundle resources"
- case .invalidManifest(let detail):
+ case let .invalidManifest(detail):
return "invalid manifest.json: \(detail)"
- case .unsafeRelativePath(let path):
+ case let .unsafeRelativePath(path):
return "unsafe relative path: \(path)"
- case .hashMismatch(let label):
+ case let .hashMismatch(label):
return "sha256 mismatch: \(label)"
- case .fixtureMetadataMismatch(let detail):
+ case let .fixtureMetadataMismatch(detail):
return "fixture metadata mismatch: \(detail)"
- case .sandboxEnvironment(let detail):
+ case let .sandboxEnvironment(detail):
return "sandbox environment check failed: \(detail)"
- case .unsupportedFixtureFormat(let detail):
+ case let .unsupportedFixtureFormat(detail):
return "unsupported fixture format: \(detail)"
case .modelsMissingOnDisk:
return "model cache incomplete before prepare"
case .providerDidNotDeallocate:
return "provider still alive after the 2s dealloc budget"
- case .memoryQueryFailed(let detail):
+ case let .memoryQueryFailed(detail):
return "memory query failed: \(detail)"
case .memorySamplerDidNotStop:
return "memory peak sampler failed to join within the 2s deadline"
- case .emptyTranscription(let arm):
+ case let .emptyTranscription(arm):
return "empty transcript or word timings: \(arm)"
- case .invalidWordTimings(let arm):
+ case let .invalidWordTimings(arm):
return "non-finite or unordered word timings: \(arm)"
}
}
@@ -823,7 +824,7 @@ nonisolated enum BaselineAudioLoader {
}
var samples: [Float] = []
samples.reserveCapacity(Int(declaredFrames))
- let scale = Float(1.0 / 32768.0)
+ let scale = Float(1.0 / 32_768.0)
var consumed: AVAudioFramePosition = 0
while consumed < declaredFrames {
let remaining = declaredFrames - consumed
diff --git a/Tests/FluidASRBaselineTests/ProviderEnhancementOptionsTests.swift b/Tests/FluidASRBaselineTests/ProviderEnhancementOptionsTests.swift
index 3125306a..05584fa7 100644
--- a/Tests/FluidASRBaselineTests/ProviderEnhancementOptionsTests.swift
+++ b/Tests/FluidASRBaselineTests/ProviderEnhancementOptionsTests.swift
@@ -8,6 +8,8 @@ import XCTest
final class ProviderEnhancementOptionsTests: XCTestCase {
private func makeEntry() -> SettingsStore.CustomDictionaryEntry {
SettingsStore.CustomDictionaryEntry(
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
id: UUID(uuidString: "11111111-2222-3333-4444-555555555555")!,
triggers: ["fluid voice", "fluid boys"],
replacement: "FluidVoice"
diff --git a/Tests/FluidDictationIntegrationTests/AudioEngineRetirementDrainTests.swift b/Tests/FluidDictationIntegrationTests/AudioEngineRetirementDrainTests.swift
index e1e8440a..ab4f69ea 100644
--- a/Tests/FluidDictationIntegrationTests/AudioEngineRetirementDrainTests.swift
+++ b/Tests/FluidDictationIntegrationTests/AudioEngineRetirementDrainTests.swift
@@ -7,7 +7,7 @@ final class AudioEngineRetirementDrainTests: XCTestCase {
let drain = AudioEngineRetirementDrain(label: "test.audio-engine-retirement.single")
let recorder = DeinitRecorder()
var probe: DeinitProbe? = DeinitProbe(id: 1, recorder: recorder)
- let token = AudioEngineRetirementToken(try XCTUnwrap(probe))
+ let token = try AudioEngineRetirementToken(XCTUnwrap(probe))
probe = nil
await drain.releaseAndWait(token)
@@ -23,8 +23,8 @@ final class AudioEngineRetirementDrainTests: XCTestCase {
let recorder = DeinitRecorder()
var first: DeinitProbe? = DeinitProbe(id: 1, recorder: recorder)
var second: DeinitProbe? = DeinitProbe(id: 2, recorder: recorder)
- let firstToken = AudioEngineRetirementToken(try XCTUnwrap(first))
- let secondToken = AudioEngineRetirementToken(try XCTUnwrap(second))
+ let firstToken = try AudioEngineRetirementToken(XCTUnwrap(first))
+ let secondToken = try AudioEngineRetirementToken(XCTUnwrap(second))
first = nil
second = nil
@@ -44,7 +44,7 @@ final class AudioEngineRetirementDrainTests: XCTestCase {
let drain = AudioEngineRetirementDrain(label: "test.audio-engine-retirement.barrier")
let recorder = DeinitRecorder()
var probe: DeinitProbe? = DeinitProbe(id: 1, recorder: recorder)
- let token = AudioEngineRetirementToken(try XCTUnwrap(probe))
+ let token = try AudioEngineRetirementToken(XCTUnwrap(probe))
probe = nil
drain.schedule(token)
diff --git a/Tests/FluidDictationIntegrationTests/AudioHardwareRecoveryTests.swift b/Tests/FluidDictationIntegrationTests/AudioHardwareRecoveryTests.swift
index b2d6d8e7..bb3fb711 100644
--- a/Tests/FluidDictationIntegrationTests/AudioHardwareRecoveryTests.swift
+++ b/Tests/FluidDictationIntegrationTests/AudioHardwareRecoveryTests.swift
@@ -348,7 +348,9 @@ final class MonitorTopologyRecoveryTests: XCTestCase {
let probe = FailedDeviceLivenessProbe()
let controller = makeRecoveryController(input, timeout: nil, deviceLivenessReader: { probe.read($0) })
_ = try await controller.start(deviceID: 144, deviceName: "Healthy", reason: "recording")
- for _ in 0..<100 { controller.noteHardwareTopologyChanged() }
+ for _ in 0..<100 {
+ controller.noteHardwareTopologyChanged()
+ }
try await waitForTopologyCheck(controller)
input.emit()
XCTAssertTrue(probe.deviceIDs.isEmpty)
@@ -395,7 +397,9 @@ final class MonitorTopologyRecoveryTests: XCTestCase {
try await waitForTopologyCheck(controller)
for alive in [true, nil] as [Bool?] {
probe.setAlive(alive)
- for _ in 0..<100 { controller.noteHardwareTopologyChanged() }
+ for _ in 0..<100 {
+ controller.noteHardwareTopologyChanged()
+ }
try await waitForTopologyCheck(controller)
XCTAssertTrue(controller.isRecoveringHardware)
XCTAssertEqual(input.count("prepare"), 1)
@@ -412,7 +416,9 @@ final class MonitorTopologyRecoveryTests: XCTestCase {
let controller = makeRecoveryController(input, deviceLivenessReader: { probe.read($0) })
defer { input.release.signal() }
_ = try? await controller.start(deviceID: 144, deviceName: "Removed", reason: "failed_start")
- for _ in 0..<100 { controller.noteHardwareTopologyChanged() }
+ for _ in 0..<100 {
+ controller.noteHardwareTopologyChanged()
+ }
try await Task.sleep(nanoseconds: 20_000_000)
XCTAssertTrue(controller.isRecoveringHardware)
XCTAssertTrue(probe.deviceIDs.isEmpty, "Do not check or unlock while native startup owns capture")
@@ -855,7 +861,6 @@ private final nonisolated class RecoveryInput: DirectCoreAudioInputControlling,
#if canImport(FluidVoice_Debug)
final class AudioRouteRecoveryIntegrationTests: XCTestCase {
-
// Pronunciation features are opt-in in the app; these tests exercise the enabled paths.
private var priorSharedFeaturesFlag: Any?
@@ -869,6 +874,7 @@ final class AudioRouteRecoveryIntegrationTests: XCTestCase {
UserDefaults.standard.set(self.priorSharedFeaturesFlag, forKey: "DictionarySharedFeatureMatcherEnabled")
super.tearDown()
}
+
@MainActor
func testStartupTriesNewMicrophoneMissingFromDeviceCache() async throws {
try await withASRRecoveryFixture(queryDelay: 0) { fixture in
@@ -1352,7 +1358,15 @@ private final class ASRRecoveryFixture {
private let expectedPriority: [String]
private let prefix: [Float] = [0.125, 0.25, 0.375]
- init(queryDelay: TimeInterval, queryFailures: Int, liveInputs: [AudioDevice.Device], externalStopDelay: TimeInterval, operationTimeout: TimeInterval?, firstQueryDelay: TimeInterval?, builtInStartDelay: TimeInterval) {
+ init(
+ queryDelay: TimeInterval,
+ queryFailures: Int,
+ liveInputs: [AudioDevice.Device],
+ externalStopDelay: TimeInterval,
+ operationTimeout: TimeInterval?,
+ firstQueryDelay: TimeInterval?,
+ builtInStartDelay: TimeInterval
+ ) {
let settings = SettingsStore.shared
let priority = settings.microphonePriority
let preferred = settings.preferredInputDeviceUID
@@ -1383,7 +1397,13 @@ private final class ASRRecoveryFixture {
self.providerID = settings.selectedProviderID
let service = ASRService()
self.service = service
- let hardware = ASRRecoveryHardware(queryDelay: queryDelay, queryFailures: queryFailures, externalStopDelay: externalStopDelay, firstQueryDelay: firstQueryDelay, builtInStartDelay: builtInStartDelay)
+ let hardware = ASRRecoveryHardware(
+ queryDelay: queryDelay,
+ queryFailures: queryFailures,
+ externalStopDelay: externalStopDelay,
+ firstQueryDelay: firstQueryDelay,
+ builtInStartDelay: builtInStartDelay
+ )
self.hardware = hardware
self.controller = DirectCoreAudioLifecycleController(
packetHandler: service.recoveryPacketHandlerForTesting,
diff --git a/Tests/FluidDictationIntegrationTests/AudioTopologyDiagnosticsTests.swift b/Tests/FluidDictationIntegrationTests/AudioTopologyDiagnosticsTests.swift
index f00e5e17..386b0574 100644
--- a/Tests/FluidDictationIntegrationTests/AudioTopologyDiagnosticsTests.swift
+++ b/Tests/FluidDictationIntegrationTests/AudioTopologyDiagnosticsTests.swift
@@ -1,5 +1,5 @@
-@testable import FluidVoice_Debug
import CoreAudio
+@testable import FluidVoice_Debug
import XCTest
final class AudioTopologyDiagnosticsTests: XCTestCase {
@@ -58,7 +58,7 @@ final class AudioTopologyDiagnosticsTests: XCTestCase {
XCTAssertEqual(snapshot.events.count, 1)
XCTAssertTrue(AudioTopologyDiagnostics.hasOpenTopologyPhase(snapshot.events))
- let line = AudioTopologyDiagnostics.jsonLine(for: try XCTUnwrap(snapshot.events.first))
+ let line = try AudioTopologyDiagnostics.jsonLine(for: XCTUnwrap(snapshot.events.first))
let object = try XCTUnwrap(
JSONSerialization.jsonObject(with: Data(line)) as? [String: Any]
)
@@ -154,12 +154,12 @@ final class AudioTopologyDiagnosticsTests: XCTestCase {
}
func testConcurrentProducersAndSnapshotsRemainOrdered() {
- DispatchQueue.concurrentPerform(iterations: 1_000) { index in
+ DispatchQueue.concurrentPerform(iterations: 1000) { index in
_ = Self.record(.callback, objectID: AudioObjectID(index + 1))
if index.isMultiple(of: 17) { _ = Self.snapshot() }
}
let snapshot = Self.snapshot()
- XCTAssertEqual(snapshot.latest, 1_000)
+ XCTAssertEqual(snapshot.latest, 1000)
XCTAssertEqual(snapshot.events.map(\.sequence), snapshot.events.map(\.sequence).sorted())
XCTAssertEqual(Set(snapshot.events.map(\.sequence)).count, snapshot.events.count)
}
diff --git a/Tests/FluidDictationIntegrationTests/ClockDomainProbeTests.swift b/Tests/FluidDictationIntegrationTests/ClockDomainProbeTests.swift
index 0f87964e..5cc34e6c 100644
--- a/Tests/FluidDictationIntegrationTests/ClockDomainProbeTests.swift
+++ b/Tests/FluidDictationIntegrationTests/ClockDomainProbeTests.swift
@@ -1,6 +1,6 @@
-@testable import FluidVoice_Debug
import AVFoundation
import CoreMedia
+@testable import FluidVoice_Debug
import Foundation
import ScreenCaptureKit
import XCTest
@@ -57,7 +57,11 @@ final class ClockDomainProbeTests: XCTestCase {
if let fit = await recorder.regression() {
print(String(
format: "[clock] t=%4.0fs n=%6d slope=%+.3f ppm residualStd=%.3f ms ptsSpan=%.1fs",
- elapsed, fit.count, fit.slopePPM, fit.residualStdMs, fit.ptsSpanSeconds
+ elapsed,
+ fit.count,
+ fit.slopePPM,
+ fit.residualStdMs,
+ fit.ptsSpanSeconds
))
}
}
@@ -68,13 +72,15 @@ final class ClockDomainProbeTests: XCTestCase {
}
print(String(
format: "\n[clock] FINAL n=%d slope=%+.3f ppm (95%% CI ±%.3f) residualStd=%.3f ms gate=%@",
- fit.count, fit.slopePPM, fit.slopeCI95PPM, fit.residualStdMs,
+ fit.count,
+ fit.slopePPM,
+ fit.slopeCI95PPM,
+ fit.residualStdMs,
abs(fit.slopePPM) < 20 ? "CONSTANT OFFSET OK" : "LINEAR MODEL REQUIRED"
))
}
}
-
private final class ClockProbeOutput: NSObject, SCStreamOutput {
private let recorder: ClockPairRecorder
private static let timebase: Double = {
diff --git a/Tests/FluidDictationIntegrationTests/ClockRegressionHelper.swift b/Tests/FluidDictationIntegrationTests/ClockRegressionHelper.swift
index 4d98728d..eb62f6c8 100644
--- a/Tests/FluidDictationIntegrationTests/ClockRegressionHelper.swift
+++ b/Tests/FluidDictationIntegrationTests/ClockRegressionHelper.swift
@@ -68,7 +68,7 @@ final actor ClockPairRecorder {
count: n,
slopePPM: (slope - 1) * 1_000_000,
slopeCI95PPM: 1.96 * slopeStdErr * 1_000_000,
- residualStdMs: residualVariance.squareRoot() * 1_000,
+ residualStdMs: residualVariance.squareRoot() * 1000,
ptsSpanSeconds: ys.last ?? 0
)
}
diff --git a/Tests/FluidDictationIntegrationTests/DashboardLayoutTests.swift b/Tests/FluidDictationIntegrationTests/DashboardLayoutTests.swift
index b7bb3c49..2717801f 100644
--- a/Tests/FluidDictationIntegrationTests/DashboardLayoutTests.swift
+++ b/Tests/FluidDictationIntegrationTests/DashboardLayoutTests.swift
@@ -6,7 +6,7 @@ final class DashboardLayoutTests: XCTestCase {
func testSetupCardsAlwaysFillTheirRows() {
for width in stride(from: 320, through: 2000, by: 1) {
let layout = DashboardLayout(width: CGFloat(width))
- for count in 1 ... 3 {
+ for count in 1...3 {
XCTAssertEqual(count % layout.setupColumns(count: count), 0)
if layout.setupColumns(count: count) > 1 {
XCTAssertGreaterThanOrEqual((layout.contentWidth - CGFloat(count - 1) * 10) / CGFloat(count), 280)
@@ -96,11 +96,27 @@ final class DashboardLayoutTests: XCTestCase {
}
func testExistingSuccessfulUseCountsEvenWhenNoWordsChanged() throws {
- let entry = TranscriptionHistoryEntry(timestamp: Date(), rawText: "Already correct.", processedText: "Already correct.", appName: "Notes", windowTitle: "", wasAIProcessed: true, processingModel: "fluid-1-mini")
+ let entry = TranscriptionHistoryEntry(
+ timestamp: Date(),
+ rawText: "Already correct.",
+ processedText: "Already correct.",
+ appName: "Notes",
+ windowTitle: "",
+ wasAIProcessed: true,
+ processingModel: "fluid-1-mini"
+ )
let snapshot = try StatsSnapshot.build(entries: [entry], now: Date(), calendar: .current)
XCTAssertTrue(snapshot.hasFluidIntelligenceUse)
XCTAssertEqual(snapshot.fluidFixedWords, 0)
- let failed = TranscriptionHistoryEntry(timestamp: Date(), rawText: "Raw", processedText: "Raw", appName: "Notes", windowTitle: "", wasAIProcessed: false, processingModel: "fluid-1-mini")
+ let failed = TranscriptionHistoryEntry(
+ timestamp: Date(),
+ rawText: "Raw",
+ processedText: "Raw",
+ appName: "Notes",
+ windowTitle: "",
+ wasAIProcessed: false,
+ processingModel: "fluid-1-mini"
+ )
XCTAssertFalse(try StatsSnapshot.build(entries: [failed], now: Date(), calendar: .current).hasFluidIntelligenceUse)
}
}
diff --git a/Tests/FluidDictationIntegrationTests/Helpers/AudioFixtureLoader.swift b/Tests/FluidDictationIntegrationTests/Helpers/AudioFixtureLoader.swift
index c6a1e46e..7838b902 100644
--- a/Tests/FluidDictationIntegrationTests/Helpers/AudioFixtureLoader.swift
+++ b/Tests/FluidDictationIntegrationTests/Helpers/AudioFixtureLoader.swift
@@ -41,7 +41,7 @@ enum AudioFixtureLoader {
inputFormat.commonFormat == desiredFormat.commonFormat
{
let buffer = try readAllFrames(file: inputFile, format: inputFormat)
- return try extractMonoFloatSamples(buffer: buffer)
+ return try self.extractMonoFloatSamples(buffer: buffer)
}
guard let converter = AVAudioConverter(from: inputFormat, to: desiredFormat) else {
@@ -73,7 +73,7 @@ enum AudioFixtureLoader {
throw LoaderError.unsupportedAudio(conversionError.localizedDescription)
}
- return try extractMonoFloatSamples(buffer: outputBuffer)
+ return try self.extractMonoFloatSamples(buffer: outputBuffer)
}
private static func readAllFrames(file: AVAudioFile, format: AVAudioFormat) throws -> AVAudioPCMBuffer {
diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
index b5c68198..65643549 100644
--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
@@ -13,8 +13,7 @@ final class HotkeyShortcutTests: XCTestCase {
let key = "OverlayGlassOpacity"
let previous = defaults.object(forKey: key)
defer {
- if let previous { defaults.set(previous, forKey: key) }
- else { defaults.removeObject(forKey: key) }
+ if let previous { defaults.set(previous, forKey: key) } else { defaults.removeObject(forKey: key) }
}
for invalid in [Double.nan, .infinity, -.infinity] {
SettingsStore.shared.overlayGlassOpacity = invalid
@@ -33,8 +32,7 @@ final class HotkeyShortcutTests: XCTestCase {
let previous = keys.map { defaults.object(forKey: $0) }
defer {
for (key, value) in zip(keys, previous) {
- if let value { defaults.set(value, forKey: key) }
- else { defaults.removeObject(forKey: key) }
+ if let value { defaults.set(value, forKey: key) } else { defaults.removeObject(forKey: key) }
}
}
// 800-point minimum window minus sidebar, settings insets, and card padding.
diff --git a/Tests/FluidDictationIntegrationTests/MeetingAEC3Tests.swift b/Tests/FluidDictationIntegrationTests/MeetingAEC3Tests.swift
index ecfe6e50..02b8cb52 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingAEC3Tests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingAEC3Tests.swift
@@ -1,9 +1,9 @@
#if DEBUG
-@testable import FluidVoice_Debug
import AudioToolbox
import AVFoundation
import CoreMedia
+@testable import FluidVoice_Debug
import Foundation
import XCTest
@@ -219,7 +219,9 @@ final class MeetingAEC3Tests: XCTestCase {
let inputs = micFirst
? [self.block(.capture, start: start, count: 480), self.block(.render, start: start, count: 480)]
: [self.block(.render, start: start, count: 480), self.block(.capture, start: start, count: 480)]
- for input in inputs { result += self.paired(joiner.append(input)) }
+ for input in inputs {
+ result += self.paired(joiner.append(input))
+ }
}
return result.map(\.capture.presentationTime)
}
@@ -243,7 +245,7 @@ final class MeetingAEC3Tests: XCTestCase {
var joiner = MeetingAECStreamJoiner()
_ = joiner.append(self.block(.render, start: 0, count: 480))
_ = joiner.append(self.block(.capture, start: 0, count: 480))
- let emissions = joiner.append(self.block(.capture, start: 480, count: 5_280))
+ let emissions = joiner.append(self.block(.capture, start: 480, count: 5280))
XCTAssertTrue(emissions.contains { if case .reset(.renderLate) = $0 { return true }; return false })
XCTAssertGreaterThan(joiner.diagnostics.bypassFrames, 0)
XCTAssertEqual(joiner.diagnostics.retainedCaptureSamples, 0)
@@ -310,7 +312,7 @@ final class MeetingAEC3Tests: XCTestCase {
let drifted = MeetingAECPCMBlock(
kind: .render,
stream: self.token,
- presentationTime: CMTime(value: 1_925, timescale: 192_000),
+ presentationTime: CMTime(value: 1925, timescale: 192_000),
duration: CMTime(value: 480, timescale: 48_000),
samples: [Float](repeating: 0.1, count: 480)
)
@@ -402,7 +404,7 @@ final class MeetingAEC3Tests: XCTestCase {
var synthesizedSource = [Float](repeating: 0.4, count: 480)
let synthesized = try XCTUnwrap(MeetingAECPCMAdapter.synthesize(
samples: synthesizedSource,
- presentationTime: CMTime(value: 9_600, timescale: 48_000)
+ presentationTime: CMTime(value: 9600, timescale: 48_000)
))
synthesizedSource = [Float](repeating: -0.4, count: 480)
let extracted = try MeetingAECPCMAdapter.extract(
@@ -411,7 +413,7 @@ final class MeetingAEC3Tests: XCTestCase {
stream: self.token
).get()
XCTAssertEqual(extracted.samples.first, 0.4)
- XCTAssertEqual(extracted.presentationTime, CMTime(value: 9_600, timescale: 48_000))
+ XCTAssertEqual(extracted.presentationTime, CMTime(value: 9600, timescale: 48_000))
XCTAssertEqual(extracted.duration, CMTime(value: 480, timescale: 48_000))
_ = synthesizedSource
}
@@ -511,9 +513,9 @@ final class MeetingAEC3Tests: XCTestCase {
func testAECProvenanceIsBackwardCompatibleAndSoftwareProtectionAdmits() throws {
XCTAssertTrue(MeetingMicrophoneEchoProtection.softwareEchoCancelled.admitsTranscript)
- let legacy = """
+ let legacy = Data("""
{"method":"screenCaptureKit","roleAtElection":"unknown","echoProtection":"unprotected","startSeconds":0}
- """.data(using: .utf8)!
+ """.utf8)
let decoded = try JSONDecoder().decode(MeetingCaptureEra.self, from: legacy)
XCTAssertNil(decoded.aecProvenance)
@@ -530,18 +532,28 @@ final class MeetingAEC3Tests: XCTestCase {
let eras = [
MeetingCaptureEra(
- method: .screenCaptureKit, deviceUID: nil, deviceName: nil,
- roleAtElection: .personal, echoProtection: .unprotected,
+ method: .screenCaptureKit,
+ deviceUID: nil,
+ deviceName: nil,
+ roleAtElection: .personal,
+ echoProtection: .unprotected,
startSeconds: -.infinity
),
MeetingCaptureEra(
- method: .screenCaptureKit, deviceUID: nil, deviceName: nil,
- roleAtElection: .personal, echoProtection: .softwareEchoCancelled,
- startSeconds: 2, aecProvenance: MeetingAECConstants.provenance
+ method: .screenCaptureKit,
+ deviceUID: nil,
+ deviceName: nil,
+ roleAtElection: .personal,
+ echoProtection: .softwareEchoCancelled,
+ startSeconds: 2,
+ aecProvenance: MeetingAECConstants.provenance
),
MeetingCaptureEra(
- method: .screenCaptureKit, deviceUID: nil, deviceName: nil,
- roleAtElection: .personal, echoProtection: .unprotected,
+ method: .screenCaptureKit,
+ deviceUID: nil,
+ deviceName: nil,
+ roleAtElection: .personal,
+ echoProtection: .unprotected,
startSeconds: 4
),
]
@@ -595,10 +607,10 @@ final class MeetingAEC3Tests: XCTestCase {
XCTAssertEqual(live.count, 0)
let promotionPTS = CMTime(value: 200 * 480, timescale: 48_000)
- pipeline.consumeRender(try XCTUnwrap(MeetingAECPCMAdapter.synthesize(
+ try pipeline.consumeRender(XCTUnwrap(MeetingAECPCMAdapter.synthesize(
samples: [Float](repeating: 0.2, count: 480), presentationTime: promotionPTS
)), stream: self.token)
- pipeline.consumeCapture(try XCTUnwrap(MeetingAECPCMAdapter.synthesize(
+ try pipeline.consumeCapture(XCTUnwrap(MeetingAECPCMAdapter.synthesize(
samples: [Float](repeating: 0.1, count: 480), presentationTime: promotionPTS
)), stream: self.token)
await committer.waitForPendingCommits()
@@ -606,14 +618,14 @@ final class MeetingAEC3Tests: XCTestCase {
XCTAssertEqual(track.captureEras?.last?.echoProtection, .softwareEchoCancelled)
XCTAssertEqual(track.captureEras?.last?.aecProvenance, MeetingAECConstants.provenance)
XCTAssertEqual(live.count, 1)
- XCTAssertEqual(try live.firstMean(token: self.token), 0.35, accuracy: 0.000_01)
+ XCTAssertEqual(try live.firstMean(token: self.token), 0.35, accuracy: 0.00_001)
processor.failNext = true
let failurePTS = CMTime(value: 201 * 480, timescale: 48_000)
- pipeline.consumeRender(try XCTUnwrap(MeetingAECPCMAdapter.synthesize(
+ try pipeline.consumeRender(XCTUnwrap(MeetingAECPCMAdapter.synthesize(
samples: [Float](repeating: 0.2, count: 480), presentationTime: failurePTS
)), stream: self.token)
- pipeline.consumeCapture(try XCTUnwrap(MeetingAECPCMAdapter.synthesize(
+ try pipeline.consumeCapture(XCTUnwrap(MeetingAECPCMAdapter.synthesize(
samples: [Float](repeating: 0.1, count: 480), presentationTime: failurePTS
)), stream: self.token)
await committer.waitForPendingCommits()
@@ -621,7 +633,8 @@ final class MeetingAEC3Tests: XCTestCase {
XCTAssertEqual(track.captureEras?.last?.echoProtection, .unprotected)
XCTAssertNil(track.captureEras?.last?.aecProvenance)
XCTAssertEqual(
- track.captureEras?.map(\.startSeconds), [0, 2, 2.01],
+ track.captureEras?.map(\.startSeconds),
+ [0, 2, 2.01],
"the demotion era must be ordered after the protected era on the sample timeline"
)
XCTAssertEqual(live.count, 1, "the bridge-failure raw frame must not reach live ASR")
@@ -736,6 +749,8 @@ final class MeetingAEC3Tests: XCTestCase {
for step in 0...completedSteps {
switch step {
case 0:
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
token = controller.reserveConstruction()!
case 1:
XCTAssertTrue(controller.commitCandidate(token))
@@ -807,7 +822,7 @@ final class MeetingAEC3Tests: XCTestCase {
}
XCTAssertEqual(bypasses.count, 1)
XCTAssertEqual(bypasses.first?.samples.count, 240, "the incomplete tail is emitted raw without padding")
- XCTAssertEqual(bypasses.first?.presentationTime, CMTime(value: 1_440, timescale: 48_000))
+ XCTAssertEqual(bypasses.first?.presentationTime, CMTime(value: 1440, timescale: 48_000))
XCTAssertTrue(flushed.contains { if case .reset(.stopped) = $0 { return true }; return false })
XCTAssertEqual(joiner.diagnostics.retainedCaptureSamples, 0)
XCTAssertEqual(joiner.diagnostics.retainedRenderSamples, 0)
@@ -890,7 +905,8 @@ final class MeetingAEC3Tests: XCTestCase {
XCTAssertEqual(track.captureEras?.last?.echoProtection, .unprotected)
XCTAssertEqual(track.captureEras?.last?.startSeconds, 2)
XCTAssertEqual(
- track.captureEras?.count, 3,
+ track.captureEras?.count,
+ 3,
"the second overlapping fail-closed command must not run its own emergency write"
)
_ = await writer.stop()
@@ -1043,18 +1059,18 @@ final class MeetingAEC3Tests: XCTestCase {
))
}
- committer.commitProcessed(try sample(480), mayPromote: true)
+ try committer.commitProcessed(sample(480), mayPromote: true)
XCTAssertTrue(recorder.waitUntilFirstHandlerStarts())
// This callback runs while the promotion handler is deliberately blocked. It must still
// observe promotionPending and therefore cannot overtake the first live frame.
- committer.commitProcessed(try sample(960), mayPromote: false)
+ try committer.commitProcessed(sample(960), mayPromote: false)
recorder.releaseFirstHandler()
await committer.waitForPendingCommits()
_ = await writer.snapshot()
- committer.commitProcessed(try sample(1_440), mayPromote: false)
+ try committer.commitProcessed(sample(1440), mayPromote: false)
_ = await writer.snapshot()
- XCTAssertEqual(recorder.presentationValues, [480, 1_440])
+ XCTAssertEqual(recorder.presentationValues, [480, 1440])
_ = await writer.stop()
}
@@ -1131,6 +1147,8 @@ final class MeetingAEC3Tests: XCTestCase {
) == noErr, let blockBuffer else { return nil }
guard interleaved.withUnsafeBytes({ bytes in
CMBlockBufferReplaceDataBytes(
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
with: bytes.baseAddress!,
blockBuffer: blockBuffer,
offsetIntoDestination: 0,
diff --git a/Tests/FluidDictationIntegrationTests/MeetingASRPreparationOwnerTests.swift b/Tests/FluidDictationIntegrationTests/MeetingASRPreparationOwnerTests.swift
index 06c65f40..ab4e6b4d 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingASRPreparationOwnerTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingASRPreparationOwnerTests.swift
@@ -288,7 +288,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
on owner: MeetingASRPreparationOwner
) -> ContinuationGate {
let secondWaiterEntered = ContinuationGate()
-#if DEBUG
+ #if DEBUG
let waiters = OrchestrationRecorder()
owner.didBeginWaitingForTesting = {
waiters.record("waiting")
@@ -296,7 +296,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
secondWaiterEntered.open()
}
}
-#endif
+ #endif
return secondWaiterEntered
}
@@ -636,8 +636,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
do {
_ = try await preparation.value
XCTFail("Expected retirement cancellation")
- } catch is CancellationError {
- }
+ } catch is CancellationError {}
XCTAssertEqual(harness.recorder.count(of: "factory"), 0)
XCTAssertEqual(harness.recorder.count(of: "drain"), 1)
XCTAssertFalse(harness.owner.isClaimed)
@@ -660,8 +659,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
do {
_ = try await preparation.value
XCTFail("Expected invalid-lease cancellation")
- } catch is CancellationError {
- }
+ } catch is CancellationError {}
XCTAssertEqual(harness.recorder.count(of: "factory"), 0)
XCTAssertEqual(harness.recorder.count(of: "drain"), 1)
XCTAssertFalse(harness.owner.isClaimed)
@@ -677,8 +675,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
lease: lease, attemptID: UUID(), configuration: MeetingFinalProcessingConfiguration()
)
XCTFail("Expected retirement failure")
- } catch PreparationTestError.retireFailed {
- }
+ } catch PreparationTestError.retireFailed {}
XCTAssertEqual(harness.recorder.events, ["retire", "drain"])
XCTAssertFalse(harness.owner.isClaimed)
}
@@ -711,8 +708,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
do {
_ = try await preparation.value
XCTFail("Expected preparation failure")
- } catch PreparationTestError.prepareFailed {
- }
+ } catch PreparationTestError.prepareFailed {}
await release.value
XCTAssertFalse(harness.owner.isClaimed)
}
@@ -749,9 +745,9 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
harness.provider.blockPrepare(on: providerGate)
harness.provider.onPrepareEntered { entered.open() }
let secondWaiterEntered = self.installSecondWaiterAcknowledgement(on: harness.owner)
-#if !DEBUG
+ #if !DEBUG
let secondStarted = ContinuationGate()
-#endif
+ #endif
let first = Task { @MainActor in
try await harness.owner.prepare(
lease: lease, attemptID: attemptID, configuration: MeetingFinalProcessingConfiguration()
@@ -760,19 +756,19 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
let enteredObserved = await waitUntilCondition { entered.opened }
XCTAssertTrue(enteredObserved)
let second = Task { @MainActor in
-#if !DEBUG
+ #if !DEBUG
secondStarted.open()
-#endif
+ #endif
return try await harness.owner.prepare(
lease: lease, attemptID: attemptID, configuration: MeetingFinalProcessingConfiguration()
)
}
// Both waiters join the same exact operation; cancellation of one cancels the shared worker.
-#if DEBUG
+ #if DEBUG
let secondObserved = await waitUntilCondition { secondWaiterEntered.opened }
-#else
+ #else
let secondObserved = await waitUntilCondition { secondStarted.opened }
-#endif
+ #endif
XCTAssertTrue(secondObserved)
second.cancel()
providerGate.open()
@@ -794,7 +790,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
XCTAssertFalse(harness.owner.isClaimed)
}
-#if DEBUG
+ #if DEBUG
func testReadyTransitionCancelsJoinedWaiterBeforeEitherCanReturn() async throws {
var joinedWaiter: Task<any TranscriptionProvider, Error>?
let harness = self.makeHarness()
@@ -809,9 +805,9 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
harness.provider.blockPrepare(on: providerGate)
harness.provider.onPrepareEntered { entered.open() }
let secondWaiterEntered = self.installSecondWaiterAcknowledgement(on: harness.owner)
-#if !DEBUG
+ #if !DEBUG
let secondStarted = ContinuationGate()
-#endif
+ #endif
let first = Task { @MainActor in
try await harness.owner.prepare(
@@ -821,19 +817,19 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
let enteredObserved = await waitUntilCondition { entered.opened }
XCTAssertTrue(enteredObserved)
let second = Task { @MainActor in
-#if !DEBUG
+ #if !DEBUG
secondStarted.open()
-#endif
+ #endif
return try await harness.owner.prepare(
lease: lease, attemptID: attemptID, configuration: MeetingFinalProcessingConfiguration()
)
}
joinedWaiter = second
-#if DEBUG
+ #if DEBUG
let secondObserved = await waitUntilCondition { secondWaiterEntered.opened }
-#else
+ #else
let secondObserved = await waitUntilCondition { secondStarted.opened }
-#endif
+ #endif
XCTAssertTrue(secondObserved)
providerGate.open()
@@ -855,7 +851,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
XCTAssertFalse(harness.owner.isClaimed)
joinedWaiter = nil
}
-#endif
+ #endif
func testProgressHopsToMainActorAndStaleEventsAreDroppedAfterReleaseAndLeaseChange() async throws {
let harness = self.makeHarness()
@@ -978,8 +974,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
do {
_ = try await preparation.value
XCTFail("Expected cancelled preparation")
- } catch is CancellationError {
- }
+ } catch is CancellationError {}
XCTAssertTrue(deliveries.events.isEmpty)
}
@@ -1012,8 +1007,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
do {
_ = try await preparation.value
XCTFail("Expected invalidated preparation")
- } catch is CancellationError {
- }
+ } catch is CancellationError {}
XCTAssertTrue(deliveries.events.isEmpty)
}
}
@@ -1096,7 +1090,7 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
XCTAssertTrue(harness.owner.isClaimed)
XCTAssertEqual(harness.recorder.count(of: "drain"), 0)
- await harness.owner.release(try XCTUnwrap(harness.owner.currentClaimToken))
+ try await harness.owner.release(XCTUnwrap(harness.owner.currentClaimToken))
XCTAssertFalse(harness.owner.isClaimed)
XCTAssertEqual(harness.recorder.count(of: "drain"), 1)
}
@@ -1121,9 +1115,9 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
drainExecutor: { _ in }
)
let secondWaiterEntered = self.installSecondWaiterAcknowledgement(on: owner)
-#if !DEBUG
+ #if !DEBUG
let secondStarted = ContinuationGate()
-#endif
+ #endif
self.addTeardownBlock { @MainActor in
providerGate.open()
if let token = owner.currentClaimToken {
@@ -1145,9 +1139,9 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
let enteredObserved = await waitUntilCondition { providerEntered.opened }
XCTAssertTrue(enteredObserved)
let second = Task { @MainActor in
-#if !DEBUG
+ #if !DEBUG
secondStarted.open()
-#endif
+ #endif
do {
_ = try await owner.prepare(
lease: lease, attemptID: attemptID, configuration: MeetingFinalProcessingConfiguration()
@@ -1157,11 +1151,11 @@ final class MeetingASRPreparationOwnerTests: XCTestCase {
return false
}
}
-#if DEBUG
+ #if DEBUG
let secondObserved = await waitUntilCondition { secondWaiterEntered.opened }
-#else
+ #else
let secondObserved = await waitUntilCondition { secondStarted.opened }
-#endif
+ #endif
XCTAssertTrue(secondObserved)
providerGate.open()
let firstSucceeded = await first.value
@@ -1622,10 +1616,10 @@ final class ASRServiceMeetingASRScopeTests: XCTestCase {
let provider = try FluidAudioProvider(meetingConfiguration: MeetingFinalProcessingConfiguration())
XCTAssertEqual(provider.modelOverride, .parakeetTDTv2)
#if DEBUG
- let options = provider.effectiveEnhancementOptionsForTesting
- XCTAssertFalse(options.experimentalUnifiedFinalEnabled)
- XCTAssertFalse(options.pronunciationMatchingEnabled)
- XCTAssertTrue(options.customDictionaryEntries.isEmpty)
+ let options = provider.effectiveEnhancementOptionsForTesting
+ XCTAssertFalse(options.experimentalUnifiedFinalEnabled)
+ XCTAssertFalse(options.pronunciationMatchingEnabled)
+ XCTAssertTrue(options.customDictionaryEntries.isEmpty)
#endif
// Dictation selection is untouched by meeting provider construction.
XCTAssertEqual(settings.selectedSpeechModel, .parakeetTDT)
diff --git a/Tests/FluidDictationIntegrationTests/MeetingAnalysisManifestTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAnalysisManifestTests.swift
index aefb0105..6967fe5f 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingAnalysisManifestTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingAnalysisManifestTests.swift
@@ -70,6 +70,8 @@ final class MeetingAnalysisManifestTests: XCTestCase {
kind: MeetingAudioTrackKind,
chunks: [MeetingAudioChunk],
captureMethod: MeetingAudioTrackCaptureMethod? = nil,
+ // nil requests the fixture default; an empty collection tests explicitly missing data.
+ // swiftlint:disable:next discouraged_optional_collection
eras: [MeetingCaptureEra]? = nil,
hostClock: UInt64 = 42
) -> MeetingAudioTrack {
@@ -172,6 +174,8 @@ final class MeetingAnalysisManifestTests: XCTestCase {
private func replacing(
_ manifest: MeetingAnalysisManifest,
origin: Double? = nil,
+ // nil requests the fixture default; an empty collection tests explicitly missing data.
+ // swiftlint:disable:next discouraged_optional_collection
tracks: [MeetingAnalysisTrackManifest]? = nil
) -> MeetingAnalysisManifest {
MeetingAnalysisManifest(
@@ -203,6 +207,8 @@ final class MeetingAnalysisManifestTests: XCTestCase {
let pcm = MeetingCodecPriming.notApplicable(.linearPCMFloat32CAFV1)
let encoded = try encoder.encode(pcm)
XCTAssertEqual(
+ // JSONEncoder fixture bytes are UTF-8; retain nonoptional decoding for assertions.
+ // swiftlint:disable:next optional_data_string_conversion
String(decoding: encoded, as: UTF8.self),
#"{"notApplicable":{"_0":"linearPCMFloat32CAFV1"}}"#
)
@@ -548,8 +554,12 @@ final class MeetingAnalysisManifestTests: XCTestCase {
channels: 1,
interleaved: true
))
- let file = try AVAudioFile(forWriting: pcmURL, settings: format.settings,
- commonFormat: .pcmFormatFloat32, interleaved: true)
+ let file = try AVAudioFile(
+ forWriting: pcmURL,
+ settings: format.settings,
+ commonFormat: .pcmFormatFloat32,
+ interleaved: true
+ )
let buffer = try XCTUnwrap(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 1600))
buffer.frameLength = 1600
try file.write(from: buffer)
@@ -568,10 +578,16 @@ final class MeetingAnalysisManifestTests: XCTestCase {
frameCount: 1600
)
let chunk = MeetingAudioChunk(
- id: UUID(), sequence: 0, relativeFilePath: "archive/chunk-0.m4a",
- presentationStart: self.mediaTime(0), presentationEnd: self.mediaTime(0.1),
- discontinuities: [], sha256: String(repeating: "a", count: 64), byteCount: 1,
- finalizationState: .finalized, audioSchemaVersion: 2,
+ id: UUID(),
+ sequence: 0,
+ relativeFilePath: "archive/chunk-0.m4a",
+ presentationStart: self.mediaTime(0),
+ presentationEnd: self.mediaTime(0.1),
+ discontinuities: [],
+ sha256: String(repeating: "a", count: 64),
+ byteCount: 1,
+ finalizationState: .finalized,
+ audioSchemaVersion: 2,
captureAnalysisAsset: asset
)
let result = MeetingChunkAudioObserver(sessionDirectory: root)
diff --git a/Tests/FluidDictationIntegrationTests/MeetingAudioAssetCompatibilityTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAudioAssetCompatibilityTests.swift
index 3412fa24..80e642df 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingAudioAssetCompatibilityTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingAudioAssetCompatibilityTests.swift
@@ -4,36 +4,70 @@ import XCTest
final class MeetingAudioAssetCompatibilityTests: XCTestCase {
func testLegacyChunkOmitsAllP0aKeysAndRoundTripsFullSession() throws {
- let chunk = MeetingAudioChunk(id: UUID(), sequence: 3, relativeFilePath: "tracks/microphone/3.caf",
- presentationStart: MeetingMediaTime(value: 0, timescale: 1000),
- presentationEnd: MeetingMediaTime(value: 1000, timescale: 1000),
- discontinuities: [], sha256: "legacy", byteCount: 42, finalizationState: .finalized)
+ let chunk = MeetingAudioChunk(
+ id: UUID(),
+ sequence: 3,
+ relativeFilePath: "tracks/microphone/3.caf",
+ presentationStart: MeetingMediaTime(value: 0, timescale: 1000),
+ presentationEnd: MeetingMediaTime(value: 1000, timescale: 1000),
+ discontinuities: [],
+ sha256: "legacy",
+ byteCount: 42,
+ finalizationState: .finalized
+ )
let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys]
let json = try encoder.encode(chunk)
let object = try XCTUnwrap(try JSONSerialization.jsonObject(with: json) as? [String: Any])
- XCTAssertEqual(Set(object.keys), Set(["id", "sequence", "relativeFilePath", "presentationStart", "presentationEnd", "discontinuities", "sha256", "byteCount", "finalizationState"]))
+ XCTAssertEqual(
+ Set(object.keys),
+ Set(["id", "sequence", "relativeFilePath", "presentationStart", "presentationEnd", "discontinuities", "sha256", "byteCount", "finalizationState"])
+ )
XCTAssertNil(object["audioSchemaVersion"]); XCTAssertNil(object["captureAnalysisAsset"]); XCTAssertNil(object["playbackArchiveAsset"])
let decodedChunk = try JSONDecoder().decode(MeetingAudioChunk.self, from: json)
XCTAssertEqual(decodedChunk, chunk)
let configuration = MeetingCaptureConfiguration(mode: .inRoom, title: "Legacy", microphone: MeetingMicrophoneIdentity(captureDeviceID: "mic", displayName: "Mic"))
- var session = MeetingSession(configuration: configuration, startedAt: Date(timeIntervalSince1970: 1_700_000_000),
- timebase: MeetingTimebaseMetadata(startedHostTime: 1, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil))
- session.audioTracks = [MeetingAudioTrack(id: UUID(), kind: .microphone, sourceIdentifier: "mic", sourceDisplayName: "Mic", format: nil,
- timebase: session.timebase, health: .waiting, chunks: [chunk])]
+ var session = MeetingSession(
+ configuration: configuration,
+ startedAt: Date(timeIntervalSince1970: 1_700_000_000),
+ timebase: MeetingTimebaseMetadata(startedHostTime: 1, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil)
+ )
+ session.audioTracks = [MeetingAudioTrack(
+ id: UUID(),
+ kind: .microphone,
+ sourceIdentifier: "mic",
+ sourceDisplayName: "Mic",
+ format: nil,
+ timebase: session.timebase,
+ health: .waiting,
+ chunks: [chunk]
+ )]
let sessionData = try encoder.encode(session)
XCTAssertEqual(try JSONDecoder().decode(MeetingSession.self, from: sessionData), session)
}
func testValidPCMAssetRoundTripsAndLegacyReadyMayOmitFrameFacts() throws {
- let asset = MeetingAudioAsset(role: .captureAnalysis, encoding: .linearPCMFloat32CAFV1, presence: .ready,
- relativeFilePath: "tracks/application/1.caf", byteCount: 128, sha256: String(repeating: "a", count: 64),
- sampleRate: 48_000, channelCount: 2, frameCount: 16)
+ let asset = MeetingAudioAsset(
+ role: .captureAnalysis,
+ encoding: .linearPCMFloat32CAFV1,
+ presence: .ready,
+ relativeFilePath: "tracks/application/1.caf",
+ byteCount: 128,
+ sha256: String(repeating: "a", count: 64),
+ sampleRate: 48_000,
+ channelCount: 2,
+ frameCount: 16
+ )
let data = try JSONEncoder().encode(asset)
XCTAssertEqual(try JSONDecoder().decode(MeetingAudioAsset.self, from: data), asset)
XCTAssertTrue(asset.validationIssues().isEmpty)
- let legacy = MeetingAudioAsset(role: .playbackArchive, encoding: .legacyAACUnknownPrimingV1, presence: .ready,
- relativeFilePath: "audio.m4a", byteCount: 1)
+ let legacy = MeetingAudioAsset(
+ role: .playbackArchive,
+ encoding: .legacyAACUnknownPrimingV1,
+ presence: .ready,
+ relativeFilePath: "audio.m4a",
+ byteCount: 1
+ )
XCTAssertTrue(legacy.validationIssues().isEmpty)
}
@@ -60,8 +94,8 @@ final class MeetingAudioAssetCompatibilityTests: XCTestCase {
id: UUID(),
sequence: 0,
relativeFilePath: "tracks/application/legacy.m4a",
- presentationStart: MeetingMediaTime(value: 0, timescale: 1_000),
- presentationEnd: MeetingMediaTime(value: 1_000, timescale: 1_000),
+ presentationStart: MeetingMediaTime(value: 0, timescale: 1000),
+ presentationEnd: MeetingMediaTime(value: 1000, timescale: 1000),
discontinuities: [],
sha256: "legacy",
byteCount: 1,
@@ -76,8 +110,13 @@ final class MeetingAudioAssetCompatibilityTests: XCTestCase {
}
func testReadyPCMAssetWithoutFactsIsInvalidPurelyFromMetadata() {
- let invalid = MeetingAudioAsset(role: .captureAnalysis, encoding: .linearPCMFloat32CAFV1, presence: .ready,
- relativeFilePath: "tracks/application/1.caf", byteCount: 128)
+ let invalid = MeetingAudioAsset(
+ role: .captureAnalysis,
+ encoding: .linearPCMFloat32CAFV1,
+ presence: .ready,
+ relativeFilePath: "tracks/application/1.caf",
+ byteCount: 128
+ )
XCTAssertTrue(invalid.validationIssues().contains(.readyAssetMissingHash))
XCTAssertTrue(invalid.validationIssues().contains(.readyAssetMissingSampleRate))
XCTAssertTrue(invalid.validationIssues().contains(.readyAssetMissingChannelCount))
diff --git a/Tests/FluidDictationIntegrationTests/MeetingAudioChunkLedgerRecoveryTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAudioChunkLedgerRecoveryTests.swift
index 5b0f2515..a71972e2 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingAudioChunkLedgerRecoveryTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingAudioChunkLedgerRecoveryTests.swift
@@ -1,5 +1,5 @@
-@testable import FluidVoice_Debug
import CryptoKit
+@testable import FluidVoice_Debug
import Foundation
import XCTest
@@ -9,9 +9,17 @@ final class MeetingAudioChunkLedgerRecoveryTests: XCTestCase {
let root = try self.makeDirectory(); defer { try? FileManager.default.removeItem(at: root) }
let sessionID = UUID(); let store = MeetingSessionStore(rootDirectory: root)
let bytes = Data([1, 2, 3, 4]); let hash = self.hash(bytes)
- let asset = MeetingAudioAsset(role: .captureAnalysis, encoding: .linearPCMFloat32CAFV1, presence: .ready,
- relativeFilePath: "tracks/microphone/pcm.caf", byteCount: Int64(bytes.count), sha256: hash,
- sampleRate: 48_000, channelCount: 1, frameCount: 1)
+ let asset = MeetingAudioAsset(
+ role: .captureAnalysis,
+ encoding: .linearPCMFloat32CAFV1,
+ presence: .ready,
+ relativeFilePath: "tracks/microphone/pcm.caf",
+ byteCount: Int64(bytes.count),
+ sha256: hash,
+ sampleRate: 48_000,
+ channelCount: 1,
+ frameCount: 1
+ )
let missingArchive = MeetingAudioAsset(
role: .playbackArchive,
encoding: .aacLCM4AV1,
@@ -23,14 +31,35 @@ final class MeetingAudioChunkLedgerRecoveryTests: XCTestCase {
channelCount: 1,
frameCount: 1
)
- let chunk = MeetingAudioChunk(id: UUID(), sequence: 0, relativeFilePath: "legacy.m4a",
- presentationStart: MeetingMediaTime(value: 0, timescale: 1000), presentationEnd: MeetingMediaTime(value: 1, timescale: 1000),
- discontinuities: [], sha256: hash, byteCount: Int64(bytes.count), finalizationState: .finalized,
- audioSchemaVersion: 2, captureAnalysisAsset: asset,
- playbackArchiveAsset: missingArchive)
- var session = MeetingSession(id: sessionID, configuration: MeetingCaptureConfiguration(mode: .inRoom, title: "P0b", microphone: MeetingMicrophoneIdentity(captureDeviceID: "m", displayName: "M")),
- timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil))
- let track = MeetingAudioTrack(id: UUID(), kind: .microphone, sourceIdentifier: "m", sourceDisplayName: "M", format: nil, timebase: session.timebase, health: .waiting, chunks: [chunk])
+ let chunk = MeetingAudioChunk(
+ id: UUID(),
+ sequence: 0,
+ relativeFilePath: "legacy.m4a",
+ presentationStart: MeetingMediaTime(value: 0, timescale: 1000),
+ presentationEnd: MeetingMediaTime(value: 1, timescale: 1000),
+ discontinuities: [],
+ sha256: hash,
+ byteCount: Int64(bytes.count),
+ finalizationState: .finalized,
+ audioSchemaVersion: 2,
+ captureAnalysisAsset: asset,
+ playbackArchiveAsset: missingArchive
+ )
+ var session = MeetingSession(
+ id: sessionID,
+ configuration: MeetingCaptureConfiguration(mode: .inRoom, title: "P0b", microphone: MeetingMicrophoneIdentity(captureDeviceID: "m", displayName: "M")),
+ timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil)
+ )
+ let track = MeetingAudioTrack(
+ id: UUID(),
+ kind: .microphone,
+ sourceIdentifier: "m",
+ sourceDisplayName: "M",
+ format: nil,
+ timebase: session.timebase,
+ health: .waiting,
+ chunks: [chunk]
+ )
session.audioTracks = [track]
try await store.create(session)
let directory = try await store.sessionDirectory(for: sessionID)
@@ -51,11 +80,25 @@ final class MeetingAudioChunkLedgerRecoveryTests: XCTestCase {
}
func testPartialOrEscapingNewAssetIsNeverPromoted() async throws {
- let chunk = MeetingAudioChunk(id: UUID(), sequence: 0, relativeFilePath: "legacy.m4a",
- presentationStart: MeetingMediaTime(value: 0, timescale: 1), presentationEnd: MeetingMediaTime(value: 1, timescale: 1),
- discontinuities: [], sha256: "legacy", byteCount: 1, finalizationState: .writing, audioSchemaVersion: 2,
- captureAnalysisAsset: MeetingAudioAsset(role: .captureAnalysis, encoding: .linearPCMFloat32CAFV1, presence: .partial,
- relativeFilePath: "../outside.partial.caf", byteCount: 0))
+ let chunk = MeetingAudioChunk(
+ id: UUID(),
+ sequence: 0,
+ relativeFilePath: "legacy.m4a",
+ presentationStart: MeetingMediaTime(value: 0, timescale: 1),
+ presentationEnd: MeetingMediaTime(value: 1, timescale: 1),
+ discontinuities: [],
+ sha256: "legacy",
+ byteCount: 1,
+ finalizationState: .writing,
+ audioSchemaVersion: 2,
+ captureAnalysisAsset: MeetingAudioAsset(
+ role: .captureAnalysis,
+ encoding: .linearPCMFloat32CAFV1,
+ presence: .partial,
+ relativeFilePath: "../outside.partial.caf",
+ byteCount: 0
+ )
+ )
let root = try self.makeDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let sessionID = UUID()
@@ -101,5 +144,10 @@ final class MeetingAudioChunkLedgerRecoveryTests: XCTestCase {
}
private func hash(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }
- private func makeDirectory() throws -> URL { let url = FileManager.default.temporaryDirectory.appendingPathComponent("FluidVoice-P0b-recovery-\(UUID().uuidString)"); try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false); return url }
+ private func makeDirectory() throws -> URL { let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("FluidVoice-P0b-recovery-\(UUID().uuidString)"); try FileManager.default.createDirectory(
+ at: url,
+ withIntermediateDirectories: false
+ ); return url
+ }
}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingAudioChunkLedgerTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAudioChunkLedgerTests.swift
index 5b793c10..eabad1db 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingAudioChunkLedgerTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingAudioChunkLedgerTests.swift
@@ -7,28 +7,50 @@ final class MeetingAudioChunkLedgerTests: XCTestCase {
let root = try self.makeDirectory()
let id = UUID()
let store = MeetingAudioChunkLedgerStore(sessionDirectory: root)
- let intent = MeetingAudioChunkLedgerIntent(chunkID: id, sequence: 4,
- canonicalStart: MeetingMediaTime(value: 125, timescale: 1000), producerEpoch: 9,
+ let intent = MeetingAudioChunkLedgerIntent(
+ chunkID: id,
+ sequence: 4,
+ canonicalStart: MeetingMediaTime(value: 125, timescale: 1000),
+ producerEpoch: 9,
sourceFormat: MeetingAudioFormat(codec: "lpcm-f32", sampleRate: 48_000, channelCount: 2, bitRate: nil),
- partialRelativeFilePath: "tracks/application/4.partial.caf", createdAt: Date(timeIntervalSince1970: 1_700_000_000))
+ partialRelativeFilePath: "tracks/application/4.partial.caf",
+ createdAt: Date(timeIntervalSince1970: 1_700_000_000)
+ )
try store.writeIntent(intent)
- try store.writeCheckpoint(MeetingAudioChunkLedgerCheckpoint(chunkID: id, expectedFrames: 48000, writtenFrames: 24000,
- lastCanonicalPTS: MeetingMediaTime(value: 625, timescale: 1000), updatedAt: intent.createdAt), for: id)
- try store.writeCheckpoint(MeetingAudioChunkLedgerCheckpoint(chunkID: id, expectedFrames: 48000, writtenFrames: 48000,
- lastCanonicalPTS: MeetingMediaTime(value: 1125, timescale: 1000), updatedAt: intent.createdAt), for: id)
+ try store.writeCheckpoint(MeetingAudioChunkLedgerCheckpoint(
+ chunkID: id,
+ expectedFrames: 48_000,
+ writtenFrames: 24_000,
+ lastCanonicalPTS: MeetingMediaTime(value: 625, timescale: 1000),
+ updatedAt: intent.createdAt
+ ), for: id)
+ try store.writeCheckpoint(MeetingAudioChunkLedgerCheckpoint(
+ chunkID: id,
+ expectedFrames: 48_000,
+ writtenFrames: 48_000,
+ lastCanonicalPTS: MeetingMediaTime(value: 1125, timescale: 1000),
+ updatedAt: intent.createdAt
+ ), for: id)
try store.writeTerminal(MeetingAudioChunkLedgerTerminal(chunkID: id, status: .ready, updatedAt: intent.createdAt, detail: nil), for: id)
XCTAssertEqual(try store.readIntent(for: id), intent)
- XCTAssertEqual(try store.readCheckpoint(for: id)?.writtenFrames, 48000)
+ XCTAssertEqual(try store.readCheckpoint(for: id)?.writtenFrames, 48_000)
XCTAssertEqual(try store.readTerminal(for: id)?.status, .ready)
let intentURL = root.appendingPathComponent("chunk-ledger/\(id.uuidString).intent.json")
- let mode = (try FileManager.default.attributesOfItem(atPath: intentURL.path)[.posixPermissions] as? NSNumber)?.intValue
+ let mode = try (FileManager.default.attributesOfItem(atPath: intentURL.path)[.posixPermissions] as? NSNumber)?.intValue
XCTAssertEqual(mode, Int(0o600))
}
func testIntentIsImmutableAndUnknownTerminalStatusSurvivesDecode() throws {
let root = try self.makeDirectory(); let id = UUID(); let store = MeetingAudioChunkLedgerStore(sessionDirectory: root)
- let intent = MeetingAudioChunkLedgerIntent(chunkID: id, sequence: 1, canonicalStart: MeetingMediaTime(value: 0, timescale: 1), producerEpoch: 0,
- sourceFormat: MeetingAudioFormat(codec: "lpcm-f32", sampleRate: 16_000, channelCount: 1, bitRate: nil), partialRelativeFilePath: "x.partial.caf", createdAt: Date())
+ let intent = MeetingAudioChunkLedgerIntent(
+ chunkID: id,
+ sequence: 1,
+ canonicalStart: MeetingMediaTime(value: 0, timescale: 1),
+ producerEpoch: 0,
+ sourceFormat: MeetingAudioFormat(codec: "lpcm-f32", sampleRate: 16_000, channelCount: 1, bitRate: nil),
+ partialRelativeFilePath: "x.partial.caf",
+ createdAt: Date()
+ )
try store.writeIntent(intent)
XCTAssertNoThrow(try store.writeIntent(intent))
var changed = intent; changed.sequence = 2
@@ -47,7 +69,7 @@ final class MeetingAudioChunkLedgerTests: XCTestCase {
try store.writeIntent(MeetingAudioChunkLedgerIntent(
chunkID: id,
sequence: 0,
- canonicalStart: MeetingMediaTime(value: 0, timescale: 1_000),
+ canonicalStart: MeetingMediaTime(value: 0, timescale: 1000),
producerEpoch: 0,
sourceFormat: MeetingAudioFormat(codec: "lpcm-f32", sampleRate: 48_000, channelCount: 1, bitRate: nil),
partialRelativeFilePath: "tracks/microphone/0.partial.caf",
@@ -57,7 +79,7 @@ final class MeetingAudioChunkLedgerTests: XCTestCase {
chunkID: id,
expectedFrames: 48_000,
writtenFrames: 24_000,
- lastCanonicalPTS: MeetingMediaTime(value: 500, timescale: 1_000),
+ lastCanonicalPTS: MeetingMediaTime(value: 500, timescale: 1000),
updatedAt: now
), for: id)
XCTAssertThrowsError(try store.writeTerminal(
@@ -70,7 +92,7 @@ final class MeetingAudioChunkLedgerTests: XCTestCase {
chunkID: id,
expectedFrames: 23_000,
writtenFrames: 23_000,
- lastCanonicalPTS: MeetingMediaTime(value: 400, timescale: 1_000),
+ lastCanonicalPTS: MeetingMediaTime(value: 400, timescale: 1000),
updatedAt: now
), for: id)) {
XCTAssertEqual($0 as? MeetingAudioChunkLedgerError, .checkpointRegression)
diff --git a/Tests/FluidDictationIntegrationTests/MeetingAudioChunkSinkTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAudioChunkSinkTests.swift
index f4c81dbc..0a253b07 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingAudioChunkSinkTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingAudioChunkSinkTests.swift
@@ -1,16 +1,16 @@
-@testable import FluidVoice_Debug
import AVFoundation
import CoreMedia
import CryptoKit
import Darwin
+@testable import FluidVoice_Debug
import Foundation
import XCTest
private final class MeetingPCMFailureCounter: @unchecked Sendable {
private let lock = NSLock()
private var count = 0
- func increment() { lock.lock(); count += 1; lock.unlock() }
- func value() -> Int { lock.lock(); defer { lock.unlock() }; return count }
+ func increment() { self.lock.lock(); self.count += 1; self.lock.unlock() }
+ func value() -> Int { self.lock.lock(); defer { lock.unlock() }; return self.count }
}
/// P1a's sink fixtures intentionally use real ready CMSampleBuffers. These tests stay in the
@@ -31,8 +31,8 @@ final class MeetingAudioChunkSinkTests: XCTestCase {
XCTAssertEqual(copied.buffer.format.channelCount, 1)
XCTAssertEqual(copied.buffer.frameLength, 512)
XCTAssertEqual(copied.pts.seconds, 1.25, accuracy: 0.000_001)
- let copiedSamples = Array(UnsafeBufferPointer(
- start: try XCTUnwrap(copied.buffer.floatChannelData?[0]),
+ let copiedSamples = try Array(UnsafeBufferPointer(
+ start: XCTUnwrap(copied.buffer.floatChannelData?[0]),
count: Int(copied.buffer.frameLength)
))
XCTAssertTrue(copiedSamples.allSatisfy { abs($0 - 0.25) < 0.000_001 })
@@ -43,13 +43,19 @@ final class MeetingAudioChunkSinkTests: XCTestCase {
XCTAssertGreaterThan(mono.frameLength, 0)
let track = MeetingAudioTrack(
- id: UUID(), kind: .microphone, sourceIdentifier: "test", sourceDisplayName: "Test",
+ id: UUID(),
+ kind: .microphone,
+ sourceIdentifier: "test",
+ sourceDisplayName: "Test",
format: nil,
timebase: MeetingTimebaseMetadata(
- startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1,
+ startedHostTime: 0,
+ machTimebaseNumerator: 1,
+ machTimebaseDenominator: 1,
firstPresentationTime: nil
),
- health: .waiting, chunks: []
+ health: .waiting,
+ chunks: []
)
let failures = MeetingPCMFailureCounter()
let writer = try MeetingAudioChunkWriter(
@@ -70,10 +76,14 @@ final class MeetingAudioChunkSinkTests: XCTestCase {
let root = try self.makeDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let track = MeetingAudioTrack(
- id: UUID(), kind: .applicationAudio, sourceIdentifier: "test", sourceDisplayName: "Test",
+ id: UUID(),
+ kind: .applicationAudio,
+ sourceIdentifier: "test",
+ sourceDisplayName: "Test",
format: nil,
timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil),
- health: .waiting, chunks: []
+ health: .waiting,
+ chunks: []
)
let failures = MeetingPCMFailureCounter()
let writer = try MeetingAudioChunkWriter(track: track, sessionDirectory: root, chunkDuration: 60) { event in
@@ -81,34 +91,38 @@ final class MeetingAudioChunkSinkTests: XCTestCase {
}
let tags: [UInt32?] = [nil, kAudioChannelLayoutTag_Mono, nil, kAudioChannelLayoutTag_DiscreteInOrder | 1]
for (index, tag) in tags.enumerated() {
- writer.enqueue(try self.makeRawSampleBuffer(channelCount: 1, layoutTag: tag, frameCount: 480, pts: Double(index) * 0.01))
+ try writer.enqueue(self.makeRawSampleBuffer(channelCount: 1, layoutTag: tag, frameCount: 480, pts: Double(index) * 0.01))
}
let result = await writer.stop()
let chunk = try XCTUnwrap(result.chunks.first)
XCTAssertEqual(result.chunks.count, 1)
XCTAssertEqual(chunk.finalizationState, .finalized)
- XCTAssertEqual(chunk.captureAnalysisAsset?.frameCount, 1_920)
+ XCTAssertEqual(chunk.captureAnalysisAsset?.frameCount, 1920)
XCTAssertEqual(failures.value(), 0)
XCTAssertEqual(chunk.discontinuities, [])
let file = try AVAudioFile(forReading: root.appendingPathComponent(chunk.relativeFilePath), commonFormat: .pcmFormatFloat32, interleaved: true)
- XCTAssertEqual(file.length, 1_920)
+ XCTAssertEqual(file.length, 1920)
}
func testWriterRotatesExactlyOnceForGenuineMonoToStereoChange() async throws {
let root = try self.makeDirectory()
defer { try? FileManager.default.removeItem(at: root) }
let track = MeetingAudioTrack(
- id: UUID(), kind: .applicationAudio, sourceIdentifier: "test", sourceDisplayName: "Test",
+ id: UUID(),
+ kind: .applicationAudio,
+ sourceIdentifier: "test",
+ sourceDisplayName: "Test",
format: nil,
timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil),
- health: .waiting, chunks: []
+ health: .waiting,
+ chunks: []
)
let failures = MeetingPCMFailureCounter()
let writer = try MeetingAudioChunkWriter(track: track, sessionDirectory: root, chunkDuration: 60) { event in
if case .interrupted(.writerFailure, _, _) = event { failures.increment() }
}
- writer.enqueue(try self.makeRawSampleBuffer(channelCount: 1, layoutTag: nil, frameCount: 480, pts: 0))
- writer.enqueue(try self.makeRawSampleBuffer(channelCount: 2, layoutTag: kAudioChannelLayoutTag_Stereo, frameCount: 480, pts: 0.01))
+ try writer.enqueue(self.makeRawSampleBuffer(channelCount: 1, layoutTag: nil, frameCount: 480, pts: 0))
+ try writer.enqueue(self.makeRawSampleBuffer(channelCount: 2, layoutTag: kAudioChannelLayoutTag_Stereo, frameCount: 480, pts: 0.01))
let result = await writer.stop()
XCTAssertEqual(result.chunks.count, 2)
XCTAssertEqual(result.chunks.map { $0.captureAnalysisAsset?.frameCount }, [480, 480])
@@ -132,25 +146,31 @@ final class MeetingAudioChunkSinkTests: XCTestCase {
func testPCMFormatContractCanonicalizesEquivalentMonoAndStereoLayouts() throws {
let monoNil = try XCTUnwrap(AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 1, interleaved: true))
- let mono = try XCTUnwrap(AVAudioFormat(
- commonFormat: .pcmFormatFloat32, sampleRate: 48_000, interleaved: true,
- channelLayout: try XCTUnwrap(AVAudioChannelLayout(layoutTag: kAudioChannelLayoutTag_Mono))
+ let mono = try XCTUnwrap(try AVAudioFormat(
+ commonFormat: .pcmFormatFloat32,
+ sampleRate: 48_000,
+ interleaved: true,
+ channelLayout: XCTUnwrap(AVAudioChannelLayout(layoutTag: kAudioChannelLayoutTag_Mono))
))
- let discrete0 = try XCTUnwrap(AVAudioFormat(
- commonFormat: .pcmFormatFloat32, sampleRate: 48_000, interleaved: true,
- channelLayout: try XCTUnwrap(AVAudioChannelLayout(layoutTag: kAudioChannelLayoutTag_DiscreteInOrder | 1))
+ let discrete0 = try XCTUnwrap(try AVAudioFormat(
+ commonFormat: .pcmFormatFloat32,
+ sampleRate: 48_000,
+ interleaved: true,
+ channelLayout: XCTUnwrap(AVAudioChannelLayout(layoutTag: kAudioChannelLayoutTag_DiscreteInOrder | 1))
))
let stereoNil = try XCTUnwrap(AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 2, interleaved: true))
- let stereo = try XCTUnwrap(AVAudioFormat(
- commonFormat: .pcmFormatFloat32, sampleRate: 48_000, interleaved: true,
- channelLayout: try XCTUnwrap(AVAudioChannelLayout(layoutTag: kAudioChannelLayoutTag_Stereo))
+ let stereo = try XCTUnwrap(try AVAudioFormat(
+ commonFormat: .pcmFormatFloat32,
+ sampleRate: 48_000,
+ interleaved: true,
+ channelLayout: XCTUnwrap(AVAudioChannelLayout(layoutTag: kAudioChannelLayoutTag_Stereo))
))
XCTAssertEqual(try MeetingPCMFormatContract(audioFormat: monoNil), try MeetingPCMFormatContract(audioFormat: mono))
XCTAssertEqual(try MeetingPCMFormatContract(audioFormat: mono), try MeetingPCMFormatContract(audioFormat: discrete0))
XCTAssertEqual(try MeetingPCMFormatContract(audioFormat: stereoNil), try MeetingPCMFormatContract(audioFormat: stereo))
XCTAssertNotEqual(try MeetingPCMFormatContract(audioFormat: monoNil), try MeetingPCMFormatContract(audioFormat: stereoNil))
- XCTAssertThrowsError(try MeetingPCMFormatContract(audioFormat: try XCTUnwrap(AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 48_000, channels: 1, interleaved: true))))
+ XCTAssertThrowsError(try MeetingPCMFormatContract(audioFormat: XCTUnwrap(AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 48_000, channels: 1, interleaved: true))))
}
func testMonoAndStereoPreserveFramesPTSAndPublishCAF() async throws {
@@ -179,14 +199,16 @@ final class MeetingAudioChunkSinkTests: XCTestCase {
)
let readBuffer = try XCTUnwrap(AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: 17))
try file.read(into: readBuffer)
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let read = Array(UnsafeBufferPointer(start: readBuffer.audioBufferList.pointee.mBuffers.mData!.assumingMemoryBound(to: Float.self), count: samples.count))
XCTAssertEqual(read, samples)
- let digest = SHA256.hash(data: try Data(contentsOf: finalURL)).map { String(format: "%02x", $0) }.joined()
+ let digest = try SHA256.hash(data: Data(contentsOf: finalURL)).map { String(format: "%02x", $0) }.joined()
XCTAssertEqual(finalization.sha256, digest)
XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("tracks/application/000001.partial.caf").path))
- let mode = (try FileManager.default.attributesOfItem(atPath: finalURL.path)[.posixPermissions] as? NSNumber)?.intValue
+ let mode = try (FileManager.default.attributesOfItem(atPath: finalURL.path)[.posixPermissions] as? NSNumber)?.intValue
XCTAssertEqual(mode, Int(0o600))
- let parentMode = (try FileManager.default.attributesOfItem(atPath: finalURL.deletingLastPathComponent().path)[.posixPermissions] as? NSNumber)?.intValue
+ let parentMode = try (FileManager.default.attributesOfItem(atPath: finalURL.deletingLastPathComponent().path)[.posixPermissions] as? NSNumber)?.intValue
XCTAssertEqual(parentMode, Int(0o700))
}
}
@@ -271,6 +293,8 @@ final class MeetingAudioChunkSinkTests: XCTestCase {
let file = try AVAudioFile(forReading: root.appendingPathComponent("noninterleaved.caf"), commonFormat: .pcmFormatFloat32, interleaved: true)
let buffer = try XCTUnwrap(AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: 6))
try file.read(into: buffer)
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let values = Array(UnsafeBufferPointer(start: buffer.audioBufferList.pointee.mBuffers.mData!.assumingMemoryBound(to: Float.self), count: 12))
XCTAssertEqual(values, [0.1, 1.1, 0.2, 1.2, 0.3, 1.3, 0.4, 1.4, 0.5, 1.5, 0.6, 1.6])
}
@@ -335,46 +359,109 @@ final class MeetingAudioChunkSinkTests: XCTestCase {
private func makeRawSampleBuffer(channelCount: Int, layoutTag: UInt32?, frameCount: Int, pts: Double) throws -> CMSampleBuffer {
let bytesPerFrame = channelCount * MemoryLayout<Float>.size
var asbd = AudioStreamBasicDescription(
- mSampleRate: 48_000, mFormatID: kAudioFormatLinearPCM, mFormatFlags: kAudioFormatFlagsNativeFloatPacked,
- mBytesPerPacket: UInt32(bytesPerFrame), mFramesPerPacket: 1, mBytesPerFrame: UInt32(bytesPerFrame),
- mChannelsPerFrame: UInt32(channelCount), mBitsPerChannel: 32, mReserved: 0
+ mSampleRate: 48_000,
+ mFormatID: kAudioFormatLinearPCM,
+ mFormatFlags: kAudioFormatFlagsNativeFloatPacked,
+ mBytesPerPacket: UInt32(bytesPerFrame),
+ mFramesPerPacket: 1,
+ mBytesPerFrame: UInt32(bytesPerFrame),
+ mChannelsPerFrame: UInt32(channelCount),
+ mBitsPerChannel: 32,
+ mReserved: 0
)
var description: CMAudioFormatDescription?
let layout = layoutTag.flatMap { AVAudioChannelLayout(layoutTag: $0) }
let layoutStatus: OSStatus
if let layout, let layoutData = MeetingPCMFormatContract.layoutData(layout) {
layoutStatus = layoutData.withUnsafeBytes { bytes in
- CMAudioFormatDescriptionCreate(allocator: kCFAllocatorDefault, asbd: &asbd,
- layoutSize: layoutData.count, layout: bytes.baseAddress!.assumingMemoryBound(to: AudioChannelLayout.self),
- magicCookieSize: 0, magicCookie: nil, extensions: nil, formatDescriptionOut: &description)
+ CMAudioFormatDescriptionCreate(
+ allocator: kCFAllocatorDefault,
+ asbd: &asbd,
+ layoutSize: layoutData.count,
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ layout: bytes.baseAddress!.assumingMemoryBound(to: AudioChannelLayout.self),
+ magicCookieSize: 0,
+ magicCookie: nil,
+ extensions: nil,
+ formatDescriptionOut: &description
+ )
}
} else {
- layoutStatus = CMAudioFormatDescriptionCreate(allocator: kCFAllocatorDefault, asbd: &asbd,
- layoutSize: 0, layout: nil, magicCookieSize: 0, magicCookie: nil, extensions: nil, formatDescriptionOut: &description)
+ layoutStatus = CMAudioFormatDescriptionCreate(
+ allocator: kCFAllocatorDefault,
+ asbd: &asbd,
+ layoutSize: 0,
+ layout: nil,
+ magicCookieSize: 0,
+ magicCookie: nil,
+ extensions: nil,
+ formatDescriptionOut: &description
+ )
}
XCTAssertEqual(layoutStatus, noErr)
let values = Array(repeating: Float(0.25), count: frameCount * channelCount)
let bytes = values.withUnsafeBytes { Data($0) }
var block: CMBlockBuffer?
- XCTAssertEqual(CMBlockBufferCreateWithMemoryBlock(allocator: kCFAllocatorDefault, memoryBlock: nil,
- blockLength: bytes.count, blockAllocator: kCFAllocatorDefault, customBlockSource: nil, offsetToData: 0,
- dataLength: bytes.count, flags: kCMBlockBufferAssureMemoryNowFlag, blockBufferOut: &block), noErr)
+ XCTAssertEqual(CMBlockBufferCreateWithMemoryBlock(
+ allocator: kCFAllocatorDefault,
+ memoryBlock: nil,
+ blockLength: bytes.count,
+ blockAllocator: kCFAllocatorDefault,
+ customBlockSource: nil,
+ offsetToData: 0,
+ dataLength: bytes.count,
+ flags: kCMBlockBufferAssureMemoryNowFlag,
+ blockBufferOut: &block
+ ), noErr)
let blockBuffer = try XCTUnwrap(block)
- XCTAssertEqual(bytes.withUnsafeBytes { CMBlockBufferReplaceDataBytes(with: $0.baseAddress!, blockBuffer: blockBuffer, offsetIntoDestination: 0, dataLength: bytes.count) }, noErr)
- var timing = CMSampleTimingInfo(duration: CMTime(value: 1, timescale: 48_000), presentationTimeStamp: CMTime(seconds: pts, preferredTimescale: 48_000), decodeTimeStamp: .invalid)
+ XCTAssertEqual(
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ bytes.withUnsafeBytes { CMBlockBufferReplaceDataBytes(with: $0.baseAddress!, blockBuffer: blockBuffer, offsetIntoDestination: 0, dataLength: bytes.count) },
+ noErr
+ )
+ var timing = CMSampleTimingInfo(
+ duration: CMTime(value: 1, timescale: 48_000),
+ presentationTimeStamp: CMTime(seconds: pts, preferredTimescale: 48_000),
+ decodeTimeStamp: .invalid
+ )
var sample: CMSampleBuffer?
- XCTAssertEqual(CMSampleBufferCreateReady(allocator: kCFAllocatorDefault, dataBuffer: blockBuffer, formatDescription: try XCTUnwrap(description), sampleCount: frameCount, sampleTimingEntryCount: 1, sampleTimingArray: &timing, sampleSizeEntryCount: 0, sampleSizeArray: nil, sampleBufferOut: &sample), noErr)
+ XCTAssertEqual(
+ try CMSampleBufferCreateReady(
+ allocator: kCFAllocatorDefault,
+ dataBuffer: blockBuffer,
+ formatDescription: XCTUnwrap(description),
+ sampleCount: frameCount,
+ sampleTimingEntryCount: 1,
+ sampleTimingArray: &timing,
+ sampleSizeEntryCount: 0,
+ sampleSizeArray: nil,
+ sampleBufferOut: &sample
+ ),
+ noErr
+ )
return try XCTUnwrap(sample)
}
private func makeSampleBuffer(format: AVAudioFormat, interleavedSamples: [Float], frameCount: Int, pts: Double) throws -> CMSampleBuffer {
let bytes = interleavedSamples.withUnsafeBytes { Data($0) }
var block: CMBlockBuffer?
- var status = CMBlockBufferCreateWithMemoryBlock(allocator: kCFAllocatorDefault, memoryBlock: nil, blockLength: bytes.count,
- blockAllocator: kCFAllocatorDefault, customBlockSource: nil, offsetToData: 0,
- dataLength: bytes.count, flags: 0, blockBufferOut: &block)
+ var status = CMBlockBufferCreateWithMemoryBlock(
+ allocator: kCFAllocatorDefault,
+ memoryBlock: nil,
+ blockLength: bytes.count,
+ blockAllocator: kCFAllocatorDefault,
+ customBlockSource: nil,
+ offsetToData: 0,
+ dataLength: bytes.count,
+ flags: 0,
+ blockBufferOut: &block
+ )
guard status == noErr, let block else { throw NSError(domain: "P1a", code: Int(status)) }
status = bytes.withUnsafeBytes { ptr in
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
CMBlockBufferReplaceDataBytes(with: ptr.baseAddress!, blockBuffer: block, offsetIntoDestination: 0, dataLength: bytes.count)
}
guard status == noErr else { throw NSError(domain: "P1a", code: Int(status)) }
@@ -387,9 +474,17 @@ final class MeetingAudioChunkSinkTests: XCTestCase {
decodeTimeStamp: .invalid
)
var sampleBuffer: CMSampleBuffer?
- status = CMSampleBufferCreateReady(allocator: kCFAllocatorDefault, dataBuffer: block, formatDescription: format.formatDescription, sampleCount: frameCount,
- sampleTimingEntryCount: 1, sampleTimingArray: &timing, sampleSizeEntryCount: 0, sampleSizeArray: nil,
- sampleBufferOut: &sampleBuffer)
+ status = CMSampleBufferCreateReady(
+ allocator: kCFAllocatorDefault,
+ dataBuffer: block,
+ formatDescription: format.formatDescription,
+ sampleCount: frameCount,
+ sampleTimingEntryCount: 1,
+ sampleTimingArray: &timing,
+ sampleSizeEntryCount: 0,
+ sampleSizeArray: nil,
+ sampleBufferOut: &sampleBuffer
+ )
guard status == noErr, let sampleBuffer else { throw NSError(domain: "P1a", code: Int(status)) }
return sampleBuffer
}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift b/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift
index 0aee1363..cdd91866 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingAutoDetectorTests.swift
@@ -194,7 +194,7 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertNil(h.detector.automaticTarget)
}
- // MARK: Generic HAL ownership resolver
+ // MARK: - Generic HAL ownership resolver
func testAudioResolverMapsHelpersInsideEachRegisteredNativeBundle() {
let apps = [
@@ -206,32 +206,58 @@ final class MeetingAutoDetectorTests: XCTestCase {
]
for (bundle, root) in apps {
let result = MeetingAudioProcessResolver.activeOwnerInputByPID(snapshot: .init(
- processes: [.init(processID: 900, bundleIdentifier: "helper.unknown", executablePath: root + "/Contents/Helpers/Module.app/Contents/MacOS/Module", isInputRunning: true, isOutputRunning: false)],
- owners: [.init(processID: 42, bundleIdentifier: bundle, bundlePath: root)], queryState: .valid
+ processes: [.init(
+ processID: 900,
+ bundleIdentifier: "helper.unknown",
+ executablePath: root + "/Contents/Helpers/Module.app/Contents/MacOS/Module",
+ isInputRunning: true,
+ isOutputRunning: false
+ )],
+ owners: [.init(processID: 42, bundleIdentifier: bundle, bundlePath: root)],
+ queryState: .valid
))
XCTAssertEqual(result?[42], true, "helper attribution should work for \(bundle)")
}
}
func testAudioResolverRejectsPrefixSpoofRelativeMissingAndAmbiguousOwners() {
+ // nil requests the fixture default; an empty collection tests explicitly missing data.
+ // swiftlint:disable:next discouraged_optional_collection
func resolve(_ processPath: String?, owners: [MeetingProcessOwner]) -> [Int32: Bool]? {
MeetingAudioProcessResolver.activeOwnerInputByPID(snapshot: .init(
processes: [.init(processID: 1, bundleIdentifier: nil, executablePath: processPath, isInputRunning: true, isOutputRunning: false)],
- owners: owners, queryState: .valid
+ owners: owners,
+ queryState: .valid
))
}
let owner = MeetingProcessOwner(processID: 10, bundleIdentifier: "com.microsoft.teams2", bundlePath: "/Applications/Teams.app")
XCTAssertEqual(resolve("/Applications/Teams.app.evil/Contents/MacOS/x", owners: [owner]), [:])
XCTAssertNil(resolve(nil, owners: [owner]))
XCTAssertNil(resolve("Applications/Teams.app/Contents/MacOS/x", owners: [owner]))
- XCTAssertNil(resolve("/Applications/Teams.app/Contents/MacOS/x", owners: [owner, .init(processID: 11, bundleIdentifier: "com.microsoft.teams2", bundlePath: "/Applications/Teams.app")]))
- XCTAssertEqual(resolve("/Applications/Teams.app/Contents/MacOS/x", owners: [.init(processID: 10, bundleIdentifier: "com.google.Chrome", bundlePath: "/Applications/Teams.app")]), [:], "browser owners must never become native audio owners")
- XCTAssertEqual(resolve("/Applications/Teams.app/Contents/MacOS/x", owners: [.init(processID: 10, bundleIdentifier: "com.microsoft.teams2", bundlePath: "relative/Teams.app")]), [:])
+ XCTAssertNil(resolve(
+ "/Applications/Teams.app/Contents/MacOS/x",
+ owners: [owner, .init(processID: 11, bundleIdentifier: "com.microsoft.teams2", bundlePath: "/Applications/Teams.app")]
+ ))
+ XCTAssertEqual(
+ resolve("/Applications/Teams.app/Contents/MacOS/x", owners: [.init(processID: 10, bundleIdentifier: "com.google.Chrome", bundlePath: "/Applications/Teams.app")]),
+ [:],
+ "browser owners must never become native audio owners"
+ )
+ XCTAssertEqual(
+ resolve("/Applications/Teams.app/Contents/MacOS/x", owners: [.init(processID: 10, bundleIdentifier: "com.microsoft.teams2", bundlePath: "relative/Teams.app")]),
+ [:]
+ )
}
func testAudioResolverRejectsBrowserOwnerAndUnknownQuery() {
let browser = MeetingProcessOwner(processID: 3, bundleIdentifier: "com.google.Chrome", bundlePath: "/Applications/Chrome.app")
- let process = AudioProcessDescriptor(processID: 4, bundleIdentifier: nil, executablePath: "/Applications/Chrome.app/Contents/MacOS/Chrome", isInputRunning: true, isOutputRunning: true)
+ let process = AudioProcessDescriptor(
+ processID: 4,
+ bundleIdentifier: nil,
+ executablePath: "/Applications/Chrome.app/Contents/MacOS/Chrome",
+ isInputRunning: true,
+ isOutputRunning: true
+ )
XCTAssertNil(MeetingAudioProcessResolver.activeOwnerInputByPID(snapshot: .init(processes: [process], owners: [browser], queryState: .unknown)))
}
@@ -247,7 +273,8 @@ final class MeetingAutoDetectorTests: XCTestCase {
defer { try? FileManager.default.removeItem(at: root) }
let result = MeetingAudioProcessResolver.activeOwnerInputByPID(snapshot: .init(
processes: [.init(processID: 1, bundleIdentifier: nil, executablePath: link.path + "/Module", isInputRunning: true, isOutputRunning: false)],
- owners: [.init(processID: 2, bundleIdentifier: "com.microsoft.teams2", bundlePath: app.path)], queryState: .valid
+ owners: [.init(processID: 2, bundleIdentifier: "com.microsoft.teams2", bundlePath: app.path)],
+ queryState: .valid
))
XCTAssertEqual(result, [:])
}
@@ -257,8 +284,15 @@ final class MeetingAutoDetectorTests: XCTestCase {
h.detector.handleWorkspaceEvent(.init(kind: .activated, bundleIdentifier: "com.microsoft.teams2", processID: 5), at: h.clock.now())
h.detector.handleWindowSnapshot([.init(processID: 5, windowID: 9, title: nil, layer: 0)], at: h.clock.now())
h.audioProcessActivity.snapshotOverride = .init(
- processes: [.init(processID: 55, bundleIdentifier: "teams.helper", executablePath: "/Applications/com.microsoft.teams2.app/Contents/Helpers/Module", isInputRunning: false, isOutputRunning: true)],
- owners: [.init(processID: 5, bundleIdentifier: "com.microsoft.teams2", bundlePath: "/Applications/com.microsoft.teams2.app")], queryState: .valid
+ processes: [.init(
+ processID: 55,
+ bundleIdentifier: "teams.helper",
+ executablePath: "/Applications/com.microsoft.teams2.app/Contents/Helpers/Module",
+ isInputRunning: false,
+ isOutputRunning: true
+ )],
+ owners: [.init(processID: 5, bundleIdentifier: "com.microsoft.teams2", bundlePath: "/Applications/com.microsoft.teams2.app")],
+ queryState: .valid
)
await h.detector.pollAudioProcessActivity(at: h.clock.now())
XCTAssertTrue(h.prompts.isEmpty)
@@ -277,8 +311,15 @@ final class MeetingAutoDetectorTests: XCTestCase {
let h = DetectorHarness()
h.detector.handleWorkspaceEvent(.init(kind: .launched, bundleIdentifier: "com.microsoft.teams2", processID: 5), at: h.clock.now())
h.audioProcessActivity.snapshotOverride = .init(
- processes: [.init(processID: 55, bundleIdentifier: "teams.helper", executablePath: "/Applications/Teams.app/Contents/Helpers/Module", isInputRunning: true, isOutputRunning: true)],
- owners: [.init(processID: 5, bundleIdentifier: "com.microsoft.teams2", bundlePath: "/Applications/Teams.app")], queryState: .valid
+ processes: [.init(
+ processID: 55,
+ bundleIdentifier: "teams.helper",
+ executablePath: "/Applications/Teams.app/Contents/Helpers/Module",
+ isInputRunning: true,
+ isOutputRunning: true
+ )],
+ owners: [.init(processID: 5, bundleIdentifier: "com.microsoft.teams2", bundlePath: "/Applications/Teams.app")],
+ queryState: .valid
)
h.audioProcessActivity.beforeSnapshot = {
h.detector.handleWorkspaceEvent(.init(kind: .terminated, bundleIdentifier: "com.microsoft.teams2", processID: 5), at: h.clock.now())
@@ -376,7 +417,7 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertEqual(h.prompts.count, 1)
}
- // MARK: Prompt suppression
+ // MARK: - Prompt suppression
func testPromptSuppressionAllowsDetectedMeetingAppFullScreen() {
let reason = MeetingDetectionPromptController.suppressionReason(
@@ -595,7 +636,7 @@ final class MeetingAutoDetectorTests: XCTestCase {
)
}
- // MARK: Coincidence window
+ // MARK: - Coincidence window
func testParkedTabWithLateMicNeverPrompts() {
let h = DetectorHarness()
@@ -609,7 +650,7 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertTrue(h.prompts.isEmpty, "evidence older than the 30s coincidence window must not confirm")
}
- // MARK: Fail-closed on unreadable AXURL
+ // MARK: - Fail-closed on unreadable AXURL
func testUnreadableAXURLNeverPrompts() {
let h = DetectorHarness()
@@ -619,14 +660,14 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertTrue(h.prompts.isEmpty)
}
- // MARK: YouTube-hostname never matches
+ // MARK: - YouTube-hostname never matches
func testYouTubeNeverMatchesInCallURL() {
XCTAssertFalse(MeetingInCallURLMatcher.isInCallURL(host: "www.youtube.com", path: "/watch"))
XCTAssertFalse(MeetingInCallURLMatcher.isInCallURL(host: "youtube.com", path: "/live/abc-defg-hij"))
}
- // MARK: Tier-1 frontmost-at-edge gate
+ // MARK: - Tier-1 frontmost-at-edge gate
func testZoomConfirmsOnlyWhenFrontmostNearTheMicEdge() {
let h = DetectorHarness()
@@ -694,7 +735,7 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertTrue(windowOnly.prompts.isEmpty)
}
- // MARK: Backfill arms only
+ // MARK: - Backfill arms only
func testBackfillAlonesNeverConfirms() {
let h = DetectorHarness()
@@ -740,7 +781,7 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertTrue(h.prompts.isEmpty, "native apps keep the activation rule; their windows persist all day")
}
- // MARK: Episode dedup + back-to-back re-arm
+ // MARK: - Episode dedup + back-to-back re-arm
func testDuplicateConfirmDoesNotReprompt() {
let h = DetectorHarness()
@@ -750,11 +791,11 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertEqual(h.prompts.count, 1, "the same window key must not re-arm while still live")
}
- func testBackToBackMeetingAfterReleaseRearmsTheSameWindow() {
+ func testBackToBackMeetingAfterReleaseRearmsTheSameWindow() throws {
let h = DetectorHarness()
let firstEpisode = h.confirmZoom()
XCTAssertNotNil(firstEpisode)
- h.detector.timeoutDismissed(episodeID: firstEpisode!)
+ h.detector.timeoutDismissed(episodeID: try XCTUnwrap(firstEpisode))
// Window disappears; after grace + the 60s release window the episode is evicted.
h.detector.handleWindowSnapshot([], at: h.clock.now())
@@ -814,11 +855,11 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertEqual(h.prompts.count, 2)
}
- // MARK: Stop mid-call, no re-prompt
+ // MARK: - Stop mid-call, no re-prompt
- func testStoppingOurRecordingMidCallDoesNotReprompt() {
+ func testStoppingOurRecordingMidCallDoesNotReprompt() throws {
let h = DetectorHarness()
- let episodeID = h.confirmZoom()!
+ let episodeID = try XCTUnwrap(h.confirmZoom())
XCTAssertTrue(h.detector.startTapped(episodeID: episodeID))
// The window is still there (the user is still in the call) — no eviction, no re-prompt.
@@ -832,34 +873,34 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertEqual(h.prompts.count, 1, "stopping our own recording must not retire a still-live episode")
}
- // MARK: Manual start consumes the episode
+ // MARK: - Manual start consumes the episode
- func testStartTappedIsSingleShot() {
+ func testStartTappedIsSingleShot() throws {
let h = DetectorHarness()
- let episodeID = h.confirmZoom()!
+ let episodeID = try XCTUnwrap(h.confirmZoom())
XCTAssertTrue(h.detector.startTapped(episodeID: episodeID))
XCTAssertFalse(h.detector.startTapped(episodeID: episodeID), "a second Start on the same episode must be a no-op")
}
- func testStartTappedFailsWhenPreflightNoLongerPasses() {
+ func testStartTappedFailsWhenPreflightNoLongerPasses() throws {
let h = DetectorHarness()
- let episodeID = h.confirmZoom()!
+ let episodeID = try XCTUnwrap(h.confirmZoom())
h.gate.preflightResult = false
XCTAssertFalse(h.detector.startTapped(episodeID: episodeID))
}
- func testCanStartDoesNotConsumeEpisode() {
+ func testCanStartDoesNotConsumeEpisode() throws {
let h = DetectorHarness()
- let episodeID = h.confirmZoom()!
+ let episodeID = try XCTUnwrap(h.confirmZoom())
XCTAssertTrue(h.detector.canStart(episodeID: episodeID))
XCTAssertTrue(h.detector.canStart(episodeID: episodeID), "canStart must not consume")
XCTAssertTrue(h.detector.startTapped(episodeID: episodeID))
XCTAssertFalse(h.detector.canStart(episodeID: episodeID))
}
- func testAdoptStartedEpisodeSkipsPreflightAndStartTappedStaysSingleShot() {
+ func testAdoptStartedEpisodeSkipsPreflightAndStartTappedStaysSingleShot() throws {
let h = DetectorHarness()
- let episodeID = h.confirmZoom()!
+ let episodeID = try XCTUnwrap(h.confirmZoom())
h.gate.preflightResult = false
XCTAssertFalse(h.detector.startTapped(episodeID: episodeID))
h.detector.adoptStartedEpisode(episodeID: episodeID)
@@ -868,18 +909,18 @@ final class MeetingAutoDetectorTests: XCTestCase {
h.detector.adoptStartedEpisode(episodeID: episodeID)
}
- func testAdoptStartedEpisodeAfterTimeoutOwnsTheEpisodeAndResetsDismissals() {
+ func testAdoptStartedEpisodeAfterTimeoutOwnsTheEpisodeAndResetsDismissals() throws {
let h = DetectorHarness()
var suggested = false
h.detector.onSuggestDisablingAutoDetect = { suggested = true }
for pid: Int32 in [1, 2] {
- let episodeID = h.confirmZoom(pid: pid)!
+ let episodeID = try XCTUnwrap(h.confirmZoom(pid: pid))
h.detector.dismissTapped(episodeID: episodeID, at: h.clock.now())
h.advance(3600)
}
- let timedOut = h.confirmZoom(pid: 3)!
+ let timedOut = try XCTUnwrap(h.confirmZoom(pid: 3))
h.detector.timeoutDismissed(episodeID: timedOut)
XCTAssertFalse(h.detector.startTapped(episodeID: timedOut))
XCTAssertFalse(h.detector.canStart(episodeID: timedOut))
@@ -890,12 +931,12 @@ final class MeetingAutoDetectorTests: XCTestCase {
h.detector.tick(at: h.clock.now())
XCTAssertEqual(h.nudges, 1, "adopting after timeout must still arm the still-recording nudge")
- let dismissedEpisode = h.confirmZoom(pid: 4)!
+ let dismissedEpisode = try XCTUnwrap(h.confirmZoom(pid: 4))
h.detector.dismissTapped(episodeID: dismissedEpisode, at: h.clock.now())
XCTAssertFalse(suggested, "adopting after timeout must still reset the rolling counter")
}
- // MARK: Preflight gate silence
+ // MARK: - Preflight gate silence
func testMissingScreenRecordingAtConfirmRequestsSetup() {
let h = DetectorHarness()
@@ -981,11 +1022,11 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertEqual(h.prompts.first?.cta, .record)
}
- // MARK: Dismissal suppression + rolling counter
+ // MARK: - Dismissal suppression + rolling counter
- func testExplicitDismissSuppressesTheBundleForThirtyMinutes() {
+ func testExplicitDismissSuppressesTheBundleForThirtyMinutes() throws {
let h = DetectorHarness()
- let firstEpisode = h.confirmZoom(pid: 1)!
+ let firstEpisode = try XCTUnwrap(h.confirmZoom(pid: 1))
h.detector.dismissTapped(episodeID: firstEpisode, at: h.clock.now())
h.detector.handleWindowSnapshot([], at: h.clock.now()) // window loss + eviction so the same window can re-arm
@@ -1001,9 +1042,9 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertEqual(h.prompts.count, 1, "the bundle stays suppressed for 30 minutes after an explicit dismiss")
}
- func testTimeoutDismissDoesNotSuppressOrCount() {
+ func testTimeoutDismissDoesNotSuppressOrCount() throws {
let h = DetectorHarness()
- let episodeID = h.confirmZoom()!
+ let episodeID = try XCTUnwrap(h.confirmZoom())
h.detector.timeoutDismissed(episodeID: episodeID)
h.detector.handleWindowSnapshot([], at: h.clock.now())
@@ -1019,38 +1060,38 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertEqual(h.prompts.count, 2, "a 20s auto-dismiss must not suppress the bundle")
}
- func testThreeDismissalsWithinFourteenDaysSuggestsDisabling() {
+ func testThreeDismissalsWithinFourteenDaysSuggestsDisabling() throws {
let h = DetectorHarness()
var suggested = false
h.detector.onSuggestDisablingAutoDetect = { suggested = true }
for pid: Int32 in [1, 2, 3] {
- let episodeID = h.confirmZoom(pid: pid)!
+ let episodeID = try XCTUnwrap(h.confirmZoom(pid: pid))
h.detector.dismissTapped(episodeID: episodeID, at: h.clock.now())
h.advance(3600)
}
XCTAssertTrue(suggested)
}
- func testAcceptedStartResetsTheDismissalCounter() {
+ func testAcceptedStartResetsTheDismissalCounter() throws {
let h = DetectorHarness()
var suggested = false
h.detector.onSuggestDisablingAutoDetect = { suggested = true }
for pid: Int32 in [1, 2] {
- let episodeID = h.confirmZoom(pid: pid)!
+ let episodeID = try XCTUnwrap(h.confirmZoom(pid: pid))
h.detector.dismissTapped(episodeID: episodeID, at: h.clock.now())
h.advance(3600)
}
- let acceptedEpisode = h.confirmZoom(pid: 3)!
+ let acceptedEpisode = try XCTUnwrap(h.confirmZoom(pid: 3))
XCTAssertTrue(h.detector.startTapped(episodeID: acceptedEpisode))
- let dismissedEpisode = h.confirmZoom(pid: 4)!
+ let dismissedEpisode = try XCTUnwrap(h.confirmZoom(pid: 4))
h.detector.dismissTapped(episodeID: dismissedEpisode, at: h.clock.now())
XCTAssertFalse(suggested, "an accepted Start must reset the rolling counter")
}
- // MARK: Lock / sleep disarm
+ // MARK: - Lock / sleep disarm
func testDisarmClearsAllTransientState() {
let h = DetectorHarness()
@@ -1064,10 +1105,10 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertTrue(h.prompts.isEmpty, "disarm must drop frontmost/window evidence so a later edge cannot confirm")
}
- func testEvictingUnconsumedEpisodeInvalidatesAndConsumedDoesNot() {
+ func testEvictingUnconsumedEpisodeInvalidatesAndConsumedDoesNot() throws {
let h = DetectorHarness()
- let unconsumed = h.confirmZoom(pid: 1)!
- let consumed = h.confirmZoom(pid: 2)!
+ let unconsumed = try XCTUnwrap(h.confirmZoom(pid: 1))
+ let consumed = try XCTUnwrap(h.confirmZoom(pid: 2))
XCTAssertTrue(h.detector.startTapped(episodeID: consumed))
h.detector.handleWindowSnapshot([], at: h.clock.now())
@@ -1076,21 +1117,21 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertEqual(h.invalidated, [unconsumed])
}
- func testDisarmInvalidatesUnconsumedEpisodesOnly() {
+ func testDisarmInvalidatesUnconsumedEpisodesOnly() throws {
let h = DetectorHarness()
- let unconsumed = h.confirmZoom(pid: 1)!
- let consumed = h.confirmZoom(pid: 2)!
+ let unconsumed = try XCTUnwrap(h.confirmZoom(pid: 1))
+ let consumed = try XCTUnwrap(h.confirmZoom(pid: 2))
XCTAssertTrue(h.detector.startTapped(episodeID: consumed))
h.detector.disarmAndClearTransientState()
XCTAssertEqual(h.invalidated, [unconsumed])
}
- // MARK: Still-recording nudge
+ // MARK: - Still-recording nudge
- func testStillRecordingNudgeFiresOnceAfterWindowGoneSixtySeconds() {
+ func testStillRecordingNudgeFiresOnceAfterWindowGoneSixtySeconds() throws {
let h = DetectorHarness()
- let episodeID = h.confirmZoom()!
+ let episodeID = try XCTUnwrap(h.confirmZoom())
XCTAssertTrue(h.detector.startTapped(episodeID: episodeID))
h.detector.handleWindowSnapshot([], at: h.clock.now())
@@ -1102,7 +1143,7 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertEqual(h.nudges, 1, "the nudge fires once per session")
}
- // MARK: Registry / URL matcher sanity
+ // MARK: - Registry / URL matcher sanity
func testRegistryTierLookup() {
XCTAssertEqual(MeetingAppRegistry.tier(forBundleIdentifier: "us.zoom.xos"), .nativeTier1)
@@ -1123,7 +1164,7 @@ final class MeetingAutoDetectorTests: XCTestCase {
XCTAssertTrue(MeetingInCallURLMatcher.isInCallURL(host: "meet.jit.si", path: "/SomeRoomName"))
}
- // MARK: windowID preference in MeetingWindowSelector
+ // MARK: - windowID preference in MeetingWindowSelector
func testWindowSelectorPrefersPreferredWindowIDWhenEligible() {
let candidates = [
diff --git a/Tests/FluidDictationIntegrationTests/MeetingEchoSignalScorerTests.swift b/Tests/FluidDictationIntegrationTests/MeetingEchoSignalScorerTests.swift
index d4541655..44df30cd 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingEchoSignalScorerTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingEchoSignalScorerTests.swift
@@ -3,7 +3,7 @@ import Foundation
import XCTest
final class MeetingEchoSignalScorerTests: XCTestCase {
- private let sampleRate = 16000.0
+ private let sampleRate = 16_000.0
private var hopSeconds: Double { Double(MeetingEchoSignalScorer.hopLength) / self.sampleRate }
/// Tight enough to catch the sidelobe/wrong-sign regressions; the fixed estimator errs by 0 samples.
private var delayAccuracySeconds: Double { 2.0 / self.sampleRate }
@@ -11,7 +11,7 @@ final class MeetingEchoSignalScorerTests: XCTestCase {
func testEstimateDelayRecoversPositiveLag() throws {
let delaySamples = 400
var lcg = LCG(seed: 1)
- let reference = self.bandLimitedNoise(count: 12000, generator: &lcg)
+ let reference = self.bandLimitedNoise(count: 12_000, generator: &lcg)
var noiseLCG = LCG(seed: 2)
let mic = self.delayedAndScaled(reference, bySamples: delaySamples, scale: 0.5, noiseAmplitude: 0.01, generator: &noiseLCG)
@@ -26,7 +26,7 @@ final class MeetingEchoSignalScorerTests: XCTestCase {
func testEstimateDelayRecoversNegativeLag() throws {
let delaySamples = -350
var lcg = LCG(seed: 3)
- let reference = self.bandLimitedNoise(count: 12000, generator: &lcg)
+ let reference = self.bandLimitedNoise(count: 12_000, generator: &lcg)
var noiseLCG = LCG(seed: 4)
let mic = self.delayedAndScaled(reference, bySamples: delaySamples, scale: 0.6, noiseAmplitude: 0.01, generator: &noiseLCG)
@@ -42,7 +42,7 @@ final class MeetingEchoSignalScorerTests: XCTestCase {
// Inverted polarity puts the true peak negative; signed argmax used to pick a sidelobe.
let delaySamples = 400
var lcg = LCG(seed: 60)
- let reference = self.bandLimitedNoise(count: 12000, generator: &lcg)
+ let reference = self.bandLimitedNoise(count: 12_000, generator: &lcg)
var noiseLCG = LCG(seed: 61)
let mic = self.delayedAndScaled(reference, bySamples: delaySamples, scale: -0.5, noiseAmplitude: 0.01, generator: &noiseLCG)
@@ -71,7 +71,7 @@ final class MeetingEchoSignalScorerTests: XCTestCase {
func testEstimateDelayHandlesMismatchedLengths() throws {
let delaySamples = 200
var lcg = LCG(seed: 62)
- let reference = self.bandLimitedNoise(count: 12000, generator: &lcg)
+ let reference = self.bandLimitedNoise(count: 12_000, generator: &lcg)
var noiseLCG = LCG(seed: 63)
let fullMic = self.delayedAndScaled(reference, bySamples: delaySamples, scale: 0.5, noiseAmplitude: 0.01, generator: &noiseLCG)
let mic = Array(fullMic.prefix(9000))
@@ -338,18 +338,21 @@ final class MeetingEchoSignalScorerTests: XCTestCase {
private struct LCG {
private var state: UInt64
- init(seed: UInt64) { self.state = seed &+ 0x9E3779B97F4A7C15 }
+ init(seed: UInt64) { self.state = seed &+ 0x9e3779b97f4a7c15 }
mutating func nextUnit() -> Float {
- self.state = self.state &* 6364136223846793005 &+ 1442695040888963407
+ self.state = self.state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407
return Float(Double(self.state >> 11) / Double(1 << 53))
}
+
mutating func nextSigned() -> Float { self.nextUnit() * 2 - 1 }
}
/// Cheap 3-tap moving-average smoothing gives GCC-PHAT a less impulsive, more speech-like spectrum.
private func bandLimitedNoise(count: Int, generator: inout LCG) -> [Float] {
var white = [Float](repeating: 0, count: count)
- for i in 0..<count { white[i] = generator.nextSigned() }
+ for i in 0..<count {
+ white[i] = generator.nextSigned()
+ }
var smoothed = [Float](repeating: 0, count: count)
for i in 0..<count {
let a = white[i]
diff --git a/Tests/FluidDictationIntegrationTests/MeetingEchoVetoTests.swift b/Tests/FluidDictationIntegrationTests/MeetingEchoVetoTests.swift
index b21da701..34f90d09 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingEchoVetoTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingEchoVetoTests.swift
@@ -1,5 +1,5 @@
-@testable import FluidVoice_Debug
import AVFoundation
+@testable import FluidVoice_Debug
import Foundation
import XCTest
@@ -28,6 +28,8 @@ final class MeetingEchoVetoTests: XCTestCase {
}
buffer.frameLength = buffer.frameCapacity
samples.withUnsafeBufferPointer { ptr in
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
buffer.floatChannelData![0].update(from: ptr.baseAddress!, count: samples.count)
}
try file.write(from: buffer)
@@ -70,18 +72,21 @@ final class MeetingEchoVetoTests: XCTestCase {
private struct LCG {
private var state: UInt64
- init(seed: UInt64) { self.state = seed &+ 0x9E3779B97F4A7C15 }
+ init(seed: UInt64) { self.state = seed &+ 0x9e3779b97f4a7c15 }
mutating func nextUnit() -> Float {
- self.state = self.state &* 6364136223846793005 &+ 1442695040888963407
+ self.state = self.state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407
return Float(Double(self.state >> 11) / Double(1 << 53))
}
+
mutating func nextSigned() -> Float { self.nextUnit() * 2 - 1 }
}
private func bandLimitedNoise(count: Int, seed: UInt64) -> [Float] {
var generator = LCG(seed: seed)
var white = [Float](repeating: 0, count: count)
- for i in 0..<count { white[i] = generator.nextSigned() }
+ for i in 0..<count {
+ white[i] = generator.nextSigned()
+ }
var smoothed = [Float](repeating: 0, count: count)
for i in 0..<count {
let a = white[i]
@@ -94,7 +99,7 @@ final class MeetingEchoVetoTests: XCTestCase {
// MARK: - 1. Reference gathering: straddling two app chunks
- func testReferenceSpansStraddlingTwoAppChunksReturnsBothWithOffsets() {
+ func testReferenceSpansStraddlingTwoAppChunksReturnsBothWithOffsets() throws {
let appChunkA = self.makeChunk(sequence: 0, relativeFilePath: "a.caf", presentationStart: 0, presentationEnd: 10)
let appChunkB = self.makeChunk(sequence: 1, relativeFilePath: "b.caf", presentationStart: 10, presentationEnd: 20)
// Mic chunk [8, 14) straddles the app boundary at 10.
@@ -104,11 +109,11 @@ final class MeetingEchoVetoTests: XCTestCase {
origin: 0
)
XCTAssertEqual(spans.count, 2)
- let first = try! XCTUnwrap(spans.first { $0.chunk.id == appChunkA.id })
+ let first = try XCTUnwrap(spans.first { $0.chunk.id == appChunkA.id })
XCTAssertEqual(first.localRange, 8.0..<10.0, "local coordinates are relative to appChunkA's own start")
XCTAssertEqual(first.outputOffset, 0, accuracy: 1e-9)
- let second = try! XCTUnwrap(spans.first { $0.chunk.id == appChunkB.id })
+ let second = try XCTUnwrap(spans.first { $0.chunk.id == appChunkB.id })
XCTAssertEqual(second.localRange, 0.0..<4.0, "local coordinates are relative to appChunkB's own start")
XCTAssertEqual(second.outputOffset, 2, accuracy: 1e-9)
}
@@ -138,15 +143,15 @@ final class MeetingEchoVetoTests: XCTestCase {
// AVAudioFile reads may legitimately short-read (fewer frames than requested); a short
// read only ever drops the tail, so the head is a reliable, non-flaky probe of "was this
// chunk actually read". The missing chunk's region must be all zero regardless.
- for (actual, expected) in zip(output.prefix(1_000), goodSamples.prefix(1_000)) {
+ for (actual, expected) in zip(output.prefix(1000), goodSamples.prefix(1000)) {
XCTAssertEqual(actual, expected, accuracy: 1e-4)
}
- XCTAssertTrue(output.suffix(1_000).allSatisfy { $0 == 0 }, "a missing chunk's file must zero-fill, not throw")
+ XCTAssertTrue(output.suffix(1000).allSatisfy { $0 == 0 }, "a missing chunk's file must zero-fill, not throw")
}
// MARK: - 3. Reference gathering: independently rotated chunk boundaries
- func testReferenceSpansMapIndependentlyRotatedBoundariesCorrectly() {
+ func testReferenceSpansMapIndependentlyRotatedBoundariesCorrectly() throws {
// Mic rotates every 7s, app rotates every 5s: chunk indices never line up.
let micChunkSessionRange = (start: 14.0, end: 21.0)
let appChunks = [
@@ -162,15 +167,15 @@ final class MeetingEchoVetoTests: XCTestCase {
// [14,21) intersects app2 [10,15), app3 [15,20), app4 [20,25).
XCTAssertEqual(Set(spans.map(\.chunk.sequence)), [2, 3, 4])
- let fromApp2 = try! XCTUnwrap(spans.first { $0.chunk.sequence == 2 })
+ let fromApp2 = try XCTUnwrap(spans.first { $0.chunk.sequence == 2 })
XCTAssertEqual(fromApp2.localRange, 4.0..<5.0)
XCTAssertEqual(fromApp2.outputOffset, 0, accuracy: 1e-9)
- let fromApp3 = try! XCTUnwrap(spans.first { $0.chunk.sequence == 3 })
+ let fromApp3 = try XCTUnwrap(spans.first { $0.chunk.sequence == 3 })
XCTAssertEqual(fromApp3.localRange, 0.0..<5.0)
XCTAssertEqual(fromApp3.outputOffset, 1, accuracy: 1e-9)
- let fromApp4 = try! XCTUnwrap(spans.first { $0.chunk.sequence == 4 })
+ let fromApp4 = try XCTUnwrap(spans.first { $0.chunk.sequence == 4 })
XCTAssertEqual(fromApp4.localRange, 0.0..<1.0)
XCTAssertEqual(fromApp4.outputOffset, 6, accuracy: 1e-9)
}
@@ -213,9 +218,17 @@ final class MeetingEchoVetoTests: XCTestCase {
func testEffectiveEchoMatrix() {
func turn(isLikelyEcho: Bool, signalVerdict: TurnEchoVerdict) -> MeetingProcessingPipeline.StagedMicrophoneTurn {
MeetingProcessingPipeline.StagedMicrophoneTurn(
- chunkID: UUID(), index: 0, clusterID: UUID(), clusterLabel: "0",
- start: 0, end: 1, text: "hi", overlapsRemote: true,
- isLikelyEcho: isLikelyEcho, echoScored: true, signalVerdict: signalVerdict
+ chunkID: UUID(),
+ index: 0,
+ clusterID: UUID(),
+ clusterLabel: "0",
+ start: 0,
+ end: 1,
+ text: "hi",
+ overlapsRemote: true,
+ isLikelyEcho: isLikelyEcho,
+ echoScored: true,
+ signalVerdict: signalVerdict
)
}
XCTAssertFalse(turn(isLikelyEcho: true, signalVerdict: .residualNotExplained).effectiveEcho)
@@ -231,10 +244,17 @@ final class MeetingEchoVetoTests: XCTestCase {
func testTextEchoObservationIsExcludedBeforeMicrophoneStitching() {
func turn(key: String, isLikelyEcho: Bool) -> MeetingProcessingPipeline.StagedMicrophoneTurn {
MeetingProcessingPipeline.StagedMicrophoneTurn(
- chunkID: UUID(), index: 0, clusterID: UUID(), clusterLabel: "0",
+ chunkID: UUID(),
+ index: 0,
+ clusterID: UUID(),
+ clusterLabel: "0",
diarizationObservationKey: key,
- start: 0, end: 1, text: "hi", overlapsRemote: true,
- isLikelyEcho: isLikelyEcho, echoScored: true
+ start: 0,
+ end: 1,
+ text: "hi",
+ overlapsRemote: true,
+ isLikelyEcho: isLikelyEcho,
+ echoScored: true
)
}
let keys = MeetingProcessingPipeline.trustedMicrophoneObservationKeys(from: [
@@ -253,14 +273,30 @@ final class MeetingEchoVetoTests: XCTestCase {
func turns(signalVerdict: TurnEchoVerdict) -> [MeetingProcessingPipeline.StagedMicrophoneTurn] {
[
MeetingProcessingPipeline.StagedMicrophoneTurn(
- chunkID: UUID(), index: 0, clusterID: localCluster, clusterLabel: "local",
- start: 0, end: 5, text: "clean local speech", overlapsRemote: false,
- isLikelyEcho: false, echoScored: false, signalVerdict: signalVerdict
+ chunkID: UUID(),
+ index: 0,
+ clusterID: localCluster,
+ clusterLabel: "local",
+ start: 0,
+ end: 5,
+ text: "clean local speech",
+ overlapsRemote: false,
+ isLikelyEcho: false,
+ echoScored: false,
+ signalVerdict: signalVerdict
),
MeetingProcessingPipeline.StagedMicrophoneTurn(
- chunkID: UUID(), index: 1, clusterID: remoteCluster, clusterLabel: "remote",
- start: 5, end: 6, text: "echoed", overlapsRemote: true,
- isLikelyEcho: true, echoScored: true, signalVerdict: signalVerdict
+ chunkID: UUID(),
+ index: 1,
+ clusterID: remoteCluster,
+ clusterLabel: "remote",
+ start: 5,
+ end: 6,
+ text: "echoed",
+ overlapsRemote: true,
+ isLikelyEcho: true,
+ echoScored: true,
+ signalVerdict: signalVerdict
),
]
}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingEpochAudioMaterializerTests.swift b/Tests/FluidDictationIntegrationTests/MeetingEpochAudioMaterializerTests.swift
index 781eb090..2a69ee83 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingEpochAudioMaterializerTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingEpochAudioMaterializerTests.swift
@@ -38,11 +38,17 @@ final class MeetingEpochAudioMaterializerTests: XCTestCase {
sampleRate: sampleRate,
channels: AVAudioChannelCount(channels),
interleaved: false
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
)!
let frameCount = AVAudioFrameCount((seconds * sampleRate).rounded())
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCount)!
buffer.frameLength = frameCount
for channel in 0..<channels {
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let data = buffer.floatChannelData![channel]
for frame in 0..<Int(frameCount) {
let half = frame >= Int(frameCount) / 2
@@ -61,7 +67,11 @@ final class MeetingEpochAudioMaterializerTests: XCTestCase {
}
let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let byteCount = (attributes[.size] as? NSNumber)!.int64Value
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let sha256 = MeetingChunkPathConfinement.sha256Hex(contentsOf: url)!
return WrittenChunk(
url: url,
diff --git a/Tests/FluidDictationIntegrationTests/MeetingEraBatchTests.swift b/Tests/FluidDictationIntegrationTests/MeetingEraBatchTests.swift
index ae1c6110..a1f35787 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingEraBatchTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingEraBatchTests.swift
@@ -7,13 +7,21 @@ final class MeetingEraBatchTests: XCTestCase {
private func track(
captureMethod: MeetingAudioTrackCaptureMethod? = nil,
clockDrift: MeetingClockDriftRecord? = nil,
+ // nil requests the fixture default; an empty collection tests explicitly missing data.
+ // swiftlint:disable:next discouraged_optional_collection
captureEras: [MeetingCaptureEra]? = nil
) -> MeetingAudioTrack {
MeetingAudioTrack(
- id: UUID(), kind: .microphone, sourceIdentifier: "mic", sourceDisplayName: "Mic",
+ id: UUID(),
+ kind: .microphone,
+ sourceIdentifier: "mic",
+ sourceDisplayName: "Mic",
format: nil,
timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil),
- health: .waiting, chunks: [], captureMethod: captureMethod, clockDrift: clockDrift,
+ health: .waiting,
+ chunks: [],
+ captureMethod: captureMethod,
+ clockDrift: clockDrift,
captureEras: captureEras
)
}
@@ -24,8 +32,12 @@ final class MeetingEraBatchTests: XCTestCase {
clockDrift: MeetingClockDriftRecord? = nil
) -> MeetingCaptureEra {
MeetingCaptureEra(
- method: method, deviceUID: nil, deviceName: nil, roleAtElection: .unknown,
- startSeconds: startSeconds, clockDrift: clockDrift
+ method: method,
+ deviceUID: nil,
+ deviceName: nil,
+ roleAtElection: .unknown,
+ startSeconds: startSeconds,
+ clockDrift: clockDrift
)
}
@@ -38,8 +50,15 @@ final class MeetingEraBatchTests: XCTestCase {
rms: Double = 0
) -> MeetingProcessingPipeline.StagedMicrophoneTurn {
MeetingProcessingPipeline.StagedMicrophoneTurn(
- chunkID: UUID(), index: 0, clusterID: clusterID, clusterLabel: "spk",
- start: start, end: end, text: text, overlapsRemote: overlapsRemote, rms: rms
+ chunkID: UUID(),
+ index: 0,
+ clusterID: clusterID,
+ clusterLabel: "spk",
+ start: start,
+ end: end,
+ text: text,
+ overlapsRemote: overlapsRemote,
+ rms: rms
)
}
@@ -84,7 +103,8 @@ final class MeetingEraBatchTests: XCTestCase {
XCTAssertEqual(MeetingProcessingPipeline.eraIndex(containing: 25, eras: rawEras), 0)
XCTAssertEqual(
- MeetingProcessingPipeline.eraIndex(containing: 35, eras: rawEras), 0,
+ MeetingProcessingPipeline.eraIndex(containing: 35, eras: rawEras),
+ 0,
"raw (unconverted) eras misclassify the post-boundary turn as era 0 — this is why conversion is mandatory"
)
}
@@ -109,7 +129,7 @@ final class MeetingEraBatchTests: XCTestCase {
func testWideningAppliesOnlyInsideTheVoiceProcessingEra() {
let eras = [self.era(.voiceProcessing, startSeconds: 0), self.era(.avCaptureSession, startSeconds: 30)]
let turns = [
- self.turn(start: 5, end: 8, overlapsRemote: false), // inside VPIO era
+ self.turn(start: 5, end: 8, overlapsRemote: false), // inside VPIO era
self.turn(start: 40, end: 42, overlapsRemote: false), // inside AVCapture era
]
let (classified, widened) = MeetingProcessingPipeline.classifyMicrophoneTurns(
@@ -223,7 +243,7 @@ final class MeetingEraBatchTests: XCTestCase {
encoder.dateEncodingStrategy = .iso8601
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
- let decoded = try decoder.decode(MeetingAudioTrack.self, from: try encoder.encode(track))
+ let decoded = try decoder.decode(MeetingAudioTrack.self, from: encoder.encode(track))
XCTAssertEqual(decoded.captureEras, eras)
}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingExistingAudioReplayTests.swift b/Tests/FluidDictationIntegrationTests/MeetingExistingAudioReplayTests.swift
index 91e84f7c..4f32724f 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingExistingAudioReplayTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingExistingAudioReplayTests.swift
@@ -1,5 +1,5 @@
-@testable import FluidVoice_Debug
import Darwin.Mach
+@testable import FluidVoice_Debug
import Foundation
import XCTest
@@ -95,7 +95,8 @@ final class MeetingExistingAudioReplayTests: XCTestCase {
for segment in result.segments {
XCTAssertFalse(segment.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
guard let speakerID = segment.speakerID,
- let speaker = speakerByID[speakerID] else {
+ let speaker = speakerByID[speakerID]
+ else {
XCTFail("\(sourceSession.id) emitted a segment with an unknown speaker")
continue
}
@@ -111,9 +112,9 @@ final class MeetingExistingAudioReplayTests: XCTestCase {
.map { "\($0.displayName)[\($0.trackKind.rawValue)]" }
.joined(separator: ", ")
let summary = "id=\(sourceSession.id) chunks=\(sourceSession.audioTracks.flatMap(\.chunks).count) "
- + "segments=\(result.segments.count) speakers=\(result.speakers.count) "
- + "skipped=\(result.skippedChunkIDs.count) wall=\(String(format: "%.3f", wallTimeSeconds))s "
- + "{\(speakerSummary)}"
+ + "segments=\(result.segments.count) speakers=\(result.speakers.count) "
+ + "skipped=\(result.skippedChunkIDs.count) wall=\(String(format: "%.3f", wallTimeSeconds))s "
+ + "{\(speakerSummary)}"
reportLines.append(summary)
print("[meeting-replay] \(summary)")
@@ -181,7 +182,7 @@ final class MeetingExistingAudioReplayTests: XCTestCase {
"residentBytesAfter": residentBytesAfter,
]
try Self.writeProtected(
- try JSONSerialization.data(withJSONObject: fixtureReport, options: [.prettyPrinted, .sortedKeys]),
+ JSONSerialization.data(withJSONObject: fixtureReport, options: [.prettyPrinted, .sortedKeys]),
to: fixtureDirectory.appendingPathComponent("run.json")
)
}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingFallbackEchoProbeTests.swift b/Tests/FluidDictationIntegrationTests/MeetingFallbackEchoProbeTests.swift
index a8cc5b1e..f50a10de 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingFallbackEchoProbeTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingFallbackEchoProbeTests.swift
@@ -48,7 +48,10 @@ final class MeetingFallbackEchoProbeTests: XCTestCase {
let verdict = outcome.verdicts[0].map { String(describing: $0) } ?? "nil"
print(String(
format: "[probe] chunk seq=%d span=[%.1f-%.1f] verdict=%@ delay=%@",
- chunk.sequence, chunkOffset, chunkOffset + chunkDuration, verdict,
+ chunk.sequence,
+ chunkOffset,
+ chunkOffset + chunkDuration,
+ verdict,
outcome.acceptedDelaySeconds.map { String(format: "%.4fs", $0) } ?? "none"
))
}
@@ -106,7 +109,9 @@ final class MeetingFallbackEchoProbeTests: XCTestCase {
)
print(String(
format: "[turn] %-22@ [%.1f-%.1f] verdict=%@ delay=%@",
- label as NSString, start, clampedEnd,
+ label as NSString,
+ start,
+ clampedEnd,
outcome.verdicts[0].map { String(describing: $0) } ?? "nil",
outcome.acceptedDelaySeconds.map { String(format: "%.4fs", $0) } ?? "none"
))
diff --git a/Tests/FluidDictationIntegrationTests/MeetingLiveReplayTests.swift b/Tests/FluidDictationIntegrationTests/MeetingLiveReplayTests.swift
index f142f843..e5d0288e 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingLiveReplayTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingLiveReplayTests.swift
@@ -1,6 +1,6 @@
-@testable import FluidVoice_Debug
import AVFoundation
import CoreMedia
+@testable import FluidVoice_Debug
import Foundation
import XCTest
@@ -29,7 +29,9 @@ final class MeetingLiveReplayTests: XCTestCase {
let micSamples = try Self.load16kMonoFloatSamples(path: micPath)
let appSamples = try Self.load16kMonoFloatSamples(path: appPath)
- print("[replay] mic samples=\(micSamples.count) (\(Double(micSamples.count) / Self.sampleRate)s), app samples=\(appSamples.count) (\(Double(appSamples.count) / Self.sampleRate)s)")
+ print(
+ "[replay] mic samples=\(micSamples.count) (\(Double(micSamples.count) / Self.sampleRate)s), app samples=\(appSamples.count) (\(Double(appSamples.count) / Self.sampleRate)s)"
+ )
guard let pcmFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: Self.sampleRate, channels: 1, interleaved: false),
let formatDescription = Self.makeFormatDescription(format: pcmFormat)
@@ -103,7 +105,7 @@ final class MeetingLiveReplayTests: XCTestCase {
// scheduled, which would test harness timing, not the pipeline. Cap the feed rate at
// `accelerationFactor`x real time instead — still far from a real 192s sleep, but paced
// enough for the actor's drain loop to keep up with genuine ASR inference.
- let accelerationFactor: Double = 1.5
+ let accelerationFactor = 1.5
let feedStart = Date()
var bufferFailures = 0
var sampleBufferFailures = 0
@@ -133,7 +135,11 @@ final class MeetingLiveReplayTests: XCTestCase {
}
}
let feedElapsed = Date().timeIntervalSince(feedStart)
- print("[replay] fed \(events.count) chunks in \(String(format: "%.2f", feedElapsed))s (offered=\(offeredCount), bufferFailures=\(bufferFailures), sampleBufferFailures=\(sampleBufferFailures), totalWaitSeconds=\(String(format: "%.2f", totalWaitSeconds)))")
+ print(
+ // Keep the exact fixture text or diagnostic output together for comparison.
+ // swiftlint:disable:next line_length
+ "[replay] fed \(events.count) chunks in \(String(format: "%.2f", feedElapsed))s (offered=\(offeredCount), bufferFailures=\(bufferFailures), sampleBufferFailures=\(sampleBufferFailures), totalWaitSeconds=\(String(format: "%.2f", totalWaitSeconds)))"
+ )
// Let the drain loops work through whatever is still queued, until the transcript stops
// changing.
diff --git a/Tests/FluidDictationIntegrationTests/MeetingLiveSilenceEndpointTests.swift b/Tests/FluidDictationIntegrationTests/MeetingLiveSilenceEndpointTests.swift
index 95d1ed1e..25f3e924 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingLiveSilenceEndpointTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingLiveSilenceEndpointTests.swift
@@ -1,5 +1,5 @@
-@testable import FluidVoice_Debug
import AVFoundation
+@testable import FluidVoice_Debug
import Foundation
import XCTest
@@ -47,7 +47,7 @@ final class MeetingLiveSilenceEndpointTests: XCTestCase {
}
let sampleRate = 16_000.0
- let blockFrames = 2_560 // one 160ms chunk
+ let blockFrames = 2560 // one 160ms chunk
func feed(_ samples: [Float]) async throws {
var index = 0
@@ -99,6 +99,8 @@ final class MeetingLiveSilenceEndpointTests: XCTestCase {
else { return nil }
buffer.frameLength = AVAudioFrameCount(samples.count)
samples.withUnsafeBufferPointer { source in
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
buffer.floatChannelData?[0].update(from: source.baseAddress!, count: samples.count)
}
return buffer
diff --git a/Tests/FluidDictationIntegrationTests/MeetingMicrophoneCaptureTests.swift b/Tests/FluidDictationIntegrationTests/MeetingMicrophoneCaptureTests.swift
index ebc00b5d..13738484 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingMicrophoneCaptureTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingMicrophoneCaptureTests.swift
@@ -1,6 +1,6 @@
-@testable import FluidVoice_Debug
import AVFoundation
import CoreMedia
+@testable import FluidVoice_Debug
import Foundation
import XCTest
@@ -21,7 +21,7 @@ final class MeetingMicrophoneCaptureTests: XCTestCase {
func testValidStampsMapHostTimeToCMTimeExactly() {
var clock = self.makeClock()
- let outcome = clock.stamp(hostTime: self.hostTime(seconds: 2.5), frameCount: 4_800)
+ let outcome = clock.stamp(hostTime: self.hostTime(seconds: 2.5), frameCount: 4800)
guard case let .emitted(pts, synthesized, corrected, resynced) = outcome else {
return XCTFail("expected an emitted stamp")
}
@@ -33,8 +33,8 @@ final class MeetingMicrophoneCaptureTests: XCTestCase {
func testValidStampsAreContinuousAcrossBuffers() {
var clock = self.makeClock()
- _ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 4_800)
- let second = clock.stamp(hostTime: self.hostTime(seconds: 0.1), frameCount: 4_800)
+ _ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 4800)
+ let second = clock.stamp(hostTime: self.hostTime(seconds: 0.1), frameCount: 4800)
guard case let .emitted(pts, _, corrected, _) = second else {
return XCTFail("expected an emitted stamp")
}
@@ -63,22 +63,26 @@ final class MeetingMicrophoneCaptureTests: XCTestCase {
if let readback = result.voiceProcessingReadback {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
- let json = String(decoding: try encoder.encode(readback), as: UTF8.self)
+ // JSONEncoder fixture bytes are UTF-8; retain nonoptional decoding for assertions.
+ // swiftlint:disable:next optional_data_string_conversion
+ let json = try String(decoding: encoder.encode(readback), as: UTF8.self)
print("[phase1] voice-processing-readback=\n\(json)")
} else {
XCTFail("running VPIO capture did not produce a read-back snapshot")
}
-#if DEBUG
+ #if DEBUG
if let acoustic = result.acousticTrialB {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
- let json = String(decoding: try encoder.encode(acoustic), as: UTF8.self)
+ // JSONEncoder fixture bytes are UTF-8; retain nonoptional decoding for assertions.
+ // swiftlint:disable:next optional_data_string_conversion
+ let json = try String(decoding: encoder.encode(acoustic), as: UTF8.self)
print("[phase0-trial-b] numeric-sidecar=\n\(json)")
XCTAssertEqual(acoustic.schemaVersion, MeetingVPIOAcousticTrialBReport.currentSchemaVersion)
XCTAssertFalse(acoustic.runs.isEmpty)
XCTAssertTrue(acoustic.stimulus.withinSafetyBounds)
}
-#endif
+ #endif
XCTAssertGreaterThanOrEqual(validRate, 0.99)
XCTAssertEqual(result.writerDiscontinuities, 0)
XCTAssertEqual(result.writerBackpressureEvents, 0)
@@ -105,8 +109,8 @@ final class MeetingMicrophoneCaptureTests: XCTestCase {
func testInvalidStampsExtrapolateFromLastValid() {
var clock = self.makeClock()
- _ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 4_800) // anchor at t=0, 100ms
- let outcome = clock.stamp(hostTime: nil, frameCount: 4_800) // extrapolated 100ms window
+ _ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 4800) // anchor at t=0, 100ms
+ let outcome = clock.stamp(hostTime: nil, frameCount: 4800) // extrapolated 100ms window
guard case let .emitted(pts, synthesized, _, _) = outcome else {
return XCTFail("expected an emitted (synthesized) stamp")
}
@@ -123,7 +127,7 @@ final class MeetingMicrophoneCaptureTests: XCTestCase {
for _ in 0..<60 { // 60 * 10ms = 600ms of invalid stamps
let outcome = clock.stamp(hostTime: nil, frameCount: 480)
switch outcome {
- case .emitted(_, let synthesized, _, _):
+ case let .emitted(_, synthesized, _, _):
XCTAssertTrue(synthesized)
XCTAssertFalse(sawDrop, "no emission should follow a drop without a valid resync")
emittedSynthesizedCount += 1
@@ -139,7 +143,9 @@ final class MeetingMicrophoneCaptureTests: XCTestCase {
func testValidStampAfterADropResyncsAndCorrectsTheAnchor() {
var clock = self.makeClock()
_ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 480)
- for _ in 0..<60 { _ = clock.stamp(hostTime: nil, frameCount: 480) }
+ for _ in 0..<60 {
+ _ = clock.stamp(hostTime: nil, frameCount: 480)
+ }
let resync = clock.stamp(hostTime: self.hostTime(seconds: 1.2), frameCount: 480)
guard case let .emitted(pts, synthesized, corrected, resynced) = resync else {
@@ -160,9 +166,9 @@ final class MeetingMicrophoneCaptureTests: XCTestCase {
func testSmallDivergenceDoesNotCorrectTheAnchor() {
var clock = self.makeClock()
- _ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 4_800)
+ _ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 4800)
// 1/96000s divergence is half a frame at 48kHz — below the one-frame correction threshold.
- let outcome = clock.stamp(hostTime: self.hostTime(seconds: 0.1 + 1.0 / 96_000), frameCount: 4_800)
+ let outcome = clock.stamp(hostTime: self.hostTime(seconds: 0.1 + 1.0 / 96_000), frameCount: 4800)
guard case let .emitted(_, _, corrected, _) = outcome else {
return XCTFail("expected an emitted stamp")
}
@@ -171,8 +177,8 @@ final class MeetingMicrophoneCaptureTests: XCTestCase {
func testLargeDivergenceCorrectsTheAnchorWithoutASynthesizedFlag() {
var clock = self.makeClock()
- _ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 4_800)
- let outcome = clock.stamp(hostTime: self.hostTime(seconds: 0.15), frameCount: 4_800) // 50ms off
+ _ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 4800)
+ let outcome = clock.stamp(hostTime: self.hostTime(seconds: 0.15), frameCount: 4800) // 50ms off
guard case let .emitted(pts, synthesized, corrected, resynced) = outcome else {
return XCTFail("expected an emitted stamp")
}
@@ -185,17 +191,25 @@ final class MeetingMicrophoneCaptureTests: XCTestCase {
// MARK: - CMSampleBuffer synthesis round-trip
private func makeMonoBuffer(frameCount: Int, fill: (Int) -> Float) -> AVAudioPCMBuffer {
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 1, interleaved: false)!
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(frameCount))!
buffer.frameLength = AVAudioFrameCount(frameCount)
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let channel = buffer.floatChannelData![0]
- for index in 0..<frameCount { channel[index] = fill(index) }
+ for index in 0..<frameCount {
+ channel[index] = fill(index)
+ }
return buffer
}
func testSynthesizedSampleBufferRoundTripsThroughLiveSampleCopy() throws {
let frameCount = 480
- let source = self.makeMonoBuffer(frameCount: frameCount) { Float($0) / 1_000 }
+ let source = self.makeMonoBuffer(frameCount: frameCount) { Float($0) / 1000 }
let pts = CMTime(value: 123, timescale: 48_000)
let sampleBuffer = try XCTUnwrap(meetingMicrophoneSynthesizeSampleBuffer(from: source, presentationTime: pts))
@@ -210,7 +224,9 @@ final class MeetingMicrophoneCaptureTests: XCTestCase {
XCTAssertEqual(copy.buffer.format.channelCount, 1)
XCTAssertEqual(copy.pts, pts)
for index in 0..<frameCount {
- XCTAssertEqual(copy.buffer.floatChannelData![0][index], Float(index) / 1_000)
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ XCTAssertEqual(copy.buffer.floatChannelData![0][index], Float(index) / 1000)
}
}
@@ -222,13 +238,21 @@ final class MeetingMicrophoneCaptureTests: XCTestCase {
)
let before = try XCTUnwrap(MeetingLiveSampleCopy.copy(sampleBuffer))
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let beforeValues = (0..<frameCount).map { before.buffer.floatChannelData![0][$0] }
// Mutate the source AFTER synthesis — the synthesized buffer must not see this.
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let channel = source.floatChannelData![0]
- for index in 0..<frameCount { channel[index] = -99 }
+ for index in 0..<frameCount {
+ channel[index] = -99
+ }
let after = try XCTUnwrap(MeetingLiveSampleCopy.copy(sampleBuffer))
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let afterValues = (0..<frameCount).map { after.buffer.floatChannelData![0][$0] }
XCTAssertEqual(beforeValues, afterValues)
@@ -357,8 +381,11 @@ final class MeetingMicrophoneCaptureTests: XCTestCase {
let (writer, sessionDirectory) = try self.makeWriter()
defer { try? FileManager.default.removeItem(at: sessionDirectory) }
for tick in 0..<100 {
- self.pushBuffer(writer, ptsSeconds: 188_092.2630985 + Double(tick) * 0.01 - Double(tick) * 0.000000042,
- timescale: 1_000_000_000)
+ self.pushBuffer(
+ writer,
+ ptsSeconds: 188_092.2_630_985 + Double(tick) * 0.01 - Double(tick) * 0.000_000_042,
+ timescale: 1_000_000_000
+ )
if tick.isMultiple(of: 10) { _ = await writer.snapshot() }
}
let track = await writer.stop()
@@ -523,12 +550,12 @@ extension MeetingMicrophoneCaptureTests {
/// re-baselined one full window off, so every subsequent stamp re-corrected forever.
func testCorrectionDoesNotLatchAcrossSubsequentStamps() {
var clock = self.makeClock()
- _ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 4_800)
+ _ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 4800)
// Force one genuine correction with a 5ms excursion…
- _ = clock.stamp(hostTime: self.hostTime(seconds: 0.105), frameCount: 4_800)
+ _ = clock.stamp(hostTime: self.hostTime(seconds: 0.105), frameCount: 4800)
// …then five contiguous jitter-free stamps on the shifted timeline: zero further corrections.
for i in 2...6 {
- let outcome = clock.stamp(hostTime: self.hostTime(seconds: 0.005 + Double(i) * 0.1), frameCount: 4_800)
+ let outcome = clock.stamp(hostTime: self.hostTime(seconds: 0.005 + Double(i) * 0.1), frameCount: 4800)
guard case let .emitted(_, _, corrected, _) = outcome else { return XCTFail("expected emission") }
XCTAssertFalse(corrected, "stamp \(i) re-corrected: the latch is back")
}
@@ -538,12 +565,12 @@ extension MeetingMicrophoneCaptureTests {
/// previous end.
func testCorrectionLeavesEmittedPTSContinuous() {
var clock = self.makeClock()
- _ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 4_800)
- guard case let .emitted(before, _, corrected1, _) = clock.stamp(hostTime: self.hostTime(seconds: 0.108), frameCount: 4_800) else {
+ _ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 4800)
+ guard case let .emitted(before, _, corrected1, _) = clock.stamp(hostTime: self.hostTime(seconds: 0.108), frameCount: 4800) else {
return XCTFail("expected emission")
}
XCTAssertTrue(corrected1)
- guard case let .emitted(after, _, _, _) = clock.stamp(hostTime: self.hostTime(seconds: 0.208), frameCount: 4_800) else {
+ guard case let .emitted(after, _, _, _) = clock.stamp(hostTime: self.hostTime(seconds: 0.208), frameCount: 4800) else {
return XCTFail("expected emission")
}
XCTAssertEqual(after.seconds - before.seconds, 0.1, accuracy: 1.0 / 48_000)
@@ -555,7 +582,7 @@ extension MeetingMicrophoneCaptureTests {
let windows = 72_000 // 2h of 100ms windows
for i in 0..<windows {
let actual = Double(i) * 0.1 * (1 + 6.4e-6)
- _ = clock.stamp(hostTime: self.hostTime(seconds: actual), frameCount: 4_800)
+ _ = clock.stamp(hostTime: self.hostTime(seconds: actual), frameCount: 4800)
}
XCTAssertEqual(clock.divergenceStepEventCount, 0)
XCTAssertGreaterThan(clock.cumulativeAbsorbedCorrectionSeconds, 0, "drift shows up as absorbed corrections")
@@ -564,11 +591,11 @@ extension MeetingMicrophoneCaptureTests {
func testSingleJumpFiresExactlyOneStepEvent() {
var clock = self.makeClock()
for i in 0..<10 {
- _ = clock.stamp(hostTime: self.hostTime(seconds: Double(i) * 0.1), frameCount: 4_800)
+ _ = clock.stamp(hostTime: self.hostTime(seconds: Double(i) * 0.1), frameCount: 4800)
}
- _ = clock.stamp(hostTime: self.hostTime(seconds: 1.0 + 0.050), frameCount: 4_800) // 50ms step
+ _ = clock.stamp(hostTime: self.hostTime(seconds: 1.0 + 0.050), frameCount: 4800) // 50ms step
for i in 11..<20 {
- _ = clock.stamp(hostTime: self.hostTime(seconds: 0.050 + Double(i) * 0.1), frameCount: 4_800)
+ _ = clock.stamp(hostTime: self.hostTime(seconds: 0.050 + Double(i) * 0.1), frameCount: 4800)
}
XCTAssertEqual(clock.divergenceStepEventCount, 1)
XCTAssertEqual(clock.maxDivergenceStepSeconds, 0.050, accuracy: 0.001)
@@ -578,12 +605,14 @@ extension MeetingMicrophoneCaptureTests {
/// anchor clamps forward so PTS never steps behind emitted audio.
func testResyncNeverStepsBehindEmittedAudio() {
var clock = self.makeClock()
- _ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 4_800)
+ _ = clock.stamp(hostTime: self.hostTime(seconds: 0), frameCount: 4800)
// 500ms of synthesized emission (cap-inclusive), delivered as a burst…
- for _ in 0..<5 { _ = clock.stamp(hostTime: nil, frameCount: 4_800) }
- _ = clock.stamp(hostTime: nil, frameCount: 4_800) // over cap → dropping
+ for _ in 0..<5 {
+ _ = clock.stamp(hostTime: nil, frameCount: 4800)
+ }
+ _ = clock.stamp(hostTime: nil, frameCount: 4800) // over cap → dropping
// …then a valid stamp whose host time is EARLIER than the emitted end (0.6s emitted, 0.3s wall).
- guard case let .emitted(pts, _, _, resynced) = clock.stamp(hostTime: self.hostTime(seconds: 0.3), frameCount: 4_800) else {
+ guard case let .emitted(pts, _, _, resynced) = clock.stamp(hostTime: self.hostTime(seconds: 0.3), frameCount: 4800) else {
return XCTFail("expected resync emission")
}
XCTAssertTrue(resynced)
@@ -595,9 +624,9 @@ extension MeetingMicrophoneCaptureTests {
func testValidHostSecondsBoundsTrackFirstAndLastValidStamp() throws {
var clock = self.makeClock()
- _ = clock.stamp(hostTime: self.hostTime(seconds: 5), frameCount: 4_800)
- _ = clock.stamp(hostTime: nil, frameCount: 4_800) // synthesized: must not move the bounds
- _ = clock.stamp(hostTime: self.hostTime(seconds: 5.3), frameCount: 4_800)
+ _ = clock.stamp(hostTime: self.hostTime(seconds: 5), frameCount: 4800)
+ _ = clock.stamp(hostTime: nil, frameCount: 4800) // synthesized: must not move the bounds
+ _ = clock.stamp(hostTime: self.hostTime(seconds: 5.3), frameCount: 4800)
XCTAssertEqual(try XCTUnwrap(clock.firstValidHostSeconds), 5.0, accuracy: 1e-9)
XCTAssertEqual(try XCTUnwrap(clock.lastValidHostSeconds), 5.3, accuracy: 1e-9)
}
@@ -610,9 +639,9 @@ extension MeetingMicrophoneCaptureTests {
func testTimelineResetReanchorsOnNextValidStamp() {
var clock = self.makeClock()
- _ = clock.stamp(hostTime: self.hostTime(seconds: 5), frameCount: 4_800)
+ _ = clock.stamp(hostTime: self.hostTime(seconds: 5), frameCount: 4800)
clock.requestTimelineReset()
- guard case let .emitted(pts, _, _, _) = clock.stamp(hostTime: self.hostTime(seconds: 9), frameCount: 4_800) else {
+ guard case let .emitted(pts, _, _, _) = clock.stamp(hostTime: self.hostTime(seconds: 9), frameCount: 4800) else {
return XCTFail("expected emission after reset")
}
XCTAssertEqual(pts.seconds, 9.0, accuracy: 1.0 / 48_000)
@@ -620,8 +649,9 @@ extension MeetingMicrophoneCaptureTests {
}
// MARK: - Bidirectional route-following mic: capture-side unit tests (no real engines/sessions)
+
extension MeetingMicrophoneCaptureTests {
- // MARK: MeetingEraAcceptanceFence
+ // MARK: - MeetingEraAcceptanceFence
func testFenceBeginSampleAfterQuiesceReturnsFalse() async {
let fence = MeetingEraAcceptanceFence()
@@ -654,7 +684,6 @@ extension MeetingMicrophoneCaptureTests {
XCTAssertFalse(fence.beginSample())
}
-
func testAckResumeBeforeWaitReturnsImmediately() async {
let ack = MeetingCaptureMethodChangeAck()
ack.resume()
@@ -689,13 +718,15 @@ extension MeetingMicrophoneCaptureTests {
XCTAssertLessThan(Date().timeIntervalSince(start), 0.5)
}
- // MARK: Writer beginSplice
+ // MARK: - Writer beginSplice
func testBeginSpliceReturnsFinalizedChunkPresentationEnd() async throws {
let (writer, sessionDirectory) = try self.makeWriter()
defer { try? FileManager.default.removeItem(at: sessionDirectory) }
- for tick in 0..<5 { self.pushBuffer(writer, ptsSeconds: Double(tick) * 0.01) }
+ for tick in 0..<5 {
+ self.pushBuffer(writer, ptsSeconds: Double(tick) * 0.01)
+ }
try? await Task.sleep(nanoseconds: 50_000_000) // let enqueue's async consume land
let boundary = await writer.beginSplice()
@@ -767,15 +798,23 @@ extension MeetingMicrophoneCaptureTests {
XCTAssertEqual(track.chunks[1].presentationStart.seconds, 0.21, accuracy: 1e-6)
}
- // MARK: Writer format-mismatch guard
+ // MARK: - Writer format-mismatch guard
private func makeStereoBuffer(frameCount: Int, fill: (Int) -> Float) -> AVAudioPCMBuffer {
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 2, interleaved: false)!
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(frameCount))!
buffer.frameLength = AVAudioFrameCount(frameCount)
for channel in 0..<2 {
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let data = buffer.floatChannelData![channel]
- for index in 0..<frameCount { data[index] = fill(index) }
+ for index in 0..<frameCount {
+ data[index] = fill(index)
+ }
}
return buffer
}
@@ -793,10 +832,14 @@ extension MeetingMicrophoneCaptureTests {
let sessionDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
defer { try? FileManager.default.removeItem(at: sessionDirectory) }
let track = MeetingAudioTrack(
- id: UUID(), kind: .microphone, sourceIdentifier: "test-mic", sourceDisplayName: "Test Microphone",
+ id: UUID(),
+ kind: .microphone,
+ sourceIdentifier: "test-mic",
+ sourceDisplayName: "Test Microphone",
format: nil,
timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil),
- health: .waiting, chunks: []
+ health: .waiting,
+ chunks: []
)
var events: [MeetingCaptureEvent] = []
let lock = NSLock()
@@ -827,7 +870,7 @@ extension MeetingMicrophoneCaptureTests {
XCTAssertEqual(finalizedFormats[1].channelCount, 2)
}
- // MARK: Transactional updateTrackMetadata
+ // MARK: - Transactional updateTrackMetadata
func testUpdateTrackMetadataPersistsSuccessfully() async throws {
let (writer, sessionDirectory) = try self.makeWriter()
@@ -860,7 +903,7 @@ extension MeetingMicrophoneCaptureTests {
XCTAssertNil(track.captureMethod, "a failed persist must leave the in-memory track untouched")
}
- // MARK: MeetingCaptureDeviceElection
+ // MARK: - MeetingCaptureDeviceElection
private func micIdentity(id: String, uid: String?, name: String, role: MeetingMicrophoneRole = .unknown) -> MeetingMicrophoneIdentity {
MeetingMicrophoneIdentity(captureDeviceID: id, coreAudioUID: uid, displayName: name, role: role)
@@ -972,21 +1015,28 @@ extension MeetingMicrophoneCaptureTests {
}
}
- // MARK: Codable: captureEras
+ // MARK: - Codable: captureEras
private func sampleEra(method: MeetingAudioTrackCaptureMethod, start: Double) -> MeetingCaptureEra {
MeetingCaptureEra(
- method: method, deviceUID: "uid-1", deviceName: "MacBook Mic",
- roleAtElection: .personal, startSeconds: start
+ method: method,
+ deviceUID: "uid-1",
+ deviceName: "MacBook Mic",
+ roleAtElection: .personal,
+ startSeconds: start
)
}
func testMultiEraCaptureErasRoundTrip() throws {
var track = MeetingAudioTrack(
- id: UUID(), kind: .microphone, sourceIdentifier: "mic", sourceDisplayName: "Mic",
+ id: UUID(),
+ kind: .microphone,
+ sourceIdentifier: "mic",
+ sourceDisplayName: "Mic",
format: nil,
timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil),
- health: .waiting, chunks: []
+ health: .waiting,
+ chunks: []
)
track.captureMethod = .avCaptureSession
track.captureEras = [
@@ -1046,10 +1096,14 @@ extension MeetingMicrophoneCaptureTests {
func testMultiEraTrackCaptureMethodIsAvCaptureSession() {
// Multi-era tracks write the conservative track-level captureMethod for legacy readers.
var track = MeetingAudioTrack(
- id: UUID(), kind: .microphone, sourceIdentifier: "mic", sourceDisplayName: "Mic",
+ id: UUID(),
+ kind: .microphone,
+ sourceIdentifier: "mic",
+ sourceDisplayName: "Mic",
format: nil,
timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil),
- health: .waiting, chunks: []
+ health: .waiting,
+ chunks: []
)
track.captureEras = [
self.sampleEra(method: .voiceProcessing, start: 0),
@@ -1060,7 +1114,7 @@ extension MeetingMicrophoneCaptureTests {
XCTAssertEqual(track.captureEras?.first?.method, .voiceProcessing)
}
- // MARK: Gate re-use per era
+ // MARK: - Gate re-use per era
func testFreshGatePerEraPassesBufferingFlushPassthroughWhilePreviousEraGateStaysTerminal() throws {
let firstEraGate = MeetingVoiceProcessingCommitGate()
@@ -1120,12 +1174,17 @@ extension MeetingMicrophoneCaptureTests {
}
// MARK: - Not covered here: phase-machine transitions (file-private, hardware-driven —
+
// needs the Phase1 probe) and writer finalizationSlots saturation (no test seam exposed).
func testPreselectionBuiltInMicDefaultsToUnknownRole() {
let builtIn = MeetingMicrophoneIdentity(captureDeviceID: "built-in", coreAudioUID: "BuiltInMicrophoneDevice", displayName: "MacBook Pro Microphone")
let selection = MeetingMicrophonePreselection.select(
- identities: [builtIn], savedDeviceID: "other-device", savedRole: .personal,
- systemDefaultUID: "BuiltInMicrophoneDevice", preferredInputUID: nil, systemDefaultCaptureID: nil
+ identities: [builtIn],
+ savedDeviceID: "other-device",
+ savedRole: .personal,
+ systemDefaultUID: "BuiltInMicrophoneDevice",
+ preferredInputUID: nil,
+ systemDefaultCaptureID: nil
)
XCTAssertEqual(selection.deviceID, "built-in")
XCTAssertEqual(selection.role, .unknown)
@@ -1145,7 +1204,6 @@ extension MeetingMicrophoneCaptureTests {
XCTAssertNotEqual(elected.role, .personal)
XCTAssertNotEqual(elected.role, .shared)
}
-
}
private final class MeetingMicrophoneCallbackOrderingState: @unchecked Sendable {
diff --git a/Tests/FluidDictationIntegrationTests/MeetingNemotronRealModelSmokeTests.swift b/Tests/FluidDictationIntegrationTests/MeetingNemotronRealModelSmokeTests.swift
index 5c8a0fbd..815f41b8 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingNemotronRealModelSmokeTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingNemotronRealModelSmokeTests.swift
@@ -14,9 +14,15 @@ final class MeetingNemotronRealModelSmokeTests: XCTestCase {
let frameCount = AVAudioFrameCount((seconds * sampleRate).rounded())
let format = AVAudioFormat(
commonFormat: .pcmFormatFloat32, sampleRate: sampleRate, channels: 1, interleaved: false
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
)!
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCount)!
buffer.frameLength = frameCount
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let data = buffer.floatChannelData![0]
// Two voiced bursts of different pitches separated by silence: structure only, not speech.
for frame in 0..<Int(frameCount) {
@@ -70,55 +76,56 @@ final class MeetingNemotronRealModelSmokeTests: XCTestCase {
let (_, samples) = try self.writeSmokeWAV(into: directory)
#if arch(arm64)
- let runtime = MeetingParakeetNemotronRuntime(
- asrServiceProvider: { ASRService() },
- modelLocator: MeetingNemotronModelLocator(
- injectedURL: modelURL,
- environment: environment
- )
- )
- let trackID = UUID()
- let epoch0 = MeetingAnalysisEpochID(trackID: trackID, ordinal: 0)
- let epoch1 = MeetingAnalysisEpochID(trackID: trackID, ordinal: 1)
- let duration = Double(samples.count) / 16_000
-
- let artifact = try MeetingNemotronModelLocator(
+ let runtime = MeetingParakeetNemotronRuntime(
+ asrServiceProvider: { ASRService() },
+ modelLocator: MeetingNemotronModelLocator(
injectedURL: modelURL,
environment: environment
- ).locate()
- let results = try await runtime.withNemotronDiarization(artifact: artifact) { factory in
- var collected = MeetingNemotronPhaseResult()
- for epoch in [epoch0, epoch1] {
- let diarizer = try await factory.makeDiarizer(epoch: epoch)
- let segments = try await diarizer.diarize(samples: samples)
- // Test-only completion marker; the runtime phase result has no separate
- // success ledger for a valid epoch that happens to contain no speech.
- collected.failures[epoch] = "smokeCompleted"
- collected.activity.append(contentsOf: segments.map {
- MeetingBackendSpeakerActivity(
- token: MeetingBackendSpeakerToken(
- analysisEpochID: epoch,
- label: "slot-\($0.slotIndex)"
- ),
- start: $0.start,
- end: $0.end
- )
- })
- }
- return collected
- }
+ )
+ )
+ let trackID = UUID()
+ let epoch0 = MeetingAnalysisEpochID(trackID: trackID, ordinal: 0)
+ let epoch1 = MeetingAnalysisEpochID(trackID: trackID, ordinal: 1)
+ let duration = Double(samples.count) / 16_000
- XCTAssertEqual(Set(results.failures.keys), [epoch0, epoch1])
- for segment in results.activity {
- XCTAssertGreaterThanOrEqual(segment.start, 0, "\(segment.token.analysisEpochID)")
- XCTAssertGreaterThan(segment.end, segment.start, "\(segment.token.analysisEpochID)")
- XCTAssertLessThanOrEqual(
- segment.end, duration + 0.5,
- "\(segment.token.analysisEpochID): segments stay inside the audio"
- )
+ let artifact = try MeetingNemotronModelLocator(
+ injectedURL: modelURL,
+ environment: environment
+ ).locate()
+ let results = try await runtime.withNemotronDiarization(artifact: artifact) { factory in
+ var collected = MeetingNemotronPhaseResult()
+ for epoch in [epoch0, epoch1] {
+ let diarizer = try await factory.makeDiarizer(epoch: epoch)
+ let segments = try await diarizer.diarize(samples: samples)
+ // Test-only completion marker; the runtime phase result has no separate
+ // success ledger for a valid epoch that happens to contain no speech.
+ collected.failures[epoch] = "smokeCompleted"
+ collected.activity.append(contentsOf: segments.map {
+ MeetingBackendSpeakerActivity(
+ token: MeetingBackendSpeakerToken(
+ analysisEpochID: epoch,
+ label: "slot-\($0.slotIndex)"
+ ),
+ start: $0.start,
+ end: $0.end
+ )
+ })
}
+ return collected
+ }
+
+ XCTAssertEqual(Set(results.failures.keys), [epoch0, epoch1])
+ for segment in results.activity {
+ XCTAssertGreaterThanOrEqual(segment.start, 0, "\(segment.token.analysisEpochID)")
+ XCTAssertGreaterThan(segment.end, segment.start, "\(segment.token.analysisEpochID)")
+ XCTAssertLessThanOrEqual(
+ segment.end,
+ duration + 0.5,
+ "\(segment.token.analysisEpochID): segments stay inside the audio"
+ )
+ }
#else
- throw XCTSkip("the production runtime is Apple-Silicon only")
+ throw XCTSkip("the production runtime is Apple-Silicon only")
#endif
}
}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingOverlayModelsTests.swift b/Tests/FluidDictationIntegrationTests/MeetingOverlayModelsTests.swift
index 8a0860f3..dea16179 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingOverlayModelsTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingOverlayModelsTests.swift
@@ -1,6 +1,6 @@
-@testable import FluidVoice_Debug
import AppKit
import CoreGraphics
+@testable import FluidVoice_Debug
import Foundation
import SwiftUI
import XCTest
@@ -48,7 +48,10 @@ final class MeetingOverlayGeometryTests: XCTestCase {
XCTAssertLessThanOrEqual(layout.attributedText.string.count, MeetingRollingCaptionLayout.maximumInputCharacters)
XCTAssertNotNil(layout.layoutManager.textStorage)
XCTAssertEqual(layout.selectedGlyphRange.upperBound, layout.layoutManager.numberOfGlyphs)
- XCTAssertEqual(MeetingRollingCaptionLayout.contentSize, CGSize(width: MeetingOverlayPresentation.captionsContentWidth, height: MeetingOverlayPresentation.captionsContentHeight))
+ XCTAssertEqual(
+ MeetingRollingCaptionLayout.contentSize,
+ CGSize(width: MeetingOverlayPresentation.captionsContentWidth, height: MeetingOverlayPresentation.captionsContentHeight)
+ )
XCTAssertTrue(CGRect(origin: .zero, size: MeetingRollingCaptionLayout.contentSize).contains(layout.inkBounds))
}
@@ -67,8 +70,10 @@ final class MeetingOverlayGeometryTests: XCTestCase {
Color.clear.frame(height: MeetingOverlayPresentation.captionsControlsHeight)
Color.clear.frame(height: MeetingOverlayPresentation.captionsTopInset)
MeetingRollingCaptionView(text: text)
- .frame(width: MeetingOverlayPresentation.captionsContentWidth,
- height: MeetingOverlayPresentation.captionsContentHeight)
+ .frame(
+ width: MeetingOverlayPresentation.captionsContentWidth,
+ height: MeetingOverlayPresentation.captionsContentHeight
+ )
Color.clear.frame(height: MeetingOverlayPresentation.captionsBottomInset)
Color.gray.frame(height: MeetingOverlayPresentation.captionsFooterHeight)
}
@@ -155,11 +160,31 @@ final class MeetingOverlayGeometryTests: XCTestCase {
let padding = MeetingOverlayPadding(top: 10, left: 12, bottom: 14, right: 16)
let cases: [(MeetingOverlayVisibleAnchor, CGSize, CGRect)] = [
(MeetingOverlayVisibleAnchor(centerX: self.screen.minX, bottomY: 200), self.pill, CGRect(origin: CGPoint(x: self.screen.minX, y: 200), size: self.pill)),
- (MeetingOverlayVisibleAnchor(centerX: self.screen.maxX, bottomY: 200), self.pill, CGRect(origin: CGPoint(x: self.screen.maxX - self.pill.width, y: 200), size: self.pill)),
- (MeetingOverlayVisibleAnchor(centerX: 820, bottomY: self.screen.minY - 40), self.pill, CGRect(origin: CGPoint(x: 820 - self.pill.width / 2, y: self.screen.minY), size: self.pill)),
- (MeetingOverlayVisibleAnchor(centerX: 820, bottomY: self.screen.maxY), self.pill, CGRect(origin: CGPoint(x: 820 - self.pill.width / 2, y: self.screen.maxY - self.pill.height), size: self.pill)),
- (MeetingOverlayVisibleAnchor(centerX: self.screen.minX, bottomY: self.screen.minY - 8), self.captions, CGRect(origin: CGPoint(x: self.screen.minX, y: self.screen.minY), size: self.captions)),
- (MeetingOverlayVisibleAnchor(centerX: self.screen.maxX, bottomY: self.screen.maxY), self.captions, CGRect(origin: CGPoint(x: self.screen.maxX - self.captions.width, y: self.screen.maxY - self.captions.height), size: self.captions)),
+ (
+ MeetingOverlayVisibleAnchor(centerX: self.screen.maxX, bottomY: 200),
+ self.pill,
+ CGRect(origin: CGPoint(x: self.screen.maxX - self.pill.width, y: 200), size: self.pill)
+ ),
+ (
+ MeetingOverlayVisibleAnchor(centerX: 820, bottomY: self.screen.minY - 40),
+ self.pill,
+ CGRect(origin: CGPoint(x: 820 - self.pill.width / 2, y: self.screen.minY), size: self.pill)
+ ),
+ (
+ MeetingOverlayVisibleAnchor(centerX: 820, bottomY: self.screen.maxY),
+ self.pill,
+ CGRect(origin: CGPoint(x: 820 - self.pill.width / 2, y: self.screen.maxY - self.pill.height), size: self.pill)
+ ),
+ (
+ MeetingOverlayVisibleAnchor(centerX: self.screen.minX, bottomY: self.screen.minY - 8),
+ self.captions,
+ CGRect(origin: CGPoint(x: self.screen.minX, y: self.screen.minY), size: self.captions)
+ ),
+ (
+ MeetingOverlayVisibleAnchor(centerX: self.screen.maxX, bottomY: self.screen.maxY),
+ self.captions,
+ CGRect(origin: CGPoint(x: self.screen.maxX - self.captions.width, y: self.screen.maxY - self.captions.height), size: self.captions)
+ ),
]
for (anchor, size, expectedVisible) in cases {
@@ -309,11 +334,11 @@ final class MeetingOverlayPresentationReducerTests: XCTestCase {
XCTAssertEqual(reducer.presentation, .pill)
}
- func testPreferenceRoundTripAndCaseIterable() {
+ func testPreferenceRoundTripAndCaseIterable() throws {
XCTAssertEqual(MeetingOverlayPreference.allCases, [.pill, .captions])
for preference in MeetingOverlayPreference.allCases {
- let data = try! JSONEncoder().encode(preference)
- let decoded = try! JSONDecoder().decode(MeetingOverlayPreference.self, from: data)
+ let data = try JSONEncoder().encode(preference)
+ let decoded = try JSONDecoder().decode(MeetingOverlayPreference.self, from: data)
XCTAssertEqual(decoded, preference)
}
}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingPCMStoragePolicyTests.swift b/Tests/FluidDictationIntegrationTests/MeetingPCMStoragePolicyTests.swift
index 83951777..33e3052f 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingPCMStoragePolicyTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingPCMStoragePolicyTests.swift
@@ -31,29 +31,53 @@ final class MeetingPCMStoragePolicyTests: XCTestCase {
let timebase = MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil)
var session = MeetingSession(configuration: configuration, timebase: timebase)
let chunk = MeetingAudioChunk(
- id: UUID(), sequence: 0, relativeFilePath: pcmPath,
+ id: UUID(),
+ sequence: 0,
+ relativeFilePath: pcmPath,
presentationStart: MeetingMediaTime(value: 0, timescale: 1),
presentationEnd: MeetingMediaTime(value: 1, timescale: 1),
- discontinuities: [], sha256: "hash", byteCount: 1, finalizationState: .finalized,
+ discontinuities: [],
+ sha256: "hash",
+ byteCount: 1,
+ finalizationState: .finalized,
audioSchemaVersion: 2,
captureAnalysisAsset: MeetingAudioAsset(
- role: .captureAnalysis, encoding: .linearPCMFloat32CAFV1, presence: .ready,
- relativeFilePath: pcmPath, byteCount: 1, sha256: "hash", sampleRate: 48_000,
- channelCount: 1, frameCount: 1
+ role: .captureAnalysis,
+ encoding: .linearPCMFloat32CAFV1,
+ presence: .ready,
+ relativeFilePath: pcmPath,
+ byteCount: 1,
+ sha256: "hash",
+ sampleRate: 48_000,
+ channelCount: 1,
+ frameCount: 1
)
)
session.audioTracks = [MeetingAudioTrack(
- id: UUID(), kind: .microphone, sourceIdentifier: "mic", sourceDisplayName: "Mic",
- format: nil, timebase: timebase, health: .waiting, chunks: [chunk]
+ id: UUID(),
+ kind: .microphone,
+ sourceIdentifier: "mic",
+ sourceDisplayName: "Mic",
+ format: nil,
+ timebase: timebase,
+ health: .waiting,
+ chunks: [chunk]
)]
XCTAssertEqual(MeetingAudioPresentation.firstPlaybackURL(in: session, directory: root), pcmURL)
var archivedChunk = chunk
archivedChunk.playbackArchiveAsset = MeetingAudioAsset(
- role: .playbackArchive, encoding: .aacLCM4AV1, presence: .ready,
- relativeFilePath: archivePath, byteCount: 1, sha256: "archive", sampleRate: 48_000,
- channelCount: 1, frameCount: 1, sourceAssetSHA256: "hash"
+ role: .playbackArchive,
+ encoding: .aacLCM4AV1,
+ presence: .ready,
+ relativeFilePath: archivePath,
+ byteCount: 1,
+ sha256: "archive",
+ sampleRate: 48_000,
+ channelCount: 1,
+ frameCount: 1,
+ sourceAssetSHA256: "hash"
)
session.audioTracks[0].chunks = [archivedChunk]
let archiveURL = root.appendingPathComponent(archivePath)
diff --git a/Tests/FluidDictationIntegrationTests/MeetingParakeetNemotronBackendTests.swift b/Tests/FluidDictationIntegrationTests/MeetingParakeetNemotronBackendTests.swift
index 24686007..4458a97d 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingParakeetNemotronBackendTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingParakeetNemotronBackendTests.swift
@@ -66,11 +66,17 @@ final class MeetingParakeetNemotronBackendTests: XCTestCase {
frameCount: Int64((duration * 16_000).rounded())
)
return MeetingAudioChunk(
- id: UUID(), sequence: sequence, relativeFilePath: "tracks/microphone/archive-\(sequence).m4a",
+ id: UUID(),
+ sequence: sequence,
+ relativeFilePath: "tracks/microphone/archive-\(sequence).m4a",
presentationStart: MeetingMediaTime(value: Int64((start * 1000).rounded()), timescale: 1000),
presentationEnd: MeetingMediaTime(value: Int64((end * 1000).rounded()), timescale: 1000),
- discontinuities: [], sha256: String(repeating: "a", count: 64), byteCount: 1,
- finalizationState: .finalized, audioSchemaVersion: 2, captureAnalysisAsset: asset
+ discontinuities: [],
+ sha256: String(repeating: "a", count: 64),
+ byteCount: 1,
+ finalizationState: .finalized,
+ audioSchemaVersion: 2,
+ captureAnalysisAsset: asset
)
}
@@ -384,17 +390,22 @@ final class MeetingParakeetNemotronBackendTests: XCTestCase {
let beyondBound = [
self.canonicalSegment(trackID: trackID, start: 0, end: 1.0, speakerID: speakerA, text: "First"),
self.canonicalSegment(
- trackID: trackID, start: 1.0 + gap + 0.01, end: 1.0 + gap + 0.51, speakerID: speakerA,
+ trackID: trackID,
+ start: 1.0 + gap + 0.01,
+ end: 1.0 + gap + 0.51,
+ speakerID: speakerA,
text: "Second"
),
]
XCTAssertEqual(
- MeetingProcessingPipeline.mergeCanonicalSegments(withinBound).count, 1,
+ MeetingProcessingPipeline.mergeCanonicalSegments(withinBound).count,
+ 1,
"a gap exactly at the named maximum still merges"
)
XCTAssertEqual(
- MeetingProcessingPipeline.mergeCanonicalSegments(beyondBound).count, 2,
+ MeetingProcessingPipeline.mergeCanonicalSegments(beyondBound).count,
+ 2,
"a gap past the named maximum starts a new turn"
)
}
@@ -417,11 +428,13 @@ final class MeetingParakeetNemotronBackendTests: XCTestCase {
]
XCTAssertEqual(
- MeetingProcessingPipeline.mergeCanonicalSegments(withinBound).count, 1,
+ MeetingProcessingPipeline.mergeCanonicalSegments(withinBound).count,
+ 1,
"a combined duration exactly at the named maximum still merges"
)
XCTAssertEqual(
- MeetingProcessingPipeline.mergeCanonicalSegments(beyondBound).count, 2,
+ MeetingProcessingPipeline.mergeCanonicalSegments(beyondBound).count,
+ 2,
"a combined duration past the named maximum starts a new turn even with no gap"
)
}
@@ -526,7 +539,7 @@ final class MeetingParakeetNemotronBackendTests: XCTestCase {
let backend = self.makeBackend(runtime: runtime, locator: locator)
let plan = try backend.plan(self.makeRequest(
session: fixture.session,
- directory: try self.makeTempSessionDirectory()
+ directory: self.makeTempSessionDirectory()
))
let manifest = try self.makeManifest(plan: plan, observations: fixture.observations)
locator.error = MeetingNemotronModelReadinessError.artifactChanged(
@@ -778,7 +791,7 @@ final class MeetingParakeetNemotronBackendTests: XCTestCase {
let backend = self.makeBackend(runtime: runtime, materializer: materializer)
let plan = try backend.plan(self.makeRequest(
session: session,
- directory: try self.makeTempSessionDirectory()
+ directory: self.makeTempSessionDirectory()
))
let manifest = try self.makeManifest(plan: plan, observations: [
MeetingAnalysisChunkKey(trackID: track.id, chunkID: chunk.id): self.makeObserved(chunk, duration: 1),
@@ -1071,7 +1084,7 @@ final class MeetingParakeetNemotronBackendTests: XCTestCase {
let backend = self.makeBackend(runtime: runtime, materializer: materializer)
let plan = try backend.plan(self.makeRequest(
session: session,
- directory: try self.makeTempSessionDirectory()
+ directory: self.makeTempSessionDirectory()
))
let manifest = try self.makeManifest(plan: plan, observations: [
MeetingAnalysisChunkKey(trackID: track.id, chunkID: chunk0.id): self.makeObserved(chunk0, duration: 1),
@@ -1083,7 +1096,7 @@ final class MeetingParakeetNemotronBackendTests: XCTestCase {
// Deliberately make the first one-second manifest span occupy only 0.5 seconds of the
// materialized buffer. A local time of 0.6 seconds must therefore map into span 2.
- materializer.customSpanSampleCounts[epoch.id] = [8_000, 16_000]
+ materializer.customSpanSampleCounts[epoch.id] = [8000, 16_000]
runtime.diarizerFactory.segmentsByEpoch[epoch.id] = [
MeetingNemotronSpeakerSegment(slotIndex: 3, start: 0.55, end: 0.75),
]
@@ -1221,8 +1234,10 @@ final class MeetingParakeetNemotronBackendTests: XCTestCase {
// Assembly accepts it as-is: no synthetic words exist.
_ = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(
- plan: plan, manifest: manifest,
- evidence: bundle.evidence, coverageReceipts: bundle.coverageReceipts
+ plan: plan,
+ manifest: manifest,
+ evidence: bundle.evidence,
+ coverageReceipts: bundle.coverageReceipts
))
}
@@ -1294,7 +1309,7 @@ final class MeetingParakeetNemotronBackendTests: XCTestCase {
// MARK: - Fakes
-fileprivate actor Latch {
+private actor Latch {
private var waiters: [CheckedContinuation<Void, Never>] = []
private var isOpen = false
@@ -1307,11 +1322,13 @@ fileprivate actor Latch {
self.isOpen = true
let parked = self.waiters
self.waiters.removeAll()
- for continuation in parked { continuation.resume() }
+ for continuation in parked {
+ continuation.resume()
+ }
}
}
-fileprivate final nonisolated class FakeDiarizerFactory: MeetingNemotronDiarizerFactory, @unchecked Sendable {
+private final nonisolated class FakeDiarizerFactory: MeetingNemotronDiarizerFactory, @unchecked Sendable {
struct Session: MeetingNemotronDiarizerSession {
let segments: [MeetingNemotronSpeakerSegment]
func diarize(samples _: [Float]) async throws -> [MeetingNemotronSpeakerSegment] {
@@ -1332,7 +1349,7 @@ fileprivate final nonisolated class FakeDiarizerFactory: MeetingNemotronDiarizer
}
}
-fileprivate final nonisolated class FakeASRSession: MeetingParakeetASRSession, @unchecked Sendable {
+private final nonisolated class FakeASRSession: MeetingParakeetASRSession, @unchecked Sendable {
struct Response {
let text: String
let words: [ASRWordTiming]
@@ -1361,7 +1378,7 @@ fileprivate final nonisolated class FakeASRSession: MeetingParakeetASRSession, @
}
}
-fileprivate final nonisolated class FakeRuntime: MeetingParakeetNemotronRunning, @unchecked Sendable {
+private final nonisolated class FakeRuntime: MeetingParakeetNemotronRunning, @unchecked Sendable {
let diarizerFactory = FakeDiarizerFactory()
let asrSession = FakeASRSession()
private(set) var diarizationScopeCount = 0
@@ -1387,7 +1404,7 @@ fileprivate final nonisolated class FakeRuntime: MeetingParakeetNemotronRunning,
}
}
-fileprivate final nonisolated class FakeMaterializer: MeetingEpochAudioMaterializing, @unchecked Sendable {
+private final nonisolated class FakeMaterializer: MeetingEpochAudioMaterializing, @unchecked Sendable {
var failingEpochs: Set<MeetingAnalysisEpochID> = []
var customSpanSampleCounts: [MeetingAnalysisEpochID: [Int]] = [:]
private(set) var materializedEpochs: [MeetingAnalysisEpochID] = []
@@ -1424,7 +1441,7 @@ fileprivate final nonisolated class FakeMaterializer: MeetingEpochAudioMateriali
}
}
-fileprivate final nonisolated class StubModelLocator: MeetingNemotronModelLocating, @unchecked Sendable {
+private final nonisolated class StubModelLocator: MeetingNemotronModelLocating, @unchecked Sendable {
var error: (any Error)?
static let artifact = MeetingNemotronModelArtifact(
packageURL: URL(fileURLWithPath: "/tmp/stub-nemotron.mlpackage"),
@@ -1449,7 +1466,6 @@ fileprivate final nonisolated class StubModelLocator: MeetingNemotronModelLocati
}
}
-
private final class LockedFlag: @unchecked Sendable {
private let lock = NSLock()
private var flag = false
diff --git a/Tests/FluidDictationIntegrationTests/MeetingPhase4Tests.swift b/Tests/FluidDictationIntegrationTests/MeetingPhase4Tests.swift
index 84acd291..68417c36 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingPhase4Tests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingPhase4Tests.swift
@@ -1,6 +1,6 @@
-@testable import FluidVoice_Debug
import AVFoundation
import CoreMedia
+@testable import FluidVoice_Debug
import Foundation
import XCTest
@@ -17,16 +17,26 @@ final class MeetingPhase4ClassificationTests: XCTestCase {
text: String
) -> MeetingTranscriptSegment {
MeetingTranscriptSegment(
- id: UUID(), start: self.mediaTime(start), end: self.mediaTime(end),
- sourceTrackID: trackID, speakerID: UUID(), text: text, revision: 0,
- status: .final, overlap: .none, completeness: .complete
+ id: UUID(),
+ start: self.mediaTime(start),
+ end: self.mediaTime(end),
+ sourceTrackID: trackID,
+ speakerID: UUID(),
+ text: text,
+ revision: 0,
+ status: .final,
+ overlap: .none,
+ completeness: .complete
)
}
private func singleEra(_ method: MeetingAudioTrackCaptureMethod?) -> [MeetingCaptureEra] {
[MeetingCaptureEra(
- method: method ?? .avCaptureSession, deviceUID: nil, deviceName: nil,
- roleAtElection: .unknown, startSeconds: 0
+ method: method ?? .avCaptureSession,
+ deviceUID: nil,
+ deviceName: nil,
+ roleAtElection: .unknown,
+ startSeconds: 0
)]
}
@@ -38,8 +48,14 @@ final class MeetingPhase4ClassificationTests: XCTestCase {
overlapsRemote: Bool
) -> MeetingProcessingPipeline.StagedMicrophoneTurn {
MeetingProcessingPipeline.StagedMicrophoneTurn(
- chunkID: UUID(), index: 0, clusterID: clusterID, clusterLabel: "spk",
- start: start, end: end, text: text, overlapsRemote: overlapsRemote
+ chunkID: UUID(),
+ index: 0,
+ clusterID: clusterID,
+ clusterLabel: "spk",
+ start: start,
+ end: end,
+ text: text,
+ overlapsRemote: overlapsRemote
)
}
@@ -57,8 +73,11 @@ final class MeetingPhase4ClassificationTests: XCTestCase {
let segments = [self.segment(trackID: appTrackID, start: 0, end: 3, text: echoedText)]
let (classified, widened) = MeetingProcessingPipeline.classifyMicrophoneTurns(
- turns, eras: self.singleEra(.voiceProcessing), applicationTrackID: appTrackID,
- segments: segments, fallbackSpeakerID: nil
+ turns,
+ eras: self.singleEra(.voiceProcessing),
+ applicationTrackID: appTrackID,
+ segments: segments,
+ fallbackSpeakerID: nil
)
XCTAssertTrue(classified.allSatisfy(\.echoScored), "every VPIO turn must end up scored")
@@ -99,7 +118,9 @@ final class MeetingPhase4ClassificationTests: XCTestCase {
self.turn(clusterID: userCluster, start: 0, end: 20, text: "user speech", overlapsRemote: false),
self.turn(clusterID: secondVoice, start: 20, end: 25, text: "second voice", overlapsRemote: false),
]
- for index in turns.indices { turns[index].echoScored = true }
+ for index in turns.indices {
+ turns[index].echoScored = true
+ }
let elected = MeetingProcessingPipeline.selectLocalCluster(
from: turns, prototypeSpeakerIDs: [userCluster, secondVoice]
)
@@ -113,7 +134,9 @@ final class MeetingPhase4ClassificationTests: XCTestCase {
self.turn(clusterID: userCluster, start: 0, end: 12, text: "user speech", overlapsRemote: false),
self.turn(clusterID: secondVoice, start: 12, end: 22, text: "second voice", overlapsRemote: false),
]
- for index in turns.indices { turns[index].echoScored = true }
+ for index in turns.indices {
+ turns[index].echoScored = true
+ }
let elected = MeetingProcessingPipeline.selectLocalCluster(
from: turns, prototypeSpeakerIDs: [userCluster, secondVoice]
)
@@ -133,15 +156,18 @@ final class MeetingPhase4ClassificationTests: XCTestCase {
]
let segments = [
self.segment(trackID: appTrackID, start: 0, end: 3, text: echoedText),
- self.segment(trackID: appTrackID, start: 10, end: 12, text: "fallback whole-chunk noise"),
+ self.segment(trackID: appTrackID, start: 10, end: 12, text: "fallback whole-chunk noise"),
]
var fallbackSegments = segments
fallbackSegments[1].speakerID = fallbackSpeaker
for captureMethod in [MeetingAudioTrackCaptureMethod?.none, .screenCaptureKit, .avCaptureSession] {
let (classified, widened) = MeetingProcessingPipeline.classifyMicrophoneTurns(
- turns, eras: self.singleEra(captureMethod), applicationTrackID: appTrackID,
- segments: fallbackSegments, fallbackSpeakerID: fallbackSpeaker
+ turns,
+ eras: self.singleEra(captureMethod),
+ applicationTrackID: appTrackID,
+ segments: fallbackSegments,
+ fallbackSpeakerID: fallbackSpeaker
)
XCTAssertTrue(widened.isEmpty, "non-VPIO never widens")
XCTAssertTrue(classified[0].echoScored)
@@ -158,8 +184,13 @@ final class MeetingPhase4ClassificationTests: XCTestCase {
var turn = self.turn(clusterID: userCluster, start: 0, end: 5, text: "hi", overlapsRemote: false)
turn.echoScored = true
MeetingProcessingPipeline.logLocalSpeakerElection(
- turns: [turn], prototypeSpeakerIDs: [userCluster], index: nil,
- role: .personal, elected: userCluster, captureMethod: .voiceProcessing, widenedIndices: [0]
+ turns: [turn],
+ prototypeSpeakerIDs: [userCluster],
+ index: nil,
+ role: .personal,
+ elected: userCluster,
+ captureMethod: .voiceProcessing,
+ widenedIndices: [0]
)
}
@@ -173,16 +204,21 @@ final class MeetingPhase4ClassificationTests: XCTestCase {
func testDecodedVoiceProcessingTrackDrivesWidening() throws {
var track = MeetingAudioTrack(
- id: UUID(), kind: .microphone, sourceIdentifier: "mic", sourceDisplayName: "Mic",
+ id: UUID(),
+ kind: .microphone,
+ sourceIdentifier: "mic",
+ sourceDisplayName: "Mic",
format: nil,
timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil),
- health: .waiting, chunks: [], captureMethod: .voiceProcessing
+ health: .waiting,
+ chunks: [],
+ captureMethod: .voiceProcessing
)
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
- track = try decoder.decode(MeetingAudioTrack.self, from: try encoder.encode(track))
+ track = try decoder.decode(MeetingAudioTrack.self, from: encoder.encode(track))
XCTAssertEqual(track.captureMethod, .voiceProcessing, "sanity: the round-trip preserved captureMethod")
let turns = [self.turn(start: 0, end: 5, text: "local speech", overlapsRemote: false)]
@@ -198,10 +234,16 @@ final class MeetingPhase4ClassificationTests: XCTestCase {
final class MeetingPhase4LiveGatingTests: XCTestCase {
private func sampleBuffer(ptsSeconds: Double) -> CMSampleBuffer {
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 1, interleaved: false)!
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 480)!
buffer.frameLength = 480
let pts = CMTime(seconds: ptsSeconds, preferredTimescale: 48_000)
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
return meetingMicrophoneSynthesizeSampleBuffer(from: buffer, presentationTime: pts)!
}
@@ -220,12 +262,16 @@ final class MeetingPhase4LiveGatingTests: XCTestCase {
let echoText = "let's push the release to next Tuesday afternoon"
coordinator.handleUtterance(
- kind: .applicationAudio, text: echoText,
- start: CMTime(seconds: 10, preferredTimescale: 1), end: CMTime(seconds: 14, preferredTimescale: 1)
+ kind: .applicationAudio,
+ text: echoText,
+ start: CMTime(seconds: 10, preferredTimescale: 1),
+ end: CMTime(seconds: 14, preferredTimescale: 1)
)
coordinator.handleUtterance(
- kind: .microphone, text: echoText,
- start: CMTime(seconds: 15, preferredTimescale: 1), end: CMTime(seconds: 16, preferredTimescale: 1)
+ kind: .microphone,
+ text: echoText,
+ start: CMTime(seconds: 15, preferredTimescale: 1),
+ end: CMTime(seconds: 16, preferredTimescale: 1)
)
let last = lock.withLock { snapshots.last }
@@ -239,12 +285,16 @@ final class MeetingPhase4LiveGatingTests: XCTestCase {
let echoText = "let's push the release to next Tuesday afternoon"
coordinator.handleUtterance(
- kind: .applicationAudio, text: echoText,
- start: CMTime(seconds: 10, preferredTimescale: 1), end: CMTime(seconds: 14, preferredTimescale: 1)
+ kind: .applicationAudio,
+ text: echoText,
+ start: CMTime(seconds: 10, preferredTimescale: 1),
+ end: CMTime(seconds: 14, preferredTimescale: 1)
)
coordinator.handleUtterance(
- kind: .microphone, text: echoText,
- start: CMTime(seconds: 15, preferredTimescale: 1), end: CMTime(seconds: 16, preferredTimescale: 1)
+ kind: .microphone,
+ text: echoText,
+ start: CMTime(seconds: 15, preferredTimescale: 1),
+ end: CMTime(seconds: 16, preferredTimescale: 1)
)
let all = lock.withLock { snapshots }
@@ -258,17 +308,23 @@ final class MeetingPhase4LiveGatingTests: XCTestCase {
let echoText = "let's push the release to next Tuesday afternoon"
coordinator.handleUtterance(
- kind: .applicationAudio, text: echoText,
- start: CMTime(seconds: 10, preferredTimescale: 1), end: CMTime(seconds: 14, preferredTimescale: 1)
+ kind: .applicationAudio,
+ text: echoText,
+ start: CMTime(seconds: 10, preferredTimescale: 1),
+ end: CMTime(seconds: 14, preferredTimescale: 1)
)
coordinator.handleUtterance(
- kind: .microphone, text: echoText,
- start: CMTime(seconds: 15, preferredTimescale: 1), end: CMTime(seconds: 16, preferredTimescale: 1)
+ kind: .microphone,
+ text: echoText,
+ start: CMTime(seconds: 15, preferredTimescale: 1),
+ end: CMTime(seconds: 16, preferredTimescale: 1)
)
coordinator.setMicrophoneCaptureMethod(.voiceProcessing)
coordinator.handleUtterance(
- kind: .microphone, text: "a fresh genuine utterance",
- start: CMTime(seconds: 17, preferredTimescale: 1), end: CMTime(seconds: 18, preferredTimescale: 1)
+ kind: .microphone,
+ text: "a fresh genuine utterance",
+ start: CMTime(seconds: 17, preferredTimescale: 1),
+ end: CMTime(seconds: 18, preferredTimescale: 1)
)
let last = lock.withLock { snapshots.last }
diff --git a/Tests/FluidDictationIntegrationTests/MeetingProviderOptionsTests.swift b/Tests/FluidDictationIntegrationTests/MeetingProviderOptionsTests.swift
index 4e524369..527cbc12 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingProviderOptionsTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingProviderOptionsTests.swift
@@ -20,7 +20,7 @@ final class MeetingProviderOptionsTests: XCTestCase {
func testResolveRejectsUnsupportedModelsWithoutRelabeling() {
let unsupportedModels = [
- "parakeet-tdt", // raw value of the v3 multilingual model
+ "parakeet-tdt", // raw value of the v3 multilingual model
"parakeet-tdt-v3",
"parakeet-tdt-v99",
"whisper-tiny",
diff --git a/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift b/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift
index b04a6af5..1d2bc558 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingRecoveryTests.swift
@@ -1,3 +1,5 @@
+// Existing end-to-end fixture suite is kept together to share its setup and helpers.
+// swiftlint:disable file_length
import AppKit
import CoreMedia
@testable import FluidVoice_Debug
@@ -6,6 +8,8 @@ import SwiftUI
import XCTest
@MainActor
+// Existing recovery suite shares setup across crash and corruption scenarios.
+// swiftlint:disable:next type_body_length
final class MeetingRecoveryTests: XCTestCase {
func testNotesSetupDraftDoesNotPersistDetectionChanges() {
let native = SettingsStore.shared.meetingAutoDetectEnabled
@@ -143,7 +147,9 @@ final class MeetingRecoveryTests: XCTestCase {
for width in [CGFloat(520), 1000] {
try self.renderMeetingUI(
self.meetingUICanvas(draft: draft, readiness: readiness, fixture: fixture, actions: actions),
- name: name, width: width, scheme: scheme
+ name: name,
+ width: width,
+ scheme: scheme
)
}
}
@@ -186,7 +192,9 @@ final class MeetingRecoveryTests: XCTestCase {
warning: base.palette.warning,
success: base.palette.success
),
- typography: base.typography, metrics: base.metrics, materials: base.materials
+ typography: base.typography,
+ metrics: base.metrics,
+ materials: base.materials
)
for section in [MeetingDocumentSection.transcript, .summary] {
for horizontal in [true, false] {
@@ -206,8 +214,11 @@ final class MeetingRecoveryTests: XCTestCase {
}
let context = "\(horizontal ? "hstack" : "vstack")-\(section)-\(scheme)"
let bitmap = try self.renderMeetingUI(
- ancestor.appTheme(probeTheme), name: "tabs-baseline-\(context)",
- width: 500, height: 140, scheme: scheme
+ ancestor.appTheme(probeTheme),
+ name: "tabs-baseline-\(context)",
+ width: 500,
+ height: 140,
+ scheme: scheme
)
let scale = CGFloat(bitmap.pixelsWide) / 500
// Color-managed capture can shift RGB values; classify hue, not exact pixels.
@@ -235,7 +246,9 @@ final class MeetingRecoveryTests: XCTestCase {
let bitmap = try self.renderMeetingUI(
highlight,
name: "hover-\(enabled)-\(hovered)-\(reducedMotion)",
- width: 160, height: 80, scheme: scheme
+ width: 160,
+ height: 80,
+ scheme: scheme
)
let bounds = self.meetingUIPixelBounds(in: bitmap) { color, _ in color.alphaComponent > 0.01 }
if enabled, hovered {
@@ -309,10 +322,15 @@ final class MeetingRecoveryTests: XCTestCase {
for width in [CGFloat(520), 1000] {
try self.renderMeetingUI(
self.meetingUICanvas(
- draft: fixture.draft, readiness: fixture.readiness, fixture: fixture,
- actions: actions, state: .result(result)
+ draft: fixture.draft,
+ readiness: fixture.readiness,
+ fixture: fixture,
+ actions: actions,
+ state: .result(result)
),
- name: name, width: width, scheme: scheme
+ name: name,
+ width: width,
+ scheme: scheme
)
}
}
@@ -338,10 +356,16 @@ final class MeetingRecoveryTests: XCTestCase {
for scheme in [ColorScheme.dark, .light] {
try self.renderMeetingUI(
self.meetingUICanvas(
- draft: fixture.draft, readiness: fixture.readiness, fixture: fixture,
- actions: actions, state: state
+ draft: fixture.draft,
+ readiness: fixture.readiness,
+ fixture: fixture,
+ actions: actions,
+ state: state
),
- name: "recording-short-window", width: 520, height: 500, scheme: scheme
+ name: "recording-short-window",
+ width: 520,
+ height: 500,
+ scheme: scheme
)
}
XCTAssertEqual(actions.count, 0, "Rendering recording controls must not start or stop real audio capture")
@@ -417,11 +441,16 @@ final class MeetingRecoveryTests: XCTestCase {
microphones: [microphone],
readiness: MeetingSetupReadiness(
isCheckingSources: false,
- meetingAudioStatus: "Ready", meetingAudioReady: true,
- microphoneStatus: "Ready", microphoneReady: true,
- modelStatus: "Speaker model installed", modelReady: true,
- storageStatus: "120 GB available", storageReady: true,
- activityStatus: "Ready", activityReady: true,
+ meetingAudioStatus: "Ready",
+ meetingAudioReady: true,
+ microphoneStatus: "Ready",
+ microphoneReady: true,
+ modelStatus: "Speaker model installed",
+ modelReady: true,
+ storageStatus: "120 GB available",
+ storageReady: true,
+ activityStatus: "Ready",
+ activityReady: true,
showMicrophoneSettingsAction: false,
showScreenRecordingSettingsAction: false,
blockingMessage: nil
@@ -475,7 +504,8 @@ final class MeetingRecoveryTests: XCTestCase {
application.sourceDisplayName = "Zoom Workplace"
let startedAt = Date(timeIntervalSince1970: 1_789_996_800)
var session = self.makeSession(
- state: .completed, startedAt: startedAt,
+ state: .completed,
+ startedAt: startedAt,
endedAt: startedAt.addingTimeInterval(32 * 60 + 18),
audioTracks: [microphone, application]
)
@@ -491,16 +521,50 @@ final class MeetingRecoveryTests: XCTestCase {
session.speakers = [local, amelia, rafael]
let turns: [(MeetingSessionSpeaker?, String)] = [
- (local, "Let's start with what someone needs in their first thirty seconds. They should know which meeting we are capturing, see that their microphone is ready, and find the recording control without having to read a settings page."),
- (local, "Once a conversation has finished, the transcript should read like a document. Keep the title and date nearby, but let the words take up most of the space. We can move less common actions into the menu."),
- (amelia, "I agree. In the interviews, people went back to a meeting because they remembered a decision, not because they wanted to inspect a recording. The first screen should help them recognize the conversation and pick up where they left off."),
- (rafael, "The longer examples matter here. A one-line transcript looks fine in almost any layout. We need to see what happens with several speakers, names that wrap, and a paragraph that takes more than two lines on a small laptop."),
- (amelia, "For speaker corrections, I would keep the name close to the passage. If I notice that the wrong person has been assigned, I should be able to fix it there and continue reading without losing my place."),
- (nil, "Could we also make it clear when the recording contains an overlap that the model cannot confidently assign? An honest unknown label is more useful than attributing the statement to the wrong person."),
- (local, "Yes. We should preserve uncertain attribution and avoid making the interface look more confident than the transcript is. The correction remains a deliberate action, and the original recording stays available until the retention policy removes it."),
- (rafael, "For the launch review, I will test the smallest supported window and both appearances. I will also check a meeting that has no readable transcript, so the recovery action is still obvious when someone needs it."),
- (amelia, "I'll collect three longer conversations for the design review. We should compare the same content each time, including one where the speaker names are much longer than the labels in our initial mockup."),
- (local, "The next step is to review those examples together on Thursday. We can then decide whether the meeting list, transcript width, and primary actions feel consistent with the rest of the app."),
+ (
+ local,
+ "Let's start with what someone needs in their first thirty seconds. They should know which meeting we are capturing, see that their microphone is ready, and find the recording control without having to read a settings page."
+ ),
+ (
+ local,
+ "Once a conversation has finished, the transcript should read like a document. Keep the title and date nearby, but let the words take up most of the space. We can move less common actions into the menu."
+ ),
+ (
+ amelia,
+ // Keep the exact fixture text or diagnostic output together for comparison.
+ // swiftlint:disable:next line_length
+ "I agree. In the interviews, people went back to a meeting because they remembered a decision, not because they wanted to inspect a recording. The first screen should help them recognize the conversation and pick up where they left off."
+ ),
+ (
+ rafael,
+ "The longer examples matter here. A one-line transcript looks fine in almost any layout. We need to see what happens with several speakers, names that wrap, and a paragraph that takes more than two lines on a small laptop."
+ ),
+ (
+ amelia,
+ "For speaker corrections, I would keep the name close to the passage. If I notice that the wrong person has been assigned, I should be able to fix it there and continue reading without losing my place."
+ ),
+ (
+ nil,
+ "Could we also make it clear when the recording contains an overlap that the model cannot confidently assign? An honest unknown label is more useful than attributing the statement to the wrong person."
+ ),
+ (
+ local,
+ // Keep the exact fixture text or diagnostic output together for comparison.
+ // swiftlint:disable:next line_length
+ "Yes. We should preserve uncertain attribution and avoid making the interface look more confident than the transcript is. The correction remains a deliberate action, and the original recording stays available until the retention policy removes it."
+ ),
+ (
+ rafael,
+ "For the launch review, I will test the smallest supported window and both appearances. I will also check a meeting that has no readable transcript, so the recovery action is still obvious when someone needs it."
+ ),
+ (
+ amelia,
+ "I'll collect three longer conversations for the design review. We should compare the same content each time, including one where the speaker names are much longer than the labels in our initial mockup."
+ ),
+ (
+ local,
+ "The next step is to review those examples together on Thursday. We can then decide whether the meeting list, transcript width, and primary actions feel consistent with the rest of the app."
+ ),
]
session.transcriptSegments = turns.enumerated().map { index, turn in
let trackID = turn.0?.isLocalUser == true ? microphone.id : application.id
@@ -551,7 +615,9 @@ final class MeetingRecoveryTests: XCTestCase {
let host = NSHostingView(rootView: canvas)
let window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: width, height: height),
- styleMask: [.borderless], backing: .buffered, defer: false
+ styleMask: [.borderless],
+ backing: .buffered,
+ defer: false
)
window.isReleasedWhenClosed = false
window.appearance = NSAppearance(named: scheme == .dark ? .darkAqua : .aqua)
@@ -1076,7 +1142,7 @@ final class MeetingRecoveryTests: XCTestCase {
try await store.create(session)
let url = dir.appendingPathComponent(session.id.uuidString).appendingPathComponent("session.json")
- var json = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as! [String: Any]
+ var json = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])
json.removeValue(forKey: "recoveryResolvedAt")
try JSONSerialization.data(withJSONObject: json).write(to: url)
@@ -1536,13 +1602,21 @@ final class MeetingRecoveryTests: XCTestCase {
let store = MeetingSessionStore(rootDirectory: dir)
let past = Date(timeIntervalSinceNow: -40 * 24 * 60 * 60)
let old = self.makeSession(
- state: .interrupted, startedAt: past, endedAt: past,
+ state: .interrupted,
+ startedAt: past,
+ endedAt: past,
audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])],
processingAttempts: [MeetingProcessingAttempt(
- id: UUID(), startedAt: past, completedAt: nil, stage: .pending,
+ id: UUID(),
+ startedAt: past,
+ completedAt: nil,
+ stage: .pending,
pipelineVersion: MeetingProcessingPipeline.pipelineVersion,
- asrProvider: nil, asrModel: nil, diarizationModel: nil,
- lastCompletedTrackID: nil, errorCode: nil
+ asrProvider: nil,
+ asrModel: nil,
+ diarizationModel: nil,
+ lastCompletedTrackID: nil,
+ errorCode: nil
)]
)
try await store.create(old)
@@ -1668,8 +1742,10 @@ final class MeetingRecoveryTests: XCTestCase {
var continuation: CheckedContinuation<Void, Never>?
capture.onPreflight = { await withCheckedContinuation { continuation = $0 } }
let coordinator = MeetingSessionCoordinator(
- store: MeetingSessionStore(rootDirectory: dir), capture: capture,
- processing: StubProcessingController(), audioArbiter: StubArbiter()
+ store: MeetingSessionStore(rootDirectory: dir),
+ capture: capture,
+ processing: StubProcessingController(),
+ audioArbiter: StubArbiter()
)
let start = Task { try await coordinator.startRecording(configuration: self.makeConfiguration()) }
while capture.preflightCount == 0 {
@@ -1805,7 +1881,9 @@ final class MeetingRecoveryTests: XCTestCase {
let fingerprints: [MeetingAudioTrackID: [MeetingProcessingCheckpoint.ChunkFingerprint]] = [trackID: [fingerprint]]
let checkpoint = self.makeCheckpoint(
- sessionID: session.id, completedTrackID: trackID, trackFingerprints: fingerprints,
+ sessionID: session.id,
+ completedTrackID: trackID,
+ trackFingerprints: fingerprints,
asrModel: "parakeet-tdt-v2"
)
@@ -2919,24 +2997,34 @@ final class MeetingRecoveryTests: XCTestCase {
let future = Date()
let completedPast = self.makeSession(
- state: .completed, startedAt: past, endedAt: past,
+ state: .completed,
+ startedAt: past,
+ endedAt: past,
audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]
)
let completedFuture = self.makeSession(
- state: .completed, startedAt: future, endedAt: future,
+ state: .completed,
+ startedAt: future,
+ endedAt: future,
audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]
)
let interruptedUnresolvedPast = self.makeSession(
- state: .interrupted, startedAt: past, endedAt: past,
+ state: .interrupted,
+ startedAt: past,
+ endedAt: past,
audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]
)
let failedResolvedPast = self.makeSession(
- state: .failed, startedAt: past, endedAt: past,
+ state: .failed,
+ startedAt: past,
+ endedAt: past,
audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])],
recoveryResolvedAt: Date()
)
let failedUnresolvedPast = self.makeSession(
- state: .failed, startedAt: past, endedAt: past,
+ state: .failed,
+ startedAt: past,
+ endedAt: past,
audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]
)
for session in [completedPast, completedFuture, interruptedUnresolvedPast, failedResolvedPast, failedUnresolvedPast] {
@@ -2987,7 +3075,9 @@ final class MeetingRecoveryTests: XCTestCase {
defer { try? FileManager.default.removeItem(at: dir2) }
let store2 = MeetingSessionStore(rootDirectory: dir2)
let justCompleted = self.makeSession(
- state: .completed, startedAt: Date(), endedAt: Date(),
+ state: .completed,
+ startedAt: Date(),
+ endedAt: Date(),
audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]
)
try await store2.create(justCompleted)
@@ -3009,7 +3099,9 @@ final class MeetingRecoveryTests: XCTestCase {
defer { try? FileManager.default.removeItem(at: dir) }
let store = MeetingSessionStore(rootDirectory: dir)
let session = self.makeSession(
- state: .completed, startedAt: endedAt, endedAt: endedAt,
+ state: .completed,
+ startedAt: endedAt,
+ endedAt: endedAt,
audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]
)
try await store.create(session)
@@ -3034,7 +3126,8 @@ final class MeetingRecoveryTests: XCTestCase {
defer { try? FileManager.default.removeItem(at: dir) }
let store = MeetingSessionStore(rootDirectory: dir)
let session = self.makeSession(
- state: .interrupted, endedAt: Date(),
+ state: .interrupted,
+ endedAt: Date(),
audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]
)
try await store.create(session)
@@ -3067,7 +3160,8 @@ final class MeetingRecoveryTests: XCTestCase {
defer { try? FileManager.default.removeItem(at: dir) }
let store = MeetingSessionStore(rootDirectory: dir)
let session = self.makeSession(
- state: .interrupted, endedAt: Date(),
+ state: .interrupted,
+ endedAt: Date(),
audioTracks: [self.makeMicrophoneTrack(chunks: [self.makeFinalizedChunk()])]
)
try await store.create(session)
diff --git a/Tests/FluidDictationIntegrationTests/MeetingReferenceAttributionContractsTests.swift b/Tests/FluidDictationIntegrationTests/MeetingReferenceAttributionContractsTests.swift
index 9f0cd886..cea5f668 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingReferenceAttributionContractsTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingReferenceAttributionContractsTests.swift
@@ -1,7 +1,9 @@
+@testable import FluidVoice_Debug
import Foundation
import XCTest
-@testable import FluidVoice_Debug
+// Match the production component name so its regression suite is easy to find.
+// swiftlint:disable:next type_name
final class MeetingReferenceAttributionContractsTests: XCTestCase {
private func result(
_ outcome: MeetingReferenceAttributionOutcome,
@@ -13,33 +15,61 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
reasons: [MeetingReferenceAttributionReasonCode] = []
) -> MeetingReferenceAttributionFrameResult {
MeetingReferenceAttributionFrameResult(
- frameIndex: index, epoch: epoch, startSeconds: Double(index) * duration,
- durationSeconds: duration, outcome: outcome, speechState: speech,
- residualVariant: residual, reasons: reasons,
+ frameIndex: index,
+ epoch: epoch,
+ startSeconds: Double(index) * duration,
+ durationSeconds: duration,
+ outcome: outcome,
+ speechState: speech,
+ residualVariant: residual,
+ reasons: reasons,
metrics: MeetingReferenceAttributionMetrics(
- delaySeconds: 0.04, convergence: 0.9, erlDB: 5, erleDB: 12,
- originalEnergy: 1, residualEnergy: 0.25,
- residualToOriginalEnergyRatio: 0.25),
- fallback: outcome == .unscored ? .originalMicrophone : .none)
+ delaySeconds: 0.04,
+ convergence: 0.9,
+ erlDB: 5,
+ erleDB: 12,
+ originalEnergy: 1,
+ residualEnergy: 0.25,
+ residualToOriginalEnergyRatio: 0.25
+ ),
+ fallback: outcome == .unscored ? .originalMicrophone : .none
+ )
}
func testSidecarJSONRoundTripIsNumericOnlyAndPreservesResidualIdentity() throws {
let configuration = MeetingReferenceAttributionConfiguration(candidateID: "native-multiband")
let identity = MeetingReferenceAttributionEngineIdentity(
- engineID: "native-multiband", engineVersion: "candidate-a-v1",
+ engineID: "native-multiband",
+ engineVersion: "candidate-a-v1",
sourceHashes: [
.init(name: "accelerate", hash: "sha256:abc"),
- .init(name: "source", hash: "sha256:def")
- ], buildHash: "sha256:build", configurationHash: configuration.configurationHash)
+ .init(name: "source", hash: "sha256:def"),
+ ], buildHash: "sha256:build",
+ configurationHash: configuration.configurationHash
+ )
let frames = [
- result(.acceptedNearEndSpeech, duration: 0.1, speech: .nearEndSpeech,
- residual: .linearResidual, reasons: [.residualSpeechDetected]),
- result(.likelyPlaybackOnly, duration: 0.1, index: 1, speech: .noSpeech,
- residual: .suppressedResidual, reasons: [.playbackAttributed])
+ result(
+ .acceptedNearEndSpeech,
+ duration: 0.1,
+ speech: .nearEndSpeech,
+ residual: .linearResidual,
+ reasons: [.residualSpeechDetected]
+ ),
+ result(
+ .likelyPlaybackOnly,
+ duration: 0.1,
+ index: 1,
+ speech: .noSpeech,
+ residual: .suppressedResidual,
+ reasons: [.playbackAttributed]
+ ),
]
let sidecar = MeetingReferenceAttributionSidecar(
- engineIdentity: identity, configuration: configuration,
- epochs: [.init(epoch: 0)], frameResults: frames)
+ engineIdentity: identity,
+ configuration: configuration,
+ epochs: [.init(epoch: 0)],
+ frameResults: frames
+ )
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys]
let data = try encoder.encode(sidecar)
@@ -47,8 +77,13 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
XCTAssertEqual(decoded, sidecar)
XCTAssertEqual(sidecar.sidecarHash, MeetingReferenceAttributionSidecar(
- engineIdentity: identity, configuration: configuration,
- epochs: [.init(epoch: 0)], frameResults: frames).sidecarHash)
+ engineIdentity: identity,
+ configuration: configuration,
+ epochs: [.init(epoch: 0)],
+ frameResults: frames
+ ).sidecarHash)
+ // JSONEncoder fixture bytes are UTF-8; retain nonoptional decoding for assertions.
+ // swiftlint:disable:next optional_data_string_conversion
let json = String(decoding: data, as: UTF8.self)
for forbidden in ["samples", "transcript", "embedding", "windowTitle", "absolutePath"] {
XCTAssertFalse(json.contains(forbidden), "sidecar leaked (forbidden)")
@@ -59,18 +94,31 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
func testCanonicalEncodingSortsCountEntriesAndInputOrderDoesNotAffectHash() throws {
let configuration = MeetingReferenceAttributionConfiguration(candidateID: "canonical")
let identity = MeetingReferenceAttributionEngineIdentity(
- engineID: "engine", engineVersion: "1", configuration: configuration)
- let first = result(.acceptedNearEndSpeech, duration: 0.1, index: 0,
- speech: .nearEndSpeech,
- reasons: [.residualSpeechDetected, .mixedEvidence])
- let second = result(.unscored, duration: 0.2, index: 1,
- reasons: [.referenceGap, .unknownSpeechState])
+ engineID: "engine", engineVersion: "1", configuration: configuration
+ )
+ let first = self.result(
+ .acceptedNearEndSpeech,
+ duration: 0.1,
+ index: 0,
+ speech: .nearEndSpeech,
+ reasons: [.residualSpeechDetected, .mixedEvidence]
+ )
+ let second = self.result(
+ .unscored,
+ duration: 0.2,
+ index: 1,
+ reasons: [.referenceGap, .unknownSpeechState]
+ )
let left = MeetingReferenceAttributionSidecar(
- engineIdentity: identity, configuration: configuration,
- frameResults: [first, second])
+ engineIdentity: identity,
+ configuration: configuration,
+ frameResults: [first, second]
+ )
let right = MeetingReferenceAttributionSidecar(
- engineIdentity: identity, configuration: configuration,
- frameResults: [second, first])
+ engineIdentity: identity,
+ configuration: configuration,
+ frameResults: [second, first]
+ )
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys]
let leftData = try encoder.encode(left)
@@ -83,14 +131,21 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
XCTAssertTrue(aggregate["outcomeCounts"] is [[String: Any]])
XCTAssertTrue(aggregate["reasonCounts"] is [[String: Any]])
let entries = try XCTUnwrap(aggregate["reasonCounts"] as? [[String: Any]])
- XCTAssertEqual(entries.compactMap { $0["reason"] as? String },
- entries.compactMap { $0["reason"] as? String }.sorted())
+ XCTAssertEqual(
+ entries.compactMap { $0["reason"] as? String },
+ entries.compactMap { $0["reason"] as? String }.sorted()
+ )
}
func testFailOpenPreservesUnknownAndOriginalFallback() {
let frame = MeetingReferenceAttributionFrame(
- frameIndex: 4, epoch: 2, startSeconds: .nan, durationSeconds: .nan,
- microphone: .init(samples: [0], valid: [true]), reference: nil)
+ frameIndex: 4,
+ epoch: 2,
+ startSeconds: .nan,
+ durationSeconds: .nan,
+ microphone: .init(samples: [0], valid: [true]),
+ reference: nil
+ )
let output = MeetingReferenceAttributionFrameResult.failOpen(frame: frame, reason: .referenceAbsent)
XCTAssertEqual(output.outcome, .unscored)
@@ -103,8 +158,13 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
XCTAssertFalse(output.reasons.contains(.noSpeechMeasured))
let unsafe = MeetingReferenceAttributionFrameResult(
- frameIndex: 0, epoch: 0, startSeconds: 0, durationSeconds: 0.01,
- outcome: .acceptedNearEndSpeech, speechState: .unknown)
+ frameIndex: 0,
+ epoch: 0,
+ startSeconds: 0,
+ durationSeconds: 0.01,
+ outcome: .acceptedNearEndSpeech,
+ speechState: .unknown
+ )
XCTAssertEqual(unsafe.outcome, .unscored)
XCTAssertEqual(unsafe.fallback, .originalMicrophone)
}
@@ -115,25 +175,31 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
result(.acceptedNearEndSpeech, duration: 0.3, index: 1, speech: .nearEndSpeech),
result(.mixedOrUncertain, duration: 0.2, index: 2, speech: .mixedSpeech),
result(.scopeLimited, duration: 0.1, index: 3, reasons: [.referenceScopeLimited]),
- result(.unscored, duration: 0.3, index: 4, reasons: [.referenceGap, .unknownSpeechState])
+ result(.unscored, duration: 0.3, index: 4, reasons: [.referenceGap, .unknownSpeechState]),
]
let aggregate = MeetingReferenceAttributionAggregate(frameResults: frames)
- XCTAssertEqual(aggregate.coverage.totalDurationSeconds, 1, accuracy: 0.000001)
- XCTAssertEqual(aggregate.coverage.scoredDurationSeconds, 0.6, accuracy: 0.000001)
- XCTAssertEqual(aggregate.coverage.likelyPlaybackOnlyDurationSeconds, 0.1, accuracy: 0.000001)
- XCTAssertEqual(aggregate.coverage.acceptedNearEndSpeechDurationSeconds, 0.3, accuracy: 0.000001)
- XCTAssertEqual(aggregate.coverage.unscoredFraction, 0.3, accuracy: 0.000001)
+ XCTAssertEqual(aggregate.coverage.totalDurationSeconds, 1, accuracy: 0.000_001)
+ XCTAssertEqual(aggregate.coverage.scoredDurationSeconds, 0.6, accuracy: 0.000_001)
+ XCTAssertEqual(aggregate.coverage.likelyPlaybackOnlyDurationSeconds, 0.1, accuracy: 0.000_001)
+ XCTAssertEqual(aggregate.coverage.acceptedNearEndSpeechDurationSeconds, 0.3, accuracy: 0.000_001)
+ XCTAssertEqual(aggregate.coverage.unscoredFraction, 0.3, accuracy: 0.000_001)
XCTAssertEqual(aggregate.outcomeCounts[.acceptedNearEndSpeech], 1)
XCTAssertEqual(aggregate.outcomeCounts[.unscored], 1)
XCTAssertEqual(aggregate.reasonCounts[.referenceGap], 1)
}
func testScopeLimitedAndUnknownRemainDistinctFromMeasuredNoSpeech() {
- let scopeLimited = result(.scopeLimited, duration: 0.1, reasons: [.referenceScopeLimited])
- let unknown = result(.unscored, duration: 0.1, index: 1, reasons: [.referenceAbsent, .unknownSpeechState])
- let silence = result(.likelyPlaybackOnly, duration: 0.1, index: 2, speech: .silence,
- residual: .suppressedResidual, reasons: [.silenceMeasured])
+ let scopeLimited = self.result(.scopeLimited, duration: 0.1, reasons: [.referenceScopeLimited])
+ let unknown = self.result(.unscored, duration: 0.1, index: 1, reasons: [.referenceAbsent, .unknownSpeechState])
+ let silence = self.result(
+ .likelyPlaybackOnly,
+ duration: 0.1,
+ index: 2,
+ speech: .silence,
+ residual: .suppressedResidual,
+ reasons: [.silenceMeasured]
+ )
let aggregate = MeetingReferenceAttributionAggregate(frameResults: [scopeLimited, unknown, silence])
XCTAssertEqual(aggregate.outcomeCounts[.scopeLimited], 1)
@@ -150,25 +216,37 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
XCTAssertEqual(first.configurationHash, second.configurationHash)
let one = MeetingReferenceAttributionEngineIdentity(
- engineID: "engine", engineVersion: "1",
+ engineID: "engine",
+ engineVersion: "1",
sourceHashes: [.init(name: "z", hash: "2"), .init(name: "a", hash: "1")],
- configurationHash: first.configurationHash)
+ configurationHash: first.configurationHash
+ )
let two = MeetingReferenceAttributionEngineIdentity(
- engineID: "engine", engineVersion: "1",
+ engineID: "engine",
+ engineVersion: "1",
sourceHashes: [.init(name: "a", hash: "1"), .init(name: "z", hash: "2")],
- configurationHash: second.configurationHash)
+ configurationHash: second.configurationHash
+ )
XCTAssertEqual(one.stableIdentity, two.stableIdentity)
XCTAssertNotEqual(one.stableIdentity, MeetingReferenceAttributionEngineIdentity(
- engineID: "different", engineVersion: "1", configurationHash: first.configurationHash).stableIdentity)
+ engineID: "different", engineVersion: "1", configurationHash: first.configurationHash
+ ).stableIdentity)
}
func testInvalidNonFiniteMetricsAndCoverageDoNotBecomeMeasuredValues() {
let metrics = MeetingReferenceAttributionMetrics(
- delaySeconds: .infinity, delayJitterSeconds: -.nan, convergence: 2,
- erlDB: .nan, erleDB: -.infinity, candidateScore: -0.1,
- originalEnergy: -.infinity, residualEnergy: .nan,
- residualToOriginalEnergyRatio: -0.1, processingMilliseconds: .nan,
- peakMemoryBytes: -1)
+ delaySeconds: .infinity,
+ delayJitterSeconds: -.nan,
+ convergence: 2,
+ erlDB: .nan,
+ erleDB: -.infinity,
+ candidateScore: -0.1,
+ originalEnergy: -.infinity,
+ residualEnergy: .nan,
+ residualToOriginalEnergyRatio: -0.1,
+ processingMilliseconds: .nan,
+ peakMemoryBytes: -1
+ )
XCTAssertNil(metrics.delaySeconds)
XCTAssertNil(metrics.delayJitterSeconds)
XCTAssertNil(metrics.convergence)
@@ -181,39 +259,61 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
XCTAssertNil(metrics.peakMemoryBytes)
XCTAssertNil(MeetingReferenceAttributionCoverage(
- totalDurationSeconds: 1, scoredDurationSeconds: 1.1,
- likelyPlaybackOnlyDurationSeconds: 0, acceptedNearEndSpeechDurationSeconds: 0,
- mixedOrUncertainDurationSeconds: 0, scopeLimitedDurationSeconds: 0,
- unscoredDurationSeconds: 0, frameCount: 1))
+ totalDurationSeconds: 1,
+ scoredDurationSeconds: 1.1,
+ likelyPlaybackOnlyDurationSeconds: 0,
+ acceptedNearEndSpeechDurationSeconds: 0,
+ mixedOrUncertainDurationSeconds: 0,
+ scopeLimitedDurationSeconds: 0,
+ unscoredDurationSeconds: 0,
+ frameCount: 1
+ ))
}
func testFrameValidationRejectsBadShapeNonFinitePCMAndOverflowTiming() {
let badShape = MeetingReferenceAttributionFrame(
- frameIndex: 0, epoch: 0, startSeconds: 0, durationSeconds: 0.01,
- microphone: .init(samples: [0, 1], valid: [true]), reference: nil)
+ frameIndex: 0,
+ epoch: 0,
+ startSeconds: 0,
+ durationSeconds: 0.01,
+ microphone: .init(samples: [0, 1], valid: [true]),
+ reference: nil
+ )
XCTAssertFalse(badShape.isValid)
XCTAssertTrue(badShape.validationReasons.contains(.invalidInput))
XCTAssertThrowsError(try badShape.validate())
let badPCM = MeetingReferenceAttributionFrame(
- frameIndex: 0, epoch: 0, startSeconds: 0, durationSeconds: 0.01,
- microphone: .init(samples: [.nan], valid: [true]), reference: nil)
+ frameIndex: 0,
+ epoch: 0,
+ startSeconds: 0,
+ durationSeconds: 0.01,
+ microphone: .init(samples: [.nan], valid: [true]),
+ reference: nil
+ )
XCTAssertTrue(badPCM.validationReasons.contains(.nonFiniteInput))
let overflow = MeetingReferenceAttributionFrame(
- frameIndex: 0, epoch: 0, startSeconds: .greatestFiniteMagnitude,
+ frameIndex: 0,
+ epoch: 0,
+ startSeconds: .greatestFiniteMagnitude,
durationSeconds: .greatestFiniteMagnitude,
- microphone: .init(samples: [0], valid: [true]), reference: nil)
+ microphone: .init(samples: [0], valid: [true]),
+ reference: nil
+ )
XCTAssertFalse(overflow.hasValidTiming)
}
func testFrameResultDecodeRejectsOutcomeSpeechAndFallbackContradictions() throws {
let configuration = MeetingReferenceAttributionConfiguration()
let identity = MeetingReferenceAttributionEngineIdentity(
- engineID: "engine", engineVersion: "1", configuration: configuration)
+ engineID: "engine", engineVersion: "1", configuration: configuration
+ )
let sidecar = MeetingReferenceAttributionSidecar(
- engineIdentity: identity, configuration: configuration,
- frameResults: [result(.acceptedNearEndSpeech, duration: 0.1, speech: .nearEndSpeech)])
+ engineIdentity: identity,
+ configuration: configuration,
+ frameResults: [result(.acceptedNearEndSpeech, duration: 0.1, speech: .nearEndSpeech)]
+ )
var object = try XCTUnwrap(JSONSerialization.jsonObject(
with: JSONEncoder().encode(sidecar)) as? [String: Any])
var frames = try XCTUnwrap(object["frameResults"] as? [[String: Any]])
@@ -224,8 +324,10 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
}
func testPlaybackOnlyConflictingSpeechDegradesAndNoncanonicalReasonsAreRejected() throws {
- let conflicting = result(
- .likelyPlaybackOnly, duration: 0.1, speech: .nearEndSpeech,
+ let conflicting = self.result(
+ .likelyPlaybackOnly,
+ duration: 0.1,
+ speech: .nearEndSpeech,
reasons: [.playbackAttributed]
)
XCTAssertEqual(conflicting.outcome, .mixedOrUncertain)
@@ -234,12 +336,18 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
let configuration = MeetingReferenceAttributionConfiguration()
let identity = MeetingReferenceAttributionEngineIdentity(
- engineID: "engine", engineVersion: "1", configuration: configuration)
+ engineID: "engine", engineVersion: "1", configuration: configuration
+ )
let sidecar = MeetingReferenceAttributionSidecar(
- engineIdentity: identity, configuration: configuration,
+ engineIdentity: identity,
+ configuration: configuration,
frameResults: [result(
- .likelyPlaybackOnly, duration: 0.1, speech: .noSpeech,
- reasons: [.playbackAttributed, .noSpeechMeasured])])
+ .likelyPlaybackOnly,
+ duration: 0.1,
+ speech: .noSpeech,
+ reasons: [.playbackAttributed, .noSpeechMeasured]
+ )]
+ )
var object = try XCTUnwrap(JSONSerialization.jsonObject(
with: JSONEncoder().encode(sidecar)) as? [String: Any])
var frames = try XCTUnwrap(object["frameResults"] as? [[String: Any]])
@@ -248,16 +356,20 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
object["frameResults"] = frames
let noncanonical = try JSONSerialization.data(withJSONObject: object)
XCTAssertThrowsError(try JSONDecoder().decode(
- MeetingReferenceAttributionSidecar.self, from: noncanonical))
+ MeetingReferenceAttributionSidecar.self, from: noncanonical
+ ))
}
func testSidecarDecodeRejectsAggregateEpochAndConfigurationMismatches() throws {
let configuration = MeetingReferenceAttributionConfiguration()
let identity = MeetingReferenceAttributionEngineIdentity(
- engineID: "engine", engineVersion: "1", configuration: configuration)
+ engineID: "engine", engineVersion: "1", configuration: configuration
+ )
let sidecar = MeetingReferenceAttributionSidecar(
- engineIdentity: identity, configuration: configuration,
- frameResults: [result(.acceptedNearEndSpeech, duration: 0.1, speech: .nearEndSpeech)])
+ engineIdentity: identity,
+ configuration: configuration,
+ frameResults: [result(.acceptedNearEndSpeech, duration: 0.1, speech: .nearEndSpeech)]
+ )
let encoder = JSONEncoder()
var object = try XCTUnwrap(JSONSerialization.jsonObject(
with: encoder.encode(sidecar)) as? [String: Any])
@@ -267,7 +379,8 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
object["engineIdentity"] = identityObject
XCTAssertThrowsError(try JSONDecoder().decode(
MeetingReferenceAttributionSidecar.self,
- from: JSONSerialization.data(withJSONObject: object)))
+ from: JSONSerialization.data(withJSONObject: object)
+ ))
object = try XCTUnwrap(JSONSerialization.jsonObject(
with: encoder.encode(sidecar)) as? [String: Any])
@@ -276,7 +389,8 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
object["epochs"] = epochs
XCTAssertThrowsError(try JSONDecoder().decode(
MeetingReferenceAttributionSidecar.self,
- from: JSONSerialization.data(withJSONObject: object)))
+ from: JSONSerialization.data(withJSONObject: object)
+ ))
object = try XCTUnwrap(JSONSerialization.jsonObject(
with: encoder.encode(sidecar)) as? [String: Any])
@@ -287,17 +401,21 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
object["aggregate"] = aggregate
XCTAssertThrowsError(try JSONDecoder().decode(
MeetingReferenceAttributionSidecar.self,
- from: JSONSerialization.data(withJSONObject: object)))
+ from: JSONSerialization.data(withJSONObject: object)
+ ))
}
func testProgrammaticSidecarExposesDuplicateFrameKeyAsInvalid() {
let configuration = MeetingReferenceAttributionConfiguration()
let identity = MeetingReferenceAttributionEngineIdentity(
- engineID: "engine", engineVersion: "1", configuration: configuration)
- let frame = result(.acceptedNearEndSpeech, duration: 0.1, speech: .nearEndSpeech)
+ engineID: "engine", engineVersion: "1", configuration: configuration
+ )
+ let frame = self.result(.acceptedNearEndSpeech, duration: 0.1, speech: .nearEndSpeech)
let sidecar = MeetingReferenceAttributionSidecar(
- engineIdentity: identity, configuration: configuration,
- frameResults: [frame, frame])
+ engineIdentity: identity,
+ configuration: configuration,
+ frameResults: [frame, frame]
+ )
XCTAssertEqual(sidecar.validationError, .invalid("duplicate epoch/frame key"))
XCTAssertFalse(sidecar.isValid)
}
@@ -305,11 +423,15 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
func testProgrammaticDuplicateEpochsDoNotTrapAndRemainInvalid() {
let configuration = MeetingReferenceAttributionConfiguration()
let identity = MeetingReferenceAttributionEngineIdentity(
- engineID: "engine", engineVersion: "1", configuration: configuration)
- let frame = result(.acceptedNearEndSpeech, duration: 0.1, speech: .nearEndSpeech)
+ engineID: "engine", engineVersion: "1", configuration: configuration
+ )
+ let frame = self.result(.acceptedNearEndSpeech, duration: 0.1, speech: .nearEndSpeech)
let sidecar = MeetingReferenceAttributionSidecar(
- engineIdentity: identity, configuration: configuration,
- epochs: [.init(epoch: 0), .init(epoch: 0)], frameResults: [frame])
+ engineIdentity: identity,
+ configuration: configuration,
+ epochs: [.init(epoch: 0), .init(epoch: 0)],
+ frameResults: [frame]
+ )
XCTAssertEqual(sidecar.epochs.count, 2)
XCTAssertEqual(sidecar.validationError, .invalid("duplicate epoch"))
@@ -318,33 +440,68 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
func testContradictoryFrameResultsNormalizeToDecodableFailOpenValues() throws {
let cases: [MeetingReferenceAttributionFrameResult] = [
- result(.acceptedNearEndSpeech, duration: 0.1, speech: .playbackSpeech,
- residual: .linearResidual, reasons: [.residualSpeechDetected]),
- result(.likelyPlaybackOnly, duration: 0.1, index: 1, speech: .unknown,
- residual: .suppressedResidual),
+ result(
+ .acceptedNearEndSpeech,
+ duration: 0.1,
+ speech: .playbackSpeech,
+ residual: .linearResidual,
+ reasons: [.residualSpeechDetected]
+ ),
+ result(
+ .likelyPlaybackOnly,
+ duration: 0.1,
+ index: 1,
+ speech: .unknown,
+ residual: .suppressedResidual
+ ),
MeetingReferenceAttributionFrameResult(
- frameIndex: 2, epoch: 0, startSeconds: 0.2, durationSeconds: 0.1,
- outcome: .unscored, speechState: .nearEndSpeech,
- residualVariant: .linearResidual, fallback: .none),
+ frameIndex: 2,
+ epoch: 0,
+ startSeconds: 0.2,
+ durationSeconds: 0.1,
+ outcome: .unscored,
+ speechState: .nearEndSpeech,
+ residualVariant: .linearResidual,
+ fallback: .none
+ ),
MeetingReferenceAttributionFrameResult(
- frameIndex: 3, epoch: 0, startSeconds: 0.3, durationSeconds: 0.1,
- outcome: .scopeLimited, speechState: .unknown, fallback: .originalMicrophone),
+ frameIndex: 3,
+ epoch: 0,
+ startSeconds: 0.3,
+ durationSeconds: 0.1,
+ outcome: .scopeLimited,
+ speechState: .unknown,
+ fallback: .originalMicrophone
+ ),
MeetingReferenceAttributionFrameResult(
- frameIndex: -1, epoch: 0, startSeconds: 0.4, durationSeconds: 0.1,
- outcome: .mixedOrUncertain, speechState: .mixedSpeech),
+ frameIndex: -1,
+ epoch: 0,
+ startSeconds: 0.4,
+ durationSeconds: 0.1,
+ outcome: .mixedOrUncertain,
+ speechState: .mixedSpeech
+ ),
MeetingReferenceAttributionFrameResult(
- frameIndex: 5, epoch: 0, startSeconds: .greatestFiniteMagnitude,
- durationSeconds: .greatestFiniteMagnitude, outcome: .mixedOrUncertain,
- speechState: .mixedSpeech)
+ frameIndex: 5,
+ epoch: 0,
+ startSeconds: .greatestFiniteMagnitude,
+ durationSeconds: .greatestFiniteMagnitude,
+ outcome: .mixedOrUncertain,
+ speechState: .mixedSpeech
+ ),
]
for (offset, value) in cases.enumerated() {
let data = try JSONEncoder().encode(value)
let decoded = try JSONDecoder().decode(
- MeetingReferenceAttributionFrameResult.self, from: data)
+ MeetingReferenceAttributionFrameResult.self, from: data
+ )
XCTAssertEqual(decoded, value)
- XCTAssertEqual(decoded.fallback, decoded.outcome == .unscored
- ? .originalMicrophone : .none)
+ XCTAssertEqual(
+ decoded.fallback,
+ decoded.outcome == .unscored
+ ? .originalMicrophone : .none
+ )
if decoded.outcome == .unscored {
XCTAssertEqual(decoded.speechState, .unknown)
XCTAssertNil(decoded.residualVariant)
@@ -356,26 +513,31 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
func testSidecarDecodeRejectsOverlapAndAdversarialContractPayloads() throws {
let configuration = MeetingReferenceAttributionConfiguration()
let identity = MeetingReferenceAttributionEngineIdentity(
- engineID: "engine", engineVersion: "1",
+ engineID: "engine",
+ engineVersion: "1",
sourceHashes: [.init(name: "source", hash: "sha256:1")],
- configuration: configuration)
+ configuration: configuration
+ )
let frames = [
result(.acceptedNearEndSpeech, duration: 0.1, speech: .nearEndSpeech),
- result(.likelyPlaybackOnly, duration: 0.1, index: 1, speech: .noSpeech)
+ result(.likelyPlaybackOnly, duration: 0.1, index: 1, speech: .noSpeech),
]
let sidecar = MeetingReferenceAttributionSidecar(
- engineIdentity: identity, configuration: configuration,
- frameResults: frames)
+ engineIdentity: identity,
+ configuration: configuration,
+ frameResults: frames
+ )
let encoder = JSONEncoder()
func object() throws -> [String: Any] {
try XCTUnwrap(JSONSerialization.jsonObject(with: encoder.encode(sidecar))
- as? [String: Any])
+ as? [String: Any])
}
func assertRejects(_ object: [String: Any], _ label: String = "") throws {
XCTAssertThrowsError(try JSONDecoder().decode(
MeetingReferenceAttributionSidecar.self,
- from: JSONSerialization.data(withJSONObject: object)), label)
+ from: JSONSerialization.data(withJSONObject: object)
+ ), label)
}
var value = try object()
@@ -392,7 +554,7 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
var duplicateIdentity = try XCTUnwrap(value["engineIdentity"] as? [String: Any])
duplicateIdentity["sourceHashes"] = [
["name": "source", "hash": "sha256:1"],
- ["name": "source", "hash": "sha256:2"]
+ ["name": "source", "hash": "sha256:2"],
]
value["engineIdentity"] = duplicateIdentity
try assertRejects(value, "duplicate source")
@@ -440,32 +602,47 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
func testResourceCostRejectsNonFiniteJSON() {
let data = Data(#"{"processingMilliseconds":1e400,"peakMemoryBytes":null,"derivedSidecarBytes":null,"overBudget":false,"fallback":"none"}"#.utf8)
XCTAssertThrowsError(try JSONDecoder().decode(
- MeetingReferenceAttributionResourceCost.self, from: data))
+ MeetingReferenceAttributionResourceCost.self, from: data
+ ))
}
func testProgrammaticProvenanceAndEpochsRemainCanonicalAndRejectDuplicates() {
let configuration = MeetingReferenceAttributionConfiguration()
let duplicateIdentity = MeetingReferenceAttributionEngineIdentity(
- engineID: "engine", engineVersion: "1",
+ engineID: "engine",
+ engineVersion: "1",
sourceHashes: [
.init(name: "source", hash: "sha256:1"),
- .init(name: "source", hash: "sha256:2")
- ], configuration: configuration)
+ .init(name: "source", hash: "sha256:2"),
+ ], configuration: configuration
+ )
let frames = [
result(.acceptedNearEndSpeech, duration: 0.1, epoch: 0, speech: .nearEndSpeech),
- result(.acceptedNearEndSpeech, duration: 0.1, epoch: 1, index: 1,
- speech: .nearEndSpeech)
+ result(
+ .acceptedNearEndSpeech,
+ duration: 0.1,
+ epoch: 1,
+ index: 1,
+ speech: .nearEndSpeech
+ ),
]
let duplicateSourceSidecar = MeetingReferenceAttributionSidecar(
- engineIdentity: duplicateIdentity, configuration: configuration,
- epochs: [.init(epoch: 0), .init(epoch: 1)], frameResults: frames)
+ engineIdentity: duplicateIdentity,
+ configuration: configuration,
+ epochs: [.init(epoch: 0), .init(epoch: 1)],
+ frameResults: frames
+ )
XCTAssertFalse(duplicateSourceSidecar.isValid)
let validIdentity = MeetingReferenceAttributionEngineIdentity(
- engineID: "engine", engineVersion: "1", configuration: configuration)
+ engineID: "engine", engineVersion: "1", configuration: configuration
+ )
let duplicateEpochSidecar = MeetingReferenceAttributionSidecar(
- engineIdentity: validIdentity, configuration: configuration,
- epochs: [.init(epoch: 2), .init(epoch: 0), .init(epoch: 2)], frameResults: frames)
+ engineIdentity: validIdentity,
+ configuration: configuration,
+ epochs: [.init(epoch: 2), .init(epoch: 0), .init(epoch: 2)],
+ frameResults: frames
+ )
XCTAssertEqual(duplicateEpochSidecar.epochs.map(\.epoch), [0, 2, 2])
XCTAssertEqual(duplicateEpochSidecar.validationError, .invalid("duplicate epoch"))
@@ -475,13 +652,20 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
func testSidecarRejectsUnsortedEpochsAndCrossEpochOverlap() throws {
let configuration = MeetingReferenceAttributionConfiguration()
let identity = MeetingReferenceAttributionEngineIdentity(
- engineID: "engine", engineVersion: "1", configuration: configuration)
- let first = result(.acceptedNearEndSpeech, duration: 0.1, epoch: 0,
- speech: .nearEndSpeech)
- let second = result(.likelyPlaybackOnly, duration: 0.1, epoch: 1, speech: .noSpeech)
+ engineID: "engine", engineVersion: "1", configuration: configuration
+ )
+ let first = self.result(
+ .acceptedNearEndSpeech,
+ duration: 0.1,
+ epoch: 0,
+ speech: .nearEndSpeech
+ )
+ let second = self.result(.likelyPlaybackOnly, duration: 0.1, epoch: 1, speech: .noSpeech)
let sidecar = MeetingReferenceAttributionSidecar(
- engineIdentity: identity, configuration: configuration,
- frameResults: [first, second])
+ engineIdentity: identity,
+ configuration: configuration,
+ frameResults: [first, second]
+ )
XCTAssertEqual(sidecar.epochs.map(\.epoch), [0, 1])
var object = try XCTUnwrap(JSONSerialization.jsonObject(
@@ -489,13 +673,21 @@ final class MeetingReferenceAttributionContractsTests: XCTestCase {
object["epochs"] = [["epoch": 1], ["epoch": 0]]
XCTAssertThrowsError(try JSONDecoder().decode(
MeetingReferenceAttributionSidecar.self,
- from: JSONSerialization.data(withJSONObject: object)))
+ from: JSONSerialization.data(withJSONObject: object)
+ ))
let overlapping = MeetingReferenceAttributionSidecar(
- engineIdentity: identity, configuration: configuration,
+ engineIdentity: identity,
+ configuration: configuration,
frameResults: [first, MeetingReferenceAttributionFrameResult(
- frameIndex: 0, epoch: 1, startSeconds: 0.05, durationSeconds: 0.1,
- outcome: .likelyPlaybackOnly, speechState: .noSpeech)])
+ frameIndex: 0,
+ epoch: 1,
+ startSeconds: 0.05,
+ durationSeconds: 0.1,
+ outcome: .likelyPlaybackOnly,
+ speechState: .noSpeech
+ )]
+ )
XCTAssertEqual(overlapping.validationError, .invalid("non-monotonic frame timing"))
}
}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingReferenceSynchronizerTests.swift b/Tests/FluidDictationIntegrationTests/MeetingReferenceSynchronizerTests.swift
index 3ce39f13..948ad764 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingReferenceSynchronizerTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingReferenceSynchronizerTests.swift
@@ -13,9 +13,15 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
route: String = "route-a",
discontinuity: Bool = false
) -> MeetingMicrophonePCMFrame {
- MeetingMicrophonePCMFrame(sequenceNumber: sequence, sampleTime: start, hostTime: host,
- sampleRate: sampleRate, samples: [Float](repeating: value, count: count), routeIdentifier: route,
- discontinuity: discontinuity)
+ MeetingMicrophonePCMFrame(
+ sequenceNumber: sequence,
+ sampleTime: start,
+ hostTime: host,
+ sampleRate: self.sampleRate,
+ samples: [Float](repeating: value, count: count),
+ routeIdentifier: route,
+ discontinuity: discontinuity
+ )
}
private func ref(
@@ -26,15 +32,20 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
rate: Double? = nil,
discontinuity: Bool = false
) -> MeetingReferencePCMFrame {
- MeetingReferencePCMFrame(sequenceNumber: sequence, presentationTime: pts,
- sampleRate: rate ?? sampleRate, samples: [Float](repeating: value, count: count), discontinuity: discontinuity)
+ MeetingReferencePCMFrame(
+ sequenceNumber: sequence,
+ presentationTime: pts,
+ sampleRate: rate ?? self.sampleRate,
+ samples: [Float](repeating: value, count: count),
+ discontinuity: discontinuity
+ )
}
func testExactTenMillisecondFramesAndMasks() {
let input = MeetingReferenceSynchronizer()
let result = input.synchronize(
- microphone: (0..<3).map { mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) },
- reference: (0..<3).map { ref($0, pts: Double($0) * 0.01) }
+ microphone: (0..<3).map { self.mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) },
+ reference: (0..<3).map { self.ref($0, pts: Double($0) * 0.01) }
)
XCTAssertFalse(result.failedOpen)
XCTAssertEqual(result.frames.count, 3)
@@ -45,26 +56,26 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testPositiveAndNegativeOffsetHaveExplicitLagSign() {
let positive = MeetingReferenceSynchronizer(configuration: .init(referenceToMicrophoneOffsetSeconds: 0.02))
- .synchronize(microphone: (0..<5).map { mic($0, start: Int64($0 * 160)) }, reference: (0..<5).map { ref($0, pts: Double($0) * 0.01) })
+ .synchronize(microphone: (0..<5).map { self.mic($0, start: Int64($0 * 160)) }, reference: (0..<5).map { self.ref($0, pts: Double($0) * 0.01) })
let negative = MeetingReferenceSynchronizer(configuration: .init(referenceToMicrophoneOffsetSeconds: -0.02))
- .synchronize(microphone: (0..<5).map { mic($0, start: Int64($0 * 160)) }, reference: (0..<5).map { ref($0, pts: Double($0) * 0.01) })
+ .synchronize(microphone: (0..<5).map { self.mic($0, start: Int64($0 * 160)) }, reference: (0..<5).map { self.ref($0, pts: Double($0) * 0.01) })
XCTAssertTrue(positive.frames.compactMap(\.lagSeconds).allSatisfy { $0 == -0.02 })
XCTAssertTrue(negative.frames.compactMap(\.lagSeconds).allSatisfy { $0 == 0.02 })
}
func testSlowDriftIsReportedAndLargeDriftIsUnknown() {
let stable = MeetingReferenceSynchronizer(configuration: .init(referenceClockDriftPPM: 25))
- .synchronize(microphone: [mic(0, start: 0)], reference: [ref(0, pts: 0)])
+ .synchronize(microphone: [self.mic(0, start: 0)], reference: [self.ref(0, pts: 0)])
XCTAssertEqual(stable.diagnostics.referenceClockDriftPPM, 25)
let unstable = MeetingReferenceSynchronizer(configuration: .init(referenceClockDriftPPM: 90, maximumClockDriftPPM: 100))
- .synchronize(microphone: [mic(0, start: 0)], reference: [ref(0, pts: 0)])
+ .synchronize(microphone: [self.mic(0, start: 0)], reference: [self.ref(0, pts: 0)])
XCTAssertTrue(unstable.frames[0].unknownReasons.contains(.clockDriftUnstable))
}
func testDroppedBlocksCreateGapMaskAndEpoch() {
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 0), mic(2, start: 320)],
- reference: [ref(0, pts: 0), ref(1, pts: 0.01), ref(2, pts: 0.02)]
+ microphone: [self.mic(0, start: 0), self.mic(2, start: 320)],
+ reference: [self.ref(0, pts: 0), self.ref(1, pts: 0.01), self.ref(2, pts: 0.02)]
)
XCTAssertTrue(result.frames.contains { $0.unknownReasons.contains(.captureGap) && $0.captureValidMask.contains(false) })
XCTAssertGreaterThan(result.diagnostics.epochCount, 1)
@@ -73,12 +84,15 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testCodecPrimingRemainderAndEditListAreAccountedFor() {
let configuration = MeetingReferenceSynchronizerConfiguration(
- referenceScope: .authorizedFullMix, referenceCompleteness: .measuredComplete,
- codecPrimingSamples: 32, codecRemainderSamples: 16, editListOffsetSeconds: 0.01
+ referenceScope: .authorizedFullMix,
+ referenceCompleteness: .measuredComplete,
+ codecPrimingSamples: 32,
+ codecRemainderSamples: 16,
+ editListOffsetSeconds: 0.01
)
let result = MeetingReferenceSynchronizer(configuration: configuration).synchronize(
- microphone: [mic(0, start: 0), mic(1, start: 160)],
- reference: [ref(0, pts: 0, count: 160), ref(1, pts: 0.01, count: 160)]
+ microphone: [self.mic(0, start: 0), self.mic(1, start: 160)],
+ reference: [self.ref(0, pts: 0, count: 160), self.ref(1, pts: 0.01, count: 160)]
)
XCTAssertEqual(result.frames.count, 3) // edit-list offset shifts reference one hop
XCTAssertEqual(result.diagnostics.converterVersions, ["linear-v1", "linear-v1"])
@@ -88,8 +102,8 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testDiscontinuityRouteAndSampleRateChangesResetEpoch() {
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 0), mic(1, start: 160, route: "route-b", discontinuity: true), mic(2, start: 320, route: "route-b")],
- reference: [ref(0, pts: 0), ref(1, pts: 0.01, rate: 8_000), ref(2, pts: 0.03, rate: 8_000)]
+ microphone: [self.mic(0, start: 0), self.mic(1, start: 160, route: "route-b", discontinuity: true), self.mic(2, start: 320, route: "route-b")],
+ reference: [self.ref(0, pts: 0), self.ref(1, pts: 0.01, rate: 8000), self.ref(2, pts: 0.03, rate: 8000)]
)
// Both tracks reset at the same session boundary, so the merged epoch advances once.
XCTAssertEqual(
@@ -103,12 +117,12 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testSynthesizedMicrophoneTimingFreezesUntilResynchronizationBoundary() {
let result = MeetingReferenceSynchronizer().synchronize(
microphone: [
- mic(0, start: 0, host: nil),
- mic(1, start: 160, host: nil),
- mic(2, start: 320, host: 0.02),
- mic(3, start: 480, host: 0.03)
+ self.mic(0, start: 0, host: nil),
+ self.mic(1, start: 160, host: nil),
+ self.mic(2, start: 320, host: 0.02),
+ self.mic(3, start: 480, host: 0.03),
],
- reference: (0..<4).map { ref($0, pts: Double($0) * 0.01) }
+ reference: (0..<4).map { self.ref($0, pts: Double($0) * 0.01) }
)
XCTAssertTrue(result.frames.prefix(2).allSatisfy { $0.adaptationFrozen })
guard let boundary = result.frames.firstIndex(where: { $0.resynchronizationBoundary }) else {
@@ -121,7 +135,7 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testSilenceIsValidAudioAndNotMissingCoverage() {
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 0, value: 0)], reference: [ref(0, pts: 0, value: 0)]
+ microphone: [self.mic(0, start: 0, value: 0)], reference: [self.ref(0, pts: 0, value: 0)]
)
XCTAssertTrue(result.frames[0].captureValidMask.allSatisfy { $0 })
XCTAssertTrue(result.frames[0].renderValidMask.allSatisfy { $0 })
@@ -130,24 +144,24 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
}
func testReferenceScopeAndCompletenessRemainSeparateReasons() {
- let result = MeetingReferenceSynchronizer().synchronize(microphone: [mic(0, start: 0)], reference: [ref(0, pts: 0)])
+ let result = MeetingReferenceSynchronizer().synchronize(microphone: [self.mic(0, start: 0)], reference: [self.ref(0, pts: 0)])
XCTAssertTrue(result.frames[0].unknownReasons.contains(.referenceScopeLimited))
XCTAssertTrue(result.frames[0].unknownReasons.contains(.referenceCompletenessUnobservable))
XCTAssertFalse(result.frames[0].unknownReasons.contains(.referenceAbsent))
}
func testMissingReferenceAndMissingCaptureAreUnknownNotSilence() {
- let noReference = MeetingReferenceSynchronizer().synchronize(microphone: [mic(0, start: 0)], reference: [])
+ let noReference = MeetingReferenceSynchronizer().synchronize(microphone: [self.mic(0, start: 0)], reference: [])
XCTAssertTrue(noReference.frames[0].unknownReasons.contains(.referenceAbsent))
XCTAssertTrue(noReference.frames[0].renderValidMask.allSatisfy { !$0 })
- let noCapture = MeetingReferenceSynchronizer().synchronize(microphone: [], reference: [ref(0, pts: 0)])
+ let noCapture = MeetingReferenceSynchronizer().synchronize(microphone: [], reference: [self.ref(0, pts: 0)])
XCTAssertTrue(noCapture.frames[0].unknownReasons.contains(.captureGap))
XCTAssertTrue(noCapture.frames[0].captureValidMask.allSatisfy { !$0 })
}
func testDeterministicReplayAndBoundedResourceFailOpen() {
- let micFrames = (0..<4).map { mic($0, start: Int64($0 * 160), value: Float($0)) }
- let refs = (0..<4).map { ref($0, pts: Double($0) * 0.01, value: Float($0 + 1)) }
+ let micFrames = (0..<4).map { self.mic($0, start: Int64($0 * 160), value: Float($0)) }
+ let refs = (0..<4).map { self.ref($0, pts: Double($0) * 0.01, value: Float($0 + 1)) }
let synchronizer = MeetingReferenceSynchronizer()
XCTAssertEqual(synchronizer.synchronize(microphone: micFrames, reference: refs), synchronizer.synchronize(microphone: micFrames, reference: refs))
let bounded = MeetingReferenceSynchronizer(configuration: .init(maximumInputFrameCount: 1))
@@ -158,11 +172,11 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
}
func testNonFiniteDuplicateAndLateFramesAreDroppedDeterministically() {
- var invalid = mic(1, start: 160)
- invalid = MeetingMicrophonePCMFrame(sequenceNumber: 1, sampleTime: 160, hostTime: 0.01, sampleRate: sampleRate, samples: [Float.nan] + Array(repeating: 1, count: 159))
+ var invalid = self.mic(1, start: 160)
+ invalid = MeetingMicrophonePCMFrame(sequenceNumber: 1, sampleTime: 160, hostTime: 0.01, sampleRate: self.sampleRate, samples: [Float.nan] + Array(repeating: 1, count: 159))
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 0), invalid, mic(1, start: 320), mic(3, start: 160)],
- reference: [ref(0, pts: 0), ref(1, pts: 0.01), ref(2, pts: 0.02)]
+ microphone: [self.mic(0, start: 0), invalid, self.mic(1, start: 320), self.mic(3, start: 160)],
+ reference: [self.ref(0, pts: 0), self.ref(1, pts: 0.01), self.ref(2, pts: 0.02)]
)
XCTAssertGreaterThanOrEqual(result.diagnostics.nonFiniteSampleCount, 1)
XCTAssertGreaterThanOrEqual(result.diagnostics.duplicateOrLateFrameCount, 1)
@@ -172,17 +186,29 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testStereoContinuityUsesDownmixedCountAndMalformedArrayIsGap() {
let stereo = (0..<2).map { index in
- MeetingMicrophonePCMFrame(sequenceNumber: index, sampleTime: Int64(index * 160), hostTime: Double(index) * 0.01,
- sampleRate: sampleRate, channelCount: 2, samples: [Float](repeating: Float(index + 1), count: 320))
+ MeetingMicrophonePCMFrame(
+ sequenceNumber: index,
+ sampleTime: Int64(index * 160),
+ hostTime: Double(index) * 0.01,
+ sampleRate: self.sampleRate,
+ channelCount: 2,
+ samples: [Float](repeating: Float(index + 1), count: 320)
+ )
}
- let valid = MeetingReferenceSynchronizer().synchronize(microphone: stereo, reference: [ref(0, pts: 0), ref(1, pts: 0.01)])
+ let valid = MeetingReferenceSynchronizer().synchronize(microphone: stereo, reference: [self.ref(0, pts: 0), self.ref(1, pts: 0.01)])
XCTAssertEqual(valid.diagnostics.epochCount, 1)
XCTAssertEqual(valid.frames.map { $0.captureSamples[0] }, [1, 2])
XCTAssertFalse(valid.frames.contains { $0.unknownReasons.contains(.captureGap) })
- let malformed = MeetingMicrophonePCMFrame(sequenceNumber: 0, sampleTime: 0, hostTime: 0,
- sampleRate: sampleRate, channelCount: 2, samples: [Float](repeating: 1, count: 319))
- let result = MeetingReferenceSynchronizer().synchronize(microphone: [malformed, stereo[1]], reference: [ref(0, pts: 0), ref(1, pts: 0.01)])
+ let malformed = MeetingMicrophonePCMFrame(
+ sequenceNumber: 0,
+ sampleTime: 0,
+ hostTime: 0,
+ sampleRate: sampleRate,
+ channelCount: 2,
+ samples: [Float](repeating: 1, count: 319)
+ )
+ let result = MeetingReferenceSynchronizer().synchronize(microphone: [malformed, stereo[1]], reference: [self.ref(0, pts: 0), self.ref(1, pts: 0.01)])
XCTAssertEqual(result.diagnostics.droppedFrameCount, 1)
// A malformed pre-origin block cannot define a source gap; the first accepted
// block establishes the microphone origin and is fully covered.
@@ -192,7 +218,7 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testDriftBeyondConfiguredMaximumFailsOpenAsClockDriftUnstable() {
let result = MeetingReferenceSynchronizer(configuration: .init(referenceClockDriftPPM: 101, maximumClockDriftPPM: 100))
- .synchronize(microphone: [mic(0, start: 0, host: 0)], reference: [ref(0, pts: 0)])
+ .synchronize(microphone: [self.mic(0, start: 0, host: 0)], reference: [self.ref(0, pts: 0)])
XCTAssertTrue(result.failedOpen)
XCTAssertEqual(result.failureReason, MeetingSynchronizerUnknownReason.clockDriftUnstable)
XCTAssertFalse(result.diagnostics.boundedResourceFailure)
@@ -200,12 +226,15 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testReferenceEpochAndGapUseTransformedSessionCoordinates() {
let config = MeetingReferenceSynchronizerConfiguration(
- referenceConverter: .init(algorithmicDelaySeconds: 0.004), referenceToMicrophoneOffsetSeconds: 0.03,
- editListOffsetSeconds: 0.02)
+ referenceConverter: .init(algorithmicDelaySeconds: 0.004),
+ referenceToMicrophoneOffsetSeconds: 0.03,
+ editListOffsetSeconds: 0.02
+ )
let refs = [ref(0, pts: 0), ref(1, pts: 0.03, discontinuity: true)]
- + (2..<10).map { ref($0, pts: Double($0 + 2) * 0.01) }
+ + (2..<10).map { self.ref($0, pts: Double($0 + 2) * 0.01) }
let result = MeetingReferenceSynchronizer(configuration: config).synchronize(
- microphone: (0..<10).map { mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) }, reference: refs)
+ microphone: (0..<10).map { self.mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) }, reference: refs
+ )
let firstReset = result.frames.firstIndex { $0.epochID > 0 }
XCTAssertNotNil(firstReset)
XCTAssertGreaterThanOrEqual(firstReset ?? 0, 5) // transformed event is after 0.05 s, not raw PTS 0.01
@@ -217,20 +246,22 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
microphoneConverter: .init(algorithmicDelaySeconds: 0.003),
referenceConverter: .init(algorithmicDelaySeconds: 0.005),
referenceToMicrophoneOffsetSeconds: 0.007,
- editListOffsetSeconds: 0.011)
+ editListOffsetSeconds: 0.011
+ )
let result = MeetingReferenceSynchronizer(configuration: config).synchronize(
- microphone: (0..<5).map { mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) },
- reference: (0..<5).map { ref($0, pts: Double($0) * 0.01) })
+ microphone: (0..<5).map { self.mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) },
+ reference: (0..<5).map { self.ref($0, pts: Double($0) * 0.01) }
+ )
guard let frame = result.frames.first(where: { $0.lagSeconds != nil }) else { return XCTFail("expected overlap") }
- XCTAssertEqual(frame.timelines.microphoneSourceTime ?? .nan, 0.01, accuracy: 0.000001)
- XCTAssertEqual(frame.timelines.referencePTSTime ?? .nan, 0, accuracy: 0.000001)
- XCTAssertEqual(frame.lagSeconds ?? .nan, -0.016, accuracy: 0.000001)
+ XCTAssertEqual(frame.timelines.microphoneSourceTime ?? .nan, 0.01, accuracy: 0.000_001)
+ XCTAssertEqual(frame.timelines.referencePTSTime ?? .nan, 0, accuracy: 0.000_001)
+ XCTAssertEqual(frame.lagSeconds ?? .nan, -0.016, accuracy: 0.000_001)
}
func testSynthesizedTimingMakesLagUnknown() {
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 0), mic(1, start: 160)],
- reference: [ref(0, pts: 0), ref(1, pts: 0.01)]
+ microphone: [self.mic(0, start: 0), self.mic(1, start: 160)],
+ reference: [self.ref(0, pts: 0), self.ref(1, pts: 0.01)]
)
XCTAssertEqual(result.frames.count, 2)
@@ -240,21 +271,21 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testFrameTimelinesCarryMicrophoneSampleAndHostTimes() {
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 8_000, host: 42), mic(1, start: 8_160, host: 42.01)],
- reference: [ref(0, pts: 0), ref(1, pts: 0.01)]
+ microphone: [self.mic(0, start: 8000, host: 42), self.mic(1, start: 8160, host: 42.01)],
+ reference: [self.ref(0, pts: 0), self.ref(1, pts: 0.01)]
)
XCTAssertEqual(result.frames.count, 2)
- XCTAssertEqual(result.frames[0].timelines.microphoneSampleTime, 8_000)
- XCTAssertEqual(result.frames[0].timelines.microphoneHostTime ?? .nan, 42, accuracy: 0.000001)
- XCTAssertEqual(result.frames[1].timelines.microphoneSampleTime, 8_160)
- XCTAssertEqual(result.frames[1].timelines.microphoneHostTime ?? .nan, 42.01, accuracy: 0.000001)
+ XCTAssertEqual(result.frames[0].timelines.microphoneSampleTime, 8000)
+ XCTAssertEqual(result.frames[0].timelines.microphoneHostTime ?? .nan, 42, accuracy: 0.000_001)
+ XCTAssertEqual(result.frames[1].timelines.microphoneSampleTime, 8160)
+ XCTAssertEqual(result.frames[1].timelines.microphoneHostTime ?? .nan, 42.01, accuracy: 0.000_001)
}
func testSequenceGapWithContiguousSampleTimesCreatesBoundaryWithoutGap() {
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 0, host: 1), mic(2, start: 160, host: 1.01)],
- reference: [ref(0, pts: 0), ref(1, pts: 0.01)]
+ microphone: [self.mic(0, start: 0, host: 1), self.mic(2, start: 160, host: 1.01)],
+ reference: [self.ref(0, pts: 0), self.ref(1, pts: 0.01)]
)
XCTAssertEqual(result.frames.count, 2)
@@ -265,7 +296,7 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
}
func testLongReferencePTSDiscontinuityIsMaskedFrozenAndResynchronized() {
- let frameCount = 1_400
+ let frameCount = 1400
let gapIndex = 700
let gapSeconds = 0.002
let configuration = MeetingReferenceSynchronizerConfiguration(
@@ -273,12 +304,19 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
referenceCompleteness: .measuredComplete
)
let microphone = (0..<frameCount).map {
- mic($0, start: Int64($0 * 160), host: Double($0) * 0.01,
- value: Float(($0 % 13) + 1))
+ self.mic(
+ $0,
+ start: Int64($0 * 160),
+ host: Double($0) * 0.01,
+ value: Float(($0 % 13) + 1)
+ )
}
let reference = (0..<frameCount).map { index in
- ref(index, pts: Double(index) * 0.01 + (index >= gapIndex ? gapSeconds : 0),
- value: Float((index % 17) + 1))
+ self.ref(
+ index,
+ pts: Double(index) * 0.01 + (index >= gapIndex ? gapSeconds : 0),
+ value: Float((index % 17) + 1)
+ )
}
let synchronizer = MeetingReferenceSynchronizer(configuration: configuration)
@@ -310,20 +348,28 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
}
func testInvalidReferencePTSAndRateCreateReferenceGapEpoch() {
- let invalidPTS = MeetingReferencePCMFrame(sequenceNumber: 1, presentationTime: .nan,
- sampleRate: sampleRate, samples: [Float](repeating: 2, count: 160))
+ let invalidPTS = MeetingReferencePCMFrame(
+ sequenceNumber: 1,
+ presentationTime: .nan,
+ sampleRate: sampleRate,
+ samples: [Float](repeating: 2, count: 160)
+ )
let ptsResult = MeetingReferenceSynchronizer().synchronize(
- microphone: (0..<3).map { mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) },
- reference: [ref(0, pts: 0), invalidPTS, ref(2, pts: 0.02)]
+ microphone: (0..<3).map { self.mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) },
+ reference: [self.ref(0, pts: 0), invalidPTS, self.ref(2, pts: 0.02)]
)
XCTAssertTrue(ptsResult.frames.contains { $0.unknownReasons.contains(.referenceGap) })
XCTAssertGreaterThan(ptsResult.diagnostics.epochCount, 1)
- let invalidRate = MeetingReferencePCMFrame(sequenceNumber: 1, presentationTime: 0.01,
- sampleRate: 0, samples: [Float](repeating: 2, count: 160))
+ let invalidRate = MeetingReferencePCMFrame(
+ sequenceNumber: 1,
+ presentationTime: 0.01,
+ sampleRate: 0,
+ samples: [Float](repeating: 2, count: 160)
+ )
let rateResult = MeetingReferenceSynchronizer().synchronize(
- microphone: (0..<3).map { mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) },
- reference: [ref(0, pts: 0), invalidRate, ref(2, pts: 0.02)]
+ microphone: (0..<3).map { self.mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) },
+ reference: [self.ref(0, pts: 0), invalidRate, self.ref(2, pts: 0.02)]
)
XCTAssertTrue(rateResult.frames.contains { $0.unknownReasons.contains(.referenceGap) })
XCTAssertGreaterThan(rateResult.diagnostics.epochCount, 1)
@@ -331,23 +377,23 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testRateChangePreservesReferenceSourcePTSInTimelines() {
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 0, host: 1), mic(1, start: 160, host: 1.01)],
- reference: [ref(0, pts: 0), ref(1, pts: 0.01, count: 80, rate: 8_000)]
+ microphone: [self.mic(0, start: 0, host: 1), self.mic(1, start: 160, host: 1.01)],
+ reference: [self.ref(0, pts: 0), self.ref(1, pts: 0.01, count: 80, rate: 8000)]
)
XCTAssertEqual(result.frames.count, 2)
- XCTAssertEqual(result.frames[1].timelines.referencePTSTime ?? .nan, 0.01, accuracy: 0.000001)
+ XCTAssertEqual(result.frames[1].timelines.referencePTSTime ?? .nan, 0.01, accuracy: 0.000_001)
}
func testArrivalOrderWinsAndLateFramesCannotOverwriteAcceptedAudio() {
let result = MeetingReferenceSynchronizer().synchronize(
microphone: [
- mic(1, start: 160, host: 1.01, value: 11),
- mic(0, start: 0, host: 1.00, value: 22),
- mic(1, start: 160, host: 1.02, value: 33),
- mic(2, start: 320, host: 1.03, value: 44)
+ self.mic(1, start: 160, host: 1.01, value: 11),
+ self.mic(0, start: 0, host: 1.00, value: 22),
+ self.mic(1, start: 160, host: 1.02, value: 33),
+ self.mic(2, start: 320, host: 1.03, value: 44),
],
- reference: (0..<3).map { ref($0, pts: Double($0) * 0.01) }
+ reference: (0..<3).map { self.ref($0, pts: Double($0) * 0.01) }
)
XCTAssertEqual(result.diagnostics.duplicateOrLateFrameCount, 2)
@@ -358,19 +404,22 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testRejectedSequenceIsConsumedWithoutDoubleEpochOrGap() {
let invalid = MeetingMicrophonePCMFrame(
- sequenceNumber: 1, sampleTime: 160, hostTime: 1.01, sampleRate: sampleRate,
+ sequenceNumber: 1,
+ sampleTime: 160,
+ hostTime: 1.01,
+ sampleRate: sampleRate,
samples: [Float.nan] + Array(repeating: 1, count: 159)
)
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 0, host: 1), invalid, mic(2, start: 320, host: 1.02)],
- reference: (0..<3).map { ref($0, pts: Double($0) * 0.01) }
+ microphone: [self.mic(0, start: 0, host: 1), invalid, self.mic(2, start: 320, host: 1.02)],
+ reference: (0..<3).map { self.ref($0, pts: Double($0) * 0.01) }
)
let micOnly = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 0, host: 1), invalid, mic(2, start: 320, host: 1.02)],
+ microphone: [self.mic(0, start: 0, host: 1), invalid, self.mic(2, start: 320, host: 1.02)],
reference: []
)
let refOnly = MeetingReferenceSynchronizer().synchronize(
- microphone: [], reference: (0..<3).map { ref($0, pts: Double($0) * 0.01) }
+ microphone: [], reference: (0..<3).map { self.ref($0, pts: Double($0) * 0.01) }
)
XCTAssertEqual(result.diagnostics.nonFiniteSampleCount, 1)
@@ -384,33 +433,38 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testInvalidFirstMicrophoneFrameDoesNotBecomeTheSourceOrigin() {
let invalid = MeetingMicrophonePCMFrame(
- sequenceNumber: 0, sampleTime: 8_000, hostTime: 40, sampleRate: 0,
+ sequenceNumber: 0,
+ sampleTime: 8000,
+ hostTime: 40,
+ sampleRate: 0,
samples: [Float](repeating: 1, count: 160)
)
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [invalid, mic(1, start: 8_160, host: 40.01)],
- reference: [ref(0, pts: 0), ref(1, pts: 0.01)]
+ microphone: [invalid, self.mic(1, start: 8160, host: 40.01)],
+ reference: [self.ref(0, pts: 0), self.ref(1, pts: 0.01)]
)
XCTAssertFalse(result.failedOpen)
XCTAssertEqual(result.diagnostics.droppedFrameCount, 1)
- XCTAssertEqual(result.frames.first?.timelines.microphoneSampleTime, 8_160)
+ XCTAssertEqual(result.frames.first?.timelines.microphoneSampleTime, 8160)
XCTAssertTrue(result.frames.contains { $0.captureValidMask.contains(true) })
}
func testReferenceDriftScalesSegmentPlacementAndDuration() {
let count = 10
- let sourceFrameSamples = 1_600
+ let sourceFrameSamples = 1600
let config = MeetingReferenceSynchronizerConfiguration(
- referenceClockDriftPPM: 5_000, maximumClockDriftPPM: 10_000,
- referenceScope: .authorizedFullMix, referenceCompleteness: .measuredComplete
+ referenceClockDriftPPM: 5000,
+ maximumClockDriftPPM: 10_000,
+ referenceScope: .authorizedFullMix,
+ referenceCompleteness: .measuredComplete
)
let result = MeetingReferenceSynchronizer(configuration: config).synchronize(
microphone: (0..<count).map {
- mic($0, start: Int64($0 * sourceFrameSamples), host: Double($0) * 0.1, count: sourceFrameSamples)
+ self.mic($0, start: Int64($0 * sourceFrameSamples), host: Double($0) * 0.1, count: sourceFrameSamples)
},
reference: (0..<count).map {
- ref($0, pts: Double($0) * 0.1, count: sourceFrameSamples)
+ self.ref($0, pts: Double($0) * 0.1, count: sourceFrameSamples)
}
)
@@ -429,8 +483,8 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
editListOffsetSeconds: 0.01
)
let result = MeetingReferenceSynchronizer(configuration: config).synchronize(
- microphone: (0..<5).map { mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) },
- reference: (0..<5).map { ref($0, pts: Double($0) * 0.01) }
+ microphone: (0..<5).map { self.mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) },
+ reference: (0..<5).map { self.ref($0, pts: Double($0) * 0.01) }
)
guard let frame = result.frames.first(where: { $0.lagSeconds != nil }) else {
@@ -454,29 +508,32 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
)
let synchronizer = MeetingReferenceSynchronizer(configuration: config)
let relative = synchronizer.synchronize(
- microphone: (0..<5).map { mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) },
- reference: (0..<5).map { ref($0, pts: Double($0) * 0.01) }
+ microphone: (0..<5).map { self.mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) },
+ reference: (0..<5).map { self.ref($0, pts: Double($0) * 0.01) }
)
let offset = synchronizer.synchronize(
- microphone: (0..<5).map { mic($0, start: 8_000 + Int64($0 * 160), host: Double($0) * 0.01) },
- reference: (0..<5).map { ref($0, pts: 1_234 + Double($0) * 0.01) }
+ microphone: (0..<5).map { self.mic($0, start: 8000 + Int64($0 * 160), host: Double($0) * 0.01) },
+ reference: (0..<5).map { self.ref($0, pts: 1234 + Double($0) * 0.01) }
)
let relativeLag = relative.frames.compactMap(\.lagSeconds).first
let offsetLag = offset.frames.compactMap(\.lagSeconds).first
- XCTAssertEqual(relativeLag ?? .nan, offsetLag ?? .nan, accuracy: 0.000001)
- XCTAssertEqual(offset.frames.compactMap { $0.timelines.referencePTSTime }.first ?? .nan,
- 1_234.002, accuracy: 0.001)
+ XCTAssertEqual(relativeLag ?? .nan, offsetLag ?? .nan, accuracy: 0.000_001)
+ XCTAssertEqual(
+ offset.frames.compactMap { $0.timelines.referencePTSTime }.first ?? .nan,
+ 1234.002,
+ accuracy: 0.001
+ )
}
func testForwardSequenceWithNonMonotonicMicrophoneSampleTimeIsDropped() {
let result = MeetingReferenceSynchronizer().synchronize(
microphone: [
- mic(0, start: 0, value: 10),
- mic(1, start: 80, value: 20), // overlaps the accepted source cursor
- mic(2, start: 160, value: 30)
+ self.mic(0, start: 0, value: 10),
+ self.mic(1, start: 80, value: 20), // overlaps the accepted source cursor
+ self.mic(2, start: 160, value: 30),
],
- reference: [ref(0, pts: 0), ref(1, pts: 0.01)]
+ reference: [self.ref(0, pts: 0), self.ref(1, pts: 0.01)]
)
XCTAssertEqual(result.diagnostics.droppedFrameCount, 1)
@@ -489,11 +546,11 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testForwardSequenceWithNonMonotonicReferencePTSIsDropped() {
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 0), mic(1, start: 160)],
+ microphone: [self.mic(0, start: 0), self.mic(1, start: 160)],
reference: [
- ref(0, pts: 0, value: 10),
- ref(1, pts: 0.005, value: 20), // overlaps the accepted reference cursor
- ref(2, pts: 0.01, value: 30)
+ self.ref(0, pts: 0, value: 10),
+ self.ref(1, pts: 0.005, value: 20), // overlaps the accepted reference cursor
+ self.ref(2, pts: 0.01, value: 30),
]
)
@@ -507,12 +564,18 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testContiguousRouteRateAndDiscontinuityResetsDoNotCreateGaps() {
let changedMic = MeetingMicrophonePCMFrame(
- sequenceNumber: 1, sampleTime: 160, hostTime: 1.01, sampleRate: sampleRate,
- samples: [Float](repeating: 2, count: 160), routeIdentifier: "route-b", discontinuity: true)
- let changedRef = ref(1, pts: 0.01, count: 80, rate: 8_000, discontinuity: true)
+ sequenceNumber: 1,
+ sampleTime: 160,
+ hostTime: 1.01,
+ sampleRate: sampleRate,
+ samples: [Float](repeating: 2, count: 160),
+ routeIdentifier: "route-b",
+ discontinuity: true
+ )
+ let changedRef = self.ref(1, pts: 0.01, count: 80, rate: 8000, discontinuity: true)
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 0, host: 1), changedMic],
- reference: [ref(0, pts: 0), changedRef]
+ microphone: [self.mic(0, start: 0, host: 1), changedMic],
+ reference: [self.ref(0, pts: 0), changedRef]
)
XCTAssertEqual(result.frames.count, 2)
@@ -524,11 +587,11 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
}
func testSharedResetEventAcrossTracksAdvancesEpochOnlyOnce() {
- let changedMic = mic(1, start: 160, host: 1.01, route: "route-b", discontinuity: true)
- let changedRef = ref(1, pts: 0.01, discontinuity: true)
+ let changedMic = self.mic(1, start: 160, host: 1.01, route: "route-b", discontinuity: true)
+ let changedRef = self.ref(1, pts: 0.01, discontinuity: true)
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 0, host: 1), changedMic],
- reference: [ref(0, pts: 0), changedRef]
+ microphone: [self.mic(0, start: 0, host: 1), changedMic],
+ reference: [self.ref(0, pts: 0), changedRef]
)
XCTAssertEqual(result.diagnostics.epochCount, 2)
@@ -538,10 +601,10 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testExtremeInt64SampleTimesAreDroppedWithoutOverflowTrap() {
let result = MeetingReferenceSynchronizer().synchronize(
microphone: [
- mic(0, start: .min, host: 1),
- mic(1, start: .max, host: 1.01)
+ self.mic(0, start: .min, host: 1),
+ self.mic(1, start: .max, host: 1.01),
],
- reference: [ref(0, pts: 0), ref(1, pts: 0.01)]
+ reference: [self.ref(0, pts: 0), self.ref(1, pts: 0.01)]
)
XCTAssertFalse(result.failedOpen)
@@ -551,14 +614,21 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testPreOriginInvalidFramesDoNotCreateFalseOverlapGaps() {
let invalidMic = MeetingMicrophonePCMFrame(
- sequenceNumber: 0, sampleTime: 8_000, hostTime: 40, sampleRate: 0,
- samples: [Float](repeating: 1, count: 160))
+ sequenceNumber: 0,
+ sampleTime: 8000,
+ hostTime: 40,
+ sampleRate: 0,
+ samples: [Float](repeating: 1, count: 160)
+ )
let invalidReference = MeetingReferencePCMFrame(
- sequenceNumber: 0, presentationTime: .nan, sampleRate: sampleRate,
- samples: [Float](repeating: 2, count: 160))
+ sequenceNumber: 0,
+ presentationTime: .nan,
+ sampleRate: sampleRate,
+ samples: [Float](repeating: 2, count: 160)
+ )
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [invalidMic, mic(1, start: 8_160, host: 40.01)],
- reference: [invalidReference, ref(1, pts: 0.01)]
+ microphone: [invalidMic, self.mic(1, start: 8160, host: 40.01)],
+ reference: [invalidReference, self.ref(1, pts: 0.01)]
)
XCTAssertFalse(result.failedOpen)
@@ -571,10 +641,11 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testMidstreamEmptyBlockIsOneUnknownGapAndAllEmptyInputIsDropped() {
let emptyMic = MeetingMicrophonePCMFrame(
- sequenceNumber: 1, sampleTime: 160, hostTime: 1.01, sampleRate: sampleRate, samples: [])
+ sequenceNumber: 1, sampleTime: 160, hostTime: 1.01, sampleRate: sampleRate, samples: []
+ )
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 0, host: 1), emptyMic, mic(2, start: 320, host: 1.02)],
- reference: (0..<3).map { ref($0, pts: Double($0) * 0.01) }
+ microphone: [self.mic(0, start: 0, host: 1), emptyMic, self.mic(2, start: 320, host: 1.02)],
+ reference: (0..<3).map { self.ref($0, pts: Double($0) * 0.01) }
)
XCTAssertEqual(result.diagnostics.droppedFrameCount, 1)
XCTAssertEqual(result.diagnostics.epochCount, 2)
@@ -583,7 +654,9 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
let allEmpty = MeetingReferenceSynchronizer().synchronize(
microphone: [emptyMic], reference: [MeetingReferencePCMFrame(
- sequenceNumber: 0, presentationTime: 0, sampleRate: sampleRate, samples: [])])
+ sequenceNumber: 0, presentationTime: 0, sampleRate: self.sampleRate, samples: []
+ )]
+ )
XCTAssertEqual(allEmpty.diagnostics.droppedFrameCount, 2)
XCTAssertTrue(allEmpty.frames.isEmpty)
}
@@ -591,8 +664,8 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testOutputBudgetFailureRetainsTimingDiagnostics() {
let config = MeetingReferenceSynchronizerConfiguration(maximumOutputFrameCount: 1)
let result = MeetingReferenceSynchronizer(configuration: config).synchronize(
- microphone: (0..<3).map { mic($0, start: Int64($0 * 160), host: nil) },
- reference: (0..<3).map { ref($0, pts: Double($0) * 0.01) }
+ microphone: (0..<3).map { self.mic($0, start: Int64($0 * 160), host: nil) },
+ reference: (0..<3).map { self.ref($0, pts: Double($0) * 0.01) }
)
XCTAssertTrue(result.failedOpen)
@@ -602,8 +675,8 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testFirstFrameDiscontinuityIsInitialMetadataNotAnEpochTransition() {
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [mic(0, start: 0, host: 1, discontinuity: true), mic(1, start: 160, host: 1.01)],
- reference: [ref(0, pts: 0, discontinuity: true), ref(1, pts: 0.01)]
+ microphone: [self.mic(0, start: 0, host: 1, discontinuity: true), self.mic(1, start: 160, host: 1.01)],
+ reference: [self.ref(0, pts: 0, discontinuity: true), self.ref(1, pts: 0.01)]
)
XCTAssertEqual(result.diagnostics.epochCount, 1)
@@ -615,14 +688,20 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
// 100 samples at 44.1 kHz maps to 36.28 analysis samples. Independent
// per-segment rounding would leave alternating seam holes/overlaps.
microphone: (0..<10).map {
- MeetingMicrophonePCMFrame(sequenceNumber: $0, sampleTime: Int64($0 * 100),
- hostTime: Double($0 * 100) / 44_100, sampleRate: 44_100,
+ MeetingMicrophonePCMFrame(
+ sequenceNumber: $0,
+ sampleTime: Int64($0 * 100),
+ hostTime: Double($0 * 100) / 44_100,
+ sampleRate: 44_100,
samples: [Float](repeating: 1, count: 100)
)
},
reference: (0..<10).map {
- MeetingReferencePCMFrame(sequenceNumber: $0, presentationTime: Double($0 * 100) / 44_100,
- sampleRate: 44_100, samples: [Float](repeating: 2, count: 100)
+ MeetingReferencePCMFrame(
+ sequenceNumber: $0,
+ presentationTime: Double($0 * 100) / 44_100,
+ sampleRate: 44_100,
+ samples: [Float](repeating: 2, count: 100)
)
}
)
@@ -636,10 +715,16 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testFiniteExtremeStereoSamplesRemainFiniteAfterDownmix() {
let extreme = MeetingMicrophonePCMFrame(
- sequenceNumber: 0, sampleTime: 0, hostTime: 1, sampleRate: sampleRate,
- channelCount: 2, samples: Array(repeating: .greatestFiniteMagnitude, count: 320))
+ sequenceNumber: 0,
+ sampleTime: 0,
+ hostTime: 1,
+ sampleRate: sampleRate,
+ channelCount: 2,
+ samples: Array(repeating: .greatestFiniteMagnitude, count: 320)
+ )
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: [extreme], reference: [ref(0, pts: 0)])
+ microphone: [extreme], reference: [self.ref(0, pts: 0)]
+ )
XCTAssertEqual(result.diagnostics.nonFiniteSampleCount, 0)
XCTAssertTrue(result.frames[0].captureValidMask.allSatisfy { $0 })
@@ -652,7 +737,7 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
MeetingAECDelayContractEvent(frameIndex: 0, kind: .render),
MeetingAECDelayContractEvent(frameIndex: 0, kind: .capture),
MeetingAECDelayContractEvent(frameIndex: 1, kind: .render),
- MeetingAECDelayContractEvent(frameIndex: 1, kind: .capture)
+ MeetingAECDelayContractEvent(frameIndex: 1, kind: .capture),
]
XCTAssertTrue(contract.isValid)
XCTAssertTrue(contract.validates(events: valid))
@@ -661,8 +746,9 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testStage05DelayContractAcceptsSynchronizerEpochAndMaskOutput() {
let result = MeetingReferenceSynchronizer().synchronize(
- microphone: (0..<2).map { mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) },
- reference: (0..<2).map { ref($0, pts: Double($0) * 0.01) })
+ microphone: (0..<2).map { self.mic($0, start: Int64($0 * 160), host: Double($0) * 0.01) },
+ reference: (0..<2).map { self.ref($0, pts: Double($0) * 0.01) }
+ )
let contract = MeetingAECDelayContract(renderLeadSeconds: 0.010)
XCTAssertTrue(contract.validates(synchronizedResult: result))
XCTAssertTrue(result.frames.allSatisfy { $0.epochID >= 0 && $0.renderValidMask.count == $0.captureValidMask.count })
@@ -670,14 +756,33 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testStage05ManifestRejectsCompressedUnsafeAndWrongTopologyArtifacts() {
let artifact = MeetingSignalDomainGateManifest.Artifact(
- role: "render", relativePath: "../render.m4a", sha256: String(repeating: "a", count: 64),
- codec: "aac", lossless: false, sampleRateHz: 16_000, channelCount: 1, durationSeconds: 1)
+ role: "render",
+ relativePath: "../render.m4a",
+ sha256: String(repeating: "a", count: 64),
+ codec: "aac",
+ lossless: false,
+ sampleRateHz: 16_000,
+ channelCount: 1,
+ durationSeconds: 1
+ )
let capture = MeetingSignalDomainGateManifest.Artifact(
- role: "capture", relativePath: "capture.wav", sha256: String(repeating: "b", count: 64),
- codec: "pcm_s16le", lossless: true, sampleRateHz: 16_000, channelCount: 1, durationSeconds: 1)
+ role: "capture",
+ relativePath: "capture.wav",
+ sha256: String(repeating: "b", count: 64),
+ codec: "pcm_s16le",
+ lossless: true,
+ sampleRateHz: 16_000,
+ channelCount: 1,
+ durationSeconds: 1
+ )
let manifest = MeetingSignalDomainGateManifest(
- topology: .vpio, route: .externalDevice, referenceScope: .unknown,
- referenceCompletenessMeasured: false, consentConfirmed: false, artifacts: [artifact, capture])
+ topology: .vpio,
+ route: .externalDevice,
+ referenceScope: .unknown,
+ referenceCompletenessMeasured: false,
+ consentConfirmed: false,
+ artifacts: [artifact, capture]
+ )
let reasons = manifest.validationReasons()
XCTAssertTrue(reasons.contains(.unsupportedTopology))
XCTAssertTrue(reasons.contains(.nonLossless))
@@ -688,14 +793,23 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testStage05MetadataOnlyInputIsExplicitlyUnscoredAndRetainsNoContent() {
let artifact = { (role: String, path: String) in MeetingSignalDomainGateManifest.Artifact(
- role: role, relativePath: path, sha256: String(repeating: "a", count: 64),
- codec: "pcm_s16le", lossless: true, sampleRateHz: 16_000,
- channelCount: 1, durationSeconds: 1) }
+ role: role,
+ relativePath: path,
+ sha256: String(repeating: "a", count: 64),
+ codec: "pcm_s16le",
+ lossless: true,
+ sampleRateHz: 16_000,
+ channelCount: 1,
+ durationSeconds: 1
+ ) }
let manifest = MeetingSignalDomainGateManifest(
- topology: .pairedScreenCaptureKit, route: .builtInSpeakerMicrophone,
- referenceScope: .selectedApplication, referenceCompletenessMeasured: true,
+ topology: .pairedScreenCaptureKit,
+ route: .builtInSpeakerMicrophone,
+ referenceScope: .selectedApplication,
+ referenceCompletenessMeasured: true,
consentConfirmed: true,
- artifacts: [artifact("render", "r.wav"), artifact("capture", "c.wav")])
+ artifacts: [artifact("render", "r.wav"), artifact("capture", "c.wav")]
+ )
let session = MeetingSignalDomainGateSession(ordinal: 7, renderBlocks: [], captureBlocks: [])
let report = MeetingSignalDomainGate.evaluate(manifest: manifest, sessions: [session])
XCTAssertEqual(report.outcome, .unscored)
@@ -708,12 +822,23 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testStage05RejectsGapOverlapDuplicateOrdinalAndInvalidThresholds() {
let artifact = { (role: String, path: String) in MeetingSignalDomainGateManifest.Artifact(
- role: role, relativePath: path, sha256: String(repeating: "a", count: 64),
- codec: "pcm_s16le", lossless: true, sampleRateHz: 16_000, channelCount: 1, durationSeconds: 2) }
+ role: role,
+ relativePath: path,
+ sha256: String(repeating: "a", count: 64),
+ codec: "pcm_s16le",
+ lossless: true,
+ sampleRateHz: 16_000,
+ channelCount: 1,
+ durationSeconds: 2
+ ) }
let manifest = MeetingSignalDomainGateManifest(
- topology: .pairedScreenCaptureKit, route: .builtInSpeakerMicrophone,
- referenceScope: .selectedApplication, referenceCompletenessMeasured: true,
- consentConfirmed: true, artifacts: [artifact("render", "r.wav"), artifact("capture", "c.wav")])
+ topology: .pairedScreenCaptureKit,
+ route: .builtInSpeakerMicrophone,
+ referenceScope: .selectedApplication,
+ referenceCompletenessMeasured: true,
+ consentConfirmed: true,
+ artifacts: [artifact("render", "r.wav"), artifact("capture", "c.wav")]
+ )
let samples = [Float](repeating: 0.1, count: 16_000)
let first = MeetingSignalDomainGateTrackBlock(presentationSeconds: 0, durationSeconds: 1, arrivalSeconds: 0, samples: samples)
let gap = MeetingSignalDomainGateTrackBlock(presentationSeconds: 2, durationSeconds: 1, arrivalSeconds: 2, samples: samples)
@@ -732,12 +857,23 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testStage05MissingArrivalMetadataIsNotTreatedAsMeasuredJitter() {
let artifact = { (role: String, path: String) in MeetingSignalDomainGateManifest.Artifact(
- role: role, relativePath: path, sha256: String(repeating: "a", count: 64),
- codec: "pcm_s16le", lossless: true, sampleRateHz: 16_000, channelCount: 1, durationSeconds: 2) }
+ role: role,
+ relativePath: path,
+ sha256: String(repeating: "a", count: 64),
+ codec: "pcm_s16le",
+ lossless: true,
+ sampleRateHz: 16_000,
+ channelCount: 1,
+ durationSeconds: 2
+ ) }
let manifest = MeetingSignalDomainGateManifest(
- topology: .pairedScreenCaptureKit, route: .builtInSpeakerMicrophone,
- referenceScope: .selectedApplication, referenceCompletenessMeasured: true,
- consentConfirmed: true, artifacts: [artifact("render", "r.wav"), artifact("capture", "c.wav")])
+ topology: .pairedScreenCaptureKit,
+ route: .builtInSpeakerMicrophone,
+ referenceScope: .selectedApplication,
+ referenceCompletenessMeasured: true,
+ consentConfirmed: true,
+ artifacts: [artifact("render", "r.wav"), artifact("capture", "c.wav")]
+ )
let block = MeetingSignalDomainGateTrackBlock(presentationSeconds: 0, durationSeconds: 1, samples: [0.1, 0.2])
let session = MeetingSignalDomainGateSession(ordinal: 2, renderBlocks: [block], captureBlocks: [block])
let report = MeetingSignalDomainGate.evaluate(manifest: manifest, sessions: [session])
@@ -747,30 +883,50 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testStage05DeterministicMultibandFIRFixtureCanPassSignalGate() {
let sampleRate = 16_000.0
- var state: UInt32 = 0x1234_5678
+ var state: UInt32 = 0x12345678
let samples = (0..<16_000).map { index -> Float in
let t = Double(index) / sampleRate
state = state &* 1_664_525 &+ 1_013_904_223
let noise = (Float(state) / Float(UInt32.max) - 0.5) * 0.01
- return Float(0.08 * (sin(2 * .pi * 250 * t) + sin(2 * .pi * 1_000 * t) + sin(2 * .pi * 4_000 * t)) / 3) + noise
+ return Float(0.08 * (sin(2 * .pi * 250 * t) + sin(2 * .pi * 1000 * t) + sin(2 * .pi * 4000 * t)) / 3) + noise
}
- let blocks = stride(from: 0, to: 16_000, by: 4_000).map { start in
- MeetingSignalDomainGateTrackBlock(presentationSeconds: Double(start) / sampleRate,
- durationSeconds: 0.25, arrivalSeconds: Double(start) / sampleRate,
- samples: Array(samples[start..<(start + 4_000)]))
+ let blocks = stride(from: 0, to: 16_000, by: 4000).map { start in
+ MeetingSignalDomainGateTrackBlock(
+ presentationSeconds: Double(start) / sampleRate,
+ durationSeconds: 0.25,
+ arrivalSeconds: Double(start) / sampleRate,
+ samples: Array(samples[start..<(start + 4000)])
+ )
}
let artifact = { (role: String, path: String) in MeetingSignalDomainGateManifest.Artifact(
- role: role, relativePath: path, sha256: String(repeating: "a", count: 64),
- codec: "pcm_s16le", lossless: true, sampleRateHz: sampleRate, channelCount: 1, durationSeconds: 1) }
+ role: role,
+ relativePath: path,
+ sha256: String(repeating: "a", count: 64),
+ codec: "pcm_s16le",
+ lossless: true,
+ sampleRateHz: sampleRate,
+ channelCount: 1,
+ durationSeconds: 1
+ ) }
let manifest = MeetingSignalDomainGateManifest(
- topology: .pairedScreenCaptureKit, route: .builtInSpeakerMicrophone,
- referenceScope: .selectedApplication, referenceCompletenessMeasured: true,
- consentConfirmed: true, artifacts: [artifact("render", "r.wav"), artifact("capture", "c.wav")])
+ topology: .pairedScreenCaptureKit,
+ route: .builtInSpeakerMicrophone,
+ referenceScope: .selectedApplication,
+ referenceCompletenessMeasured: true,
+ consentConfirmed: true,
+ artifacts: [artifact("render", "r.wav"), artifact("capture", "c.wav")]
+ )
let session = MeetingSignalDomainGateSession(ordinal: 3, renderBlocks: blocks, captureBlocks: blocks)
- let report = MeetingSignalDomainGate.evaluate(manifest: manifest, sessions: [session],
- thresholds: .init(maximumSearchDelaySeconds: 0.05, safetyMarginSeconds: 0.01,
- minimumBandCoherence: 0.05,
- maximumHeldOutLinearResidualFraction: 0.25))
+ let report = MeetingSignalDomainGate.evaluate(
+ manifest: manifest,
+ sessions: [session],
+ thresholds: .init(
+ maximumSearchDelaySeconds: 0.05,
+ safetyMarginSeconds: 0.01,
+ minimumBandCoherence: 0.05,
+ maximumHeldOutLinearResidualFraction: 0.25
+ )
+ )
XCTAssertEqual(report.outcome, .proceedToCandidate)
XCTAssertEqual(report.metrics.first?.sessionOrdinal, 3)
XCTAssertNotNil(report.metrics.first?.signedDelayP50Seconds)
@@ -788,30 +944,53 @@ final class MeetingReferenceSynchronizerTests: XCTestCase {
func testStage05TimeVaryingFIRFixtureFailsLearnabilityGate() {
let sampleRate = 16_000.0
- let render = (0..<16_000).map { index in Float(sin(2 * .pi * 1_000 * Double(index) / sampleRate) * 0.1) }
+ let render = (0..<16_000).map { index in Float(sin(2 * .pi * 1000 * Double(index) / sampleRate) * 0.1) }
let capture = render.enumerated().map { index, value in index >= 12_000 ? value * 0.05 : value }
- let blocks = stride(from: 0, to: 16_000, by: 4_000).map { start in
- MeetingSignalDomainGateTrackBlock(presentationSeconds: Double(start) / sampleRate,
- durationSeconds: 0.25, arrivalSeconds: Double(start) / sampleRate,
- samples: Array(render[start..<(start + 4_000)]))
+ let blocks = stride(from: 0, to: 16_000, by: 4000).map { start in
+ MeetingSignalDomainGateTrackBlock(
+ presentationSeconds: Double(start) / sampleRate,
+ durationSeconds: 0.25,
+ arrivalSeconds: Double(start) / sampleRate,
+ samples: Array(render[start..<(start + 4000)])
+ )
}
- let captureBlocks = stride(from: 0, to: 16_000, by: 4_000).map { start in
- MeetingSignalDomainGateTrackBlock(presentationSeconds: Double(start) / sampleRate,
- durationSeconds: 0.25, arrivalSeconds: Double(start) / sampleRate,
- samples: Array(capture[start..<(start + 4_000)]))
+ let captureBlocks = stride(from: 0, to: 16_000, by: 4000).map { start in
+ MeetingSignalDomainGateTrackBlock(
+ presentationSeconds: Double(start) / sampleRate,
+ durationSeconds: 0.25,
+ arrivalSeconds: Double(start) / sampleRate,
+ samples: Array(capture[start..<(start + 4000)])
+ )
}
let artifact = { (role: String, path: String) in MeetingSignalDomainGateManifest.Artifact(
- role: role, relativePath: path, sha256: String(repeating: "a", count: 64),
- codec: "pcm_s16le", lossless: true, sampleRateHz: sampleRate, channelCount: 1, durationSeconds: 1) }
+ role: role,
+ relativePath: path,
+ sha256: String(repeating: "a", count: 64),
+ codec: "pcm_s16le",
+ lossless: true,
+ sampleRateHz: sampleRate,
+ channelCount: 1,
+ durationSeconds: 1
+ ) }
let manifest = MeetingSignalDomainGateManifest(
- topology: .pairedScreenCaptureKit, route: .builtInSpeakerMicrophone,
- referenceScope: .selectedApplication, referenceCompletenessMeasured: true,
- consentConfirmed: true, artifacts: [artifact("render", "r.wav"), artifact("capture", "c.wav")])
+ topology: .pairedScreenCaptureKit,
+ route: .builtInSpeakerMicrophone,
+ referenceScope: .selectedApplication,
+ referenceCompletenessMeasured: true,
+ consentConfirmed: true,
+ artifacts: [artifact("render", "r.wav"), artifact("capture", "c.wav")]
+ )
let session = MeetingSignalDomainGateSession(ordinal: 4, renderBlocks: blocks, captureBlocks: captureBlocks)
- let report = MeetingSignalDomainGate.evaluate(manifest: manifest, sessions: [session],
- thresholds: .init(maximumSearchDelaySeconds: 0.05, safetyMarginSeconds: 0.01,
- minimumBandCoherence: 0,
- maximumHeldOutLinearResidualFraction: 0.10))
+ let report = MeetingSignalDomainGate.evaluate(
+ manifest: manifest,
+ sessions: [session],
+ thresholds: .init(
+ maximumSearchDelaySeconds: 0.05,
+ safetyMarginSeconds: 0.01,
+ minimumBandCoherence: 0,
+ maximumHeldOutLinearResidualFraction: 0.10
+ )
+ )
XCTAssertEqual(report.outcome, .rejected)
XCTAssertTrue(report.metrics.isEmpty)
XCTAssertTrue(report.reasonCounts[MeetingSignalDomainGateReason.linearPathUnlearnable.rawValue] ?? 0 > 0)
diff --git a/Tests/FluidDictationIntegrationTests/MeetingResultSidecarTests.swift b/Tests/FluidDictationIntegrationTests/MeetingResultSidecarTests.swift
index 8bfa0385..94397399 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingResultSidecarTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingResultSidecarTests.swift
@@ -22,6 +22,8 @@ final class MeetingResultSidecarTests: XCTestCase {
confidence: Double? = nil,
analysisStart: TimeInterval = 1,
analysisEnd: TimeInterval = 2,
+ // nil requests the fixture default; an empty collection tests explicitly missing data.
+ // swiftlint:disable:next discouraged_optional_collection
analysisSpanIDs: [String]? = nil
) -> MeetingFinalTextUnit {
MeetingFinalTextUnit(
@@ -58,8 +60,14 @@ final class MeetingResultSidecarTests: XCTestCase {
private func makeSidecar(
attemptID: UUID = UUID(),
+ // nil requests the fixture default; an empty collection tests explicitly missing data.
+ // swiftlint:disable:next discouraged_optional_collection
units: [MeetingFinalTextUnit]? = nil,
+ // nil requests the fixture default; an empty collection tests explicitly missing data.
+ // swiftlint:disable:next discouraged_optional_collection
dispositions: [MeetingTextUnitDispositionRecord]? = nil,
+ // nil requests the fixture default; an empty collection tests explicitly missing data.
+ // swiftlint:disable:next discouraged_optional_collection
receipts: [MeetingSpanCoverageReceipt]? = nil
) -> MeetingResultSidecar {
let resolvedUnits = units ?? [self.makeUnit()]
@@ -100,11 +108,11 @@ final class MeetingResultSidecarTests: XCTestCase {
id: index == 0 ? self.chunkID : UUID(),
sequence: index,
relativeFilePath: "tracks/fixture-\(index).caf",
- presentationStart: MeetingMediaTime(value: Int64(start * 1_000), timescale: 1_000),
- presentationEnd: MeetingMediaTime(value: Int64(end * 1_000), timescale: 1_000),
+ presentationStart: MeetingMediaTime(value: Int64(start * 1000), timescale: 1000),
+ presentationEnd: MeetingMediaTime(value: Int64(end * 1000), timescale: 1000),
discontinuities: [],
sha256: String(repeating: String((index % 9) + 1), count: 64),
- byteCount: 1_024,
+ byteCount: 1024,
finalizationState: .finalized
)
let identity = MeetingAnalysisChunkIdentity(trackID: self.trackID, chunk: chunk)
@@ -311,14 +319,18 @@ final class MeetingResultSidecarTests: XCTestCase {
dispositions: [
MeetingTextUnitDispositionRecord(unitID: "w-0", disposition: .emitted),
MeetingTextUnitDispositionRecord(
- unitID: "w-amb", disposition: .ambiguousUnassigned,
+ unitID: "w-amb",
+ disposition: .ambiguousUnassigned,
reasonCode: MeetingUnitDispositionReason.ambiguousSpeaker.rawValue
),
],
receipts: [
self.makeReceipt(id: "receipt-0"),
self.makeReceipt(
- id: "receipt-1", spanID: "span-1", analysisStart: 5, analysisEnd: 9,
+ id: "receipt-1",
+ spanID: "span-1",
+ analysisStart: 5,
+ analysisEnd: 9,
status: .failed
),
]
@@ -420,7 +432,8 @@ final class MeetingResultSidecarTests: XCTestCase {
units: [ambiguousUnit],
dispositions: [
MeetingTextUnitDispositionRecord(
- unitID: "w-amb", disposition: .inadmissible,
+ unitID: "w-amb",
+ disposition: .inadmissible,
reasonCode: MeetingUnitDispositionReason.inadmissibleCaptureEra.rawValue
),
]
diff --git a/Tests/FluidDictationIntegrationTests/MeetingSCKPairedDiagnosticsTests.swift b/Tests/FluidDictationIntegrationTests/MeetingSCKPairedDiagnosticsTests.swift
index 370499b8..cacc62f7 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingSCKPairedDiagnosticsTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingSCKPairedDiagnosticsTests.swift
@@ -1,8 +1,8 @@
#if DEBUG
-@testable import FluidVoice_Debug
import AVFoundation
import CoreMedia
+@testable import FluidVoice_Debug
import Foundation
import XCTest
@@ -17,15 +17,21 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
rate: Double = 48_000,
channels: Int = 2
) -> MeetingSCKPairedDiagnosticSample {
- .init(output: output, presentationSeconds: pts, durationSeconds: duration,
- frameCount: Int((duration * rate).rounded()), sampleRateHz: rate,
- channelCount: channels, arrivalSeconds: arrival)
+ .init(
+ output: output,
+ presentationSeconds: pts,
+ durationSeconds: duration,
+ frameCount: Int((duration * rate).rounded()),
+ sampleRateHz: rate,
+ channelCount: channels,
+ arrivalSeconds: arrival
+ )
}
func testGateIsExplicitAndDisabledReportsNoSamples() throws {
let collector = MeetingSCKPairedDiagnosticCollector(environment: [:])
XCTAssertFalse(collector.enabled)
- collector.record(sample(.applicationAudio, pts: 1))
+ collector.record(self.sample(.applicationAudio, pts: 1))
let report = collector.report()
XCTAssertFalse(report.enabled)
XCTAssertEqual(report.acceptedSampleCount, 0)
@@ -37,12 +43,12 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
func testTracksFormatContinuityGapJitterAndOffsetWithoutClockClaim() throws {
let collector = MeetingSCKPairedDiagnosticCollector(environment: enabledEnvironment)
- collector.record(sample(.applicationAudio, pts: 100, arrival: 0))
- collector.record(sample(.applicationAudio, pts: 100.02, arrival: 0.025))
- collector.record(sample(.applicationAudio, pts: 100.04, arrival: 0.04, channels: 1))
- collector.record(sample(.microphone, pts: 100.08, arrival: 0.01))
- collector.record(sample(.microphone, pts: 100.10, arrival: 0.03))
- collector.record(sample(.microphone, pts: 100.14, arrival: 0.08))
+ collector.record(self.sample(.applicationAudio, pts: 100, arrival: 0))
+ collector.record(self.sample(.applicationAudio, pts: 100.02, arrival: 0.025))
+ collector.record(self.sample(.applicationAudio, pts: 100.04, arrival: 0.04, channels: 1))
+ collector.record(self.sample(.microphone, pts: 100.08, arrival: 0.01))
+ collector.record(self.sample(.microphone, pts: 100.10, arrival: 0.03))
+ collector.record(self.sample(.microphone, pts: 100.14, arrival: 0.08))
let report = collector.report()
XCTAssertEqual(report.acceptedSampleCount, 6)
@@ -50,13 +56,17 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
XCTAssertEqual(report.application.sampleCount, 3)
XCTAssertEqual(report.application.formatChangeCount, 1)
XCTAssertEqual(report.application.jitterObservationCount, 2)
- XCTAssertEqual(report.application.meanAbsoluteJitterSeconds!, 0.005, accuracy: 0.000_001)
+ XCTAssertEqual(try XCTUnwrap(report.application.meanAbsoluteJitterSeconds), 0.005, accuracy: 0.000_001)
XCTAssertEqual(report.microphone.gapCount, 1)
XCTAssertEqual(report.microphone.gapDurationSeconds, 0.02, accuracy: 0.000_001)
- XCTAssertEqual(report.crossTrack.firstPresentationOffsetSeconds!, 0.08, accuracy: 0.000_001)
- XCTAssertEqual(report.crossTrack.relativeTimestampSpanDifferencePPM!,
- ((report.microphone.timestampSpanSeconds! / report.application.timestampSpanSeconds!) - 1) * 1_000_000,
- accuracy: 0.001)
+ XCTAssertEqual(try XCTUnwrap(report.crossTrack.firstPresentationOffsetSeconds), 0.08, accuracy: 0.000_001)
+ let microphoneSpan = try XCTUnwrap(report.microphone.timestampSpanSeconds)
+ let applicationSpan = try XCTUnwrap(report.application.timestampSpanSeconds)
+ XCTAssertEqual(
+ try XCTUnwrap(report.crossTrack.relativeTimestampSpanDifferencePPM),
+ ((microphoneSpan / applicationSpan) - 1) * 1_000_000,
+ accuracy: 0.001
+ )
XCTAssertFalse(report.crossTrack.sharedClockEstablished)
XCTAssertNil(report.crossTrack.acousticDelaySeconds)
XCTAssertFalse(report.crossTrack.aecEvaluated)
@@ -68,23 +78,23 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
let rate = 48_000.0
let epsilon = 1e-9
let contiguous = MeetingSCKPairedDiagnosticCollector(environment: enabledEnvironment)
- contiguous.record(sample(.microphone, pts: 0, rate: rate, channels: 1))
- contiguous.record(sample(.microphone, pts: 0.02 + epsilon, rate: rate, channels: 1))
- contiguous.record(sample(.microphone, pts: 0.04 - epsilon, rate: rate, channels: 1))
+ contiguous.record(self.sample(.microphone, pts: 0, rate: rate, channels: 1))
+ contiguous.record(self.sample(.microphone, pts: 0.02 + epsilon, rate: rate, channels: 1))
+ contiguous.record(self.sample(.microphone, pts: 0.04 - epsilon, rate: rate, channels: 1))
let contiguousReport = contiguous.report().microphone
XCTAssertEqual(contiguousReport.gapCount, 0)
XCTAssertEqual(contiguousReport.overlapCount, 0)
XCTAssertEqual(contiguousReport.backwardsTimestampCount, 0)
let oneSampleGap = MeetingSCKPairedDiagnosticCollector(environment: enabledEnvironment)
- oneSampleGap.record(sample(.microphone, pts: 0, rate: rate, channels: 1))
- oneSampleGap.record(sample(.microphone, pts: 0.02 + 1 / rate, rate: rate, channels: 1))
+ oneSampleGap.record(self.sample(.microphone, pts: 0, rate: rate, channels: 1))
+ oneSampleGap.record(self.sample(.microphone, pts: 0.02 + 1 / rate, rate: rate, channels: 1))
XCTAssertEqual(oneSampleGap.report().microphone.gapCount, 1)
XCTAssertEqual(oneSampleGap.report().microphone.gapDurationSeconds, 1 / rate, accuracy: 1e-12)
let oneSampleOverlap = MeetingSCKPairedDiagnosticCollector(environment: enabledEnvironment)
- oneSampleOverlap.record(sample(.microphone, pts: 0, rate: rate, channels: 1))
- oneSampleOverlap.record(sample(.microphone, pts: 0.02 - 1 / rate, rate: rate, channels: 1))
+ oneSampleOverlap.record(self.sample(.microphone, pts: 0, rate: rate, channels: 1))
+ oneSampleOverlap.record(self.sample(.microphone, pts: 0.02 - 1 / rate, rate: rate, channels: 1))
XCTAssertEqual(oneSampleOverlap.report().microphone.overlapCount, 1)
}
@@ -92,11 +102,17 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
let collector = MeetingSCKPairedDiagnosticCollector(
configuration: .init(maximumSamples: 2), environment: enabledEnvironment
)
- collector.record(sample(.applicationAudio, pts: 1))
- collector.record(.init(output: .applicationAudio, presentationSeconds: .nan, durationSeconds: 0.02,
- frameCount: 960, sampleRateHz: 48_000, channelCount: 2))
- collector.record(sample(.microphone, pts: 1))
- collector.record(sample(.microphone, pts: 2))
+ collector.record(self.sample(.applicationAudio, pts: 1))
+ collector.record(.init(
+ output: .applicationAudio,
+ presentationSeconds: .nan,
+ durationSeconds: 0.02,
+ frameCount: 960,
+ sampleRateHz: 48_000,
+ channelCount: 2
+ ))
+ collector.record(self.sample(.microphone, pts: 1))
+ collector.record(self.sample(.microphone, pts: 2))
let report = collector.report()
XCTAssertEqual(report.acceptedSampleCount, 2)
@@ -109,7 +125,7 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
func testReportIsNumericAndDoesNotContainRawAudioOrTextFields() throws {
let collector = MeetingSCKPairedDiagnosticCollector(environment: enabledEnvironment)
- collector.record(sample(.microphone, pts: 3))
+ collector.record(self.sample(.microphone, pts: 3))
let data = try collector.report().jsonData()
let json = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
XCTAssertNil(json["samples"])
@@ -121,8 +137,8 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
func testDeterministicHarnessConsumesMetadataOnly() {
let report = MeetingSCKPairedDiagnosticHarness.run(
- [sample(.applicationAudio, pts: 2), sample(.microphone, pts: 2.1, channels: 1)],
- environment: enabledEnvironment
+ [self.sample(.applicationAudio, pts: 2), self.sample(.microphone, pts: 2.1, channels: 1)],
+ environment: self.enabledEnvironment
)
XCTAssertEqual(report.acceptedSampleCount, 2)
XCTAssertEqual(report.application.sampleCount, 1)
@@ -160,7 +176,7 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
scope: .selectedApplicationDisplay, applicationSelectionConfirmed: true
)
XCTAssertFalse(collector.record(
- sample(.microphone, pts: 5), provenance: provenance
+ self.sample(.microphone, pts: 5), provenance: provenance
))
XCTAssertEqual(collector.report().acceptedSampleCount, 0)
XCTAssertNil(collector.report().provenance)
@@ -171,16 +187,16 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
XCTAssertFalse(MeetingSCKPairedDiagnosticGate.hardwareEnabled(environment: [:]))
XCTAssertFalse(MeetingSCKPairedDiagnosticGate.hardwareEnabled(environment: [
MeetingSCKPairedDiagnosticGate.environmentKey: "1",
- MeetingSCKPairedDiagnosticGate.hardwareEnvironmentKey: "1"
+ MeetingSCKPairedDiagnosticGate.hardwareEnvironmentKey: "1",
]))
XCTAssertFalse(MeetingSCKPairedDiagnosticGate.hardwareEnabled(environment: [
MeetingSCKPairedDiagnosticGate.environmentKey: "1",
- MeetingSCKPairedDiagnosticGate.targetBundleIDEnvironmentKey: "com.example.Meeting"
+ MeetingSCKPairedDiagnosticGate.targetBundleIDEnvironmentKey: "com.example.Meeting",
]))
XCTAssertTrue(MeetingSCKPairedDiagnosticGate.hardwareEnabled(environment: [
MeetingSCKPairedDiagnosticGate.environmentKey: "1",
MeetingSCKPairedDiagnosticGate.hardwareEnvironmentKey: "1",
- MeetingSCKPairedDiagnosticGate.targetBundleIDEnvironmentKey: "com.example.Meeting"
+ MeetingSCKPairedDiagnosticGate.targetBundleIDEnvironmentKey: "com.example.Meeting",
]))
}
@@ -188,21 +204,23 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
let hardware = [
MeetingSCKPairedDiagnosticGate.environmentKey: "1",
MeetingSCKPairedDiagnosticGate.hardwareEnvironmentKey: "1",
- MeetingSCKPairedDiagnosticGate.targetBundleIDEnvironmentKey: "com.example.Meeting"
+ MeetingSCKPairedDiagnosticGate.targetBundleIDEnvironmentKey: "com.example.Meeting",
]
XCTAssertFalse(MeetingSCKPairedDiagnosticGate.autorunEnabled(environment: hardware))
XCTAssertFalse(MeetingSCKPairedDiagnosticGate.autorunEnabled(environment: hardware.merging([
- MeetingSCKPairedDiagnosticGate.autorunEnvironmentKey: "true"
+ MeetingSCKPairedDiagnosticGate.autorunEnvironmentKey: "true",
]) { _, new in new }))
XCTAssertTrue(MeetingSCKPairedDiagnosticGate.autorunEnabled(environment: hardware.merging([
- MeetingSCKPairedDiagnosticGate.autorunEnvironmentKey: "1"
+ MeetingSCKPairedDiagnosticGate.autorunEnvironmentKey: "1",
]) { _, new in new }))
XCTAssertFalse(MeetingSCKPairedAutorun.startIfRequested(environment: [:]))
}
func testAutorunTimeoutBudgetHasHardWatchdogHeadroom() {
- XCTAssertGreaterThan(MeetingSCKPairedAutorun.hardWatchdogSeconds,
- MeetingSCKPairedAutorun.maximumRunSeconds)
+ XCTAssertGreaterThan(
+ MeetingSCKPairedAutorun.hardWatchdogSeconds,
+ MeetingSCKPairedAutorun.maximumRunSeconds
+ )
XCTAssertLessThanOrEqual(MeetingSCKPairedAutorun.hardWatchdogSeconds, 15)
}
@@ -235,17 +253,17 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
XCTAssertFalse(MeetingExternalReferenceTrialAGate.autorunEnabled(environment: [
MeetingExternalReferenceTrialAGate.environmentKey: "1",
MeetingExternalReferenceTrialAGate.autorunEnvironmentKey: "1",
- MeetingExternalReferenceTrialAGate.targetBundleIDEnvironmentKey: "com.example.App"
+ MeetingExternalReferenceTrialAGate.targetBundleIDEnvironmentKey: "com.example.App",
]))
XCTAssertFalse(MeetingExternalReferenceTrialAGate.autorunEnabled(environment: [
MeetingExternalReferenceTrialAGate.environmentKey: "1",
MeetingExternalReferenceTrialAGate.autorunEnvironmentKey: "1",
- MeetingSCKPairedDiagnosticGate.targetBundleIDEnvironmentKey: "com.google.Chrome"
+ MeetingSCKPairedDiagnosticGate.targetBundleIDEnvironmentKey: "com.google.Chrome",
]))
XCTAssertTrue(MeetingExternalReferenceTrialAGate.autorunEnabled(environment: [
MeetingExternalReferenceTrialAGate.environmentKey: "1",
MeetingExternalReferenceTrialAGate.autorunEnvironmentKey: "1",
- MeetingExternalReferenceTrialAGate.targetBundleIDEnvironmentKey: "com.google.Chrome"
+ MeetingExternalReferenceTrialAGate.targetBundleIDEnvironmentKey: "com.google.Chrome",
]))
}
@@ -267,65 +285,105 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
func testTrialASelectsUniqueDisplayWithMaximumWindowIntersection() {
let left = MeetingExternalReferenceTrialADisplayCandidate(
- displayID: 1, frame: CGRect(x: 0, y: 0, width: 1_000, height: 800))
+ displayID: 1, frame: CGRect(x: 0, y: 0, width: 1000, height: 800)
+ )
let right = MeetingExternalReferenceTrialADisplayCandidate(
- displayID: 2, frame: CGRect(x: 1_000, y: 0, width: 1_000, height: 800))
+ displayID: 2, frame: CGRect(x: 1000, y: 0, width: 1000, height: 800)
+ )
let window = CGRect(x: 800, y: 100, width: 500, height: 400)
XCTAssertEqual(
MeetingExternalReferenceTrialADisplaySelector.selectDisplayID(
- windowFrame: window, displays: [left, right]), 2)
+ windowFrame: window, displays: [left, right]
+ ), 2
+ )
}
func testTrialADisplaySelectionFailsClosedForNoIntersectionAndTie() {
let first = MeetingExternalReferenceTrialADisplayCandidate(
- displayID: 1, frame: CGRect(x: 0, y: 0, width: 1_000, height: 800))
+ displayID: 1, frame: CGRect(x: 0, y: 0, width: 1000, height: 800)
+ )
let second = MeetingExternalReferenceTrialADisplayCandidate(
- displayID: 2, frame: CGRect(x: 1_000, y: 0, width: 1_000, height: 800))
+ displayID: 2, frame: CGRect(x: 1000, y: 0, width: 1000, height: 800)
+ )
XCTAssertNil(MeetingExternalReferenceTrialADisplaySelector.selectDisplayID(
- windowFrame: CGRect(x: 3_000, y: 0, width: 100, height: 100), displays: [first, second]))
+ windowFrame: CGRect(x: 3000, y: 0, width: 100, height: 100), displays: [first, second]
+ ))
XCTAssertNil(MeetingExternalReferenceTrialADisplaySelector.selectDisplayID(
- windowFrame: CGRect(x: 800, y: 100, width: 400, height: 400), displays: [first, second]))
+ windowFrame: CGRect(x: 800, y: 100, width: 400, height: 400), displays: [first, second]
+ ))
}
func testTrialAWindowSelectionUsesOwningWindowAuthorityAcrossDuplicateAppRecords() {
let staleRecordWindow = MeetingExternalReferenceTrialAWindowCandidate(
- windowID: 1, owningBundleIdentifier: "com.google.Chrome", owningProcessID: 101,
- title: "FluidVoice C2 Diagnostic Stimulus — READY")
+ windowID: 1,
+ owningBundleIdentifier: "com.google.Chrome",
+ owningProcessID: 101,
+ title: "FluidVoice C2 Diagnostic Stimulus — READY"
+ )
let playingWindow = MeetingExternalReferenceTrialAWindowCandidate(
- windowID: 2, owningBundleIdentifier: "com.google.Chrome", owningProcessID: 202,
- title: "FluidVoice C2 Diagnostic Stimulus — PLAYING")
+ windowID: 2,
+ owningBundleIdentifier: "com.google.Chrome",
+ owningProcessID: 202,
+ title: "FluidVoice C2 Diagnostic Stimulus — PLAYING"
+ )
let selected = MeetingExternalReferenceTrialAWindowSelector.selectPlayingWindow(
- from: [staleRecordWindow, playingWindow], targetBundleIdentifier: "com.google.Chrome")
+ from: [staleRecordWindow, playingWindow], targetBundleIdentifier: "com.google.Chrome"
+ )
XCTAssertEqual(selected?.windowID, 2)
XCTAssertEqual(selected?.owningProcessID, 202)
}
func testTrialAWindowSelectionFailsClosedForDuplicatePlayingWindowsOrWrongOwner() {
let first = MeetingExternalReferenceTrialAWindowCandidate(
- windowID: 1, owningBundleIdentifier: "com.google.Chrome", owningProcessID: 101,
- title: "FluidVoice C2 Diagnostic Stimulus — PLAYING")
+ windowID: 1,
+ owningBundleIdentifier: "com.google.Chrome",
+ owningProcessID: 101,
+ title: "FluidVoice C2 Diagnostic Stimulus — PLAYING"
+ )
let second = MeetingExternalReferenceTrialAWindowCandidate(
- windowID: 2, owningBundleIdentifier: "com.google.Chrome", owningProcessID: 202,
- title: "FluidVoice C2 Diagnostic Stimulus — PLAYING")
+ windowID: 2,
+ owningBundleIdentifier: "com.google.Chrome",
+ owningProcessID: 202,
+ title: "FluidVoice C2 Diagnostic Stimulus — PLAYING"
+ )
XCTAssertNil(MeetingExternalReferenceTrialAWindowSelector.selectPlayingWindow(
- from: [first, second], targetBundleIdentifier: "com.google.Chrome"))
+ from: [first, second], targetBundleIdentifier: "com.google.Chrome"
+ ))
let wrongOwner = MeetingExternalReferenceTrialAWindowCandidate(
- windowID: 3, owningBundleIdentifier: "com.apple.Safari", owningProcessID: 303,
- title: "FluidVoice C2 Diagnostic Stimulus — PLAYING")
+ windowID: 3,
+ owningBundleIdentifier: "com.apple.Safari",
+ owningProcessID: 303,
+ title: "FluidVoice C2 Diagnostic Stimulus — PLAYING"
+ )
XCTAssertNil(MeetingExternalReferenceTrialAWindowSelector.selectPlayingWindow(
- from: [wrongOwner], targetBundleIdentifier: "com.google.Chrome"))
+ from: [wrongOwner], targetBundleIdentifier: "com.google.Chrome"
+ ))
}
func testTrialAOfflineAnalyzerRejectsGapsOverlapsSynthesizedAndBadGeometry() throws {
- func sample(_ pts: Double, _ duration: Double = 0.1, synthesized: Bool = false,
- frames: Int = 4_800, arrival: Double? = nil) -> MeetingExternalReferenceTrialATrackSample {
- .init(presentationSeconds: pts, durationSeconds: duration, frameCount: frames,
- sampleRateHz: 48_000, channelCount: 1, synthesizedTiming: synthesized,
- rms: 0.05, peak: 0.08, arrivalSeconds: arrival)
+ func sample(
+ _ pts: Double,
+ _ duration: Double = 0.1,
+ synthesized: Bool = false,
+ frames: Int = 4800,
+ arrival: Double? = nil
+ ) -> MeetingExternalReferenceTrialATrackSample {
+ .init(
+ presentationSeconds: pts,
+ durationSeconds: duration,
+ frameCount: frames,
+ sampleRateHz: 48_000,
+ channelCount: 1,
+ synthesizedTiming: synthesized,
+ rms: 0.05,
+ peak: 0.08,
+ arrivalSeconds: arrival
+ )
}
let clean = MeetingExternalReferenceTrialAOfflineHarness.analyze(
reference: [sample(0), sample(0.1), sample(0.2)],
- microphone: [sample(0), sample(0.1), sample(0.2)])
+ microphone: [sample(0), sample(0.1), sample(0.2)]
+ )
XCTAssertFalse(clean.valid, "clock mapping is intentionally still unknown")
XCTAssertFalse(clean.reference.timingValid, "three tenths of audio cannot cover a five-second request")
XCTAssertEqual(clean.reference.coverageFraction, 0.06, accuracy: 0.000_001)
@@ -333,11 +391,13 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
XCTAssertNil(clean.clock.acousticDelaySeconds)
let completeTiming = MeetingExternalReferenceTrialATrackReport.analyze(
- [sample(0), sample(0.1), sample(0.2)], requestedDurationSeconds: 0.3)
+ [sample(0), sample(0.1), sample(0.2)], requestedDurationSeconds: 0.3
+ )
XCTAssertTrue(completeTiming.timingValid)
let ninetyFivePercent = MeetingExternalReferenceTrialATrackReport.analyze(
- (0..<19).map { sample(Double($0) * 0.1) }, requestedDurationSeconds: 2.0)
+ (0..<19).map { sample(Double($0) * 0.1) }, requestedDurationSeconds: 2.0
+ )
XCTAssertEqual(ninetyFivePercent.coverageFraction, 0.95, accuracy: 0.000_001)
XCTAssertFalse(ninetyFivePercent.timingValid, "95% coverage is not complete capture")
@@ -345,7 +405,8 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
[sample(0, arrival: 10), sample(0.1, arrival: 10.1), sample(0.2, arrival: 10.2)],
requestedDurationSeconds: 0.3,
captureOpenArrivalSeconds: 0,
- captureCloseArrivalSeconds: 0.3)
+ captureCloseArrivalSeconds: 0.3
+ )
XCTAssertFalse(shiftedArrival.arrivalBoundaryValid)
XCTAssertFalse(shiftedArrival.timingValid)
@@ -353,7 +414,8 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
[sample(0), sample(0.1), sample(0.2)],
requestedDurationSeconds: 0.3,
captureOpenArrivalSeconds: 0,
- captureCloseArrivalSeconds: 0.3)
+ captureCloseArrivalSeconds: 0.3
+ )
XCTAssertFalse(missingArrival.arrivalBoundaryValid)
XCTAssertFalse(missingArrival.timingValid)
@@ -361,27 +423,36 @@ final class MeetingSCKPairedDiagnosticsTests: XCTestCase {
[sample(0, arrival: 0.01), sample(0.1, arrival: 0.11), sample(0.2, arrival: 0.21)],
requestedDurationSeconds: 0.3,
captureOpenArrivalSeconds: 0,
- captureCloseArrivalSeconds: 0.3)
+ captureCloseArrivalSeconds: 0.3
+ )
XCTAssertTrue(boundedArrival.arrivalBoundaryValid)
XCTAssertTrue(boundedArrival.timingValid)
let invalid = MeetingExternalReferenceTrialATrackReport.analyze(
[sample(0), sample(0.2), sample(0.15, synthesized: true), sample(.nan), sample(0.3, frames: 1)],
- requestedDurationSeconds: 0.3)
+ requestedDurationSeconds: 0.3
+ )
XCTAssertEqual(invalid.gapCount, 1)
XCTAssertEqual(invalid.overlapCount, 1)
- XCTAssertEqual(invalid.synthesizedFrameCount, 4_800)
+ XCTAssertEqual(invalid.synthesizedFrameCount, 4800)
XCTAssertEqual(invalid.invalidTimestampCount, 2)
XCTAssertFalse(invalid.timingValid)
}
func testTrialAReportIsNumericOnlyAndNoPlaybackOrRetention() throws {
let sample = MeetingExternalReferenceTrialATrackSample(
- presentationSeconds: 0, durationSeconds: 0.1, frameCount: 4_800,
- sampleRateHz: 48_000, channelCount: 1, synthesizedTiming: false,
- rms: 0.05, peak: 0.08)
+ presentationSeconds: 0,
+ durationSeconds: 0.1,
+ frameCount: 4800,
+ sampleRateHz: 48_000,
+ channelCount: 1,
+ synthesizedTiming: false,
+ rms: 0.05,
+ peak: 0.08
+ )
let report = MeetingExternalReferenceTrialAOfflineHarness.analyze(
- reference: [sample], microphone: [sample])
+ reference: [sample], microphone: [sample]
+ )
let data = try JSONEncoder().encode(report)
let object = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
XCTAssertEqual(object["appOwnedPlayback"] as? Bool, false)
diff --git a/Tests/FluidDictationIntegrationTests/MeetingSCKPairedHardwareTests.swift b/Tests/FluidDictationIntegrationTests/MeetingSCKPairedHardwareTests.swift
index 2de7e5de..a1cd4554 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingSCKPairedHardwareTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingSCKPairedHardwareTests.swift
@@ -1,8 +1,8 @@
#if DEBUG
-@testable import FluidVoice_Debug
import AVFoundation
import CoreMedia
+@testable import FluidVoice_Debug
import Foundation
import ScreenCaptureKit
import XCTest
@@ -22,7 +22,8 @@ final class MeetingSCKPairedHardwareTests: XCTestCase {
)
}
guard let bundleID = environment[MeetingSCKPairedDiagnosticGate.targetBundleIDEnvironmentKey]?
- .trimmingCharacters(in: .whitespacesAndNewlines), !bundleID.isEmpty else {
+ .trimmingCharacters(in: .whitespacesAndNewlines), !bundleID.isEmpty
+ else {
throw XCTSkip("FLUIDVOICE_C2_TARGET_BUNDLE_ID is empty")
}
guard AVCaptureDevice.authorizationStatus(for: .audio) == .authorized else {
@@ -87,6 +88,8 @@ final class MeetingSCKPairedHardwareTests: XCTestCase {
let report = collector.report()
let data = try report.jsonData()
+ // JSONEncoder fixture bytes are UTF-8; retain nonoptional decoding for assertions.
+ // swiftlint:disable:next optional_data_string_conversion
print("[C2] sorted report JSON: \(String(decoding: data, as: UTF8.self))")
XCTAssertTrue(report.enabled)
XCTAssertEqual(report.provenance, provenance)
diff --git a/Tests/FluidDictationIntegrationTests/MeetingStage05EvidenceTests.swift b/Tests/FluidDictationIntegrationTests/MeetingStage05EvidenceTests.swift
index c0feb51a..af387c58 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingStage05EvidenceTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingStage05EvidenceTests.swift
@@ -1,78 +1,126 @@
#if DEBUG
-@testable import FluidVoice_Debug
import CoreAudio
+@testable import FluidVoice_Debug
import Foundation
import XCTest
final class MeetingStage05EvidenceTests: XCTestCase {
- private func window(_ id: UInt32 = 1, bundle: String? = "com.google.Chrome",
- pid: Int32 = 42, title: String? = MeetingStage05StimulusHandshake.readyTitle
+ private func window(
+ _ id: UInt32 = 1,
+ bundle: String? = "com.google.Chrome",
+ pid: Int32 = 42,
+ title: String? = MeetingStage05StimulusHandshake.readyTitle
) -> MeetingExternalReferenceTrialAWindowCandidate {
.init(windowID: id, owningBundleIdentifier: bundle, owningProcessID: pid, title: title)
}
func testReadySelectionRequiresExactlyOneOwnedExactReadyWindow() {
- let ready = window()
+ let ready = self.window()
XCTAssertEqual(
MeetingStage05StimulusHandshake.selectReadyWindow(
- from: [ready, window(2, title: "Unrelated")], targetBundleIdentifier: "com.google.Chrome"),
- ready)
+ from: [ready, self.window(2, title: "Unrelated")], targetBundleIdentifier: "com.google.Chrome"
+ ),
+ ready
+ )
XCTAssertNil(MeetingStage05StimulusHandshake.selectReadyWindow(
- from: [ready, window(2)], targetBundleIdentifier: "com.google.Chrome"))
+ from: [ready, self.window(2)], targetBundleIdentifier: "com.google.Chrome"
+ ))
XCTAssertNil(MeetingStage05StimulusHandshake.selectReadyWindow(
- from: [window(bundle: "com.apple.Safari")], targetBundleIdentifier: "com.google.Chrome"))
+ from: [self.window(bundle: "com.apple.Safari")], targetBundleIdentifier: "com.google.Chrome"
+ ))
XCTAssertNil(MeetingStage05StimulusHandshake.selectReadyWindow(
- from: [window(0)], targetBundleIdentifier: "com.google.Chrome"))
+ from: [self.window(0)], targetBundleIdentifier: "com.google.Chrome"
+ ))
}
func testReadyToPlayingTransitionSucceedsForSameWindowOwnerAndPID() {
- let ready = window()
- let playing = window(title: "FluidVoice C2 Diagnostic Stimulus — PLAYING — 24s")
+ let ready = self.window()
+ let playing = self.window(title: "FluidVoice C2 Diagnostic Stimulus — PLAYING — 24s")
let decision = MeetingStage05StimulusHandshake.decision(
- for: ready, current: [playing], targetBundleIdentifier: "com.google.Chrome",
- now: 0.5, deadline: 2)
+ for: ready,
+ current: [playing],
+ targetBundleIdentifier: "com.google.Chrome",
+ now: 0.5,
+ deadline: 2
+ )
XCTAssertEqual(decision, .success(playing))
}
func testPlayingTransitionRejectsAmbiguityAndIdentityChanges() {
- let ready = window()
- let playing = window(title: "FluidVoice C2 Diagnostic Stimulus — PLAYING — 24s")
+ let ready = self.window()
+ let playing = self.window(title: "FluidVoice C2 Diagnostic Stimulus — PLAYING — 24s")
XCTAssertEqual(MeetingStage05StimulusHandshake.decision(
- for: ready, current: [playing, window(2, title: "FluidVoice C2 Diagnostic Stimulus — PLAYING — 11s")],
- targetBundleIdentifier: "com.google.Chrome", now: 0.5, deadline: 2), .failure(.ambiguous))
+ for: ready,
+ current: [playing, self.window(2, title: "FluidVoice C2 Diagnostic Stimulus — PLAYING — 11s")],
+ targetBundleIdentifier: "com.google.Chrome",
+ now: 0.5,
+ deadline: 2
+ ), .failure(.ambiguous))
XCTAssertEqual(MeetingStage05StimulusHandshake.decision(
- for: ready, current: [window(bundle: "com.apple.Safari", title: "FluidVoice C2 Diagnostic Stimulus — PLAYING — 24s")],
- targetBundleIdentifier: "com.google.Chrome", now: 0.5, deadline: 2), .failure(.ownerChanged))
+ for: ready,
+ current: [self.window(bundle: "com.apple.Safari", title: "FluidVoice C2 Diagnostic Stimulus — PLAYING — 24s")],
+ targetBundleIdentifier: "com.google.Chrome",
+ now: 0.5,
+ deadline: 2
+ ), .failure(.ownerChanged))
XCTAssertEqual(MeetingStage05StimulusHandshake.decision(
- for: ready, current: [window(pid: 43, title: "FluidVoice C2 Diagnostic Stimulus — PLAYING — 24s")],
- targetBundleIdentifier: "com.google.Chrome", now: 0.5, deadline: 2), .failure(.processChanged))
+ for: ready,
+ current: [self.window(pid: 43, title: "FluidVoice C2 Diagnostic Stimulus — PLAYING — 24s")],
+ targetBundleIdentifier: "com.google.Chrome",
+ now: 0.5,
+ deadline: 2
+ ), .failure(.processChanged))
XCTAssertEqual(MeetingStage05StimulusHandshake.decision(
- for: ready, current: [window(2, title: "FluidVoice C2 Diagnostic Stimulus — PLAYING — 24s")],
- targetBundleIdentifier: "com.google.Chrome", now: 0.5, deadline: 2), .failure(.windowChanged))
+ for: ready,
+ current: [self.window(2, title: "FluidVoice C2 Diagnostic Stimulus — PLAYING — 24s")],
+ targetBundleIdentifier: "com.google.Chrome",
+ now: 0.5,
+ deadline: 2
+ ), .failure(.windowChanged))
}
func testPlayingTransitionRejectsTimeoutMalformedAndInsufficientRemainingTime() {
- let ready = window()
+ let ready = self.window()
XCTAssertEqual(MeetingStage05StimulusHandshake.decision(
- for: ready, current: [ready], targetBundleIdentifier: "com.google.Chrome",
- now: 2, deadline: 2), .failure(.timeout))
+ for: ready,
+ current: [ready],
+ targetBundleIdentifier: "com.google.Chrome",
+ now: 2,
+ deadline: 2
+ ), .failure(.timeout))
XCTAssertEqual(MeetingStage05StimulusHandshake.decision(
- for: ready, current: [window(title: "FluidVoice C2 Diagnostic Stimulus — COMPLETE")],
- targetBundleIdentifier: "com.google.Chrome", now: 0.5, deadline: 2), .failure(.malformedState))
+ for: ready,
+ current: [self.window(title: "FluidVoice C2 Diagnostic Stimulus — COMPLETE")],
+ targetBundleIdentifier: "com.google.Chrome",
+ now: 0.5,
+ deadline: 2
+ ), .failure(.malformedState))
XCTAssertEqual(MeetingStage05StimulusHandshake.decision(
- for: ready, current: [window(title: "FluidVoice C2 Diagnostic Stimulus — PLAYING — 21s")],
- targetBundleIdentifier: "com.google.Chrome", now: 0.5, deadline: 2), .failure(.remainingInsufficient))
+ for: ready,
+ current: [self.window(title: "FluidVoice C2 Diagnostic Stimulus — PLAYING — 21s")],
+ targetBundleIdentifier: "com.google.Chrome",
+ now: 0.5,
+ deadline: 2
+ ), .failure(.remainingInsufficient))
}
func testHandshakeDecisionMayWaitBeforePlaybackWithoutStartingCapture() {
- let ready = window()
+ let ready = self.window()
XCTAssertEqual(MeetingStage05StimulusHandshake.decision(
- for: ready, current: [ready], targetBundleIdentifier: "com.google.Chrome",
- now: 7.99, deadline: 8), .waiting)
+ for: ready,
+ current: [ready],
+ targetBundleIdentifier: "com.google.Chrome",
+ now: 7.99,
+ deadline: 8
+ ), .waiting)
XCTAssertEqual(MeetingStage05StimulusHandshake.decision(
- for: ready, current: [ready], targetBundleIdentifier: "com.google.Chrome",
- now: 8, deadline: 8), .failure(.timeout))
+ for: ready,
+ current: [ready],
+ targetBundleIdentifier: "com.google.Chrome",
+ now: 8,
+ deadline: 8
+ ), .failure(.timeout))
}
func testPlayingCountdownParserRequiresTheExactBoundedTitle() {
@@ -123,10 +171,16 @@ final class MeetingStage05EvidenceTests: XCTestCase {
func testNativeMonoFloat32FormatIsAcceptedWithoutConversion() {
let asbd = AudioStreamBasicDescription(
- mSampleRate: 48_000, mFormatID: kAudioFormatLinearPCM,
+ mSampleRate: 48_000,
+ mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
- mBytesPerPacket: 4, mFramesPerPacket: 1, mBytesPerFrame: 4,
- mChannelsPerFrame: 1, mBitsPerChannel: 32, mReserved: 0)
+ mBytesPerPacket: 4,
+ mFramesPerPacket: 1,
+ mBytesPerFrame: 4,
+ mChannelsPerFrame: 1,
+ mBitsPerChannel: 32,
+ mReserved: 0
+ )
XCTAssertEqual(MeetingStage05NativePCMFormat.from(asbd)?.codec, "pcm_f32le")
XCTAssertEqual(MeetingStage05NativePCMFormat.from(asbd)?.bytesPerFrame, 4)
}
@@ -143,15 +197,27 @@ final class MeetingStage05EvidenceTests: XCTestCase {
func testStereoAndIntegerFormatsFailClosed() {
let stereo = AudioStreamBasicDescription(
- mSampleRate: 48_000, mFormatID: kAudioFormatLinearPCM,
+ mSampleRate: 48_000,
+ mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
- mBytesPerPacket: 8, mFramesPerPacket: 1, mBytesPerFrame: 8,
- mChannelsPerFrame: 2, mBitsPerChannel: 32, mReserved: 0)
+ mBytesPerPacket: 8,
+ mFramesPerPacket: 1,
+ mBytesPerFrame: 8,
+ mChannelsPerFrame: 2,
+ mBitsPerChannel: 32,
+ mReserved: 0
+ )
let integer = AudioStreamBasicDescription(
- mSampleRate: 48_000, mFormatID: kAudioFormatLinearPCM,
+ mSampleRate: 48_000,
+ mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked,
- mBytesPerPacket: 2, mFramesPerPacket: 1, mBytesPerFrame: 2,
- mChannelsPerFrame: 1, mBitsPerChannel: 16, mReserved: 0)
+ mBytesPerPacket: 2,
+ mFramesPerPacket: 1,
+ mBytesPerFrame: 2,
+ mChannelsPerFrame: 1,
+ mBitsPerChannel: 16,
+ mReserved: 0
+ )
XCTAssertNil(MeetingStage05NativePCMFormat.from(stereo))
XCTAssertNil(MeetingStage05NativePCMFormat.from(integer))
}
@@ -159,11 +225,11 @@ final class MeetingStage05EvidenceTests: XCTestCase {
func testConsentAndCaptureAreExplicitlyOptIn() {
XCTAssertFalse(MeetingStage05EvidenceAutorun.requested(environment: [:]))
XCTAssertFalse(MeetingStage05EvidenceAutorun.consentConfirmed(environment: [
- MeetingStage05EvidenceAutorun.consentEnvironmentKey: "1"
+ MeetingStage05EvidenceAutorun.consentEnvironmentKey: "1",
]))
XCTAssertTrue(MeetingStage05EvidenceAutorun.consentConfirmed(environment: [
MeetingStage05EvidenceAutorun.consentEnvironmentKey:
- MeetingStage05EvidenceAutorun.consentToken
+ MeetingStage05EvidenceAutorun.consentToken,
]))
let complete = [
MeetingStage05EvidenceAutorun.environmentKey: "1",
@@ -177,7 +243,7 @@ final class MeetingStage05EvidenceTests: XCTestCase {
]
XCTAssertTrue(MeetingStage05EvidenceAutorun.requested(environment: complete))
XCTAssertFalse(MeetingStage05EvidenceAutorun.requested(environment: complete.merging([
- MeetingStage05EvidenceAutorun.consentEnvironmentKey: "1"
+ MeetingStage05EvidenceAutorun.consentEnvironmentKey: "1",
]) { _, new in new }))
let operatorMedia = complete.merging([
MeetingStage05EvidenceAutorun.operatorMediaConsentEnvironmentKey:
@@ -186,7 +252,7 @@ final class MeetingStage05EvidenceTests: XCTestCase {
XCTAssertTrue(MeetingStage05EvidenceAutorun.requested(environment: operatorMedia))
XCTAssertTrue(MeetingStage05EvidenceAutorun.operatorMediaRequested(environment: operatorMedia))
XCTAssertFalse(MeetingStage05EvidenceAutorun.requested(environment: operatorMedia.merging([
- MeetingStage05EvidenceAutorun.operatorMediaConsentEnvironmentKey: "1"
+ MeetingStage05EvidenceAutorun.operatorMediaConsentEnvironmentKey: "1",
]) { _, new in new }))
XCTAssertEqual(MeetingStage05EvidenceAutorun.remainingStimulusSeconds(
"FluidVoice C2 Diagnostic Stimulus — PLAYING — 24s"), 24)
@@ -205,9 +271,13 @@ final class MeetingStage05EvidenceTests: XCTestCase {
height: CGFloat = 720
) -> Bool {
MeetingStage05EvidenceAutorun.operatorMediaWindowIsEligible(
- windowID: id, owningBundleIdentifier: bundle, owningProcessID: pid,
- frameWidth: width, frameHeight: height,
- targetBundleIdentifier: "com.google.Chrome")
+ windowID: id,
+ owningBundleIdentifier: bundle,
+ owningProcessID: pid,
+ frameWidth: width,
+ frameHeight: height,
+ targetBundleIdentifier: "com.google.Chrome"
+ )
}
XCTAssertTrue(eligible())
XCTAssertFalse(eligible(id: 0))
diff --git a/Tests/FluidDictationIntegrationTests/MeetingStage05SCKFrameAdapterTests.swift b/Tests/FluidDictationIntegrationTests/MeetingStage05SCKFrameAdapterTests.swift
index 2d88b313..3fc756f3 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingStage05SCKFrameAdapterTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingStage05SCKFrameAdapterTests.swift
@@ -1,9 +1,9 @@
#if DEBUG
-@testable import FluidVoice_Debug
import CoreAudio
import CoreMedia
import Darwin
+@testable import FluidVoice_Debug
import Foundation
import XCTest
@@ -20,42 +20,76 @@ enum Stage05SyntheticBuffer {
) -> CMSampleBuffer? {
let bytesPerFrame = 4 * channels
var asbd = AudioStreamBasicDescription(
- mSampleRate: sampleRate, mFormatID: kAudioFormatLinearPCM,
+ mSampleRate: sampleRate,
+ mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
- mBytesPerPacket: UInt32(bytesPerFrame), mFramesPerPacket: 1,
+ mBytesPerPacket: UInt32(bytesPerFrame),
+ mFramesPerPacket: 1,
mBytesPerFrame: UInt32(bytesPerFrame),
- mChannelsPerFrame: UInt32(channels), mBitsPerChannel: 32, mReserved: 0)
+ mChannelsPerFrame: UInt32(channels),
+ mBitsPerChannel: 32,
+ mReserved: 0
+ )
var formatDescription: CMAudioFormatDescription?
guard CMAudioFormatDescriptionCreate(
- allocator: kCFAllocatorDefault, asbd: &asbd, layoutSize: 0, layout: nil,
- magicCookieSize: 0, magicCookie: nil, extensions: nil,
- formatDescriptionOut: &formatDescription) == noErr, let formatDescription else { return nil }
+ allocator: kCFAllocatorDefault,
+ asbd: &asbd,
+ layoutSize: 0,
+ layout: nil,
+ magicCookieSize: 0,
+ magicCookie: nil,
+ extensions: nil,
+ formatDescriptionOut: &formatDescription
+ ) == noErr, let formatDescription else { return nil }
let byteCount = frameCount * bytesPerFrame
var blockBuffer: CMBlockBuffer?
guard CMBlockBufferCreateWithMemoryBlock(
- allocator: kCFAllocatorDefault, memoryBlock: nil, blockLength: byteCount,
- blockAllocator: kCFAllocatorDefault, customBlockSource: nil, offsetToData: 0,
- dataLength: byteCount, flags: 0, blockBufferOut: &blockBuffer) == noErr,
- let blockBuffer else { return nil }
+ allocator: kCFAllocatorDefault,
+ memoryBlock: nil,
+ blockLength: byteCount,
+ blockAllocator: kCFAllocatorDefault,
+ customBlockSource: nil,
+ offsetToData: 0,
+ dataLength: byteCount,
+ flags: 0,
+ blockBufferOut: &blockBuffer
+ ) == noErr,
+ let blockBuffer else { return nil }
let samples = [Float](repeating: value, count: frameCount * channels)
guard samples.withUnsafeBytes({
- CMBlockBufferReplaceDataBytes(with: $0.baseAddress!, blockBuffer: blockBuffer,
- offsetIntoDestination: 0, dataLength: byteCount)
+ CMBlockBufferReplaceDataBytes(
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ with: $0.baseAddress!,
+ blockBuffer: blockBuffer,
+ offsetIntoDestination: 0,
+ dataLength: byteCount
+ )
}) == noErr else { return nil }
var timing = CMSampleTimingInfo(
duration: CMTime(value: 1, timescale: CMTimeScale(sampleRate)),
presentationTimeStamp: CMTime(seconds: pts, preferredTimescale: 1_000_000_000),
- decodeTimeStamp: .invalid)
+ decodeTimeStamp: .invalid
+ )
var sampleBuffer: CMSampleBuffer?
guard CMSampleBufferCreate(
- allocator: kCFAllocatorDefault, dataBuffer: blockBuffer, dataReady: true,
- makeDataReadyCallback: nil, refcon: nil, formatDescription: formatDescription,
- sampleCount: frameCount, sampleTimingEntryCount: 1, sampleTimingArray: &timing,
- sampleSizeEntryCount: 0, sampleSizeArray: nil,
- sampleBufferOut: &sampleBuffer) == noErr, let sampleBuffer else { return nil }
+ allocator: kCFAllocatorDefault,
+ dataBuffer: blockBuffer,
+ dataReady: true,
+ makeDataReadyCallback: nil,
+ refcon: nil,
+ formatDescription: formatDescription,
+ sampleCount: frameCount,
+ sampleTimingEntryCount: 1,
+ sampleTimingArray: &timing,
+ sampleSizeEntryCount: 0,
+ sampleSizeArray: nil,
+ sampleBufferOut: &sampleBuffer
+ ) == noErr, let sampleBuffer else { return nil }
if discontinuity,
let attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, createIfNecessary: true) as? [NSMutableDictionary],
- let first = attachments.first {
+ let first = attachments.first
+ {
first[MeetingStage05SCKFrameAdapter.discontinuityAttachmentKey] = true
}
return sampleBuffer
@@ -70,11 +104,16 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
pts: Double, frames: Int? = nil, arrival: Double? = nil,
value: Float = 0.5, discontinuity: Bool = false
) -> MeetingStage05AdapterFrame {
- let count = frames ?? blockFrames
+ let count = frames ?? self.blockFrames
return MeetingStage05AdapterFrame(
- presentationSeconds: pts, durationSeconds: Double(count) / rate,
- frameCount: count, sampleRateHz: rate, arrivalSeconds: arrival,
- samples: [Float](repeating: value, count: count), discontinuity: discontinuity)
+ presentationSeconds: pts,
+ durationSeconds: Double(count) / self.rate,
+ frameCount: count,
+ sampleRateHz: self.rate,
+ arrivalSeconds: arrival,
+ samples: [Float](repeating: value, count: count),
+ discontinuity: discontinuity
+ )
}
private func feedPaired(
@@ -86,16 +125,16 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
let base = Double(index) * 0.01
let renderPTS = base + (renderGap.map { index >= $0.at ? $0.seconds : 0 } ?? 0)
let micPTS = base + (microphoneGap.map { index >= $0.at ? $0.seconds : 0 } ?? 0)
- XCTAssertNil(adapter.appendRenderFrame(block(pts: renderPTS, value: 0.25)))
- XCTAssertNil(adapter.appendMicrophoneFrame(block(pts: micPTS, arrival: micPTS, value: 0.5)))
+ XCTAssertNil(adapter.appendRenderFrame(self.block(pts: renderPTS, value: 0.25)))
+ XCTAssertNil(adapter.appendMicrophoneFrame(self.block(pts: micPTS, arrival: micPTS, value: 0.5)))
}
}
- // MARK: Contiguous baseline and mock-seam contract
+ // MARK: - Contiguous baseline and mock-seam contract
func testContiguousPairedCallbacksSynchronizeAndValidateRenderBeforeCapture() {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
- feedPaired(adapter, count: 10)
+ self.feedPaired(adapter, count: 10)
let (drained, result) = adapter.synchronize()
XCTAssertEqual(drained.renderDiagnostics, MeetingStage05AdapterTrackDiagnostics(accepted: 10))
@@ -128,12 +167,13 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
XCTAssertTrue(MeetingAECDelayContract(renderLeadSeconds: 0.010).validates(events: seam.events))
}
- // MARK: Gap matrix
+ // MARK: - Gap matrix
private func runRenderGap(gapSeconds: Double, gapIndex: Int = 20, blocks: Int = 40)
- -> (MeetingStage05AdapterDrain, MeetingSynchronizationResult) {
+ -> (MeetingStage05AdapterDrain, MeetingSynchronizationResult)
+ {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
- feedPaired(adapter, count: blocks, renderGap: (gapIndex, gapSeconds))
+ self.feedPaired(adapter, count: blocks, renderGap: (gapIndex, gapSeconds))
return adapter.synchronize()
}
@@ -154,20 +194,33 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
frame.adaptationFrozen
&& frame.captureValidMask.allSatisfy { $0 }
&& zip(frame.renderSamples, frame.renderValidMask).allSatisfy { $0.1 || $0.0 == 0 }
- }, file: file, line: line)
- XCTAssertEqual(result.frames.filter(\.resynchronizationBoundary).map(\.index),
- [boundaryIndex], file: file, line: line)
+ }, file: file,
+ line: line)
+ XCTAssertEqual(
+ result.frames.filter(\.resynchronizationBoundary).map(\.index),
+ [boundaryIndex],
+ file: file,
+ line: line
+ )
XCTAssertEqual(result.frames[resumedIndex].epochID, 1, file: file, line: line)
- XCTAssertTrue(result.frames[resumedIndex].renderValidMask.allSatisfy { $0 },
- file: file, line: line)
+ XCTAssertTrue(
+ result.frames[resumedIndex].renderValidMask.allSatisfy { $0 },
+ file: file,
+ line: line
+ )
}
func testAdapterDrivenTwoMillisecondRenderJumpYieldsExactly32InvalidSamples() {
- let (drained, result) = runRenderGap(gapSeconds: 0.002)
+ let (drained, result) = self.runRenderGap(gapSeconds: 0.002)
XCTAssertEqual(drained.renderDiagnostics.gapCount, 1)
XCTAssertEqual(drained.renderDiagnostics.acceptedCallbackCount, 40)
- assertRenderGap(result, gapIndices: 20..<21, invalidRender: 32,
- boundaryIndex: 20, resumedIndex: 21)
+ self.assertRenderGap(
+ result,
+ gapIndices: 20..<21,
+ invalidRender: 32,
+ boundaryIndex: 20,
+ resumedIndex: 21
+ )
let resumed = result.frames[21]
XCTAssertEqual(resumed.epochID, 1)
@@ -188,16 +241,20 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
XCTAssertEqual(seam.observations[20].renderValidCount, 128)
XCTAssertEqual(seam.observations[20].captureValidCount, 160)
XCTAssertTrue(seam.observations[20].unknownReasons.contains(.referenceGap))
- XCTAssertFalse(MeetingAECDelayContract(renderLeadSeconds: 0.010).validates(events: seam.events),
- "a frozen hop must be absent from events, so the full contract cannot validate")
+ XCTAssertFalse(
+ MeetingAECDelayContract(renderLeadSeconds: 0.010).validates(events: seam.events),
+ "a frozen hop must be absent from events, so the full contract cannot validate"
+ )
var seen: [Int: [MeetingAECDelayContractEventKind]] = [:]
- for event in seam.events { seen[event.frameIndex, default: []].append(event.kind) }
+ for event in seam.events {
+ seen[event.frameIndex, default: []].append(event.kind)
+ }
XCTAssertTrue(seen.values.allSatisfy { $0 == [.render, .capture] })
XCTAssertNil(seen[20])
}
func testRenderGapOfOneSampleFreezesWithoutInventedCoverage() {
- let (drained, result) = runRenderGap(gapSeconds: 1 / rate)
+ let (drained, result) = self.runRenderGap(gapSeconds: 1 / self.rate)
XCTAssertEqual(drained.renderDiagnostics.gapCount, 1)
// A sub-analysis-sample hole cannot produce invalid 16 kHz samples; the reason,
// freeze, and boundary carry it instead of fabricated silence.
@@ -211,20 +268,30 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
}
func testRenderGapOfTenMillisecondsIsExactlyOneInvalidHop() {
- let (drained, result) = runRenderGap(gapSeconds: 0.010)
+ let (drained, result) = self.runRenderGap(gapSeconds: 0.010)
XCTAssertEqual(drained.renderDiagnostics.gapCount, 1)
- assertRenderGap(result, gapIndices: 20..<21, invalidRender: 160,
- boundaryIndex: 21, resumedIndex: 21)
+ self.assertRenderGap(
+ result,
+ gapIndices: 20..<21,
+ invalidRender: 160,
+ boundaryIndex: 21,
+ resumedIndex: 21
+ )
XCTAssertEqual(result.frames.count, 41)
XCTAssertEqual(result.frames[20].renderValidMask, [Bool](repeating: false, count: 160))
XCTAssertTrue(result.frames[21].adaptationFrozen, "the first resumed hop performs the reset")
}
func testRenderGapOfHundredMillisecondsSpansTenInvalidHops() {
- let (drained, result) = runRenderGap(gapSeconds: 0.100)
+ let (drained, result) = self.runRenderGap(gapSeconds: 0.100)
XCTAssertEqual(drained.renderDiagnostics.gapCount, 1)
- assertRenderGap(result, gapIndices: 20..<30, invalidRender: 1_600,
- boundaryIndex: 30, resumedIndex: 30)
+ self.assertRenderGap(
+ result,
+ gapIndices: 20..<30,
+ invalidRender: 1600,
+ boundaryIndex: 30,
+ resumedIndex: 30
+ )
XCTAssertEqual(result.frames.count, 50)
XCTAssertTrue(result.frames[20..<30].allSatisfy {
$0.renderValidMask.allSatisfy { !$0 } && $0.adaptationFrozen
@@ -236,7 +303,7 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
func testMicrophoneGapOfTwoMillisecondsYieldsExactly32InvalidCaptureSamples() {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
- feedPaired(adapter, count: 40, microphoneGap: (20, 0.002))
+ self.feedPaired(adapter, count: 40, microphoneGap: (20, 0.002))
let (drained, result) = adapter.synchronize()
XCTAssertEqual(drained.microphoneDiagnostics.gapCount, 1)
@@ -262,9 +329,11 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
for index in 0..<60 {
let shift = (index >= 20 ? 0.010 : 0) + (index >= 40 ? 0.020 : 0)
let pts = Double(index) * 0.01 + shift
- XCTAssertNil(adapter.appendRenderFrame(block(pts: pts, value: 0.25)))
- XCTAssertNil(adapter.appendMicrophoneFrame(block(pts: Double(index) * 0.01 + shift,
- arrival: Double(index) * 0.01 + shift)))
+ XCTAssertNil(adapter.appendRenderFrame(self.block(pts: pts, value: 0.25)))
+ XCTAssertNil(adapter.appendMicrophoneFrame(self.block(
+ pts: Double(index) * 0.01 + shift,
+ arrival: Double(index) * 0.01 + shift
+ )))
}
let (drained, result) = adapter.synchronize()
@@ -284,7 +353,7 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
XCTAssertEqual(seam.frames, result.frames)
}
- // MARK: Overlaps and backward timestamps
+ // MARK: - Overlaps and backward timestamps
private func overlapScenario(
overlappedPTS: Double
@@ -294,13 +363,15 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
for index in 0..<10 {
let value = Float(index + 1) / 20
XCTAssertNil(baseline.appendRenderFrame(
- block(pts: Double(index) * 0.01, value: value)))
+ self.block(pts: Double(index) * 0.01, value: value)))
XCTAssertNil(baseline.appendMicrophoneFrame(
- block(pts: Double(index) * 0.01, arrival: Double(index) * 0.01)))
+ self.block(pts: Double(index) * 0.01, arrival: Double(index) * 0.01)))
let pts = index == 5 ? overlappedPTS : Double(index) * 0.01
- XCTAssertNil(variant.appendRenderFrame(block(pts: pts, value: value)))
- XCTAssertNil(variant.appendMicrophoneFrame(block(pts: Double(index) * 0.01,
- arrival: Double(index) * 0.01)))
+ XCTAssertNil(variant.appendRenderFrame(self.block(pts: pts, value: value)))
+ XCTAssertNil(variant.appendMicrophoneFrame(self.block(
+ pts: Double(index) * 0.01,
+ arrival: Double(index) * 0.01
+ )))
}
let baselineResult = baseline.synchronize().1
let (drained, result) = variant.synchronize()
@@ -320,47 +391,79 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
XCTAssertFalse(result.failedOpen, file: file, line: line)
XCTAssertEqual(result.frames.count, baseline.frames.count, file: file, line: line)
for hop in 0..<5 {
- XCTAssertEqual(result.frames[hop].renderSamples, baseline.frames[hop].renderSamples,
- file: file, line: line)
+ XCTAssertEqual(
+ result.frames[hop].renderSamples,
+ baseline.frames[hop].renderSamples,
+ file: file,
+ line: line
+ )
}
- XCTAssertEqual(result.frames[5].renderValidMask, [Bool](repeating: false, count: 160),
- file: file, line: line)
+ XCTAssertEqual(
+ result.frames[5].renderValidMask,
+ [Bool](repeating: false, count: 160),
+ file: file,
+ line: line
+ )
for hop in 6..<10 {
- XCTAssertEqual(result.frames[hop].renderSamples, baseline.frames[hop].renderSamples,
- file: file, line: line)
+ XCTAssertEqual(
+ result.frames[hop].renderSamples,
+ baseline.frames[hop].renderSamples,
+ file: file,
+ line: line
+ )
}
}
func testOneSampleOverlapCannotOverwriteAcceptedSamples() {
- let (drained, result, baseline) = overlapScenario(overlappedPTS: 0.05 - 1 / rate)
- assertOverlapDropsLateBlock(drained, result, baseline, expectBackward: false)
+ let (drained, result, baseline) = self.overlapScenario(overlappedPTS: 0.05 - 1 / self.rate)
+ self.assertOverlapDropsLateBlock(drained, result, baseline, expectBackward: false)
}
func testHalfFrameOverlapCannotOverwriteAcceptedSamples() {
- let (drained, result, baseline) = overlapScenario(overlappedPTS: 0.045)
- assertOverlapDropsLateBlock(drained, result, baseline, expectBackward: false)
+ let (drained, result, baseline) = self.overlapScenario(overlappedPTS: 0.045)
+ self.assertOverlapDropsLateBlock(drained, result, baseline, expectBackward: false)
}
func testDuplicateTimestampIsBackwardAndOverlapping() {
- let (drained, result, baseline) = overlapScenario(overlappedPTS: 0.04)
- assertOverlapDropsLateBlock(drained, result, baseline, expectBackward: true)
+ let (drained, result, baseline) = self.overlapScenario(overlappedPTS: 0.04)
+ self.assertOverlapDropsLateBlock(drained, result, baseline, expectBackward: true)
}
func testSequenceDisorderDropsLateSequenceWithoutOverwriting() {
let refs = [
- MeetingReferencePCMFrame(sequenceNumber: 0, presentationTime: 0, sampleRate: 16_000,
- samples: [Float](repeating: 1, count: 160)),
- MeetingReferencePCMFrame(sequenceNumber: 2, presentationTime: 0.02, sampleRate: 16_000,
- samples: [Float](repeating: 3, count: 160)),
- MeetingReferencePCMFrame(sequenceNumber: 1, presentationTime: 0.01, sampleRate: 16_000,
- samples: [Float](repeating: 2, count: 160)),
- MeetingReferencePCMFrame(sequenceNumber: 3, presentationTime: 0.03, sampleRate: 16_000,
- samples: [Float](repeating: 4, count: 160)),
+ MeetingReferencePCMFrame(
+ sequenceNumber: 0,
+ presentationTime: 0,
+ sampleRate: 16_000,
+ samples: [Float](repeating: 1, count: 160)
+ ),
+ MeetingReferencePCMFrame(
+ sequenceNumber: 2,
+ presentationTime: 0.02,
+ sampleRate: 16_000,
+ samples: [Float](repeating: 3, count: 160)
+ ),
+ MeetingReferencePCMFrame(
+ sequenceNumber: 1,
+ presentationTime: 0.01,
+ sampleRate: 16_000,
+ samples: [Float](repeating: 2, count: 160)
+ ),
+ MeetingReferencePCMFrame(
+ sequenceNumber: 3,
+ presentationTime: 0.03,
+ sampleRate: 16_000,
+ samples: [Float](repeating: 4, count: 160)
+ ),
]
let mics = (0..<4).map {
- MeetingMicrophonePCMFrame(sequenceNumber: $0, sampleTime: Int64($0 * 160),
- hostTime: Double($0) * 0.01, sampleRate: 16_000,
- samples: [Float](repeating: 5, count: 160))
+ MeetingMicrophonePCMFrame(
+ sequenceNumber: $0,
+ sampleTime: Int64($0 * 160),
+ hostTime: Double($0) * 0.01,
+ sampleRate: 16_000,
+ samples: [Float](repeating: 5, count: 160)
+ )
}
let result = MeetingReferenceSynchronizer().synchronize(microphone: mics, reference: refs)
@@ -370,15 +473,19 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
XCTAssertTrue(result.frames[2].resynchronizationBoundary)
}
- // MARK: Discontinuity, format/rate, route
+ // MARK: - Discontinuity, format/rate, route
func testExplicitDiscontinuityWithContiguousTimingResetsWithoutGap() {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
for index in 0..<10 {
- XCTAssertNil(adapter.appendRenderFrame(block(pts: Double(index) * 0.01,
- discontinuity: index == 5)))
- XCTAssertNil(adapter.appendMicrophoneFrame(block(pts: Double(index) * 0.01,
- arrival: Double(index) * 0.01)))
+ XCTAssertNil(adapter.appendRenderFrame(self.block(
+ pts: Double(index) * 0.01,
+ discontinuity: index == 5
+ )))
+ XCTAssertNil(adapter.appendMicrophoneFrame(self.block(
+ pts: Double(index) * 0.01,
+ arrival: Double(index) * 0.01
+ )))
}
let (drained, result) = adapter.synchronize()
@@ -395,12 +502,16 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
func testUnsupportedRateAndFormatTransitionsAreRejectedAndCounted() {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
- XCTAssertNil(adapter.appendRenderFrame(block(pts: 0)))
- var shifted = block(pts: 0.01)
+ XCTAssertNil(adapter.appendRenderFrame(self.block(pts: 0)))
+ var shifted = self.block(pts: 0.01)
shifted = MeetingStage05AdapterFrame(
- presentationSeconds: 0.01, durationSeconds: Double(blockFrames) / 44_100,
- frameCount: blockFrames, sampleRateHz: 44_100, arrivalSeconds: nil,
- samples: [Float](repeating: 0.5, count: blockFrames))
+ presentationSeconds: 0.01,
+ durationSeconds: Double(self.blockFrames) / 44_100,
+ frameCount: self.blockFrames,
+ sampleRateHz: 44_100,
+ arrivalSeconds: nil,
+ samples: [Float](repeating: 0.5, count: self.blockFrames)
+ )
XCTAssertEqual(adapter.appendRenderFrame(shifted), .unsupportedSampleRate)
let drained = adapter.drain()
XCTAssertEqual(drained.renderDiagnostics.rejectedCallbackCount, 1)
@@ -410,13 +521,17 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
func testRejectedCallbackConsumesItsArrivalSequenceAndExposesTheHole() {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
- XCTAssertNil(adapter.appendRenderFrame(block(pts: 0)))
+ XCTAssertNil(adapter.appendRenderFrame(self.block(pts: 0)))
let invalid = MeetingStage05AdapterFrame(
- presentationSeconds: .nan, durationSeconds: 0.01, frameCount: blockFrames,
- sampleRateHz: rate, arrivalSeconds: nil,
- samples: [Float](repeating: 0.5, count: blockFrames))
+ presentationSeconds: .nan,
+ durationSeconds: 0.01,
+ frameCount: blockFrames,
+ sampleRateHz: rate,
+ arrivalSeconds: nil,
+ samples: [Float](repeating: 0.5, count: blockFrames)
+ )
XCTAssertEqual(adapter.appendRenderFrame(invalid), .nonFiniteTiming)
- XCTAssertNil(adapter.appendRenderFrame(block(pts: 0.02)))
+ XCTAssertNil(adapter.appendRenderFrame(self.block(pts: 0.02)))
let drained = adapter.drain()
XCTAssertEqual(drained.reference.map(\.sequenceNumber), [0, 2])
@@ -427,54 +542,83 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
func testValidationRejectsBadTimingGeometryAndPayload() {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
- let valid = block(pts: 0)
+ let valid = self.block(pts: 0)
func variant(_ mutate: (inout MeetingStage05AdapterFrame) -> Void) -> MeetingStage05AdapterFrame {
var copy = valid; mutate(&copy); return copy
}
XCTAssertEqual(adapter.appendRenderFrame(variant { $0 = MeetingStage05AdapterFrame(
- presentationSeconds: .nan, durationSeconds: $0.durationSeconds, frameCount: $0.frameCount,
- sampleRateHz: $0.sampleRateHz, arrivalSeconds: nil, samples: $0.samples) }), .nonFiniteTiming)
+ presentationSeconds: .nan,
+ durationSeconds: $0.durationSeconds,
+ frameCount: $0.frameCount,
+ sampleRateHz: $0.sampleRateHz,
+ arrivalSeconds: nil,
+ samples: $0.samples
+ ) }), .nonFiniteTiming)
XCTAssertEqual(adapter.appendRenderFrame(variant { $0 = MeetingStage05AdapterFrame(
- presentationSeconds: -0.01, durationSeconds: $0.durationSeconds, frameCount: $0.frameCount,
- sampleRateHz: $0.sampleRateHz, arrivalSeconds: nil, samples: $0.samples) }), .negativeTiming)
+ presentationSeconds: -0.01,
+ durationSeconds: $0.durationSeconds,
+ frameCount: $0.frameCount,
+ sampleRateHz: $0.sampleRateHz,
+ arrivalSeconds: nil,
+ samples: $0.samples
+ ) }), .negativeTiming)
XCTAssertEqual(adapter.appendRenderFrame(variant { $0 = MeetingStage05AdapterFrame(
- presentationSeconds: 0, durationSeconds: 0.02, frameCount: $0.frameCount,
- sampleRateHz: $0.sampleRateHz, arrivalSeconds: nil, samples: $0.samples) }), .durationMismatch)
+ presentationSeconds: 0,
+ durationSeconds: 0.02,
+ frameCount: $0.frameCount,
+ sampleRateHz: $0.sampleRateHz,
+ arrivalSeconds: nil,
+ samples: $0.samples
+ ) }), .durationMismatch)
XCTAssertEqual(adapter.appendRenderFrame(variant { $0 = MeetingStage05AdapterFrame(
- presentationSeconds: 0, durationSeconds: $0.durationSeconds, frameCount: $0.frameCount,
- sampleRateHz: $0.sampleRateHz, arrivalSeconds: nil,
- samples: [Float](repeating: 0.5, count: $0.frameCount - 1)) }), .invalidGeometry)
+ presentationSeconds: 0,
+ durationSeconds: $0.durationSeconds,
+ frameCount: $0.frameCount,
+ sampleRateHz: $0.sampleRateHz,
+ arrivalSeconds: nil,
+ samples: [Float](repeating: 0.5, count: $0.frameCount - 1)
+ ) }), .invalidGeometry)
XCTAssertEqual(adapter.appendRenderFrame(variant { $0 = MeetingStage05AdapterFrame(
- presentationSeconds: 0, durationSeconds: $0.durationSeconds, frameCount: $0.frameCount,
- sampleRateHz: $0.sampleRateHz, arrivalSeconds: nil,
- samples: [.nan] + [Float](repeating: 0.5, count: $0.frameCount - 1)) }), .nonFiniteSamples)
+ presentationSeconds: 0,
+ durationSeconds: $0.durationSeconds,
+ frameCount: $0.frameCount,
+ sampleRateHz: $0.sampleRateHz,
+ arrivalSeconds: nil,
+ samples: [.nan] + [Float](repeating: 0.5, count: $0.frameCount - 1)
+ ) }), .nonFiniteSamples)
XCTAssertEqual(adapter.drain().renderDiagnostics.rejectedCallbackCount, 5)
}
func testBlockAndFrameCeilingsBoundTheAdapter() {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
- for index in 0..<2_000 {
- XCTAssertNil(adapter.appendMicrophoneFrame(block(pts: Double(index) * 0.01,
- arrival: Double(index) * 0.01)))
+ for index in 0..<2000 {
+ XCTAssertNil(adapter.appendMicrophoneFrame(self.block(
+ pts: Double(index) * 0.01,
+ arrival: Double(index) * 0.01
+ )))
}
- XCTAssertEqual(adapter.appendMicrophoneFrame(block(pts: 20, arrival: 20)), .blockLimit)
+ XCTAssertEqual(adapter.appendMicrophoneFrame(self.block(pts: 20, arrival: 20)), .blockLimit)
let wide = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
for index in 0..<200 {
- XCTAssertNil(wide.appendMicrophoneFrame(block(pts: Double(index) * 0.1, frames: 4_800,
- arrival: Double(index) * 0.1)))
+ XCTAssertNil(wide.appendMicrophoneFrame(self.block(
+ pts: Double(index) * 0.1,
+ frames: 4800,
+ arrival: Double(index) * 0.1
+ )))
}
- XCTAssertEqual(wide.appendMicrophoneFrame(block(pts: 20, frames: 4_800, arrival: 20)), .frameLimit)
+ XCTAssertEqual(wide.appendMicrophoneFrame(self.block(pts: 20, frames: 4800, arrival: 20)), .frameLimit)
XCTAssertEqual(wide.drain().microphone.count, 200)
}
- // MARK: Drift ownership
+ // MARK: - Drift ownership
func testFailedOpenDriftThresholdAuthorizesNothing() {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
- feedPaired(adapter, count: 5)
+ self.feedPaired(adapter, count: 5)
let (_, result) = adapter.synchronize(configuration: .init(
- referenceClockDriftPPM: 150, maximumClockDriftPPM: 100))
+ referenceClockDriftPPM: 150, maximumClockDriftPPM: 100
+ ))
XCTAssertTrue(result.failedOpen)
XCTAssertEqual(result.failureReason, .clockDriftUnstable)
XCTAssertEqual(result.diagnostics.referenceClockDriftPPM, 150)
@@ -494,20 +638,30 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
XCTAssertTrue(emptySeam.events.isEmpty)
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
- feedPaired(adapter, count: 1)
+ self.feedPaired(adapter, count: 1)
let valid = adapter.synchronize().1
let source = valid.frames[0]
let malformedFrame = MeetingSynchronizedFrame(
- index: 1, sessionStartTime: source.sessionStartTime,
- sessionEndTime: source.sessionEndTime, epochID: source.epochID,
- renderSamples: source.renderSamples, captureSamples: source.captureSamples,
- renderValidMask: source.renderValidMask, captureValidMask: source.captureValidMask,
- unknownReasons: source.unknownReasons, adaptationFrozen: source.adaptationFrozen,
+ index: 1,
+ sessionStartTime: source.sessionStartTime,
+ sessionEndTime: source.sessionEndTime,
+ epochID: source.epochID,
+ renderSamples: source.renderSamples,
+ captureSamples: source.captureSamples,
+ renderValidMask: source.renderValidMask,
+ captureValidMask: source.captureValidMask,
+ unknownReasons: source.unknownReasons,
+ adaptationFrozen: source.adaptationFrozen,
resynchronizationBoundary: source.resynchronizationBoundary,
- lagSeconds: source.lagSeconds, timelines: source.timelines)
+ lagSeconds: source.lagSeconds,
+ timelines: source.timelines
+ )
let malformed = MeetingSynchronizationResult(
- frames: [malformedFrame], failedOpen: false, failureReason: nil,
- diagnostics: valid.diagnostics)
+ frames: [malformedFrame],
+ failedOpen: false,
+ failureReason: nil,
+ diagnostics: valid.diagnostics
+ )
let malformedSeam = MeetingStage05MockAECSeam().process(malformed)
XCTAssertFalse(malformedSeam.authorized)
XCTAssertTrue(malformedSeam.events.isEmpty)
@@ -516,32 +670,35 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
func testBoundedDriftIsReportedNotEstimatedFromCallbackPTS() {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
- feedPaired(adapter, count: 5)
+ self.feedPaired(adapter, count: 5)
let (drained, result) = adapter.synchronize(configuration: .init(
- referenceClockDriftPPM: 90, maximumClockDriftPPM: 100))
+ referenceClockDriftPPM: 90, maximumClockDriftPPM: 100
+ ))
XCTAssertFalse(result.failedOpen)
XCTAssertEqual(result.diagnostics.referenceClockDriftPPM, 90)
XCTAssertTrue(result.frames.allSatisfy { $0.unknownReasons.contains(.clockDriftUnstable) })
XCTAssertEqual(drained.renderDiagnostics.acceptedCallbackCount, 5)
}
- // MARK: Deterministic replay
+ // MARK: - Deterministic replay
func testAdapterSynchronizationIsDeterministic() {
let first = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
let second = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
- feedPaired(first, count: 40, renderGap: (20, 0.002))
- feedPaired(second, count: 40, renderGap: (20, 0.002))
+ self.feedPaired(first, count: 40, renderGap: (20, 0.002))
+ self.feedPaired(second, count: 40, renderGap: (20, 0.002))
XCTAssertEqual(first.drain(), second.drain())
XCTAssertEqual(first.synchronize().1, second.synchronize().1)
}
- // MARK: Synthetic CMSampleBuffer path
+ // MARK: - Synthetic CMSampleBuffer path
func testSyntheticRenderBufferMapsPTSToPresentationTime() {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
let buffer = Stage05SyntheticBuffer.monoFloat32(pts: 1.25, frameCount: 480, value: 0.25)
XCTAssertNotNil(buffer)
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
XCTAssertNil(adapter.appendRender(buffer!, arrivalSeconds: 3.5))
let drained = adapter.drain()
XCTAssertEqual(drained.reference.count, 1)
@@ -553,6 +710,8 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-b")
let buffer = Stage05SyntheticBuffer.monoFloat32(pts: 0.5, frameCount: 480, value: 0.5)
XCTAssertNotNil(buffer)
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
XCTAssertNil(adapter.appendMicrophone(buffer!, arrivalSeconds: 9.75))
let drained = adapter.drain()
XCTAssertEqual(drained.microphone.count, 1)
@@ -565,6 +724,8 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
let buffer = Stage05SyntheticBuffer.monoFloat32(pts: 0, frameCount: 480, discontinuity: true)
XCTAssertNotNil(buffer)
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
XCTAssertNil(adapter.appendRender(buffer!, arrivalSeconds: 0))
let drained = adapter.drain()
XCTAssertEqual(drained.reference.first?.discontinuity, true)
@@ -575,6 +736,8 @@ final class MeetingStage05SCKFrameAdapterTests: XCTestCase {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
let stereo = Stage05SyntheticBuffer.monoFloat32(pts: 0, frameCount: 480, channels: 2)
XCTAssertNotNil(stereo)
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
XCTAssertEqual(adapter.appendRender(stereo!, arrivalSeconds: 0), .unsupportedFormat)
let drained = adapter.drain()
XCTAssertEqual(drained.renderDiagnostics.rejectedCallbackCount, 1)
@@ -592,29 +755,36 @@ final class MeetingStage05LiveAdapterRuntimeTests: XCTestCase {
init(_ values: [Double]) { self.values = values }
func now() -> Double {
- lock.lock(); defer { lock.unlock() }
- readCount += 1
- return values.isEmpty ? 0 : values.removeFirst()
+ self.lock.lock(); defer { lock.unlock() }
+ self.readCount += 1
+ return self.values.isEmpty ? 0 : self.values.removeFirst()
}
}
private func makeRoot() throws -> URL {
let root = URL(
fileURLWithPath: "/private/tmp/fv-stage05-evidence.live-\(UUID().uuidString)",
- isDirectory: true)
+ isDirectory: true
+ )
try FileManager.default.createDirectory(
- at: root, withIntermediateDirectories: false,
- attributes: [.posixPermissions: 0o700])
+ at: root,
+ withIntermediateDirectories: false,
+ attributes: [.posixPermissions: 0o700]
+ )
XCTAssertEqual(Darwin.chmod(root.path, 0o700), 0)
return root
}
private func collector(at root: URL) throws -> MeetingStage05PCMCollector {
try MeetingStage05PCMCollector(
- root: root, inputUID: "not-retained-input", outputUID: "not-retained-output",
+ root: root,
+ inputUID: "not-retained-input",
+ outputUID: "not-retained-output",
fixtureSHA256: String(repeating: "a", count: 64),
executableSHA256: String(repeating: "b", count: 64),
- initialOutputVolume: 0.25, targetProcessID: 42)
+ initialOutputVolume: 0.25,
+ targetProcessID: 42
+ )
}
func testRealStreamOutputRoutesBuffersAndReadsClockExactlyOncePerAudioCallback() throws {
@@ -624,11 +794,14 @@ final class MeetingStage05LiveAdapterRuntimeTests: XCTestCase {
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
let clock = MonotonicClock([10, 11])
let output = MeetingStage05StreamOutput(
- collector: collector, adapter: adapter, monotonicNow: clock.now)
+ collector: collector, adapter: adapter, monotonicNow: clock.now
+ )
let render = try XCTUnwrap(Stage05SyntheticBuffer.monoFloat32(
- pts: 0, frameCount: 480, value: 0.02))
+ pts: 0, frameCount: 480, value: 0.02
+ ))
let capture = try XCTUnwrap(Stage05SyntheticBuffer.monoFloat32(
- pts: 0, frameCount: 480, value: 0.01))
+ pts: 0, frameCount: 480, value: 0.01
+ ))
output.handle(render, outputType: .audio)
output.handle(capture, outputType: .microphone)
@@ -643,7 +816,8 @@ final class MeetingStage05LiveAdapterRuntimeTests: XCTestCase {
collector.retainTimingFailureRecord(.renderTiming)
let record = try JSONDecoder().decode(
MeetingStage05TimingFailureRecord.self,
- from: Data(contentsOf: root.appendingPathComponent("timing.json")))
+ from: Data(contentsOf: root.appendingPathComponent("timing.json"))
+ )
XCTAssertEqual(record.render.blocks.first?.arrivalSeconds, 10)
XCTAssertEqual(record.capture.blocks.first?.arrivalSeconds, 11)
}
@@ -654,9 +828,11 @@ final class MeetingStage05LiveAdapterRuntimeTests: XCTestCase {
let collector = try collector(at: root)
let adapter = MeetingStage05SCKFrameAdapter(routeIdentifier: "route-a")
let output = MeetingStage05StreamOutput(
- collector: collector, adapter: adapter, monotonicNow: { 10 })
+ collector: collector, adapter: adapter, monotonicNow: { 10 }
+ )
let stereo = try XCTUnwrap(Stage05SyntheticBuffer.monoFloat32(
- pts: 0, frameCount: 480, channels: 2))
+ pts: 0, frameCount: 480, channels: 2
+ ))
output.handle(stereo, outputType: .audio)
@@ -664,7 +840,8 @@ final class MeetingStage05LiveAdapterRuntimeTests: XCTestCase {
XCTAssertEqual(drained.renderDiagnostics.rejectedCallbackCount, 1)
XCTAssertEqual(drained.renderDiagnostics.formatChangeCount, 1)
XCTAssertThrowsError(
- try collector.finish(consentConfirmed: true, finalOutputVolume: 0.25)) {
+ try collector.finish(consentConfirmed: true, finalOutputVolume: 0.25))
+ {
XCTAssertEqual($0 as? MeetingStage05FinalizeFailure, .appendInvalidFrame)
}
collector.abort()
@@ -672,7 +849,7 @@ final class MeetingStage05LiveAdapterRuntimeTests: XCTestCase {
}
func testContiguousSummaryIsValidEligibleAndSortedWithoutSensitiveFields() throws {
- let summary = makeSummary(renderGapSeconds: 0)
+ let summary = self.makeSummary(renderGapSeconds: 0)
XCTAssertTrue(summary.validationReasons().isEmpty)
XCTAssertTrue(summary.structurallyValid)
XCTAssertTrue(summary.eligibleForAECTrial)
@@ -680,7 +857,8 @@ final class MeetingStage05LiveAdapterRuntimeTests: XCTestCase {
XCTAssertEqual(summary.mockFrozenFrameCount, 0)
let encoded = MeetingStage05EvidenceAutorun.encodedOutcome(
- exitStatus: 0, status: "success", adapter: summary)
+ exitStatus: 0, status: "success", adapter: summary
+ )
XCTAssertTrue(encoded.hasPrefix("{\"adapter\":"), encoded)
let data = Data(encoded.utf8)
let decoded = try JSONDecoder().decode(MeetingStage05AutorunOutcome.self, from: data)
@@ -690,14 +868,25 @@ final class MeetingStage05LiveAdapterRuntimeTests: XCTestCase {
as? [String: Any])
XCTAssertTrue(object.values.allSatisfy { $0 is NSNumber })
let lower = encoded.lowercased()
- for forbidden in ["samples", "peak", "uid", "pid", "title", "path", "transcript",
- "sha256", "fixture", "executable", "timestamp"] {
+ for forbidden in [
+ "samples",
+ "peak",
+ "uid",
+ "pid",
+ "title",
+ "path",
+ "transcript",
+ "sha256",
+ "fixture",
+ "executable",
+ "timestamp",
+ ] {
XCTAssertFalse(lower.contains(forbidden), "forbidden outcome field: \(forbidden)")
}
}
func testGapSummaryRemainsStructurallyValidButCannotAuthorizeAECTrial() {
- let summary = makeSummary(renderGapSeconds: 0.002)
+ let summary = self.makeSummary(renderGapSeconds: 0.002)
XCTAssertTrue(summary.validationReasons().isEmpty)
XCTAssertTrue(summary.structurallyValid)
XCTAssertFalse(summary.eligibleForAECTrial)
@@ -708,7 +897,7 @@ final class MeetingStage05LiveAdapterRuntimeTests: XCTestCase {
}
func testSummaryRejectsTamperedEligibilityAndNonfiniteDrift() throws {
- let valid = makeSummary(renderGapSeconds: 0)
+ let valid = self.makeSummary(renderGapSeconds: 0)
let data = try JSONEncoder().encode(valid)
var object = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any])
object["eligibleForAECTrial"] = false
@@ -716,14 +905,17 @@ final class MeetingStage05LiveAdapterRuntimeTests: XCTestCase {
object["referenceClockDriftPresent"] = false
let tampered = try JSONDecoder().decode(
MeetingStage05LiveAdapterSummary.self,
- from: JSONSerialization.data(withJSONObject: object))
+ from: JSONSerialization.data(withJSONObject: object)
+ )
XCTAssertTrue(tampered.validationReasons().contains("eligibility"))
XCTAssertTrue(tampered.validationReasons().contains("drift"))
XCTAssertEqual(
MeetingStage05EvidenceAutorun.encodedOutcome(
- exitStatus: 0, status: "success", adapter: tampered),
- "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"outcome\"}")
+ exitStatus: 0, status: "success", adapter: tampered
+ ),
+ "{\"exitStatus\":1,\"status\":\"failure\",\"reason\":\"outcome\"}"
+ )
}
private func makeSummary(renderGapSeconds: Double) -> MeetingStage05LiveAdapterSummary {
@@ -732,20 +924,30 @@ final class MeetingStage05LiveAdapterRuntimeTests: XCTestCase {
let base = Double(index) * 0.01
let renderPTS = index >= 5 ? base + renderGapSeconds : base
XCTAssertNil(adapter.appendRenderFrame(MeetingStage05AdapterFrame(
- presentationSeconds: renderPTS, durationSeconds: 0.01,
- frameCount: 480, sampleRateHz: 48_000,
- arrivalSeconds: 1 + base, samples: [Float](repeating: 0.02, count: 480))))
+ presentationSeconds: renderPTS,
+ durationSeconds: 0.01,
+ frameCount: 480,
+ sampleRateHz: 48_000,
+ arrivalSeconds: 1 + base,
+ samples: [Float](repeating: 0.02, count: 480)
+ )))
XCTAssertNil(adapter.appendMicrophoneFrame(MeetingStage05AdapterFrame(
- presentationSeconds: base, durationSeconds: 0.01,
- frameCount: 480, sampleRateHz: 48_000,
- arrivalSeconds: 1 + base, samples: [Float](repeating: 0.01, count: 480))))
+ presentationSeconds: base,
+ durationSeconds: 0.01,
+ frameCount: 480,
+ sampleRateHz: 48_000,
+ arrivalSeconds: 1 + base,
+ samples: [Float](repeating: 0.01, count: 480)
+ )))
}
let (drain, synchronization) = adapter.synchronize(configuration: .init(
referenceScope: .selectedWindow,
- referenceCompleteness: .measuredComplete))
+ referenceCompleteness: .measuredComplete
+ ))
let seam = MeetingStage05MockAECSeam().process(synchronization)
return MeetingStage05LiveAdapterSummary.make(
- drain: drain, synchronization: synchronization, seam: seam)
+ drain: drain, synchronization: synchronization, seam: seam
+ )
}
}
@@ -753,20 +955,27 @@ final class MeetingStage05TimingFailureRecordTests: XCTestCase {
private func makeRoot() throws -> URL {
let root = URL(
fileURLWithPath: "/private/tmp/fv-stage05-evidence.unit-\(UUID().uuidString)",
- isDirectory: true)
+ isDirectory: true
+ )
try FileManager.default.createDirectory(
- at: root, withIntermediateDirectories: false,
- attributes: [.posixPermissions: 0o700])
+ at: root,
+ withIntermediateDirectories: false,
+ attributes: [.posixPermissions: 0o700]
+ )
XCTAssertEqual(Darwin.chmod(root.path, 0o700), 0)
return root
}
private func collector(at root: URL) throws -> MeetingStage05PCMCollector {
try MeetingStage05PCMCollector(
- root: root, inputUID: "not-retained-input", outputUID: "not-retained-output",
+ root: root,
+ inputUID: "not-retained-input",
+ outputUID: "not-retained-output",
fixtureSHA256: String(repeating: "a", count: 64),
executableSHA256: String(repeating: "b", count: 64),
- initialOutputVolume: 0.25, targetProcessID: 42)
+ initialOutputVolume: 0.25,
+ targetProcessID: 42
+ )
}
private func appendShortTimingFailureFixture(_ collector: MeetingStage05PCMCollector) {
@@ -774,9 +983,15 @@ final class MeetingStage05TimingFailureRecordTests: XCTestCase {
let base = Double(index) * 0.01
let renderPTS = index >= 2 ? base + 0.002 : base
let render = Stage05SyntheticBuffer.monoFloat32(
- pts: renderPTS, frameCount: 480, value: 0.02)!
+ pts: renderPTS, frameCount: 480, value: 0.02
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ )!
let capture = Stage05SyntheticBuffer.monoFloat32(
- pts: base, frameCount: 480, value: 0.01)!
+ pts: base, frameCount: 480, value: 0.01
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
+ )!
collector.append(render, output: .render)
collector.append(capture, output: .capture)
}
@@ -786,7 +1001,7 @@ final class MeetingStage05TimingFailureRecordTests: XCTestCase {
let root = try makeRoot()
defer { try? FileManager.default.removeItem(at: root) }
let collector = try collector(at: root)
- appendShortTimingFailureFixture(collector)
+ self.appendShortTimingFailureFixture(collector)
XCTAssertThrowsError(try collector.finish(consentConfirmed: true, finalOutputVolume: 0.25)) {
XCTAssertEqual($0 as? MeetingStage05FinalizeFailure, .renderTiming)
@@ -795,7 +1010,7 @@ final class MeetingStage05TimingFailureRecordTests: XCTestCase {
XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: root.path), ["timing.json"])
let timingURL = root.appendingPathComponent("timing.json")
- let mode = (try FileManager.default.attributesOfItem(atPath: timingURL.path)[.posixPermissions]
+ let mode = try (FileManager.default.attributesOfItem(atPath: timingURL.path)[.posixPermissions]
as? NSNumber)?.intValue
XCTAssertEqual(mode.map { $0 & 0o777 }, 0o600)
let data = try Data(contentsOf: timingURL)
@@ -808,9 +1023,21 @@ final class MeetingStage05TimingFailureRecordTests: XCTestCase {
XCTAssertEqual(record.capture.blocks.count, 4)
XCTAssertGreaterThanOrEqual(record.render.gapCount, 1)
+ // JSONEncoder fixture bytes are UTF-8; retain nonoptional decoding for assertions.
+ // swiftlint:disable:next optional_data_string_conversion
let encoded = String(decoding: data, as: UTF8.self).lowercased()
- for forbidden in ["\"samples\"", "\"peak\"", "uid", "pid", "title", "path",
- "transcript", "sha256", "fixture", "executable"] {
+ for forbidden in [
+ "\"samples\"",
+ "\"peak\"",
+ "uid",
+ "pid",
+ "title",
+ "path",
+ "transcript",
+ "sha256",
+ "fixture",
+ "executable",
+ ] {
XCTAssertFalse(encoded.contains(forbidden), "forbidden timing-record key: \(forbidden)")
}
for absent in ["render.wav", "capture.wav", "manifest.json", "provenance.json"] {
@@ -822,23 +1049,40 @@ final class MeetingStage05TimingFailureRecordTests: XCTestCase {
func testTimingRecordRejectsTamperedDerivedCounts() {
let blocks = [
MeetingSignalDomainGateManifest.TimingBlock(
- presentationSeconds: 0, durationSeconds: 0.01,
- frameCount: 480, arrivalSeconds: 1),
+ presentationSeconds: 0,
+ durationSeconds: 0.01,
+ frameCount: 480,
+ arrivalSeconds: 1
+ ),
MeetingSignalDomainGateManifest.TimingBlock(
- presentationSeconds: 0.012, durationSeconds: 0.01,
- frameCount: 480, arrivalSeconds: 1.01),
+ presentationSeconds: 0.012,
+ durationSeconds: 0.01,
+ frameCount: 480,
+ arrivalSeconds: 1.01
+ ),
]
let valid = MeetingStage05TimingFailureRecord.make(
- failure: .renderTiming, renderTiming: blocks, captureTiming: blocks,
- sampleRateHz: 48_000)
+ failure: .renderTiming,
+ renderTiming: blocks,
+ captureTiming: blocks,
+ sampleRateHz: 48_000
+ )
XCTAssertTrue(valid.validationReasons().isEmpty)
let tamperedRender = MeetingStage05TimingFailureRecord.Track(
- blocks: valid.render.blocks, gapCount: valid.render.gapCount + 1,
- overlapCount: valid.render.overlapCount, backwardCount: valid.render.backwardCount,
- formatChangeCount: valid.render.formatChangeCount)
+ blocks: valid.render.blocks,
+ gapCount: valid.render.gapCount + 1,
+ overlapCount: valid.render.overlapCount,
+ backwardCount: valid.render.backwardCount,
+ formatChangeCount: valid.render.formatChangeCount
+ )
let tampered = MeetingStage05TimingFailureRecord(
- schema: valid.schema, failure: valid.failure, track: valid.track,
- sampleRateHz: valid.sampleRateHz, render: tamperedRender, capture: valid.capture)
+ schema: valid.schema,
+ failure: valid.failure,
+ track: valid.track,
+ sampleRateHz: valid.sampleRateHz,
+ render: tamperedRender,
+ capture: valid.capture
+ )
XCTAssertTrue(tampered.validationReasons().contains("derivedCounts"))
}
@@ -846,7 +1090,7 @@ final class MeetingStage05TimingFailureRecordTests: XCTestCase {
let root = try makeRoot()
defer { try? FileManager.default.removeItem(at: root) }
let collector = try collector(at: root)
- appendShortTimingFailureFixture(collector)
+ self.appendShortTimingFailureFixture(collector)
collector.retainTimingFailureRecord(.renderSilent)
XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: root.path), [])
}
@@ -864,8 +1108,15 @@ final class MeetingStage05TimingFailureRecordTests: XCTestCase {
private extension MeetingStage05AdapterTrackDiagnostics {
init(accepted: Int) {
- self.init(acceptedCallbackCount: accepted, rejectedCallbackCount: 0, gapCount: 0,
- overlapCount: 0, backwardCount: 0, discontinuityCount: 0, formatChangeCount: 0)
+ self.init(
+ acceptedCallbackCount: accepted,
+ rejectedCallbackCount: 0,
+ gapCount: 0,
+ overlapCount: 0,
+ backwardCount: 0,
+ discontinuityCount: 0,
+ formatChangeCount: 0
+ )
}
}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingTextOverlapEchoVerdictProviderTests.swift b/Tests/FluidDictationIntegrationTests/MeetingTextOverlapEchoVerdictProviderTests.swift
index 848ed11f..ca523437 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingTextOverlapEchoVerdictProviderTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingTextOverlapEchoVerdictProviderTests.swift
@@ -6,6 +6,8 @@ import XCTest
/// verdict provider. Only online-call microphone units get verdicts, and only against temporally
/// overlapping application units measured by the existing `MeetingEchoDetector`.
@MainActor
+// Match the production component name so its regression suite is easy to find.
+// swiftlint:disable:next type_name
final class MeetingTextOverlapEchoVerdictProviderTests: XCTestCase {
// MARK: - Fixtures
@@ -141,13 +143,13 @@ final class MeetingTextOverlapEchoVerdictProviderTests: XCTestCase {
]),
analysisSampleRate: 16_000
).build()
- return EchoFixture(
+ return try EchoFixture(
plan: plan,
manifest: manifest,
micTrackID: micTrack.id,
appTrackID: appTrack.id,
- micEpoch: try XCTUnwrap(manifest.track(micTrack.id)?.epochs.first),
- appEpochs: try XCTUnwrap(manifest.track(appTrack.id)?.epochs)
+ micEpoch: XCTUnwrap(manifest.track(micTrack.id)?.epochs.first),
+ appEpochs: XCTUnwrap(manifest.track(appTrack.id)?.epochs)
)
}
@@ -201,17 +203,29 @@ final class MeetingTextOverlapEchoVerdictProviderTests: XCTestCase {
for (index, word) in words.enumerated() {
let start = 0.2 + Double(index) * 0.25
units.append(self.unit(
- "app-word-\(index)", trackID: fixture.appTrackID, epoch: fixture.appEpochs[0],
- text: word, analysisStart: start, analysisEnd: start + 0.2
+ "app-word-\(index)",
+ trackID: fixture.appTrackID,
+ epoch: fixture.appEpochs[0],
+ text: word,
+ analysisStart: start,
+ analysisEnd: start + 0.2
))
units.append(self.unit(
- "mic-word-\(index)", trackID: fixture.micTrackID, epoch: fixture.micEpoch,
- text: word, analysisStart: start + 0.05, analysisEnd: start + 0.25
+ "mic-word-\(index)",
+ trackID: fixture.micTrackID,
+ epoch: fixture.micEpoch,
+ text: word,
+ analysisStart: start + 0.05,
+ analysisEnd: start + 0.25
))
}
units.append(self.unit(
- "mic-local", trackID: fixture.micTrackID, epoch: fixture.micEpoch,
- text: "lunch", analysisStart: 1.3, analysisEnd: 1.5
+ "mic-local",
+ trackID: fixture.micTrackID,
+ epoch: fixture.micEpoch,
+ text: "lunch",
+ analysisStart: 1.3,
+ analysisEnd: 1.5
))
let evidence = MeetingFinalTranscriptEvidence(
backendID: .parakeetNemotron,
@@ -240,7 +254,14 @@ final class MeetingTextOverlapEchoVerdictProviderTests: XCTestCase {
attemptID: fixture.plan.attemptID,
units: [
// Same words, ten seconds later: text match alone must not suppress.
- self.unit("app-far", trackID: fixture.appTrackID, epoch: farEpoch, text: echoText, analysisStart: farEpoch.analysisInterval.start + 0.2, analysisEnd: farEpoch.analysisInterval.start + 1.8),
+ self.unit(
+ "app-far",
+ trackID: fixture.appTrackID,
+ epoch: farEpoch,
+ text: echoText,
+ analysisStart: farEpoch.analysisInterval.start + 0.2,
+ analysisEnd: farEpoch.analysisInterval.start + 1.8
+ ),
self.unit("mic-0", trackID: fixture.micTrackID, epoch: fixture.micEpoch, text: echoText, analysisStart: 0.4, analysisEnd: 1.9),
]
)
@@ -258,12 +279,20 @@ final class MeetingTextOverlapEchoVerdictProviderTests: XCTestCase {
let micStart = 0.05 + Double(index) * 0.15
let appStart = 1.1 + Double(index) * 0.15
units.append(self.unit(
- "mic-earlier-\(index)", trackID: fixture.micTrackID, epoch: fixture.micEpoch,
- text: word, analysisStart: micStart, analysisEnd: micStart + 0.1
+ "mic-earlier-\(index)",
+ trackID: fixture.micTrackID,
+ epoch: fixture.micEpoch,
+ text: word,
+ analysisStart: micStart,
+ analysisEnd: micStart + 0.1
))
units.append(self.unit(
- "app-later-\(index)", trackID: fixture.appTrackID, epoch: fixture.appEpochs[0],
- text: word, analysisStart: appStart, analysisEnd: appStart + 0.1
+ "app-later-\(index)",
+ trackID: fixture.appTrackID,
+ epoch: fixture.appEpochs[0],
+ text: word,
+ analysisStart: appStart,
+ analysisEnd: appStart + 0.1
))
}
let evidence = MeetingFinalTranscriptEvidence(
diff --git a/Tests/FluidDictationIntegrationTests/MeetingTimelineDriftProbeTests.swift b/Tests/FluidDictationIntegrationTests/MeetingTimelineDriftProbeTests.swift
index ec0bb8d2..357e1379 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingTimelineDriftProbeTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingTimelineDriftProbeTests.swift
@@ -1,7 +1,7 @@
-@testable import FluidVoice_Debug
import AudioToolbox
import AVFoundation
import CoreMedia
+@testable import FluidVoice_Debug
import Foundation
import ScreenCaptureKit
import XCTest
@@ -55,8 +55,10 @@ final class MeetingTimelineDriftProbeTests: XCTestCase {
let microphone = try await MeetingCaptureSourceCatalog.defaultMicrophone(preferredCoreAudioUID: "BuiltInMicrophoneDevice")
var writerDiscontinuities = 0
let track = MeetingAudioTrack(
- id: UUID(), kind: .microphone,
- sourceIdentifier: microphone.captureDeviceID, sourceDisplayName: microphone.displayName,
+ id: UUID(),
+ kind: .microphone,
+ sourceIdentifier: microphone.captureDeviceID,
+ sourceDisplayName: microphone.displayName,
format: nil,
timebase: MeetingTimebaseMetadata(
startedHostTime: mach_absolute_time(),
@@ -64,7 +66,8 @@ final class MeetingTimelineDriftProbeTests: XCTestCase {
machTimebaseDenominator: Self.timebase.denom,
firstPresentationTime: nil
),
- health: .waiting, chunks: []
+ health: .waiting,
+ chunks: []
)
let writer = try MeetingAudioChunkWriter(track: track, sessionDirectory: temp, chunkDuration: 60) { _ in }
@@ -99,7 +102,11 @@ final class MeetingTimelineDriftProbeTests: XCTestCase {
let app = await appRecorder.regression()
print(String(
format: "[drift] t=%4.0fs mic n=%5d slope=%+7.3f ppm | app n=%6d slope=%+7.3f ppm",
- elapsed, mic?.count ?? 0, mic?.slopePPM ?? .nan, app?.count ?? 0, app?.slopePPM ?? .nan
+ elapsed,
+ mic?.count ?? 0,
+ mic?.slopePPM ?? .nan,
+ app?.count ?? 0,
+ app?.slopePPM ?? .nan
))
}
@@ -121,7 +128,11 @@ final class MeetingTimelineDriftProbeTests: XCTestCase {
if let halves = micHalves {
print(String(format: "[drift] mic half-split: %+.3f / %+.3f ppm (Δ=%.3f)", halves.first, halves.second, abs(halves.first - halves.second)))
}
- print("[drift] guards: seqViolations=\(stats.sequenceContinuityViolations) convFail=\(stats.conversionFailures) droppedPostCap=\(stats.droppedPostCapCount) resyncs=\(stats.resyncCount) writerDisc=\(writerDiscontinuities) configChanges=\(stats.configurationChangeEvents) corrections=\(stats.anchorCorrectionCount) absorbed=\(String(format: "%.3f", stats.cumulativeAbsorbedCorrectionSeconds * 1_000))ms stepEvents=\(stats.divergenceStepEventCount)")
+ print(
+ // Keep the exact fixture text or diagnostic output together for comparison.
+ // swiftlint:disable:next line_length
+ "[drift] guards: seqViolations=\(stats.sequenceContinuityViolations) convFail=\(stats.conversionFailures) droppedPostCap=\(stats.droppedPostCapCount) resyncs=\(stats.resyncCount) writerDisc=\(writerDiscontinuities) configChanges=\(stats.configurationChangeEvents) corrections=\(stats.anchorCorrectionCount) absorbed=\(String(format: "%.3f", stats.cumulativeAbsorbedCorrectionSeconds * 1000))ms stepEvents=\(stats.divergenceStepEventCount)"
+ )
print("[drift] NOTE: absolute cross-path offset is unmeasured here (AEC removes acoustic stimuli); Phase 3 validates it on a real call.")
if stats.configurationChangeEvents > 0 {
@@ -141,12 +152,15 @@ final class MeetingTimelineDriftProbeTests: XCTestCase {
mach_timebase_info(&info)
return info
}()
+
private static let timebaseSeconds = Double(timebase.numer) / Double(timebase.denom) / 1_000_000_000
/// The deterministic latency components — the Phase 3 absolute-offset estimate.
private static func printLatencyEstimate(capture settled: MeetingMicrophoneSettledConfig?) {
guard let settled else { return }
- print("[drift] settled: input=\(settled.settledInputDeviceUID ?? "?") output=\(settled.settledOutputDeviceUID ?? "?") source=\(settled.sourceSampleRate)Hz/\(settled.sourceChannelCount)ch")
+ print(
+ "[drift] settled: input=\(settled.settledInputDeviceUID ?? "?") output=\(settled.settledOutputDeviceUID ?? "?") source=\(settled.sourceSampleRate)Hz/\(settled.sourceChannelCount)ch"
+ )
}
}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingTimelineMigrationTests.swift b/Tests/FluidDictationIntegrationTests/MeetingTimelineMigrationTests.swift
index 11dedf9c..31743b76 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingTimelineMigrationTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingTimelineMigrationTests.swift
@@ -127,6 +127,6 @@ final class MeetingTimelineMigrationTests: XCTestCase {
}
private func mediaTime(_ seconds: TimeInterval) -> MeetingMediaTime {
- MeetingMediaTime(value: Int64((seconds * 1_000).rounded()), timescale: 1_000)
+ MeetingMediaTime(value: Int64((seconds * 1000).rounded()), timescale: 1000)
}
}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingTranscriptAssemblerTests.swift b/Tests/FluidDictationIntegrationTests/MeetingTranscriptAssemblerTests.swift
index 6f46beb8..0d830f0a 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingTranscriptAssemblerTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingTranscriptAssemblerTests.swift
@@ -68,6 +68,8 @@ final class MeetingTranscriptAssemblerTests: XCTestCase {
kind: MeetingAudioTrackKind,
chunks: [MeetingAudioChunk],
captureMethod: MeetingAudioTrackCaptureMethod? = nil,
+ // nil requests the fixture default; an empty collection tests explicitly missing data.
+ // swiftlint:disable:next discouraged_optional_collection
eras: [MeetingCaptureEra]? = nil
) -> MeetingAudioTrack {
MeetingAudioTrack(
@@ -213,6 +215,8 @@ final class MeetingTranscriptAssemblerTests: XCTestCase {
analysisEnd: TimeInterval? = nil,
epoch: MeetingAnalysisEpochID? = nil,
speaker: MeetingBackendSpeakerAssignment? = nil,
+ // nil requests the fixture default; an empty collection tests explicitly missing data.
+ // swiftlint:disable:next discouraged_optional_collection
spanIDs: [String]? = nil,
confidence: Double? = nil
) -> MeetingFinalTextUnit {
@@ -735,7 +739,10 @@ final class MeetingTranscriptAssemblerTests: XCTestCase {
id: "r-0", spanID: span.id, analysisStart: 0, analysisEnd: 4, status: .processed
),
MeetingSpanCoverageReceipt(
- id: "r-1", spanID: span.id, analysisStart: 4, analysisEnd: 10,
+ id: "r-1",
+ spanID: span.id,
+ analysisStart: 4,
+ analysisEnd: 10,
status: .providerTruncated
),
]
@@ -779,7 +786,9 @@ final class MeetingTranscriptAssemblerTests: XCTestCase {
let baseEvidence = self.evidence(plan: plan, units: [])
XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(
- plan: plan, manifest: manifest, evidence: baseEvidence,
+ plan: plan,
+ manifest: manifest,
+ evidence: baseEvidence,
coverageReceipts: validReceipts + [MeetingSpanCoverageReceipt(
id: "receipt-0", spanID: span.id, analysisStart: 9, analysisEnd: 10, status: .processed
)]
@@ -788,7 +797,9 @@ final class MeetingTranscriptAssemblerTests: XCTestCase {
}
XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(
- plan: plan, manifest: manifest, evidence: baseEvidence,
+ plan: plan,
+ manifest: manifest,
+ evidence: baseEvidence,
coverageReceipts: [MeetingSpanCoverageReceipt(
id: "r-x", spanID: "no-such-span", analysisStart: 0, analysisEnd: 1, status: .processed
)]
@@ -799,7 +810,9 @@ final class MeetingTranscriptAssemblerTests: XCTestCase {
}
XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(
- plan: plan, manifest: manifest, evidence: baseEvidence,
+ plan: plan,
+ manifest: manifest,
+ evidence: baseEvidence,
coverageReceipts: [MeetingSpanCoverageReceipt(
id: "r-oob", spanID: span.id, analysisStart: 0, analysisEnd: 99, status: .processed
)]
@@ -810,7 +823,9 @@ final class MeetingTranscriptAssemblerTests: XCTestCase {
}
XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(
- plan: plan, manifest: manifest, evidence: baseEvidence,
+ plan: plan,
+ manifest: manifest,
+ evidence: baseEvidence,
coverageReceipts: [
MeetingSpanCoverageReceipt(
id: "r-0", spanID: span.id, analysisStart: 0, analysisEnd: 6, status: .processed
@@ -826,7 +841,9 @@ final class MeetingTranscriptAssemblerTests: XCTestCase {
}
XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(
- plan: plan, manifest: manifest, evidence: baseEvidence,
+ plan: plan,
+ manifest: manifest,
+ evidence: baseEvidence,
coverageReceipts: [MeetingSpanCoverageReceipt(
id: "r-partial", spanID: span.id, analysisStart: 0, analysisEnd: 5, status: .processed
)]
@@ -837,7 +854,9 @@ final class MeetingTranscriptAssemblerTests: XCTestCase {
}
XCTAssertThrowsError(try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(
- plan: plan, manifest: manifest, evidence: baseEvidence,
+ plan: plan,
+ manifest: manifest,
+ evidence: baseEvidence,
coverageReceipts: [MeetingSpanCoverageReceipt(
id: "r-flat", spanID: span.id, analysisStart: 5, analysisEnd: 5, status: .processed
)]
@@ -1013,7 +1032,11 @@ final class MeetingTranscriptAssemblerTests: XCTestCase {
let units = [
self.unit(id: "emitted", span: micSpan, text: "kept", analysisStart: 1, analysisEnd: 2),
self.unit(
- id: "ambiguous", span: micSpan, text: "fuzzy", analysisStart: 1.5, analysisEnd: 2.5,
+ id: "ambiguous",
+ span: micSpan,
+ text: "fuzzy",
+ analysisStart: 1.5,
+ analysisEnd: 2.5,
speaker: .ambiguous([
MeetingBackendSpeakerToken(analysisEpochID: micSpan.analysisEpochID, label: "slot-0"),
MeetingBackendSpeakerToken(analysisEpochID: micSpan.analysisEpochID, label: "slot-1"),
@@ -1273,7 +1296,11 @@ final class MeetingTranscriptAssemblerTests: XCTestCase {
let (plan, manifest, span) = try self.onlineMicFixture()
let assignedUnit = self.unit(id: "u-assigned", span: span, text: "clear", analysisStart: 1, analysisEnd: 2)
let unassignedUnit = self.unit(
- id: "u-unassigned", span: span, text: "noEvidence", analysisStart: 3, analysisEnd: 4,
+ id: "u-unassigned",
+ span: span,
+ text: "noEvidence",
+ analysisStart: 3,
+ analysisEnd: 4,
speaker: .unassigned
)
let result = try MeetingTranscriptAssembler().assemble(MeetingAssemblyInput(
diff --git a/Tests/FluidDictationIntegrationTests/MeetingTranscriptionBackendTests.swift b/Tests/FluidDictationIntegrationTests/MeetingTranscriptionBackendTests.swift
index f2dc411d..51208755 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingTranscriptionBackendTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingTranscriptionBackendTests.swift
@@ -205,6 +205,8 @@ final class MeetingTranscriptionBackendTests: XCTestCase {
private func makeSession(
languageCode: String = "en",
+ // nil requests the fixture default; an empty collection tests explicitly missing data.
+ // swiftlint:disable:next discouraged_optional_collection
tracks: [MeetingAudioTrack]? = nil,
processingAttempts: [MeetingProcessingAttempt] = []
) -> MeetingSession {
@@ -302,7 +304,8 @@ final class MeetingTranscriptionBackendTests: XCTestCase {
registry.register(Self.fixtureBackendID) { _ in
FixtureMeetingBackend(descriptor: descriptor, planOverride: { request in
MeetingBackendPlan(request: MeetingBackendRequest(
- attemptID: request.attemptID, session: request.session,
+ attemptID: request.attemptID,
+ session: request.session,
sessionDirectory: request.sessionDirectory.appendingPathComponent("another-session"),
configuration: request.configuration
), descriptor: descriptor)
@@ -310,7 +313,8 @@ final class MeetingTranscriptionBackendTests: XCTestCase {
}
do {
_ = try await self.makePipeline(registry: registry, backendID: nil).process(
- session: self.makeSession(), sessionDirectory: FileManager.default.temporaryDirectory,
+ session: self.makeSession(),
+ sessionDirectory: FileManager.default.temporaryDirectory,
progress: { _ in }
)
XCTFail("Substituted request must fail before model work")
@@ -328,14 +332,17 @@ final class MeetingTranscriptionBackendTests: XCTestCase {
registry.register(Self.fixtureBackendID) { context in
LegacyCallbackBackend(descriptor: descriptor, executor: context.legacyExecutor) { request in
MeetingBackendRequest(
- attemptID: UUID(), session: request.session, sessionDirectory: request.sessionDirectory,
+ attemptID: UUID(),
+ session: request.session,
+ sessionDirectory: request.sessionDirectory,
configuration: request.configuration
)
}
}
do {
_ = try await self.makePipeline(registry: registry, backendID: nil).process(
- session: self.makeSession(), sessionDirectory: FileManager.default.temporaryDirectory,
+ session: self.makeSession(),
+ sessionDirectory: FileManager.default.temporaryDirectory,
progress: { _ in }
)
XCTFail("Substituted executor request must fail")
@@ -395,8 +402,7 @@ final class MeetingTranscriptionBackendTests: XCTestCase {
let key = "MeetingTranscriptionBackendID"
let oldValue = defaults.object(forKey: key)
defer {
- if let oldValue { defaults.set(oldValue, forKey: key) }
- else { defaults.removeObject(forKey: key) }
+ if let oldValue { defaults.set(oldValue, forKey: key) } else { defaults.removeObject(forKey: key) }
}
let settings = SettingsStore.shared
let dictationModel = settings.selectedSpeechModel
@@ -414,8 +420,7 @@ final class MeetingTranscriptionBackendTests: XCTestCase {
let key = "MeetingTranscriptionBackendID"
let oldValue = defaults.object(forKey: key)
defer {
- if let oldValue { defaults.set(oldValue, forKey: key) }
- else { defaults.removeObject(forKey: key) }
+ if let oldValue { defaults.set(oldValue, forKey: key) } else { defaults.removeObject(forKey: key) }
}
let settingsStore = SettingsStore.shared
let future = MeetingBackendID(rawValue: "future.hosted-provider")
@@ -466,7 +471,8 @@ final class MeetingTranscriptionBackendTests: XCTestCase {
var selectionReads = 0
let pipeline = MeetingProcessingPipeline(
asrServiceProvider: { fatalError("Fixture must not load ASR") },
- serializationGate: MeetingProcessingSerializationGate(), backendRegistry: registry,
+ serializationGate: MeetingProcessingSerializationGate(),
+ backendRegistry: registry,
backendIDProvider: { selectionReads += 1; return selected }
)
let session = self.makeSession()
@@ -836,6 +842,8 @@ final class MeetingTranscriptionBackendTests: XCTestCase {
trackID: MeetingAudioTrackID? = nil,
epoch: MeetingAnalysisEpochID? = nil,
speaker: MeetingBackendSpeakerAssignment? = nil,
+ // nil requests the fixture default; an empty collection tests explicitly missing data.
+ // swiftlint:disable:next discouraged_optional_collection
analysisSpanIDs: [String]? = nil,
confidence: Double? = nil
) -> MeetingFinalTextUnit {
@@ -874,12 +882,22 @@ final class MeetingTranscriptionBackendTests: XCTestCase {
units: [
self.makeUnit(fixture, id: "w-0", precision: .word, analysisStart: 1, analysisEnd: 1.4),
self.makeUnit(
- fixture, id: "utt-0", precision: .utterance, text: "a whole sentence",
- analysisStart: 2, analysisEnd: 6, speaker: .unassigned, confidence: 0.75
+ fixture,
+ id: "utt-0",
+ precision: .utterance,
+ text: "a whole sentence",
+ analysisStart: 2,
+ analysisEnd: 6,
+ speaker: .unassigned,
+ confidence: 0.75
),
self.makeUnit(
- fixture, id: "utt-1", precision: .utterance, text: "overlapped",
- analysisStart: 6, analysisEnd: 7,
+ fixture,
+ id: "utt-1",
+ precision: .utterance,
+ text: "overlapped",
+ analysisStart: 6,
+ analysisEnd: 7,
speaker: .ambiguous([
MeetingBackendSpeakerToken(analysisEpochID: fixture.epoch, label: "slot-0"),
MeetingBackendSpeakerToken(analysisEpochID: fixture.epoch, label: "slot-1"),
diff --git a/Tests/FluidDictationIntegrationTests/MeetingVoiceProcessingCaptureTests.swift b/Tests/FluidDictationIntegrationTests/MeetingVoiceProcessingCaptureTests.swift
index d60a5082..e1782350 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingVoiceProcessingCaptureTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingVoiceProcessingCaptureTests.swift
@@ -1,10 +1,10 @@
-@testable import FluidVoice_Debug
import AVFoundation
import CoreAudio
import CoreMedia
+@testable import FluidVoice_Debug
import Foundation
-import ScreenCaptureKit
import os
+import ScreenCaptureKit
import XCTest
/// Hardware/permission-free: ScreenCaptureKit and AVAudioEngine integration paths need live
@@ -48,20 +48,22 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
func testDirectAEC3GateDefaultsOnAndHasExactDisableEscapeHatch() {
XCTAssertTrue(MeetingDirectAEC3Gate.enabled(environment: [:]))
XCTAssertTrue(MeetingDirectAEC3Gate.enabled(environment: [
- MeetingDirectAEC3Gate.disableEnvironmentKey: "true"
+ MeetingDirectAEC3Gate.disableEnvironmentKey: "true",
]))
XCTAssertFalse(MeetingDirectAEC3Gate.enabled(environment: [
- MeetingDirectAEC3Gate.disableEnvironmentKey: "1"
+ MeetingDirectAEC3Gate.disableEnvironmentKey: "1",
]))
}
-#if DEBUG
+ #if DEBUG
func testExplicitC2GateCanForcePairedScreenCaptureKitWithoutChangingDefault() {
let defaultDecision = MeetingCapturePathDecider.decide(
mode: .onlineCall, microphone: self.mic(), outputRoute: self.viableRoute()
)
let forcedDecision = MeetingCapturePathDecider.decide(
- mode: .onlineCall, microphone: self.mic(), outputRoute: self.viableRoute(),
+ mode: .onlineCall,
+ microphone: self.mic(),
+ outputRoute: self.viableRoute(),
forcePairedScreenCaptureKit: true,
preferDirectAEC3: true
)
@@ -78,13 +80,13 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
func testC2GateIsOnlyEnabledByExplicitEnvironmentValue() {
XCTAssertFalse(MeetingSCKPairedDiagnosticGate.enabled(environment: [:]))
XCTAssertFalse(MeetingSCKPairedDiagnosticGate.enabled(environment: [
- MeetingSCKPairedDiagnosticGate.environmentKey: "true"
+ MeetingSCKPairedDiagnosticGate.environmentKey: "true",
]))
XCTAssertTrue(MeetingSCKPairedDiagnosticGate.enabled(environment: [
- MeetingSCKPairedDiagnosticGate.environmentKey: "1"
+ MeetingSCKPairedDiagnosticGate.environmentKey: "1",
]))
}
-#endif
+ #endif
func testDecisionDeclinesForInRoomMode() {
let decision = MeetingCapturePathDecider.decide(mode: .inRoom, microphone: self.mic(), outputRoute: self.viableRoute())
@@ -161,8 +163,11 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
func testRawRouteRequiresPositiveHeadphoneEvidence() {
let unknownBluetooth = MeetingOutputRouteSnapshot(
- deviceExists: true, isBluetooth: true, isBuiltIn: false,
- isHeadphonesDataSource: false, terminalTypes: []
+ deviceExists: true,
+ isBluetooth: true,
+ isBuiltIn: false,
+ isHeadphonesDataSource: false,
+ terminalTypes: []
)
XCTAssertEqual(MeetingRawMicrophoneProtection.classify(unknownBluetooth), .unprotected)
@@ -179,7 +184,9 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
XCTAssertEqual(MeetingRawMicrophoneProtection.classify(headphones), .acousticallyClosed)
let builtInHeadphoneJack = MeetingOutputRouteSnapshot(
- deviceExists: true, isBluetooth: false, isBuiltIn: true,
+ deviceExists: true,
+ isBluetooth: false,
+ isBuiltIn: true,
isHeadphonesDataSource: true
)
XCTAssertEqual(MeetingRawMicrophoneProtection.classify(builtInHeadphoneJack), .acousticallyClosed)
@@ -197,12 +204,20 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
func testTurnCrossingUnprotectedEraIsRejectedAsAWhole() {
let eras = [
MeetingCaptureEra(
- method: .voiceProcessing, deviceUID: "mic", deviceName: "Mic",
- roleAtElection: .unknown, echoProtection: .voiceProcessed, startSeconds: -.infinity
+ method: .voiceProcessing,
+ deviceUID: "mic",
+ deviceName: "Mic",
+ roleAtElection: .unknown,
+ echoProtection: .voiceProcessed,
+ startSeconds: -.infinity
),
MeetingCaptureEra(
- method: .avCaptureSession, deviceUID: "mic", deviceName: "Mic",
- roleAtElection: .unknown, echoProtection: .unprotected, startSeconds: 10
+ method: .avCaptureSession,
+ deviceUID: "mic",
+ deviceName: "Mic",
+ roleAtElection: .unknown,
+ echoProtection: .unprotected,
+ startSeconds: 10
),
]
XCTAssertTrue(MeetingProcessingPipeline.microphoneIntervalIsAdmitted(start: 8, end: 9.9, eras: eras))
@@ -249,26 +264,40 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
sourceDisplayName: "Mic",
format: nil,
timebase: MeetingTimebaseMetadata(
- startedHostTime: 0, machTimebaseNumerator: 1,
- machTimebaseDenominator: 1, firstPresentationTime: nil
+ startedHostTime: 0,
+ machTimebaseNumerator: 1,
+ machTimebaseDenominator: 1,
+ firstPresentationTime: nil
),
health: .waiting,
chunks: [MeetingAudioChunk(
- id: UUID(), sequence: 0, relativeFilePath: "mic.m4a",
+ id: UUID(),
+ sequence: 0,
+ relativeFilePath: "mic.m4a",
presentationStart: MeetingMediaTime(value: 100, timescale: 1),
presentationEnd: MeetingMediaTime(value: 120, timescale: 1),
- discontinuities: [], sha256: "x", byteCount: 1,
+ discontinuities: [],
+ sha256: "x",
+ byteCount: 1,
finalizationState: .finalized
)],
captureMethod: .avCaptureSession,
captureEras: [
MeetingCaptureEra(
- method: .voiceProcessing, deviceUID: "mic", deviceName: "Mic",
- roleAtElection: .unknown, echoProtection: .voiceProcessed, startSeconds: 0
+ method: .voiceProcessing,
+ deviceUID: "mic",
+ deviceName: "Mic",
+ roleAtElection: .unknown,
+ echoProtection: .voiceProcessed,
+ startSeconds: 0
),
MeetingCaptureEra(
- method: .avCaptureSession, deviceUID: "mic", deviceName: "Mic",
- roleAtElection: .unknown, echoProtection: .unprotected, startSeconds: 110
+ method: .avCaptureSession,
+ deviceUID: "mic",
+ deviceName: "Mic",
+ roleAtElection: .unknown,
+ echoProtection: .unprotected,
+ startSeconds: 110
),
]
)
@@ -281,10 +310,16 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
// MARK: - Commit gate
private func makeSampleBuffer(ptsSeconds: Double = 0) -> CMSampleBuffer {
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 1, interleaved: false)!
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 480)!
buffer.frameLength = 480
let pts = CMTime(seconds: ptsSeconds, preferredTimescale: 48_000)
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
return meetingMicrophoneSynthesizeSampleBuffer(from: buffer, presentationTime: pts)!
}
@@ -323,7 +358,7 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
func testGateAbortsAndSwallowsAfterRingExhaustion() throws {
// Cap sized to fit exactly one sample's worth of bytes: the second sample must not fit.
let one = self.makeSampleBuffer()
- let bytes = CMBlockBufferGetDataLength(try XCTUnwrap(CMSampleBufferGetDataBuffer(one)))
+ let bytes = try CMBlockBufferGetDataLength(XCTUnwrap(CMSampleBufferGetDataBuffer(one)))
XCTAssertGreaterThan(bytes, 0)
let gate = MeetingVoiceProcessingCommitGate(ringCapBytes: bytes)
XCTAssertEqual(gate.offer(one), .buffered)
@@ -542,7 +577,8 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
XCTAssertEqual(startEntered.wait(timeout: .now() + 1), .success)
let stopTask = Task { await lifecycle.stop() }
XCTAssertEqual(
- stopRan.wait(timeout: .now() + 0.1), .timedOut,
+ stopRan.wait(timeout: .now() + 0.1),
+ .timedOut,
"retirement must not bypass an uninterruptible startRunning call"
)
@@ -573,7 +609,8 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
let lateStartSucceeded = await lifecycle.start()
XCTAssertFalse(lateStartSucceeded)
XCTAssertEqual(
- startRan.wait(timeout: .now() + 0.1), .timedOut,
+ startRan.wait(timeout: .now() + 0.1),
+ .timedOut,
"retirement must permanently seal the lifecycle against late restarts"
)
@@ -768,10 +805,15 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil),
health: .waiting,
chunks: [MeetingAudioChunk(
- id: UUID(), sequence: 0, relativeFilePath: "x.m4a",
+ id: UUID(),
+ sequence: 0,
+ relativeFilePath: "x.m4a",
presentationStart: MeetingMediaTime(value: Int64(chunkStart * 48_000), timescale: 48_000),
presentationEnd: MeetingMediaTime(value: Int64((chunkStart + 60) * 48_000), timescale: 48_000),
- discontinuities: [], sha256: "x", byteCount: 1, finalizationState: .finalized
+ discontinuities: [],
+ sha256: "x",
+ byteCount: 1,
+ finalizationState: .finalized
)]
)
track.captureMethod = captureMethod
@@ -797,10 +839,10 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
var clock = MeetingMicrophonePTSClock(timebase: mach_timebase_info_data_t(numer: 1, denom: 1))
let ppm = 6.7e-6
let windowSeconds = 0.1
- let windows = 9_500 // 950s: past the ~12.5min materiality crossover at 6.7ppm
+ let windows = 9500 // 950s: past the ~12.5min materiality crossover at 6.7ppm
for i in 0..<windows {
let hostSeconds = Double(i) * windowSeconds * (1 - ppm) // fast mic: less host time per window
- _ = clock.stamp(hostTime: UInt64(hostSeconds * 1_000_000_000), frameCount: 4_800)
+ _ = clock.stamp(hostTime: UInt64(hostSeconds * 1_000_000_000), frameCount: 4800)
}
let elapsed = Double(windows - 1) * windowSeconds * (1 - ppm)
let cumulative = clock.cumulativeAbsorbedCorrectionSeconds
@@ -847,10 +889,14 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
let sessionDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
defer { try? FileManager.default.removeItem(at: sessionDirectory) }
let track = MeetingAudioTrack(
- id: UUID(), kind: .microphone, sourceIdentifier: "mic", sourceDisplayName: "Mic",
+ id: UUID(),
+ kind: .microphone,
+ sourceIdentifier: "mic",
+ sourceDisplayName: "Mic",
format: nil,
timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil),
- health: .waiting, chunks: []
+ health: .waiting,
+ chunks: []
)
let backpressureCount = OSAllocatedUnfairLock<Int>(initialState: 0)
let writer = try MeetingAudioChunkWriter(track: track, sessionDirectory: sessionDirectory, chunkDuration: 60) { event in
@@ -876,10 +922,15 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
let sessionDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
defer { try? FileManager.default.removeItem(at: sessionDirectory) }
let track = MeetingAudioTrack(
- id: UUID(), kind: .microphone, sourceIdentifier: "mic", sourceDisplayName: "Mic",
+ id: UUID(),
+ kind: .microphone,
+ sourceIdentifier: "mic",
+ sourceDisplayName: "Mic",
format: nil,
timebase: MeetingTimebaseMetadata(startedHostTime: 0, machTimebaseNumerator: 1, machTimebaseDenominator: 1, firstPresentationTime: nil),
- health: .waiting, chunks: [], captureMethod: .screenCaptureKit
+ health: .waiting,
+ chunks: [],
+ captureMethod: .screenCaptureKit
)
let writer = try MeetingAudioChunkWriter(track: track, sessionDirectory: sessionDirectory, chunkDuration: 60) { _ in }
@@ -938,7 +989,7 @@ final class MeetingVoiceProcessingCaptureTests: XCTestCase {
encoder.dateEncodingStrategy = .iso8601
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
- let decoded = try decoder.decode(MeetingAudioTrack.self, from: try encoder.encode(track))
+ let decoded = try decoder.decode(MeetingAudioTrack.self, from: encoder.encode(track))
XCTAssertEqual(decoded.captureMethod, .voiceProcessing)
XCTAssertEqual(decoded.clockDrift, drift)
}
diff --git a/Tests/FluidDictationIntegrationTests/MeetingVoiceProcessingProbeTests.swift b/Tests/FluidDictationIntegrationTests/MeetingVoiceProcessingProbeTests.swift
index 6974ada3..8d5eb90a 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingVoiceProcessingProbeTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingVoiceProcessingProbeTests.swift
@@ -1,7 +1,7 @@
#if DEBUG
-@testable import FluidVoice_Debug
import AudioToolbox
import AVFoundation
+@testable import FluidVoice_Debug
import XCTest
final class MeetingVoiceProcessingProbeTests: XCTestCase {
@@ -17,15 +17,17 @@ final class MeetingVoiceProcessingProbeTests: XCTestCase {
XCTAssertEqual(
MeetingVPIOAcousticTrialB.stimulusSampleZeroHostSeconds(
renderActivityStartHostSeconds: 10.2,
- leadingSilenceFrameCount: 9_600,
+ leadingSilenceFrameCount: 9600,
sampleRate: 48_000
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
)!,
10.0,
accuracy: 1e-12
)
XCTAssertNil(MeetingVPIOAcousticTrialB.stimulusSampleZeroHostSeconds(
renderActivityStartHostSeconds: .infinity,
- leadingSilenceFrameCount: 9_600,
+ leadingSilenceFrameCount: 9600,
sampleRate: 48_000
))
}
@@ -35,10 +37,16 @@ final class MeetingVoiceProcessingProbeTests: XCTestCase {
let empty = collector.window(startHostSeconds: 0, frameCount: 4, sampleRate: 48_000)
XCTAssertLessThan(empty.window.coverage, 1)
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 1, interleaved: false)!
func sampleBuffer() throws -> CMSampleBuffer {
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
let pcm = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 4)!
pcm.frameLength = 4
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
pcm.floatChannelData![0].update(repeating: 0.1, count: 4)
return try XCTUnwrap(meetingMicrophoneSynthesizeSampleBuffer(
from: pcm, presentationTime: CMTime.zero
@@ -46,7 +54,7 @@ final class MeetingVoiceProcessingProbeTests: XCTestCase {
}
let first = try sampleBuffer()
collector.ingest(first, synthesized: true, resynced: false)
- collector.ingest(try sampleBuffer(), synthesized: false, resynced: true)
+ try collector.ingest(sampleBuffer(), synthesized: false, resynced: true)
let window = collector.window(startHostSeconds: 0, frameCount: 4, sampleRate: 48_000)
XCTAssertGreaterThan(window.window.overlapFrameCount, 0)
XCTAssertGreaterThan(window.window.synthesizedFrameCount, 0)
@@ -76,7 +84,7 @@ final class MeetingVoiceProcessingProbeTests: XCTestCase {
reference: reference, captured: captured, sampleRate: sampleRate, silencePrefixFrames: 0
)
XCTAssertTrue(measurement.delay.resolved, "reasons=\(measurement.delay.reasons)")
- XCTAssertEqual(measurement.delay.signedSeconds!, Double(delay) / sampleRate, accuracy: 2 / sampleRate)
+ XCTAssertEqual(try XCTUnwrap(measurement.delay.signedSeconds), Double(delay) / sampleRate, accuracy: 2 / sampleRate)
XCTAssertGreaterThanOrEqual(measurement.bands.count, 4)
}
@@ -102,9 +110,9 @@ final class MeetingVoiceProcessingProbeTests: XCTestCase {
}
func testVPIOMetricsMarksSilenceLowExcitationAndMismatchedControlUnknown() {
- let silence = Array(repeating: Float.zero, count: 5_000)
+ let silence = Array(repeating: Float.zero, count: 5000)
let silentMeasurement = MeetingVPIOAcousticMetrics.measure(
- reference: silence, captured: silence, sampleRate: 16_000, silencePrefixFrames: 1_024
+ reference: silence, captured: silence, sampleRate: 16_000, silencePrefixFrames: 1024
)
XCTAssertFalse(silentMeasurement.valid)
XCTAssertTrue(silentMeasurement.reasons.contains(.referenceBelowExcitationFloor))
@@ -126,12 +134,18 @@ final class MeetingVoiceProcessingProbeTests: XCTestCase {
let stimulus = try XCTUnwrap(MeetingVPIOAcousticStimulus.make(sampleRate: 16_000))
let report = MeetingVPIOAcousticTrialBReport(
schemaVersion: MeetingVPIOAcousticTrialBReport.currentSchemaVersion,
- stimulus: stimulus.descriptor, renderVolume: 0.5, preRollSeconds: 0.3,
- postRollSeconds: 0.6, settleSeconds: 0.35, runs: [],
+ stimulus: stimulus.descriptor,
+ renderVolume: 0.5,
+ preRollSeconds: 0.3,
+ postRollSeconds: 0.6,
+ settleSeconds: 0.35,
+ runs: [],
caveats: MeetingVPIOAcousticTrialBReport.interpretationCaveats
)
let data = try JSONEncoder().encode(report)
XCTAssertEqual(try JSONDecoder().decode(MeetingVPIOAcousticTrialBReport.self, from: data), report)
+ // JSONEncoder fixture bytes are UTF-8; retain nonoptional decoding for assertions.
+ // swiftlint:disable:next optional_data_string_conversion
let json = String(decoding: data, as: UTF8.self)
XCTAssertFalse(json.contains("samples"))
XCTAssertFalse(json.contains("transcript"))
@@ -170,6 +184,8 @@ final class MeetingVoiceProcessingProbeTests: XCTestCase {
sampleRate: 48_000,
channels: 1,
interleaved: false
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
)!
let successfulRead = MeetingAudioUnitUInt32Readback(
propertyID: kAUVoiceIOProperty_VoiceProcessingEnableAGC,
diff --git a/Tests/FluidDictationIntegrationTests/MeetingWindowSelectorTests.swift b/Tests/FluidDictationIntegrationTests/MeetingWindowSelectorTests.swift
index 3cf34115..d672ec05 100644
--- a/Tests/FluidDictationIntegrationTests/MeetingWindowSelectorTests.swift
+++ b/Tests/FluidDictationIntegrationTests/MeetingWindowSelectorTests.swift
@@ -66,28 +66,28 @@ final class MeetingWindowSelectorTests: XCTestCase {
}
func testExactMinimumSizeIsIncludedAndOnePixelUnderIsNot() {
- let atMinimum = candidate(1, title: "Meeting", frame: CGRect(x: 0, y: 0, width: 200, height: 100))
+ let atMinimum = self.candidate(1, title: "Meeting", frame: CGRect(x: 0, y: 0, width: 200, height: 100))
XCTAssertEqual(MeetingWindowSelector.selectWindow(from: [atMinimum])?.windowID, 1)
- let underWidth = candidate(2, title: "Meeting", frame: CGRect(x: 0, y: 0, width: 199, height: 100))
- let underHeight = candidate(3, title: "Meeting", frame: CGRect(x: 0, y: 0, width: 200, height: 99))
+ let underWidth = self.candidate(2, title: "Meeting", frame: CGRect(x: 0, y: 0, width: 199, height: 100))
+ let underHeight = self.candidate(3, title: "Meeting", frame: CGRect(x: 0, y: 0, width: 200, height: 99))
XCTAssertNil(MeetingWindowSelector.selectWindow(from: [underWidth, underHeight]))
}
func testWhitespaceOnlyTitleCountsAsUntitled() {
- let whitespace = candidate(1, title: " \n", frame: CGRect(x: 0, y: 0, width: 2000, height: 1500), zOrderIndex: 0)
- let titled = candidate(2, title: "Meeting", frame: CGRect(x: 0, y: 0, width: 400, height: 300), zOrderIndex: 5)
+ let whitespace = self.candidate(1, title: " \n", frame: CGRect(x: 0, y: 0, width: 2000, height: 1500), zOrderIndex: 0)
+ let titled = self.candidate(2, title: "Meeting", frame: CGRect(x: 0, y: 0, width: 400, height: 300), zOrderIndex: 5)
XCTAssertEqual(MeetingWindowSelector.selectWindow(from: [whitespace, titled])?.windowID, 2)
}
func testLargerAreaBeatsSmallerWindowIDWhenTitleAndZOrderTie() {
- let smallEarlyID = candidate(1, title: "A", frame: CGRect(x: 0, y: 0, width: 400, height: 300), zOrderIndex: 2)
- let largeLateID = candidate(9, title: "B", frame: CGRect(x: 0, y: 0, width: 900, height: 700), zOrderIndex: 2)
+ let smallEarlyID = self.candidate(1, title: "A", frame: CGRect(x: 0, y: 0, width: 400, height: 300), zOrderIndex: 2)
+ let largeLateID = self.candidate(9, title: "B", frame: CGRect(x: 0, y: 0, width: 900, height: 700), zOrderIndex: 2)
XCTAssertEqual(MeetingWindowSelector.selectWindow(from: [smallEarlyID, largeLateID])?.windowID, 9)
}
func testFrontmostBeatsSmallerWindowID() {
- let behindEarlyID = candidate(1, title: "A", frame: CGRect(x: 0, y: 0, width: 800, height: 600), zOrderIndex: 4)
- let frontLateID = candidate(9, title: "B", frame: CGRect(x: 0, y: 0, width: 800, height: 600), zOrderIndex: 1)
+ let behindEarlyID = self.candidate(1, title: "A", frame: CGRect(x: 0, y: 0, width: 800, height: 600), zOrderIndex: 4)
+ let frontLateID = self.candidate(9, title: "B", frame: CGRect(x: 0, y: 0, width: 800, height: 600), zOrderIndex: 1)
XCTAssertEqual(MeetingWindowSelector.selectWindow(from: [behindEarlyID, frontLateID])?.windowID, 9)
}
}
diff --git a/Tests/FluidDictationIntegrationTests/SearchIndexTests.swift b/Tests/FluidDictationIntegrationTests/SearchIndexTests.swift
index 899dcca5..17a4afeb 100644
--- a/Tests/FluidDictationIntegrationTests/SearchIndexTests.swift
+++ b/Tests/FluidDictationIntegrationTests/SearchIndexTests.swift
@@ -30,11 +30,11 @@ final class SearchIndexTests: XCTestCase {
}
private func ids(_ kind: SearchIndexKind, query: String) async throws -> Set<UUID> {
- Set(try await self.index.query(kind, text: query, limit: 50).map(\.id))
+ try Set(await self.index.query(kind, text: query, limit: 50).map(\.id))
}
private func count(_ kind: SearchIndexKind) async throws -> Int {
- Int(try await self.index.namespace(kind).count().count)
+ try Int(await self.index.namespace(kind).count().count)
}
// MARK: - Reconcile
diff --git a/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift b/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift
index f989201d..a426ffeb 100644
--- a/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift
+++ b/Tests/FluidDictationIntegrationTests/SpeakerTurnMergingTests.swift
@@ -1,5 +1,5 @@
-@testable import FluidVoice_Debug
import CoreMedia
+@testable import FluidVoice_Debug
import Foundation
import XCTest
@@ -176,8 +176,8 @@ final class SpeakerLabeledTranscriptionPolicyTests: XCTestCase {
func testEmptyLaterChunkKeepsEarlierTextAndRecordsOnlyTheMissingRange() async {
let ranges = [
- SpeakerTranscriptGap(startSeconds: 0, endSeconds: 1_200),
- SpeakerTranscriptGap(startSeconds: 1_200, endSeconds: 1_205),
+ SpeakerTranscriptGap(startSeconds: 0, endSeconds: 1200),
+ SpeakerTranscriptGap(startSeconds: 1200, endSeconds: 1205),
]
let result = await SpeakerLabeledTranscriptionPolicy.transcribeChunks(ranges) { range in
@@ -284,7 +284,7 @@ final class SpeakerLabeledTranscriptionPolicyTests: XCTestCase {
XCTAssertTrue(SpeakerLabeledTranscriptionPolicy.shouldKeepSpeakerLabels(
hasRecognizedText: true,
gaps: gaps,
- diarizedDurationSeconds: 3_000
+ diarizedDurationSeconds: 3000
))
}
@@ -323,7 +323,7 @@ final class SpeakerLabeledTranscriptionPolicyTests: XCTestCase {
XCTAssertFalse(SpeakerLabeledTranscriptionPolicy.shouldKeepSpeakerLabels(
hasRecognizedText: true,
gaps: gaps,
- diarizedDurationSeconds: 1_000
+ diarizedDurationSeconds: 1000
))
}
@@ -362,7 +362,7 @@ final class SpeakerLabeledTranscriptionPolicyTests: XCTestCase {
XCTAssertEqual(coverage.skippedDurationSeconds, 5.75, accuracy: 0.0001)
XCTAssertEqual(coverage.maxGapDurationSeconds, 4.25, accuracy: 0.0001)
XCTAssertEqual(coverage.diarizedDurationSeconds, 200, accuracy: 0.0001)
- XCTAssertEqual(coverage.skippedRatio, 0.02875, accuracy: 0.000001)
+ XCTAssertEqual(coverage.skippedRatio, 0.02_875, accuracy: 0.000_001)
}
func testFallbackDiagnosticNamesMissingRecognizedTextInsteadOfOmittedAudio() {
@@ -425,7 +425,7 @@ final class SpeakerLabeledTranscriptionPolicyTests: XCTestCase {
let duration: TimeInterval = 5
let processingTime: TimeInterval = 1
let fileName = "old.wav"
- let timestamp = Date(timeIntervalSince1970: 1_000)
+ let timestamp = Date(timeIntervalSince1970: 1000)
}
let decoded = try JSONDecoder().decode(
@@ -458,7 +458,7 @@ final class SpeakerLabeledTranscriptionPolicyTests: XCTestCase {
func testOlderHistoryEntryWithoutSpeakerLabelingDetailsStillDecodes() throws {
struct LegacyEntry: Encodable {
let id = UUID()
- let timestamp = Date(timeIntervalSince1970: 1_000)
+ let timestamp = Date(timeIntervalSince1970: 1000)
let fileName = "old.wav"
let duration: TimeInterval = 5
let processingTime: TimeInterval = 1
@@ -493,7 +493,7 @@ final class SpeakerLabeledTranscriptionPolicyTests: XCTestCase {
SpeakerRecognizedTurn(
speaker: "Speaker 3",
startSeconds: 501,
- endSeconds: 1_001,
+ endSeconds: 1001,
transcription: SpeakerTurnTranscription(text: "Last", confidence: 1, gaps: [])
),
]
@@ -525,7 +525,7 @@ final class SpeakerLabeledTranscriptionPolicyTests: XCTestCase {
SpeakerRecognizedTurn(
speaker: "Speaker 3",
startSeconds: 506,
- endSeconds: 1_006,
+ endSeconds: 1006,
transcription: SpeakerTurnTranscription(text: "Last", confidence: 1, gaps: [])
),
]
@@ -571,6 +571,7 @@ final class FluidAudioProviderWordTimingTests: XCTestCase {
#endif
// MARK: - Transcript exporter tests (kept on MeetingSessionModelTests so the standard
+
// meeting-suite -only-testing invocation exercises them without an extra class filter).
extension MeetingSessionModelTests {
private static let allowedExportKeys: Set<String> = [
@@ -1768,6 +1769,8 @@ final class MeetingSessionModelTests: XCTestCase {
private func micTurn(
_ cluster: UUID, _ start: Double, _ end: Double,
overlapsRemote: Bool = true, echoScored: Bool = true, isEcho: Bool = false
+ // Mirror the test fixture fields in one named return value.
+ // swiftlint:disable:next large_tuple
) -> (clusterID: UUID, start: Double, end: Double, overlapsRemote: Bool, echoScored: Bool, isEcho: Bool) {
(cluster, start, end, overlapsRemote, echoScored, isEcho)
}
@@ -2573,7 +2576,9 @@ private actor FakeMeetingSessionStore: MeetingSessionStoring {
func deleteAudioFiles(for id: MeetingSessionID) throws {
guard var session = self.sessions[id] else { return }
- for index in session.audioTracks.indices { session.audioTracks[index].chunks = [] }
+ for index in session.audioTracks.indices {
+ session.audioTracks[index].chunks = []
+ }
self.sessions[id] = session
}
diff --git a/Tests/FluidDictationIntegrationTests/VoiceProcessingAsrQualityTests.swift b/Tests/FluidDictationIntegrationTests/VoiceProcessingAsrQualityTests.swift
index 39e08d9c..42f655ba 100644
--- a/Tests/FluidDictationIntegrationTests/VoiceProcessingAsrQualityTests.swift
+++ b/Tests/FluidDictationIntegrationTests/VoiceProcessingAsrQualityTests.swift
@@ -1,5 +1,5 @@
-@testable import FluidVoice_Debug
import AVFoundation
+@testable import FluidVoice_Debug
import Foundation
import XCTest
@@ -32,10 +32,18 @@ final class VoiceProcessingAsrQualityTests: XCTestCase {
try await Task.sleep(nanoseconds: 2_000_000_000)
let processed = try await Self.capture(voiceProcessing: true, label: "TAKE 2 of 2 — voice processing ON")
- print(String(format: "\n[ab] raw %.1fs rms=%.5f (%.1f dBFS)",
- Double(raw.count) / 16_000, Self.rms(raw), 20 * log10(max(Self.rms(raw), 1e-9))))
- print(String(format: "[ab] vpio %.1fs rms=%.5f (%.1f dBFS)",
- Double(processed.count) / 16_000, Self.rms(processed), 20 * log10(max(Self.rms(processed), 1e-9))))
+ print(String(
+ format: "\n[ab] raw %.1fs rms=%.5f (%.1f dBFS)",
+ Double(raw.count) / 16_000,
+ Self.rms(raw),
+ 20 * log10(max(Self.rms(raw), 1e-9))
+ ))
+ print(String(
+ format: "[ab] vpio %.1fs rms=%.5f (%.1f dBFS)",
+ Double(processed.count) / 16_000,
+ Self.rms(processed),
+ 20 * log10(max(Self.rms(processed), 1e-9))
+ ))
let rawText = try await Self.transcribe(raw)
let vpioText = try await Self.transcribe(processed)
@@ -89,10 +97,12 @@ final class VoiceProcessingAsrQualityTests: XCTestCase {
else { return "(format error)" }
var index = 0
while index < samples.count {
- let end = min(index + 2_560, samples.count)
+ let end = min(index + 2560, samples.count)
guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(end - index)) else { break }
buffer.frameLength = AVAudioFrameCount(end - index)
samples[index..<end].withUnsafeBufferPointer { source in
+ // Fixed test fixture: missing required audio storage or evidence is a setup failure.
+ // swiftlint:disable:next force_unwrapping
buffer.floatChannelData?[0].update(from: source.baseAddress!, count: end - index)
}
try await manager.appendAudio(buffer)
diff --git a/Tests/FluidDictationIntegrationTests/VoiceProcessingDuckingProbeTests.swift b/Tests/FluidDictationIntegrationTests/VoiceProcessingDuckingProbeTests.swift
index 78664e1b..779b921c 100644
--- a/Tests/FluidDictationIntegrationTests/VoiceProcessingDuckingProbeTests.swift
+++ b/Tests/FluidDictationIntegrationTests/VoiceProcessingDuckingProbeTests.swift
@@ -1,5 +1,5 @@
-@testable import FluidVoice_Debug
import AVFoundation
+@testable import FluidVoice_Debug
import Foundation
import ScreenCaptureKit
import XCTest
@@ -99,7 +99,6 @@ final class VoiceProcessingDuckingProbeTests: XCTestCase {
print("[vpio] buffers=\(stats.buffers) copyFailures=\(stats.copyFailures) framesTotal=\(stats.frames) streamError=\(errorDelegate.lastError ?? "none")")
XCTAssertGreaterThan(baseline, 0, "SCStream captured no audio; tone or permission problem")
}
-
}
private actor AudioLevelCollector {
@@ -152,7 +151,9 @@ private final class LevelStreamOutput: NSObject, SCStreamOutput {
return
}
var sum = 0.0
- for i in 0..<Int(frames) { sum += Double(channel[i]) * Double(channel[i]) }
+ for i in 0..<Int(frames) {
+ sum += Double(channel[i]) * Double(channel[i])
+ }
Task { [collector] in await collector.add(sumOfSquares: sum, frames: Int(frames)) }
}
}
diff --git a/Tests/FluidDictationIntegrationTests/VoiceProcessingSpeechDuckingTests.swift b/Tests/FluidDictationIntegrationTests/VoiceProcessingSpeechDuckingTests.swift
index a6cfad5d..a7963fb6 100644
--- a/Tests/FluidDictationIntegrationTests/VoiceProcessingSpeechDuckingTests.swift
+++ b/Tests/FluidDictationIntegrationTests/VoiceProcessingSpeechDuckingTests.swift
@@ -1,5 +1,5 @@
-@testable import FluidVoice_Debug
import AVFoundation
+@testable import FluidVoice_Debug
import Foundation
import ScreenCaptureKit
import XCTest
@@ -76,7 +76,11 @@ final class VoiceProcessingSpeechDuckingTests: XCTestCase {
let mean = values.reduce(0, +) / Double(values.count)
print(String(
format: "[speech] %-18@ seconds=%d mean=%.1f dBFS min=%.1f max=%.1f swing=%.1f dB",
- label as NSString, values.count, dB(mean), dB(values.min() ?? 0), dB(values.max() ?? 0),
+ label as NSString,
+ values.count,
+ dB(mean),
+ dB(values.min() ?? 0),
+ dB(values.max() ?? 0),
dB(values.max() ?? 0) - dB(values.min() ?? 0)
))
}
@@ -170,7 +174,9 @@ private final class TimelineStreamOutput: NSObject, SCStreamOutput {
sampleBuffer, at: 0, frameCount: Int32(frames), into: buffer.mutableAudioBufferList
) == noErr, let channel = buffer.floatChannelData?[0] else { return }
var sum = 0.0
- for i in 0..<Int(frames) { sum += Double(channel[i]) * Double(channel[i]) }
+ for i in 0..<Int(frames) {
+ sum += Double(channel[i]) * Double(channel[i])
+ }
Task { [recorder] in await recorder.add(sumOfSquares: sum, frames: Int(frames)) }
}
}
diff --git a/Tests/FluidTypographyTests.swift b/Tests/FluidTypographyTests.swift
index aca9a58d..451a4c80 100644
--- a/Tests/FluidTypographyTests.swift
+++ b/Tests/FluidTypographyTests.swift
@@ -13,7 +13,11 @@ struct FluidTypographyTests {
precondition(Font.fluidSystem(size: 23, weight: .semibold, design: design) == Font.custom("AvenirNext-Regular", fixedSize: 23).weight(.semibold))
} else {
precondition(FluidTypography.name(for: design) == nil)
- precondition(Font.fluidSystem(size: 23, weight: .semibold, design: design) == Font.system(size: 23, weight: .semibold, design: FluidTypography.systemDesign(for: design)))
+ precondition(Font.fluidSystem(size: 23, weight: .semibold, design: design) == Font.system(
+ size: 23,
+ weight: .semibold,
+ design: FluidTypography.systemDesign(for: design)
+ ))
precondition(Font.fluidSystem(.caption, design: design) == Font.system(.caption, design: FluidTypography.systemDesign(for: design)))
}
}
diff --git a/Tests/OnboardingAISetupControllerTests.swift b/Tests/OnboardingAISetupControllerTests.swift
index 89555d9a..8a8539d9 100644
--- a/Tests/OnboardingAISetupControllerTests.swift
+++ b/Tests/OnboardingAISetupControllerTests.swift
@@ -232,6 +232,8 @@ struct OnboardingAISetupControllerTests {
missing.enable { _ in throw Harness.Failure.simulated }
await self.waitUntil { missing.errorMessage != nil }
precondition(missing.phase == .offered && unavailable.commits == 0)
- print("PASS: recommendation prefetch, fresh/cached activation, prefetch cancellation/retry, duplicate actions, cancellation during download/load, stale progress, failure/retry and commit rejection")
+ print(
+ "PASS: recommendation prefetch, fresh/cached activation, prefetch cancellation/retry, duplicate actions, cancellation during download/load, stale progress, failure/retry and commit rejection"
+ )
}
}
diff --git a/Tests/OnboardingDictationOutputPolicyTests.swift b/Tests/OnboardingDictationOutputPolicyTests.swift
index ffc88f82..c6b7169d 100644
--- a/Tests/OnboardingDictationOutputPolicyTests.swift
+++ b/Tests/OnboardingDictationOutputPolicyTests.swift
@@ -5,7 +5,12 @@ struct OnboardingDictationOutputPolicyTests {
for active in [false, true] {
for dictation in [false, true] {
for target: Int32? in [nil, 100, 200] {
- let actual = OnboardingDictationOutputPolicy.usesSandbox(onboardingPracticeActive: active, isDictation: dictation, targetProcessID: target, fluidVoiceProcessID: 100)
+ let actual = OnboardingDictationOutputPolicy.usesSandbox(
+ onboardingPracticeActive: active,
+ isDictation: dictation,
+ targetProcessID: target,
+ fluidVoiceProcessID: 100
+ )
precondition(actual == (active && dictation && target != 200))
cases += 1
}
diff --git a/Tests/PasteKeyCodeCacheLiveLayoutTests.swift b/Tests/PasteKeyCodeCacheLiveLayoutTests.swift
index bd8abfbe..ab7adffd 100644
--- a/Tests/PasteKeyCodeCacheLiveLayoutTests.swift
+++ b/Tests/PasteKeyCodeCacheLiveLayoutTests.swift
@@ -31,7 +31,9 @@ enum PasteKeyCodeCacheLiveLayoutTests {
let restored = TISSelectInputSource(original)
RunLoop.current.run(until: Date().addingTimeInterval(0.2))
let disabled = wasEnabled ? noErr : TISDisableInputSource(dvorak)
- print("RESTORE selection=\(restored) removeTemporaryDvorak=\(disabled) current=\(value(TISCopyCurrentKeyboardInputSource().takeRetainedValue(), kTISPropertyInputSourceID))")
+ print(
+ "RESTORE selection=\(restored) removeTemporaryDvorak=\(disabled) current=\(value(TISCopyCurrentKeyboardInputSource().takeRetainedValue(), kTISPropertyInputSourceID))"
+ )
}
guard TISEnableInputSource(dvorak) == noErr else { throw NSError(domain: "Enable failed", code: 2) }
var refreshes = 0
@@ -51,7 +53,9 @@ enum PasteKeyCodeCacheLiveLayoutTests {
RunLoop.current.run(until: Date().addingTimeInterval(0.001))
}
guard cache.snapshot() == expected else { throw NSError(domain: "Stale cache", code: 4) }
- print("SWITCH \(self.value(source, kTISPropertyInputSourceID)) expected=\(expected) immediate=\(immediate) refreshed=\(cache.snapshot()) elapsedMs=\((ProcessInfo.processInfo.systemUptime - start) * 1000)")
+ print(
+ "SWITCH \(self.value(source, kTISPropertyInputSourceID)) expected=\(expected) immediate=\(immediate) refreshed=\(cache.snapshot()) elapsedMs=\((ProcessInfo.processInfo.systemUptime - start) * 1000)"
+ )
}
// Several changes without yielding the main run loop: the request must use
// the final layout, even if notifications are still queued or coalesced.
diff --git a/Tests/PrivateAIIdleUnloaderTests.swift b/Tests/PrivateAIIdleUnloaderTests.swift
index 5a22a033..cff56530 100644
--- a/Tests/PrivateAIIdleUnloaderTests.swift
+++ b/Tests/PrivateAIIdleUnloaderTests.swift
@@ -44,7 +44,7 @@ enum PrivateAIIdleUnloaderTests {
let recorder = Recorder()
await recorder.set(delayMs: 150)
let unloader = makeUnloader(recorder)
- for _ in 0 ..< 4 {
+ for _ in 0..<4 {
await unloader.tracking {}
await pause(60)
}
diff --git a/Tests/PrivateAISettingsBoundaryTests.swift b/Tests/PrivateAISettingsBoundaryTests.swift
index d2c086dc..8fe07d22 100644
--- a/Tests/PrivateAISettingsBoundaryTests.swift
+++ b/Tests/PrivateAISettingsBoundaryTests.swift
@@ -21,7 +21,9 @@ struct PrivateAISettingsBoundaryTests {
check(PrivateAIModelCarouselNavigation.position(of: "full", in: ["pico", "mini", "full"], current: "mini") == 1, "Three-model carousel places the next card right")
var session = PrivateAISettingsSession(selectedModelID: "mini")
let initialRevision = session.revision
- for id in ["pico", "mini", "pico"] { session.preview(id) }
+ for id in ["pico", "mini", "pico"] {
+ session.preview(id)
+ }
check(session.previewModelID == "pico", "Preview follows browsing")
check(session.selectedModelID == "mini", "Browsing must not activate")
check(session.revision == initialRevision, "Browsing must not invalidate active work")
@@ -142,7 +144,10 @@ struct PrivateAISettingsBoundaryTests {
let card = try String(contentsOfFile: "Sources/Fluid/UI/AISettings/FluidModelShowcaseCard.swift", encoding: .utf8)
check(!card.contains(".popover("), "Model information stays inside its card")
check(card.contains("Button { self.showsInfo.toggle() }"), "Information toggles only local presentation state")
- check(card.contains("self.reduceMotion ? nil") && card.contains("ZStack(alignment: .topLeading)"), "Inline information respects reduced motion and shares stable content bounds")
+ check(
+ card.contains("self.reduceMotion ? nil") && card.contains("ZStack(alignment: .topLeading)"),
+ "Inline information respects reduced motion and shares stable content bounds"
+ )
print("Passed \(checks) FI boundary/controller assertions")
}
}
diff --git a/Tests/PrivateAISettingsControllerDoubles.swift b/Tests/PrivateAISettingsControllerDoubles.swift
index c733feae..cdda2473 100644
--- a/Tests/PrivateAISettingsControllerDoubles.swift
+++ b/Tests/PrivateAISettingsControllerDoubles.swift
@@ -6,30 +6,36 @@ struct PrivateAIModelDownloadProgress: Equatable, Sendable {
init(initialExpectedBytes: Int?) {}
func withFallbackExpectedBytes(_ bytes: Int?) -> Self { self }
}
+
struct PrivateAIRegisteredModel: Sendable {
let id: String
var canDownload = true
var artifact: Artifact { Artifact() }
struct Artifact { var byteCount: Int? = 10 }
}
+
struct PrivateAIModelUpdateStatus {
enum State { case current, updateAvailable }
var state: State
}
+
struct PrivateAIModelUpdateToken: Sendable { let id = UUID() }
struct PrivateAIStatus { enum State { case ready, failed }; var state: State; var message: String? }
enum PrivateAIModelRegistry {
static let defaultModel = PrivateAIRegisteredModel(id: "mini")
static func model(id: String) -> PrivateAIRegisteredModel? {
- modelIDs().contains(id) ? PrivateAIRegisteredModel(id: id) : nil
+ self.modelIDs().contains(id) ? PrivateAIRegisteredModel(id: id) : nil
}
+
static func modelIDs() -> [String] { ["mini", "pico"] }
- static func canonicalModelID(for id: String) -> String? { model(id: id)?.id }
+ static func canonicalModelID(for id: String) -> String? { self.model(id: id)?.id }
}
+
struct PrivateAIProviderFeature { static let shared = Self(); let providerID = "fi" }
enum PrivateAIProviderPromptFormat {
static func verifiedModelID(settings: SettingsStore) -> String? { "mini" }
}
+
final class SettingsStore {
enum PrivateAIBackendPreference { case auto, mlx; var displayName: String { "test" } }
var privateAIBackendPreference: PrivateAIBackendPreference = .auto
@@ -40,13 +46,15 @@ final class SettingsStore {
var availableModelsByProvider = ["external": ["external-model"]]
static func clampPrivateAIContextTokenLimit(_ value: Int) -> Int { max(1, value) }
}
+
@MainActor
final class UserDefaults {
static let standard = UserDefaults()
var writes = 0
- func set(_ value: String, forKey key: String) { writes += 1 }
- func removeObject(forKey key: String) { writes += 1 }
+ func set(_ value: String, forKey key: String) { self.writes += 1 }
+ func removeObject(forKey key: String) { self.writes += 1 }
}
+
@MainActor
final class AIEnhancementSettingsViewModel {
enum ConnectionStatus { case success }
@@ -63,25 +71,28 @@ final class AIEnhancementSettingsViewModel {
var smartSelectionCount = 0
var smartSelected = false
func selectPrivateAIPromptIfAvailable() {
- guard verified else { return }
- smartSelectionCount += 1
- smartSelected = true
+ guard self.verified else { return }
+ self.smartSelectionCount += 1
+ self.smartSelected = true
}
+
func providerKey(for id: String) -> String { id }
func refreshProviderItems() {}
func connectionErrorMessage(for id: String) -> String { "test failure" }
- func resetVerification(for id: String) { resetCount += 1 }
+ func resetVerification(for id: String) { self.resetCount += 1 }
func updateConnectionStatus(_ status: ConnectionStatus, for id: String) {}
func verifyPrivateAIProvider(model: PrivateAIRegisteredModel) async -> Bool {
- verificationCount += 1
- return verified
+ self.verificationCount += 1
+ return self.verified
}
}
+
struct DebugLogger {
static let shared = Self()
func info(_ message: String, source: String) {}
func error(_ message: String, source: String) {}
}
+
@MainActor
final class PrivateAIIntegrationService {
struct LoadedModelState { var state: PrivateAIStatus.State; var modelID: String }
@@ -102,37 +113,41 @@ final class PrivateAIIntegrationService {
static var suspendRead = false
static var loadContinuation: CheckedContinuation<PrivateAIStatus, Never>?
static var suspendLoad = false
- static func isModelInstalled(_ model: PrivateAIRegisteredModel) -> Bool { installed }
- static func canRemoveInstalledModel(_ model: PrivateAIRegisteredModel) -> Bool { installed }
+ static func isModelInstalled(_ model: PrivateAIRegisteredModel) -> Bool { self.installed }
+ static func canRemoveInstalledModel(_ model: PrivateAIRegisteredModel) -> Bool { self.installed }
static func modelUpdateStatus(_ model: PrivateAIRegisteredModel) async -> PrivateAIModelUpdateStatus { .init(state: .current) }
static func prepareModel(
_ model: PrivateAIRegisteredModel,
progressHandler: (@Sendable (PrivateAIModelDownloadProgress) async -> Void)? = nil
) async throws -> URL {
- downloads += 1
- lastProgress = progressHandler
- if failDownload { throw PrivateAISettingsBoundaryTests.Failure.expected }
+ self.downloads += 1
+ self.lastProgress = progressHandler
+ if self.failDownload { throw PrivateAISettingsBoundaryTests.Failure.expected }
await progressHandler?(.init(initialExpectedBytes: 10))
- return modelDirectoryURL
+ return self.modelDirectoryURL
}
+
static func updateModel(
_ model: PrivateAIRegisteredModel,
progressHandler: (@Sendable (PrivateAIModelDownloadProgress) async -> Void)? = nil
) async throws -> PrivateAIModelUpdateToken {
- _ = try await prepareModel(model, progressHandler: progressHandler)
+ _ = try await self.prepareModel(model, progressHandler: progressHandler)
return .init()
}
- static func commitModelUpdate(_ token: PrivateAIModelUpdateToken) async { commits += 1 }
- static func rollbackModelUpdate(_ token: PrivateAIModelUpdateToken) async { rollbacks += 1 }
+
+ static func commitModelUpdate(_ token: PrivateAIModelUpdateToken) async { self.commits += 1 }
+ static func rollbackModelUpdate(_ token: PrivateAIModelUpdateToken) async { self.rollbacks += 1 }
func loadedModelState() async -> LoadedModelState? {
if Self.suspendRead { return await withCheckedContinuation { Self.readContinuation = $0 } }
return nil
}
+
func loadModel(_ model: PrivateAIRegisteredModel) async throws -> PrivateAIStatus {
Self.loads += 1
if Self.suspendLoad { return await withCheckedContinuation { Self.loadContinuation = $0 } }
return .init(state: .ready)
}
+
func unloadCachedRuntime(reason: String) async {}
func unloadAndRemoveInstalledModel(_ model: PrivateAIRegisteredModel, reason: String) async throws { Self.removals += 1 }
}
@@ -140,7 +155,7 @@ final class PrivateAIIntegrationService {
@MainActor
enum PrivateAIControllerChecks {
static func eventually(_ predicate: () -> Bool) async {
- for _ in 0..<10000 {
+ for _ in 0..<10_000 {
if predicate() { return }
await Task.yield()
}
@@ -150,7 +165,9 @@ enum PrivateAIControllerChecks {
static func run(check: (Bool, String) -> Void) async {
let vm = AIEnhancementSettingsViewModel()
let controller = PrivateAISettingsController(viewModel: vm)
- for _ in 0..<50 { controller.previewModel("pico"); controller.previewModel("mini") }
+ for _ in 0..<50 {
+ controller.previewModel("pico"); controller.previewModel("mini")
+ }
controller.previewModel("pico")
controller.previewModel("invalid")
check(controller.previewModelID == "pico" && controller.privateAISelectedModelID == "mini", "Controller preview remains separate and rejects invalid IDs")
@@ -163,7 +180,7 @@ enum PrivateAIControllerChecks {
let writesBeforeCardRead = UserDefaults.standard.writes
controller.refreshPrivateAIModelUpdateStatus(PrivateAIRegisteredModel(id: "mini"))
- await eventually { controller.privateAIModelUpdateStatusByID["mini"] != nil }
+ await self.eventually { controller.privateAIModelUpdateStatusByID["mini"] != nil }
check(controller.privateAIModelUpdateStatusByID["mini"]?.state == .current, "Inactive card receives its own update status")
check(controller.privateAISelectedModelID == "pico" && UserDefaults.standard.writes == writesBeforeCardRead, "Card update read never selects or persists another model")
let verificationBeforeInactiveAction = vm.verificationCount
@@ -176,12 +193,12 @@ enum PrivateAIControllerChecks {
controller.downloadPrivateAIModel(pico)
controller.persistPrivateAIModelSelection("mini")
check(controller.isBusy && controller.privateAISelectedModelID == "pico", "Busy controller rejects duplicate action/model switching")
- await eventually { !controller.isBusy }
+ await self.eventually { !controller.isBusy }
check(PrivateAIIntegrationService.downloads == 1 && vm.verificationCount == 0, "Failed download never verifies and only starts once")
check(controller.privateAILoadState.failureMessage(for: "pico") != nil, "Failure is visible and releases busy state")
PrivateAIIntegrationService.failDownload = false
controller.downloadPrivateAIModel(pico)
- await eventually { !controller.isBusy }
+ await self.eventually { !controller.isBusy }
check(controller.privateAILoadState.isLoaded("pico") && vm.verificationCount == 1, "Download retry verifies and completes")
await PrivateAIIntegrationService.lastProgress?(.init(initialExpectedBytes: 10))
check(controller.privateAILoadState.isLoaded("pico"), "Late progress from finished download cannot replace ready state")
@@ -189,10 +206,13 @@ enum PrivateAIControllerChecks {
controller.privateAIModelUpdateStatusByID["pico"] = .init(state: .updateAvailable)
vm.verified = false
controller.updatePrivateAIModel(pico)
- await eventually { !controller.isBusy }
+ await self.eventually { !controller.isBusy }
check(PrivateAIIntegrationService.rollbacks == 1 && PrivateAIIntegrationService.commits == 0, "Real controller update path rolls back failed verification")
check(controller.privateAILoadState.failureMessage(for: "pico") != nil, "Update verification failure remains visible")
- check(controller.privateAILoadState.failureMessage(for: "pico")?.contains("test failure") == true, "Update error includes provider-specific detail, not literal interpolation")
+ check(
+ controller.privateAILoadState.failureMessage(for: "pico")?.contains("test failure") == true,
+ "Update error includes provider-specific detail, not literal interpolation"
+ )
let writesBeforeNoop = UserDefaults.standard.writes
let previewBeforeUpcoming = controller.previewModelID
@@ -202,7 +222,10 @@ enum PrivateAIControllerChecks {
controller.persistPrivateAIModelSelection(upcoming.id)
check(PrivateAIModelRegistry.model(id: upcoming.id) == nil, "Coming-soon previews are not runtime models")
}
- check(controller.previewModelID == previewBeforeUpcoming && controller.privateAISelectedModelID == selectionBeforeUpcoming, "Coming-soon identifiers cannot alter runtime selection")
+ check(
+ controller.previewModelID == previewBeforeUpcoming && controller.privateAISelectedModelID == selectionBeforeUpcoming,
+ "Coming-soon identifiers cannot alter runtime selection"
+ )
check(UserDefaults.standard.writes == writesBeforeNoop, "Coming-soon identifiers never persist")
controller.persistPrivateAIModelSelection("invalid")
controller.persistPrivateAIModelSelection("pico")
@@ -217,7 +240,7 @@ enum PrivateAIControllerChecks {
let writesBeforeDeletion = UserDefaults.standard.writes
controller.deletePrivateAIModel(pico)
controller.deletePrivateAIModel(pico)
- await eventually { !controller.isBusy }
+ await self.eventually { !controller.isBusy }
check(PrivateAIIntegrationService.removals == 1 && controller.privateAILoadState == .idle, "Confirmed deletion runs once and returns to idle")
check(UserDefaults.standard.writes == writesBeforeDeletion && vm.selectedProviderID == "external", "Deletion does not change model selection or shortcut provider")
PrivateAIIntegrationService.installed = false
@@ -225,34 +248,38 @@ enum PrivateAIControllerChecks {
PrivateAIIntegrationService.suspendRead = true
controller.privateAILoadState = .idle
controller.refreshPrivateAILoadState()
- await eventually { PrivateAIIntegrationService.readContinuation != nil }
+ await self.eventually { PrivateAIIntegrationService.readContinuation != nil }
PrivateAIIntegrationService.installed = true
PrivateAIIntegrationService.suspendLoad = true
controller.loadPrivateAIModel(pico)
- await eventually { PrivateAIIntegrationService.loadContinuation != nil }
+ await self.eventually { PrivateAIIntegrationService.loadContinuation != nil }
PrivateAIIntegrationService.readContinuation?.resume(returning: nil)
PrivateAIIntegrationService.readContinuation = nil
- for _ in 0..<20 { await Task.yield() }
+ for _ in 0..<20 {
+ await Task.yield()
+ }
check(controller.privateAILoadState.isLoading("pico") && controller.isBusy, "Late idle read cannot erase a newer load")
controller.previewModel("mini")
controller.activatePreviewModel()
check(controller.privateAISelectedModelID == "pico" && controller.previewModelID == "mini", "Pending load permits preview but not activation")
PrivateAIIntegrationService.loadContinuation?.resume(returning: .init(state: .ready))
PrivateAIIntegrationService.loadContinuation = nil
- await eventually { !controller.isBusy }
+ await self.eventually { !controller.isBusy }
check(controller.privateAILoadState.isLoaded("pico"), "Load completion stays attached to activated model, not preview")
var activations = 0
vm.verified = false
controller.usePreviewModel(isInstalled: true) { activations += 1 }
controller.usePreviewModel(isInstalled: true) { activations += 1 }
- await eventually { !controller.isBusy }
+ await self.eventually { !controller.isBusy }
check(activations == 0 && vm.smartSelectionCount == 0, "Failed activation must not switch shortcut routing")
controller.refreshPrivateAILoadState()
- for _ in 0..<20 { await Task.yield() }
+ for _ in 0..<20 {
+ await Task.yield()
+ }
check(controller.privateAILoadState.failureMessage(for: "mini") != nil, "Passive runtime refresh preserves failed activation")
vm.verified = true
controller.usePreviewModel(isInstalled: true) { activations += 1 }
- await eventually { !controller.isBusy }
+ await self.eventually { !controller.isBusy }
check(activations == 1 && controller.privateAILoadState.isLoaded("mini"), "Explicit activation calls routing once after successful verification")
check(vm.smartSelected && vm.smartSelectionCount == 1, "Successful explicit activation selects Smart once")
check(vm.selectedProviderID == "external" && vm.selectedModel == "external-model", "Activation preserves external editor configuration")
@@ -267,7 +294,7 @@ enum PrivateAIControllerChecks {
reportedError = error
})
controller.verifyPrivateAIConnection(.init(id: "mini"), onCompletion: { _ in completionCount += 100 })
- await eventually { !controller.isBusy }
+ await self.eventually { !controller.isBusy }
check(completionCount == 1 && reportedError == nil, "Manual verification reports success once; duplicate clicks do not report")
check(!vm.smartSelected && vm.smartSelectionCount == 1, "Verification preserves manually selected Basic")
vm.verified = false
@@ -275,13 +302,13 @@ enum PrivateAIControllerChecks {
completionCount += 1
reportedError = error
})
- await eventually { !controller.isBusy }
+ await self.eventually { !controller.isBusy }
check(completionCount == 2 && reportedError?.contains("test failure") == true, "Manual verification reports the actual failure")
controller.verifyPrivateAIConnection(.init(id: "pico"), onCompletion: { _ in completionCount += 100 })
check(completionCount == 2 && UserDefaults.standard.writes == writesBeforeVerification, "Inactive verification has no result or persistence side effects")
vm.verified = true
controller.usePreviewModel(isInstalled: true) {}
- await eventually { !controller.isBusy }
+ await self.eventually { !controller.isBusy }
check(vm.smartSelected && vm.smartSelectionCount == 2, "Another explicit activation switches Basic back to Smart")
}
}
diff --git a/Tests/ProviderSetupBoundaryTests.swift b/Tests/ProviderSetupBoundaryTests.swift
index 34d52767..97e34a79 100644
--- a/Tests/ProviderSetupBoundaryTests.swift
+++ b/Tests/ProviderSetupBoundaryTests.swift
@@ -6,18 +6,21 @@ final class UserDefaults {
var values: [String: [String]] = [:]
// Match Foundation UserDefaults, including an absent key.
// swiftlint:disable:next discouraged_optional_collection
- func stringArray(forKey key: String) -> [String]? { values[key] }
- func set(_ value: [String], forKey key: String) { values[key] = value }
+ func stringArray(forKey key: String) -> [String]? { self.values[key] }
+ func set(_ value: [String], forKey key: String) { self.values[key] = value }
}
+
struct PrivateAIProviderFeature {
static let shared = PrivateAIProviderFeature()
let providerID = "fluid"
}
+
struct ModelRepository {
static let shared = ModelRepository()
func isBuiltIn(_ id: String) -> Bool { ["openai", "ollama", "fluid"].contains(id) }
func defaultModels(for id: String) -> [String] { ["default-model"] }
}
+
final class SettingsStore {
struct SavedProvider {
var id = UUID().uuidString
@@ -25,11 +28,13 @@ final class SettingsStore {
let baseURL: String
let models: [String]
}
+
struct Configuration: Equatable {
var providerID: String
var modelName = "model"
var shortcut = "keep-shortcut"
}
+
var selectedProviderID = "fluid"
var selectedModel: String? = "mini"
var rewriteModeSelectedProviderID = ""
@@ -41,12 +46,14 @@ final class SettingsStore {
var dictationPromptConfigurations: [String: Configuration] = [:]
var verifiedProviderFingerprints: [String: String] = [:]
}
+
final class AIEnhancementSettingsViewModel {
struct ProviderItemData {
let id: String
let name: String
let isBuiltIn: Bool
}
+
let settings = SettingsStore()
var isTestingConnection = false
var isFetchingModels = false
@@ -63,25 +70,29 @@ final class AIEnhancementSettingsViewModel {
var keySaves = 0
var persistedKeys: [String: String] = [:]
func providerKey(for id: String) -> String { id }
- func providerAPIKey(for id: String) -> String { providerAPIKeys[id] ?? "" }
- func updateProviderAPIKey(_ value: String, for id: String) { providerAPIKeys[id] = value }
+ func providerAPIKey(for id: String) -> String { self.providerAPIKeys[id] ?? "" }
+ func updateProviderAPIKey(_ value: String, for id: String) { self.providerAPIKeys[id] = value }
func saveProviderAPIKeys(invalidating id: String) -> Bool {
- keySaves += 1
- guard !failKeychain else { return false }
- persistedKeys = providerAPIKeys
+ self.keySaves += 1
+ guard !self.failKeychain else { return false }
+ self.persistedKeys = self.providerAPIKeys
return true
}
- func hasProviderAPIKeyDraft(for id: String) -> Bool { providerAPIKeys[id] != nil }
+
+ func hasProviderAPIKeyDraft(for id: String) -> Bool { self.providerAPIKeys[id] != nil }
func refreshProviderItems() {
- let items = [ProviderItemData(id: "openai", name: "OpenAI", isBuiltIn: true),
- ProviderItemData(id: "ollama", name: "Ollama", isBuiltIn: true),
- ProviderItemData(id: "fluid", name: "Fluid", isBuiltIn: true)]
- + savedProviders.map { ProviderItemData(id: $0.id, name: $0.name, isBuiltIn: false) }
- cachedAddedProviderItems = addedProviderItems(from: items)
+ let items = [
+ ProviderItemData(id: "openai", name: "OpenAI", isBuiltIn: true),
+ ProviderItemData(id: "ollama", name: "Ollama", isBuiltIn: true),
+ ProviderItemData(id: "fluid", name: "Fluid", isBuiltIn: true),
+ ]
+ + self.savedProviders.map { ProviderItemData(id: $0.id, name: $0.name, isBuiltIn: false) }
+ self.cachedAddedProviderItems = addedProviderItems(from: items)
}
- func saveSavedProviders() { saves += 1; refreshProviderItems() }
+
+ func saveSavedProviders() { self.saves += 1; self.refreshProviderItems() }
func clearEditProviderDraft() {}
- func finishConfiguringProvider() { selectedProviderID = settings.selectedProviderID }
+ func finishConfiguringProvider() { self.selectedProviderID = self.settings.selectedProviderID }
func refreshVerifiedProviders() {}
func selectSoleVerifiedProviderIfNeeded() {}
}
@@ -105,8 +116,10 @@ final class AIEnhancementSettingsViewModel {
draft.baseURL = "http://localhost:1234/v1"
draft.apiKey = "test-key"
vm.failKeychain = true
- check(!vm.addProvider(draft) && vm.savedProviders.isEmpty && vm.providerAPIKeys.isEmpty && vm.saves == 0,
- "Keychain failure keeps records, keys, and model maps unchanged")
+ check(
+ !vm.addProvider(draft) && vm.savedProviders.isEmpty && vm.providerAPIKeys.isEmpty && vm.saves == 0,
+ "Keychain failure keeps records, keys, and model maps unchanged"
+ )
vm.failKeychain = false
check(vm.addProvider(draft) && vm.savedProviders.count == 1, "Explicit Add saves a custom provider")
check(vm.settings.selectedProviderID == "fluid" && vm.selectedModelByProvider["fluid"] == "mini", "Adding does not change current route/model")
@@ -134,8 +147,10 @@ final class AIEnhancementSettingsViewModel {
check(source.contains("if isCustom || managementLayout"), "Built-in management exposes removal")
let makeDefault = source.components(separatedBy: "private func makePrimaryDefaultProvider")[1]
.components(separatedBy: "private func modelBinding")[0]
- check(makeDefault.contains("saveManagedProviderAPIKeyIfNeeded") && !makeDefault.contains("saveProviderAPIKeys"),
- "Making a provider default only persists an active credential edit")
+ check(
+ makeDefault.contains("saveManagedProviderAPIKeyIfNeeded") && !makeDefault.contains("saveProviderAPIKeys"),
+ "Making a provider default only persists an active credential edit"
+ )
let removal = AIEnhancementSettingsViewModel()
removal.providerAPIKeys = ["openai": "remove-key", "other": "keep-key"]
removal.settings.dictationPromptConfigurations = [
@@ -172,7 +187,10 @@ final class AIEnhancementSettingsViewModel {
removal.settings.selectedProviderID = "ollama"
let keySavesBeforeKeylessRemoval = removal.keySaves
removal.failKeychain = true
- check(removal.deleteCurrentProvider() && removal.settings.selectedProviderID.isEmpty && removal.settings.selectedModel == nil, "Removing the default clears its model without selecting another provider")
+ check(
+ removal.deleteCurrentProvider() && removal.settings.selectedProviderID.isEmpty && removal.settings.selectedModel == nil,
+ "Removing the default clears its model without selecting another provider"
+ )
check(removal.keySaves == keySavesBeforeKeylessRemoval, "Removing a keyless provider does not require a Keychain write")
removal.selectedProviderID = "fluid"
check(!removal.deleteCurrentProvider(), "External provider removal cannot remove private AI")
@@ -186,7 +204,10 @@ final class AIEnhancementSettingsViewModel {
check(!closing.saveManagedProviderBeforeClosing("openai"), "Keychain failure keeps Manage open")
check(closing.providerAPIKeys["openai"] == "edited-key" && closing.settings.selectedProviderID == "fluid", "Failed close preserves the draft and default")
closing.failKeychain = false
- check(closing.saveManagedProviderBeforeClosing("openai") && closing.persistedKeys["openai"] == "edited-key", "Done persists an edited key without verification or model refresh")
+ check(
+ closing.saveManagedProviderBeforeClosing("openai") && closing.persistedKeys["openai"] == "edited-key",
+ "Done persists an edited key without verification or model refresh"
+ )
let savedCount = closing.keySaves
closing.selectedProviderID = "fluid"
check(closing.saveManagedProviderBeforeClosing("openai") && closing.keySaves == savedCount, "Removal cleanup must not save a different selected provider")
diff --git a/Tests/Standalone/DictionaryCorrectionDetectorTests.swift b/Tests/Standalone/DictionaryCorrectionDetectorTests.swift
index b21b4b29..f80a5bf9 100644
--- a/Tests/Standalone/DictionaryCorrectionDetectorTests.swift
+++ b/Tests/Standalone/DictionaryCorrectionDetectorTests.swift
@@ -47,7 +47,10 @@ struct DictionaryNegativeCorrection {}
let punctuated = self.candidate("I met Barat.", "I met Barath.")
self.expect(punctuated?.heardText == "Barat" && punctuated?.correctedText == "Barath", "Sentence punctuation")
let before = "Title: I met Barat"
- self.expect(AutomaticDictionaryCorrectionDetector.candidate(before: before, after: "Heading: I met Barat", insertedRange: (before as NSString).range(of: "I met Barat")) == nil, "Outside insertion")
+ self.expect(
+ AutomaticDictionaryCorrectionDetector.candidate(before: before, after: "Heading: I met Barat", insertedRange: (before as NSString).range(of: "I met Barat")) == nil,
+ "Outside insertion"
+ )
// Evaluate the accumulated edit, as the observer does after rapid keystrokes.
for intermediate in ["better t", "better to", "better too", "better tool", "better tools"] {
self.expect(self.candidate("I use tools", "I use " + intermediate) == nil, "Typed phrase never becomes a word correction")
diff --git a/Tests/Standalone/DictionaryMatcherExperimentTests.swift b/Tests/Standalone/DictionaryMatcherExperimentTests.swift
index d83a52ea..8f2df7a0 100644
--- a/Tests/Standalone/DictionaryMatcherExperimentTests.swift
+++ b/Tests/Standalone/DictionaryMatcherExperimentTests.swift
@@ -15,10 +15,20 @@ enum PronunciationDictionaryStoreError: Error { case inconsistentEnrollment, sta
}
static func main() async throws {
- let keys = ["DictionarySharedFeatureMatcherEnabled", "DictionaryTemporalMatcherEnabled", "DictionaryNegativeLearningEnabled", "DictionaryNegativeComparisonEnabled", "DictionaryPronunciationGeneration"]
+ let keys = [
+ "DictionarySharedFeatureMatcherEnabled",
+ "DictionaryTemporalMatcherEnabled",
+ "DictionaryNegativeLearningEnabled",
+ "DictionaryNegativeComparisonEnabled",
+ "DictionaryPronunciationGeneration",
+ ]
let savedPreferences = keys.map { UserDefaults.standard.object(forKey: $0) }
- defer { for (key, value) in zip(keys, savedPreferences) { UserDefaults.standard.set(value, forKey: key) } }
- for key in keys { UserDefaults.standard.set(true, forKey: key) }
+ defer { for (key, value) in zip(keys, savedPreferences) {
+ UserDefaults.standard.set(value, forKey: key)
+ } }
+ for key in keys {
+ UserDefaults.standard.set(true, forKey: key)
+ }
UserDefaults.standard.set(false, forKey: keys[0])
self.expect(!DictionaryMatcherExperiment.positiveEnabled && !DictionaryMatcherExperiment.needsFrames, "Off overrides legacy matching preferences")
self.expect(!DictionaryMatcherExperiment.collectNegatives && !DictionaryMatcherExperiment.compareNegatives, "Off disables negative audio learning and comparisons")
@@ -38,12 +48,12 @@ enum PronunciationDictionaryStoreError: Error { case inconsistentEnrollment, sta
let sharedDecision = await DictionaryExperimentalMatcher.compareSharedFeatures(query: contextual, references: refs)
self.expect(sharedDecision?.accepted == true, "Shared sentence features use their calibrated operating point")
self.expect(DictionaryExperimentalMatcher.positive(query: contextual, references: refs)?.accepted == false, "Shared thresholds must not loosen isolated-query scoring")
- let weakContext = DictionaryMatchFrames(hiddenSize: 2, values: [0.58, 0.814616, 0.58, 0.814616, 0.58, 0.814616])
+ let weakContext = DictionaryMatchFrames(hiddenSize: 2, values: [0.58, 0.814_616, 0.58, 0.814_616, 0.58, 0.814_616])
let weakShared = await DictionaryExperimentalMatcher.compareSharedFeatures(query: weakContext, references: refs)
self.expect(weakShared?.accepted == false, "Shared matching still rejects weak overall similarity")
let missingShared = await DictionaryExperimentalMatcher.compareSharedFeatures(query: contextual, references: [positive])
self.expect(missingShared == nil, "Missing reference features must not accept a candidate")
- let contextualChunk = DictionaryMatchFrames(hiddenSize: 2, values: [0.56, 0.828493, 0.56, 0.828493, 0.56, 0.828493])
+ let contextualChunk = DictionaryMatchFrames(hiddenSize: 2, values: [0.56, 0.828_493, 0.56, 0.828_493, 0.56, 0.828_493])
let chunkDecision = await DictionaryExperimentalMatcher.compareSharedFeatures(query: contextualChunk, references: refs, chunked: true)
let shortDecision = await DictionaryExperimentalMatcher.compareSharedFeatures(query: contextualChunk, references: refs)
self.expect(chunkDecision?.accepted == true && shortDecision?.accepted == false, "Long-window calibration must not loosen the short-recording operating point")
@@ -58,30 +68,84 @@ enum PronunciationDictionaryStoreError: Error { case inconsistentEnrollment, sta
self.expect(!DictionaryExperimentalMatcher.negativeAllows(query: negative, references: refs, negatives: [negative]), "Close negative with margin vetoes")
self.expect(DictionaryExperimentalMatcher.negativeAllows(query: positive, references: refs, negatives: [negative]), "Unrelated negative is inert")
let now = Date(), entry = UUID()
- let evidence = DictionaryAcousticEvidence(id: UUID(), entryID: entry, label: "Manimekalai", profileKey: "profile", modelKey: "parakeet-v2", sourceWordRange: 1..<2, frames: positive)
+ let evidence = DictionaryAcousticEvidence(
+ id: UUID(),
+ entryID: entry,
+ label: "Manimekalai",
+ profileKey: "profile",
+ modelKey: "parakeet-v2",
+ sourceWordRange: 1..<2,
+ frames: positive
+ )
// nil selects the default evidence; an empty array tests missing evidence.
- // swiftlint:disable:next discouraged_optional_collection
- func context(_ text: String = "Hello Manimekalai today", events: [DictionaryAcousticEvidence]? = nil, date: Date? = nil, selected: String = "Manimekalai") -> DictionaryLearningCorrectionContext {
- let alignment = DictionaryLearningAlignment(modelKey: "parakeet-v2", words: [.init(text: "raw", start: 0, end: 1)], acousticOutput: text, acousticEvidence: events ?? [evidence])
- guard let recording = DictionaryLearningRecording(alignment: alignment, samples: [0.1, 0.1], now: date ?? now) else { preconditionFailure("Missing fixture: recording") }
+ func context(
+ _ text: String = "Hello Manimekalai today",
+ // nil requests the fixture default; an empty collection tests explicitly missing data.
+ // swiftlint:disable:next discouraged_optional_collection
+ events: [DictionaryAcousticEvidence]? = nil,
+ date: Date? = nil,
+ selected: String = "Manimekalai"
+ ) -> DictionaryLearningCorrectionContext {
+ let alignment = DictionaryLearningAlignment(
+ modelKey: "parakeet-v2",
+ words: [.init(text: "raw", start: 0, end: 1)],
+ acousticOutput: text,
+ acousticEvidence: events ?? [evidence]
+ )
+ guard let recording = DictionaryLearningRecording(alignment: alignment, samples: [0.1, 0.1], now: date ?? now)
+ else { preconditionFailure("Missing fixture: recording") }
return .init(recording: recording, deliveredTextBeforeEdit: text, selectedUTF16Range: (text as NSString).range(of: selected))
}
- guard let correction = DictionaryNegativeEvidenceResolver.resolve(context: context(), heard: "Manimekalai", corrected: "another", now: now) else { preconditionFailure("Missing fixture: correction") }
+ guard let correction = DictionaryNegativeEvidenceResolver.resolve(context: context(), heard: "Manimekalai", corrected: "another", now: now)
+ else { preconditionFailure("Missing fixture: correction") }
self.expect(correction.evidence.id == evidence.id, "Keep exact accepted occurrence")
- self.expect(DictionaryNegativeEvidenceResolver.resolve(context: context(), heard: "Manimekalai", corrected: "better Manimekalai", now: now) == nil, "Added words never become negatives")
- self.expect(DictionaryNegativeEvidenceResolver.resolve(context: context(), heard: "Manimekalai", corrected: "Manimekalais", now: now) == nil, "Plural edits never become negatives")
- guard let featureOnly = DictionaryLearningRecording(alignment: context().recording.alignment, samples: [0.1], retainAudio: false, now: now) else { preconditionFailure("Missing fixture: featureOnly") }
+ self.expect(
+ DictionaryNegativeEvidenceResolver.resolve(context: context(), heard: "Manimekalai", corrected: "better Manimekalai", now: now) == nil,
+ "Added words never become negatives"
+ )
+ self.expect(
+ DictionaryNegativeEvidenceResolver.resolve(context: context(), heard: "Manimekalai", corrected: "Manimekalais", now: now) == nil,
+ "Plural edits never become negatives"
+ )
+ guard let featureOnly = DictionaryLearningRecording(alignment: context().recording.alignment, samples: [0.1], retainAudio: false, now: now)
+ else { preconditionFailure("Missing fixture: featureOnly") }
self.expect(featureOnly.samples.isEmpty && featureOnly.alignment.acousticEvidence.count == 1, "Negative-only observation does not retain full PCM")
let punctuated = context("Hello Manimekalai.")
- let punctuationContext = DictionaryLearningCorrectionContext(recording: punctuated.recording, deliveredTextBeforeEdit: punctuated.deliveredTextBeforeEdit, selectedUTF16Range: NSRange(location: 6, length: 12))
- self.expect(DictionaryNegativeEvidenceResolver.resolve(context: punctuationContext, heard: "Manimekalai", corrected: "another", now: now) != nil, "Sentence punctuation still maps to the exact occurrence")
- self.expect(DictionaryNegativeEvidenceResolver.resolve(context: context(), heard: "Manimekalai", corrected: "MANIMEKALAI!", now: now) == nil, "Case and punctuation are not negative examples")
+ let punctuationContext = DictionaryLearningCorrectionContext(
+ recording: punctuated.recording,
+ deliveredTextBeforeEdit: punctuated.deliveredTextBeforeEdit,
+ selectedUTF16Range: NSRange(location: 6, length: 12)
+ )
+ self.expect(
+ DictionaryNegativeEvidenceResolver.resolve(context: punctuationContext, heard: "Manimekalai", corrected: "another", now: now) != nil,
+ "Sentence punctuation still maps to the exact occurrence"
+ )
+ self.expect(
+ DictionaryNegativeEvidenceResolver.resolve(context: context(), heard: "Manimekalai", corrected: "MANIMEKALAI!", now: now) == nil,
+ "Case and punctuation are not negative examples"
+ )
self.expect(DictionaryNegativeEvidenceResolver.resolve(context: context(), heard: "Manimekalai", corrected: "", now: now) == nil, "Deletion is ambiguous")
- self.expect(DictionaryNegativeEvidenceResolver.resolve(context: context(events: []), heard: "Manimekalai", corrected: "other", now: now) == nil, "No acoustic acceptance means no negative")
- self.expect(DictionaryNegativeEvidenceResolver.resolve(context: context("Manimekalai and Manimekalai"), heard: "Manimekalai", corrected: "other", now: now) == nil, "Repeated names are ambiguous")
- self.expect(DictionaryNegativeEvidenceResolver.resolve(context: context(selected: "Mani"), heard: "Mani", corrected: "other", now: now) == nil, "Partial label edit is ambiguous")
- self.expect(DictionaryNegativeEvidenceResolver.resolve(context: context(date: now.addingTimeInterval(-121)), heard: "Manimekalai", corrected: "other", now: now) == nil, "Expired recording rejected")
- let changed = DictionaryLearningCorrectionContext(recording: context().recording, deliveredTextBeforeEdit: "Hello Manimekalai tomorrow", selectedUTF16Range: NSRange(location: 6, length: 11))
+ self.expect(
+ DictionaryNegativeEvidenceResolver.resolve(context: context(events: []), heard: "Manimekalai", corrected: "other", now: now) == nil,
+ "No acoustic acceptance means no negative"
+ )
+ self.expect(
+ DictionaryNegativeEvidenceResolver.resolve(context: context("Manimekalai and Manimekalai"), heard: "Manimekalai", corrected: "other", now: now) == nil,
+ "Repeated names are ambiguous"
+ )
+ self.expect(
+ DictionaryNegativeEvidenceResolver.resolve(context: context(selected: "Mani"), heard: "Mani", corrected: "other", now: now) == nil,
+ "Partial label edit is ambiguous"
+ )
+ self.expect(
+ DictionaryNegativeEvidenceResolver.resolve(context: context(date: now.addingTimeInterval(-121)), heard: "Manimekalai", corrected: "other", now: now) == nil,
+ "Expired recording rejected"
+ )
+ let changed = DictionaryLearningCorrectionContext(
+ recording: context().recording,
+ deliveredTextBeforeEdit: "Hello Manimekalai tomorrow",
+ selectedUTF16Range: NSRange(location: 6, length: 11)
+ )
self.expect(DictionaryNegativeEvidenceResolver.resolve(context: changed, heard: "Manimekalai", corrected: "other", now: now) == nil, "AI rewriting invalidates mapping")
let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
@@ -98,13 +162,29 @@ enum PronunciationDictionaryStoreError: Error { case inconsistentEnrollment, sta
let retrained = await store.frames(entryID: entry, profileKey: "changed", modelKey: "parakeet-v2")
self.expect(retrained.isEmpty, "Retraining invalidates old negatives")
for _ in 0..<10 {
- let e = DictionaryAcousticEvidence(id: UUID(), entryID: entry, label: evidence.label, profileKey: "profile", modelKey: evidence.modelKey, sourceWordRange: 1..<2, frames: positive)
+ let e = DictionaryAcousticEvidence(
+ id: UUID(),
+ entryID: entry,
+ label: evidence.label,
+ profileKey: "profile",
+ modelKey: evidence.modelKey,
+ sourceWordRange: 1..<2,
+ frames: positive
+ )
try await store.save(.init(evidence: e, correctedText: "other", expiresAt: now.addingTimeInterval(120)), expectedRevision: revision)
}
let bounded = await store.frames(entryID: entry, profileKey: "profile", modelKey: "parakeet-v2")
self.expect(bounded.count == 6, "Per-word bank bounded")
for _ in 0..<40 {
- let e = DictionaryAcousticEvidence(id: UUID(), entryID: UUID(), label: evidence.label, profileKey: "profile", modelKey: evidence.modelKey, sourceWordRange: 1..<2, frames: positive)
+ let e = DictionaryAcousticEvidence(
+ id: UUID(),
+ entryID: UUID(),
+ label: evidence.label,
+ profileKey: "profile",
+ modelKey: evidence.modelKey,
+ sourceWordRange: 1..<2,
+ frames: positive
+ )
try await store.save(.init(evidence: e, correctedText: "other", expiresAt: now.addingTimeInterval(120)), expectedRevision: revision)
}
let persisted = try PropertyListDecoder().decode([DictionaryNegativeExampleStore.Example].self, from: Data(contentsOf: url))
@@ -137,7 +217,8 @@ enum PronunciationDictionaryStoreError: Error { case inconsistentEnrollment, sta
let expected = Dictionary(uniqueKeysWithValues: report.decisions.map { ($0.id, $0) })
for q in input.queries {
let refs = input.enrollments.filter { $0.word == q.word }.map { DictionaryMatchFrames(hiddenSize: 1024, values: $0.values) }
- guard let d = DictionaryExperimentalMatcher.positive(query: .init(hiddenSize: 1024, values: q.values), references: refs) else { preconditionFailure("Missing fixture: d") }
+ guard let d = DictionaryExperimentalMatcher.positive(query: .init(hiddenSize: 1024, values: q.values), references: refs)
+ else { preconditionFailure("Missing fixture: d") }
guard let e = expected[q.id] else { preconditionFailure("Missing fixture: e") }
self.expect(d.accepted == e.combinedAccepted, "Production scorer parity \(q.id)")
self.expect(abs(d.meanRelative - e.meanRelative) < 0.00_001 && abs(d.lowerRelative - e.lowerRelative) < 0.00_001, "Production score tolerance \(q.id)")
diff --git a/Tests/StatsSnapshotTests.swift b/Tests/StatsSnapshotTests.swift
index f4d4e8ad..91004b10 100644
--- a/Tests/StatsSnapshotTests.swift
+++ b/Tests/StatsSnapshotTests.swift
@@ -52,7 +52,11 @@ struct StatsSnapshotTests {
precondition(stale.currentStreak == 0 && stale.weekdayCurrentStreak == 0 && stale.bestStreak == 2)
let weekend = try StatsSnapshot.build(entries: [entry(3, text: "x"), entry(4, text: "x"), entry(6, text: "x")], now: date(6), calendar: calendar)
precondition(weekend.weekdayCurrentStreak == 2 && weekend.weekdayBestStreak == 2)
- let dst = try StatsSnapshot.build(entries: [entry(7, text: "a", month: 3), entry(8, text: "b", month: 3), entry(9, text: "c", month: 3)], now: date(9, month: 3), calendar: calendar)
+ let dst = try StatsSnapshot.build(
+ entries: [entry(7, text: "a", month: 3), entry(8, text: "b", month: 3), entry(9, text: "c", month: 3)],
+ now: date(9, month: 3),
+ calendar: calendar
+ )
precondition(dst.currentStreak == 3 && dst.bestStreak == 3, "Streaks must use calendar days across DST")
let large = Array(repeating: entry(7, text: String(repeating: "word ", count: 100)), count: 9000)
let start = Date()
diff --git a/scripts/trace_clipboard.swift b/scripts/trace_clipboard.swift
index d6b6eecc..7559767a 100644
--- a/scripts/trace_clipboard.swift
+++ b/scripts/trace_clipboard.swift
@@ -38,7 +38,8 @@ while ProcessInfo.processInfo.systemUptime < deadline {
"frontmostAppNotWriter": NSWorkspace.shared.frontmostApplication?.bundleIdentifier ?? "unknown",
]
if let data = try? JSONSerialization.data(withJSONObject: event, options: [.sortedKeys]),
- let line = String(data: data, encoding: .utf8) {
+ let line = String(data: data, encoding: .utf8)
+ {
print(line)
fflush(stdout)
}
diff --git a/tools/DictionaryLearningEvaluation/Package.swift b/tools/DictionaryLearningEvaluation/Package.swift
index b98a9da9..6c10070f 100644
--- a/tools/DictionaryLearningEvaluation/Package.swift
+++ b/tools/DictionaryLearningEvaluation/Package.swift
@@ -3,18 +3,21 @@ import Foundation
import PackageDescription
let package = Package(
- name: "DictionaryLearningEvaluation",
- platforms: [.macOS(.v14)],
- dependencies: [
- .package(
- name: "FluidAudio",
- path: ProcessInfo.processInfo.environment["FLUIDAUDIO_SOURCE"]
- ?? "../../../FluidAudio_pronunciation_streaming")
- ],
- targets: [
- .executableTarget(
- name: "Evaluate", dependencies: [.product(name: "FluidAudio", package: "FluidAudio")]),
- .executableTarget(
- name: "PersonalProof", dependencies: [.product(name: "FluidAudio", package: "FluidAudio")]),
- ]
+ name: "DictionaryLearningEvaluation",
+ platforms: [.macOS(.v14)],
+ dependencies: [
+ .package(
+ name: "FluidAudio",
+ path: ProcessInfo.processInfo.environment["FLUIDAUDIO_SOURCE"]
+ ?? "../../../FluidAudio_pronunciation_streaming"
+ ),
+ ],
+ targets: [
+ .executableTarget(
+ name: "Evaluate", dependencies: [.product(name: "FluidAudio", package: "FluidAudio")]
+ ),
+ .executableTarget(
+ name: "PersonalProof", dependencies: [.product(name: "FluidAudio", package: "FluidAudio")]
+ ),
+ ]
)
diff --git a/tools/DictionaryLearningEvaluation/Sources/Evaluate/main.swift b/tools/DictionaryLearningEvaluation/Sources/Evaluate/main.swift
index 8b76f74d..79eb914d 100644
--- a/tools/DictionaryLearningEvaluation/Sources/Evaluate/main.swift
+++ b/tools/DictionaryLearningEvaluation/Sources/Evaluate/main.swift
@@ -2,168 +2,202 @@ import FluidAudio
import Foundation
struct Word: Codable {
- let clip: String
- let language: String
- let index: Int
- let text: String
- let reference: String?
- let start: Double
- let end: Double
- let values: [Float]
- let frames: Int
+ let clip: String
+ let language: String
+ let index: Int
+ let text: String
+ let reference: String?
+ let start: Double
+ let end: Double
+ let values: [Float]
+ let frames: Int
}
+
struct Hit: Codable {
- let score: Float
- let indices: [Int]
+ let score: Float
+ let indices: [Int]
}
+
struct Trial: Codable {
- let language: String
- let target: String
- let known: String
- let clip: String
- let words: [Word]
- let hits: [Hit]
+ let language: String
+ let target: String
+ let known: String
+ let clip: String
+ let words: [Word]
+ let hits: [Hit]
}
+
func normalized(_ text: String) -> String {
- text.lowercased().filter { $0.isLetter || $0.isNumber }
+ text.lowercased().filter { $0.isLetter || $0.isNumber }
}
+
func align(_ hypothesis: [String], _ reference: [String]) -> [Int: String] {
- let n = hypothesis.count
- let m = reference.count
- var costs = Array(repeating: Array(repeating: 0, count: m + 1), count: n + 1)
- for i in 0...n { costs[i][0] = i }
- for j in 0...m { costs[0][j] = j }
- if n > 0, m > 0 {
- for i in 1...n {
- for j in 1...m {
- costs[i][j] = min(
- costs[i - 1][j] + 1, costs[i][j - 1] + 1,
- costs[i - 1][j - 1] + (hypothesis[i - 1] == reference[j - 1] ? 0 : 1))
- }
+ let n = hypothesis.count
+ let m = reference.count
+ var costs = Array(repeating: Array(repeating: 0, count: m + 1), count: n + 1)
+ for i in 0...n {
+ costs[i][0] = i
}
- }
- var result: [Int: String] = [:]
- var i = n
- var j = m
- while i > 0 || j > 0 {
- if i > 0, j > 0,
- costs[i][j] == costs[i - 1][j - 1] + (hypothesis[i - 1] == reference[j - 1] ? 0 : 1)
- {
- result[i - 1] = reference[j - 1]
- i -= 1
- j -= 1
- } else if i > 0, costs[i][j] == costs[i - 1][j] + 1 {
- i -= 1
- } else {
- j -= 1
+ for j in 0...m {
+ costs[0][j] = j
}
- }
- return result
+ if n > 0, m > 0 {
+ for i in 1...n {
+ for j in 1...m {
+ costs[i][j] = min(
+ costs[i - 1][j] + 1,
+ costs[i][j - 1] + 1,
+ costs[i - 1][j - 1] + (hypothesis[i - 1] == reference[j - 1] ? 0 : 1)
+ )
+ }
+ }
+ }
+ var result: [Int: String] = [:]
+ var i = n
+ var j = m
+ while i > 0 || j > 0 {
+ if i > 0, j > 0,
+ costs[i][j] == costs[i - 1][j - 1] + (hypothesis[i - 1] == reference[j - 1] ? 0 : 1)
+ {
+ result[i - 1] = reference[j - 1]
+ i -= 1
+ j -= 1
+ } else if i > 0, costs[i][j] == costs[i - 1][j] + 1 {
+ i -= 1
+ } else {
+ j -= 1
+ }
+ }
+ return result
}
+
@main struct Evaluate {
- static func main() async throws {
- guard CommandLine.arguments.count == 4 else {
- throw NSError(
- domain: "DictionaryLearningEvaluation", code: 1,
- userInfo: [
- NSLocalizedDescriptionKey: "Usage: Evaluate FLEURS_DIRECTORY MODEL_DIRECTORY OUTPUT_JSON"
- ])
- }
- let root = URL(fileURLWithPath: CommandLine.arguments[1])
- let models = try await AsrModels.loadLocalOnly(
- from: URL(fileURLWithPath: CommandLine.arguments[2]), version: .v3)
- let manager = AsrManager(
- config: ASRConfig(
- tdtConfig: TdtConfig(blankId: AsrModelVersion.v3.blankId), encoderHiddenSize: 1024))
- try await manager.initialize(models: models)
- var output: [Word] = []
- var clips: [String: (samples: [Float], features: EncoderFeatureSequence)] = [:]
- for language in ["en_us", "es_419", "fr_fr", "de_de", "ru_ru", "pl_pl", "el_gr", "da_dk"] {
- let directory = root.appendingPathComponent(language)
- let referenceLines = try String(
- contentsOf: directory.appendingPathComponent("\(language).trans.txt"), encoding: .utf8
- ).split(separator: "\n")
- let references = Dictionary(
- uniqueKeysWithValues: referenceLines.compactMap { line -> (String, [String])? in
- let parts = line.split(separator: " ", maxSplits: 1)
- guard parts.count == 2 else { return nil }
- return (String(parts[0]), parts[1].split(separator: " ").map { normalized(String($0)) })
- })
- for file in try FileManager.default.contentsOfDirectory(
- at: directory, includingPropertiesForKeys: nil
- ).filter({ $0.pathExtension == "wav" }).sorted(by: { $0.path < $1.path }) {
- let samples = try AudioConverter().resampleAudioFile(path: file.path)
- guard samples.count <= 238080 else {
- print("SKIP_LONG \(file.lastPathComponent)")
- continue
+ static func main() async throws {
+ guard CommandLine.arguments.count == 4 else {
+ throw NSError(
+ domain: "DictionaryLearningEvaluation",
+ code: 1,
+ userInfo: [
+ NSLocalizedDescriptionKey: "Usage: Evaluate FLEURS_DIRECTORY MODEL_DIRECTORY OUTPUT_JSON",
+ ]
+ )
}
- await manager.setPronunciationCustomizationEnabled(true)
- let result = try await manager.transcribe(samples, source: .microphone)
- guard let features = await manager.consumePronunciationEncoderFeatures() else { continue }
- let words = WordAudioChunkExtractor.words(from: result.tokenTimings ?? [])
- let clip = file.deletingPathExtension().lastPathComponent
- clips[clip] = (samples, features)
- let labels = align(words.map { normalized($0.text) }, references[clip] ?? [])
- for (index, word) in words.enumerated() {
- let start = max(0, Int((word.startTime / 0.08).rounded(.down)))
- let end = min(features.frameCount, Int((word.endTime / 0.08).rounded(.up)))
- guard end > start,
- let embedding = PronunciationEmbeddingMatcher.embedding(
- from: features, frameRange: start..<end)
- else { continue }
- output.append(
- Word(
- clip: clip, language: language, index: index, text: normalized(word.text),
- reference: labels[index], start: word.startTime, end: word.endTime,
- values: embedding.values, frames: embedding.sourceFrameCount))
+ let root = URL(fileURLWithPath: CommandLine.arguments[1])
+ let models = try await AsrModels.loadLocalOnly(
+ from: URL(fileURLWithPath: CommandLine.arguments[2]), version: .v3
+ )
+ let manager = AsrManager(
+ config: ASRConfig(
+ tdtConfig: TdtConfig(blankId: AsrModelVersion.v3.blankId), encoderHiddenSize: 1024
+ ))
+ try await manager.initialize(models: models)
+ var output: [Word] = []
+ var clips: [String: (samples: [Float], features: EncoderFeatureSequence)] = [:]
+ for language in ["en_us", "es_419", "fr_fr", "de_de", "ru_ru", "pl_pl", "el_gr", "da_dk"] {
+ let directory = root.appendingPathComponent(language)
+ let referenceLines = try String(
+ contentsOf: directory.appendingPathComponent("\(language).trans.txt"), encoding: .utf8
+ ).split(separator: "\n")
+ let references = Dictionary(
+ uniqueKeysWithValues: referenceLines.compactMap { line -> (String, [String])? in
+ let parts = line.split(separator: " ", maxSplits: 1)
+ guard parts.count == 2 else { return nil }
+ return (String(parts[0]), parts[1].split(separator: " ").map { normalized(String($0)) })
+ })
+ for file in try FileManager.default.contentsOfDirectory(
+ at: directory, includingPropertiesForKeys: nil
+ ).filter({ $0.pathExtension == "wav" }).sorted(by: { $0.path < $1.path }) {
+ let samples = try AudioConverter().resampleAudioFile(path: file.path)
+ guard samples.count <= 238_080 else {
+ print("SKIP_LONG \(file.lastPathComponent)")
+ continue
+ }
+ await manager.setPronunciationCustomizationEnabled(true)
+ let result = try await manager.transcribe(samples, source: .microphone)
+ guard let features = await manager.consumePronunciationEncoderFeatures() else { continue }
+ let words = WordAudioChunkExtractor.words(from: result.tokenTimings ?? [])
+ let clip = file.deletingPathExtension().lastPathComponent
+ clips[clip] = (samples, features)
+ let labels = align(words.map { normalized($0.text) }, references[clip] ?? [])
+ for (index, word) in words.enumerated() {
+ let start = max(0, Int((word.startTime / 0.08).rounded(.down)))
+ let end = min(features.frameCount, Int((word.endTime / 0.08).rounded(.up)))
+ guard end > start,
+ let embedding = PronunciationEmbeddingMatcher.embedding(
+ from: features, frameRange: start..<end
+ )
+ else { continue }
+ output.append(
+ Word(
+ clip: clip,
+ language: language,
+ index: index,
+ text: normalized(word.text),
+ reference: labels[index],
+ start: word.startTime,
+ end: word.endTime,
+ values: embedding.values,
+ frames: embedding.sourceFrameCount
+ ))
+ }
+ print("CLIP \(clip) \(words.count) words")
+ }
}
- print("CLIP \(clip) \(words.count) words")
- }
- }
- var trials: [Trial] = []
- let grouped = Dictionary(grouping: output.filter { ($0.reference?.count ?? 0) >= 3 }) {
- "\($0.language):\($0.reference!)"
- }
- for key in grouped.keys.sorted() {
- let occurrences = grouped[key]!
- guard Set(occurrences.map(\.clip)).count > 1,
- let enrollment = occurrences.first(where: { $0.text != $0.reference }) ?? occurrences.first,
- let source = clips[enrollment.clip]
- else { continue }
- let focalStart = Int((enrollment.start * 16000).rounded(.down))
- let focalEnd = min(source.samples.count, Int((enrollment.end * 16000).rounded(.up)))
- let contextStart = max(0, focalStart - 32000) / 1280 * 1280
- let contextEnd = min(source.samples.count, contextStart + 238080)
- guard focalEnd <= contextEnd, focalEnd > focalStart else { continue }
- let prototype = try await manager.pronunciationEmbedding(
- audioSamples: Array(source.samples[contextStart..<contextEnd]),
- focalSampleRange: (focalStart - contextStart)..<(focalEnd - contextStart)
- )
- for clip in clips.keys.sorted()
- where clip != enrollment.clip && clip.hasPrefix(enrollment.language) {
- let words = output.filter { $0.clip == clip }
- let matches = PronunciationEmbeddingMatcher.allMatches(
- prototypes: [prototype], in: clips[clip]!.features)[0]
- let hits = matches.map { match in
- let start = Double(match.frameRange.lowerBound) * 0.08
- let end = Double(match.frameRange.upperBound) * 0.08
- let indices = words.indices.filter { index in
- let word = words[index]
- return max(0, min(word.end, end) - max(word.start, start))
- / max(0.0001, word.end - word.start) >= 0.5
- }
- return Hit(score: match.score, indices: indices)
+ var trials: [Trial] = []
+ let grouped = Dictionary(grouping: output.filter { ($0.reference?.count ?? 0) >= 3 }) {
+ "\($0.language):\($0.reference ?? "")"
+ }
+ for key in grouped.keys.sorted() {
+ guard let occurrences = grouped[key] else { continue }
+ guard Set(occurrences.map(\.clip)).count > 1,
+ let enrollment = occurrences.first(where: { $0.text != $0.reference }) ?? occurrences.first,
+ let target = enrollment.reference,
+ let source = clips[enrollment.clip]
+ else { continue }
+ let focalStart = Int((enrollment.start * 16_000).rounded(.down))
+ let focalEnd = min(source.samples.count, Int((enrollment.end * 16_000).rounded(.up)))
+ let contextStart = max(0, focalStart - 32_000) / 1280 * 1280
+ let contextEnd = min(source.samples.count, contextStart + 238_080)
+ guard focalEnd <= contextEnd, focalEnd > focalStart else { continue }
+ let prototype = try await manager.pronunciationEmbedding(
+ audioSamples: Array(source.samples[contextStart..<contextEnd]),
+ focalSampleRange: (focalStart - contextStart)..<(focalEnd - contextStart)
+ )
+ for clip in clips.keys.sorted()
+ where clip != enrollment.clip && clip.hasPrefix(enrollment.language)
+ {
+ guard let clipFeatures = clips[clip]?.features else { continue }
+ let words = output.filter { $0.clip == clip }
+ let matches = PronunciationEmbeddingMatcher.allMatches(
+ prototypes: [prototype], in: clipFeatures
+ )[0]
+ let hits = matches.map { match in
+ let start = Double(match.frameRange.lowerBound) * 0.08
+ let end = Double(match.frameRange.upperBound) * 0.08
+ let indices = words.indices.filter { index in
+ let word = words[index]
+ return max(0, min(word.end, end) - max(word.start, start))
+ / max(0.0001, word.end - word.start) >= 0.5
+ }
+ return Hit(score: match.score, indices: indices)
+ }
+ trials.append(
+ Trial(
+ language: enrollment.language,
+ target: target,
+ known: enrollment.text,
+ clip: clip,
+ words: words,
+ hits: hits
+ ))
+ }
}
- trials.append(
- Trial(
- language: enrollment.language, target: enrollment.reference!, known: enrollment.text,
- clip: clip, words: words, hits: hits))
- }
+ try JSONEncoder().encode(trials).write(
+ to: URL(fileURLWithPath: CommandLine.arguments[3] + ".trials.json"), options: .atomic
+ )
+ try JSONEncoder().encode(output).write(
+ to: URL(fileURLWithPath: CommandLine.arguments[3]), options: .atomic
+ )
+ await manager.cleanup()
}
- try JSONEncoder().encode(trials).write(
- to: URL(fileURLWithPath: CommandLine.arguments[3] + ".trials.json"), options: .atomic)
- try JSONEncoder().encode(output).write(
- to: URL(fileURLWithPath: CommandLine.arguments[3]), options: .atomic)
- await manager.cleanup()
- }
}
diff --git a/tools/DictionaryLearningEvaluation/Sources/PersonalProof/main.swift b/tools/DictionaryLearningEvaluation/Sources/PersonalProof/main.swift
index edbdbb49..6566fc34 100644
--- a/tools/DictionaryLearningEvaluation/Sources/PersonalProof/main.swift
+++ b/tools/DictionaryLearningEvaluation/Sources/PersonalProof/main.swift
@@ -2,106 +2,125 @@ import FluidAudio
import Foundation
struct Token: Codable {
- let text: String
- let start: Double
- let end: Double
+ let text: String
+ let start: Double
+ let end: Double
}
+
struct Hit: Codable {
- let score: Float
- let text: String
- let start: Double
- let end: Double
- let targetOnly: Bool
+ let score: Float
+ let text: String
+ let start: Double
+ let end: Double
+ let targetOnly: Bool
}
+
struct Trial: Codable {
- let target: String
- let enrollmentStart: Double
- let positiveOccurrences: Int
- let hits: [Hit]
+ let target: String
+ let enrollmentStart: Double
+ let positiveOccurrences: Int
+ let hits: [Hit]
}
+
func normalize(_ s: String) -> String { s.lowercased().filter { $0.isLetter || $0.isNumber } }
@main struct PersonalProof {
- static func main() async throws {
- guard CommandLine.arguments.count == 4 else {
- throw NSError(
- domain: "DictionaryLearningEvaluation", code: 1,
- userInfo: [
- NSLocalizedDescriptionKey: "Usage: PersonalProof AUDIO MODEL_DIRECTORY OUTPUT_JSON"
- ])
- }
- let source = try AudioConverter().resampleAudioFile(path: CommandLine.arguments[1])
- let models = try await AsrModels.loadLocalOnly(
- from: URL(fileURLWithPath: CommandLine.arguments[2]), version: .v3)
- let manager = AsrManager(
- config: ASRConfig(
- tdtConfig: TdtConfig(blankId: AsrModelVersion.v3.blankId), encoderHiddenSize: 1024))
- try await manager.initialize(models: models)
- var windows: [(offset: Int, features: EncoderFeatureSequence, words: [Token])] = []
- var allWords: [Token] = []
- for start in stride(from: 0, to: source.count, by: 238080) {
- let samples = Array(source[start..<min(source.count, start + 238080)])
- guard samples.count >= 16000 else {
- print("SKIP_TAIL samples=\(samples.count)")
- continue
- }
- await manager.setPronunciationCustomizationEnabled(true)
- let result = try await manager.transcribe(samples, source: .microphone)
- guard let features = await manager.consumePronunciationEncoderFeatures() else { continue }
- let words = WordAudioChunkExtractor.words(from: result.tokenTimings ?? []).map {
- Token(
- text: normalize($0.text), start: $0.startTime + Double(start) / 16000,
- end: $0.endTime + Double(start) / 16000)
- }
- windows.append((start, features, words))
- allWords += words
- print("WINDOW \(start) \(result.text)")
- }
- var trials: [Trial] = []
- for target in ["nvidia", "jensen", "huang", "design", "ai"] {
- let occurrences = allWords.filter { $0.text == target }
- guard let enrollment = occurrences.first else { continue }
- let lower = Int((enrollment.start * 16000).rounded(.down))
- let upper = Int((enrollment.end * 16000).rounded(.up))
- let contextStart = max(0, lower - 32000) / 1280 * 1280
- let contextEnd = min(source.count, contextStart + 238080)
- let prototype = try await manager.pronunciationEmbedding(
- audioSamples: Array(source[contextStart..<contextEnd]),
- focalSampleRange: (lower - contextStart)..<(upper - contextStart))
- var hits: [Hit] = []
- var positives = 0
- for window in windows {
- // Entire enrollment ASR window is excluded; never count replay as held-out speech.
- if enrollment.start >= Double(window.offset) / 16000
- && enrollment.start < Double(window.offset + 238080) / 16000
- {
- continue
+ static func main() async throws {
+ guard CommandLine.arguments.count == 4 else {
+ throw NSError(
+ domain: "DictionaryLearningEvaluation",
+ code: 1,
+ userInfo: [
+ NSLocalizedDescriptionKey: "Usage: PersonalProof AUDIO MODEL_DIRECTORY OUTPUT_JSON",
+ ]
+ )
+ }
+ let source = try AudioConverter().resampleAudioFile(path: CommandLine.arguments[1])
+ let models = try await AsrModels.loadLocalOnly(
+ from: URL(fileURLWithPath: CommandLine.arguments[2]), version: .v3
+ )
+ let manager = AsrManager(
+ config: ASRConfig(
+ tdtConfig: TdtConfig(blankId: AsrModelVersion.v3.blankId), encoderHiddenSize: 1024
+ ))
+ try await manager.initialize(models: models)
+ var windows: [(offset: Int, features: EncoderFeatureSequence, words: [Token])] = []
+ var allWords: [Token] = []
+ for start in stride(from: 0, to: source.count, by: 238_080) {
+ let samples = Array(source[start..<min(source.count, start + 238_080)])
+ guard samples.count >= 16_000 else {
+ print("SKIP_TAIL samples=\(samples.count)")
+ continue
+ }
+ await manager.setPronunciationCustomizationEnabled(true)
+ let result = try await manager.transcribe(samples, source: .microphone)
+ guard let features = await manager.consumePronunciationEncoderFeatures() else { continue }
+ let words = WordAudioChunkExtractor.words(from: result.tokenTimings ?? []).map {
+ Token(
+ text: normalize($0.text),
+ start: $0.startTime + Double(start) / 16_000,
+ end: $0.endTime + Double(start) / 16_000
+ )
+ }
+ windows.append((start, features, words))
+ allWords += words
+ print("WINDOW \(start) \(result.text)")
}
- positives += window.words.filter { $0.text == target }.count
- let matchStart = ProcessInfo.processInfo.systemUptime
- let matches = PronunciationEmbeddingMatcher.allMatches(
- prototypes: [prototype], in: window.features)[0]
- let matchMs = (ProcessInfo.processInfo.systemUptime - matchStart) * 1000
- print("MATCH_MS target=\(target) frames=\(window.features.frameCount) elapsed=\(matchMs)")
- for match in matches {
- let start = Double(window.offset) / 16000 + Double(match.frameRange.lowerBound) * 0.08
- let end = Double(window.offset) / 16000 + Double(match.frameRange.upperBound) * 0.08
- let words = window.words.filter {
- max(0, min($0.end, end) - max($0.start, start)) / max(0.0001, $0.end - $0.start) >= 0.5
- }
- guard !words.isEmpty else { continue }
- hits.append(
- Hit(
- score: match.score, text: words.map(\.text).joined(separator: " "), start: start,
- end: end, targetOnly: words.count == 1 && words[0].text == target))
+ var trials: [Trial] = []
+ for target in ["nvidia", "jensen", "huang", "design", "ai"] {
+ let occurrences = allWords.filter { $0.text == target }
+ guard let enrollment = occurrences.first else { continue }
+ let lower = Int((enrollment.start * 16_000).rounded(.down))
+ let upper = Int((enrollment.end * 16_000).rounded(.up))
+ let contextStart = max(0, lower - 32_000) / 1280 * 1280
+ let contextEnd = min(source.count, contextStart + 238_080)
+ let prototype = try await manager.pronunciationEmbedding(
+ audioSamples: Array(source[contextStart..<contextEnd]),
+ focalSampleRange: (lower - contextStart)..<(upper - contextStart)
+ )
+ var hits: [Hit] = []
+ var positives = 0
+ for window in windows {
+ // Entire enrollment ASR window is excluded; never count replay as held-out speech.
+ if enrollment.start >= Double(window.offset) / 16_000,
+ enrollment.start < Double(window.offset + 238_080) / 16_000
+ {
+ continue
+ }
+ positives += window.words.filter { $0.text == target }.count
+ let matchStart = ProcessInfo.processInfo.systemUptime
+ let matches = PronunciationEmbeddingMatcher.allMatches(
+ prototypes: [prototype], in: window.features
+ )[0]
+ let matchMs = (ProcessInfo.processInfo.systemUptime - matchStart) * 1000
+ print("MATCH_MS target=\(target) frames=\(window.features.frameCount) elapsed=\(matchMs)")
+ for match in matches {
+ let start = Double(window.offset) / 16_000 + Double(match.frameRange.lowerBound) * 0.08
+ let end = Double(window.offset) / 16_000 + Double(match.frameRange.upperBound) * 0.08
+ let words = window.words.filter {
+ max(0, min($0.end, end) - max($0.start, start)) / max(0.0001, $0.end - $0.start) >= 0.5
+ }
+ guard !words.isEmpty else { continue }
+ hits.append(
+ Hit(
+ score: match.score,
+ text: words.map(\.text).joined(separator: " "),
+ start: start,
+ end: end,
+ targetOnly: words.count == 1 && words[0].text == target
+ ))
+ }
+ }
+ trials.append(
+ Trial(
+ target: target,
+ enrollmentStart: enrollment.start,
+ positiveOccurrences: positives,
+ hits: hits
+ ))
}
- }
- trials.append(
- Trial(
- target: target, enrollmentStart: enrollment.start, positiveOccurrences: positives,
- hits: hits))
+ try JSONEncoder().encode(trials).write(
+ to: URL(fileURLWithPath: CommandLine.arguments[3]), options: .atomic
+ )
+ await manager.cleanup()
}
- try JSONEncoder().encode(trials).write(
- to: URL(fileURLWithPath: CommandLine.arguments[3]), options: .atomic)
- await manager.cleanup()
- }
}
diff --git a/tools/meeting_temporal_shadow.swift b/tools/meeting_temporal_shadow.swift
index 6be2026c..66d01558 100644
--- a/tools/meeting_temporal_shadow.swift
+++ b/tools/meeting_temporal_shadow.swift
@@ -9,8 +9,9 @@ struct MeetingTemporalShadow {
struct Stamp: Decodable {
let value: Double
let timescale: Double
- var seconds: Double { value / timescale }
+ var seconds: Double { self.value / self.timescale }
}
+
struct Discontinuity: Decodable { let presentationTime: Stamp? }
struct Chunk: Decodable {
let id: UUID
@@ -19,6 +20,7 @@ struct MeetingTemporalShadow {
let presentationEnd: Stamp
let discontinuities: [Discontinuity]
}
+
struct Track: Decodable { let kind: String; let chunks: [Chunk] }
struct Session: Decodable { let id: UUID; let audioTracks: [Track] }
struct InputFingerprint: Codable { let chunkID: UUID; let sha256: String }
@@ -29,6 +31,7 @@ struct MeetingTemporalShadow {
let proposedAdmission = "uncertainCandidate"
let legacyEchoEvidence = "notMeasured"
}
+
struct Report: Encodable {
let version = MeetingPlaybackDuplicateDetector.version
let experimental = true
@@ -51,29 +54,39 @@ struct MeetingTemporalShadow {
let stateCounts: [String: Int]
let reasonCounts: [String: Int]
let windows: [MeetingPlaybackDuplicateDetector.Result]
+ // nil means speech analysis was disabled or unavailable, distinct from an empty result.
+ // swiftlint:disable:next discouraged_optional_collection
let speechModelHashes: [String: String]?
let speechModelStatus: String
let speechAdapterVersion = "speech-shadow-b2-v1"
let speechFrameSampleRate = 16_000
let speechFrameSamples = 4096
let speechDiagnosticThreshold = 0.85
+ // nil means speech analysis was disabled or unavailable, distinct from an empty result.
+ // swiftlint:disable:next discouraged_optional_collection
let speechFrames: [SpeechRecord]?
let speechUnwindowedTailSeconds: Double?
let speechUnavailableSeconds: Double?
}
+
enum Failure: Error { case invalidInput, unsafePath, decoder, outputExists }
- static func decode(_ url: URL, rate: Double = 2_000) throws -> [Float] {
+ static func decode(_ url: URL, rate: Double = 2000) throws -> [Float] {
let file = try AVAudioFile(forReading: url)
let format = file.processingFormat
- guard format.sampleRate.isFinite, format.sampleRate >= 2_000,
+ guard format.sampleRate.isFinite, format.sampleRate >= 2000,
format.sampleRate <= 192_000, (1...8).contains(format.channelCount),
file.length > 0, file.length <= Int64(format.sampleRate * 65),
let input = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(file.length)),
- let outputFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: rate,
- channels: 1, interleaved: false),
+ let outputFormat = AVAudioFormat(
+ commonFormat: .pcmFormatFloat32,
+ sampleRate: rate,
+ channels: 1,
+ interleaved: false
+ ),
let converter = AVAudioConverter(from: format, to: outputFormat),
- let output = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: AVAudioFrameCount(rate * 66)) else {
+ let output = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: AVAudioFrameCount(rate * 66))
+ else {
throw Failure.decoder
}
try file.read(into: input)
@@ -93,6 +106,8 @@ struct MeetingTemporalShadow {
guard (3...4).contains(CommandLine.arguments.count) else { throw Failure.invalidInput }
let speechEnabled = CommandLine.arguments.count == 4
var speechModel: MeetingLocalSileroActivityModel?
+ // nil means speech analysis was disabled or unavailable, distinct from an empty result.
+ // swiftlint:disable:next discouraged_optional_collection
var modelHashes: [String: String]?
var modelFiles: [String: URL] = [:]
var modelStatus = "off"
@@ -101,8 +116,10 @@ struct MeetingTemporalShadow {
let modelURL = URL(fileURLWithPath: CommandLine.arguments[3]).resolvingSymlinksInPath()
do {
guard modelURL.pathExtension == "mlmodelc",
- let enumerator = FileManager.default.enumerator(at: modelURL,
- includingPropertiesForKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey])
+ let enumerator = FileManager.default.enumerator(
+ at: modelURL,
+ includingPropertiesForKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]
+ )
else { throw Failure.invalidInput }
var hashes: [String: String] = [:], totalBytes = 0
for case let file as URL in enumerator {
@@ -112,7 +129,7 @@ struct MeetingTemporalShadow {
totalBytes += info.fileSize ?? 0
guard totalBytes <= 32_000_000, hashes.count < 64 else { throw Failure.invalidInput }
let name = String(file.path.dropFirst(modelURL.path.count + 1))
- hashes[name] = SHA256.hash(data: try Data(contentsOf: file)).map { String(format: "%02x", $0) }.joined()
+ hashes[name] = try SHA256.hash(data: Data(contentsOf: file)).map { String(format: "%02x", $0) }.joined()
modelFiles[name] = file
}
}
@@ -140,17 +157,18 @@ struct MeetingTemporalShadow {
Set(session.audioTracks.map(\.kind)).count == session.audioTracks.count,
session.audioTracks.allSatisfy({ ["microphone", "applicationAudio"].contains($0.kind) }),
chunks.allSatisfy({ $0.presentationStart.seconds.isFinite && $0.presentationEnd.seconds.isFinite
- && $0.presentationEnd.seconds > $0.presentationStart.seconds
- && $0.presentationEnd.seconds - $0.presentationStart.seconds <= 65 }) else { throw Failure.invalidInput }
- let origin = chunks.map { $0.presentationStart.seconds }.min()!
- let duration = chunks.map { $0.presentationEnd.seconds - origin }.max()!
+ && $0.presentationEnd.seconds > $0.presentationStart.seconds
+ && $0.presentationEnd.seconds - $0.presentationStart.seconds <= 65 }) else { throw Failure.invalidInput }
+ guard let origin = chunks.map({ $0.presentationStart.seconds }).min(),
+ let duration = chunks.map({ $0.presentationEnd.seconds - origin }).max()
+ else { throw Failure.invalidInput }
guard duration > 0, duration <= 600 else { throw Failure.invalidInput }
// Same either-track boundary definition and ±blockSeconds=2 guard as the pipeline.
// Missing-PTS discontinuities cannot be placed: fail closed for this offline input.
let discontinuities = chunks.flatMap(\.discontinuities)
guard discontinuities.allSatisfy({ $0.presentationTime?.seconds.isFinite == true }) else { throw Failure.invalidInput }
- let boundaries = discontinuities.map { $0.presentationTime!.seconds - origin }.sorted()
- let count = Int(ceil(duration * 2_000))
+ let boundaries = discontinuities.compactMap { $0.presentationTime.map { $0.seconds - origin } }.sorted()
+ let count = Int(ceil(duration * 2000))
var tracks: [String: MeetingPlaybackDuplicateDetector.PCM] = [:]
var fingerprints: [InputFingerprint] = []
let speechCount = speechEnabled ? Int(ceil(duration * 16_000)) : 0
@@ -169,10 +187,10 @@ struct MeetingTemporalShadow {
guard url.path.hasPrefix(root.path + "/") else { throw Failure.unsafePath }
let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
guard let bytes = attributes[.size] as? NSNumber, bytes.intValue <= 32_000_000 else { throw Failure.invalidInput }
- let before = SHA256.hash(data: try Data(contentsOf: url)).map { String(format: "%02x", $0) }.joined()
+ let before = try SHA256.hash(data: Data(contentsOf: url)).map { String(format: "%02x", $0) }.joined()
let decoded = try decode(url)
- let decodedSpeech = speechEnabled && track.kind == "microphone" ? try decode(url, rate: 16_000) : nil
- let after = SHA256.hash(data: try Data(contentsOf: url)).map { String(format: "%02x", $0) }.joined()
+ let decodedSpeech = speechEnabled && track.kind == "microphone" ? try self.decode(url, rate: 16_000) : nil
+ let after = try SHA256.hash(data: Data(contentsOf: url)).map { String(format: "%02x", $0) }.joined()
guard before == after else { throw Failure.invalidInput }
fingerprints.append(.init(chunkID: chunk.id, sha256: before))
let start = chunk.presentationStart.seconds - origin
@@ -193,11 +211,11 @@ struct MeetingTemporalShadow {
}
}
}
- let first = max(0, Int(ceil(start * 2_000)))
- let last = min(count, Int(floor(end * 2_000)))
+ let first = max(0, Int(ceil(start * 2000)))
+ let last = min(count, Int(floor(end * 2000)))
for index in first..<last {
- let time = Double(index) / 2_000
- let position = (time - start) * 2_000
+ let time = Double(index) / 2000
+ let position = (time - start) * 2000
let lower = Int(floor(position)), alpha = Float(position - floor(position))
// Trim declared end, decoded end and conservative codec/converter edges.
let usable = time >= start + 0.05 && time < end - 0.05
@@ -213,10 +231,14 @@ struct MeetingTemporalShadow {
}
tracks[track.kind] = .init(start: 0, samples: samples, valid: valid)
}
- func slice(_ track: MeetingPlaybackDuplicateDetector.PCM?, start: Double, count: Int,
- mappedStart: Double? = nil) -> MeetingPlaybackDuplicateDetector.PCM? {
+ func slice(
+ _ track: MeetingPlaybackDuplicateDetector.PCM?,
+ start: Double,
+ count: Int,
+ mappedStart: Double? = nil
+ ) -> MeetingPlaybackDuplicateDetector.PCM? {
guard let track else { return nil }
- let first = Int((start * 2_000).rounded())
+ let first = Int((start * 2000).rounded())
var samples = [Float](repeating: 0, count: count), valid = [Bool](repeating: false, count: count)
for i in 0..<count where first + i >= 0 && first + i < track.samples.count {
samples[i] = track.samples[first + i]; valid[i] = track.valid[first + i]
@@ -231,42 +253,65 @@ struct MeetingTemporalShadow {
let referenceStart = start - 0.5
let nullStart = start + 10.5 <= duration ? referenceStart + 8 : referenceStart - 8
let nullControl = nullStart >= 0 && nullStart + 3 <= duration
- ? slice(tracks["applicationAudio"], start: nullStart, count: 6_000, mappedStart: referenceStart) : nil
- let mic = slice(tracks["microphone"], start: start, count: 4_000)
+ ? slice(tracks["applicationAudio"], start: nullStart, count: 6000, mappedStart: referenceStart) : nil
+ let mic = slice(tracks["microphone"], start: start, count: 4000)
?? .init(start: start, samples: [], valid: [])
- results.append(detector.process(.init(sessionID: session.id, epoch: epoch, routeID: "recorded",
- start: start, microphone: mic,
- reference: slice(tracks["applicationAudio"], start: referenceStart, count: 6_000),
- mismatchedReference: nullControl)))
+ results.append(detector.process(.init(
+ sessionID: session.id,
+ epoch: epoch,
+ routeID: "recorded",
+ start: start,
+ microphone: mic,
+ reference: slice(tracks["applicationAudio"], start: referenceStart, count: 6000),
+ mismatchedReference: nullControl
+ )))
}
var speechRecords: [SpeechRecord] = []
if let speechModel {
var detector = MeetingSpeechActivityDetector(model: speechModel)
for first in stride(from: 0, through: max(-1, speechCount - 4096), by: 4096) {
let start = Double(first) / 16_000, epoch = UInt64(boundaries.filter { $0 <= start }.count)
- let frame = detector.process(samples: Array(speechSamples[first..<(first + 4096)]),
- valid: Array(speechValid[first..<(first + 4096)]), start: start, session: session.id, epoch: epoch, route: "recorded")
+ let frame = detector.process(
+ samples: Array(speechSamples[first..<(first + 4096)]),
+ valid: Array(speechValid[first..<(first + 4096)]),
+ start: start,
+ session: session.id,
+ epoch: epoch,
+ route: "recorded"
+ )
let temporal = MeetingSpeechPlaybackShadowPolicy.temporalContext(start: start, epoch: epoch, windows: results)
- speechRecords.append(.init(frame: frame, temporalState: temporal,
- combinedReason: MeetingSpeechPlaybackShadowPolicy.reason(activity: frame.active,
- reliableDuplicate: temporal == .supported)))
+ speechRecords.append(.init(
+ frame: frame,
+ temporalState: temporal,
+ combinedReason: MeetingSpeechPlaybackShadowPolicy.reason(
+ activity: frame.active,
+ reliableDuplicate: temporal == .supported
+ )
+ ))
}
}
if let modelHashes {
for (name, file) in modelFiles {
- guard SHA256.hash(data: try Data(contentsOf: file)).map({ String(format: "%02x", $0) }).joined() == modelHashes[name]
+ guard try SHA256.hash(data: Data(contentsOf: file)).map({ String(format: "%02x", $0) }).joined() == modelHashes[name]
else { throw Failure.invalidInput }
}
}
- let report = Report(sessionSHA256: SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined(),
- inputs: fingerprints, configuration: .init(), durationSeconds: duration,
+ let report = Report(
+ sessionSHA256: SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined(),
+ inputs: fingerprints,
+ configuration: .init(),
+ durationSeconds: duration,
unwindowedTailSeconds: duration - Double(results.count * 2),
maximumWindowWallSeconds: results.map(\.elapsedSeconds).max() ?? 0,
stateCounts: Dictionary(grouping: results, by: { $0.state.rawValue }).mapValues(\.count),
- reasonCounts: Dictionary(grouping: results, by: { $0.reason.rawValue }).mapValues(\.count), windows: results,
- speechModelHashes: modelHashes, speechModelStatus: modelStatus, speechFrames: speechEnabled ? speechRecords : nil,
+ reasonCounts: Dictionary(grouping: results, by: { $0.reason.rawValue }).mapValues(\.count),
+ windows: results,
+ speechModelHashes: modelHashes,
+ speechModelStatus: modelStatus,
+ speechFrames: speechEnabled ? speechRecords : nil,
speechUnwindowedTailSeconds: speechModel == nil ? nil : duration - Double(speechRecords.count) * 0.256,
- speechUnavailableSeconds: speechEnabled ? duration - Double(speechRecords.filter { $0.frame.probability != nil }.count) * 0.256 : nil)
+ speechUnavailableSeconds: speechEnabled ? duration - Double(speechRecords.filter { $0.frame.probability != nil }.count) * 0.256 : nil
+ )
let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
try encoder.encode(report).write(to: output, options: [.withoutOverwriting])
print("Created numeric-only shadow sidecar: \(results.count) windows; no session changes.")