@mentra/bluetooth-sdk 3.4.0-dev.1166 → 3.4.0-dev.1170

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 (79) hide show
  1. package/android/build.gradle +6 -36
  2. package/android/settings.gradle +1 -4
  3. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +61 -3
  4. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +27 -0
  5. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +89 -104
  6. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
  7. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  8. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  9. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  10. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  11. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  12. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  13. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  14. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  15. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  17. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  18. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  19. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  20. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  21. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  22. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  23. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  24. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  25. package/build/BluetoothSdk.types.d.ts +49 -0
  26. package/build/BluetoothSdk.types.d.ts.map +1 -1
  27. package/build/BluetoothSdk.types.js.map +1 -1
  28. package/build/_private/BluetoothSdkModule.d.ts +31 -4
  29. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  30. package/build/_private/BluetoothSdkModule.js.map +1 -1
  31. package/build/generated/releaseMetadata.js +5 -5
  32. package/build/generated/releaseMetadata.js.map +1 -1
  33. package/build/index.d.ts +1 -1
  34. package/build/index.d.ts.map +1 -1
  35. package/build/index.js +5 -0
  36. package/build/index.js.map +1 -1
  37. package/ios/BluetoothSdkModule.swift +58 -8
  38. package/ios/MentraBluetoothSDK.podspec +4 -0
  39. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  40. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  41. package/ios/Source/BluetoothSdkDefaults.swift +1 -1
  42. package/ios/Source/DeviceManager.swift +30 -12
  43. package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
  44. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  45. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  46. package/ios/Source/audio/SpeechActivity.swift +277 -0
  47. package/ios/Source/stt/STTTools.swift +13 -31
  48. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  49. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  50. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  51. package/ios/Source/utils/BoundedWait.swift +44 -0
  52. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  53. package/ios/Source/utils/SttModelTraits.swift +62 -0
  54. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  55. package/ios/Tests/PcmStreamTests.swift +299 -0
  56. package/ios/Tests/SpeechActivityTests.swift +238 -0
  57. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  58. package/package.json +2 -2
  59. package/plugin/build/withAndroid.js +7 -11
  60. package/src/BluetoothSdk.types.ts +49 -0
  61. package/src/_private/BluetoothSdkModule.ts +33 -4
  62. package/src/generated/releaseMetadata.ts +5 -5
  63. package/src/index.ts +7 -0
  64. package/android/silero/LICENSE.md +0 -17
  65. package/android/silero/build.gradle +0 -50
  66. package/android/silero/proguard-rules.pro +0 -24
  67. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  68. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  69. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  70. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  71. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  72. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  73. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  74. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  75. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  76. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  77. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  78. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  79. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -95,7 +95,7 @@ if (!sherpaOnnxAar.exists()) {
95
95
  }
96
96
 
97
97
  // Minimal POM so the Maven resolver is happy. No transitive deps — the AAR
98
- // ships its own native libs and we already pin onnxruntime separately below.
98
+ // ships its own native libs, including its own libonnxruntime.so.
99
99
  if (!sherpaOnnxPom.exists()) {
100
100
  sherpaOnnxPom.text = """<?xml version="1.0" encoding="UTF-8"?>
101
101
  <project xmlns="http://maven.apache.org/POM/4.0.0">
@@ -347,28 +347,18 @@ dependencies {
347
347
  // Maven Central/Google repositories for normal SDK use.
348
348
  def optionalMentraOsIntegrationDependency = publicMavenSdk ? 'compileOnly' : 'implementation'
349
349
 
350
- // Sherpa-ONNX for local transcription. Jitpack's v1.13.2 build failed
351
- // upstream, so we stage the prebuilt AAR into libs/maven/ (see top of file)
352
- // and consume it as a Maven coord — AGP rejects raw files() .aar deps in
353
- // library modules.
350
+ // Sherpa-ONNX for on-device transcription, the wake word and Silero speech
351
+ // activity (com.k2fsa.sherpa.onnx.Vad, model in src/main/assets/vad/).
352
+ // Jitpack's v1.13.2 build failed upstream, so we stage the prebuilt AAR into
353
+ // libs/maven/ (see top of file) and consume it as a Maven coord — AGP rejects
354
+ // raw files() .aar deps in library modules.
354
355
  dependencies.add(optionalMentraOsIntegrationDependency, "${sherpaOnnxGroup}:${sherpaOnnxArtifact}:${sherpaOnnxVersion}@aar")
355
356
 
356
357
  if (!publicMavenSdk) {
357
- // Silero VAD — vendored source under silero/, wired as :silero
358
- // sub-project (see settings.gradle). This replaces the previous Jitpack AAR
359
- // (com.github.gkonovalov:android-vad:2.0.9) whose prebuilt JNI was bound to
360
- // an ORT version incompatible with the one bundled by sherpa-onnx, causing a
361
- // dlopen UnsatisfiedLinkError for OrtGetApiBase at VAD startup. By owning the
362
- // source we control both the Java API surface and the ORT version it links
363
- // against; today both consumers (Silero VAD and sherpa-onnx) load their own
364
- // libonnxruntime.so — see packagingOptions pickFirst above.
365
- implementation project(':silero')
366
-
367
358
  // Vuzix Z100
368
359
  implementation 'com.vuzix:ultralite-sdk-android:1.8'
369
360
  implementation 'com.squareup.picasso:picasso:2.8'
370
361
  } else {
371
- compileOnly project(':silero')
372
362
  compileOnly 'com.vuzix:ultralite-sdk-android:1.8'
373
363
  compileOnly 'com.squareup.picasso:picasso:2.8'
374
364
  }
@@ -377,26 +367,6 @@ dependencies {
377
367
  implementation 'com.google.protobuf:protobuf-java-util:4.32.0'
378
368
  }
379
369
 
380
- // Pin onnxruntime-android to 1.24.3 — the version sherpa-onnx 1.13.2 was built
381
- // against (its libonnxruntime.so exports OrtGetApiBase@@VERS_1.24.3). Matching
382
- // this lets the :silero VAD module share a single libonnxruntime.so with
383
- // sherpa-onnx, resolving the ELF symbol-versioning conflict that crashed VAD
384
- // startup on previous mismatched versions.
385
- configurations.all {
386
- resolutionStrategy {
387
- eachDependency { DependencyResolveDetails details ->
388
- if (details.requested.group == 'com.microsoft.onnxruntime') {
389
- details.useVersion '1.24.3'
390
- details.because('Match sherpa-onnx 1.13.2 ORT 1.24.3')
391
- }
392
- if (details.requested.name == 'onnxruntime-android') {
393
- details.useVersion '1.24.3'
394
- details.because('Match sherpa-onnx 1.13.2 ORT 1.24.3')
395
- }
396
- }
397
- }
398
- }
399
-
400
370
  afterEvaluate {
401
371
  publishing {
402
372
  publications {
@@ -5,7 +5,7 @@
5
5
  // with com.mentraglass:bluetooth-sdk substituted by project(":").
6
6
  // The MentraOS app (an Expo host) ignores this file: Expo autolinking adds this
7
7
  // directory as :mentra-bluetooth-sdk, and the SDK's config plugin adds :lc3Lib
8
- // and :silero to the host's own settings.gradle.
8
+ // to the host's own settings.gradle.
9
9
 
10
10
  gradle.rootProject { project ->
11
11
  // Same versions as the MentraOS app's generated Android project. AGP refuses
@@ -46,6 +46,3 @@ gradle.beforeProject { project ->
46
46
  rootProject.name = 'mentra-bluetooth-sdk'
47
47
 
48
48
  include ':lc3Lib'
49
-
50
- include ':silero'
51
- project(':silero').projectDir = new File(rootDir, 'silero')
@@ -355,6 +355,8 @@ class BluetoothSdkModule : Module() {
355
355
  "speaking_status",
356
356
  "battery_status",
357
357
  "local_transcription",
358
+ "wake_word",
359
+ "speech_activity",
358
360
  "wifi_status_change",
359
361
  "wifi_scan_result",
360
362
  "wifi_forget_result",
@@ -894,13 +896,42 @@ class BluetoothSdkModule : Module() {
894
896
  sdk?.setMicSourcePin(source)
895
897
  }
896
898
 
897
- // Runs on Dispatchers.IO, not the shared Expo AsyncFunctionQueue: restart()
898
- // does a synchronous JNI model reload that would otherwise block every other
899
- // native call in the app until it completes.
899
+ // MARK: - On-device voice
900
+ //
901
+ // Everything that can wait on a model load or a worker runs on Dispatchers.IO,
902
+ // never on the shared Expo AsyncFunctionQueue, which every other native call
903
+ // (and every miniapp) waits behind.
904
+
905
+ AsyncFunction("setWakeWordDetection") Coroutine { enabled: Boolean, modelDir: String? ->
906
+ withContext(Dispatchers.IO) {
907
+ com.mentra.bluetoothsdk.stt.WakeWordDetector.configure(enabled, modelDir)
908
+ }
909
+ }
910
+
911
+ // Lock-free: never waits on a model load.
912
+ AsyncFunction("isSttModelLoaded") { path: String ->
913
+ deviceManager?.isSttModelLoaded(path) ?: false
914
+ }
915
+
916
+ // Resolves with the final text, "" when nothing was pending, or null when no
917
+ // streaming model is active, the model can't finalize early, or after 3 s.
918
+ AsyncFunction("finishTranscription") Coroutine { ->
919
+ withContext(Dispatchers.IO) { deviceManager?.finishTranscription() }
920
+ }
921
+
900
922
  AsyncFunction("restartTranscriber") Coroutine { ->
901
923
  withContext(Dispatchers.IO) { deviceManager?.restartTranscriber() }
902
924
  }
903
925
 
926
+ AsyncFunction("setSpeechActivityDetection") Coroutine { enabled: Boolean, options: Map<String, Any?>? ->
927
+ val minSilenceMs =
928
+ (options?.get("minSilenceMs") as? Number)?.toInt()
929
+ ?: com.mentra.bluetoothsdk.stt.SpeechActivityEngine.DEFAULT_MIN_SILENCE_MS
930
+ withContext(Dispatchers.IO) {
931
+ com.mentra.bluetoothsdk.stt.SpeechActivityDetector.configure(enabled, minSilenceMs)
932
+ }
933
+ }
934
+
904
935
  // MARK: - Audio Playback Monitoring
905
936
 
906
937
  SdkAsyncFunction("setOwnAppAudioPlaying") { playing: Boolean ->
@@ -942,6 +973,33 @@ class BluetoothSdkModule : Module() {
942
973
  PcmStreamManager.abort(streamId)
943
974
  }
944
975
 
976
+ // Native HTTP GET of raw s16le mono PCM, played as it arrives. Blocks a
977
+ // Dispatchers.IO thread (never the shared queue) until the body has played.
978
+ AsyncFunction("pcmStreamPlayUrl") Coroutine {
979
+ streamId: String,
980
+ url: String,
981
+ sampleRate: Int,
982
+ volume: Double,
983
+ jitterMs: Int?,
984
+ ->
985
+ withContext(Dispatchers.IO) {
986
+ try {
987
+ mapOf(
988
+ "durationMs" to
989
+ PcmStreamManager.playUrl(
990
+ streamId,
991
+ url,
992
+ sampleRate,
993
+ volume.toFloat(),
994
+ jitterMs,
995
+ )
996
+ )
997
+ } catch (error: com.mentra.bluetoothsdk.utils.audio.PcmUrlPlaybackException) {
998
+ throw CodedException(error.code, error.message ?: error.code, error)
999
+ }
1000
+ }
1001
+ }
1002
+
945
1003
  // *Blocking on Dispatchers.IO, not the shared AsyncFunctionQueue: these wait on
946
1004
  // a CountDownLatch (up to 5s) for a BLE round-trip, which would otherwise stall
947
1005
  // every other native call queued behind them.
@@ -255,6 +255,33 @@ public class Bridge private constructor() {
255
255
  sendTypedMessage("speaking_status", body as Map<String, Any>)
256
256
  }
257
257
 
258
+ /**
259
+ * Send a phone-side speech activity transition from the on-device Silero detector.
260
+ * [silentForMs] is 0 while speaking; on a silence transition, how long it has been quiet.
261
+ */
262
+ @JvmStatic
263
+ fun sendSpeechActivity(speaking: Boolean, silentForMs: Long) {
264
+ val body = HashMap<String, Any>()
265
+ body["speaking"] = speaking
266
+ body["silentForMs"] = silentForMs
267
+ body["timestamp"] = System.currentTimeMillis()
268
+ sendTypedMessage("speech_activity", body as Map<String, Any>)
269
+ }
270
+
271
+ /**
272
+ * Send on-device keyword spotter state or a detection. [kind] is "loading", "ready",
273
+ * "detected" or "error"; it describes only the wake-word model.
274
+ */
275
+ @JvmStatic
276
+ fun sendWakeWord(kind: String, phrase: String, message: String? = null) {
277
+ val body = HashMap<String, Any>()
278
+ body["kind"] = kind
279
+ body["phrase"] = phrase
280
+ body["timestamp"] = System.currentTimeMillis()
281
+ if (message != null) body["message"] = message
282
+ sendTypedMessage("wake_word", body as Map<String, Any>)
283
+ }
284
+
258
285
  /** Send battery status */
259
286
  @JvmStatic
260
287
  fun sendBatteryStatus(level: Int, charging: Boolean) {
@@ -36,7 +36,11 @@ import com.mentra.bluetoothsdk.utils.MicSourcePin
36
36
  import com.mentra.bluetoothsdk.utils.MicTypes
37
37
  import com.mentra.bluetoothsdk.utils.PhoneAudioMonitor
38
38
  import com.mentra.lc3Lib.Lc3Cpp
39
+ import com.mentra.bluetoothsdk.stt.OnDeviceRecognizerHost
40
+ import com.mentra.bluetoothsdk.stt.STTTools
39
41
  import com.mentra.bluetoothsdk.stt.SherpaOnnxTranscriber
42
+ import com.mentra.bluetoothsdk.stt.SpeechActivityDetector
43
+ import com.mentra.bluetoothsdk.stt.WakeWordDetector
40
44
  import kotlin.coroutines.resume
41
45
  import kotlinx.coroutines.suspendCancellableCoroutine
42
46
  import kotlinx.coroutines.CoroutineScope
@@ -46,6 +50,7 @@ import kotlinx.coroutines.launch
46
50
  import java.text.SimpleDateFormat
47
51
  import java.util.*
48
52
  import java.util.concurrent.CountDownLatch
53
+ import java.util.concurrent.ExecutionException
49
54
  import java.util.concurrent.ExecutorService
50
55
  import java.util.concurrent.Executors
51
56
  import java.util.concurrent.TimeUnit
@@ -165,13 +170,6 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
165
170
  get() = DeviceStore.store.get("bluetooth", "power_saving_mode") as? Boolean ?: false
166
171
  set(value) = DeviceStore.apply("bluetooth", "power_saving_mode", value)
167
172
 
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
173
  private var localSttFallbackActive: Boolean
176
174
  get() = DeviceStore.store.get("bluetooth", "local_stt_fallback_active") as? Boolean ?: false
177
175
  set(value) = DeviceStore.apply("bluetooth", "local_stt_fallback_active", value)
@@ -284,13 +282,23 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
284
282
  private var micReinitRunnable: Runnable? = null
285
283
  private var systemMicAvailabilityRecheckRunnable: Runnable? = null
286
284
 
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
285
+ // STT: one recognizer, loaded only while on-device transcription is in demand. Models
286
+ // load on sttLoader (never on the audio thread or under a DeviceManager lock) and are
287
+ // swapped in afterwards; see OnDeviceRecognizerHost.
288
+ private val sttLoader: ExecutorService =
289
+ Executors.newSingleThreadExecutor { runnable ->
290
+ Thread(runnable, "SttModelLoader").apply { isDaemon = true }
291
+ }
292
+ private val transcription =
293
+ OnDeviceRecognizerHost(
294
+ selection = ::selectedSttModel,
295
+ loadModel = ::loadTranscriber,
296
+ pathMatches = { transcriber, path -> transcriber.isModelLoaded(path) },
297
+ // Returns at once; the model is released on its worker after queued audio.
298
+ release = { transcriber -> transcriber.shutdown() },
299
+ loader = sttLoader,
300
+ log = { message -> Bridge.log(message) },
301
+ )
294
302
 
295
303
  // View states
296
304
  private val viewStates = mutableListOf<ViewState>()
@@ -336,30 +344,6 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
336
344
  lc3DecoderPtr = 0
337
345
  }
338
346
 
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
347
  // Mic reinit check every 10 seconds
364
348
  val micReinitR =
365
349
  object : Runnable {
@@ -966,22 +950,15 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
966
950
  // #endregion
967
951
 
968
952
  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`).
953
+ // Audio always flows; nothing here gates it. The on-device consumers below only
954
+ // copy and queue on this (glasses or phone mic) audio thread: model loading and
955
+ // inference run on their own workers. The glasses' hardware voice detection
956
+ // (Mentra Live sr_vad -> speaking_status) is separate and unaffected.
957
+ WakeWordDetector.accept(pcmData)
958
+ SpeechActivityDetector.accept(pcmData)
979
959
  handleSendingPcm(pcmData)
980
- if (shouldSendTranscript || localSttFallbackActive) {
981
- if (ensureTranscriberInitialized()) {
982
- transcriber?.acceptAudio(pcmData)
983
- }
984
- }
960
+ // Non-null only while on-device transcription is in demand.
961
+ transcription.current?.acceptAudio(pcmData)
985
962
  }
986
963
 
987
964
  // turns a single mic on and turns off all other mics:
@@ -1454,55 +1431,67 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
1454
1431
  }
1455
1432
  }
1456
1433
 
1434
+ /**
1435
+ * Finish the active recognizer's current utterance. Returns the final text once its
1436
+ * `local_transcription` event has been sent, `""` when nothing was pending, or null when
1437
+ * no streaming model is active, the loaded model can't finalize early, or the 3 s wait
1438
+ * expires. Never throws. Call from a background thread: the final event is delivered on
1439
+ * the main thread before this returns.
1440
+ */
1441
+ fun finishTranscription(): String? =
1442
+ try {
1443
+ transcription.current?.finishUtterance()
1444
+ } catch (e: Exception) {
1445
+ Bridge.log("STT: finishTranscription failed: ${e.message}")
1446
+ null
1447
+ }
1448
+
1449
+ /** Whether the active recognizer has [path] loaded. Lock-free; never waits on a load. */
1450
+ fun isSttModelLoaded(path: String): Boolean = transcription.isLoaded(path)
1451
+
1452
+ /**
1453
+ * Load the selected speech model if on-device transcription is in demand, and wait until
1454
+ * it is loaded. Returns at once when there is no demand or the model is already loaded;
1455
+ * throws when loading fails. Call from a background thread.
1456
+ */
1457
1457
  fun restartTranscriber() {
1458
1458
  Bridge.log("MAN: Restarting transcriber via command")
1459
- if (ensureTranscriberInitialized()) {
1460
- transcriber?.restart()
1459
+ try {
1460
+ transcription.restart().get()
1461
+ } catch (e: ExecutionException) {
1462
+ throw e.cause ?: e
1461
1463
  }
1462
1464
  }
1463
1465
 
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
- }
1466
+ private fun selectedSttModel(): OnDeviceRecognizerHost.Selection? {
1467
+ val context =
1468
+ try {
1469
+ Bridge.getContext()
1470
+ } catch (_: IllegalStateException) {
1471
+ return null
1472
+ }
1473
+ val path = STTTools.getSttModelPath(context).takeIf { it.isNotBlank() } ?: return null
1474
+ return OnDeviceRecognizerHost.Selection(path, STTTools.getSttModelLanguage(context))
1475
+ }
1476
+
1477
+ /** Runs on [sttLoader]. Throws when the model can't be loaded. */
1478
+ private fun loadTranscriber(selection: OnDeviceRecognizerHost.Selection): SherpaOnnxTranscriber {
1479
+ val next = SherpaOnnxTranscriber(Bridge.getContext(), selection.path, selection.language)
1480
+ next.setTranscriptListener(
1481
+ object : SherpaOnnxTranscriber.TranscriptListener {
1482
+ override fun onPartialResult(text: String, language: String) {
1483
+ Bridge.log("STT: Partial result: $text")
1484
+ Bridge.sendLocalTranscription(text, false, language)
1485
+ }
1479
1486
 
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
- }
1487
+ override fun onFinalResult(text: String, language: String) {
1488
+ Bridge.log("STT: Final result: $text")
1489
+ Bridge.sendLocalTranscription(text, true, language)
1487
1490
  }
1488
- )
1489
- nextTranscriber.initialize()
1490
- if (!nextTranscriber.isInitialized()) {
1491
- Bridge.log("SherpaOnnxTranscriber initialize() returned without becoming ready")
1492
- return false
1493
1491
  }
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
- }
1492
+ )
1493
+ next.load()
1494
+ return next
1506
1495
  }
1507
1496
 
1508
1497
  // MARK: - connection state management
@@ -2311,14 +2300,9 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2311
2300
  val willSendPcm = shouldSendPcm || shouldSendLc3
2312
2301
  val willSendTranscript = shouldSendTranscript || localSttFallbackActive
2313
2302
  val nextEnabled = willSendPcm || willSendTranscript
2314
- // Tell VAD when the mic is shutting down so it doesn't get stuck in
2315
- // a stale "speaking" state and keep emitting vad_status=true after
2316
- // audio stops flowing.
2317
- if (micEnabled && !nextEnabled) {
2318
- vadPolicy?.microphoneStateChanged(false)
2319
- }
2303
+ // Load the recognizer while on-device transcription is in demand; release it when not.
2304
+ transcription.setDemand(willSendTranscript)
2320
2305
  micEnabled = nextEnabled
2321
- vadBuffer.clear()
2322
2306
  updateMicState()
2323
2307
  }
2324
2308
 
@@ -2746,9 +2730,10 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2746
2730
  systemMicAvailabilityRecheckRunnable?.let { mainHandler.removeCallbacks(it) }
2747
2731
  systemMicAvailabilityRecheckRunnable = null
2748
2732
 
2749
- // Clean up transcriber resources
2750
- transcriber?.shutdown()
2751
- transcriber = null
2733
+ // Release on-device voice models (each on its own worker).
2734
+ transcription.setDemand(false)
2735
+ WakeWordDetector.shutdown()
2736
+ SpeechActivityDetector.shutdown()
2752
2737
 
2753
2738
  // Clean up LC3 encoder/decoder (synchronized to prevent use-after-free
2754
2739
  // if the recording thread is mid-encode/decode)
@@ -3,9 +3,9 @@ package com.mentra.bluetoothsdk
3
3
  /** Generated by release CI. Do not edit in a release checkout. */
4
4
  internal object GeneratedReleaseMetadata {
5
5
  const val FAMILY_BASE_VERSION: String = "3.4.0"
6
- const val RELEASE_IDENTITY: String = "3.4.0-dev.1166"
7
- const val RELEASE_SET_ID: String = "mentra-3.4.0-dev.1166"
8
- const val SOURCE_COMMIT: String = "f7eb5fd8825043223a09e3f9cfa8f948d1921463"
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.1166.json"
10
- const val OTA_MANIFEST_SHA256: String = "fb9890859825746fca6d18653a7f28702dc22ba9cbf36cc884f81ce7f1e6b331"
6
+ const val RELEASE_IDENTITY: String = "3.4.0-dev.1170"
7
+ const val RELEASE_SET_ID: String = "mentra-3.4.0-dev.1170"
8
+ const val SOURCE_COMMIT: String = "bda9eb4b45f3a2f9ab27a3843055470a3fa1a0cf"
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.1170.json"
10
+ const val OTA_MANIFEST_SHA256: String = "595391b32c28a6710a47db1088ecd98d8d7b692230a4cddbfa82c950580cbe6c"
11
11
  }
@@ -0,0 +1,92 @@
1
+ package com.mentra.bluetoothsdk.stt
2
+
3
+ import java.util.ArrayDeque
4
+ import java.util.concurrent.TimeUnit
5
+ import java.util.concurrent.locks.ReentrantLock
6
+ import kotlin.concurrent.withLock
7
+
8
+ /**
9
+ * FIFO work queue for a speech worker thread.
10
+ *
11
+ * Audio frames are bounded: when [audioCapacity] frames are already waiting, the oldest
12
+ * waiting frame is dropped. Control items (load, configure, finish, release) are never
13
+ * dropped, so a caller waiting on one can't wait forever because the worker fell behind.
14
+ * Order between audio and control items is preserved, so a control item runs after every
15
+ * frame queued before it.
16
+ */
17
+ internal class BoundedAudioQueue<T : Any>(
18
+ private val audioCapacity: Int,
19
+ private val isAudio: (T) -> Boolean,
20
+ ) {
21
+ init {
22
+ require(audioCapacity > 0) { "audioCapacity must be positive" }
23
+ }
24
+
25
+ private val lock = ReentrantLock()
26
+ private val changed = lock.newCondition()
27
+ private val items = ArrayDeque<T>()
28
+ private var audioCount = 0
29
+
30
+ /** Total audio frames dropped because the worker fell behind. */
31
+ var droppedAudio = 0L
32
+ private set
33
+
34
+ /** Enqueue [item]. Returns the audio frame dropped to make room, if any. */
35
+ fun offer(item: T): T? =
36
+ lock.withLock {
37
+ var dropped: T? = null
38
+ if (isAudio(item)) {
39
+ if (audioCount >= audioCapacity) {
40
+ val iterator = items.iterator()
41
+ while (iterator.hasNext()) {
42
+ val queued = iterator.next()
43
+ if (isAudio(queued)) {
44
+ iterator.remove()
45
+ audioCount--
46
+ droppedAudio++
47
+ dropped = queued
48
+ break
49
+ }
50
+ }
51
+ }
52
+ audioCount++
53
+ }
54
+ items.addLast(item)
55
+ changed.signalAll()
56
+ dropped
57
+ }
58
+
59
+ /** Next item, waiting up to [timeoutMs]; null on timeout. */
60
+ fun poll(timeoutMs: Long): T? =
61
+ lock.withLock {
62
+ var remainingNanos = TimeUnit.MILLISECONDS.toNanos(timeoutMs)
63
+ while (items.isEmpty()) {
64
+ if (remainingNanos <= 0L) return null
65
+ remainingNanos = changed.awaitNanos(remainingNanos)
66
+ }
67
+ val item = items.removeFirst()
68
+ if (isAudio(item)) audioCount--
69
+ item
70
+ }
71
+
72
+ /** Remove every waiting audio frame, keeping control items. */
73
+ fun clearAudio(): Int =
74
+ lock.withLock {
75
+ val before = items.size
76
+ items.removeAll { isAudio(it) }
77
+ audioCount = 0
78
+ before - items.size
79
+ }
80
+
81
+ /** Remove and return everything waiting. */
82
+ fun drain(): List<T> =
83
+ lock.withLock {
84
+ val all = items.toList()
85
+ items.clear()
86
+ audioCount = 0
87
+ all
88
+ }
89
+
90
+ val size: Int
91
+ get() = lock.withLock { items.size }
92
+ }