@mentra/bluetooth-sdk 3.4.0-dev.999 → 3.5.0-dev.1239

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
@@ -26,7 +26,6 @@ import com.mentra.bluetoothsdk.sgcs.MentraLive
26
26
  import com.mentra.bluetoothsdk.sgcs.MentraLivePairingStateStore
27
27
  import com.mentra.bluetoothsdk.sgcs.MentraNex
28
28
  import com.mentra.bluetoothsdk.sgcs.Nimo
29
- import com.mentra.bluetoothsdk.sgcs.NimoResourceDiagnostics
30
29
  import com.mentra.bluetoothsdk.sgcs.SGCManager
31
30
  import com.mentra.bluetoothsdk.sgcs.Simulated
32
31
  import com.mentra.bluetoothsdk.utils.ControllerTypes
@@ -36,7 +35,11 @@ import com.mentra.bluetoothsdk.utils.MicSourcePin
36
35
  import com.mentra.bluetoothsdk.utils.MicTypes
37
36
  import com.mentra.bluetoothsdk.utils.PhoneAudioMonitor
38
37
  import com.mentra.lc3Lib.Lc3Cpp
38
+ import com.mentra.bluetoothsdk.stt.OnDeviceRecognizerHost
39
+ import com.mentra.bluetoothsdk.stt.STTTools
39
40
  import com.mentra.bluetoothsdk.stt.SherpaOnnxTranscriber
41
+ import com.mentra.bluetoothsdk.stt.SpeechActivityDetector
42
+ import com.mentra.bluetoothsdk.stt.WakeWordDetector
40
43
  import kotlin.coroutines.resume
41
44
  import kotlinx.coroutines.suspendCancellableCoroutine
42
45
  import kotlinx.coroutines.CoroutineScope
@@ -46,6 +49,7 @@ import kotlinx.coroutines.launch
46
49
  import java.text.SimpleDateFormat
47
50
  import java.util.*
48
51
  import java.util.concurrent.CountDownLatch
52
+ import java.util.concurrent.ExecutionException
49
53
  import java.util.concurrent.ExecutorService
50
54
  import java.util.concurrent.Executors
51
55
  import java.util.concurrent.TimeUnit
@@ -165,13 +169,6 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
165
169
  get() = DeviceStore.store.get("bluetooth", "power_saving_mode") as? Boolean ?: false
166
170
  set(value) = DeviceStore.apply("bluetooth", "power_saving_mode", value)
167
171
 
168
- // Phone-side VAD gating switch. Default is OFF (VAD runs) so the
169
- // coordinator can drive per-utterance offline/online STT switching from
170
- // `vad_status` events. Set to `true` only as an emergency kill-switch.
171
- private var bypassVad: Boolean
172
- get() = DeviceStore.store.get("bluetooth", "bypass_vad") as? Boolean ?: false
173
- set(value) = DeviceStore.apply("bluetooth", "bypass_vad", value)
174
-
175
172
  private var localSttFallbackActive: Boolean
176
173
  get() = DeviceStore.store.get("bluetooth", "local_stt_fallback_active") as? Boolean ?: false
177
174
  set(value) = DeviceStore.apply("bluetooth", "local_stt_fallback_active", value)
@@ -284,13 +281,23 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
284
281
  private var micReinitRunnable: Runnable? = null
285
282
  private var systemMicAvailabilityRecheckRunnable: Runnable? = null
286
283
 
287
- // VAD
288
- private val vadBuffer = mutableListOf<ByteArray>()
289
- private var isSpeaking = false
290
- private var vadPolicy: com.mentra.bluetoothsdk.stt.VadGateSpeechPolicy? = null
291
-
292
- // STT
293
- private var transcriber: SherpaOnnxTranscriber? = null
284
+ // STT: one recognizer, loaded only while on-device transcription is in demand. Models
285
+ // load on sttLoader (never on the audio thread or under a DeviceManager lock) and are
286
+ // swapped in afterwards; see OnDeviceRecognizerHost.
287
+ private val sttLoader: ExecutorService =
288
+ Executors.newSingleThreadExecutor { runnable ->
289
+ Thread(runnable, "SttModelLoader").apply { isDaemon = true }
290
+ }
291
+ private val transcription =
292
+ OnDeviceRecognizerHost(
293
+ selection = ::selectedSttModel,
294
+ loadModel = ::loadTranscriber,
295
+ pathMatches = { transcriber, path -> transcriber.isModelLoaded(path) },
296
+ // Returns at once; the model is released on its worker after queued audio.
297
+ release = { transcriber -> transcriber.shutdown() },
298
+ loader = sttLoader,
299
+ log = { message -> Bridge.log(message) },
300
+ )
294
301
 
295
302
  // View states
296
303
  private val viewStates = mutableListOf<ViewState>()
@@ -309,7 +316,6 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
309
316
  initializeViewStates()
310
317
  if (initializeHardware) {
311
318
  initializeHardwareServices()
312
- NimoResourceDiagnostics.start(Bridge.getContext())
313
319
  }
314
320
  }
315
321
 
@@ -336,30 +342,6 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
336
342
  lc3DecoderPtr = 0
337
343
  }
338
344
 
339
- // Initialize phone-side Silero VAD. Used by handlePcm to gate audio
340
- // fan-out and to drive per-utterance offline/online STT switching
341
- // (see LocalSttFallbackCoordinator on the JS side). If a previous
342
- // policy somehow exists (re-init on hot reload), stop it first to
343
- // release the ONNX session.
344
- try {
345
- vadPolicy?.stop()
346
- val ctx = Bridge.getContext()
347
- val policy = com.mentra.bluetoothsdk.stt.VadGateSpeechPolicy(ctx)
348
- policy.init(blockSizeSamples = 512)
349
- policy.onSpeechStateChanged = { speaking ->
350
- isSpeaking = speaking
351
- Bridge.sendVoiceActivityDetectionStatus(speaking)
352
- }
353
- vadPolicy = policy
354
- Bridge.log("VadGateSpeechPolicy initialized")
355
- } catch (e: Exception) {
356
- Bridge.log("Failed to initialize VadGateSpeechPolicy: ${e.message}")
357
- vadPolicy = null
358
- } catch (e: LinkageError) {
359
- Bridge.log("Failed to initialize VadGateSpeechPolicy: ${e.message}")
360
- vadPolicy = null
361
- }
362
-
363
345
  // Mic reinit check every 10 seconds
364
346
  val micReinitR =
365
347
  object : Runnable {
@@ -966,22 +948,15 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
966
948
  // #endregion
967
949
 
968
950
  fun handlePcm(pcmData: ByteArray) {
969
- // Audio always flows. The previous phone-side Silero VAD gate was a
970
- // bandwidth-saver that ate transcripts when the mic delivered frames
971
- // not aligned to 512 samples (the case for Android AudioRecord on the
972
- // phone internal mic) and was never wired up correctly anyway —
973
- // `bypass_vad_for_debugging` was dead, cloud-side `bypass_vad` was
974
- // the only knob, and the policy double-VAD'd what the cloud already
975
- // VADs server-side. VadGateSpeechPolicy is kept around because
976
- // hardware-side VAD events from the glasses route through the same
977
- // class to fire `vad_status` (a separate signal the cloud SDK
978
- // surfaces as `session.audio.isSpeaking`).
951
+ // Audio always flows; nothing here gates it. The on-device consumers below only
952
+ // copy and queue on this (glasses or phone mic) audio thread: model loading and
953
+ // inference run on their own workers. The glasses' hardware voice detection
954
+ // (Mentra Live sr_vad -> speaking_status) is separate and unaffected.
955
+ WakeWordDetector.accept(pcmData)
956
+ SpeechActivityDetector.accept(pcmData)
979
957
  handleSendingPcm(pcmData)
980
- if (shouldSendTranscript || localSttFallbackActive) {
981
- if (ensureTranscriberInitialized()) {
982
- transcriber?.acceptAudio(pcmData)
983
- }
984
- }
958
+ // Non-null only while on-device transcription is in demand.
959
+ transcription.current?.acceptAudio(pcmData)
985
960
  }
986
961
 
987
962
  // turns a single mic on and turns off all other mics:
@@ -1382,7 +1357,6 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
1382
1357
  // MARK: - Auxiliary Commands
1383
1358
 
1384
1359
  fun initSGC(wearable: String) {
1385
- if (!NimoResourceDiagnostics.allowManagerConnect(wearable)) return
1386
1360
  Bridge.log("Initializing manager for wearable: $wearable")
1387
1361
  if (sgc != null && sgc?.type != wearable) {
1388
1362
  Bridge.log("MAN: Manager already initialized, cleaning up previous sgc")
@@ -1454,55 +1428,67 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
1454
1428
  }
1455
1429
  }
1456
1430
 
1431
+ /**
1432
+ * Finish the active recognizer's current utterance. Returns the final text once its
1433
+ * `local_transcription` event has been sent, `""` when nothing was pending, or null when
1434
+ * no streaming model is active, the loaded model can't finalize early, or the 3 s wait
1435
+ * expires. Never throws. Call from a background thread: the final event is delivered on
1436
+ * the main thread before this returns.
1437
+ */
1438
+ fun finishTranscription(): String? =
1439
+ try {
1440
+ transcription.current?.finishUtterance()
1441
+ } catch (e: Exception) {
1442
+ Bridge.log("STT: finishTranscription failed: ${e.message}")
1443
+ null
1444
+ }
1445
+
1446
+ /** Whether the active recognizer has [path] loaded. Lock-free; never waits on a load. */
1447
+ fun isSttModelLoaded(path: String): Boolean = transcription.isLoaded(path)
1448
+
1449
+ /**
1450
+ * Load the selected speech model if on-device transcription is in demand, and wait until
1451
+ * it is loaded. Returns at once when there is no demand or the model is already loaded;
1452
+ * throws when loading fails. Call from a background thread.
1453
+ */
1457
1454
  fun restartTranscriber() {
1458
1455
  Bridge.log("MAN: Restarting transcriber via command")
1459
- if (ensureTranscriberInitialized()) {
1460
- transcriber?.restart()
1456
+ try {
1457
+ transcription.restart().get()
1458
+ } catch (e: ExecutionException) {
1459
+ throw e.cause ?: e
1461
1460
  }
1462
1461
  }
1463
1462
 
1464
- private fun ensureTranscriberInitialized(): Boolean {
1465
- if (transcriber != null) return true
1466
-
1467
- return try {
1468
- val context = Bridge.getContext()
1469
- val nextTranscriber = SherpaOnnxTranscriber(context)
1470
- nextTranscriber.setTranscriptListener(
1471
- object : SherpaOnnxTranscriber.TranscriptListener {
1472
- override fun onPartialResult(text: String, language: String) {
1473
- Bridge.log("STT: Partial result: $text")
1474
- // The Sherpa model emits all-caps text; lowercase English
1475
- // output to match the rest of the pipeline (parity with iOS).
1476
- val formatted = if (language == "en-US") text.lowercase() else text
1477
- Bridge.sendLocalTranscription(formatted, false, language)
1478
- }
1463
+ private fun selectedSttModel(): OnDeviceRecognizerHost.Selection? {
1464
+ val context =
1465
+ try {
1466
+ Bridge.getContext()
1467
+ } catch (_: IllegalStateException) {
1468
+ return null
1469
+ }
1470
+ val path = STTTools.getSttModelPath(context).takeIf { it.isNotBlank() } ?: return null
1471
+ return OnDeviceRecognizerHost.Selection(path, STTTools.getSttModelLanguage(context))
1472
+ }
1473
+
1474
+ /** Runs on [sttLoader]. Throws when the model can't be loaded. */
1475
+ private fun loadTranscriber(selection: OnDeviceRecognizerHost.Selection): SherpaOnnxTranscriber {
1476
+ val next = SherpaOnnxTranscriber(Bridge.getContext(), selection.path, selection.language)
1477
+ next.setTranscriptListener(
1478
+ object : SherpaOnnxTranscriber.TranscriptListener {
1479
+ override fun onPartialResult(text: String, language: String) {
1480
+ Bridge.log("STT: Partial result: $text")
1481
+ Bridge.sendLocalTranscription(text, false, language)
1482
+ }
1479
1483
 
1480
- override fun onFinalResult(text: String, language: String) {
1481
- Bridge.log("STT: Final result: $text")
1482
- // The Sherpa model emits all-caps text; lowercase English
1483
- // output to match the rest of the pipeline (parity with iOS).
1484
- val formatted = if (language == "en-US") text.lowercase() else text
1485
- Bridge.sendLocalTranscription(formatted, true, language)
1486
- }
1484
+ override fun onFinalResult(text: String, language: String) {
1485
+ Bridge.log("STT: Final result: $text")
1486
+ Bridge.sendLocalTranscription(text, true, language)
1487
1487
  }
1488
- )
1489
- nextTranscriber.initialize()
1490
- if (!nextTranscriber.isInitialized()) {
1491
- Bridge.log("SherpaOnnxTranscriber initialize() returned without becoming ready")
1492
- return false
1493
1488
  }
1494
- transcriber = nextTranscriber
1495
- Bridge.log("SherpaOnnxTranscriber fully initialized")
1496
- true
1497
- } catch (e: Exception) {
1498
- Bridge.log("Failed to initialize SherpaOnnxTranscriber: ${e.message}")
1499
- transcriber = null
1500
- false
1501
- } catch (e: LinkageError) {
1502
- Bridge.log("Failed to initialize SherpaOnnxTranscriber: ${e.message}")
1503
- transcriber = null
1504
- false
1505
- }
1489
+ )
1490
+ next.load()
1491
+ return next
1506
1492
  }
1507
1493
 
1508
1494
  // MARK: - connection state management
@@ -2006,6 +1992,13 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2006
1992
  driver.sendIncidentId(incidentId, apiBaseUrl)
2007
1993
  }
2008
1994
 
1995
+ fun sendBesCrashReported(incidentKey: String, reportId: String) {
1996
+ val driver = sgc ?: throw BluetoothSdkException(
1997
+ "glasses_not_connected", "Cannot report the BES crash because glasses are not connected.",
1998
+ )
1999
+ driver.sendBesCrashReported(incidentKey, reportId)
2000
+ }
2001
+
2009
2002
  /** Push a notification into the glasses' own notification centre; rejects unsupported or disconnected devices. */
2010
2003
  fun sendPhoneNotification(notification: Map<String, Any>) {
2011
2004
  // Package only - never the notification text.
@@ -2304,14 +2297,9 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2304
2297
  val willSendPcm = shouldSendPcm || shouldSendLc3
2305
2298
  val willSendTranscript = shouldSendTranscript || localSttFallbackActive
2306
2299
  val nextEnabled = willSendPcm || willSendTranscript
2307
- // Tell VAD when the mic is shutting down so it doesn't get stuck in
2308
- // a stale "speaking" state and keep emitting vad_status=true after
2309
- // audio stops flowing.
2310
- if (micEnabled && !nextEnabled) {
2311
- vadPolicy?.microphoneStateChanged(false)
2312
- }
2300
+ // Load the recognizer while on-device transcription is in demand; release it when not.
2301
+ transcription.setDemand(willSendTranscript)
2313
2302
  micEnabled = nextEnabled
2314
- vadBuffer.clear()
2315
2303
  updateMicState()
2316
2304
  }
2317
2305
 
@@ -2387,7 +2375,6 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2387
2375
  }
2388
2376
 
2389
2377
  fun connectDefault() {
2390
- if (NimoResourceDiagnostics.dispatchCapturedEntry { connectDefault() }) return
2391
2378
  if (defaultWearable.isEmpty()) {
2392
2379
  Bridge.log("MAN: No default wearable, returning")
2393
2380
  return
@@ -2409,7 +2396,6 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2409
2396
  Bridge.log("MAN: connectDefault skipped — bluetooth runtime permissions not granted")
2410
2397
  return
2411
2398
  }
2412
- if (!NimoResourceDiagnostics.allowManagerConnect(defaultWearable, reconnectTarget)) return
2413
2399
  initSGC(defaultWearable)
2414
2400
  val live = sgc as? MentraLive
2415
2401
  if (live != null && MentraLivePairingStateStore.isRejected) {
@@ -2446,7 +2432,6 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2446
2432
  }
2447
2433
 
2448
2434
  fun connectByName(dName: String) {
2449
- if (NimoResourceDiagnostics.dispatchCapturedEntry { connectByName(dName) }) return
2450
2435
  Bridge.log("MAN: Connecting to wearable: $dName")
2451
2436
 
2452
2437
  var name = dName
@@ -2461,7 +2446,6 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2461
2446
  return
2462
2447
  }
2463
2448
 
2464
- if (!NimoResourceDiagnostics.allowManagerConnect(pendingWearable.ifEmpty { defaultWearable }, name)) return
2465
2449
  if (pendingWearable.isEmpty() && !defaultWearable.isEmpty()) {
2466
2450
  Bridge.log("MAN: No pending wearable, using default wearable")
2467
2451
  pendingWearable = defaultWearable
@@ -2476,11 +2460,8 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2476
2460
  return
2477
2461
  }
2478
2462
 
2479
- if (!NimoResourceDiagnostics.allowManagerConnect(pendingWearable, name)) return
2480
- if (!NimoResourceDiagnostics.preserveCapturedScan(pendingWearable, name)) {
2481
- disconnect(clearPendingIdentity = false)
2482
- Thread.sleep(100)
2483
- }
2463
+ disconnect(clearPendingIdentity = false)
2464
+ Thread.sleep(100)
2484
2465
  searching = true
2485
2466
  pendingDeviceName = name
2486
2467
 
@@ -2489,10 +2470,8 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2489
2470
  }
2490
2471
 
2491
2472
  fun connectDevice(deviceModel: String, deviceName: String) {
2492
- if (NimoResourceDiagnostics.dispatchCapturedEntry { connectDevice(deviceModel, deviceName) }) return
2493
2473
  Bridge.log("MAN: Connecting to device: $deviceModel $deviceName")
2494
2474
  if (DeviceTypes.ALL.contains(deviceModel)) {
2495
- if (!NimoResourceDiagnostics.allowManagerConnect(deviceModel, deviceName)) return
2496
2475
  pendingWearable = deviceModel
2497
2476
  initSGC(pendingWearable)
2498
2477
  sgc?.connectById(deviceName)
@@ -2698,8 +2677,6 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2698
2677
  }
2699
2678
 
2700
2679
  fun findCompatibleDevices(deviceModel: String) {
2701
- if (NimoResourceDiagnostics.dispatchCapturedEntry { findCompatibleDevices(deviceModel) }) return
2702
- if (!NimoResourceDiagnostics.allowManagerConnect(deviceModel)) return
2703
2680
  Bridge.log("MAN: Searching for compatible device names for: $deviceModel")
2704
2681
 
2705
2682
  // reset the search results:
@@ -2739,9 +2716,10 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2739
2716
  systemMicAvailabilityRecheckRunnable?.let { mainHandler.removeCallbacks(it) }
2740
2717
  systemMicAvailabilityRecheckRunnable = null
2741
2718
 
2742
- // Clean up transcriber resources
2743
- transcriber?.shutdown()
2744
- transcriber = null
2719
+ // Release on-device voice models (each on its own worker).
2720
+ transcription.setDemand(false)
2721
+ WakeWordDetector.shutdown()
2722
+ SpeechActivityDetector.shutdown()
2745
2723
 
2746
2724
  // Clean up LC3 encoder/decoder (synchronized to prevent use-after-free
2747
2725
  // if the recording thread is mid-encode/decode)
@@ -3,8 +3,9 @@ package com.mentra.bluetoothsdk
3
3
  /** Generated from /changelogs. Do not edit directly. */
4
4
  internal val GENERATED_RELEASE_CHANGELOGS: List<ReleaseChangelog> =
5
5
  listOf(
6
+ ReleaseChangelog(version = "3.5.0", markdown = "This release is under active development. User-facing changes will be documented as they land."),
6
7
  ReleaseChangelog(version = "3.4.0", markdown = "This release is under active development. User-facing changes will be documented as they land."),
7
- ReleaseChangelog(version = "3.3.0", markdown = "This release is under active development. User-facing changes will be documented as they land."),
8
+ ReleaseChangelog(version = "3.3.0", markdown = "- **Mentra Call:** Now available on iPhone, with a redesigned call screen and photo sharing during calls.\n- **Microphone:** Improved glasses microphone reliability, including after phone calls.\n- **Photos and gallery:** More reliable photo capture and gallery syncing.\n- **Glasses updates:** More reliable glasses updates, with clearer progress.\n- **Miniapps:** Miniapps now update automatically. Fixed miniapps getting stuck on loading screens.\n- **Mentra AI:** Reliability improvements and bug fixes.\n- **Notes:** Take photos with the glasses camera button, and add meeting and location details to your notes.\n- **Pairing and connections:** Improved glasses audio reconnection on Android.\n- **G1 and NIMO:** Improved text display, including accented letters.\n- **Android tablets:** The Mentra App now rotates to landscape."),
8
9
  ReleaseChangelog(version = "3.2.1", markdown = "- **Livestreamer:** \"Stream Here\" now works without a Wi-Fi network. Improved stream startup and connection reliability.\n- **Photos and gallery:** More reliable photo capture and gallery syncing.\n- **Mentra AI:** Reliability improvements and bug fixes.\n- **Miniapps:** Smoother transitions, with back buttons and gestures that take you to the previous screen inside a miniapp.\n- **Pairing and connections:** Improved G1 pairing and G2 background reconnection.\n- **Glasses updates:** Fixed repeated update checks and improved recovery after interrupted updates.\n- **Mentra Maps:** Bug fixes.\n- **NIMO:** Improved text and map layouts.\n- **Self-hosting:** Connect the Mentra App to your own self-hosted Mentra backend."),
9
10
  ReleaseChangelog(version = "3.2.0", markdown = "- Improved glasses connectivity and Wi-Fi setup.\n\n- Breaking Bluetooth SDK change: `forgetWifiNetwork(ssid)` now returns `WifiForgetResult` instead of `WifiStatusChangeEvent`. Migrate status-only consumers to the semantic `outcome`; the requested network remains `ssid`, while optional post-command connectivity is reported by `connected`, `currentSsid`, and `localIp`."),
10
11
  ReleaseChangelog(version = "3.1.1", markdown = "- Improved Google login on iOS.\n- Pairing no longer requires phone microphone access."),
@@ -2,10 +2,10 @@ package com.mentra.bluetoothsdk
2
2
 
3
3
  /** Generated by release CI. Do not edit in a release checkout. */
4
4
  internal object GeneratedReleaseMetadata {
5
- const val FAMILY_BASE_VERSION: String = "3.4.0"
6
- const val RELEASE_IDENTITY: String = "3.4.0-dev.999"
7
- const val RELEASE_SET_ID: String = "mentra-3.4.0-dev.999"
8
- const val SOURCE_COMMIT: String = "9a179e6cb8dfaebca82e4f69e6b7515130915cd8"
9
- const val OTA_MANIFEST_URL: String = "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.4.0/mentra-live-ota-3.4.0-dev.999.json"
10
- const val OTA_MANIFEST_SHA256: String = "e4112d567b31e56cd8e56bca94a83bd82fdc82e56670d51a0280b9043433dce1"
5
+ const val FAMILY_BASE_VERSION: String = "3.5.0"
6
+ const val RELEASE_IDENTITY: String = "3.5.0-dev.1239"
7
+ const val RELEASE_SET_ID: String = "mentra-3.5.0-dev.1239"
8
+ const val SOURCE_COMMIT: String = "e8aa2cac40175a5b7b1dfd1611283d81bbc7fa6a"
9
+ const val OTA_MANIFEST_URL: String = "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.5.0/mentra-live-ota-3.5.0-dev.1239.json"
10
+ const val OTA_MANIFEST_SHA256: String = "22eff2798c8bc376ca3afd708efd0eaa385b9241be8e44c07da1911be82130a4"
11
11
  }
@@ -10,7 +10,6 @@ import android.os.Handler
10
10
  import android.os.Looper
11
11
  import android.util.Log
12
12
  import com.mentra.bluetoothsdk.sgcs.MentraLive
13
- import com.mentra.bluetoothsdk.sgcs.NimoResourceDiagnostics
14
13
  import com.mentra.bluetoothsdk.streaming.StreamSessionState
15
14
  import com.mentra.bluetoothsdk.utils.ControllerTypes
16
15
  import com.mentra.bluetoothsdk.utils.PhoneAudioMonitor
@@ -95,6 +94,7 @@ class MentraBluetoothSdk private constructor(
95
94
  private var pendingHotspotStatus: PendingHotspotStatusRequest? = null
96
95
  private val hotspotMutex = Mutex()
97
96
  private var pendingVersionInfo: PendingVersionInfoRequest? = null
97
+ private val besCrashReports = BesCrashReportWaiters()
98
98
  private val wifiSessionCapabilities = WifiSessionCapabilities()
99
99
  @Volatile private var configuredOtaVersionUrl: String? = null
100
100
 
@@ -149,6 +149,7 @@ class MentraBluetoothSdk private constructor(
149
149
  private const val VIDEO_UPLOAD_STOP_TIMEOUT_MS = 10 * 60 * 1000L
150
150
  private const val STREAM_START_TIMEOUT_MS = 30_000L
151
151
  private const val STREAM_STOP_TIMEOUT_MS = 15_000L
152
+ private const val BES_CRASH_REPORTED_TIMEOUT_MS = 10_000L
152
153
  private const val OTA_BES_VERSION_WAIT_MS = 5_000L
153
154
  private const val OTA_MTK_VERSION_WAIT_MS = 2_000L
154
155
  private const val OTA_VERSION_POLL_MS = 100L
@@ -366,8 +367,6 @@ class MentraBluetoothSdk private constructor(
366
367
  }
367
368
 
368
369
  fun startScan(model: DeviceModel) {
369
- if (NimoResourceDiagnostics.dispatchCapturedEntry { startScan(model) }) return
370
- if (!NimoResourceDiagnostics.allowManagerConnect(model.deviceType)) return
371
370
  if (model != DeviceModel.SIMULATED) {
372
371
  requireBluetoothReady("scan for glasses")
373
372
  }
@@ -474,13 +473,11 @@ class MentraBluetoothSdk private constructor(
474
473
 
475
474
  @JvmOverloads
476
475
  fun connect(device: Device, options: ConnectOptions = ConnectOptions()) {
477
- if (NimoResourceDiagnostics.dispatchCapturedEntry { connect(device, options) }) return
478
- if (!NimoResourceDiagnostics.allowManagerConnect(device.model.deviceType, device.name)) return
479
476
  if (device.model != DeviceModel.SIMULATED) {
480
477
  requireBluetoothReady("connect to glasses")
481
478
  }
482
479
  val isController = ControllerTypes.ALL.contains(device.model.deviceType)
483
- if (options.cancelExistingConnectionAttempt && !NimoResourceDiagnostics.preserveCapturedScan(device.model.deviceType, device.name)) {
480
+ if (options.cancelExistingConnectionAttempt) {
484
481
  if (isController) {
485
482
  deviceManager.disconnectController()
486
483
  } else {
@@ -517,18 +514,16 @@ class MentraBluetoothSdk private constructor(
517
514
 
518
515
  @JvmOverloads
519
516
  fun connectDefault(options: ConnectOptions = ConnectOptions()) {
520
- if (NimoResourceDiagnostics.dispatchCapturedEntry { connectDefault(options) }) return
521
517
  val defaultDevice =
522
518
  currentDefaultDevice()
523
519
  ?: throw BluetoothSdkException(
524
520
  "default_device_missing",
525
521
  "Set a default glasses device before calling connectDefault.",
526
522
  )
527
- if (!NimoResourceDiagnostics.allowManagerConnect(defaultDevice.model.deviceType, defaultDevice.name)) return
528
523
  if (defaultDevice.model != DeviceModel.SIMULATED) {
529
524
  requireBluetoothReady("connect to glasses")
530
525
  }
531
- if (options.cancelExistingConnectionAttempt && !NimoResourceDiagnostics.preserveCapturedScan(defaultDevice.model.deviceType, defaultDevice.name)) {
526
+ if (options.cancelExistingConnectionAttempt) {
532
527
  cancelConnectionAttempt()
533
528
  }
534
529
  deviceManager.connectDefault()
@@ -1684,6 +1679,14 @@ class MentraBluetoothSdk private constructor(
1684
1679
  deviceManager.sendIncidentId(incidentId, apiBaseUrl)
1685
1680
  }
1686
1681
 
1682
+ /** Resolves on the glasses' matching `ok:true` ack; throws on `ok:false`, disconnect or timeout. */
1683
+ internal suspend fun sendBesCrashReported(incidentKey: String, reportId: String) {
1684
+ requireGlassesConnected("report the BES crash")
1685
+ besCrashReports.await(incidentKey, reportId, BES_CRASH_REPORTED_TIMEOUT_MS) {
1686
+ deviceManager.sendBesCrashReported(incidentKey, reportId)
1687
+ }
1688
+ }
1689
+
1687
1690
  override fun close() {
1688
1691
  resetWifiProtocolSession("", "sdk_closed")
1689
1692
  if (activityLifecycleCallbacksRegistered) {
@@ -1704,6 +1707,12 @@ class MentraBluetoothSdk private constructor(
1704
1707
  "glasses" -> {
1705
1708
  if (changes["connected"] == false) {
1706
1709
  resetWifiProtocolSession("", "wifi_session_disconnected")
1710
+ besCrashReports.rejectAll(
1711
+ BluetoothSdkException(
1712
+ "glasses_not_connected",
1713
+ "Glasses disconnected before acknowledging bes_crash_reported.",
1714
+ )
1715
+ )
1707
1716
  }
1708
1717
  analytics.observeGlassesStatus(getRawGlassesStatus(), ::isPhoneBluetoothOff)
1709
1718
  val state = getState()
@@ -2065,6 +2074,12 @@ class MentraBluetoothSdk private constructor(
2065
2074
  }
2066
2075
  dispatchToListeners { it.onOtaStatus(event) }
2067
2076
  }
2077
+ "bes_crash_detected" -> {
2078
+ val event = BesCrashDetectedEvent(data + mapOf("type" to "bes_crash_detected"))
2079
+ dispatchToListeners { it.onBesCrashDetected(event) }
2080
+ }
2081
+ // Request-scoped: consumed by the waiting sendBesCrashReported call, never a listener event.
2082
+ "bes_crash_reported_ack" -> besCrashReports.onAck(data)
2068
2083
  "mic_health" -> {
2069
2084
  dispatchToListeners { it.onMicHealth(MicHealthEvent.fromMap(data)) }
2070
2085
  }
@@ -106,6 +106,21 @@ data class OtaStatusEvent(
106
106
  }
107
107
  }
108
108
 
109
+ /** Mentra Live stored a BES crash incident; [values] is the glasses message with JSON nulls omitted. */
110
+ data class BesCrashDetectedEvent(
111
+ val values: Map<String, Any>,
112
+ ) {
113
+ val incidentKey: String get() = stringValue(values, "incidentKey").orEmpty()
114
+ val reason: String get() = stringValue(values, "reason").orEmpty()
115
+ val state: String get() = stringValue(values, "state").orEmpty()
116
+ val reportId: String? get() = stringValue(values, "reportId")?.takeIf { it.isNotEmpty() }
117
+ @Suppress("UNCHECKED_CAST")
118
+ val summary: Map<String, Any> get() = values["summary"] as? Map<String, Any> ?: emptyMap()
119
+
120
+ /** Event body for JavaScript; `reportId` is null rather than absent before a report exists. */
121
+ fun toEventMap(): Map<String, Any?> = values + ("reportId" to reportId)
122
+ }
123
+
109
124
  data class OtaQueryResult(
110
125
  val values: Map<String, Any>,
111
126
  ) {
@@ -170,6 +185,7 @@ interface MentraBluetoothSdkListener {
170
185
  fun onKeepAliveAck(event: KeepAliveAckEvent) {}
171
186
  fun onOtaStartAck(event: OtaStartAckEvent) {}
172
187
  fun onOtaStatus(event: OtaStatusEvent) {}
188
+ fun onBesCrashDetected(event: BesCrashDetectedEvent) {}
173
189
  fun onSettingsAck(event: SettingsAckEvent) {}
174
190
  fun onVersionInfo(event: VersionInfoResult) {}
175
191
  fun onMicPcm(event: MicPcmEvent) {}