@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
@@ -0,0 +1,245 @@
1
+ package com.mentra.bluetoothsdk.stt
2
+
3
+ import org.junit.Assert.assertEquals
4
+ import org.junit.Assert.assertFalse
5
+ import org.junit.Assert.assertTrue
6
+ import org.junit.Test
7
+
8
+ /**
9
+ * Pure framing, transition and gap-fill logic. The classifier is a stand-in with Silero-like
10
+ * hysteresis: a frame is speech when its peak is above 0.1, and speaking only ends after
11
+ * minSilenceMs of quiet frames (sherpa-onnx's min_silence_duration).
12
+ */
13
+ class SpeechActivityEngineTest {
14
+ private class FakeClassifier(minSilenceMs: Int) : SpeechFrameClassifier {
15
+ private val quietFramesToEnd =
16
+ ((minSilenceMs + SpeechActivityEngine.FRAME_MS - 1) / SpeechActivityEngine.FRAME_MS).toInt()
17
+ val frames = mutableListOf<FloatArray>()
18
+ var released = false
19
+ private var speaking = false
20
+ private var quiet = 0
21
+
22
+ override fun accept(frame: FloatArray): Boolean {
23
+ frames.add(frame)
24
+ val loud = frame.any { kotlin.math.abs(it) > 0.1f }
25
+ if (loud) {
26
+ speaking = true
27
+ quiet = 0
28
+ } else if (speaking && ++quiet >= quietFramesToEnd) {
29
+ speaking = false
30
+ quiet = 0
31
+ }
32
+ return speaking
33
+ }
34
+
35
+ override fun release() {
36
+ released = true
37
+ }
38
+ }
39
+
40
+ private data class Event(val speaking: Boolean, val silentForMs: Long, val atMs: Long)
41
+
42
+ private var now = 0L
43
+ private val events = mutableListOf<Event>()
44
+
45
+ private fun engine(classifier: SpeechFrameClassifier, minSilenceMs: Int = 300) =
46
+ SpeechActivityEngine(
47
+ classifier = classifier,
48
+ minSilenceMs = minSilenceMs,
49
+ emit = { speaking, silentForMs -> events.add(Event(speaking, silentForMs, now)) },
50
+ startedAtMs = now,
51
+ )
52
+
53
+ /** 16-bit LE PCM for [samples] samples of [value] (as a fraction of full scale). */
54
+ private fun pcm(samples: Int, value: Float): ByteArray {
55
+ val out = ByteArray(samples * 2)
56
+ val s = (value * 32767).toInt()
57
+ for (i in 0 until samples) {
58
+ out[i * 2] = (s and 0xff).toByte()
59
+ out[i * 2 + 1] = (s shr 8).toByte()
60
+ }
61
+ return out
62
+ }
63
+
64
+ /** Deliver [bytes] in chunks of [chunkBytes], advancing the clock in real time. */
65
+ private fun deliver(engine: SpeechActivityEngine, bytes: ByteArray, chunkBytes: Int) {
66
+ var off = 0
67
+ while (off < bytes.size) {
68
+ val end = minOf(bytes.size, off + chunkBytes)
69
+ now += ((end - off) / 2) * 1000L / SpeechActivityEngine.SAMPLE_RATE
70
+ engine.onAudio(bytes.copyOfRange(off, end), now)
71
+ engine.onIdle(now)
72
+ off = end
73
+ }
74
+ }
75
+
76
+ /** Let wall time pass with no audio, waking the engine the way the worker does. */
77
+ private fun idle(engine: SpeechActivityEngine, forMs: Long) {
78
+ val until = now + forMs
79
+ while (now < until) {
80
+ val wait = engine.nextWakeDelayMs(now) ?: (until - now)
81
+ now = minOf(until, now + wait)
82
+ engine.onIdle(now)
83
+ }
84
+ }
85
+
86
+ @Test
87
+ fun assemblerAnalyzesEverySampleWhateverTheChunkSize() {
88
+ val assembler = PcmFrameAssembler(512)
89
+ val frames = mutableListOf<FloatArray>()
90
+ // A ramp so order and alignment are checkable; odd chunk sizes split samples.
91
+ val total = 512 * 7 + 100
92
+ val bytes = ByteArray(total * 2)
93
+ for (i in 0 until total) {
94
+ bytes[i * 2] = (i and 0xff).toByte()
95
+ bytes[i * 2 + 1] = (i shr 8).toByte()
96
+ }
97
+ var off = 0
98
+ val sizes = intArrayOf(333, 1, 2, 1001, 77, 4096, 5)
99
+ var k = 0
100
+ while (off < bytes.size) {
101
+ val end = minOf(bytes.size, off + sizes[k++ % sizes.size])
102
+ assembler.push(bytes.copyOfRange(off, end)) { frames.add(it) }
103
+ off = end
104
+ }
105
+
106
+ assertEquals(7, frames.size)
107
+ assertEquals(100, assembler.pendingSamples)
108
+ frames.forEachIndexed { f, frame ->
109
+ assertEquals(512, frame.size)
110
+ frame.forEachIndexed { j, value -> assertEquals((f * 512 + j) / 32768f, value, 0f) }
111
+ }
112
+ }
113
+
114
+ @Test
115
+ fun assemblerDecodesNegativeSamplesAcrossChunkBoundaries() {
116
+ val assembler = PcmFrameAssembler(2)
117
+ val frames = mutableListOf<FloatArray>()
118
+ // -2 = 0xFFFE, -32768 = 0x8000, split mid-sample.
119
+ assembler.push(byteArrayOf(0xFE.toByte())) { frames.add(it) }
120
+ assembler.push(byteArrayOf(0xFF.toByte(), 0x00)) { frames.add(it) }
121
+ assembler.push(byteArrayOf(0x80.toByte())) { frames.add(it) }
122
+ assertEquals(1, frames.size)
123
+ assertEquals(-2 / 32768f, frames[0][0], 0f)
124
+ assertEquals(-1f, frames[0][1], 0f)
125
+ }
126
+
127
+ @Test
128
+ fun nonAlignedChunksAreFullyAnalyzed() {
129
+ val classifier = FakeClassifier(300)
130
+ val engine = engine(classifier)
131
+ // 40 frames of audio delivered in 333-byte (odd) chunks.
132
+ deliver(engine, pcm(512 * 40, 0.5f), 333)
133
+ assertEquals(40, classifier.frames.size)
134
+ assertEquals(40L, engine.framesClassified)
135
+ }
136
+
137
+ @Test
138
+ fun emitsOnlyOnTransitions() {
139
+ val engine = engine(FakeClassifier(300))
140
+ deliver(engine, pcm(16_000, 0.5f), 640) // 1 s of speech
141
+ deliver(engine, pcm(16_000, 0f), 640) // 1 s of quiet audio
142
+ deliver(engine, pcm(8_000, 0.5f), 640) // speech again
143
+
144
+ assertEquals(listOf(true, false, true), events.map { it.speaking })
145
+ assertEquals(listOf(0L, 300L, 0L), events.map { it.silentForMs })
146
+ }
147
+
148
+ @Test
149
+ fun speechToSilenceReportsWithinTheConfiguredGap() {
150
+ for (minSilenceMs in listOf(300, 800)) {
151
+ events.clear()
152
+ now = 0
153
+ val engine = engine(FakeClassifier(minSilenceMs), minSilenceMs)
154
+ deliver(engine, pcm(16_000, 0.5f), 640)
155
+ val speechEndedAt = now
156
+ deliver(engine, pcm(32_000, 0f), 640)
157
+
158
+ val silent = events.single { !it.speaking }
159
+ val latency = silent.atMs - speechEndedAt
160
+ assertTrue("silence after ${latency}ms for $minSilenceMs", latency in minSilenceMs.toLong()..(minSilenceMs + 80L))
161
+ assertEquals(minSilenceMs.toLong(), silent.silentForMs)
162
+ }
163
+ }
164
+
165
+ @Test
166
+ fun audioThatStopsMidSessionProducesSilence() {
167
+ val classifier = FakeClassifier(300)
168
+ val engine = engine(classifier)
169
+ deliver(engine, pcm(16_000, 0.5f), 640) // speaking, then the loudness gate cuts audio
170
+ val audioStoppedAt = now
171
+ assertTrue(engine.speaking)
172
+
173
+ idle(engine, 2_000)
174
+
175
+ val silent = events.last()
176
+ assertFalse(silent.speaking)
177
+ // ~100 ms gap before filling starts from the end of the audio, then ~300 ms of silence.
178
+ val latency = silent.atMs - audioStoppedAt
179
+ assertTrue("silence reported after ${latency}ms", latency in 300L..500L)
180
+ }
181
+
182
+ @Test
183
+ fun gapFillingIsRealTimeAndStopsOnceSettled() {
184
+ val classifier = FakeClassifier(300)
185
+ val engine = engine(classifier)
186
+ deliver(engine, pcm(16_000, 0.5f), 640)
187
+ val framesBefore = classifier.frames.size
188
+
189
+ // Shorter than the gap: nothing synthetic yet.
190
+ idle(engine, 90)
191
+ assertEquals(framesBefore, classifier.frames.size)
192
+
193
+ // Past the gap: silent frames for the elapsed time, never ahead of the clock.
194
+ idle(engine, 110)
195
+ val synthetic = classifier.frames.size - framesBefore
196
+ assertTrue("fed $synthetic frames for 200 ms", synthetic in 5..7)
197
+ // The first one completes the partial frame of real audio (16000 % 512 = 128 samples).
198
+ val firstFill = classifier.frames[framesBefore]
199
+ assertTrue(firstFill.take(128).all { it > 0.4f } && firstFill.drop(128).all { it == 0f })
200
+ assertTrue(classifier.frames.drop(framesBefore + 1).all { frame -> frame.all { it == 0f } })
201
+
202
+ // After silence is reported and settled, no more inference while audio stays off.
203
+ idle(engine, 5_000)
204
+ val settled = classifier.frames.size
205
+ idle(engine, 5_000)
206
+ assertEquals(settled, classifier.frames.size)
207
+ assertEquals(null, engine.nextWakeDelayMs(now))
208
+ }
209
+
210
+ @Test
211
+ fun missingAudioWhileSilentNeedsNoFill() {
212
+ val classifier = FakeClassifier(300)
213
+ val engine = engine(classifier)
214
+ deliver(engine, pcm(16_000, 0f), 640)
215
+ val frames = classifier.frames.size
216
+ assertEquals(null, engine.nextWakeDelayMs(now))
217
+ idle(engine, 2_000)
218
+ assertEquals(frames, classifier.frames.size)
219
+ assertTrue(events.isEmpty())
220
+ }
221
+
222
+ @Test
223
+ fun fillStopsAsSoonAsSilenceIsReported() {
224
+ val classifier = FakeClassifier(300)
225
+ val engine = engine(classifier)
226
+ deliver(engine, pcm(16_000, 0.5f), 640)
227
+ val framesBefore = classifier.frames.size
228
+ idle(engine, 5_000)
229
+ // 1 frame completing the partial real frame + 10 quiet frames (320 ms) to report silence.
230
+ assertEquals(11, classifier.frames.size - framesBefore)
231
+ assertFalse(events.last().speaking)
232
+ }
233
+
234
+ @Test
235
+ fun realAudioResumingStopsTheFill() {
236
+ val classifier = FakeClassifier(300)
237
+ val engine = engine(classifier)
238
+ deliver(engine, pcm(16_000, 0.5f), 640)
239
+ idle(engine, 150) // gap fill has started; still speaking
240
+ assertTrue(engine.speaking)
241
+ deliver(engine, pcm(16_000, 0.5f), 640) // speech resumes
242
+ assertEquals(listOf(true), events.map { it.speaking })
243
+ assertEquals(SpeechActivityEngine.GAP_MS, engine.nextWakeDelayMs(now))
244
+ }
245
+ }
@@ -0,0 +1,67 @@
1
+ package com.mentra.bluetoothsdk.stt
2
+
3
+ import java.io.File
4
+ import java.nio.file.Files
5
+ import org.junit.Assert.assertEquals
6
+ import org.junit.Test
7
+
8
+ class SttTextFormatterTest {
9
+ private val text = "Hello, Mentra! I'm in New York."
10
+
11
+ // Excerpts of real tokens.txt files.
12
+ private val originalZipformerTokens =
13
+ sequenceOf("<blk> 0", "<sos/eos> 1", "<unk> 2", "S 3", "▁THE 4", "▁A 5", "T 6", "'S 7")
14
+ private val krokoTokens =
15
+ sequenceOf("<blk> 0", "<unk> 1", "▁the 2", "▁I 3", "s 4", ", 5", ". 6", "▁New 7")
16
+
17
+ @Test
18
+ fun upperCaseOnlyVocabularyIsLowercased() {
19
+ val casing = SttTextFormatter.casingForTokens(originalZipformerTokens)
20
+ assertEquals(SttTextFormatter.Casing.LOWERCASE, casing)
21
+ assertEquals("hello mentra", SttTextFormatter.format("HELLO MENTRA", casing))
22
+ }
23
+
24
+ @Test
25
+ fun mixedCaseVocabularyKeepsTheModelsText() {
26
+ val casing = SttTextFormatter.casingForTokens(krokoTokens)
27
+ assertEquals(SttTextFormatter.Casing.PRESERVE, casing)
28
+ assertEquals(text, SttTextFormatter.format(text, casing))
29
+ }
30
+
31
+ @Test
32
+ fun specialTokensAloneDoNotDecide() {
33
+ // <blk>/<unk> contain lower-case letters but never reach the transcript.
34
+ assertEquals(
35
+ SttTextFormatter.Casing.LOWERCASE,
36
+ SttTextFormatter.casingForTokens(sequenceOf("<blk> 0", "<unk> 1", "▁HI 2", "<0x41> 3")),
37
+ )
38
+ assertEquals(
39
+ SttTextFormatter.Casing.PRESERVE,
40
+ SttTextFormatter.casingForTokens(sequenceOf("<blk> 0", "▁ 1", "1 2")),
41
+ )
42
+ // Tab-separated ids, as some tokens.txt files use.
43
+ assertEquals(
44
+ SttTextFormatter.Casing.LOWERCASE,
45
+ SttTextFormatter.casingForTokens(sequenceOf("<blk>\t0", "▁HELLO\t1")),
46
+ )
47
+ }
48
+
49
+ @Test
50
+ fun casingComesFromTheModelFilesNotTheFolderName() {
51
+ val root = Files.createTempDirectory("stt-format").toFile()
52
+ try {
53
+ // The original Zipformer under a folder named like Kroko still lowercases.
54
+ val misnamed = File(root, "en-kroko").apply { mkdirs() }
55
+ File(misnamed, "tokens.txt").writeText(originalZipformerTokens.joinToString("\n"))
56
+ assertEquals(SttTextFormatter.Casing.LOWERCASE, SttTextFormatter.casingForModel(misnamed))
57
+
58
+ val kroko = File(root, "en").apply { mkdirs() }
59
+ File(kroko, "tokens.txt").writeText(krokoTokens.joinToString("\n"))
60
+ assertEquals(SttTextFormatter.Casing.PRESERVE, SttTextFormatter.casingForModel(kroko))
61
+
62
+ assertEquals(SttTextFormatter.Casing.PRESERVE, SttTextFormatter.casingForModel(File(root, "missing")))
63
+ } finally {
64
+ root.deleteRecursively()
65
+ }
66
+ }
67
+ }
@@ -0,0 +1,76 @@
1
+ package com.mentra.bluetoothsdk.utils.audio
2
+
3
+ import java.io.ByteArrayOutputStream
4
+ import java.io.InputStream
5
+ import org.junit.Assert.assertArrayEquals
6
+ import org.junit.Assert.assertEquals
7
+ import org.junit.Assert.assertFalse
8
+ import org.junit.Assert.assertNull
9
+ import org.junit.Assert.assertTrue
10
+ import org.junit.Test
11
+ import org.junit.runner.RunWith
12
+ import org.robolectric.RobolectricTestRunner
13
+ import org.robolectric.annotation.Config
14
+
15
+ @RunWith(RobolectricTestRunner::class)
16
+ @Config(sdk = [33])
17
+ class PcmUrlPlaybackTest {
18
+ @Test
19
+ fun carryKeepsSamplesWholeAcrossOddChunks() {
20
+ val carry = Pcm16ByteCarry()
21
+ assertNull(carry.push(byteArrayOf(1), 1))
22
+ assertTrue(carry.hasPendingByte)
23
+ assertArrayEquals(byteArrayOf(1, 2), carry.push(byteArrayOf(2, 3, 4, 5), 1))
24
+ assertFalse(carry.hasPendingByte)
25
+ assertArrayEquals(byteArrayOf(3, 4, 5, 6), carry.push(byteArrayOf(3, 4, 5, 6, 7), 5))
26
+ assertTrue(carry.hasPendingByte)
27
+ assertArrayEquals(byteArrayOf(7, 8, 9, 10), carry.push(byteArrayOf(8, 9, 10), 3))
28
+ assertFalse(carry.hasPendingByte)
29
+ assertNull(carry.push(byteArrayOf(), 0))
30
+ }
31
+
32
+ @Test
33
+ fun compressedContentTypesAreRejectedAndRawTypesPlayed() {
34
+ for (type in listOf("audio/mpeg", "Audio/MPEG; charset=binary", "audio/mp3", "audio/aac", "audio/ogg", "audio/opus", "audio/webm")) {
35
+ assertTrue(type, PcmUrlPlayback.isCompressedAudio(type))
36
+ }
37
+ for (type in listOf(null, "", "audio/L16; rate=24000", "audio/pcm", "application/octet-stream")) {
38
+ assertFalse(type.toString(), PcmUrlPlayback.isCompressedAudio(type))
39
+ }
40
+ assertEquals("audio/mpeg", PcmUrlPlayback.mediaType(" Audio/MPEG ; q=1"))
41
+ }
42
+
43
+ /** Returns at most a scripted number of bytes per read, like a network body. */
44
+ private class TricklingStream(private val data: ByteArray, private val sizes: IntArray) : InputStream() {
45
+ private var pos = 0
46
+ private var call = 0
47
+
48
+ override fun read(): Int = if (pos < data.size) data[pos++].toInt() and 0xff else -1
49
+
50
+ override fun read(b: ByteArray, off: Int, len: Int): Int {
51
+ if (pos >= data.size) return -1
52
+ val n = minOf(len, sizes[call++ % sizes.size], data.size - pos)
53
+ System.arraycopy(data, pos, b, off, n)
54
+ pos += n
55
+ return n
56
+ }
57
+ }
58
+
59
+ @Test
60
+ fun pumpWritesEverySampleInOrderInEvenChunks() {
61
+ val body = ByteArray(10_001) { (it * 7).toByte() }
62
+ val written = ByteArrayOutputStream()
63
+ val chunkSizes = mutableListOf<Int>()
64
+
65
+ val total =
66
+ PcmUrlPlayback.pump(TricklingStream(body, intArrayOf(1, 333, 2, 4095, 7, 64))) { chunk ->
67
+ chunkSizes.add(chunk.size)
68
+ written.write(chunk)
69
+ }
70
+
71
+ // The final odd byte has no pair and is dropped; everything else arrives in order.
72
+ assertEquals(10_000L, total)
73
+ assertArrayEquals(body.copyOf(10_000), written.toByteArray())
74
+ assertTrue(chunkSizes.all { it > 0 && it % 2 == 0 })
75
+ }
76
+ }
@@ -69,6 +69,26 @@ export type GlassesMediaVolumeGetResult = {
69
69
  export type GlassesMediaVolumeSetResult = {
70
70
  statusCode: number;
71
71
  };
72
+ /** On-device keyword spotter state and detections. Describes only the wake-word model. */
73
+ export type WakeWordEvent = {
74
+ kind: "loading" | "ready" | "detected" | "error";
75
+ phrase: string;
76
+ /** Unix epoch milliseconds. */
77
+ timestamp: number;
78
+ message?: string;
79
+ };
80
+ /**
81
+ * Phone-side speech activity from the on-device Silero detector
82
+ * ([setSpeechActivityDetection]). Sent on transitions only. A gap in incoming
83
+ * microphone audio counts as silence.
84
+ */
85
+ export type SpeechActivityEvent = {
86
+ speaking: boolean;
87
+ /** 0 while speaking; on a silence transition, how long the audio has been silent. */
88
+ silentForMs: number;
89
+ /** Unix epoch milliseconds. */
90
+ timestamp: number;
91
+ };
72
92
  export type LocalTranscriptionEvent = {
73
93
  text: string;
74
94
  isFinal?: boolean;
@@ -1089,6 +1109,8 @@ export type BluetoothSdkModuleEvents = {
1089
1109
  voice_activity_detection_status: (event: VoiceActivityDetectionStatusEvent) => void;
1090
1110
  speaking_status: (event: SpeakingStatusEvent) => void;
1091
1111
  battery_status: (event: BatteryStatusEvent) => void;
1112
+ wake_word: (event: WakeWordEvent) => void;
1113
+ speech_activity: (event: SpeechActivityEvent) => void;
1092
1114
  local_transcription: (event: LocalTranscriptionEvent) => void;
1093
1115
  native_notification_status: (event: NativeNotificationStatus) => void;
1094
1116
  native_notification_delivery: (event: NativeNotificationDelivery) => void;
@@ -1240,6 +1262,8 @@ export type BluetoothSdkEventMap = {
1240
1262
  voice_activity_detection_status: VoiceActivityDetectionStatusEvent;
1241
1263
  speaking_status: SpeakingStatusEvent;
1242
1264
  battery_status: BatteryStatusEvent;
1265
+ wake_word: WakeWordEvent;
1266
+ speech_activity: SpeechActivityEvent;
1243
1267
  local_transcription: LocalTranscriptionEvent;
1244
1268
  wifi_status_change: WifiStatusChangeEvent;
1245
1269
  wifi_scan_result: WifiScanResultEvent;
@@ -1432,7 +1456,32 @@ export interface BluetoothSdkPublicModule {
1432
1456
  checkSttModelAvailable(): Promise<boolean>;
1433
1457
  validateSttModel(path: string): Promise<boolean>;
1434
1458
  extractTarBz2(sourcePath: string, destinationPath: string): Promise<boolean>;
1459
+ /**
1460
+ * Start or stop on-device keyword spotting on microphone PCM. `modelDir` must contain
1461
+ * `encoder.int8.onnx`, `decoder.onnx`, `joiner.int8.onnx`, `tokens.txt` and `keywords.txt`;
1462
+ * it is required when enabling. Disabling releases the model.
1463
+ */
1464
+ setWakeWordDetection(enabled: boolean, modelDir?: string | null): Promise<void>;
1465
+ /**
1466
+ * Finalize the active on-device recognizer's current utterance now. Resolves after the final
1467
+ * `local_transcription` event for it has been emitted, with that final text (empty when nothing
1468
+ * was pending). Resolves `null` when no streaming model is active or the loaded model can't
1469
+ * finalize early.
1470
+ */
1471
+ finishTranscription(): Promise<string | null>;
1472
+ /**
1473
+ * Reload the selected speech model when on-device transcription is in demand. Resolves after
1474
+ * it is loaded; rejects when loading fails; resolves immediately when there is no demand.
1475
+ */
1435
1476
  restartTranscriber(): Promise<void>;
1477
+ /**
1478
+ * Start or stop the on-device Silero speech detector on microphone PCM. While enabled it emits
1479
+ * `speech_activity` transitions; `minSilenceMs` (default 300) is the quiet gap before a silence
1480
+ * transition. Disabling releases the model.
1481
+ */
1482
+ setSpeechActivityDetection(enabled: boolean, options?: {
1483
+ minSilenceMs?: number;
1484
+ }): Promise<void>;
1436
1485
  setTtsModelDetails(path: string, languageCode: string): Promise<void>;
1437
1486
  getTtsModelPath(): Promise<string>;
1438
1487
  getTtsModelLanguage(): Promise<string>;