@mentra/bluetooth-sdk 3.3.0-dev.944 → 3.4.0-beta.1237

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 (174) hide show
  1. package/MIGRATION.md +61 -0
  2. package/README.md +111 -11
  3. package/android/build.gradle +60 -51
  4. package/android/gradle.properties +3 -0
  5. package/android/settings.gradle +47 -3
  6. package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -2
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +89 -6
  9. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +35 -1
  10. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +159 -110
  11. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +21 -0
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +2 -1
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +35 -2
  15. package/android/src/main/java/com/mentra/bluetoothsdk/TouchGesture.kt +19 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/connection/ConnectionModels.kt +5 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicy.kt +64 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +1002 -157
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +227 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +19 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicy.kt +94 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachine.kt +411 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateStore.kt +124 -0
  25. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +54 -59
  26. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +5 -32
  27. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +8 -1
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +3 -10
  29. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  30. package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +50 -0
  31. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  32. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  33. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  34. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  35. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  36. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  38. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  39. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  40. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  41. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  42. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  43. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  44. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  45. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  46. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerOwnerLossTest.kt +146 -0
  47. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusAudioSetupTest.kt +51 -0
  48. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusClassicAudioTest.kt +2 -0
  49. package/android/src/test/java/com/mentra/bluetoothsdk/TouchGestureCommandTest.kt +112 -0
  50. package/android/src/test/java/com/mentra/bluetoothsdk/WifiAdbPeerIntentTest.kt +19 -0
  51. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicyTest.kt +65 -0
  52. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveAudioSetupReadinessTest.kt +231 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
  54. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +368 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +20 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicyTest.kt +136 -0
  58. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachineTest.kt +346 -0
  59. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
  60. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  61. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  62. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  63. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  64. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  65. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  66. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  67. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  68. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  69. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  70. package/build/BluetoothSdk.types.d.ts +207 -2
  71. package/build/BluetoothSdk.types.d.ts.map +1 -1
  72. package/build/BluetoothSdk.types.js.map +1 -1
  73. package/build/_private/BluetoothSdkModule.d.ts +45 -6
  74. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  75. package/build/_private/BluetoothSdkModule.js +2 -0
  76. package/build/_private/BluetoothSdkModule.js.map +1 -1
  77. package/build/generated/changelogCatalog.d.ts +4 -1
  78. package/build/generated/changelogCatalog.d.ts.map +1 -1
  79. package/build/generated/changelogCatalog.js +5 -1
  80. package/build/generated/changelogCatalog.js.map +1 -1
  81. package/build/generated/releaseMetadata.js +6 -6
  82. package/build/generated/releaseMetadata.js.map +1 -1
  83. package/build/index.d.ts +1 -1
  84. package/build/index.d.ts.map +1 -1
  85. package/build/index.js +10 -0
  86. package/build/index.js.map +1 -1
  87. package/ios/BluetoothSdkModule.swift +84 -12
  88. package/ios/MentraBluetoothSDK.podspec +4 -0
  89. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  90. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  91. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  92. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  93. package/ios/Source/Bridge.swift +11 -3
  94. package/ios/Source/DeviceManager.swift +135 -18
  95. package/ios/Source/DeviceStore.swift +27 -0
  96. package/ios/Source/GeneratedChangelogCatalog.swift +2 -1
  97. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  98. package/ios/Source/MentraBluetoothSDK.swift +51 -5
  99. package/ios/Source/TouchGesture.swift +13 -0
  100. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  101. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  102. package/ios/Source/audio/SpeechActivity.swift +277 -0
  103. package/ios/Source/errors/BluetoothSdkError.swift +5 -1
  104. package/ios/Source/events/BluetoothEvents.swift +45 -0
  105. package/ios/Source/internal/BleTraceLogger.swift +9 -6
  106. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  107. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +186 -0
  108. package/ios/Source/sgcs/MentraLive.swift +1366 -212
  109. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +260 -1
  110. package/ios/Source/sgcs/MentraLivePairingStateMachine.swift +385 -0
  111. package/ios/Source/sgcs/MentraLivePairingStateStore.swift +121 -0
  112. package/ios/Source/sgcs/Nimo.swift +10 -3
  113. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +39 -9
  114. package/ios/Source/sgcs/SGCManager.swift +13 -0
  115. package/ios/Source/sgcs/Simulated.swift +2 -0
  116. package/ios/Source/status/DeviceStatus.swift +35 -0
  117. package/ios/Source/stt/STTTools.swift +13 -31
  118. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  119. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  120. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  121. package/ios/Source/types/DeviceModels.swift +8 -1
  122. package/ios/Source/utils/AudioSessionMonitor.swift +158 -5
  123. package/ios/Source/utils/BoundedWait.swift +44 -0
  124. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  125. package/ios/Source/utils/SttModelTraits.swift +62 -0
  126. package/ios/Tests/BesCrashReportTests.swift +142 -0
  127. package/ios/Tests/BluetoothAudioRouteTests.swift +82 -0
  128. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  129. package/ios/Tests/DeviceManagerReconnectTests.swift +4 -2
  130. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +197 -0
  131. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  132. package/ios/Tests/MentraLiveAudioSetupTests.swift +209 -0
  133. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  134. package/ios/Tests/MentraLiveConnectionOptionsTests.swift +55 -0
  135. package/ios/Tests/MentraLivePairingAdvertisementTests.swift +327 -0
  136. package/ios/Tests/MentraLivePairingStateMachineTests.swift +402 -0
  137. package/ios/Tests/MentraLiveSessionReadinessTests.swift +497 -26
  138. package/ios/Tests/NimoCanvasTransportTests.swift +58 -0
  139. package/ios/Tests/PcmStreamTests.swift +299 -0
  140. package/ios/Tests/SpeechActivityTests.swift +238 -0
  141. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  142. package/ios/Tests/TouchGestureCommandTests.swift +87 -0
  143. package/ios/Tests/WifiAdbDispatchTests.swift +118 -0
  144. package/package.json +3 -2
  145. package/plugin/build/withAndroid.js +9 -11
  146. package/plugin/build/withKotlinVersion.d.ts +2 -0
  147. package/plugin/build/withKotlinVersion.js +46 -0
  148. package/src/BluetoothSdk.types.ts +216 -1
  149. package/src/_private/BluetoothSdkModule.ts +49 -5
  150. package/src/generated/changelogCatalog.ts +5 -1
  151. package/src/generated/releaseMetadata.ts +6 -6
  152. package/src/index.ts +24 -0
  153. package/android/silero/LICENSE.md +0 -17
  154. package/android/silero/build.gradle +0 -50
  155. package/android/silero/proguard-rules.pro +0 -24
  156. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  157. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  158. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  159. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  160. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  161. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  162. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  163. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  164. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  165. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  166. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  167. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  168. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  169. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  170. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  171. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  172. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -288
  173. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  174. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -0,0 +1,231 @@
1
+ import Foundation
2
+
3
+ /// One HTTP GET whose raw s16le mono body is written into a `PcmStreamSink` as it arrives.
4
+ ///
5
+ /// All state is touched only on the loader's serial queue, which is also the URLSession
6
+ /// delegate queue. Settles exactly once: with the played duration after the sink drained, or
7
+ /// with an error.
8
+ final class PcmUrlPlayback: @unchecked Sendable {
9
+ fileprivate let sink: PcmStreamSink
10
+ fileprivate let queue: DispatchQueue
11
+ fileprivate var task: URLSessionDataTask?
12
+ fileprivate var carry = PcmByteCarry()
13
+ fileprivate var pending = Data()
14
+ fileprivate var writing = false
15
+ fileprivate var suspended = false
16
+ fileprivate var bodyComplete = false
17
+ fileprivate var bodyError: Error?
18
+ fileprivate var closing = false
19
+ fileprivate var result: Result<Int64, Error>?
20
+ fileprivate var waiters: [CheckedContinuation<Int64, Error>] = []
21
+ fileprivate var onSettled: (() -> Void)?
22
+
23
+ /// Times the transfer was paused for backpressure. For diagnostics and tests.
24
+ private(set) var suspensions = 0
25
+
26
+ fileprivate init(sink: PcmStreamSink, queue: DispatchQueue) {
27
+ self.sink = sink
28
+ self.queue = queue
29
+ }
30
+
31
+ /// Wait for the body to finish playing. Throws `PcmStreamError.aborted` after `cancel()`.
32
+ func wait() async throws -> Int64 {
33
+ try await withCheckedThrowingContinuation { continuation in
34
+ queue.async {
35
+ if let result = self.result {
36
+ continuation.resume(with: result)
37
+ } else {
38
+ self.waiters.append(continuation)
39
+ }
40
+ }
41
+ }
42
+ }
43
+
44
+ /// Stop downloading and settle with "aborted". The caller stops the sink.
45
+ func cancel() {
46
+ queue.async {
47
+ self.settle(.failure(PcmStreamError.aborted))
48
+ }
49
+ }
50
+
51
+ // MARK: Queue only
52
+
53
+ fileprivate func settle(_ outcome: Result<Int64, Error>) {
54
+ guard result == nil else { return }
55
+ result = outcome
56
+ if let task, task.state != .completed {
57
+ task.cancel()
58
+ }
59
+ pending.removeAll()
60
+ let pendingWaiters = waiters
61
+ waiters.removeAll()
62
+ pendingWaiters.forEach { $0.resume(with: outcome) }
63
+ let callback = onSettled
64
+ onSettled = nil
65
+ callback?()
66
+ }
67
+
68
+ fileprivate func receive(_ data: Data, highWaterBytes: Int) {
69
+ guard result == nil else { return }
70
+ pending.append(carry.align(data))
71
+ if pending.count > highWaterBytes, !suspended, let task {
72
+ task.suspend()
73
+ suspended = true
74
+ suspensions += 1
75
+ }
76
+ pump()
77
+ }
78
+
79
+ fileprivate func complete(error: Error?) {
80
+ guard result == nil else { return }
81
+ bodyComplete = true
82
+ bodyError = error
83
+ // A trailing half sample left in `carry` can't be played and is dropped.
84
+ pump()
85
+ }
86
+
87
+ /// Hand pending audio to the sink one write at a time. The sink's write suspends while its
88
+ /// backlog is above its ceiling; meanwhile `pending` fills, and past the high-water mark the
89
+ /// transfer is paused until the next write takes it. Once the body is complete and
90
+ /// everything is written, close the sink.
91
+ fileprivate func pump() {
92
+ guard result == nil, !writing, !closing else { return }
93
+ if !pending.isEmpty {
94
+ let chunk = pending
95
+ pending = Data()
96
+ writing = true
97
+ if suspended, let task {
98
+ task.resume()
99
+ suspended = false
100
+ }
101
+ Task {
102
+ do {
103
+ _ = try await self.sink.write(data: chunk)
104
+ self.queue.async {
105
+ self.writing = false
106
+ self.pump()
107
+ }
108
+ } catch {
109
+ self.queue.async { self.settle(.failure(error)) }
110
+ }
111
+ }
112
+ return
113
+ }
114
+ guard bodyComplete else { return }
115
+ closing = true
116
+ let failure = bodyError
117
+ Task {
118
+ // A dropped connection still ends cleanly: what arrived plays out, then the error.
119
+ let outcome: Result<Int64, Error>
120
+ do {
121
+ let duration = try await self.sink.close()
122
+ outcome = failure.map { .failure($0) } ?? .success(duration)
123
+ } catch {
124
+ outcome = .failure(failure ?? error)
125
+ }
126
+ self.queue.async { self.settle(outcome) }
127
+ }
128
+ }
129
+ }
130
+
131
+ /// Shared URLSession for `pcmStreamPlayUrl`. Requests reuse connections, which matters when a
132
+ /// spoken answer arrives as one request per sentence.
133
+ final class PcmUrlLoader: NSObject, URLSessionDataDelegate {
134
+ static let shared = PcmUrlLoader()
135
+
136
+ /// Pause the transfer when this much audio is waiting for the sink (about 1.3 s at 24 kHz).
137
+ static let defaultHighWaterBytes = 64 * 1024
138
+
139
+ private static let compressedContentTypes = ["audio/mpeg", "audio/mp3", "audio/aac", "audio/ogg", "audio/opus", "audio/webm"]
140
+
141
+ let queue = DispatchQueue(label: "com.mentra.pcm-url", qos: .userInitiated)
142
+ private let highWaterBytes: Int
143
+ private let configuration: URLSessionConfiguration
144
+ private lazy var session: URLSession = {
145
+ let delegateQueue = OperationQueue()
146
+ delegateQueue.maxConcurrentOperationCount = 1
147
+ delegateQueue.underlyingQueue = queue
148
+ return URLSession(configuration: configuration, delegate: self, delegateQueue: delegateQueue)
149
+ }()
150
+
151
+ // Queue only.
152
+ private var playbacks: [Int: PcmUrlPlayback] = [:]
153
+
154
+ init(configuration: URLSessionConfiguration = PcmUrlLoader.defaultConfiguration(), highWaterBytes: Int = PcmUrlLoader.defaultHighWaterBytes) {
155
+ self.configuration = configuration
156
+ self.highWaterBytes = max(2, highWaterBytes)
157
+ super.init()
158
+ }
159
+
160
+ static func defaultConfiguration() -> URLSessionConfiguration {
161
+ let configuration = URLSessionConfiguration.default
162
+ configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
163
+ configuration.urlCache = nil
164
+ // Speech is useless late: fail a stalled response instead of waiting a minute.
165
+ configuration.timeoutIntervalForRequest = 20
166
+ configuration.waitsForConnectivity = false
167
+ return configuration
168
+ }
169
+
170
+ /// Start fetching `url` into `sink`. Never blocks the caller.
171
+ func start(url: URL, sink: PcmStreamSink) -> PcmUrlPlayback {
172
+ let playback = PcmUrlPlayback(sink: sink, queue: queue)
173
+ queue.async {
174
+ guard playback.result == nil else { return } // Cancelled before it started.
175
+ var request = URLRequest(url: url)
176
+ request.httpMethod = "GET"
177
+ let task = self.session.dataTask(with: request)
178
+ playback.task = task
179
+ self.playbacks[task.taskIdentifier] = playback
180
+ playback.onSettled = { [weak self] in
181
+ self?.playbacks.removeValue(forKey: task.taskIdentifier)
182
+ }
183
+ task.resume()
184
+ }
185
+ return playback
186
+ }
187
+
188
+ // MARK: URLSessionDataDelegate (on `queue`)
189
+
190
+ func urlSession(
191
+ _: URLSession,
192
+ dataTask: URLSessionDataTask,
193
+ didReceive response: URLResponse,
194
+ completionHandler: @escaping (URLSession.ResponseDisposition) -> Void
195
+ ) {
196
+ guard let playback = playbacks[dataTask.taskIdentifier] else {
197
+ completionHandler(.cancel)
198
+ return
199
+ }
200
+ if let http = response as? HTTPURLResponse, !(200 ..< 300).contains(http.statusCode) {
201
+ completionHandler(.cancel)
202
+ playback.settle(.failure(PcmStreamError.native("http_error: PCM stream request failed with HTTP \(http.statusCode)")))
203
+ return
204
+ }
205
+ if let type = response.mimeType?.lowercased(), Self.compressedContentTypes.contains(type) {
206
+ completionHandler(.cancel)
207
+ playback.settle(.failure(PcmStreamError.native("unsupported_format: PCM stream URL returned \(type), not raw PCM")))
208
+ return
209
+ }
210
+ completionHandler(.allow)
211
+ }
212
+
213
+ func urlSession(_: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
214
+ playbacks[dataTask.taskIdentifier]?.receive(data, highWaterBytes: highWaterBytes)
215
+ }
216
+
217
+ func urlSession(_: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
218
+ guard let playback = playbacks[task.taskIdentifier] else { return }
219
+ let failure = error.map { PcmStreamError.native("network_error: PCM stream download failed: \($0.localizedDescription)") as Error }
220
+ playback.complete(error: failure)
221
+ }
222
+
223
+ func urlSession(
224
+ _: URLSession,
225
+ dataTask _: URLSessionDataTask,
226
+ willCacheResponse _: CachedURLResponse,
227
+ completionHandler: @escaping (CachedURLResponse?) -> Void
228
+ ) {
229
+ completionHandler(nil)
230
+ }
231
+ }
@@ -0,0 +1,277 @@
1
+ import Foundation
2
+
3
+ /// A frame-level speech detector, e.g. Silero through sherpa-onnx.
4
+ ///
5
+ /// It owns its own hangover: once speaking, it keeps answering `true` until it has heard the
6
+ /// configured minimum silence, and it answers `false` until speech has lasted long enough.
7
+ protocol SpeechActivityClassifier: AnyObject {
8
+ /// Analyze exactly `SpeechActivityTracker.frameSamples` samples (16 kHz mono, [-1, 1]) and
9
+ /// return whether speech is detected after this frame.
10
+ func isSpeech(afterAccepting frame: [Float]) -> Bool
11
+ }
12
+
13
+ /// A reported change in phone-side speech activity.
14
+ struct SpeechActivityTransition: Equatable {
15
+ let speaking: Bool
16
+ /// 0 while speaking; on a silence transition, how long the audio has been silent.
17
+ let silentForMs: Int
18
+ }
19
+
20
+ /// Turns 16 kHz mono s16le PCM chunks of any size into 512-sample frames, checks every frame,
21
+ /// and reports transitions only. Fills gaps in incoming audio with silence in real time, because
22
+ /// Mentra Live's loudness gate stops sending audio when it's quiet.
23
+ ///
24
+ /// Not thread-safe: the caller serializes all calls.
25
+ final class SpeechActivityTracker {
26
+ static let sampleRate = 16000
27
+ static let frameSamples = 512
28
+ static let defaultMinSilenceMs = 300
29
+ /// Audio missing for this long counts as silence and is filled in.
30
+ static let gapFillAfterMs: Int64 = 100
31
+
32
+ private static let samplesPerMs = Int64(sampleRate / 1000)
33
+
34
+ let minSilenceMs: Int
35
+ private let classifier: SpeechActivityClassifier
36
+ private var frame: [Float] = []
37
+ private var carry: UInt8?
38
+ private var detecting = false
39
+ private var lastAudioAtMs: Int64?
40
+ private var gapFilledSamples: Int64 = 0
41
+
42
+ /// The last state reported. Starts silent; nothing is reported until speech is heard.
43
+ private(set) var speaking = false
44
+ /// Samples analyzed so far, real and filled. For diagnostics and tests.
45
+ private(set) var analyzedSamples: Int64 = 0
46
+ private(set) var filledSamples: Int64 = 0
47
+
48
+ init(classifier: SpeechActivityClassifier, minSilenceMs: Int = SpeechActivityTracker.defaultMinSilenceMs) {
49
+ self.classifier = classifier
50
+ self.minSilenceMs = max(0, minSilenceMs)
51
+ frame.reserveCapacity(Self.frameSamples)
52
+ }
53
+
54
+ /// Filling only matters while speech is reported or the detector still hears it; silence fed
55
+ /// to a silent detector can't produce a transition.
56
+ var needsGapFill: Bool {
57
+ lastAudioAtMs != nil && (speaking || detecting)
58
+ }
59
+
60
+ /// When the next gap-fill check is due, or nil when none is needed.
61
+ func nextGapFillDueMs(nowMs: Int64) -> Int64? {
62
+ guard needsGapFill, let lastAudioAtMs else { return nil }
63
+ let due = lastAudioAtMs + Self.gapFillAfterMs
64
+ return due > nowMs ? due : nowMs + Int64(Self.frameSamples * 1000 / Self.sampleRate)
65
+ }
66
+
67
+ func accept(_ pcm: Data, nowMs: Int64) -> [SpeechActivityTransition] {
68
+ guard !pcm.isEmpty else { return [] }
69
+ lastAudioAtMs = nowMs
70
+ gapFilledSamples = 0
71
+ var transitions: [SpeechActivityTransition] = []
72
+ pcm.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
73
+ var index = 0
74
+ if let low = carry {
75
+ appendSample(low: low, high: bytes[0], into: &transitions)
76
+ carry = nil
77
+ index = 1
78
+ }
79
+ while index + 1 < bytes.count {
80
+ appendSample(low: bytes[index], high: bytes[index + 1], into: &transitions)
81
+ index += 2
82
+ }
83
+ if index < bytes.count {
84
+ carry = bytes[index]
85
+ }
86
+ }
87
+ return transitions
88
+ }
89
+
90
+ /// Feed silence for the time no audio has arrived, once that exceeds `gapFillAfterMs`.
91
+ func fillGap(nowMs: Int64) -> [SpeechActivityTransition] {
92
+ guard let lastAudioAtMs, nowMs - lastAudioAtMs >= Self.gapFillAfterMs else { return [] }
93
+ let targetSamples = (nowMs - lastAudioAtMs) * Self.samplesPerMs
94
+ var transitions: [SpeechActivityTransition] = []
95
+ // A half-received sample is lost with the gap.
96
+ carry = nil
97
+ while needsGapFill {
98
+ let missing = Self.frameSamples - frame.count
99
+ guard gapFilledSamples + Int64(missing) <= targetSamples else { break }
100
+ frame.append(contentsOf: repeatElement(0, count: missing))
101
+ gapFilledSamples += Int64(missing)
102
+ filledSamples += Int64(missing)
103
+ analyzeFrame(into: &transitions)
104
+ }
105
+ return transitions
106
+ }
107
+
108
+ private func appendSample(low: UInt8, high: UInt8, into transitions: inout [SpeechActivityTransition]) {
109
+ frame.append(Float(Int16(bitPattern: UInt16(low) | UInt16(high) << 8)) / 32768)
110
+ if frame.count == Self.frameSamples {
111
+ analyzeFrame(into: &transitions)
112
+ }
113
+ }
114
+
115
+ private func analyzeFrame(into transitions: inout [SpeechActivityTransition]) {
116
+ detecting = classifier.isSpeech(afterAccepting: frame)
117
+ analyzedSamples += Int64(frame.count)
118
+ frame.removeAll(keepingCapacity: true)
119
+ if detecting, !speaking {
120
+ speaking = true
121
+ transitions.append(SpeechActivityTransition(speaking: true, silentForMs: 0))
122
+ } else if !detecting, speaking {
123
+ // The detector only turns off after `minSilenceMs` of silence.
124
+ speaking = false
125
+ transitions.append(SpeechActivityTransition(speaking: false, silentForMs: minSilenceMs))
126
+ }
127
+ }
128
+ }
129
+
130
+ /// Runs a `SpeechActivityTracker` on its own queue while enabled. Enabling creates the classifier
131
+ /// (loads the model); disabling drops it. Audio is accepted from any thread.
132
+ final class SpeechActivityMonitor: @unchecked Sendable {
133
+ struct Event: Equatable {
134
+ let speaking: Bool
135
+ let silentForMs: Int
136
+ /// Unix epoch milliseconds.
137
+ let timestamp: Int64
138
+ }
139
+
140
+ enum MonitorError: LocalizedError {
141
+ case modelUnavailable
142
+
143
+ var errorDescription: String? {
144
+ "Could not load the speech activity model"
145
+ }
146
+ }
147
+
148
+ private let queue: DispatchQueue
149
+ private let makeClassifier: (_ minSilenceMs: Int) -> SpeechActivityClassifier?
150
+ private let emit: (Event) -> Void
151
+ private let monotonicMs: () -> Int64
152
+ private let epochMs: () -> Int64
153
+
154
+ private let lock = NSLock()
155
+ private var enabled = false
156
+ private var generation: UInt64 = 0
157
+
158
+ // Queue only.
159
+ private var tracker: SpeechActivityTracker?
160
+ private var trackerGeneration: UInt64 = 0
161
+ private var gapCheckScheduled = false
162
+
163
+ init(
164
+ queue: DispatchQueue = DispatchQueue(label: "com.mentra.speech-activity", qos: .userInitiated),
165
+ makeClassifier: @escaping (_ minSilenceMs: Int) -> SpeechActivityClassifier?,
166
+ emit: @escaping (Event) -> Void,
167
+ monotonicMs: @escaping () -> Int64 = { Int64(ProcessInfo.processInfo.systemUptime * 1000) },
168
+ epochMs: @escaping () -> Int64 = { Int64(Date().timeIntervalSince1970 * 1000) }
169
+ ) {
170
+ self.queue = queue
171
+ self.makeClassifier = makeClassifier
172
+ self.emit = emit
173
+ self.monotonicMs = monotonicMs
174
+ self.epochMs = epochMs
175
+ }
176
+
177
+ var isEnabled: Bool {
178
+ lock.lock()
179
+ defer { lock.unlock() }
180
+ return enabled
181
+ }
182
+
183
+ /// Whether a classifier (model) is currently held. Queue-serialized; for tests.
184
+ func hasClassifier() -> Bool {
185
+ queue.sync { tracker != nil }
186
+ }
187
+
188
+ /// Enable with `minSilenceMs` (default 300), or disable and release the model. Enabling
189
+ /// again replaces the detector, so a new `minSilenceMs` takes effect. Throws when the model
190
+ /// can't be loaded.
191
+ func setEnabled(_ value: Bool, minSilenceMs: Int?) async throws {
192
+ let token = beginDemandChange(enabled: value)
193
+ let silence = max(0, minSilenceMs ?? SpeechActivityTracker.defaultMinSilenceMs)
194
+ let loaded: Bool = await withCheckedContinuation { continuation in
195
+ queue.async {
196
+ // Release before loading a replacement, so two models are never held.
197
+ self.tracker = nil
198
+ guard value, self.isCurrent(token) else {
199
+ continuation.resume(returning: true)
200
+ return
201
+ }
202
+ guard let classifier = self.makeClassifier(silence) else {
203
+ continuation.resume(returning: false)
204
+ return
205
+ }
206
+ if self.isCurrent(token) {
207
+ self.tracker = SpeechActivityTracker(classifier: classifier, minSilenceMs: silence)
208
+ self.trackerGeneration = token
209
+ }
210
+ continuation.resume(returning: true)
211
+ }
212
+ }
213
+ if !loaded {
214
+ disableIfCurrent(token)
215
+ throw MonitorError.modelUnavailable
216
+ }
217
+ }
218
+
219
+ private func beginDemandChange(enabled value: Bool) -> UInt64 {
220
+ lock.lock()
221
+ defer { lock.unlock() }
222
+ generation &+= 1
223
+ enabled = value
224
+ return generation
225
+ }
226
+
227
+ private func disableIfCurrent(_ token: UInt64) {
228
+ lock.lock()
229
+ defer { lock.unlock() }
230
+ if generation == token { enabled = false }
231
+ }
232
+
233
+ func accept(_ pcm: Data) {
234
+ guard !pcm.isEmpty, isEnabled else { return }
235
+ let now = monotonicMs()
236
+ queue.async {
237
+ guard let tracker = self.tracker, self.isCurrent(self.trackerGeneration) else { return }
238
+ self.report(tracker.accept(pcm, nowMs: now))
239
+ self.scheduleGapCheck()
240
+ }
241
+ }
242
+
243
+ /// Run the gap-fill check now. Queue-serialized; for tests.
244
+ func checkGapNow() {
245
+ queue.sync {
246
+ guard let tracker = self.tracker else { return }
247
+ self.report(tracker.fillGap(nowMs: self.monotonicMs()))
248
+ }
249
+ }
250
+
251
+ private func isCurrent(_ token: UInt64) -> Bool {
252
+ lock.lock()
253
+ defer { lock.unlock() }
254
+ return enabled && generation == token
255
+ }
256
+
257
+ /// Queue only. At most one check is pending; it always works on the current tracker.
258
+ private func scheduleGapCheck() {
259
+ guard !gapCheckScheduled, let tracker, let due = tracker.nextGapFillDueMs(nowMs: monotonicMs()) else { return }
260
+ gapCheckScheduled = true
261
+ let delayMs = max(1, due - monotonicMs())
262
+ queue.asyncAfter(deadline: .now() + .milliseconds(Int(delayMs))) { [weak self] in
263
+ guard let self else { return }
264
+ self.gapCheckScheduled = false
265
+ guard let current = self.tracker, self.isCurrent(self.trackerGeneration) else { return }
266
+ self.report(current.fillGap(nowMs: self.monotonicMs()))
267
+ self.scheduleGapCheck()
268
+ }
269
+ }
270
+
271
+ /// Queue only.
272
+ private func report(_ transitions: [SpeechActivityTransition]) {
273
+ for transition in transitions {
274
+ emit(Event(speaking: transition.speaking, silentForMs: transition.silentForMs, timestamp: epochMs()))
275
+ }
276
+ }
277
+ }
@@ -3,10 +3,14 @@ import Foundation
3
3
  public struct BluetoothSdkError: Error, LocalizedError, CustomStringConvertible {
4
4
  public let code: String
5
5
  public let message: String
6
+ /// Machine-readable reason a `pair_failure` carries (`pair_failure.code`), such as
7
+ /// `ios_forget_pairing`. Nil for other errors.
8
+ public let failureCode: String?
6
9
 
7
- public init(code: String, message: String) {
10
+ public init(code: String, message: String, failureCode: String? = nil) {
8
11
  self.code = code
9
12
  self.message = message
13
+ self.failureCode = failureCode
10
14
  }
11
15
 
12
16
  public var errorDescription: String? {
@@ -143,6 +143,44 @@ public struct OtaStatusEvent: CustomStringConvertible {
143
143
  }
144
144
  }
145
145
 
146
+ /// Mentra Live stored a BES crash incident; `values` is the glasses message unchanged.
147
+ public struct BesCrashDetectedEvent: CustomStringConvertible {
148
+ public let values: [String: Any]
149
+
150
+ public init(values: [String: Any]) {
151
+ var values = values
152
+ // JavaScript sees null, not undefined, before the incident has a report.
153
+ if stringValue(values, "reportId")?.isEmpty ?? true {
154
+ values["reportId"] = NSNull()
155
+ }
156
+ self.values = values
157
+ }
158
+
159
+ public var incidentKey: String {
160
+ stringValue(values, "incidentKey") ?? ""
161
+ }
162
+
163
+ public var reason: String {
164
+ stringValue(values, "reason") ?? ""
165
+ }
166
+
167
+ public var state: String {
168
+ stringValue(values, "state") ?? ""
169
+ }
170
+
171
+ public var reportId: String? {
172
+ stringValue(values, "reportId")
173
+ }
174
+
175
+ public var summary: [String: Any] {
176
+ values["summary"] as? [String: Any] ?? [:]
177
+ }
178
+
179
+ public var description: String {
180
+ "BesCrashDetectedEvent(incidentKey: \(incidentKey), state: \(state))"
181
+ }
182
+ }
183
+
146
184
  public struct OtaQueryResult: CustomStringConvertible {
147
185
  public let values: [String: Any]
148
186
 
@@ -174,6 +212,10 @@ public struct SettingsAckEvent: CustomStringConvertible {
174
212
  stringValue(values, "requestId") ?? ""
175
213
  }
176
214
 
215
+ public var gesture: TouchGesture? {
216
+ stringValue(values, "gesture").flatMap(TouchGesture.init(rawValue:))
217
+ }
218
+
177
219
  public var setting: String {
178
220
  stringValue(values, "setting") ?? ""
179
221
  }
@@ -269,6 +311,7 @@ public enum BluetoothEvent: CustomStringConvertible {
269
311
  case keepAliveAck(KeepAliveAckEvent)
270
312
  case otaStartAck(OtaStartAckEvent)
271
313
  case otaStatus(OtaStatusEvent)
314
+ case besCrashDetected(BesCrashDetectedEvent)
272
315
  case settingsAck(SettingsAckEvent)
273
316
  case versionInfo(VersionInfoResult)
274
317
  case localTranscription(LocalTranscriptionEvent)
@@ -312,6 +355,8 @@ public enum BluetoothEvent: CustomStringConvertible {
312
355
  event.description
313
356
  case let .otaStatus(event):
314
357
  event.description
358
+ case let .besCrashDetected(event):
359
+ event.description
315
360
  case let .settingsAck(event):
316
361
  event.description
317
362
  case let .versionInfo(event):
@@ -17,7 +17,8 @@ enum BleTraceLogger {
17
17
  bytes: Int? = nil,
18
18
  sourceFile: String = #fileID,
19
19
  sourceFunction: String = #function,
20
- sourceLine: Int = #line
20
+ sourceLine: Int = #line,
21
+ forwardToBridge: Bool = true
21
22
  ) {
22
23
  guard let payload else {
23
24
  emit(format(
@@ -27,7 +28,7 @@ enum BleTraceLogger {
27
28
  type: "null",
28
29
  bytes: bytes,
29
30
  payload: "null"
30
- ))
31
+ ), forwardToBridge: forwardToBridge)
31
32
  return
32
33
  }
33
34
 
@@ -39,7 +40,7 @@ enum BleTraceLogger {
39
40
  type: extractType(from: payload),
40
41
  bytes: bytes,
41
42
  payload: jsonString(sanitized)
42
- ))
43
+ ), forwardToBridge: forwardToBridge)
43
44
  }
44
45
 
45
46
  static func logMap(
@@ -50,7 +51,8 @@ enum BleTraceLogger {
50
51
  bytes: Int? = nil,
51
52
  sourceFile: String = #fileID,
52
53
  sourceFunction: String = #function,
53
- sourceLine: Int = #line
54
+ sourceLine: Int = #line,
55
+ forwardToBridge: Bool = true
54
56
  ) {
55
57
  let sanitized = sanitizeDictionary(payload)
56
58
  emit(format(
@@ -60,7 +62,7 @@ enum BleTraceLogger {
60
62
  type: type ?? extractType(from: sanitized),
61
63
  bytes: bytes,
62
64
  payload: jsonString(sanitized)
63
- ))
65
+ ), forwardToBridge: forwardToBridge)
64
66
  }
65
67
 
66
68
  static func logLifecycle(component: String, event: String, extra: [String: Any] = [:]) {
@@ -82,8 +84,9 @@ enum BleTraceLogger {
82
84
  logMap(direction: "phone_app", layer: "app_lifecycle", type: event, payload: payload)
83
85
  }
84
86
 
85
- private static func emit(_ line: String) {
87
+ private static func emit(_ line: String, forwardToBridge: Bool = true) {
86
88
  os_log("%{public}@", log: log, type: .info, line)
89
+ guard forwardToBridge else { return }
87
90
  // Log events are excluded from tracing in Bridge, so forwarding a trace
88
91
  // cannot recursively generate another trace.
89
92
  Bridge.sendTypedMessage("log", body: ["message": line])