@mentra/bluetooth-sdk 3.4.0-dev.999 → 3.4.0

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 (215) hide show
  1. package/MIGRATION.md +16 -7
  2. package/README.md +40 -13
  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 +114 -122
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +2 -2
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
  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 +274 -56
  30. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +5 -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 +3 -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 +2 -2
  93. package/build/generated/changelogCatalog.js +2 -2
  94. package/build/generated/changelogCatalog.js.map +1 -1
  95. package/build/generated/releaseMetadata.js +5 -5
  96. package/build/generated/releaseMetadata.js.map +1 -1
  97. package/build/index.d.ts +1 -1
  98. package/build/index.d.ts.map +1 -1
  99. package/build/index.js +7 -1
  100. package/build/index.js.map +1 -1
  101. package/build/ota-server/MentraOtaServerModule.d.ts +0 -2
  102. package/build/ota-server/MentraOtaServerModule.d.ts.map +1 -1
  103. package/build/ota-server/MentraOtaServerModule.js.map +1 -1
  104. package/build/ota-server/MentraOtaServerModule.web.d.ts +0 -1
  105. package/build/ota-server/MentraOtaServerModule.web.d.ts.map +1 -1
  106. package/build/ota-server/MentraOtaServerModule.web.js +0 -3
  107. package/build/ota-server/MentraOtaServerModule.web.js.map +1 -1
  108. package/build/ota-transport/index.d.ts +3 -3
  109. package/build/ota-transport/index.d.ts.map +1 -1
  110. package/build/ota-transport/index.js +4 -4
  111. package/build/ota-transport/index.js.map +1 -1
  112. package/build/react/useGlassesConnection.d.ts +1 -1
  113. package/build/react/useGlassesConnection.d.ts.map +1 -1
  114. package/build/react/useGlassesConnection.js +3 -3
  115. package/build/react/useGlassesConnection.js.map +1 -1
  116. package/build/react/useMentraBluetooth.d.ts +1 -1
  117. package/build/react/useMentraBluetooth.d.ts.map +1 -1
  118. package/build/react/useMentraBluetooth.js +1 -1
  119. package/build/react/useMentraBluetooth.js.map +1 -1
  120. package/ios/BluetoothSdkModule.swift +73 -22
  121. package/ios/LocalIPv4.swift +0 -61
  122. package/ios/MentraBluetoothSDK.podspec +7 -1
  123. package/ios/MentraOtaServerModule.swift +0 -16
  124. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  125. package/ios/Resources/NimoFirmware/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
  126. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  127. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  128. package/ios/Source/BluetoothSdkDefaults.swift +4 -4
  129. package/ios/Source/Bridge.swift +14 -0
  130. package/ios/Source/DeviceManager.swift +43 -22
  131. package/ios/Source/GeneratedChangelogCatalog.swift +2 -2
  132. package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
  133. package/ios/Source/MentraBluetoothSDK.swift +35 -16
  134. package/ios/Source/OtaManifest.swift +1 -17
  135. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  136. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  137. package/ios/Source/audio/SpeechActivity.swift +277 -0
  138. package/ios/Source/events/BluetoothEvents.swift +41 -0
  139. package/ios/Source/internal/BleTraceLogger.swift +14 -1
  140. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  141. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +5 -0
  142. package/ios/Source/sgcs/MentraLive.swift +195 -66
  143. package/ios/Source/sgcs/Nimo.swift +249 -276
  144. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +9 -38
  145. package/ios/Source/sgcs/NimoCanvasSession.swift +0 -1
  146. package/ios/Source/sgcs/NimoFirmwareUpdater.swift +260 -0
  147. package/ios/Source/sgcs/NimoOtaProtocol.swift +159 -0
  148. package/ios/Source/sgcs/SGCManager.swift +6 -0
  149. package/ios/Source/streaming/StreamModels.swift +15 -6
  150. package/ios/Source/stt/STTTools.swift +13 -31
  151. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  152. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  153. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  154. package/ios/Source/utils/BoundedWait.swift +44 -0
  155. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  156. package/ios/Source/utils/SttModelTraits.swift +62 -0
  157. package/ios/Tests/BesCrashReportTests.swift +142 -0
  158. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  159. package/ios/Tests/DeviceManagerReconnectTests.swift +0 -71
  160. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +9 -3
  161. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  162. package/ios/Tests/MentraLiveAudioSetupTests.swift +6 -12
  163. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  164. package/ios/Tests/MentraLiveSessionReadinessTests.swift +179 -10
  165. package/ios/Tests/NimoCanvasTransportTests.swift +0 -89
  166. package/ios/Tests/NimoOtaProtocolTests.swift +78 -0
  167. package/ios/Tests/PcmStreamTests.swift +299 -0
  168. package/ios/Tests/SpeechActivityTests.swift +238 -0
  169. package/ios/Tests/StreamRequestTests.swift +18 -0
  170. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  171. package/package.json +2 -2
  172. package/plugin/build/withAndroid.js +9 -11
  173. package/plugin/build/withKotlinVersion.d.ts +2 -0
  174. package/plugin/build/withKotlinVersion.js +46 -0
  175. package/src/BluetoothSdk.types.ts +107 -5
  176. package/src/_private/BluetoothSdkModule.ts +45 -8
  177. package/src/_private/MentraLocalNetworkModule.ts +5 -1
  178. package/src/generated/changelogCatalog.ts +2 -2
  179. package/src/generated/releaseMetadata.ts +5 -5
  180. package/src/index.ts +13 -1
  181. package/src/ota-server/MentraOtaServerModule.ts +0 -2
  182. package/src/ota-server/MentraOtaServerModule.web.ts +0 -4
  183. package/src/ota-transport/index.ts +4 -5
  184. package/src/react/useGlassesConnection.ts +4 -4
  185. package/src/react/useMentraBluetooth.ts +2 -2
  186. package/android/silero/LICENSE.md +0 -17
  187. package/android/silero/build.gradle +0 -50
  188. package/android/silero/proguard-rules.pro +0 -24
  189. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  190. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  191. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  192. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  193. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  194. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  195. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  196. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  197. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  198. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  199. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  200. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  201. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -274
  202. package/android/src/main/java/com/mentra/bluetoothsdk/ScopedNetworkReadiness.kt +0 -17
  203. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  204. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  205. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -16
  206. package/android/src/test/java/com/mentra/bluetoothsdk/ScopedNetworkReadinessTest.kt +0 -39
  207. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  208. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  209. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -851
  210. package/ios/Source/sgcs/NimoMacResourceTransport.swift +0 -217
  211. package/ios/Source/sgcs/NimoResourceFixture.swift +0 -384
  212. package/ios/Source/sgcs/NimoResourceSession.swift +0 -406
  213. package/ios/Tests/NimoResourceSessionTests.swift +0 -476
  214. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  215. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -2,9 +2,11 @@ import AVFoundation
2
2
  import Foundation
3
3
  import os
4
4
 
5
- private enum PcmStreamError: LocalizedError {
5
+ enum PcmStreamError: LocalizedError, Equatable {
6
6
  case invalidArgument(String)
7
7
  case closed
8
+ case notOpen(String)
9
+ case aborted
8
10
  case native(String)
9
11
 
10
12
  var errorDescription: String? {
@@ -13,10 +15,67 @@ private enum PcmStreamError: LocalizedError {
13
15
  return message
14
16
  case .closed:
15
17
  return "PCM stream is closed"
18
+ case let .notOpen(streamId):
19
+ return "pcm stream \(streamId) is not open"
20
+ case .aborted:
21
+ return "aborted"
16
22
  }
17
23
  }
18
24
  }
19
25
 
26
+ /// When a stream starts playing: once `jitterMs` of audio is queued, or when it is closed with
27
+ /// less than that, so a sound shorter than the cushion still plays. Same range as Android.
28
+ struct PcmJitterGate: Equatable {
29
+ static let defaultJitterMs = 500
30
+ static let minimumJitterMs = 80
31
+
32
+ let jitterMs: Int
33
+ let startFrames: Int64
34
+
35
+ init(jitterMs requested: Int?, sampleRate: Int) {
36
+ let jitterMs = min(max(requested ?? Self.defaultJitterMs, Self.minimumJitterMs), Self.defaultJitterMs)
37
+ self.jitterMs = jitterMs
38
+ startFrames = max(1, Int64(sampleRate) * Int64(jitterMs) / 1000)
39
+ }
40
+
41
+ func shouldStart(queuedFrames: Int64, closing: Bool) -> Bool {
42
+ guard queuedFrames > 0 else { return false }
43
+ return closing || queuedFrames >= startFrames
44
+ }
45
+ }
46
+
47
+ /// Holds back an odd trailing byte so every chunk handed on is whole 16-bit samples.
48
+ struct PcmByteCarry {
49
+ private var pending: UInt8?
50
+
51
+ var hasPendingByte: Bool {
52
+ pending != nil
53
+ }
54
+
55
+ mutating func align(_ chunk: Data) -> Data {
56
+ var bytes = Data()
57
+ bytes.reserveCapacity(chunk.count + 1)
58
+ if let pending {
59
+ bytes.append(pending)
60
+ self.pending = nil
61
+ }
62
+ bytes.append(chunk)
63
+ if !bytes.count.isMultiple(of: 2) {
64
+ pending = bytes.removeLast()
65
+ }
66
+ return bytes
67
+ }
68
+ }
69
+
70
+ /// Destination for PCM fetched by `PcmUrlLoader`.
71
+ protocol PcmStreamSink: AnyObject {
72
+ /// Queue whole s16le samples; suspends while the backlog is above the backpressure ceiling.
73
+ func write(data: Data) async throws -> Int64
74
+ /// Play out what is queued, then end. Returns the played duration in ms.
75
+ func close() async throws -> Int64
76
+ func abort() async
77
+ }
78
+
20
79
  /// Low-latency, bounded live PCM playback for `speaker.createStream()`.
21
80
  ///
22
81
  /// Input is signed 16-bit little-endian mono PCM. Chunks are converted to the
@@ -25,30 +84,45 @@ private enum PcmStreamError: LocalizedError {
25
84
  /// serial state queue keeps writes, completion callbacks, interruption
26
85
  /// recovery, close, and abort deterministic without blocking Expo's module
27
86
  /// queue.
28
- final class PcmStreamPlayer: @unchecked Sendable {
87
+ ///
88
+ /// Nothing starts until `jitterMs` of audio is queued or the stream is closed,
89
+ /// so a prewarmed stream holds no output route. A stream that hasn't received
90
+ /// audio when the audio output changes or the session is interrupted is
91
+ /// abandoned: it may point at a stale output, and its next write fails with
92
+ /// "not open" so the caller reopens on the current route.
93
+ final class PcmStreamPlayer: PcmStreamSink, @unchecked Sendable {
29
94
  private let logger = Logger(subsystem: "com.mentra.pcm-stream", category: "playback")
30
95
  private static let backpressureCeilingMs: Int64 = 2000
31
96
  private static let maximumBacklogMs: Int64 = 10000
32
97
 
33
98
  private let streamId: String
34
99
  private let sampleRate: Int
100
+ private let gate: PcmJitterGate
35
101
  private let stateQueue: DispatchQueue
36
102
  private let engine = AVAudioEngine()
37
103
  private let player = AVAudioPlayerNode()
38
104
  private let format: AVAudioFormat
39
105
 
106
+ /// Called once, on the state queue, when the stream abandons itself after a route change or
107
+ /// interruption before any audio arrived. State queue only.
108
+ private var onAbandoned: (() -> Void)?
109
+
40
110
  private var queuedFrames: Int64 = 0
41
111
  private var playedFrames: Int64 = 0
42
112
  private var writtenFrames: Int64 = 0
113
+ private var playbackStarted = false
114
+ /// Buffers written before playback starts; scheduled together when it does.
115
+ private var heldBuffers: [(buffer: AVAudioPCMBuffer, frames: Int)] = []
43
116
  private var closing = false
44
117
  private var aborted = false
118
+ private var abandoned = false
45
119
  private var finished = false
46
120
  private var terminalError: Error?
47
121
  private var writeWaiters: [CheckedContinuation<Int64, Error>] = []
48
122
  private var closeWaiters: [CheckedContinuation<Int64, Error>] = []
49
123
  private var observers: [NSObjectProtocol] = []
50
124
 
51
- init(streamId: String, sampleRate: Int, channels: Int, volume: Float) throws {
125
+ init(streamId: String, sampleRate: Int, channels: Int, volume: Float, jitterMs: Int? = nil) throws {
52
126
  guard !streamId.isEmpty else {
53
127
  throw PcmStreamError.invalidArgument("streamId is required")
54
128
  }
@@ -70,14 +144,14 @@ final class PcmStreamPlayer: @unchecked Sendable {
70
144
  self.streamId = streamId
71
145
  self.sampleRate = sampleRate
72
146
  self.format = format
147
+ gate = PcmJitterGate(jitterMs: jitterMs, sampleRate: sampleRate)
73
148
  stateQueue = DispatchQueue(label: "com.mentra.pcm-stream.\(streamId)")
74
149
 
75
150
  engine.attach(player)
76
151
  engine.connect(player, to: engine.mainMixerNode, format: format)
77
152
  player.volume = min(max(volume, 0), 1)
78
153
  engine.prepare()
79
- try engine.start()
80
- player.play()
154
+ // An empty prewarmed stream must not start playback or microphone gating.
81
155
  installAudioSessionObservers()
82
156
  }
83
157
 
@@ -85,10 +159,22 @@ final class PcmStreamPlayer: @unchecked Sendable {
85
159
  observers.forEach(NotificationCenter.default.removeObserver)
86
160
  }
87
161
 
162
+ /// Set the handler `onAbandoned` calls. Must not be called from the state queue.
163
+ func setAbandonHandler(_ handler: @escaping () -> Void) {
164
+ stateQueue.sync { onAbandoned = handler }
165
+ }
166
+
88
167
  func write(base64: String) async throws -> Int64 {
89
168
  guard let data = Data(base64Encoded: base64), !data.isEmpty else {
90
169
  throw PcmStreamError.invalidArgument("PCM chunk is empty or invalid base64")
91
170
  }
171
+ return try await write(data: data)
172
+ }
173
+
174
+ func write(data: Data) async throws -> Int64 {
175
+ guard !data.isEmpty else {
176
+ throw PcmStreamError.invalidArgument("PCM chunk is empty")
177
+ }
92
178
  guard data.count.isMultiple(of: 2) else {
93
179
  throw PcmStreamError.invalidArgument(
94
180
  "PCM chunk length \(data.count) is not aligned to a 2-byte frame"
@@ -98,6 +184,7 @@ final class PcmStreamPlayer: @unchecked Sendable {
98
184
  return try await withCheckedThrowingContinuation { continuation in
99
185
  stateQueue.async { [self] in
100
186
  do {
187
+ if abandoned { throw PcmStreamError.notOpen(streamId) }
101
188
  if let terminalError { throw terminalError }
102
189
  guard !closing && !aborted else { throw PcmStreamError.closed }
103
190
 
@@ -111,19 +198,17 @@ final class PcmStreamPlayer: @unchecked Sendable {
111
198
 
112
199
  let buffer = try makeBuffer(data: data, frameCount: frameCount)
113
200
  if writtenFrames == 0 {
114
- logger.info("PCM_PLAYBACK first_write frames=\(frameCount) sampleRate=\(self.sampleRate) engineRunning=\(self.engine.isRunning)")
201
+ logger.info("PCM_PLAYBACK first_write frames=\(frameCount) sampleRate=\(self.sampleRate) jitterMs=\(self.gate.jitterMs)")
115
202
  }
116
203
  writtenFrames += Int64(frameCount)
117
204
  queuedFrames += Int64(frameCount)
118
- player.scheduleBuffer(
119
- buffer,
120
- completionCallbackType: .dataPlayedBack
121
- ) { [weak self] _ in
122
- self?.stateQueue.async {
123
- self?.didPlay(frameCount: frameCount)
124
- }
205
+ if playbackStarted {
206
+ schedule(buffer, frames: frameCount)
207
+ resumePlaybackIfNeeded()
208
+ } else {
209
+ heldBuffers.append((buffer, frameCount))
210
+ startPlaybackIfReady()
125
211
  }
126
- resumePlaybackIfNeeded()
127
212
  if let terminalError { throw terminalError }
128
213
 
129
214
  let current = bufferedMs(frames: queuedFrames)
@@ -155,6 +240,8 @@ final class PcmStreamPlayer: @unchecked Sendable {
155
240
  finishClose(extra: continuation)
156
241
  } else {
157
242
  closeWaiters.append(continuation)
243
+ // Audio shorter than the jitter cushion starts now.
244
+ startPlaybackIfReady()
158
245
  }
159
246
  }
160
247
  }
@@ -163,25 +250,42 @@ final class PcmStreamPlayer: @unchecked Sendable {
163
250
  func abort() async {
164
251
  await withCheckedContinuation { continuation in
165
252
  stateQueue.async { [self] in
166
- if !aborted {
167
- logger.info("PCM_PLAYBACK abort writtenFrames=\(self.writtenFrames) playedFrames=\(self.playedFrames) queuedFrames=\(self.queuedFrames)")
168
- aborted = true
169
- finished = true
170
- player.stop()
171
- engine.stop()
172
- queuedFrames = 0
173
- let error = PcmStreamError.closed
174
- writeWaiters.forEach { $0.resume(throwing: error) }
175
- writeWaiters.removeAll()
176
- closeWaiters.forEach { $0.resume(returning: durationMs) }
177
- closeWaiters.removeAll()
178
- removeAudioSessionObservers()
179
- }
253
+ abortOnStateQueue()
180
254
  continuation.resume()
181
255
  }
182
256
  }
183
257
  }
184
258
 
259
+ private func abortOnStateQueue() {
260
+ guard !aborted else { return }
261
+ logger.info("PCM_PLAYBACK abort writtenFrames=\(self.writtenFrames) playedFrames=\(self.playedFrames) queuedFrames=\(self.queuedFrames)")
262
+ aborted = true
263
+ finished = true
264
+ player.stop()
265
+ engine.stop()
266
+ heldBuffers.removeAll()
267
+ queuedFrames = 0
268
+ let error: PcmStreamError = abandoned ? .notOpen(streamId) : .closed
269
+ writeWaiters.forEach { $0.resume(throwing: error) }
270
+ writeWaiters.removeAll()
271
+ closeWaiters.forEach { $0.resume(returning: durationMs) }
272
+ closeWaiters.removeAll()
273
+ removeAudioSessionObservers()
274
+ }
275
+
276
+ /// A stream that never received audio must not survive a route change: it would play on
277
+ /// the old route. Returns true when the stream was abandoned.
278
+ private func abandonIfUnwritten(reason: String) -> Bool {
279
+ guard writtenFrames == 0, !aborted, !finished else { return false }
280
+ logger.info("PCM_PLAYBACK abandon_unwritten reason=\(reason)")
281
+ abandoned = true
282
+ abortOnStateQueue()
283
+ let callback = onAbandoned
284
+ onAbandoned = nil
285
+ callback?()
286
+ return true
287
+ }
288
+
185
289
  private var durationMs: Int64 {
186
290
  bufferedMs(frames: playedFrames)
187
291
  }
@@ -198,15 +302,50 @@ final class PcmStreamPlayer: @unchecked Sendable {
198
302
  throw PcmStreamError.native("failed to allocate PCM audio buffer")
199
303
  }
200
304
 
201
- let bytes = [UInt8](data)
202
- for index in 0 ..< frameCount {
203
- let bits = UInt16(bytes[index * 2]) | (UInt16(bytes[index * 2 + 1]) << 8)
204
- channel[index] = Float(Int16(bitPattern: bits)) / 32768.0
305
+ data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
306
+ for index in 0 ..< frameCount {
307
+ let bits = UInt16(bytes[index * 2]) | (UInt16(bytes[index * 2 + 1]) << 8)
308
+ channel[index] = Float(Int16(bitPattern: bits)) / 32768.0
309
+ }
205
310
  }
206
311
  buffer.frameLength = AVAudioFrameCount(frameCount)
207
312
  return buffer
208
313
  }
209
314
 
315
+ private func schedule(_ buffer: AVAudioPCMBuffer, frames frameCount: Int) {
316
+ player.scheduleBuffer(
317
+ buffer,
318
+ completionCallbackType: .dataPlayedBack
319
+ ) { [weak self] _ in
320
+ self?.stateQueue.async {
321
+ self?.didPlay(frameCount: frameCount)
322
+ }
323
+ }
324
+ }
325
+
326
+ /// Start once the jitter cushion is queued, or on close with whatever is queued.
327
+ private func startPlaybackIfReady() {
328
+ guard !playbackStarted, !finished, terminalError == nil,
329
+ gate.shouldStart(queuedFrames: queuedFrames, closing: closing)
330
+ else { return }
331
+ do {
332
+ if !engine.isRunning {
333
+ try engine.start()
334
+ }
335
+ } catch {
336
+ fail(PcmStreamError.native("PCM playback start failed: \(error.localizedDescription)"))
337
+ return
338
+ }
339
+ playbackStarted = true
340
+ logger.info("PCM_PLAYBACK start queuedMs=\(self.bufferedMs(frames: self.queuedFrames)) closing=\(self.closing)")
341
+ let held = heldBuffers
342
+ heldBuffers.removeAll()
343
+ for entry in held {
344
+ schedule(entry.buffer, frames: entry.frames)
345
+ }
346
+ player.play()
347
+ }
348
+
210
349
  private func didPlay(frameCount: Int) {
211
350
  guard !aborted, terminalError == nil else { return }
212
351
  if playedFrames == 0 {
@@ -243,8 +382,10 @@ final class PcmStreamPlayer: @unchecked Sendable {
243
382
  extra?.resume(returning: result)
244
383
  }
245
384
 
385
+ /// Restart output that already started, e.g. after an interruption or route change.
386
+ /// Never starts a stream that hasn't started; the jitter gate does that.
246
387
  private func resumePlaybackIfNeeded() {
247
- guard !finished, terminalError == nil else { return }
388
+ guard playbackStarted, !finished, terminalError == nil else { return }
248
389
  do {
249
390
  if !engine.isRunning {
250
391
  try engine.start()
@@ -263,6 +404,7 @@ final class PcmStreamPlayer: @unchecked Sendable {
263
404
  finished = true
264
405
  player.stop()
265
406
  engine.stop()
407
+ heldBuffers.removeAll()
266
408
  queuedFrames = 0
267
409
  writeWaiters.forEach { $0.resume(throwing: error) }
268
410
  writeWaiters.removeAll()
@@ -278,9 +420,10 @@ final class PcmStreamPlayer: @unchecked Sendable {
278
420
  forName: .AVAudioEngineConfigurationChange, object: engine, queue: nil
279
421
  ) { [weak self] _ in
280
422
  self?.stateQueue.async {
423
+ guard let self, !self.abandonIfUnwritten(reason: "configuration_change") else { return }
281
424
  // A device change invalidates scheduled buffers. Reject pending writes/close
282
425
  // instead of leaving callers waiting for callbacks that cannot arrive.
283
- self?.fail(PcmStreamError.native("Audio device changed; reopen the PCM stream"))
426
+ self.fail(PcmStreamError.native("Audio device changed; reopen the PCM stream"))
284
427
  }
285
428
  })
286
429
  #else
@@ -300,9 +443,14 @@ final class PcmStreamPlayer: @unchecked Sendable {
300
443
  forName: AVAudioSession.routeChangeNotification,
301
444
  object: nil,
302
445
  queue: nil
303
- ) { [weak self] _ in
304
- self?.stateQueue.asyncAfter(deadline: .now() + 0.1) {
305
- self?.resumePlaybackIfNeeded()
446
+ ) { [weak self] notification in
447
+ let outputChanged = Self.outputsChanged(notification)
448
+ self?.stateQueue.async {
449
+ guard let self else { return }
450
+ if outputChanged, self.abandonIfUnwritten(reason: "route_change") { return }
451
+ self.stateQueue.asyncAfter(deadline: .now() + 0.1) {
452
+ self.resumePlaybackIfNeeded()
453
+ }
306
454
  }
307
455
  }
308
456
  )
@@ -326,12 +474,26 @@ final class PcmStreamPlayer: @unchecked Sendable {
326
474
  }
327
475
 
328
476
  #if !os(macOS)
477
+ /// Whether a route change moved the output. The engine resets the session category before
478
+ /// every playback, which posts a route change that leaves the output where it was; a
479
+ /// prewarmed stream must survive that.
480
+ private static func outputsChanged(_ notification: Notification) -> Bool {
481
+ guard let previous = notification.userInfo?[AVAudioSessionRouteChangePreviousRouteKey]
482
+ as? AVAudioSessionRouteDescription
483
+ else { return true }
484
+ let signature = { (route: AVAudioSessionRouteDescription) in
485
+ route.outputs.map { "\($0.portType.rawValue)#\($0.uid)" }
486
+ }
487
+ return signature(previous) != signature(AVAudioSession.sharedInstance().currentRoute)
488
+ }
489
+
329
490
  private func handleInterruption(_ notification: Notification) {
330
491
  guard
331
492
  let raw = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
332
493
  let type = AVAudioSession.InterruptionType(rawValue: raw)
333
494
  else { return }
334
495
 
496
+ if abandonIfUnwritten(reason: "interruption") { return }
335
497
  switch type {
336
498
  case .began:
337
499
  player.pause()
@@ -353,25 +515,36 @@ final class PcmStreamPlayer: @unchecked Sendable {
353
515
  enum PcmStreamManager {
354
516
  private static let lock = NSLock()
355
517
  private static var players: [String: PcmStreamPlayer] = [:]
518
+ private static var urlPlaybacks: [String: PcmUrlPlayback] = [:]
356
519
 
520
+ @discardableResult
357
521
  static func open(
358
522
  streamId: String,
359
523
  sampleRate: Int,
360
524
  channels: Int,
361
- volume: Float
362
- ) throws {
525
+ volume: Float,
526
+ jitterMs: Int? = nil
527
+ ) throws -> PcmStreamPlayer {
363
528
  let player = try PcmStreamPlayer(
364
529
  streamId: streamId,
365
530
  sampleRate: sampleRate,
366
531
  channels: channels,
367
- volume: volume
532
+ volume: volume,
533
+ jitterMs: jitterMs
368
534
  )
535
+ player.setAbandonHandler { [weak player] in
536
+ guard let player else { return }
537
+ removeIfCurrent(streamId: streamId, player: player)
538
+ }
369
539
  lock.lock()
370
540
  let previous = players.updateValue(player, forKey: streamId)
541
+ let previousPlayback = urlPlaybacks.removeValue(forKey: streamId)
371
542
  lock.unlock()
543
+ previousPlayback?.cancel()
372
544
  if let previous {
373
545
  Task { await previous.abort() }
374
546
  }
547
+ return player
375
548
  }
376
549
 
377
550
  static func write(streamId: String, base64: String) async throws -> Int64 {
@@ -391,46 +564,106 @@ enum PcmStreamManager {
391
564
  }
392
565
  }
393
566
 
567
+ /// Open `streamId` and play the raw s16le mono body of `url` as it downloads. Resolves with
568
+ /// the played duration once the whole body has played.
569
+ static func playUrl(
570
+ streamId: String,
571
+ url rawUrl: String,
572
+ sampleRate: Int,
573
+ volume: Float,
574
+ jitterMs: Int?
575
+ ) async throws -> Int64 {
576
+ guard let url = URL(string: rawUrl), let scheme = url.scheme?.lowercased(), scheme == "https" || scheme == "http" else {
577
+ throw PcmStreamError.invalidArgument("PCM stream URL must be http(s)")
578
+ }
579
+ let player = try open(
580
+ streamId: streamId,
581
+ sampleRate: sampleRate,
582
+ channels: 1,
583
+ volume: volume,
584
+ jitterMs: jitterMs
585
+ )
586
+ let playback = PcmUrlLoader.shared.start(url: url, sink: player)
587
+ if !register(playback, streamId: streamId, player: player) {
588
+ playback.cancel()
589
+ }
590
+ do {
591
+ let duration = try await playback.wait()
592
+ removeUrlPlaybackIfCurrent(streamId: streamId, playback: playback)
593
+ removeIfCurrent(streamId: streamId, player: player)
594
+ return duration
595
+ } catch {
596
+ removeUrlPlaybackIfCurrent(streamId: streamId, playback: playback)
597
+ if removeIfCurrent(streamId: streamId, player: player) {
598
+ await player.abort()
599
+ }
600
+ throw error
601
+ }
602
+ }
603
+
394
604
  static func abort(streamId: String) async {
395
- guard let player = optionalRemove(streamId: streamId) else { return }
396
- await player.abort()
605
+ let (playback, player) = take(streamId: streamId)
606
+ // Cancel first so a URL playback rejects with "aborted", not a write error.
607
+ playback?.cancel()
608
+ await player?.abort()
397
609
  }
398
610
 
399
611
  static func abortAll() async {
400
- let active = takeAll()
612
+ let (playbacks, active) = takeAll()
613
+ playbacks.forEach { $0.cancel() }
401
614
  for player in active {
402
615
  await player.abort()
403
616
  }
404
617
  }
405
618
 
406
- private static func lookup(streamId: String) throws -> PcmStreamPlayer {
619
+ /// `open` cleared any earlier playback for this id; only a racing open can have replaced
620
+ /// the player since, and that one owns the id now.
621
+ private static func register(_ playback: PcmUrlPlayback, streamId: String, player: PcmStreamPlayer) -> Bool {
407
622
  lock.lock()
408
623
  defer { lock.unlock() }
409
- guard let player = players[streamId] else {
410
- throw PcmStreamError.closed
411
- }
412
- return player
624
+ guard players[streamId] === player else { return false }
625
+ urlPlaybacks[streamId] = playback
626
+ return true
413
627
  }
414
628
 
415
- private static func optionalRemove(streamId: String) -> PcmStreamPlayer? {
629
+ private static func take(streamId: String) -> (PcmUrlPlayback?, PcmStreamPlayer?) {
416
630
  lock.lock()
417
631
  defer { lock.unlock() }
418
- return players.removeValue(forKey: streamId)
632
+ return (urlPlaybacks.removeValue(forKey: streamId), players.removeValue(forKey: streamId))
419
633
  }
420
634
 
421
- private static func removeIfCurrent(streamId: String, player: PcmStreamPlayer) {
635
+ private static func takeAll() -> ([PcmUrlPlayback], [PcmStreamPlayer]) {
422
636
  lock.lock()
423
637
  defer { lock.unlock() }
424
- if players[streamId] === player {
425
- players.removeValue(forKey: streamId)
638
+ let result = (Array(urlPlaybacks.values), Array(players.values))
639
+ urlPlaybacks.removeAll()
640
+ players.removeAll()
641
+ return result
642
+ }
643
+
644
+ private static func lookup(streamId: String) throws -> PcmStreamPlayer {
645
+ lock.lock()
646
+ defer { lock.unlock() }
647
+ guard let player = players[streamId] else {
648
+ throw PcmStreamError.notOpen(streamId)
426
649
  }
650
+ return player
427
651
  }
428
652
 
429
- private static func takeAll() -> [PcmStreamPlayer] {
653
+ @discardableResult
654
+ private static func removeIfCurrent(streamId: String, player: PcmStreamPlayer) -> Bool {
430
655
  lock.lock()
431
656
  defer { lock.unlock() }
432
- let active = Array(players.values)
433
- players.removeAll()
434
- return active
657
+ guard players[streamId] === player else { return false }
658
+ players.removeValue(forKey: streamId)
659
+ return true
660
+ }
661
+
662
+ private static func removeUrlPlaybackIfCurrent(streamId: String, playback: PcmUrlPlayback) {
663
+ lock.lock()
664
+ defer { lock.unlock() }
665
+ if urlPlaybacks[streamId] === playback {
666
+ urlPlaybacks.removeValue(forKey: streamId)
667
+ }
435
668
  }
436
669
  }