@mentra/bluetooth-sdk 3.4.0-dev.999 → 3.4.1-beta.1409

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 (216) hide show
  1. package/MIGRATION.md +16 -7
  2. package/README.md +41 -14
  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/assets/nimo/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -1
  9. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +77 -6
  10. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +41 -0
  11. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +131 -122
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +3 -2
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +31 -10
  15. package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +57 -196
  16. package/android/src/main/java/com/mentra/bluetoothsdk/OtaManifest.kt +1 -16
  17. package/android/src/main/java/com/mentra/bluetoothsdk/debug/BleTraceLogger.kt +10 -1
  18. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/Ipv4Prefix.kt +51 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/NetworkFacts.kt +81 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkError.kt +108 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadiness.kt +103 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpec.kt +44 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkState.kt +117 -0
  25. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedSoftApNetwork.kt +598 -0
  26. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/SoftApTrace.kt +143 -0
  27. package/android/src/main/java/com/mentra/bluetoothsdk/otaserver/MentraOtaServerModule.kt +0 -7
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTracker.kt +15 -0
  29. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +308 -60
  30. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +14 -5
  31. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +210 -325
  32. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +0 -35
  33. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +2 -10
  34. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdater.kt +213 -0
  35. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocol.kt +112 -0
  36. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/streaming/StreamModels.kt +17 -6
  38. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  39. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  40. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  41. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  42. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  43. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  44. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  45. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  46. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  47. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  48. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  49. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  50. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  51. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  52. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/StreamRequestCaptureAudioTest.kt +23 -4
  54. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/Ipv4PrefixTest.kt +59 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/NetworkFactsTest.kt +59 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedLocalNetworkPermissionTest.kt +35 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkErrorTest.kt +85 -0
  58. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkLifecycleTest.kt +164 -0
  59. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadinessTest.kt +141 -0
  60. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpecTest.kt +56 -0
  61. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/SoftApTraceTest.kt +97 -0
  62. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/UnavailableRetryTest.kt +47 -0
  63. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTrackerTest.kt +26 -0
  64. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
  65. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  66. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +9 -3
  67. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
  68. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  69. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  70. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareTargetTest.kt +15 -0
  71. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdaterTest.kt +76 -0
  72. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocolTest.kt +77 -0
  73. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  74. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoReadinessDriverTest.kt +31 -1
  75. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  76. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  77. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  78. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  79. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  80. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  81. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  82. package/build/BluetoothSdk.types.d.ts +103 -5
  83. package/build/BluetoothSdk.types.d.ts.map +1 -1
  84. package/build/BluetoothSdk.types.js.map +1 -1
  85. package/build/_private/BluetoothSdkModule.d.ts +42 -8
  86. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  87. package/build/_private/BluetoothSdkModule.js +1 -0
  88. package/build/_private/BluetoothSdkModule.js.map +1 -1
  89. package/build/_private/MentraLocalNetworkModule.d.ts +1 -1
  90. package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
  91. package/build/_private/MentraLocalNetworkModule.js.map +1 -1
  92. package/build/generated/changelogCatalog.d.ts +5 -2
  93. package/build/generated/changelogCatalog.d.ts.map +1 -1
  94. package/build/generated/changelogCatalog.js +6 -2
  95. package/build/generated/changelogCatalog.js.map +1 -1
  96. package/build/generated/releaseMetadata.js +6 -6
  97. package/build/generated/releaseMetadata.js.map +1 -1
  98. package/build/index.d.ts +1 -1
  99. package/build/index.d.ts.map +1 -1
  100. package/build/index.js +7 -1
  101. package/build/index.js.map +1 -1
  102. package/build/ota-server/MentraOtaServerModule.d.ts +0 -2
  103. package/build/ota-server/MentraOtaServerModule.d.ts.map +1 -1
  104. package/build/ota-server/MentraOtaServerModule.js.map +1 -1
  105. package/build/ota-server/MentraOtaServerModule.web.d.ts +0 -1
  106. package/build/ota-server/MentraOtaServerModule.web.d.ts.map +1 -1
  107. package/build/ota-server/MentraOtaServerModule.web.js +0 -3
  108. package/build/ota-server/MentraOtaServerModule.web.js.map +1 -1
  109. package/build/ota-transport/index.d.ts +3 -3
  110. package/build/ota-transport/index.d.ts.map +1 -1
  111. package/build/ota-transport/index.js +4 -4
  112. package/build/ota-transport/index.js.map +1 -1
  113. package/build/react/useGlassesConnection.d.ts +1 -1
  114. package/build/react/useGlassesConnection.d.ts.map +1 -1
  115. package/build/react/useGlassesConnection.js +3 -3
  116. package/build/react/useGlassesConnection.js.map +1 -1
  117. package/build/react/useMentraBluetooth.d.ts +1 -1
  118. package/build/react/useMentraBluetooth.d.ts.map +1 -1
  119. package/build/react/useMentraBluetooth.js +1 -1
  120. package/build/react/useMentraBluetooth.js.map +1 -1
  121. package/ios/BluetoothSdkModule.swift +73 -22
  122. package/ios/LocalIPv4.swift +0 -61
  123. package/ios/MentraBluetoothSDK.podspec +7 -1
  124. package/ios/MentraOtaServerModule.swift +0 -16
  125. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  126. package/ios/Resources/NimoFirmware/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
  127. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  128. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  129. package/ios/Source/BluetoothSdkDefaults.swift +4 -4
  130. package/ios/Source/Bridge.swift +14 -0
  131. package/ios/Source/DeviceManager.swift +52 -22
  132. package/ios/Source/GeneratedChangelogCatalog.swift +3 -2
  133. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  134. package/ios/Source/MentraBluetoothSDK.swift +35 -16
  135. package/ios/Source/OtaManifest.swift +1 -17
  136. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  137. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  138. package/ios/Source/audio/SpeechActivity.swift +277 -0
  139. package/ios/Source/events/BluetoothEvents.swift +41 -0
  140. package/ios/Source/internal/BleTraceLogger.swift +14 -1
  141. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  142. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +5 -0
  143. package/ios/Source/sgcs/MentraLive.swift +207 -66
  144. package/ios/Source/sgcs/Nimo.swift +249 -276
  145. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +9 -38
  146. package/ios/Source/sgcs/NimoCanvasSession.swift +0 -1
  147. package/ios/Source/sgcs/NimoFirmwareUpdater.swift +260 -0
  148. package/ios/Source/sgcs/NimoOtaProtocol.swift +159 -0
  149. package/ios/Source/sgcs/SGCManager.swift +6 -0
  150. package/ios/Source/streaming/StreamModels.swift +15 -6
  151. package/ios/Source/stt/STTTools.swift +13 -31
  152. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  153. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  154. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  155. package/ios/Source/utils/BoundedWait.swift +44 -0
  156. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  157. package/ios/Source/utils/SttModelTraits.swift +62 -0
  158. package/ios/Tests/BesCrashReportTests.swift +142 -0
  159. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  160. package/ios/Tests/DeviceManagerReconnectTests.swift +0 -71
  161. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +9 -3
  162. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  163. package/ios/Tests/MentraLiveAudioSetupTests.swift +6 -12
  164. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  165. package/ios/Tests/MentraLiveSessionReadinessTests.swift +179 -10
  166. package/ios/Tests/NimoCanvasTransportTests.swift +0 -89
  167. package/ios/Tests/NimoOtaProtocolTests.swift +78 -0
  168. package/ios/Tests/PcmStreamTests.swift +299 -0
  169. package/ios/Tests/SpeechActivityTests.swift +238 -0
  170. package/ios/Tests/StreamRequestTests.swift +18 -0
  171. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  172. package/package.json +2 -2
  173. package/plugin/build/withAndroid.js +9 -11
  174. package/plugin/build/withKotlinVersion.d.ts +2 -0
  175. package/plugin/build/withKotlinVersion.js +46 -0
  176. package/src/BluetoothSdk.types.ts +107 -5
  177. package/src/_private/BluetoothSdkModule.ts +45 -8
  178. package/src/_private/MentraLocalNetworkModule.ts +5 -1
  179. package/src/generated/changelogCatalog.ts +6 -2
  180. package/src/generated/releaseMetadata.ts +6 -6
  181. package/src/index.ts +13 -1
  182. package/src/ota-server/MentraOtaServerModule.ts +0 -2
  183. package/src/ota-server/MentraOtaServerModule.web.ts +0 -4
  184. package/src/ota-transport/index.ts +4 -5
  185. package/src/react/useGlassesConnection.ts +4 -4
  186. package/src/react/useMentraBluetooth.ts +2 -2
  187. package/android/silero/LICENSE.md +0 -17
  188. package/android/silero/build.gradle +0 -50
  189. package/android/silero/proguard-rules.pro +0 -24
  190. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  191. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  192. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  193. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  194. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  195. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  196. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  197. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  198. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  199. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  200. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  201. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  202. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -274
  203. package/android/src/main/java/com/mentra/bluetoothsdk/ScopedNetworkReadiness.kt +0 -17
  204. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  205. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  206. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -16
  207. package/android/src/test/java/com/mentra/bluetoothsdk/ScopedNetworkReadinessTest.kt +0 -39
  208. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  209. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  210. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -851
  211. package/ios/Source/sgcs/NimoMacResourceTransport.swift +0 -217
  212. package/ios/Source/sgcs/NimoResourceFixture.swift +0 -384
  213. package/ios/Source/sgcs/NimoResourceSession.swift +0 -406
  214. package/ios/Tests/NimoResourceSessionTests.swift +0 -476
  215. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  216. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -121,8 +121,6 @@ internal class NimoCanvasCoordinator(
121
121
  private val enqueue: (List<ByteArray>, () -> Unit, () -> Unit) -> Boolean,
122
122
  private val reconnect: (String) -> Unit,
123
123
  private val rejected: (Int) -> Unit = {},
124
- private val holdPreempted: () -> Unit = {},
125
- private val businessResponse: (Int, Int) -> Unit = { _, _ -> },
126
124
  ) {
127
125
  private class Flight(val action: NimoCanvasSession.Action.Send) {
128
126
  var finalStarted = false
@@ -131,21 +129,13 @@ internal class NimoCanvasCoordinator(
131
129
  }
132
130
  private val session = NimoCanvasSession()
133
131
  private var flight: Flight? = null
134
- private var holdReady: (() -> Unit)? = null
135
- private var holding = false
136
- private var heldScope: String? = null
137
132
  private var cancelDeadline: (() -> Unit)? = null
138
133
  private var cancelRetry: (() -> Unit)? = null
139
134
 
140
135
  fun pendingCount(): Int = if (flight != null) 1 else 0
141
136
  fun active(): Boolean = session.active()
142
- fun launchPending(): Boolean = flight?.action?.key == 1
143
137
 
144
138
  fun offer(bytes: ByteArray, scope: String, force: Boolean = false) {
145
- if (holding && scope != heldScope) {
146
- releaseHold(resume = false)
147
- holdPreempted()
148
- }
149
139
  run(session.offer(bytes, scope, force))
150
140
  }
151
141
  fun activate() = run(session.activate())
@@ -157,19 +147,6 @@ internal class NimoCanvasCoordinator(
157
147
  if (!ready) { cancelRetry?.invoke(); cancelRetry = null }
158
148
  run(session.confirmedReadiness(ready))
159
149
  }
160
- fun hold(onReady: () -> Unit) {
161
- session.hold(true)
162
- holding = true
163
- heldScope = session.currentScope()
164
- holdReady = onReady
165
- notifyHoldReadyIfIdle()
166
- }
167
- fun releaseHold(resume: Boolean = true) {
168
- holdReady = null
169
- holding = false
170
- heldScope = null
171
- run(session.hold(false, resume))
172
- }
173
150
  fun exit() {
174
151
  cancelRetry?.invoke(); cancelRetry = null
175
152
  run(session.exit())
@@ -180,9 +157,6 @@ internal class NimoCanvasCoordinator(
180
157
  cancelRetry?.invoke(); cancelRetry = null
181
158
  cancelDeadline?.invoke(); cancelDeadline = null
182
159
  flight = null
183
- holdReady = null
184
- holding = false
185
- heldScope = null
186
160
  session.disconnected()
187
161
  }
188
162
 
@@ -195,16 +169,7 @@ internal class NimoCanvasCoordinator(
195
169
  }
196
170
  cancelDeadline?.invoke(); cancelDeadline = null
197
171
  flight = null
198
- businessResponse(key, payload[0].toInt() and 255)
199
172
  run(session.response(key, payload))
200
- notifyHoldReadyIfIdle()
201
- }
202
-
203
- private fun notifyHoldReadyIfIdle() {
204
- if (flight != null) return
205
- val ready = holdReady ?: return
206
- holdReady = null
207
- ready()
208
173
  }
209
174
 
210
175
  private fun run(actions: List<NimoCanvasSession.Action>) {
@@ -11,7 +11,6 @@ internal class NimoCanvasSession {
11
11
  private var ready = false
12
12
  private var transportReady = false
13
13
  private var active = false
14
- private var held = false
15
14
  private var locked = false
16
15
  private var launchBlocked = false
17
16
  private var waitingReadiness = false
@@ -54,14 +53,7 @@ internal class NimoCanvasSession {
54
53
  return pump()
55
54
  }
56
55
 
57
- /** Debug capture seam; production behavior is unchanged unless explicitly held. */
58
- fun hold(value: Boolean, resume: Boolean = true): List<Action> {
59
- held = value
60
- return if (!value && resume) pump() else emptyList()
61
- }
62
-
63
56
  fun active(): Boolean = active
64
- fun currentScope(): String? = scope
65
57
 
66
58
  fun readiness(value: Boolean): List<Action> = updateReadiness(value, confirmed = false)
67
59
 
@@ -88,7 +80,7 @@ internal class NimoCanvasSession {
88
80
 
89
81
  /** A new transport generation has no accepted frame. Retain only the latest desired scene. */
90
82
  fun disconnected() {
91
- ready = false; transportReady = false; active = false; held = false; locked = false; launchBlocked = false
83
+ ready = false; transportReady = false; active = false; locked = false; launchBlocked = false
92
84
  waitingReadiness = false; observedNotReady = false
93
85
  readinessRetries = 0; probeRetries = 0
94
86
  accepted = null; rejected = null; flight = null; ticket++; forceRevision++
@@ -161,7 +153,7 @@ internal class NimoCanvasSession {
161
153
  }
162
154
 
163
155
  private fun pump(): List<Action> {
164
- if (!ready || held || locked || launchBlocked || waitingReadiness || flight != null) return emptyList()
156
+ if (!ready || locked || launchBlocked || waitingReadiness || flight != null) return emptyList()
165
157
  val next = desired
166
158
  val key = when {
167
159
  exitRequested && active -> 3
@@ -0,0 +1,213 @@
1
+ package com.mentra.bluetoothsdk.sgcs
2
+
3
+ import java.security.MessageDigest
4
+
5
+ /** The one NIMO firmware the app supports: the vendor's 537cf1 dynamic-v1 build. */
6
+ internal object NimoFirmwareTarget {
7
+ const val PACKED_VERSION = "0.1.1.1"
8
+ const val BUILD_TAG = "537cf1"
9
+ const val SHA256 = "5e23c574e3dfd8c27172f4f9a33475e6efd0d33e7230bfcce8f4fe8ca59fe433"
10
+ const val ASSET_PATH = "nimo/nimo-firmware-0.1.1.1-537cf1.bin"
11
+ const val UPDATING_TEXT = "Updating your NIMO glasses.\n\nKeep the Mentra app open."
12
+
13
+ /** A missing detail string (older firmware) is judged on the packed version alone. */
14
+ fun isCurrent(packedVersion: String, detail: String): Boolean =
15
+ packedVersion == PACKED_VERSION && (detail.isEmpty() || detail.contains("-$BUILD_TAG-"))
16
+
17
+ fun sha256(bytes: ByteArray): String =
18
+ MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it.toInt() and 255) }
19
+ }
20
+
21
+ /**
22
+ * Single-attempt NIMO OTA over the 2001/2002 channel. Main-thread confined; [scheduler] posts there.
23
+ * [finished] gets null once the reboot command was sent, otherwise the failure reason.
24
+ * No failure path sends reset; the next connection decides again from the reported version.
25
+ */
26
+ internal class NimoFirmwareUpdater(
27
+ firmware: ByteArray,
28
+ writeCapacity: Int,
29
+ private val scheduler: NimoScheduler,
30
+ private val write: (ByteArray, (Boolean) -> Unit) -> Unit,
31
+ private val progress: (Int) -> Unit,
32
+ private val finished: (String?) -> Unit,
33
+ ) {
34
+ private class Pending(val command: Int, val sequence: Int, val callback: (Result<ByteArray>) -> Unit)
35
+
36
+ private val firmware = firmware.copyOf()
37
+ private val capacity = writeCapacity.coerceAtMost(512)
38
+ private val decoder = NimoOtaProtocol.Decoder()
39
+ private var sequence = 0
40
+ private var pending: Pending? = null
41
+ private var cancelTimer: (() -> Unit)? = null
42
+ private var cancelDelay: (() -> Unit)? = null
43
+ private var done = false
44
+ private var crc = false
45
+ private val covered = BooleanArray(firmware.size)
46
+ private var coveredCount = 0
47
+ private var lastPercent = -1
48
+ private var stalls = 0
49
+ private var transferStarted = 0L
50
+ private var syncPending = 0
51
+ private var syncFailures = 0
52
+
53
+ fun start() {
54
+ exchange(NimoOtaProtocol.INFO, ByteArray(4) { 255.toByte() }) { info ->
55
+ checkDeviceInfo(info)
56
+ exchange(NimoOtaProtocol.FILE_OFFSET) { body ->
57
+ val header = NimoOtaProtocol.firmwareSlice(firmware, NimoOtaProtocol.fileOffset(body))
58
+ exchange(NimoOtaProtocol.CAN_UPDATE, header) { result ->
59
+ // 0 = can update, 3 = same image already staged; anything else is a refusal.
60
+ require(result.contentEquals(byteArrayOf(0)) || result.contentEquals(byteArrayOf(3))) {
61
+ "Glasses refused the firmware (battery or prerequisites)"
62
+ }
63
+ exchange(NimoOtaProtocol.ENTER) { entryBody ->
64
+ val entry = NimoOtaProtocol.enterResult(entryBody)
65
+ crc = entry.crc
66
+ transferStarted = System.currentTimeMillis()
67
+ sendBlock(entry.slice)
68
+ }
69
+ }
70
+ }
71
+ }
72
+ }
73
+
74
+ fun receive(data: ByteArray) {
75
+ if (done) return
76
+ try {
77
+ for (reply in decoder.feed(data)) {
78
+ val expected = pending ?: continue
79
+ if (expected.command != reply.command || expected.sequence != reply.sequence) continue
80
+ pending = null
81
+ cancelTimer?.invoke(); cancelTimer = null
82
+ if (reply.status == 0) expected.callback(Result.success(reply.body))
83
+ else expected.callback(Result.failure(IllegalStateException("OTA command ${reply.command} returned status ${reply.status}")))
84
+ }
85
+ } catch (error: Exception) { fail(error) }
86
+ }
87
+
88
+ /** The connection went away; stop without reporting. */
89
+ fun cancel() {
90
+ done = true
91
+ clearTimers()
92
+ }
93
+
94
+ private fun checkDeviceInfo(body: ByteArray) {
95
+ val fields = NimoOtaProtocol.deviceInfo(body)
96
+ val batteries = fields[2]
97
+ require(fields[3]?.contentEquals(byteArrayOf(1)) == true && fields[5]?.contentEquals(byteArrayOf(1)) == true &&
98
+ batteries?.size == 2) { "Both arms must be connected and ready to update" }
99
+ }
100
+
101
+ private fun sendBlock(slice: NimoOtaProtocol.Slice) {
102
+ check(System.currentTimeMillis() - transferStarted <= 20 * 60_000L) { "Transfer exceeded 20 minutes" }
103
+ val parts = NimoOtaProtocol.blockParts(firmware, slice, crc, capacity)
104
+ sendPart(parts, 0) { body ->
105
+ val next = NimoOtaProtocol.blockResult(body)
106
+ var added = 0
107
+ for (index in slice.offset.toInt() until slice.offset.toInt() + slice.length) {
108
+ if (!covered[index]) { covered[index] = true; added++ }
109
+ }
110
+ coveredCount += added
111
+ stalls = if (added == 0) stalls + 1 else 0
112
+ check(stalls < 5) { "Five repeated blocks without progress" }
113
+ val percent = coveredCount * 100 / firmware.size
114
+ if (percent != lastPercent) { lastPercent = percent; progress(percent) }
115
+ if (next.slice.offset == 0L && next.slice.length == 0) {
116
+ exchange(NimoOtaProtocol.VALIDATE, timeoutMs = 30_000) { validation ->
117
+ require(validation.contentEquals(byteArrayOf(0))) { "Glasses rejected the transferred image" }
118
+ pollSync()
119
+ }
120
+ } else {
121
+ NimoOtaProtocol.firmwareSlice(firmware, next.slice)
122
+ delay(next.delayMs.toLong()) { sendBlock(next.slice) }
123
+ }
124
+ }
125
+ }
126
+
127
+ private fun sendPart(parts: List<ByteArray>, index: Int, completion: (ByteArray) -> Unit) {
128
+ if (index == parts.lastIndex) { exchange(NimoOtaProtocol.BLOCK, parts[index], 30_000, completion); return }
129
+ val packet = nextPacket(NimoOtaProtocol.BLOCK, parts[index])
130
+ write(packet) { ok ->
131
+ if (done) return@write
132
+ if (!ok) fail(IllegalStateException("OTA write failed"))
133
+ else delay(5) { sendPart(parts, index + 1, completion) }
134
+ }
135
+ }
136
+
137
+ /** Wait for the right arm to copy the image to the left arm, then reboot both. */
138
+ private fun pollSync() {
139
+ exchangeResult(NimoOtaProtocol.SYNC, timeoutMs = 8_000) { result ->
140
+ val body = result.getOrNull()
141
+ if (body?.contentEquals(byteArrayOf(0)) == true) {
142
+ val packet = nextPacket(NimoOtaProtocol.RESET, byteArrayOf(0))
143
+ write(packet) { }
144
+ done = true
145
+ clearTimers()
146
+ finished(null)
147
+ return@exchangeResult
148
+ }
149
+ if (body?.contentEquals(byteArrayOf(1)) == true) syncPending++ else syncFailures++
150
+ if (syncPending >= 180 || syncFailures >= 8) fail(IllegalStateException("Arms did not finish synchronizing; no reboot sent"))
151
+ else delay(1_000) { pollSync() }
152
+ }
153
+ }
154
+
155
+ private fun exchange(command: Int, params: ByteArray = byteArrayOf(), timeoutMs: Long = 15_000,
156
+ completion: (ByteArray) -> Unit) {
157
+ exchangeResult(command, params, timeoutMs) { result ->
158
+ try { completion(result.getOrThrow()) } catch (error: Exception) { fail(error) }
159
+ }
160
+ }
161
+
162
+ private fun exchangeResult(command: Int, params: ByteArray = byteArrayOf(), timeoutMs: Long,
163
+ completion: (Result<ByteArray>) -> Unit) {
164
+ if (done) return
165
+ try {
166
+ val packet = nextPacket(command, params)
167
+ val entry = Pending(command, sequence, completion)
168
+ pending = entry
169
+ cancelTimer = scheduler.post(timeoutMs) {
170
+ if (pending === entry && !done) {
171
+ pending = null; cancelTimer = null
172
+ completion(Result.failure(IllegalStateException("OTA command $command timed out")))
173
+ }
174
+ }
175
+ write(packet) { ok ->
176
+ if (!ok && pending === entry && !done) {
177
+ pending = null
178
+ cancelTimer?.invoke(); cancelTimer = null
179
+ completion(Result.failure(IllegalStateException("OTA write failed")))
180
+ }
181
+ }
182
+ } catch (error: Exception) { completion(Result.failure(error)) }
183
+ }
184
+
185
+ private fun nextPacket(command: Int, params: ByteArray = byteArrayOf()): ByteArray {
186
+ sequence = (sequence + 1) and 255
187
+ val packet = NimoOtaProtocol.request(command, sequence, params)
188
+ require(packet.size <= capacity) { "OTA request exceeds the negotiated write capacity" }
189
+ return packet
190
+ }
191
+
192
+ private fun delay(delayMs: Long, callback: () -> Unit) {
193
+ cancelDelay?.invoke()
194
+ cancelDelay = scheduler.post(delayMs) {
195
+ cancelDelay = null
196
+ if (!done) try { callback() } catch (error: Exception) { fail(error) }
197
+ }
198
+ }
199
+
200
+ private fun clearTimers() {
201
+ cancelTimer?.invoke(); cancelTimer = null
202
+ cancelDelay?.invoke(); cancelDelay = null
203
+ pending = null
204
+ decoder.reset()
205
+ }
206
+
207
+ private fun fail(error: Throwable) {
208
+ if (done) return
209
+ done = true
210
+ clearTimers()
211
+ finished(error.message ?: "NIMO firmware update failed")
212
+ }
213
+ }
@@ -0,0 +1,112 @@
1
+ package com.mentra.bluetoothsdk.sgcs
2
+
3
+ import java.util.zip.CRC32
4
+
5
+ /** NIMO's OTA channel (7033/2001/2002), distinct from the normal 0xBF command channel. */
6
+ internal object NimoOtaProtocol {
7
+ const val INFO = 0x02
8
+ const val RESET = 0x03
9
+ const val FILE_OFFSET = 0xE1
10
+ const val CAN_UPDATE = 0xE2
11
+ const val ENTER = 0xE3
12
+ const val BLOCK = 0xE5
13
+ const val VALIDATE = 0xE6
14
+ const val SYNC = 0xE8
15
+ private val header = byteArrayOf(0x70, 0x07, 0x6E)
16
+
17
+ data class Response(val command: Int, val sequence: Int, val status: Int, val body: ByteArray)
18
+ data class Slice(val offset: Long, val length: Int)
19
+ data class EnterResult(val slice: Slice, val crc: Boolean)
20
+ data class BlockResult(val slice: Slice, val delayMs: Int)
21
+
22
+ fun request(command: Int, sequence: Int, params: ByteArray = byteArrayOf()): ByteArray {
23
+ require(command in 0..255 && sequence in 0..255 && params.size <= 65534) { "Invalid OTA request" }
24
+ val length = params.size + 1
25
+ return header + byteArrayOf(0xC0.toByte(), command.toByte(), (length shr 8).toByte(), length.toByte(), sequence.toByte()) + params + 0x33.toByte()
26
+ }
27
+
28
+ /** Bounded incremental decoder. Any malformed frame invalidates this exchange, never resynchronizes silently. */
29
+ class Decoder {
30
+ private var buffer = byteArrayOf()
31
+ fun reset() { buffer = byteArrayOf() }
32
+ fun feed(bytes: ByteArray): List<Response> {
33
+ val result = mutableListOf<Response>()
34
+ try {
35
+ // Append incrementally so a large/coalesced notification cannot grow the retained buffer without bound.
36
+ for (byte in bytes) {
37
+ buffer += byte
38
+ if (buffer.size <= 3) require(buffer.last() == header[buffer.lastIndex]) { "Invalid OTA header" }
39
+ if (buffer.size == 4) require(buffer[3] == 0.toByte()) { "Invalid OTA direction" }
40
+ if (buffer.size >= 7) {
41
+ val length = u16(buffer, 5)
42
+ require(length in 2..4096) { "Invalid OTA response length" }
43
+ if (buffer.size == length + 8) {
44
+ require(buffer.last() == 0x33.toByte()) { "Invalid OTA footer" }
45
+ result += Response(u8(buffer[4]), u8(buffer[8]), u8(buffer[7]), buffer.copyOfRange(9, buffer.size - 1))
46
+ buffer = byteArrayOf()
47
+ }
48
+ }
49
+ }
50
+ } catch (error: IllegalArgumentException) {
51
+ reset()
52
+ throw error
53
+ }
54
+ return result
55
+ }
56
+ }
57
+
58
+ fun deviceInfo(body: ByteArray): Map<Int, ByteArray> {
59
+ val fields = mutableMapOf<Int, ByteArray>()
60
+ var index = 0
61
+ while (index < body.size) {
62
+ val length = u8(body[index])
63
+ require(length >= 1 && length <= body.size - index - 1) { "Truncated OTA device info" }
64
+ val type = u8(body[index + 1])
65
+ require(!fields.containsKey(type)) { "Duplicate OTA device info" }
66
+ fields[type] = body.copyOfRange(index + 2, index + 1 + length)
67
+ index += 1 + length
68
+ }
69
+ return fields
70
+ }
71
+
72
+ fun fileOffset(body: ByteArray): Slice {
73
+ require(body.size == 6) { "Invalid OTA file offset" }
74
+ return Slice(u32(body, 0), u16(body, 4))
75
+ }
76
+
77
+ fun enterResult(body: ByteArray): EnterResult {
78
+ require(body.size == 8 && body[0] == 0.toByte() && u8(body[7]) in 0..1) { "OTA upgrade entry refused" }
79
+ return EnterResult(Slice(u32(body, 1), u16(body, 5)), body[7] == 1.toByte())
80
+ }
81
+
82
+ fun blockResult(body: ByteArray): BlockResult {
83
+ require(body.size == 9 && body[0] == 0.toByte()) { "OTA block refused" }
84
+ val delay = u16(body, 7)
85
+ require(delay <= 30000) { "Invalid OTA block delay" }
86
+ return BlockResult(Slice(u32(body, 1), u16(body, 5)), delay)
87
+ }
88
+
89
+ fun firmwareSlice(firmware: ByteArray, slice: Slice): ByteArray {
90
+ require(slice.offset >= 0 && slice.offset <= firmware.size.toLong() && slice.length > 0 &&
91
+ slice.length.toLong() <= firmware.size.toLong() - slice.offset) { "OTA slice exceeds firmware" }
92
+ return firmware.copyOfRange(slice.offset.toInt(), slice.offset.toInt() + slice.length)
93
+ }
94
+
95
+ /** Each chunk gets its own CRC and sequence; only the final chunk gets a block response. */
96
+ fun blockParts(firmware: ByteArray, slice: Slice, crc: Boolean, writeCapacity: Int): List<ByteArray> {
97
+ val data = firmwareSlice(firmware, slice)
98
+ require(writeCapacity in 20..512) { "Unsupported OTA write capacity" }
99
+ val chunkSize = minOf(496, writeCapacity - 16) - if (crc) 4 else 0
100
+ require(chunkSize > 0) { "OTA write capacity too small for CRC" }
101
+ return (data.indices step chunkSize).map { start ->
102
+ val piece = data.copyOfRange(start, minOf(start + chunkSize, data.size))
103
+ val checksum = if (crc) u32Bytes(CRC32().apply { update(piece) }.value) else byteArrayOf()
104
+ u32Bytes(slice.offset + start) + piece + checksum
105
+ }
106
+ }
107
+
108
+ private fun u8(value: Byte) = value.toInt() and 255
109
+ private fun u16(bytes: ByteArray, offset: Int) = (u8(bytes[offset]) shl 8) or u8(bytes[offset + 1])
110
+ private fun u32(bytes: ByteArray, offset: Int): Long = (0..3).fold(0L) { value, index -> (value shl 8) or u8(bytes[offset + index]).toLong() }
111
+ private fun u32Bytes(value: Long) = byteArrayOf((value shr 24).toByte(), (value shr 16).toByte(), (value shr 8).toByte(), value.toByte())
112
+ }
@@ -1,6 +1,7 @@
1
1
  package com.mentra.bluetoothsdk.sgcs
2
2
 
3
3
  import com.mentra.bluetoothsdk.BluetoothSdkDefaults
4
+ import com.mentra.bluetoothsdk.BluetoothSdkException
4
5
  import com.mentra.bluetoothsdk.Bridge
5
6
  import com.mentra.bluetoothsdk.DeviceStore
6
7
  import com.mentra.bluetoothsdk.PhotoRequest
@@ -348,6 +349,11 @@ abstract class SGCManager {
348
349
  // Incident Reporting
349
350
  abstract fun sendIncidentId(incidentId: String, apiBaseUrl: String? = null)
350
351
 
352
+ /** Tell the glasses Cloud recorded [reportId] for a BES crash incident (Mentra Live only). */
353
+ open fun sendBesCrashReported(incidentKey: String, reportId: String) {
354
+ throw BluetoothSdkException("unsupported_device", "BES crash reporting is not supported on $type.")
355
+ }
356
+
351
357
  // Gallery
352
358
  abstract fun queryGalleryStatus()
353
359
  abstract fun sendGalleryMode()
@@ -67,22 +67,25 @@ data class StreamAudioConfig @JvmOverloads constructor(
67
67
  }
68
68
  }
69
69
 
70
+ /** STUN server for a WHIP stream whose caller names none: the glasses have none of their own. */
71
+ private const val DEFAULT_WHIP_STUN_SERVER = "stun:stun.cloudflare.com:3478"
72
+
70
73
  /** ICE overrides for a WHIP stream. Ignored by the RTMP and SRT paths. */
71
74
  data class StreamIceConfig @JvmOverloads constructor(
72
75
  /**
73
76
  * STUN server the glasses use while gathering candidates.
74
77
  *
75
- * Null and empty are different answers, and both have to survive the BLE round trip. Null
76
- * leaves the glasses on their default Cloudflare STUN server; an empty string is SoftAP
77
- * calling's explicit request for host-only gathering, because the phone's WHIP server sits on
78
- * the glasses' own hotspot where a reflexive candidate is meaningless and unreachable.
78
+ * Null and empty are different answers. Null sends the default Cloudflare STUN server; an
79
+ * empty string is SoftAP calling's explicit request for host-only gathering, because the
80
+ * phone's WHIP server sits on the glasses' own hotspot where a reflexive candidate is
81
+ * meaningless and unreachable.
79
82
  */
80
83
  val stun: String? = null,
81
84
  ) {
82
85
  fun toMap(): Map<String, Any> =
83
86
  buildMap {
84
87
  // Not filtered on blankness, unlike the other optional string fields here: "" is the
85
- // host-only signal, so dropping it would silently restore the default STUN server.
88
+ // host-only signal, so dropping it would silently send the default STUN server.
86
89
  stun?.let { put("stun", it) }
87
90
  }
88
91
 
@@ -268,11 +271,19 @@ data class StreamRequest @JvmOverloads constructor(
268
271
  audio?.toMap()?.takeIf { it.isNotEmpty() }?.let { put("audio", it) }
269
272
  authToken?.takeIf { it.isNotEmpty() }?.let { put("authToken", it) }
270
273
  if (!captureAudio) put("captureAudio", false)
271
- ice?.toMap()?.takeIf { it.isNotEmpty() }?.let { put("ice", it) }
274
+ iceToSend()?.toMap()?.takeIf { it.isNotEmpty() }?.let { put("ice", it) }
272
275
  traceId?.takeIf { it.isNotEmpty() }?.let { put("traceId", it) }
273
276
  telemetry?.let { put("telemetry", it) }
274
277
  }
275
278
 
279
+ /** The glasses read an http(s) URL as WHIP, the only protocol that uses ICE. */
280
+ private fun iceToSend(): StreamIceConfig? =
281
+ if (ice?.stun == null && (streamUrl.startsWith("https://") || streamUrl.startsWith("http://"))) {
282
+ StreamIceConfig(stun = DEFAULT_WHIP_STUN_SERVER)
283
+ } else {
284
+ ice
285
+ }
286
+
276
287
  companion object {
277
288
  @JvmStatic
278
289
  fun fromMap(values: Map<String, Any>): StreamRequest =
@@ -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
+ }