@mentra/bluetooth-sdk 3.4.0-dev.1169 → 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
@@ -0,0 +1,211 @@
1
+ package com.mentra.bluetoothsdk.stt
2
+
3
+ import android.content.Context
4
+ import android.os.SystemClock
5
+ import com.k2fsa.sherpa.onnx.SileroVadModelConfig
6
+ import com.k2fsa.sherpa.onnx.Vad
7
+ import com.k2fsa.sherpa.onnx.VadModelConfig
8
+ import com.mentra.bluetoothsdk.Bridge
9
+ import java.util.concurrent.CompletableFuture
10
+ import java.util.concurrent.ExecutionException
11
+ import java.util.concurrent.atomic.AtomicLong
12
+
13
+ /**
14
+ * Silero voice activity from sherpa-onnx ([Vad]) on one 512-sample window at a time.
15
+ *
16
+ * Settings are shared with iOS (`SherpaOnnxVoiceActivityDetectorWrapper`) so both platforms
17
+ * report the same transitions: threshold 0.5, 0.25 s minimum speech, [minSilenceMs] minimum
18
+ * silence, and a 30 s speech cap (bounds the buffered segment) after which sherpa-onnx splits
19
+ * long speech at shorter pauses.
20
+ */
21
+ internal class SileroSpeechClassifier(context: Context, minSilenceMs: Int) : SpeechFrameClassifier {
22
+ companion object {
23
+ /** Model shipped in the SDK's assets. */
24
+ const val MODEL_ASSET = "vad/silero_vad.onnx"
25
+ const val THRESHOLD = 0.5f
26
+ const val MIN_SPEECH_SECONDS = 0.25f
27
+ const val MAX_SPEECH_SECONDS = 30f
28
+ }
29
+
30
+ private val vad =
31
+ Vad(
32
+ context.assets,
33
+ VadModelConfig(
34
+ sileroVadModelConfig =
35
+ SileroVadModelConfig(
36
+ model = MODEL_ASSET,
37
+ threshold = THRESHOLD,
38
+ minSilenceDuration = minSilenceMs / 1000f,
39
+ minSpeechDuration = MIN_SPEECH_SECONDS,
40
+ windowSize = SpeechActivityEngine.FRAME_SAMPLES,
41
+ maxSpeechDuration = MAX_SPEECH_SECONDS,
42
+ ),
43
+ sampleRate = SpeechActivityEngine.SAMPLE_RATE,
44
+ numThreads = 1,
45
+ ),
46
+ )
47
+
48
+ override fun accept(frame: FloatArray): Boolean {
49
+ vad.acceptWaveform(frame)
50
+ // Speech segments are not used; drop them so memory stays flat.
51
+ if (!vad.empty()) vad.clear()
52
+ return vad.isSpeechDetected()
53
+ }
54
+
55
+ override fun reset() = vad.reset()
56
+
57
+ override fun release() = vad.release()
58
+ }
59
+
60
+ /**
61
+ * Phone-side speech activity on the same 16 kHz mono microphone PCM the wake word and on-device
62
+ * transcription see, for every microphone source. Runs only while enabled; disabling releases
63
+ * the model. Emits `speech_activity` on transitions only.
64
+ *
65
+ * One worker thread owns the classifier. Control tasks are never dropped; if the worker falls
66
+ * behind, the oldest audio frames are.
67
+ */
68
+ internal object SpeechActivityDetector {
69
+ private const val AUDIO_CAPACITY = 200
70
+
71
+ private sealed class Task {
72
+ class Audio(val pcm: ByteArray, val generation: Long) : Task()
73
+ class Control(val action: () -> Unit) : Task()
74
+ }
75
+
76
+ private val queue = BoundedAudioQueue<Task>(AUDIO_CAPACITY) { it is Task.Audio }
77
+ private val generation = AtomicLong(0)
78
+ @Volatile private var active = false
79
+ @Volatile private var workerThread: Thread? = null
80
+
81
+ /** Builds the classifier; replaced in tests. */
82
+ @Volatile
83
+ internal var classifierFactory: (minSilenceMs: Int) -> SpeechFrameClassifier = { minSilenceMs ->
84
+ SileroSpeechClassifier(Bridge.getContext(), minSilenceMs)
85
+ }
86
+
87
+ /** Receives transitions; replaced in tests. */
88
+ @Volatile
89
+ internal var emitter: (speaking: Boolean, silentForMs: Long) -> Unit = { speaking, silentForMs ->
90
+ Bridge.sendSpeechActivity(speaking, silentForMs)
91
+ }
92
+
93
+ @Volatile internal var clock: () -> Long = { SystemClock.elapsedRealtime() }
94
+
95
+ // Written only on the worker thread.
96
+ @Volatile private var classifier: SpeechFrameClassifier? = null
97
+ private var engine: SpeechActivityEngine? = null
98
+
99
+ /**
100
+ * Enable with [minSilenceMs] (the quiet gap before a silence transition) or disable,
101
+ * releasing the model. Blocks the calling thread (a background dispatcher) until done;
102
+ * throws when enabling fails.
103
+ */
104
+ fun configure(enabled: Boolean, minSilenceMs: Int = SpeechActivityEngine.DEFAULT_MIN_SILENCE_MS) {
105
+ require(minSilenceMs > 0) { "minSilenceMs must be positive" }
106
+ active = false
107
+ val token = generation.incrementAndGet()
108
+ val done = CompletableFuture<Unit>()
109
+ submit {
110
+ try {
111
+ if (enabled) enable(minSilenceMs, token) else disable()
112
+ done.complete(Unit)
113
+ } catch (error: Throwable) {
114
+ done.completeExceptionally(error)
115
+ }
116
+ }
117
+ try {
118
+ done.get()
119
+ } catch (error: ExecutionException) {
120
+ throw error.cause ?: error
121
+ }
122
+ }
123
+
124
+ /** Release the model without waiting (module teardown). */
125
+ fun shutdown() {
126
+ active = false
127
+ generation.incrementAndGet()
128
+ submit { disable() }
129
+ }
130
+
131
+ /** Called on the audio thread; only copies and queues. */
132
+ fun accept(pcm: ByteArray) {
133
+ if (!active || pcm.isEmpty()) return
134
+ queue.offer(Task.Audio(pcm.copyOf(), generation.get()))
135
+ }
136
+
137
+ private fun enable(minSilenceMs: Int, token: Long) {
138
+ val loaded = classifier
139
+ if (loaded != null && engine?.minSilenceMs == minSilenceMs) {
140
+ loaded.reset()
141
+ } else {
142
+ disable()
143
+ classifier =
144
+ try {
145
+ classifierFactory(minSilenceMs)
146
+ } catch (error: LinkageError) {
147
+ throw IllegalStateException("On-device speech detection is not available in this build", error)
148
+ }
149
+ }
150
+ val current = classifier!!
151
+ engine = SpeechActivityEngine(
152
+ classifier = current,
153
+ minSilenceMs = minSilenceMs,
154
+ emit = { speaking, silentForMs -> if (token == generation.get()) emitter(speaking, silentForMs) },
155
+ startedAtMs = clock(),
156
+ )
157
+ if (token == generation.get()) active = true
158
+ Bridge.log("SPEECH_ACTIVITY: enabled (minSilenceMs=$minSilenceMs)")
159
+ }
160
+
161
+ private fun disable() {
162
+ engine = null
163
+ val loaded = classifier ?: return
164
+ classifier = null
165
+ try {
166
+ loaded.release()
167
+ } catch (error: Exception) {
168
+ Bridge.log("SPEECH_ACTIVITY: release failed: ${error.message}")
169
+ }
170
+ Bridge.log("SPEECH_ACTIVITY: model released")
171
+ }
172
+
173
+ private fun submit(action: () -> Unit) {
174
+ queue.offer(Task.Control(action))
175
+ ensureWorker()
176
+ }
177
+
178
+ private fun ensureWorker() {
179
+ if (workerThread != null) return
180
+ synchronized(this) {
181
+ if (workerThread != null) return
182
+ workerThread =
183
+ Thread({ runLoop() }, "SpeechActivityDetector").apply {
184
+ isDaemon = true
185
+ start()
186
+ }
187
+ }
188
+ }
189
+
190
+ private fun runLoop() {
191
+ while (true) {
192
+ val wait = engine?.nextWakeDelayMs(clock()) ?: 60_000L
193
+ val task = queue.poll(wait)
194
+ try {
195
+ when (task) {
196
+ is Task.Audio ->
197
+ if (active && task.generation == generation.get()) engine?.onAudio(task.pcm, clock())
198
+ is Task.Control -> task.action()
199
+ null -> Unit
200
+ }
201
+ if (active) engine?.onIdle(clock())
202
+ } catch (error: Throwable) {
203
+ Bridge.log("SPEECH_ACTIVITY: ${error.message}")
204
+ }
205
+ }
206
+ }
207
+
208
+ /** Test hook: whether a model is loaded (read on any thread; for assertions only). */
209
+ internal val isModelLoadedForTest: Boolean
210
+ get() = classifier != null
211
+ }
@@ -0,0 +1,137 @@
1
+ package com.mentra.bluetoothsdk.stt
2
+
3
+ /**
4
+ * Splits 16-bit little-endian mono PCM into fixed-size float frames.
5
+ *
6
+ * Chunks of any length are accepted, including odd byte counts: leftover samples and a
7
+ * dangling byte carry over to the next chunk, so no audio is skipped.
8
+ */
9
+ internal class PcmFrameAssembler(val frameSize: Int = SpeechActivityEngine.FRAME_SAMPLES) {
10
+ private val frame = FloatArray(frameSize)
11
+ private var filled = 0
12
+ private var pendingByte = -1
13
+
14
+ /** Samples waiting for a full frame. */
15
+ val pendingSamples: Int
16
+ get() = filled
17
+
18
+ fun push(bytes: ByteArray, onFrame: (FloatArray) -> Unit) {
19
+ var i = 0
20
+ if (pendingByte >= 0 && bytes.isNotEmpty()) {
21
+ add(pendingByte or (bytes[0].toInt() shl 8), onFrame)
22
+ pendingByte = -1
23
+ i = 1
24
+ }
25
+ while (i + 1 < bytes.size) {
26
+ add((bytes[i].toInt() and 0xff) or (bytes[i + 1].toInt() shl 8), onFrame)
27
+ i += 2
28
+ }
29
+ if (i < bytes.size) pendingByte = bytes[i].toInt() and 0xff
30
+ }
31
+
32
+ /** Append [samples] of digital silence (drops a dangling byte: the audio is discontinuous). */
33
+ fun pushSilence(samples: Int, onFrame: (FloatArray) -> Unit) {
34
+ pendingByte = -1
35
+ repeat(samples) { add(0, onFrame) }
36
+ }
37
+
38
+ fun clear() {
39
+ filled = 0
40
+ pendingByte = -1
41
+ }
42
+
43
+ private fun add(sample16: Int, onFrame: (FloatArray) -> Unit) {
44
+ frame[filled++] = sample16.toShort() / 32768f
45
+ if (filled == frameSize) {
46
+ filled = 0
47
+ onFrame(frame.copyOf())
48
+ }
49
+ }
50
+ }
51
+
52
+ /** Classifies consecutive frames; returns whether speech is detected after each frame. */
53
+ internal interface SpeechFrameClassifier {
54
+ fun accept(frame: FloatArray): Boolean
55
+
56
+ /** Forget all state (a new session). */
57
+ fun reset() {}
58
+
59
+ fun release()
60
+ }
61
+
62
+ /**
63
+ * Speech/silence transitions from a frame classifier, with missing audio treated as silence.
64
+ *
65
+ * Every complete [FRAME_SAMPLES]-sample frame is classified; nothing is skipped or throttled.
66
+ * Transitions are emitted only when the classifier's state flips. When no audio has arrived for
67
+ * [gapMs] (Mentra Live's loudness gate stops sending audio when it's quiet) while speech is
68
+ * detected, silent frames are fed in real time from the end of the last audio, so silence comes
69
+ * out of the same classifier as any other quiet. Feeding stops once silence has been reported;
70
+ * real audio drives the classifier again as soon as it arrives. Same rules as iOS.
71
+ *
72
+ * Not thread-safe: drive it from one thread. Times are monotonic milliseconds.
73
+ */
74
+ internal class SpeechActivityEngine(
75
+ private val classifier: SpeechFrameClassifier,
76
+ val minSilenceMs: Int,
77
+ private val emit: (speaking: Boolean, silentForMs: Long) -> Unit,
78
+ startedAtMs: Long,
79
+ private val gapMs: Long = GAP_MS,
80
+ ) {
81
+ companion object {
82
+ const val SAMPLE_RATE = 16_000
83
+ const val FRAME_SAMPLES = 512
84
+ const val FRAME_MS = FRAME_SAMPLES * 1000L / SAMPLE_RATE // 32 ms
85
+ const val GAP_MS = 100L
86
+ const val DEFAULT_MIN_SILENCE_MS = 300
87
+ }
88
+
89
+ private val assembler = PcmFrameAssembler(FRAME_SAMPLES)
90
+
91
+ var speaking = false
92
+ private set
93
+
94
+ /** Frames classified so far (real and synthetic). */
95
+ var framesClassified = 0L
96
+ private set
97
+
98
+ private var lastAudioAtMs = startedAtMs
99
+ private var filling = false
100
+ private var filledUntilMs = startedAtMs
101
+
102
+ fun onAudio(pcm: ByteArray, nowMs: Long) {
103
+ filling = false
104
+ lastAudioAtMs = nowMs
105
+ filledUntilMs = nowMs
106
+ assembler.push(pcm, ::classify)
107
+ }
108
+
109
+ /** Feed silence for an audio gap, if one is due. Call whenever the driving thread wakes. */
110
+ fun onIdle(nowMs: Long) {
111
+ if (nowMs - lastAudioAtMs < gapMs) return
112
+ if (!filling) {
113
+ filling = true
114
+ filledUntilMs = lastAudioAtMs
115
+ }
116
+ while (filledUntilMs + FRAME_MS <= nowMs && speaking) {
117
+ assembler.pushSilence(FRAME_SAMPLES, ::classify)
118
+ filledUntilMs += FRAME_MS
119
+ }
120
+ }
121
+
122
+ /** How long the driving thread may sleep before [onIdle] has work, or null if none is due. */
123
+ fun nextWakeDelayMs(nowMs: Long): Long? {
124
+ if (!speaking) return null
125
+ if (!filling) return (lastAudioAtMs + gapMs - nowMs).coerceAtLeast(1)
126
+ return (filledUntilMs + FRAME_MS - nowMs).coerceAtLeast(1)
127
+ }
128
+
129
+ private fun classify(frame: FloatArray) {
130
+ framesClassified++
131
+ val speech = classifier.accept(frame)
132
+ if (speech == speaking) return
133
+ speaking = speech
134
+ // The classifier reports silence only after minSilenceMs of quiet.
135
+ emit(speech, if (speech) 0L else minSilenceMs.toLong())
136
+ }
137
+ }
@@ -0,0 +1,52 @@
1
+ package com.mentra.bluetoothsdk.stt
2
+
3
+ import java.io.File
4
+
5
+ /**
6
+ * Transcript casing, chosen from the vocabulary of the model that is actually loaded.
7
+ *
8
+ * Some streaming models (the original English Zipformer among them) only have upper-case
9
+ * tokens, so they emit ALL-CAPS text; that output is lower-cased. Models whose vocabulary
10
+ * has lower-case letters (Kroko, for example) produce their own casing and punctuation,
11
+ * which is kept exactly. The decision never depends on a folder name or the selected path.
12
+ */
13
+ internal object SttTextFormatter {
14
+ enum class Casing {
15
+ /** Keep the model's text as-is. */
16
+ PRESERVE,
17
+
18
+ /** The model only knows upper-case letters: lower-case its text. */
19
+ LOWERCASE,
20
+ }
21
+
22
+ /** Casing for a model whose `tokens.txt` lines are [tokenLines]. */
23
+ fun casingForTokens(tokenLines: Sequence<String>): Casing {
24
+ var sawUpper = false
25
+ for (line in tokenLines) {
26
+ // tokens.txt lines are "<symbol> <id>"; only the symbol matters. Special
27
+ // symbols such as <blk>, <unk> and byte tokens (<0x41>) never reach text.
28
+ val trimmed = line.trim()
29
+ val separator = trimmed.indexOfLast { it == ' ' || it == '\t' }
30
+ val symbol = if (separator >= 0) trimmed.substring(0, separator) else trimmed
31
+ if (symbol.startsWith('<') && symbol.endsWith('>')) continue
32
+ for (ch in symbol) {
33
+ if (ch.isLowerCase()) return Casing.PRESERVE
34
+ if (ch.isUpperCase()) sawUpper = true
35
+ }
36
+ }
37
+ return if (sawUpper) Casing.LOWERCASE else Casing.PRESERVE
38
+ }
39
+
40
+ /** Casing for the model directory [modelDir] (reads its `tokens.txt`). */
41
+ fun casingForModel(modelDir: File): Casing {
42
+ val tokens = File(modelDir, "tokens.txt")
43
+ if (!tokens.isFile) return Casing.PRESERVE
44
+ return tokens.bufferedReader().use { reader -> casingForTokens(reader.lineSequence()) }
45
+ }
46
+
47
+ fun format(text: String, casing: Casing): String =
48
+ when (casing) {
49
+ Casing.PRESERVE -> text
50
+ Casing.LOWERCASE -> text.lowercase()
51
+ }
52
+ }
@@ -0,0 +1,235 @@
1
+ package com.mentra.bluetoothsdk.stt
2
+
3
+ import com.k2fsa.sherpa.onnx.KeywordSpotter
4
+ import com.k2fsa.sherpa.onnx.KeywordSpotterConfig
5
+ import com.k2fsa.sherpa.onnx.OnlineModelConfig
6
+ import com.k2fsa.sherpa.onnx.OnlineStream
7
+ import com.k2fsa.sherpa.onnx.OnlineTransducerModelConfig
8
+ import com.mentra.bluetoothsdk.Bridge
9
+ import java.io.File
10
+ import java.util.concurrent.CompletableFuture
11
+ import java.util.concurrent.ExecutionException
12
+ import java.util.concurrent.atomic.AtomicLong
13
+
14
+ /**
15
+ * Demand-driven keyword spotting ("Hey Mentra") on the 16 kHz mono microphone PCM.
16
+ *
17
+ * The model comes from the directory the host passes when enabling (the Speech-page download),
18
+ * not from bundled assets. One worker thread owns the spotter: it loads, runs and releases it.
19
+ * Control tasks are never dropped; when the worker falls behind only audio frames are dropped,
20
+ * so a caller waiting on [configure] always gets an answer.
21
+ */
22
+ internal object WakeWordDetector {
23
+ const val PHRASE = "Hey Mentra"
24
+ private const val SAMPLE_RATE = 16000
25
+ private const val AUDIO_CAPACITY = 100
26
+ private const val DETECTION_COOLDOWN_MS = 250L
27
+
28
+ /** Files the model directory must contain. */
29
+ val MODEL_FILES =
30
+ listOf("encoder.int8.onnx", "decoder.onnx", "joiner.int8.onnx", "tokens.txt", "keywords.txt")
31
+
32
+ private sealed class Task {
33
+ class Audio(val pcm: ByteArray, val generation: Long) : Task()
34
+ class Control(val action: () -> Unit) : Task()
35
+ }
36
+
37
+ private val queue = BoundedAudioQueue<Task>(AUDIO_CAPACITY) { it is Task.Audio }
38
+ private val generation = AtomicLong(0)
39
+ @Volatile private var active = false
40
+ @Volatile private var workerThread: Thread? = null
41
+
42
+ // Accessed only on the worker thread, including release.
43
+ private var engine: Engine? = null
44
+ private var lastDetection = 0L
45
+
46
+ /** The loaded spotter and its stream. */
47
+ private class Engine(val modelDir: String, val spotter: KeywordSpotter, val stream: OnlineStream) {
48
+ fun release() {
49
+ stream.release()
50
+ spotter.release()
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Enable (loading the model from [modelDir]) or disable (releasing the stream and the model).
56
+ * Blocks the calling thread (a background dispatcher) until the worker has done it: enabling
57
+ * returns after the model is loaded and `ready` was emitted, and throws when loading fails
58
+ * (no `wake_word` event; the caller reports the rejection).
59
+ */
60
+ fun configure(enabled: Boolean, modelDir: String?) {
61
+ if (enabled && modelDir.isNullOrBlank()) {
62
+ throw IllegalArgumentException("modelDir is required to enable wake-word detection")
63
+ }
64
+ active = false
65
+ val token = generation.incrementAndGet()
66
+ val done = CompletableFuture<Unit>()
67
+ submit {
68
+ try {
69
+ if (enabled) enable(modelDir!!, token) else disable()
70
+ done.complete(Unit)
71
+ } catch (error: Throwable) {
72
+ done.completeExceptionally(error)
73
+ }
74
+ }
75
+ try {
76
+ done.get()
77
+ } catch (error: ExecutionException) {
78
+ throw error.cause ?: error
79
+ }
80
+ }
81
+
82
+ /** Release the model without waiting (module teardown). */
83
+ fun shutdown() {
84
+ active = false
85
+ generation.incrementAndGet()
86
+ submit { disable() }
87
+ }
88
+
89
+ private fun enable(modelDir: String, token: Long) {
90
+ lastDetection = 0
91
+ val loaded = engine
92
+ if (loaded != null && loaded.modelDir == modelDir) {
93
+ loaded.spotter.reset(loaded.stream)
94
+ } else {
95
+ disable()
96
+ try {
97
+ engine = load(modelDir)
98
+ } catch (error: Throwable) {
99
+ // The caller's promise rejects; the engine reports it as a wake_word error.
100
+ val message =
101
+ when (error) {
102
+ is LinkageError -> "On-device wake-word detection is not available in this build"
103
+ else -> error.message ?: "Could not load the wake-word model"
104
+ }
105
+ throw IllegalStateException(message, error)
106
+ }
107
+ }
108
+ // A newer configure() call supersedes this one: don't report or listen for it.
109
+ if (token != generation.get()) return
110
+ active = true
111
+ emit("ready", token)
112
+ }
113
+
114
+ private fun disable() {
115
+ val loaded = engine ?: return
116
+ engine = null
117
+ try {
118
+ loaded.release()
119
+ } catch (error: Exception) {
120
+ Bridge.log("WAKE_WORD: release failed: ${error.message}")
121
+ }
122
+ Bridge.log("WAKE_WORD: model released")
123
+ }
124
+
125
+ private fun load(modelDir: String): Engine {
126
+ val dir = File(modelDir)
127
+ val missing = MODEL_FILES.filter { name -> !File(dir, name).let { it.isFile && it.length() > 0 } }
128
+ if (missing.isNotEmpty()) {
129
+ throw IllegalStateException("Wake-word model is incomplete; missing ${missing.joinToString()}")
130
+ }
131
+ fun path(name: String) = File(dir, name).absolutePath
132
+ val model =
133
+ OnlineModelConfig(
134
+ transducer =
135
+ OnlineTransducerModelConfig(
136
+ encoder = path("encoder.int8.onnx"),
137
+ decoder = path("decoder.onnx"),
138
+ joiner = path("joiner.int8.onnx"),
139
+ ),
140
+ tokens = path("tokens.txt"),
141
+ numThreads = 1,
142
+ )
143
+ val config =
144
+ KeywordSpotterConfig(
145
+ modelConfig = model,
146
+ keywordsFile = path("keywords.txt"),
147
+ numTrailingBlanks = 1,
148
+ maxActivePaths = 8,
149
+ )
150
+ // Null AssetManager: load from files.
151
+ val spotter = KeywordSpotter(null, config)
152
+ val stream =
153
+ try {
154
+ spotter.createStream("")
155
+ } catch (error: Exception) {
156
+ spotter.release()
157
+ throw error
158
+ }
159
+ Bridge.log("WAKE_WORD: model loaded from $modelDir")
160
+ return Engine(modelDir, spotter, stream)
161
+ }
162
+
163
+ /** Called on the audio thread. Never loads or runs the model there. */
164
+ fun accept(pcm: ByteArray) {
165
+ if (!active || pcm.isEmpty() || pcm.size % 2 != 0) return
166
+ queue.offer(Task.Audio(pcm.copyOf(), generation.get()))
167
+ ensureWorker()
168
+ }
169
+
170
+ private fun process(task: Task.Audio) {
171
+ if (!active || task.generation != generation.get()) return
172
+ val loaded = engine ?: return
173
+ try {
174
+ val samples =
175
+ FloatArray(task.pcm.size / 2) { i ->
176
+ val sample =
177
+ ((task.pcm[i * 2].toInt() and 0xff) or (task.pcm[i * 2 + 1].toInt() shl 8)).toShort()
178
+ sample.toFloat() / 32768f
179
+ }
180
+ loaded.stream.acceptWaveform(samples, SAMPLE_RATE)
181
+ while (loaded.spotter.isReady(loaded.stream)) {
182
+ loaded.spotter.decode(loaded.stream)
183
+ if (loaded.spotter.getResult(loaded.stream).keyword.isNotEmpty()) {
184
+ loaded.spotter.reset(loaded.stream)
185
+ val now = System.currentTimeMillis()
186
+ if (active && task.generation == generation.get() && now - lastDetection >= DETECTION_COOLDOWN_MS) {
187
+ lastDetection = now
188
+ emit("detected", task.generation)
189
+ }
190
+ }
191
+ }
192
+ } catch (error: Exception) {
193
+ if (task.generation == generation.get()) {
194
+ active = false
195
+ emit("error", task.generation, error.message ?: "Wake-word detection failed")
196
+ }
197
+ }
198
+ }
199
+
200
+ private fun emit(kind: String, token: Long, message: String? = null) {
201
+ if (token != generation.get()) return
202
+ Bridge.sendWakeWord(kind, PHRASE, message)
203
+ }
204
+
205
+ private fun submit(action: () -> Unit) {
206
+ queue.offer(Task.Control(action))
207
+ ensureWorker()
208
+ }
209
+
210
+ private fun ensureWorker() {
211
+ if (workerThread != null) return
212
+ synchronized(this) {
213
+ if (workerThread != null) return
214
+ workerThread =
215
+ Thread({ runLoop() }, "WakeWordDetector").apply {
216
+ isDaemon = true
217
+ start()
218
+ }
219
+ }
220
+ }
221
+
222
+ private fun runLoop() {
223
+ while (true) {
224
+ when (val task = queue.poll(60_000) ?: continue) {
225
+ is Task.Audio -> process(task)
226
+ is Task.Control ->
227
+ try {
228
+ task.action()
229
+ } catch (error: Throwable) {
230
+ Bridge.log("WAKE_WORD: control task failed: ${error.message}")
231
+ }
232
+ }
233
+ }
234
+ }
235
+ }