@mentra/bluetooth-sdk 3.4.0-dev.999 → 3.4.1-beta.1409
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MIGRATION.md +16 -7
- package/README.md +41 -14
- package/android/build.gradle +60 -51
- package/android/gradle.properties +3 -0
- package/android/settings.gradle +47 -3
- package/android/src/main/assets/nimo/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +77 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +41 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +131 -122
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +3 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +31 -10
- package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +57 -196
- package/android/src/main/java/com/mentra/bluetoothsdk/OtaManifest.kt +1 -16
- package/android/src/main/java/com/mentra/bluetoothsdk/debug/BleTraceLogger.kt +10 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/Ipv4Prefix.kt +51 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/NetworkFacts.kt +81 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkError.kt +108 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadiness.kt +103 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpec.kt +44 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkState.kt +117 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedSoftApNetwork.kt +598 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/SoftApTrace.kt +143 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/otaserver/MentraOtaServerModule.kt +0 -7
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTracker.kt +15 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +308 -60
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +14 -5
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +210 -325
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +0 -35
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +2 -10
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdater.kt +213 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocol.kt +112 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/streaming/StreamModels.kt +17 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/StreamRequestCaptureAudioTest.kt +23 -4
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/Ipv4PrefixTest.kt +59 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/NetworkFactsTest.kt +59 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedLocalNetworkPermissionTest.kt +35 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkErrorTest.kt +85 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkLifecycleTest.kt +164 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadinessTest.kt +141 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpecTest.kt +56 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/SoftApTraceTest.kt +97 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/UnavailableRetryTest.kt +47 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTrackerTest.kt +26 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +9 -3
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareTargetTest.kt +15 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdaterTest.kt +76 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocolTest.kt +77 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoReadinessDriverTest.kt +31 -1
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
- package/build/BluetoothSdk.types.d.ts +103 -5
- package/build/BluetoothSdk.types.d.ts.map +1 -1
- package/build/BluetoothSdk.types.js.map +1 -1
- package/build/_private/BluetoothSdkModule.d.ts +42 -8
- package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
- package/build/_private/BluetoothSdkModule.js +1 -0
- package/build/_private/BluetoothSdkModule.js.map +1 -1
- package/build/_private/MentraLocalNetworkModule.d.ts +1 -1
- package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
- package/build/_private/MentraLocalNetworkModule.js.map +1 -1
- package/build/generated/changelogCatalog.d.ts +5 -2
- package/build/generated/changelogCatalog.d.ts.map +1 -1
- package/build/generated/changelogCatalog.js +6 -2
- package/build/generated/changelogCatalog.js.map +1 -1
- package/build/generated/releaseMetadata.js +6 -6
- package/build/generated/releaseMetadata.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +7 -1
- package/build/index.js.map +1 -1
- package/build/ota-server/MentraOtaServerModule.d.ts +0 -2
- package/build/ota-server/MentraOtaServerModule.d.ts.map +1 -1
- package/build/ota-server/MentraOtaServerModule.js.map +1 -1
- package/build/ota-server/MentraOtaServerModule.web.d.ts +0 -1
- package/build/ota-server/MentraOtaServerModule.web.d.ts.map +1 -1
- package/build/ota-server/MentraOtaServerModule.web.js +0 -3
- package/build/ota-server/MentraOtaServerModule.web.js.map +1 -1
- package/build/ota-transport/index.d.ts +3 -3
- package/build/ota-transport/index.d.ts.map +1 -1
- package/build/ota-transport/index.js +4 -4
- package/build/ota-transport/index.js.map +1 -1
- package/build/react/useGlassesConnection.d.ts +1 -1
- package/build/react/useGlassesConnection.d.ts.map +1 -1
- package/build/react/useGlassesConnection.js +3 -3
- package/build/react/useGlassesConnection.js.map +1 -1
- package/build/react/useMentraBluetooth.d.ts +1 -1
- package/build/react/useMentraBluetooth.d.ts.map +1 -1
- package/build/react/useMentraBluetooth.js +1 -1
- package/build/react/useMentraBluetooth.js.map +1 -1
- package/ios/BluetoothSdkModule.swift +73 -22
- package/ios/LocalIPv4.swift +0 -61
- package/ios/MentraBluetoothSDK.podspec +7 -1
- package/ios/MentraOtaServerModule.swift +0 -16
- package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
- package/ios/Resources/NimoFirmware/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
- package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
- package/ios/Source/BesCrashReportWaiters.swift +64 -0
- package/ios/Source/BluetoothSdkDefaults.swift +4 -4
- package/ios/Source/Bridge.swift +14 -0
- package/ios/Source/DeviceManager.swift +52 -22
- package/ios/Source/GeneratedChangelogCatalog.swift +3 -2
- package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
- package/ios/Source/MentraBluetoothSDK.swift +35 -16
- package/ios/Source/OtaManifest.swift +1 -17
- package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
- package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
- package/ios/Source/audio/SpeechActivity.swift +277 -0
- package/ios/Source/events/BluetoothEvents.swift +41 -0
- package/ios/Source/internal/BleTraceLogger.swift +14 -1
- package/ios/Source/internal/BluetoothAvailability.swift +15 -5
- package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +5 -0
- package/ios/Source/sgcs/MentraLive.swift +207 -66
- package/ios/Source/sgcs/Nimo.swift +249 -276
- package/ios/Source/sgcs/NimoCanvasCoordinator.swift +9 -38
- package/ios/Source/sgcs/NimoCanvasSession.swift +0 -1
- package/ios/Source/sgcs/NimoFirmwareUpdater.swift +260 -0
- package/ios/Source/sgcs/NimoOtaProtocol.swift +159 -0
- package/ios/Source/sgcs/SGCManager.swift +6 -0
- package/ios/Source/streaming/StreamModels.swift +15 -6
- package/ios/Source/stt/STTTools.swift +13 -31
- package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
- package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
- package/ios/Source/stt/WakeWordDetector.swift +145 -0
- package/ios/Source/utils/BoundedWait.swift +44 -0
- package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
- package/ios/Source/utils/SttModelTraits.swift +62 -0
- package/ios/Tests/BesCrashReportTests.swift +142 -0
- package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
- package/ios/Tests/DeviceManagerReconnectTests.swift +0 -71
- package/ios/Tests/GlassesAudioSetupPolicyTests.swift +9 -3
- package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
- package/ios/Tests/MentraLiveAudioSetupTests.swift +6 -12
- package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
- package/ios/Tests/MentraLiveSessionReadinessTests.swift +179 -10
- package/ios/Tests/NimoCanvasTransportTests.swift +0 -89
- package/ios/Tests/NimoOtaProtocolTests.swift +78 -0
- package/ios/Tests/PcmStreamTests.swift +299 -0
- package/ios/Tests/SpeechActivityTests.swift +238 -0
- package/ios/Tests/StreamRequestTests.swift +18 -0
- package/ios/Tests/SttModelTraitsTests.swift +62 -0
- package/package.json +2 -2
- package/plugin/build/withAndroid.js +9 -11
- package/plugin/build/withKotlinVersion.d.ts +2 -0
- package/plugin/build/withKotlinVersion.js +46 -0
- package/src/BluetoothSdk.types.ts +107 -5
- package/src/_private/BluetoothSdkModule.ts +45 -8
- package/src/_private/MentraLocalNetworkModule.ts +5 -1
- package/src/generated/changelogCatalog.ts +6 -2
- package/src/generated/releaseMetadata.ts +6 -6
- package/src/index.ts +13 -1
- package/src/ota-server/MentraOtaServerModule.ts +0 -2
- package/src/ota-server/MentraOtaServerModule.web.ts +0 -4
- package/src/ota-transport/index.ts +4 -5
- package/src/react/useGlassesConnection.ts +4 -4
- package/src/react/useMentraBluetooth.ts +2 -2
- package/android/silero/LICENSE.md +0 -17
- package/android/silero/build.gradle +0 -50
- package/android/silero/proguard-rules.pro +0 -24
- package/android/silero/src/androidTest/assets/hello.wav +0 -0
- package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
- package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
- package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
- package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
- package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
- package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -274
- package/android/src/main/java/com/mentra/bluetoothsdk/ScopedNetworkReadiness.kt +0 -17
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
- package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
- package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -16
- package/android/src/test/java/com/mentra/bluetoothsdk/ScopedNetworkReadinessTest.kt +0 -39
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -851
- package/ios/Source/sgcs/NimoMacResourceTransport.swift +0 -217
- package/ios/Source/sgcs/NimoResourceFixture.swift +0 -384
- package/ios/Source/sgcs/NimoResourceSession.swift +0 -406
- package/ios/Tests/NimoResourceSessionTests.swift +0 -476
- /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
- /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Native keyword spotting, independent of full speech transcription.
|
|
4
|
+
///
|
|
5
|
+
/// The model comes from the Speech-page model directory passed to `configure`. It is loaded
|
|
6
|
+
/// while detection is enabled and released when detection is disabled.
|
|
7
|
+
final class WakeWordDetector {
|
|
8
|
+
static let shared = WakeWordDetector()
|
|
9
|
+
|
|
10
|
+
static let requiredModelFiles = ["encoder.int8.onnx", "decoder.onnx", "joiner.int8.onnx", "tokens.txt", "keywords.txt"]
|
|
11
|
+
private static let phrase = "Hey Mentra"
|
|
12
|
+
|
|
13
|
+
private let lock = NSLock()
|
|
14
|
+
private var modelDir: String?
|
|
15
|
+
// Worker queue only.
|
|
16
|
+
private var lastDetection: TimeInterval = 0
|
|
17
|
+
private lazy var worker: DemandDrivenAudioWorker<SherpaOnnxKeywordSpotterWrapper> = DemandDrivenAudioWorker(
|
|
18
|
+
queue: DispatchQueue(label: "com.mentra.wakeword.processor", qos: .userInitiated),
|
|
19
|
+
makeProcessor: { [weak self] in self?.makeSpotter() },
|
|
20
|
+
process: { [weak self] spotter, data, generation in
|
|
21
|
+
self?.process(spotter, data: data, generation: generation)
|
|
22
|
+
}
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
private init() {
|
|
26
|
+
_ = worker
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/// Enable with the model in `modelDir`, or disable and release the model. Enabling returns
|
|
30
|
+
/// once the model is loaded and `ready` has been sent; it throws when the model is missing
|
|
31
|
+
/// or fails to load, and sends no `ready` in that case.
|
|
32
|
+
func configure(enabled: Bool, modelDir requestedDir: String?) async throws {
|
|
33
|
+
guard enabled else {
|
|
34
|
+
setModelDir(nil)
|
|
35
|
+
worker.setActive(false)
|
|
36
|
+
return
|
|
37
|
+
}
|
|
38
|
+
guard let dir = requestedDir, !dir.isEmpty else {
|
|
39
|
+
throw Self.error("Wake-word model directory is required to enable detection")
|
|
40
|
+
}
|
|
41
|
+
let missing = Self.requiredModelFiles.filter {
|
|
42
|
+
!FileManager.default.fileExists(atPath: (dir as NSString).appendingPathComponent($0))
|
|
43
|
+
}
|
|
44
|
+
guard missing.isEmpty else {
|
|
45
|
+
throw Self.error("Wake-word model files are missing: \(missing.joined(separator: ", "))")
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
lock.lock()
|
|
49
|
+
let changed = modelDir != dir
|
|
50
|
+
modelDir = dir
|
|
51
|
+
lock.unlock()
|
|
52
|
+
if changed {
|
|
53
|
+
// Load the new directory even if detection was already on with another one.
|
|
54
|
+
worker.setActive(false)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// The engine retries a failed load by enabling the same directory again.
|
|
58
|
+
switch await worker.activateAndAwaitLoad() {
|
|
59
|
+
case .loaded:
|
|
60
|
+
// Send `ready` only for the detector that is still on; disabling in the meantime
|
|
61
|
+
// invalidates the generation captured here.
|
|
62
|
+
let sent = await worker.withCurrentProcessor { _, _ -> Bool in
|
|
63
|
+
Self.emit("ready")
|
|
64
|
+
return true
|
|
65
|
+
}
|
|
66
|
+
if sent != true {
|
|
67
|
+
Bridge.log("WAKE_WORD: disabled before the model finished loading")
|
|
68
|
+
}
|
|
69
|
+
case .failed:
|
|
70
|
+
throw Self.error("Could not load the wake-word model")
|
|
71
|
+
case .noDemand:
|
|
72
|
+
break // Disabled while loading.
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
func accept(_ pcm: Data) {
|
|
77
|
+
worker.accept(pcm)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private func setModelDir(_ dir: String?) {
|
|
81
|
+
lock.lock()
|
|
82
|
+
modelDir = dir
|
|
83
|
+
lock.unlock()
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/// Worker queue only.
|
|
87
|
+
private func makeSpotter() -> SherpaOnnxKeywordSpotterWrapper? {
|
|
88
|
+
lock.lock()
|
|
89
|
+
let dir = modelDir
|
|
90
|
+
lock.unlock()
|
|
91
|
+
guard let dir else { return nil }
|
|
92
|
+
let path = { (name: String) in (dir as NSString).appendingPathComponent(name) }
|
|
93
|
+
guard Self.requiredModelFiles.allSatisfy({ FileManager.default.fileExists(atPath: path($0)) }) else {
|
|
94
|
+
Bridge.log("WAKE_WORD: model files are missing in \(dir)")
|
|
95
|
+
return nil
|
|
96
|
+
}
|
|
97
|
+
let transducer = sherpaOnnxOnlineTransducerModelConfig(
|
|
98
|
+
encoder: path("encoder.int8.onnx"), decoder: path("decoder.onnx"), joiner: path("joiner.int8.onnx")
|
|
99
|
+
)
|
|
100
|
+
let model = sherpaOnnxOnlineModelConfig(tokens: path("tokens.txt"), transducer: transducer, numThreads: 1)
|
|
101
|
+
var config = sherpaOnnxKeywordSpotterConfig(featConfig: sherpaOnnxFeatureConfig(), modelConfig: model,
|
|
102
|
+
keywordsFile: path("keywords.txt"), maxActivePaths: 8, numTrailingBlanks: 1, keywordsScore: 3.0)
|
|
103
|
+
guard let spotter = SherpaOnnxKeywordSpotterWrapper(config: &config) else {
|
|
104
|
+
Bridge.log("WAKE_WORD: sherpa-onnx rejected the keyword spotter model in \(dir)")
|
|
105
|
+
return nil
|
|
106
|
+
}
|
|
107
|
+
lastDetection = 0
|
|
108
|
+
Bridge.log("WAKE_WORD: keyword spotter loaded from \(dir)")
|
|
109
|
+
return spotter
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/// Worker queue only.
|
|
113
|
+
private func process(_ spotter: SherpaOnnxKeywordSpotterWrapper, data: Data, generation: UInt64) {
|
|
114
|
+
let samples: [Float] = data.withUnsafeBytes { bytes in
|
|
115
|
+
(0 ..< (bytes.count / 2)).map { i in
|
|
116
|
+
let bits = UInt16(bytes[i * 2]) | UInt16(bytes[i * 2 + 1]) << 8
|
|
117
|
+
return Float(Int16(bitPattern: bits)) / 32768
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
spotter.acceptWaveform(samples: samples)
|
|
121
|
+
while spotter.isReady() {
|
|
122
|
+
spotter.decode()
|
|
123
|
+
if !spotter.getResult().keyword.isEmpty {
|
|
124
|
+
spotter.reset()
|
|
125
|
+
let now = Date().timeIntervalSince1970
|
|
126
|
+
if worker.isCurrent(generation), now - lastDetection >= 0.25 {
|
|
127
|
+
lastDetection = now
|
|
128
|
+
Self.emit("detected")
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
private static func error(_ message: String) -> NSError {
|
|
135
|
+
NSError(domain: "WakeWordDetector", code: 1, userInfo: [NSLocalizedDescriptionKey: message])
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private static func emit(_ kind: String) {
|
|
139
|
+
Bridge.sendTypedMessage("wake_word", body: [
|
|
140
|
+
"kind": kind,
|
|
141
|
+
"phrase": phrase,
|
|
142
|
+
"timestamp": Date().timeIntervalSince1970 * 1000,
|
|
143
|
+
])
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Settles a bounded wait exactly once, from whichever comes first: the work or the timeout.
|
|
4
|
+
final class BoundedWaitResolver<T>: @unchecked Sendable {
|
|
5
|
+
private let lock = NSLock()
|
|
6
|
+
private var continuation: CheckedContinuation<T, Never>?
|
|
7
|
+
|
|
8
|
+
fileprivate init(_ continuation: CheckedContinuation<T, Never>) {
|
|
9
|
+
self.continuation = continuation
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/// True once the wait has settled. Work that finds it settled should skip its side effects.
|
|
13
|
+
var isSettled: Bool {
|
|
14
|
+
lock.lock()
|
|
15
|
+
defer { lock.unlock() }
|
|
16
|
+
return continuation == nil
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/// Settle with `value`. Later calls are ignored.
|
|
20
|
+
func resolve(_ value: T) {
|
|
21
|
+
lock.lock()
|
|
22
|
+
let pending = continuation
|
|
23
|
+
continuation = nil
|
|
24
|
+
lock.unlock()
|
|
25
|
+
pending?.resume(returning: value)
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/// Run `start`, which must eventually call `resolve` on the resolver it receives, and settle with
|
|
30
|
+
/// `timeoutValue` if it has not done so within `timeout` seconds. Never throws.
|
|
31
|
+
func withBoundedWait<T>(
|
|
32
|
+
timeout: TimeInterval,
|
|
33
|
+
timeoutValue: T,
|
|
34
|
+
timerQueue: DispatchQueue = .global(qos: .userInitiated),
|
|
35
|
+
_ start: (BoundedWaitResolver<T>) -> Void
|
|
36
|
+
) async -> T {
|
|
37
|
+
await withCheckedContinuation { continuation in
|
|
38
|
+
let resolver = BoundedWaitResolver(continuation)
|
|
39
|
+
timerQueue.asyncAfter(deadline: .now() + timeout) {
|
|
40
|
+
resolver.resolve(timeoutValue)
|
|
41
|
+
}
|
|
42
|
+
start(resolver)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -31,6 +31,8 @@ final class DemandDrivenAudioWorker<Processor> {
|
|
|
31
31
|
private var processor: Processor?
|
|
32
32
|
private var processorGeneration: UInt64?
|
|
33
33
|
private var attemptedInitialization = false
|
|
34
|
+
/// Control operations queued behind audio; while any wait, `drain` yields after each buffer.
|
|
35
|
+
private var pendingControlOperations = 0
|
|
34
36
|
|
|
35
37
|
init(capacity: Int = 100,
|
|
36
38
|
queue: DispatchQueue = DispatchQueue(label: "com.mentra.speech.processor", qos: .userInitiated),
|
|
@@ -86,6 +88,76 @@ final class DemandDrivenAudioWorker<Processor> {
|
|
|
86
88
|
return active && generation == token
|
|
87
89
|
}
|
|
88
90
|
|
|
91
|
+
/// Outcome of the processor load for the current demand.
|
|
92
|
+
enum LoadState: Equatable {
|
|
93
|
+
/// No demand, so nothing is loaded and nothing needs to be.
|
|
94
|
+
case noDemand
|
|
95
|
+
case loaded
|
|
96
|
+
case failed
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/// Serialize control operations with inference without enabling audio demand.
|
|
100
|
+
func perform<T>(_ operation: @escaping () -> T) async -> T {
|
|
101
|
+
await withCheckedContinuation { continuation in
|
|
102
|
+
lock.lock()
|
|
103
|
+
pendingControlOperations += 1
|
|
104
|
+
lock.unlock()
|
|
105
|
+
queue.async {
|
|
106
|
+
self.lock.lock()
|
|
107
|
+
self.pendingControlOperations -= 1
|
|
108
|
+
self.lock.unlock()
|
|
109
|
+
continuation.resume(returning: operation())
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/// Run `operation` on the worker queue, after audio already queued, with the processor of the
|
|
115
|
+
/// current demand. Returns nil without running it when there is no demand or no processor.
|
|
116
|
+
func withCurrentProcessor<T>(_ operation: @escaping (Processor, UInt64) -> T) async -> T? {
|
|
117
|
+
await perform {
|
|
118
|
+
self.lock.lock()
|
|
119
|
+
let token = self.generation
|
|
120
|
+
let current = self.active && self.processorGeneration == token
|
|
121
|
+
self.lock.unlock()
|
|
122
|
+
guard current, let processor = self.processor else { return nil }
|
|
123
|
+
return operation(processor, token)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/// Wait until the processor for the current demand has been created (or failed to be).
|
|
128
|
+
/// Returns immediately when there is no demand.
|
|
129
|
+
func awaitLoad() async -> LoadState {
|
|
130
|
+
while true {
|
|
131
|
+
guard snapshot().active else { return .noDemand }
|
|
132
|
+
// A drain is already scheduled ahead of this block whenever demand changed, so
|
|
133
|
+
// the state seen here is settled unless demand changed again in the meantime.
|
|
134
|
+
let state: LoadState? = await perform {
|
|
135
|
+
self.lock.lock()
|
|
136
|
+
defer { self.lock.unlock() }
|
|
137
|
+
guard self.active else { return .noDemand }
|
|
138
|
+
guard self.processorGeneration == self.generation, self.attemptedInitialization else { return nil }
|
|
139
|
+
return self.processor == nil ? .failed : .loaded
|
|
140
|
+
}
|
|
141
|
+
if let state { return state }
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/// Reload the processor if there is demand, and wait for the result.
|
|
146
|
+
func restartAndAwaitLoad() async -> LoadState {
|
|
147
|
+
restart()
|
|
148
|
+
return await awaitLoad()
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/// Turn demand on and wait for the load. Enabling again while a failed load is cached is a
|
|
152
|
+
/// retry, so it loads once more; enabling a loaded or loading processor changes nothing.
|
|
153
|
+
func activateAndAwaitLoad() async -> LoadState {
|
|
154
|
+
let wasActive = snapshot().active
|
|
155
|
+
setActive(true)
|
|
156
|
+
let state = await awaitLoad()
|
|
157
|
+
guard state == .failed, wasActive else { return state }
|
|
158
|
+
return await restartAndAwaitLoad()
|
|
159
|
+
}
|
|
160
|
+
|
|
89
161
|
func snapshot() -> Snapshot {
|
|
90
162
|
lock.lock()
|
|
91
163
|
defer { lock.unlock() }
|
|
@@ -144,6 +216,13 @@ final class DemandDrivenAudioWorker<Processor> {
|
|
|
144
216
|
lock.lock()
|
|
145
217
|
processedBuffers &+= 1
|
|
146
218
|
processing = false
|
|
219
|
+
// When inference can't keep up, audio never runs out. Yield to a waiting control
|
|
220
|
+
// operation (a load wait, a flush) instead of starving it.
|
|
221
|
+
if pendingControlOperations > 0, !buffers.isEmpty {
|
|
222
|
+
lock.unlock()
|
|
223
|
+
queue.async { self.drain() }
|
|
224
|
+
return
|
|
225
|
+
}
|
|
147
226
|
lock.unlock()
|
|
148
227
|
}
|
|
149
228
|
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// What a loaded on-device speech model can do, decided from its files, never its folder name.
|
|
4
|
+
struct SttModelTraits: Equatable {
|
|
5
|
+
enum Kind: String {
|
|
6
|
+
/// Streaming transducer (encoder/decoder/joiner), e.g. Zipformer or Kroko.
|
|
7
|
+
case transducer
|
|
8
|
+
/// Streaming CTC (single model file).
|
|
9
|
+
case ctc
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
let kind: Kind
|
|
13
|
+
/// The vocabulary has no lowercase letters, so the model writes ALL CAPS.
|
|
14
|
+
let uppercaseOnlyVocabulary: Bool
|
|
15
|
+
|
|
16
|
+
init(kind: Kind, uppercaseOnlyVocabulary: Bool) {
|
|
17
|
+
self.kind = kind
|
|
18
|
+
self.uppercaseOnlyVocabulary = uppercaseOnlyVocabulary
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
init(kind: Kind, tokensFileContents: String) {
|
|
22
|
+
self.init(kind: kind, uppercaseOnlyVocabulary: Self.isUppercaseOnly(tokensFileContents: tokensFileContents))
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/// Any streaming transducer can end its utterance early by flushing its stream.
|
|
26
|
+
var canFinalizeEarly: Bool {
|
|
27
|
+
kind == .transducer
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/// Same rule as Android: streaming transducers get four CPU threads, other models one.
|
|
31
|
+
var numThreads: Int {
|
|
32
|
+
kind == .transducer ? 4 : 1
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// Lowercase output from a model that can only write capitals; keep everything else as the
|
|
36
|
+
/// model wrote it, including its punctuation and capitalization.
|
|
37
|
+
func format(_ text: String) -> String {
|
|
38
|
+
uppercaseOnlyVocabulary ? text.lowercased() : text
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/// `tokens.txt` holds one `<token> <id>` per line. Special tokens such as `<blk>` or `<0x41>`
|
|
42
|
+
/// are ignored. A vocabulary with capital letters and no lowercase letters is uppercase-only.
|
|
43
|
+
static func isUppercaseOnly(tokensFileContents: String) -> Bool {
|
|
44
|
+
var sawUppercase = false
|
|
45
|
+
for rawLine in tokensFileContents.split(whereSeparator: \.isNewline) {
|
|
46
|
+
let line = rawLine.trimmingCharacters(in: .whitespaces)
|
|
47
|
+
guard !line.isEmpty else { continue }
|
|
48
|
+
let token: Substring
|
|
49
|
+
if let separator = line.lastIndex(where: { $0 == " " || $0 == "\t" }) {
|
|
50
|
+
token = line[..<separator]
|
|
51
|
+
} else {
|
|
52
|
+
token = Substring(line)
|
|
53
|
+
}
|
|
54
|
+
if token.hasPrefix("<"), token.hasSuffix(">") { continue }
|
|
55
|
+
for character in token where character.isLetter {
|
|
56
|
+
if character.isLowercase { return false }
|
|
57
|
+
if character.isUppercase { sawUppercase = true }
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return sawUppercase
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
@testable import MentraBluetoothSDK
|
|
2
|
+
import XCTest
|
|
3
|
+
|
|
4
|
+
/// Keep native serialization and fragment packing; replace only the radio writes.
|
|
5
|
+
@MainActor
|
|
6
|
+
private final class BesCrashTransport: MentraLive {
|
|
7
|
+
var ready = true
|
|
8
|
+
var writes: [(Data, BleWriteTrace?)] = []
|
|
9
|
+
|
|
10
|
+
override var incidentLogTransportReady: Bool {
|
|
11
|
+
ready
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
override func queueSend(_ data: Data, id _: String, trace: BleWriteTrace?) {
|
|
15
|
+
writes.append((data, trace))
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
@MainActor
|
|
20
|
+
final class BesCrashReportTests: XCTestCase {
|
|
21
|
+
private let keyA = "ML395018B-dump-0000002a-1f2e3d4c"
|
|
22
|
+
private let keyB = "ML395018B-reset-9f3a0c1b2d4e5f60"
|
|
23
|
+
|
|
24
|
+
private func ack(_ key: String, _ reportId: String?, ok: Bool, error: String? = nil) -> [String: Any] {
|
|
25
|
+
var values: [String: Any] = ["type": "bes_crash_reported_ack", "incidentKey": key, "ok": ok]
|
|
26
|
+
if let reportId { values["reportId"] = reportId }
|
|
27
|
+
if let error { values["error"] = error }
|
|
28
|
+
return values
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
private func expectCode(_ code: String, _ body: () async throws -> Void) async -> BluetoothSdkError? {
|
|
32
|
+
do {
|
|
33
|
+
try await body()
|
|
34
|
+
XCTFail("expected \(code)")
|
|
35
|
+
return nil
|
|
36
|
+
} catch {
|
|
37
|
+
let sdkError = error as? BluetoothSdkError
|
|
38
|
+
XCTAssertEqual(sdkError?.code, code)
|
|
39
|
+
return sdkError
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
func testAckDeliveredDuringSendResolves() async throws {
|
|
44
|
+
let waiters = BesCrashReportWaiters()
|
|
45
|
+
try await waiters.report(incidentKey: keyA, reportId: "rep_1", timeoutMs: 1000) {
|
|
46
|
+
XCTAssertEqual(waiters.onAck(ack(keyA, "rep_1", ok: true)), 1)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
func testConcurrentIncidentsSettleOnlyTheirOwnCall() async throws {
|
|
51
|
+
let waiters = BesCrashReportWaiters()
|
|
52
|
+
let b = Task { @MainActor in
|
|
53
|
+
try await waiters.report(incidentKey: keyB, reportId: "rep_b", timeoutMs: 300) {}
|
|
54
|
+
}
|
|
55
|
+
try await waiters.report(incidentKey: keyA, reportId: "rep_a", timeoutMs: 1000) {
|
|
56
|
+
XCTAssertEqual(waiters.onAck(ack(keyA, "rep_a", ok: true)), 1)
|
|
57
|
+
}
|
|
58
|
+
_ = await expectCode("request_timeout") { try await b.value }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
func testStaleReportIdIsIgnored() async {
|
|
62
|
+
let waiters = BesCrashReportWaiters()
|
|
63
|
+
_ = await expectCode("request_timeout") {
|
|
64
|
+
try await waiters.report(incidentKey: keyA, reportId: "rep_new", timeoutMs: 200) {
|
|
65
|
+
XCTAssertEqual(waiters.onAck(ack(keyA, "rep_old", ok: true)), 0)
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
func testOkFalseRejectsWithGlassesError() async {
|
|
71
|
+
let waiters = BesCrashReportWaiters()
|
|
72
|
+
let error = await expectCode("bes_crash_report_rejected") {
|
|
73
|
+
try await waiters.report(incidentKey: keyA, reportId: "rep_1", timeoutMs: 1000) {
|
|
74
|
+
XCTAssertEqual(waiters.onAck(ack(keyA, "rep_1", ok: false, error: "unknown_incident")), 1)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
XCTAssertTrue(error?.message.contains("unknown_incident") == true)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
func testOkTrueWithoutReportIdDoesNotResolve() async {
|
|
81
|
+
let waiters = BesCrashReportWaiters()
|
|
82
|
+
_ = await expectCode("request_timeout") {
|
|
83
|
+
try await waiters.report(incidentKey: keyA, reportId: "rep_1", timeoutMs: 200) {
|
|
84
|
+
XCTAssertEqual(waiters.onAck(ack(keyA, nil, ok: true)), 0)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
func testDisconnectRejectsPendingCalls() async {
|
|
90
|
+
let waiters = BesCrashReportWaiters()
|
|
91
|
+
_ = await expectCode("glasses_not_connected") {
|
|
92
|
+
try await waiters.report(incidentKey: keyA, reportId: "rep_1", timeoutMs: 5000) {
|
|
93
|
+
waiters.rejectAll(BluetoothSdkError(code: "glasses_not_connected", message: "disconnected"))
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
func testSendFailureLeavesNoWaiter() async {
|
|
99
|
+
let waiters = BesCrashReportWaiters()
|
|
100
|
+
_ = await expectCode("glasses_not_connected") {
|
|
101
|
+
try await waiters.report(incidentKey: keyA, reportId: "rep_1", timeoutMs: 1000) {
|
|
102
|
+
throw BluetoothSdkError(code: "glasses_not_connected", message: "no link")
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
XCTAssertEqual(waiters.onAck(ack(keyA, "rep_1", ok: true)), 0)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
func testCommandIsQueuedWithWakeUp() throws {
|
|
109
|
+
let live = BesCrashTransport()
|
|
110
|
+
try live.sendBesCrashReported(incidentKey: keyA, reportId: "rep_01M4HBVT88DFSN8TYNZ1WTV4PB")
|
|
111
|
+
XCTAssertEqual(live.writes.compactMap { $0.1?.commandType }, ["bes_crash_reported"])
|
|
112
|
+
XCTAssertTrue(live.writes.allSatisfy { $0.1?.wakeup == true })
|
|
113
|
+
let wire = live.writes.map { String(decoding: $0.0, as: UTF8.self) }.joined()
|
|
114
|
+
XCTAssertTrue(wire.contains(keyA))
|
|
115
|
+
XCTAssertTrue(wire.contains("rep_01M4HBVT88DFSN8TYNZ1WTV4PB"))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
func testCommandRejectsWithoutLink() {
|
|
119
|
+
let live = BesCrashTransport()
|
|
120
|
+
live.ready = false
|
|
121
|
+
XCTAssertThrowsError(try live.sendBesCrashReported(incidentKey: keyA, reportId: "rep_1")) { error in
|
|
122
|
+
XCTAssertEqual((error as? BluetoothSdkError)?.code, "glasses_not_connected")
|
|
123
|
+
}
|
|
124
|
+
XCTAssertTrue(live.writes.isEmpty)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
func testDetectedEventReportsNullBeforeAReport() {
|
|
128
|
+
let event = BesCrashDetectedEvent(values: ["incidentKey": keyA, "reportId": NSNull(), "summary": ["traceGaps": 0]])
|
|
129
|
+
XCTAssertNil(event.reportId)
|
|
130
|
+
XCTAssertTrue(event.values["reportId"] is NSNull)
|
|
131
|
+
XCTAssertEqual(event.summary["traceGaps"] as? Int, 0)
|
|
132
|
+
XCTAssertEqual(BesCrashDetectedEvent(values: ["reportId": "rep_1"]).reportId, "rep_1")
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
func testRelayFileNamesAreRecognized() {
|
|
136
|
+
XCTAssertTrue(MentraLive.isIncidentRelayFileName("Brep_01m4hbvt88d"))
|
|
137
|
+
XCTAssertTrue(MentraLive.isIncidentRelayFileName("Lrep_01m4hbvt88d"))
|
|
138
|
+
for name in ["I000123456", "I000123456.jpg", "ble_1234567890", "Brep_01m4hbvt88d.json", "Xrep_01m4hbvt88d", ""] {
|
|
139
|
+
XCTAssertFalse(MentraLive.isIncidentRelayFileName(name), name)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
@@ -154,4 +154,175 @@ final class DemandDrivenAudioWorkerTests: XCTestCase {
|
|
|
154
154
|
worker.setActive(false)
|
|
155
155
|
queue.sync {}
|
|
156
156
|
}
|
|
157
|
+
|
|
158
|
+
func testControlOperationDoesNotEnableMicrophoneDemand() async {
|
|
159
|
+
let worker = DemandDrivenAudioWorker<Processor>(makeProcessor: { Processor() }, process: { _, _, _ in })
|
|
160
|
+
let prepared = await worker.perform { true }
|
|
161
|
+
XCTAssertTrue(prepared)
|
|
162
|
+
XCTAssertFalse(worker.snapshot().active)
|
|
163
|
+
XCTAssertEqual(worker.snapshot().processedBuffers, 0)
|
|
164
|
+
let ran = await worker.withCurrentProcessor { _, _ in true }
|
|
165
|
+
XCTAssertNil(ran)
|
|
166
|
+
XCTAssertFalse(worker.snapshot().initialized)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
func testCurrentProcessorOperationRunsAfterQueuedAudio() async {
|
|
170
|
+
var events = [String]()
|
|
171
|
+
let worker = DemandDrivenAudioWorker<Processor>(makeProcessor: { Processor() }, process: { _, _, _ in
|
|
172
|
+
events.append("audio")
|
|
173
|
+
})
|
|
174
|
+
worker.setActive(true)
|
|
175
|
+
worker.accept(Data([1, 0]))
|
|
176
|
+
let finished = await worker.withCurrentProcessor { _, token -> Bool in
|
|
177
|
+
events.append("flush")
|
|
178
|
+
return worker.isCurrent(token)
|
|
179
|
+
}
|
|
180
|
+
XCTAssertEqual(finished, true)
|
|
181
|
+
XCTAssertEqual(events, ["audio", "flush"])
|
|
182
|
+
worker.setActive(false)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
func testDemandEndReleasesProcessorAndNextDemandLoadsAgain() async {
|
|
186
|
+
var creations = 0
|
|
187
|
+
var releases = 0
|
|
188
|
+
let worker = DemandDrivenAudioWorker<Processor>(makeProcessor: {
|
|
189
|
+
creations += 1
|
|
190
|
+
return Processor { releases += 1 }
|
|
191
|
+
}, process: { _, _, _ in })
|
|
192
|
+
let idle = await worker.awaitLoad()
|
|
193
|
+
XCTAssertEqual(idle, .noDemand)
|
|
194
|
+
XCTAssertEqual(creations, 0)
|
|
195
|
+
|
|
196
|
+
worker.setActive(true)
|
|
197
|
+
let loaded = await worker.awaitLoad()
|
|
198
|
+
XCTAssertEqual(loaded, .loaded)
|
|
199
|
+
XCTAssertTrue(worker.snapshot().initialized)
|
|
200
|
+
XCTAssertEqual(creations, 1)
|
|
201
|
+
|
|
202
|
+
worker.setActive(false)
|
|
203
|
+
// Release is serialized on the worker queue, after which no processor is reachable.
|
|
204
|
+
let afterRelease = await worker.withCurrentProcessor { _, _ in true }
|
|
205
|
+
XCTAssertNil(afterRelease)
|
|
206
|
+
XCTAssertEqual(releases, 1)
|
|
207
|
+
XCTAssertFalse(worker.snapshot().initialized)
|
|
208
|
+
let ended = await worker.awaitLoad()
|
|
209
|
+
XCTAssertEqual(ended, .noDemand)
|
|
210
|
+
|
|
211
|
+
worker.setActive(true)
|
|
212
|
+
let reloaded = await worker.awaitLoad()
|
|
213
|
+
XCTAssertEqual(reloaded, .loaded)
|
|
214
|
+
XCTAssertEqual(creations, 2)
|
|
215
|
+
worker.setActive(false)
|
|
216
|
+
_ = await worker.perform { true }
|
|
217
|
+
XCTAssertEqual(releases, 2)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
func testRestartAndAwaitLoadReportsFailureAndSkipsLoadingWithoutDemand() async {
|
|
221
|
+
var attempts = 0
|
|
222
|
+
var succeed = true
|
|
223
|
+
let worker = DemandDrivenAudioWorker<Processor>(makeProcessor: {
|
|
224
|
+
attempts += 1
|
|
225
|
+
return succeed ? Processor() : nil
|
|
226
|
+
}, process: { _, _, _ in })
|
|
227
|
+
let withoutDemand = await worker.restartAndAwaitLoad()
|
|
228
|
+
XCTAssertEqual(withoutDemand, .noDemand)
|
|
229
|
+
_ = await worker.perform { true }
|
|
230
|
+
XCTAssertEqual(attempts, 0)
|
|
231
|
+
|
|
232
|
+
worker.setActive(true)
|
|
233
|
+
let first = await worker.awaitLoad()
|
|
234
|
+
XCTAssertEqual(first, .loaded)
|
|
235
|
+
succeed = false
|
|
236
|
+
let failed = await worker.restartAndAwaitLoad()
|
|
237
|
+
XCTAssertEqual(failed, .failed)
|
|
238
|
+
XCTAssertFalse(worker.snapshot().initialized)
|
|
239
|
+
succeed = true
|
|
240
|
+
let recovered = await worker.restartAndAwaitLoad()
|
|
241
|
+
XCTAssertEqual(recovered, .loaded)
|
|
242
|
+
XCTAssertEqual(attempts, 3)
|
|
243
|
+
worker.setActive(false)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
func testControlOperationRunsWhileAudioArrivesFasterThanInference() async {
|
|
247
|
+
let queue = DispatchQueue(label: "test.speech.slow")
|
|
248
|
+
let worker = DemandDrivenAudioWorker<Processor>(queue: queue, makeProcessor: { Processor() }, process: { _, _, _ in
|
|
249
|
+
Thread.sleep(forTimeInterval: 0.004)
|
|
250
|
+
})
|
|
251
|
+
let loaded = await worker.activateAndAwaitLoad()
|
|
252
|
+
XCTAssertEqual(loaded, .loaded)
|
|
253
|
+
|
|
254
|
+
let feeding = ManagedAtomicFlag()
|
|
255
|
+
let feeder = Thread {
|
|
256
|
+
// One buffer per millisecond against 4 ms of inference each: the queue never empties.
|
|
257
|
+
while !feeding.isSet {
|
|
258
|
+
worker.accept(Data([1]))
|
|
259
|
+
Thread.sleep(forTimeInterval: 0.001)
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
feeder.start()
|
|
263
|
+
let started = Date()
|
|
264
|
+
let ran = await worker.perform { true }
|
|
265
|
+
let waited = Date().timeIntervalSince(started)
|
|
266
|
+
feeding.set()
|
|
267
|
+
XCTAssertTrue(ran)
|
|
268
|
+
XCTAssertLessThan(waited, 1.0)
|
|
269
|
+
worker.setActive(false)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
func testEnablingAgainRetriesAFailedLoadButNotAWorkingOne() async {
|
|
273
|
+
var attempts = 0
|
|
274
|
+
var succeed = false
|
|
275
|
+
let worker = DemandDrivenAudioWorker<Processor>(makeProcessor: {
|
|
276
|
+
attempts += 1
|
|
277
|
+
return succeed ? Processor() : nil
|
|
278
|
+
}, process: { _, _, _ in })
|
|
279
|
+
let failed = await worker.activateAndAwaitLoad()
|
|
280
|
+
XCTAssertEqual(failed, .failed)
|
|
281
|
+
XCTAssertEqual(attempts, 1)
|
|
282
|
+
|
|
283
|
+
succeed = true
|
|
284
|
+
let recovered = await worker.activateAndAwaitLoad()
|
|
285
|
+
XCTAssertEqual(recovered, .loaded)
|
|
286
|
+
XCTAssertEqual(attempts, 2)
|
|
287
|
+
|
|
288
|
+
let again = await worker.activateAndAwaitLoad()
|
|
289
|
+
XCTAssertEqual(again, .loaded)
|
|
290
|
+
XCTAssertEqual(attempts, 2)
|
|
291
|
+
worker.setActive(false)
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
func testAwaitLoadWaitsForASlowLoad() async {
|
|
295
|
+
let loading = DispatchSemaphore(value: 0)
|
|
296
|
+
let release = DispatchSemaphore(value: 0)
|
|
297
|
+
let worker = DemandDrivenAudioWorker<Processor>(makeProcessor: {
|
|
298
|
+
loading.signal()
|
|
299
|
+
release.wait()
|
|
300
|
+
return Processor()
|
|
301
|
+
}, process: { _, _, _ in })
|
|
302
|
+
worker.setActive(true)
|
|
303
|
+
XCTAssertEqual(loading.wait(timeout: .now() + 2), .success)
|
|
304
|
+
XCTAssertFalse(worker.snapshot().initialized)
|
|
305
|
+
DispatchQueue.global().asyncAfter(deadline: .now() + 0.05) { release.signal() }
|
|
306
|
+
let state = await worker.awaitLoad()
|
|
307
|
+
XCTAssertEqual(state, .loaded)
|
|
308
|
+
XCTAssertTrue(worker.snapshot().initialized)
|
|
309
|
+
worker.setActive(false)
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/// A tiny thread-safe stop flag for the feeder thread.
|
|
314
|
+
private final class ManagedAtomicFlag: @unchecked Sendable {
|
|
315
|
+
private let lock = NSLock()
|
|
316
|
+
private var value = false
|
|
317
|
+
var isSet: Bool {
|
|
318
|
+
lock.lock()
|
|
319
|
+
defer { lock.unlock() }
|
|
320
|
+
return value
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
func set() {
|
|
324
|
+
lock.lock()
|
|
325
|
+
value = true
|
|
326
|
+
lock.unlock()
|
|
327
|
+
}
|
|
157
328
|
}
|