@mentra/bluetooth-sdk 3.4.0-dev.998 → 3.5.0-dev.1238

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.
Files changed (140) hide show
  1. package/README.md +33 -11
  2. package/android/build.gradle +60 -51
  3. package/android/gradle.properties +3 -0
  4. package/android/settings.gradle +47 -3
  5. package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  6. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -2
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +76 -3
  8. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +27 -0
  9. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +98 -120
  10. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +2 -1
  11. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  12. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +24 -9
  13. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  14. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +170 -23
  15. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +13 -316
  16. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +0 -35
  17. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +2 -10
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  22. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  23. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  25. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  26. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  27. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  28. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  29. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  30. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  31. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  32. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  33. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  34. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
  35. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  36. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
  37. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  38. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  39. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  40. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  41. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  42. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  43. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  44. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  45. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  46. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  47. package/build/BluetoothSdk.types.d.ts +98 -1
  48. package/build/BluetoothSdk.types.d.ts.map +1 -1
  49. package/build/BluetoothSdk.types.js.map +1 -1
  50. package/build/_private/BluetoothSdkModule.d.ts +42 -7
  51. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  52. package/build/_private/BluetoothSdkModule.js +1 -0
  53. package/build/_private/BluetoothSdkModule.js.map +1 -1
  54. package/build/generated/changelogCatalog.d.ts +4 -1
  55. package/build/generated/changelogCatalog.d.ts.map +1 -1
  56. package/build/generated/changelogCatalog.js +5 -1
  57. package/build/generated/changelogCatalog.js.map +1 -1
  58. package/build/generated/releaseMetadata.js +6 -6
  59. package/build/generated/releaseMetadata.js.map +1 -1
  60. package/build/index.d.ts +1 -1
  61. package/build/index.d.ts.map +1 -1
  62. package/build/index.js +6 -0
  63. package/build/index.js.map +1 -1
  64. package/ios/BluetoothSdkModule.swift +66 -14
  65. package/ios/MentraBluetoothSDK.podspec +4 -0
  66. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  67. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  68. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  69. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  70. package/ios/Source/DeviceManager.swift +43 -22
  71. package/ios/Source/GeneratedChangelogCatalog.swift +2 -1
  72. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  73. package/ios/Source/MentraBluetoothSDK.swift +27 -15
  74. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  75. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  76. package/ios/Source/audio/SpeechActivity.swift +277 -0
  77. package/ios/Source/events/BluetoothEvents.swift +41 -0
  78. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  79. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +5 -0
  80. package/ios/Source/sgcs/MentraLive.swift +173 -42
  81. package/ios/Source/sgcs/Nimo.swift +39 -272
  82. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +9 -38
  83. package/ios/Source/sgcs/NimoCanvasSession.swift +0 -1
  84. package/ios/Source/sgcs/SGCManager.swift +6 -0
  85. package/ios/Source/stt/STTTools.swift +13 -31
  86. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  87. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  88. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  89. package/ios/Source/utils/BoundedWait.swift +44 -0
  90. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  91. package/ios/Source/utils/SttModelTraits.swift +62 -0
  92. package/ios/Tests/BesCrashReportTests.swift +142 -0
  93. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  94. package/ios/Tests/DeviceManagerReconnectTests.swift +0 -71
  95. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +9 -3
  96. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  97. package/ios/Tests/MentraLiveAudioSetupTests.swift +6 -12
  98. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  99. package/ios/Tests/MentraLiveSessionReadinessTests.swift +179 -10
  100. package/ios/Tests/NimoCanvasTransportTests.swift +0 -89
  101. package/ios/Tests/PcmStreamTests.swift +299 -0
  102. package/ios/Tests/SpeechActivityTests.swift +238 -0
  103. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  104. package/package.json +2 -2
  105. package/plugin/build/withAndroid.js +9 -11
  106. package/plugin/build/withKotlinVersion.d.ts +2 -0
  107. package/plugin/build/withKotlinVersion.js +46 -0
  108. package/src/BluetoothSdk.types.ts +102 -1
  109. package/src/_private/BluetoothSdkModule.ts +45 -7
  110. package/src/generated/changelogCatalog.ts +5 -1
  111. package/src/generated/releaseMetadata.ts +6 -6
  112. package/src/index.ts +12 -0
  113. package/android/silero/LICENSE.md +0 -17
  114. package/android/silero/build.gradle +0 -50
  115. package/android/silero/proguard-rules.pro +0 -24
  116. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  117. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  118. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  119. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  120. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  121. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  122. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  123. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  124. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  125. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  126. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  127. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  128. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -274
  129. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  130. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  131. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -16
  132. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  133. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  134. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -851
  135. package/ios/Source/sgcs/NimoMacResourceTransport.swift +0 -217
  136. package/ios/Source/sgcs/NimoResourceFixture.swift +0 -384
  137. package/ios/Source/sgcs/NimoResourceSession.swift +0 -406
  138. package/ios/Tests/NimoResourceSessionTests.swift +0 -476
  139. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  140. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -0,0 +1,87 @@
1
+ import Foundation
2
+
3
+ /// Silero voice activity detection through sherpa-onnx, one 512-sample frame at a time.
4
+ final class SileroSpeechActivityClassifier: SpeechActivityClassifier {
5
+ /// Resource bundle declared in MentraBluetoothSDK.podspec.
6
+ private static let bundleName = "MentraSileroVad"
7
+ /// Long enough that real speech is never split. sherpa-onnx raises its threshold past this
8
+ /// to force a split, which bounds the speech it buffers during continuous noise.
9
+ private static let maxSpeechSeconds: Float = 30
10
+ private static let minSpeechSeconds: Float = 0.25
11
+ private static let threshold: Float = 0.5
12
+
13
+ private let vad: SherpaOnnxVoiceActivityDetectorWrapper
14
+
15
+ init?(modelPath: String, minSilenceMs: Int) {
16
+ guard FileManager.default.fileExists(atPath: modelPath) else {
17
+ Bridge.log("SPEECH_ACTIVITY: Silero model missing at \(modelPath)")
18
+ return nil
19
+ }
20
+ let silero = sherpaOnnxSileroVadModelConfig(
21
+ model: modelPath,
22
+ threshold: Self.threshold,
23
+ minSilenceDuration: Float(minSilenceMs) / 1000,
24
+ minSpeechDuration: Self.minSpeechSeconds,
25
+ windowSize: SpeechActivityTracker.frameSamples,
26
+ maxSpeechDuration: Self.maxSpeechSeconds
27
+ )
28
+ var config = sherpaOnnxVadModelConfig(
29
+ sileroVad: silero,
30
+ sampleRate: Int32(SpeechActivityTracker.sampleRate),
31
+ numThreads: 1
32
+ )
33
+ guard let vad = SherpaOnnxVoiceActivityDetectorWrapper(
34
+ config: &config,
35
+ buffer_size_in_seconds: Self.maxSpeechSeconds + 2
36
+ ) else {
37
+ Bridge.log("SPEECH_ACTIVITY: sherpa-onnx rejected the Silero model")
38
+ return nil
39
+ }
40
+ self.vad = vad
41
+ }
42
+
43
+ func isSpeech(afterAccepting frame: [Float]) -> Bool {
44
+ vad.acceptWaveform(samples: frame)
45
+ // Only the live state matters; drop finished segments so they don't accumulate.
46
+ while !vad.isEmpty() {
47
+ vad.pop()
48
+ }
49
+ return vad.isSpeechDetected()
50
+ }
51
+
52
+ static var bundledModelPath: String? {
53
+ let candidates = [Bundle(for: SileroSpeechActivityClassifier.self), Bundle.main]
54
+ for bundle in candidates {
55
+ if let url = bundle.url(forResource: bundleName, withExtension: "bundle"),
56
+ let resources = Bundle(url: url),
57
+ let path = resources.path(forResource: "silero_vad", ofType: "onnx")
58
+ {
59
+ return path
60
+ }
61
+ if let path = bundle.path(forResource: "silero_vad", ofType: "onnx") {
62
+ return path
63
+ }
64
+ }
65
+ return nil
66
+ }
67
+ }
68
+
69
+ extension SpeechActivityMonitor {
70
+ /// Phone-side speech activity on the microphone PCM the wake word and STT also see.
71
+ static let shared = SpeechActivityMonitor(
72
+ makeClassifier: { minSilenceMs in
73
+ guard let path = SileroSpeechActivityClassifier.bundledModelPath else {
74
+ Bridge.log("SPEECH_ACTIVITY: silero_vad.onnx is not bundled")
75
+ return nil
76
+ }
77
+ return SileroSpeechActivityClassifier(modelPath: path, minSilenceMs: minSilenceMs)
78
+ },
79
+ emit: { event in
80
+ Bridge.sendTypedMessage("speech_activity", body: [
81
+ "speaking": event.speaking,
82
+ "silentForMs": event.silentForMs,
83
+ "timestamp": event.timestamp,
84
+ ])
85
+ }
86
+ )
87
+ }
@@ -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
+ }