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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/MIGRATION.md +61 -0
  2. package/README.md +80 -11
  3. package/android/build.gradle +60 -51
  4. package/android/gradle.properties +3 -0
  5. package/android/settings.gradle +47 -3
  6. package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -2
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +85 -6
  9. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +35 -1
  10. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +154 -110
  11. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +21 -0
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +1 -0
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +27 -2
  15. package/android/src/main/java/com/mentra/bluetoothsdk/connection/ConnectionModels.kt +5 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicy.kt +64 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +925 -155
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +227 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +19 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicy.kt +94 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachine.kt +411 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateStore.kt +124 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +54 -59
  25. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +5 -32
  26. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +8 -1
  27. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +3 -10
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  29. package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +50 -0
  30. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  31. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  32. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  33. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  34. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  35. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  36. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  38. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  39. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  40. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  41. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  42. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  43. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  44. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  45. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerOwnerLossTest.kt +146 -0
  46. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusAudioSetupTest.kt +51 -0
  47. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusClassicAudioTest.kt +2 -0
  48. package/android/src/test/java/com/mentra/bluetoothsdk/WifiAdbPeerIntentTest.kt +19 -0
  49. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicyTest.kt +65 -0
  50. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveAudioSetupReadinessTest.kt +231 -0
  51. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +5 -1
  52. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +368 -0
  54. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +20 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicyTest.kt +136 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachineTest.kt +346 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  58. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  59. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  60. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  61. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  62. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  63. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  64. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  65. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  66. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  67. package/build/BluetoothSdk.types.d.ts +201 -1
  68. package/build/BluetoothSdk.types.d.ts.map +1 -1
  69. package/build/BluetoothSdk.types.js.map +1 -1
  70. package/build/_private/BluetoothSdkModule.d.ts +43 -5
  71. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  72. package/build/_private/BluetoothSdkModule.js +2 -0
  73. package/build/_private/BluetoothSdkModule.js.map +1 -1
  74. package/build/generated/changelogCatalog.d.ts +3 -0
  75. package/build/generated/changelogCatalog.d.ts.map +1 -1
  76. package/build/generated/changelogCatalog.js +4 -0
  77. package/build/generated/changelogCatalog.js.map +1 -1
  78. package/build/generated/releaseMetadata.js +6 -6
  79. package/build/generated/releaseMetadata.js.map +1 -1
  80. package/build/index.d.ts +1 -1
  81. package/build/index.d.ts.map +1 -1
  82. package/build/index.js +9 -0
  83. package/build/index.js.map +1 -1
  84. package/ios/BluetoothSdkModule.swift +76 -12
  85. package/ios/MentraBluetoothSDK.podspec +4 -0
  86. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  87. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  88. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  89. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  90. package/ios/Source/Bridge.swift +11 -3
  91. package/ios/Source/DeviceManager.swift +131 -18
  92. package/ios/Source/DeviceStore.swift +27 -0
  93. package/ios/Source/GeneratedChangelogCatalog.swift +1 -0
  94. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  95. package/ios/Source/MentraBluetoothSDK.swift +40 -5
  96. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  97. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  98. package/ios/Source/audio/SpeechActivity.swift +277 -0
  99. package/ios/Source/errors/BluetoothSdkError.swift +5 -1
  100. package/ios/Source/events/BluetoothEvents.swift +41 -0
  101. package/ios/Source/internal/BleTraceLogger.swift +9 -6
  102. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  103. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +186 -0
  104. package/ios/Source/sgcs/MentraLive.swift +1270 -189
  105. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +260 -1
  106. package/ios/Source/sgcs/MentraLivePairingStateMachine.swift +385 -0
  107. package/ios/Source/sgcs/MentraLivePairingStateStore.swift +121 -0
  108. package/ios/Source/sgcs/Nimo.swift +10 -3
  109. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +39 -9
  110. package/ios/Source/sgcs/SGCManager.swift +13 -0
  111. package/ios/Source/sgcs/Simulated.swift +2 -0
  112. package/ios/Source/status/DeviceStatus.swift +35 -0
  113. package/ios/Source/stt/STTTools.swift +13 -31
  114. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  115. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  116. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  117. package/ios/Source/types/DeviceModels.swift +8 -1
  118. package/ios/Source/utils/AudioSessionMonitor.swift +158 -5
  119. package/ios/Source/utils/BoundedWait.swift +44 -0
  120. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  121. package/ios/Source/utils/SttModelTraits.swift +62 -0
  122. package/ios/Tests/BesCrashReportTests.swift +142 -0
  123. package/ios/Tests/BluetoothAudioRouteTests.swift +82 -0
  124. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  125. package/ios/Tests/DeviceManagerReconnectTests.swift +4 -2
  126. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +197 -0
  127. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  128. package/ios/Tests/MentraLiveAudioSetupTests.swift +209 -0
  129. package/ios/Tests/MentraLiveConnectionOptionsTests.swift +55 -0
  130. package/ios/Tests/MentraLivePairingAdvertisementTests.swift +327 -0
  131. package/ios/Tests/MentraLivePairingStateMachineTests.swift +402 -0
  132. package/ios/Tests/MentraLiveSessionReadinessTests.swift +368 -26
  133. package/ios/Tests/NimoCanvasTransportTests.swift +58 -0
  134. package/ios/Tests/PcmStreamTests.swift +299 -0
  135. package/ios/Tests/SpeechActivityTests.swift +238 -0
  136. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  137. package/ios/Tests/WifiAdbDispatchTests.swift +118 -0
  138. package/package.json +3 -2
  139. package/plugin/build/withAndroid.js +9 -11
  140. package/plugin/build/withKotlinVersion.d.ts +2 -0
  141. package/plugin/build/withKotlinVersion.js +46 -0
  142. package/src/BluetoothSdk.types.ts +201 -1
  143. package/src/_private/BluetoothSdkModule.ts +47 -5
  144. package/src/generated/changelogCatalog.ts +4 -0
  145. package/src/generated/releaseMetadata.ts +6 -6
  146. package/src/index.ts +22 -0
  147. package/android/silero/LICENSE.md +0 -17
  148. package/android/silero/build.gradle +0 -50
  149. package/android/silero/proguard-rules.pro +0 -24
  150. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  151. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  152. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  153. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  154. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  155. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  156. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  157. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  158. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  159. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  160. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  161. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  162. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  163. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  164. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  165. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  166. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -288
  167. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  168. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -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
+ }
@@ -0,0 +1,169 @@
1
+ package com.mentra.bluetoothsdk.stt
2
+
3
+ import java.util.concurrent.CompletableFuture
4
+ import java.util.concurrent.Executor
5
+
6
+ /**
7
+ * Owns the one on-device speech recognizer and loads it only while on-device transcription is
8
+ * in demand.
9
+ *
10
+ * - Models load on [loader], never on the audio thread and never while [lock] is held.
11
+ * - A finished load is swapped in under [lock]; the replaced recognizer is released after the
12
+ * swap, so the audio thread can no longer reach it by the time [release] runs. [release]
13
+ * must not free native memory on the calling thread (the recognizer releases on its own
14
+ * worker after the audio already queued to it).
15
+ * - [current] and [isLoaded] are lock-free volatile reads, safe on the audio thread and on
16
+ * Expo's shared module queue.
17
+ * - Demand ending releases the recognizer and discards any load still in flight.
18
+ */
19
+ internal class OnDeviceRecognizerHost<R : Any>(
20
+ private val selection: () -> Selection?,
21
+ private val loadModel: (Selection) -> R,
22
+ private val pathMatches: (R, String) -> Boolean,
23
+ private val release: (R) -> Unit,
24
+ private val loader: Executor,
25
+ private val log: (String) -> Unit = {},
26
+ ) {
27
+ /** The model to load: its stored path and language. */
28
+ data class Selection(val path: String, val language: String)
29
+
30
+ private class Pending(val generation: Long, val selection: Selection) {
31
+ val result = CompletableFuture<Unit>()
32
+ }
33
+
34
+ private val lock = Any()
35
+
36
+ /** The loaded recognizer, or null. Read without locking. */
37
+ @Volatile
38
+ var current: R? = null
39
+ private set
40
+
41
+ // Guarded by lock.
42
+ private var currentSelection: Selection? = null
43
+ private var demand = false
44
+ private var generation = 0L
45
+ private var pending: Pending? = null
46
+
47
+ /** Whether the loaded recognizer has [path]. Never blocks. */
48
+ fun isLoaded(path: String): Boolean {
49
+ val recognizer = current ?: return false
50
+ return pathMatches(recognizer, path)
51
+ }
52
+
53
+ /**
54
+ * On-device transcription demand changed. Gaining demand starts loading the selected model;
55
+ * losing it releases the recognizer and invalidates an in-flight load.
56
+ */
57
+ fun setDemand(active: Boolean) {
58
+ val selected = if (active) selection() else null
59
+ var toRelease: R? = null
60
+ var settle: Pending? = null
61
+ synchronized(lock) {
62
+ if (demand == active) return
63
+ demand = active
64
+ if (active) {
65
+ if (selected != null && !(current != null && currentSelection == selected)) {
66
+ startLoadLocked(selected)
67
+ }
68
+ } else {
69
+ generation++
70
+ settle = pending
71
+ pending = null
72
+ toRelease = current
73
+ current = null
74
+ currentSelection = null
75
+ }
76
+ }
77
+ // A restart waiting on a discarded load resolves: there is no demand any more.
78
+ settle?.result?.complete(Unit)
79
+ toRelease?.let {
80
+ log("STT: on-device transcription demand ended; releasing the speech model")
81
+ release(it)
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Load the selected model if on-device transcription is in demand. The future completes
87
+ * once that model is loaded (immediately when it already is, or when there is no demand)
88
+ * and fails if loading fails.
89
+ */
90
+ fun restart(): CompletableFuture<Unit> {
91
+ val selected = selection()
92
+ synchronized(lock) {
93
+ if (!demand) return CompletableFuture.completedFuture(Unit)
94
+ if (selected == null) {
95
+ return CompletableFuture<Unit>().apply {
96
+ completeExceptionally(IllegalStateException("No on-device speech model is selected"))
97
+ }
98
+ }
99
+ if (current != null && currentSelection == selected) {
100
+ return CompletableFuture.completedFuture(Unit)
101
+ }
102
+ pending?.let { if (it.selection == selected) return it.result }
103
+ return startLoadLocked(selected).result
104
+ }
105
+ }
106
+
107
+ private fun startLoadLocked(selected: Selection): Pending {
108
+ generation++
109
+ val next = Pending(generation, selected)
110
+ // A superseded load's waiter gets the outcome of the load that replaced it.
111
+ pending?.let { superseded ->
112
+ next.result.whenComplete { _, error ->
113
+ if (error == null) superseded.result.complete(Unit)
114
+ else superseded.result.completeExceptionally(error)
115
+ }
116
+ }
117
+ pending = next
118
+ loader.execute { runLoad(next) }
119
+ return next
120
+ }
121
+
122
+ private fun runLoad(job: Pending) {
123
+ synchronized(lock) {
124
+ if (job.generation != generation) return
125
+ }
126
+ log("STT: loading speech model ${job.selection.path}")
127
+ val startedAt = System.currentTimeMillis()
128
+ var loaded: R? = null
129
+ var failure: Throwable? = null
130
+ try {
131
+ loaded = loadModel(job.selection)
132
+ } catch (error: Exception) {
133
+ failure = error
134
+ } catch (error: LinkageError) {
135
+ // Public SDK builds compile against sherpa-onnx without shipping it.
136
+ failure = IllegalStateException("On-device transcription is not available in this build", error)
137
+ }
138
+
139
+ var toRelease: R? = null
140
+ synchronized(lock) {
141
+ if (job.generation != generation) {
142
+ // Superseded or demand ended while loading: never swap a stale model in.
143
+ toRelease = loaded
144
+ } else {
145
+ pending = null
146
+ if (loaded != null) {
147
+ toRelease = current
148
+ current = loaded
149
+ currentSelection = job.selection
150
+ } else if (currentSelection?.path != job.selection.path) {
151
+ // Don't keep running a model that is no longer the selected one.
152
+ toRelease = current
153
+ current = null
154
+ currentSelection = null
155
+ }
156
+ }
157
+ }
158
+ toRelease?.let(release)
159
+
160
+ if (loaded != null) {
161
+ log("STT: speech model loaded in ${System.currentTimeMillis() - startedAt}ms")
162
+ job.result.complete(Unit)
163
+ } else {
164
+ val error = failure ?: IllegalStateException("Could not load the speech model")
165
+ log("STT: speech model failed to load: ${error.message}")
166
+ job.result.completeExceptionally(error)
167
+ }
168
+ }
169
+ }
@@ -171,31 +171,35 @@ object STTTools {
171
171
  }
172
172
 
173
173
  /**
174
- * Extract a tar.bz2 file to a destination directory
174
+ * Extract a tar.bz2 file to a destination directory.
175
+ *
176
+ * The archive is extracted into a temporary sibling directory, and that directory is renamed
177
+ * to [destinationPath] only once extraction has finished. A partial extract (app killed,
178
+ * disk full, corrupt archive) therefore never passes a files-exist check, so a truncated
179
+ * model can't be loaded (that crashes inside sherpa-onnx's native code). An existing
180
+ * [destinationPath] is replaced only after a successful extract.
175
181
  *
176
182
  * @param sourcePath Path to the .tar.bz2 file
177
183
  * @param destinationPath Directory to extract to
178
184
  * @return true if extraction succeeded, false otherwise
179
185
  */
180
186
  fun extractTarBz2(sourcePath: String, destinationPath: String): Boolean {
187
+ val destDir = File(destinationPath)
188
+ val parent = destDir.absoluteFile.parentFile
189
+ if (parent == null) {
190
+ Bridge.log("EXTRACTION_ERROR: Destination has no parent directory: $destinationPath")
191
+ return false
192
+ }
193
+ val staging = File(parent, ".${destDir.name}.extracting-${System.nanoTime()}")
181
194
  try {
182
195
  val sourceFile = File(sourcePath)
183
196
  if (!sourceFile.exists()) {
184
197
  Bridge.log("EXTRACTION_ERROR: Source file does not exist: $sourcePath")
185
198
  return false
186
199
  }
187
-
188
- val destDir = File(destinationPath)
189
-
190
- // Create destination directory if it doesn't exist
191
- if (!destDir.exists()) {
192
- Bridge.log("Creating destination directory: $destinationPath")
193
- if (!destDir.mkdirs()) {
194
- Bridge.log(
195
- "EXTRACTION_ERROR: Failed to create destination directory: $destinationPath"
196
- )
197
- return false
198
- }
200
+ if (!staging.mkdirs()) {
201
+ Bridge.log("EXTRACTION_ERROR: Failed to create staging directory: ${staging.absolutePath}")
202
+ return false
199
203
  }
200
204
 
201
205
  Bridge.log("Extracting tar.bz2 from $sourcePath to $destinationPath")
@@ -204,11 +208,12 @@ object STTTools {
204
208
  val startTime = System.currentTimeMillis()
205
209
  var fileCount = 0
206
210
  var bytesExtracted = 0L
211
+ val stagingPath = staging.canonicalPath
212
+ val stagingRoot = stagingPath + File.separator
207
213
 
208
214
  val totalCompressedBytes = sourceFile.length()
209
215
  Bridge.sendExtractionProgress(0, 0, totalCompressedBytes)
210
216
 
211
- // Open the tar.bz2 file with buffered streams for better performance
212
217
  FileInputStream(sourceFile).use { fis ->
213
218
  ProgressInputStream(fis, totalCompressedBytes) { read, total ->
214
219
  val pct =
@@ -216,140 +221,94 @@ object STTTools {
216
221
  Bridge.sendExtractionProgress(pct, read, total)
217
222
  }.use { progress ->
218
223
  BufferedInputStream(progress, 65536).use { bis ->
219
- Bridge.log("Opening bz2 decompression stream...")
220
224
  BZip2CompressorInputStream(bis).use { bzIn ->
221
- Bridge.log("Opening tar archive stream...")
222
225
  TarArchiveInputStream(bzIn).use { tarIn ->
223
- Bridge.log("Reading first tar entry...")
224
226
  var entry = tarIn.nextEntry
225
-
226
227
  while (entry != null) {
227
- try {
228
- val outputFile = File(destDir, entry.name)
229
-
230
- if (entry.isDirectory) {
231
- if (!outputFile.exists()) {
232
- outputFile.mkdirs()
233
- }
234
- } else {
235
- outputFile.parentFile?.let { parent ->
236
- if (!parent.exists()) {
237
- parent.mkdirs()
238
- }
239
- }
240
-
241
- FileOutputStream(outputFile).use { fos ->
242
- BufferedOutputStream(fos, 65536).use { bos ->
243
- // 64KB buffer matches iOS path and cuts JNI/stream
244
- // overhead ~16x vs. the prior 4KB. The per-read
245
- // progress hook is already 200ms-throttled by
246
- // ProgressInputStream, so we don't log per-chunk.
247
- val buffer = ByteArray(65536)
248
- var len: Int
249
- var fileBytes = 0L
250
- val fileSizeMB = entry.size / 1024 / 1024
251
- var lastProgressMB = 0L
252
-
253
- while (tarIn.read(buffer).also { len = it } != -1) {
254
- bos.write(buffer, 0, len)
255
- fileBytes += len
256
- bytesExtracted += len
257
-
258
- if (fileSizeMB > 10) {
259
- val currentMB = fileBytes / 1024 / 1024
260
- if (currentMB >= lastProgressMB + 10) {
261
- lastProgressMB = currentMB
262
- val percent =
263
- if (entry.size > 0)
264
- (fileBytes * 100 / entry.size)
265
- else 0
266
- Bridge.log(
267
- " Extracting ${entry.name}: ${currentMB}MB / ${fileSizeMB}MB (${percent}%)"
268
- )
269
- }
270
- }
271
- }
272
-
273
- fileCount++
228
+ val outputFile = File(staging, entry.name)
229
+ val outputPath = outputFile.canonicalPath
230
+ if (outputPath != stagingPath && !outputPath.startsWith(stagingRoot)) {
231
+ throw IllegalStateException("Archive entry escapes the destination: ${entry.name}")
232
+ }
233
+ if (entry.isDirectory) {
234
+ outputFile.mkdirs()
235
+ } else {
236
+ outputFile.parentFile?.mkdirs()
237
+ FileOutputStream(outputFile).use { fos ->
238
+ BufferedOutputStream(fos, 65536).use { bos ->
239
+ // 64KB buffer matches iOS path and cuts JNI/stream
240
+ // overhead vs. a 4KB buffer. Progress is reported by
241
+ // the 200ms-throttled ProgressInputStream.
242
+ val buffer = ByteArray(65536)
243
+ var len: Int
244
+ while (tarIn.read(buffer).also { len = it } != -1) {
245
+ bos.write(buffer, 0, len)
246
+ bytesExtracted += len
274
247
  }
275
248
  }
276
249
  }
277
-
278
- entry = tarIn.nextEntry
279
- } catch (e: Exception) {
280
- Bridge.log(
281
- "ERROR extracting entry ${entry?.name}: ${e.javaClass.simpleName}: ${e.message}"
282
- )
283
- com.mentra.bluetoothsdk.utils.NativeLog.e("STTTools", "Native exception", e)
284
- throw e
250
+ fileCount++
285
251
  }
252
+ entry = tarIn.nextEntry
286
253
  }
287
-
288
- Bridge.log("Finished reading all tar entries")
289
254
  }
290
255
  }
291
256
  }
292
257
  }
293
258
  }
294
259
 
295
- Bridge.sendExtractionProgress(100, totalCompressedBytes, totalCompressedBytes)
296
-
297
260
  val duration = (System.currentTimeMillis() - startTime) / 1000
298
- val mbExtracted = bytesExtracted / 1024 / 1024
299
261
  Bridge.log(
300
- "Extraction completed successfully: $fileCount files, ${mbExtracted}MB in ${duration}s"
262
+ "Extraction completed: $fileCount files, ${bytesExtracted / 1024 / 1024}MB in ${duration}s"
301
263
  )
302
264
 
303
- // Rename epoch-numbered files to expected names for transducer models
304
- // Files are extracted to a subdirectory, find it
305
- val subdirs = destDir.listFiles { file -> file.isDirectory } ?: emptyArray()
306
- val actualModelDir = if (subdirs.isNotEmpty()) subdirs[0] else destDir
307
- Bridge.log("Model directory: ${actualModelDir.absolutePath}")
308
-
309
- // Rename encoder
310
- val oldEncoderFile = File(actualModelDir, "encoder-epoch-99-avg-1.onnx")
311
- val newEncoderFile = File(actualModelDir, "encoder.onnx")
312
- if (oldEncoderFile.exists()) {
313
- Bridge.log("Renaming encoder-epoch-99-avg-1.onnx to encoder.onnx")
314
- oldEncoderFile.renameTo(newEncoderFile)
315
- }
316
-
317
- // Rename decoder
318
- val oldDecoderFile = File(actualModelDir, "decoder-epoch-99-avg-1.onnx")
319
- val newDecoderFile = File(actualModelDir, "decoder.onnx")
320
- if (oldDecoderFile.exists()) {
321
- Bridge.log("Renaming decoder-epoch-99-avg-1.onnx to decoder.onnx")
322
- oldDecoderFile.renameTo(newDecoderFile)
323
- }
265
+ // Archives usually hold one top-level directory: use it as the model directory.
266
+ val subdirs = staging.listFiles { file -> file.isDirectory } ?: emptyArray()
267
+ val actualModelDir = if (subdirs.isNotEmpty()) subdirs[0] else staging
324
268
 
325
- // Rename joiner
326
- val oldJoinerFile = File(actualModelDir, "joiner-epoch-99-avg-1.int8.onnx")
327
- val newJoinerFile = File(actualModelDir, "joiner.onnx")
328
- if (oldJoinerFile.exists()) {
329
- Bridge.log("Renaming joiner-epoch-99-avg-1.int8.onnx to joiner.onnx")
330
- oldJoinerFile.renameTo(newJoinerFile)
331
- }
269
+ // Rename epoch-numbered files to expected names for transducer models
270
+ renameIfPresent(actualModelDir, "encoder-epoch-99-avg-1.onnx", "encoder.onnx")
271
+ renameIfPresent(actualModelDir, "decoder-epoch-99-avg-1.onnx", "decoder.onnx")
272
+ renameIfPresent(actualModelDir, "joiner-epoch-99-avg-1.int8.onnx", "joiner.onnx")
332
273
 
333
- // If files were extracted to subdirectory, move them to parent directory
334
- if (actualModelDir != destDir) {
335
- Bridge.log("Moving files from subdirectory to parent directory")
274
+ // If files were extracted to a subdirectory, move them up to the staging root
275
+ if (actualModelDir != staging) {
336
276
  actualModelDir.listFiles()?.forEach { file ->
337
- val targetFile = File(destDir, file.name)
338
- if (targetFile.exists()) {
277
+ val targetFile = File(staging, file.name)
278
+ if (targetFile.exists() && targetFile != file) {
339
279
  targetFile.deleteRecursively()
340
280
  }
341
- Bridge.log("Moving ${file.name}")
342
- file.renameTo(targetFile)
281
+ if (!file.renameTo(targetFile)) {
282
+ throw IllegalStateException("Failed to move ${file.name} out of ${actualModelDir.name}")
283
+ }
343
284
  }
344
- // Delete the now-empty subdirectory
345
285
  actualModelDir.delete()
346
286
  }
347
287
 
288
+ // Move the complete model into place.
289
+ if (destDir.exists() && !destDir.deleteRecursively()) {
290
+ throw IllegalStateException("Failed to replace existing directory $destinationPath")
291
+ }
292
+ if (!staging.renameTo(destDir)) {
293
+ throw IllegalStateException("Failed to move extracted model to $destinationPath")
294
+ }
295
+
296
+ Bridge.sendExtractionProgress(100, totalCompressedBytes, totalCompressedBytes)
348
297
  return true
349
298
  } catch (e: Exception) {
350
299
  Bridge.log("EXTRACTION_ERROR: ${e.javaClass.simpleName}: ${e.message}")
351
300
  com.mentra.bluetoothsdk.utils.NativeLog.e("STTTools", "Native exception", e)
352
301
  return false
302
+ } finally {
303
+ if (staging.exists()) staging.deleteRecursively()
304
+ }
305
+ }
306
+
307
+ private fun renameIfPresent(dir: File, from: String, to: String) {
308
+ val source = File(dir, from)
309
+ if (source.exists()) {
310
+ Bridge.log("Renaming $from to $to")
311
+ source.renameTo(File(dir, to))
353
312
  }
354
313
  }
355
314