@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.
- package/MIGRATION.md +16 -7
- package/README.md +41 -14
- package/android/build.gradle +60 -51
- package/android/gradle.properties +3 -0
- package/android/settings.gradle +47 -3
- package/android/src/main/assets/nimo/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +77 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +41 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +131 -122
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +3 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +31 -10
- package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +57 -196
- package/android/src/main/java/com/mentra/bluetoothsdk/OtaManifest.kt +1 -16
- package/android/src/main/java/com/mentra/bluetoothsdk/debug/BleTraceLogger.kt +10 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/Ipv4Prefix.kt +51 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/NetworkFacts.kt +81 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkError.kt +108 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadiness.kt +103 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpec.kt +44 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkState.kt +117 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedSoftApNetwork.kt +598 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/SoftApTrace.kt +143 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/otaserver/MentraOtaServerModule.kt +0 -7
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTracker.kt +15 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +308 -60
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +14 -5
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +210 -325
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +0 -35
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +2 -10
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdater.kt +213 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocol.kt +112 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/streaming/StreamModels.kt +17 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/StreamRequestCaptureAudioTest.kt +23 -4
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/Ipv4PrefixTest.kt +59 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/NetworkFactsTest.kt +59 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedLocalNetworkPermissionTest.kt +35 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkErrorTest.kt +85 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkLifecycleTest.kt +164 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadinessTest.kt +141 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpecTest.kt +56 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/SoftApTraceTest.kt +97 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/UnavailableRetryTest.kt +47 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTrackerTest.kt +26 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +9 -3
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareTargetTest.kt +15 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdaterTest.kt +76 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocolTest.kt +77 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoReadinessDriverTest.kt +31 -1
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
- package/build/BluetoothSdk.types.d.ts +103 -5
- package/build/BluetoothSdk.types.d.ts.map +1 -1
- package/build/BluetoothSdk.types.js.map +1 -1
- package/build/_private/BluetoothSdkModule.d.ts +42 -8
- package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
- package/build/_private/BluetoothSdkModule.js +1 -0
- package/build/_private/BluetoothSdkModule.js.map +1 -1
- package/build/_private/MentraLocalNetworkModule.d.ts +1 -1
- package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
- package/build/_private/MentraLocalNetworkModule.js.map +1 -1
- package/build/generated/changelogCatalog.d.ts +5 -2
- package/build/generated/changelogCatalog.d.ts.map +1 -1
- package/build/generated/changelogCatalog.js +6 -2
- package/build/generated/changelogCatalog.js.map +1 -1
- package/build/generated/releaseMetadata.js +6 -6
- package/build/generated/releaseMetadata.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +7 -1
- package/build/index.js.map +1 -1
- package/build/ota-server/MentraOtaServerModule.d.ts +0 -2
- package/build/ota-server/MentraOtaServerModule.d.ts.map +1 -1
- package/build/ota-server/MentraOtaServerModule.js.map +1 -1
- package/build/ota-server/MentraOtaServerModule.web.d.ts +0 -1
- package/build/ota-server/MentraOtaServerModule.web.d.ts.map +1 -1
- package/build/ota-server/MentraOtaServerModule.web.js +0 -3
- package/build/ota-server/MentraOtaServerModule.web.js.map +1 -1
- package/build/ota-transport/index.d.ts +3 -3
- package/build/ota-transport/index.d.ts.map +1 -1
- package/build/ota-transport/index.js +4 -4
- package/build/ota-transport/index.js.map +1 -1
- package/build/react/useGlassesConnection.d.ts +1 -1
- package/build/react/useGlassesConnection.d.ts.map +1 -1
- package/build/react/useGlassesConnection.js +3 -3
- package/build/react/useGlassesConnection.js.map +1 -1
- package/build/react/useMentraBluetooth.d.ts +1 -1
- package/build/react/useMentraBluetooth.d.ts.map +1 -1
- package/build/react/useMentraBluetooth.js +1 -1
- package/build/react/useMentraBluetooth.js.map +1 -1
- package/ios/BluetoothSdkModule.swift +73 -22
- package/ios/LocalIPv4.swift +0 -61
- package/ios/MentraBluetoothSDK.podspec +7 -1
- package/ios/MentraOtaServerModule.swift +0 -16
- package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
- package/ios/Resources/NimoFirmware/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
- package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
- package/ios/Source/BesCrashReportWaiters.swift +64 -0
- package/ios/Source/BluetoothSdkDefaults.swift +4 -4
- package/ios/Source/Bridge.swift +14 -0
- package/ios/Source/DeviceManager.swift +52 -22
- package/ios/Source/GeneratedChangelogCatalog.swift +3 -2
- package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
- package/ios/Source/MentraBluetoothSDK.swift +35 -16
- package/ios/Source/OtaManifest.swift +1 -17
- package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
- package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
- package/ios/Source/audio/SpeechActivity.swift +277 -0
- package/ios/Source/events/BluetoothEvents.swift +41 -0
- package/ios/Source/internal/BleTraceLogger.swift +14 -1
- package/ios/Source/internal/BluetoothAvailability.swift +15 -5
- package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +5 -0
- package/ios/Source/sgcs/MentraLive.swift +207 -66
- package/ios/Source/sgcs/Nimo.swift +249 -276
- package/ios/Source/sgcs/NimoCanvasCoordinator.swift +9 -38
- package/ios/Source/sgcs/NimoCanvasSession.swift +0 -1
- package/ios/Source/sgcs/NimoFirmwareUpdater.swift +260 -0
- package/ios/Source/sgcs/NimoOtaProtocol.swift +159 -0
- package/ios/Source/sgcs/SGCManager.swift +6 -0
- package/ios/Source/streaming/StreamModels.swift +15 -6
- package/ios/Source/stt/STTTools.swift +13 -31
- package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
- package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
- package/ios/Source/stt/WakeWordDetector.swift +145 -0
- package/ios/Source/utils/BoundedWait.swift +44 -0
- package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
- package/ios/Source/utils/SttModelTraits.swift +62 -0
- package/ios/Tests/BesCrashReportTests.swift +142 -0
- package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
- package/ios/Tests/DeviceManagerReconnectTests.swift +0 -71
- package/ios/Tests/GlassesAudioSetupPolicyTests.swift +9 -3
- package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
- package/ios/Tests/MentraLiveAudioSetupTests.swift +6 -12
- package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
- package/ios/Tests/MentraLiveSessionReadinessTests.swift +179 -10
- package/ios/Tests/NimoCanvasTransportTests.swift +0 -89
- package/ios/Tests/NimoOtaProtocolTests.swift +78 -0
- package/ios/Tests/PcmStreamTests.swift +299 -0
- package/ios/Tests/SpeechActivityTests.swift +238 -0
- package/ios/Tests/StreamRequestTests.swift +18 -0
- package/ios/Tests/SttModelTraitsTests.swift +62 -0
- package/package.json +2 -2
- package/plugin/build/withAndroid.js +9 -11
- package/plugin/build/withKotlinVersion.d.ts +2 -0
- package/plugin/build/withKotlinVersion.js +46 -0
- package/src/BluetoothSdk.types.ts +107 -5
- package/src/_private/BluetoothSdkModule.ts +45 -8
- package/src/_private/MentraLocalNetworkModule.ts +5 -1
- package/src/generated/changelogCatalog.ts +6 -2
- package/src/generated/releaseMetadata.ts +6 -6
- package/src/index.ts +13 -1
- package/src/ota-server/MentraOtaServerModule.ts +0 -2
- package/src/ota-server/MentraOtaServerModule.web.ts +0 -4
- package/src/ota-transport/index.ts +4 -5
- package/src/react/useGlassesConnection.ts +4 -4
- package/src/react/useMentraBluetooth.ts +2 -2
- package/android/silero/LICENSE.md +0 -17
- package/android/silero/build.gradle +0 -50
- package/android/silero/proguard-rules.pro +0 -24
- package/android/silero/src/androidTest/assets/hello.wav +0 -0
- package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
- package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
- package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
- package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
- package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
- package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -274
- package/android/src/main/java/com/mentra/bluetoothsdk/ScopedNetworkReadiness.kt +0 -17
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
- package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
- package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -16
- package/android/src/test/java/com/mentra/bluetoothsdk/ScopedNetworkReadinessTest.kt +0 -39
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -851
- package/ios/Source/sgcs/NimoMacResourceTransport.swift +0 -217
- package/ios/Source/sgcs/NimoResourceFixture.swift +0 -384
- package/ios/Source/sgcs/NimoResourceSession.swift +0 -406
- package/ios/Tests/NimoResourceSessionTests.swift +0 -476
- /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
- /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// One HTTP GET whose raw s16le mono body is written into a `PcmStreamSink` as it arrives.
|
|
4
|
+
///
|
|
5
|
+
/// All state is touched only on the loader's serial queue, which is also the URLSession
|
|
6
|
+
/// delegate queue. Settles exactly once: with the played duration after the sink drained, or
|
|
7
|
+
/// with an error.
|
|
8
|
+
final class PcmUrlPlayback: @unchecked Sendable {
|
|
9
|
+
fileprivate let sink: PcmStreamSink
|
|
10
|
+
fileprivate let queue: DispatchQueue
|
|
11
|
+
fileprivate var task: URLSessionDataTask?
|
|
12
|
+
fileprivate var carry = PcmByteCarry()
|
|
13
|
+
fileprivate var pending = Data()
|
|
14
|
+
fileprivate var writing = false
|
|
15
|
+
fileprivate var suspended = false
|
|
16
|
+
fileprivate var bodyComplete = false
|
|
17
|
+
fileprivate var bodyError: Error?
|
|
18
|
+
fileprivate var closing = false
|
|
19
|
+
fileprivate var result: Result<Int64, Error>?
|
|
20
|
+
fileprivate var waiters: [CheckedContinuation<Int64, Error>] = []
|
|
21
|
+
fileprivate var onSettled: (() -> Void)?
|
|
22
|
+
|
|
23
|
+
/// Times the transfer was paused for backpressure. For diagnostics and tests.
|
|
24
|
+
private(set) var suspensions = 0
|
|
25
|
+
|
|
26
|
+
fileprivate init(sink: PcmStreamSink, queue: DispatchQueue) {
|
|
27
|
+
self.sink = sink
|
|
28
|
+
self.queue = queue
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// Wait for the body to finish playing. Throws `PcmStreamError.aborted` after `cancel()`.
|
|
32
|
+
func wait() async throws -> Int64 {
|
|
33
|
+
try await withCheckedThrowingContinuation { continuation in
|
|
34
|
+
queue.async {
|
|
35
|
+
if let result = self.result {
|
|
36
|
+
continuation.resume(with: result)
|
|
37
|
+
} else {
|
|
38
|
+
self.waiters.append(continuation)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/// Stop downloading and settle with "aborted". The caller stops the sink.
|
|
45
|
+
func cancel() {
|
|
46
|
+
queue.async {
|
|
47
|
+
self.settle(.failure(PcmStreamError.aborted))
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// MARK: Queue only
|
|
52
|
+
|
|
53
|
+
fileprivate func settle(_ outcome: Result<Int64, Error>) {
|
|
54
|
+
guard result == nil else { return }
|
|
55
|
+
result = outcome
|
|
56
|
+
if let task, task.state != .completed {
|
|
57
|
+
task.cancel()
|
|
58
|
+
}
|
|
59
|
+
pending.removeAll()
|
|
60
|
+
let pendingWaiters = waiters
|
|
61
|
+
waiters.removeAll()
|
|
62
|
+
pendingWaiters.forEach { $0.resume(with: outcome) }
|
|
63
|
+
let callback = onSettled
|
|
64
|
+
onSettled = nil
|
|
65
|
+
callback?()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
fileprivate func receive(_ data: Data, highWaterBytes: Int) {
|
|
69
|
+
guard result == nil else { return }
|
|
70
|
+
pending.append(carry.align(data))
|
|
71
|
+
if pending.count > highWaterBytes, !suspended, let task {
|
|
72
|
+
task.suspend()
|
|
73
|
+
suspended = true
|
|
74
|
+
suspensions += 1
|
|
75
|
+
}
|
|
76
|
+
pump()
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
fileprivate func complete(error: Error?) {
|
|
80
|
+
guard result == nil else { return }
|
|
81
|
+
bodyComplete = true
|
|
82
|
+
bodyError = error
|
|
83
|
+
// A trailing half sample left in `carry` can't be played and is dropped.
|
|
84
|
+
pump()
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/// Hand pending audio to the sink one write at a time. The sink's write suspends while its
|
|
88
|
+
/// backlog is above its ceiling; meanwhile `pending` fills, and past the high-water mark the
|
|
89
|
+
/// transfer is paused until the next write takes it. Once the body is complete and
|
|
90
|
+
/// everything is written, close the sink.
|
|
91
|
+
fileprivate func pump() {
|
|
92
|
+
guard result == nil, !writing, !closing else { return }
|
|
93
|
+
if !pending.isEmpty {
|
|
94
|
+
let chunk = pending
|
|
95
|
+
pending = Data()
|
|
96
|
+
writing = true
|
|
97
|
+
if suspended, let task {
|
|
98
|
+
task.resume()
|
|
99
|
+
suspended = false
|
|
100
|
+
}
|
|
101
|
+
Task {
|
|
102
|
+
do {
|
|
103
|
+
_ = try await self.sink.write(data: chunk)
|
|
104
|
+
self.queue.async {
|
|
105
|
+
self.writing = false
|
|
106
|
+
self.pump()
|
|
107
|
+
}
|
|
108
|
+
} catch {
|
|
109
|
+
self.queue.async { self.settle(.failure(error)) }
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return
|
|
113
|
+
}
|
|
114
|
+
guard bodyComplete else { return }
|
|
115
|
+
closing = true
|
|
116
|
+
let failure = bodyError
|
|
117
|
+
Task {
|
|
118
|
+
// A dropped connection still ends cleanly: what arrived plays out, then the error.
|
|
119
|
+
let outcome: Result<Int64, Error>
|
|
120
|
+
do {
|
|
121
|
+
let duration = try await self.sink.close()
|
|
122
|
+
outcome = failure.map { .failure($0) } ?? .success(duration)
|
|
123
|
+
} catch {
|
|
124
|
+
outcome = .failure(failure ?? error)
|
|
125
|
+
}
|
|
126
|
+
self.queue.async { self.settle(outcome) }
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/// Shared URLSession for `pcmStreamPlayUrl`. Requests reuse connections, which matters when a
|
|
132
|
+
/// spoken answer arrives as one request per sentence.
|
|
133
|
+
final class PcmUrlLoader: NSObject, URLSessionDataDelegate {
|
|
134
|
+
static let shared = PcmUrlLoader()
|
|
135
|
+
|
|
136
|
+
/// Pause the transfer when this much audio is waiting for the sink (about 1.3 s at 24 kHz).
|
|
137
|
+
static let defaultHighWaterBytes = 64 * 1024
|
|
138
|
+
|
|
139
|
+
private static let compressedContentTypes = ["audio/mpeg", "audio/mp3", "audio/aac", "audio/ogg", "audio/opus", "audio/webm"]
|
|
140
|
+
|
|
141
|
+
let queue = DispatchQueue(label: "com.mentra.pcm-url", qos: .userInitiated)
|
|
142
|
+
private let highWaterBytes: Int
|
|
143
|
+
private let configuration: URLSessionConfiguration
|
|
144
|
+
private lazy var session: URLSession = {
|
|
145
|
+
let delegateQueue = OperationQueue()
|
|
146
|
+
delegateQueue.maxConcurrentOperationCount = 1
|
|
147
|
+
delegateQueue.underlyingQueue = queue
|
|
148
|
+
return URLSession(configuration: configuration, delegate: self, delegateQueue: delegateQueue)
|
|
149
|
+
}()
|
|
150
|
+
|
|
151
|
+
// Queue only.
|
|
152
|
+
private var playbacks: [Int: PcmUrlPlayback] = [:]
|
|
153
|
+
|
|
154
|
+
init(configuration: URLSessionConfiguration = PcmUrlLoader.defaultConfiguration(), highWaterBytes: Int = PcmUrlLoader.defaultHighWaterBytes) {
|
|
155
|
+
self.configuration = configuration
|
|
156
|
+
self.highWaterBytes = max(2, highWaterBytes)
|
|
157
|
+
super.init()
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
static func defaultConfiguration() -> URLSessionConfiguration {
|
|
161
|
+
let configuration = URLSessionConfiguration.default
|
|
162
|
+
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
|
|
163
|
+
configuration.urlCache = nil
|
|
164
|
+
// Speech is useless late: fail a stalled response instead of waiting a minute.
|
|
165
|
+
configuration.timeoutIntervalForRequest = 20
|
|
166
|
+
configuration.waitsForConnectivity = false
|
|
167
|
+
return configuration
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/// Start fetching `url` into `sink`. Never blocks the caller.
|
|
171
|
+
func start(url: URL, sink: PcmStreamSink) -> PcmUrlPlayback {
|
|
172
|
+
let playback = PcmUrlPlayback(sink: sink, queue: queue)
|
|
173
|
+
queue.async {
|
|
174
|
+
guard playback.result == nil else { return } // Cancelled before it started.
|
|
175
|
+
var request = URLRequest(url: url)
|
|
176
|
+
request.httpMethod = "GET"
|
|
177
|
+
let task = self.session.dataTask(with: request)
|
|
178
|
+
playback.task = task
|
|
179
|
+
self.playbacks[task.taskIdentifier] = playback
|
|
180
|
+
playback.onSettled = { [weak self] in
|
|
181
|
+
self?.playbacks.removeValue(forKey: task.taskIdentifier)
|
|
182
|
+
}
|
|
183
|
+
task.resume()
|
|
184
|
+
}
|
|
185
|
+
return playback
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// MARK: URLSessionDataDelegate (on `queue`)
|
|
189
|
+
|
|
190
|
+
func urlSession(
|
|
191
|
+
_: URLSession,
|
|
192
|
+
dataTask: URLSessionDataTask,
|
|
193
|
+
didReceive response: URLResponse,
|
|
194
|
+
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void
|
|
195
|
+
) {
|
|
196
|
+
guard let playback = playbacks[dataTask.taskIdentifier] else {
|
|
197
|
+
completionHandler(.cancel)
|
|
198
|
+
return
|
|
199
|
+
}
|
|
200
|
+
if let http = response as? HTTPURLResponse, !(200 ..< 300).contains(http.statusCode) {
|
|
201
|
+
completionHandler(.cancel)
|
|
202
|
+
playback.settle(.failure(PcmStreamError.native("http_error: PCM stream request failed with HTTP \(http.statusCode)")))
|
|
203
|
+
return
|
|
204
|
+
}
|
|
205
|
+
if let type = response.mimeType?.lowercased(), Self.compressedContentTypes.contains(type) {
|
|
206
|
+
completionHandler(.cancel)
|
|
207
|
+
playback.settle(.failure(PcmStreamError.native("unsupported_format: PCM stream URL returned \(type), not raw PCM")))
|
|
208
|
+
return
|
|
209
|
+
}
|
|
210
|
+
completionHandler(.allow)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
func urlSession(_: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
|
|
214
|
+
playbacks[dataTask.taskIdentifier]?.receive(data, highWaterBytes: highWaterBytes)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
func urlSession(_: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
|
|
218
|
+
guard let playback = playbacks[task.taskIdentifier] else { return }
|
|
219
|
+
let failure = error.map { PcmStreamError.native("network_error: PCM stream download failed: \($0.localizedDescription)") as Error }
|
|
220
|
+
playback.complete(error: failure)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
func urlSession(
|
|
224
|
+
_: URLSession,
|
|
225
|
+
dataTask _: URLSessionDataTask,
|
|
226
|
+
willCacheResponse _: CachedURLResponse,
|
|
227
|
+
completionHandler: @escaping (CachedURLResponse?) -> Void
|
|
228
|
+
) {
|
|
229
|
+
completionHandler(nil)
|
|
230
|
+
}
|
|
231
|
+
}
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// A frame-level speech detector, e.g. Silero through sherpa-onnx.
|
|
4
|
+
///
|
|
5
|
+
/// It owns its own hangover: once speaking, it keeps answering `true` until it has heard the
|
|
6
|
+
/// configured minimum silence, and it answers `false` until speech has lasted long enough.
|
|
7
|
+
protocol SpeechActivityClassifier: AnyObject {
|
|
8
|
+
/// Analyze exactly `SpeechActivityTracker.frameSamples` samples (16 kHz mono, [-1, 1]) and
|
|
9
|
+
/// return whether speech is detected after this frame.
|
|
10
|
+
func isSpeech(afterAccepting frame: [Float]) -> Bool
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/// A reported change in phone-side speech activity.
|
|
14
|
+
struct SpeechActivityTransition: Equatable {
|
|
15
|
+
let speaking: Bool
|
|
16
|
+
/// 0 while speaking; on a silence transition, how long the audio has been silent.
|
|
17
|
+
let silentForMs: Int
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/// Turns 16 kHz mono s16le PCM chunks of any size into 512-sample frames, checks every frame,
|
|
21
|
+
/// and reports transitions only. Fills gaps in incoming audio with silence in real time, because
|
|
22
|
+
/// Mentra Live's loudness gate stops sending audio when it's quiet.
|
|
23
|
+
///
|
|
24
|
+
/// Not thread-safe: the caller serializes all calls.
|
|
25
|
+
final class SpeechActivityTracker {
|
|
26
|
+
static let sampleRate = 16000
|
|
27
|
+
static let frameSamples = 512
|
|
28
|
+
static let defaultMinSilenceMs = 300
|
|
29
|
+
/// Audio missing for this long counts as silence and is filled in.
|
|
30
|
+
static let gapFillAfterMs: Int64 = 100
|
|
31
|
+
|
|
32
|
+
private static let samplesPerMs = Int64(sampleRate / 1000)
|
|
33
|
+
|
|
34
|
+
let minSilenceMs: Int
|
|
35
|
+
private let classifier: SpeechActivityClassifier
|
|
36
|
+
private var frame: [Float] = []
|
|
37
|
+
private var carry: UInt8?
|
|
38
|
+
private var detecting = false
|
|
39
|
+
private var lastAudioAtMs: Int64?
|
|
40
|
+
private var gapFilledSamples: Int64 = 0
|
|
41
|
+
|
|
42
|
+
/// The last state reported. Starts silent; nothing is reported until speech is heard.
|
|
43
|
+
private(set) var speaking = false
|
|
44
|
+
/// Samples analyzed so far, real and filled. For diagnostics and tests.
|
|
45
|
+
private(set) var analyzedSamples: Int64 = 0
|
|
46
|
+
private(set) var filledSamples: Int64 = 0
|
|
47
|
+
|
|
48
|
+
init(classifier: SpeechActivityClassifier, minSilenceMs: Int = SpeechActivityTracker.defaultMinSilenceMs) {
|
|
49
|
+
self.classifier = classifier
|
|
50
|
+
self.minSilenceMs = max(0, minSilenceMs)
|
|
51
|
+
frame.reserveCapacity(Self.frameSamples)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/// Filling only matters while speech is reported or the detector still hears it; silence fed
|
|
55
|
+
/// to a silent detector can't produce a transition.
|
|
56
|
+
var needsGapFill: Bool {
|
|
57
|
+
lastAudioAtMs != nil && (speaking || detecting)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/// When the next gap-fill check is due, or nil when none is needed.
|
|
61
|
+
func nextGapFillDueMs(nowMs: Int64) -> Int64? {
|
|
62
|
+
guard needsGapFill, let lastAudioAtMs else { return nil }
|
|
63
|
+
let due = lastAudioAtMs + Self.gapFillAfterMs
|
|
64
|
+
return due > nowMs ? due : nowMs + Int64(Self.frameSamples * 1000 / Self.sampleRate)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
func accept(_ pcm: Data, nowMs: Int64) -> [SpeechActivityTransition] {
|
|
68
|
+
guard !pcm.isEmpty else { return [] }
|
|
69
|
+
lastAudioAtMs = nowMs
|
|
70
|
+
gapFilledSamples = 0
|
|
71
|
+
var transitions: [SpeechActivityTransition] = []
|
|
72
|
+
pcm.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
|
|
73
|
+
var index = 0
|
|
74
|
+
if let low = carry {
|
|
75
|
+
appendSample(low: low, high: bytes[0], into: &transitions)
|
|
76
|
+
carry = nil
|
|
77
|
+
index = 1
|
|
78
|
+
}
|
|
79
|
+
while index + 1 < bytes.count {
|
|
80
|
+
appendSample(low: bytes[index], high: bytes[index + 1], into: &transitions)
|
|
81
|
+
index += 2
|
|
82
|
+
}
|
|
83
|
+
if index < bytes.count {
|
|
84
|
+
carry = bytes[index]
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return transitions
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/// Feed silence for the time no audio has arrived, once that exceeds `gapFillAfterMs`.
|
|
91
|
+
func fillGap(nowMs: Int64) -> [SpeechActivityTransition] {
|
|
92
|
+
guard let lastAudioAtMs, nowMs - lastAudioAtMs >= Self.gapFillAfterMs else { return [] }
|
|
93
|
+
let targetSamples = (nowMs - lastAudioAtMs) * Self.samplesPerMs
|
|
94
|
+
var transitions: [SpeechActivityTransition] = []
|
|
95
|
+
// A half-received sample is lost with the gap.
|
|
96
|
+
carry = nil
|
|
97
|
+
while needsGapFill {
|
|
98
|
+
let missing = Self.frameSamples - frame.count
|
|
99
|
+
guard gapFilledSamples + Int64(missing) <= targetSamples else { break }
|
|
100
|
+
frame.append(contentsOf: repeatElement(0, count: missing))
|
|
101
|
+
gapFilledSamples += Int64(missing)
|
|
102
|
+
filledSamples += Int64(missing)
|
|
103
|
+
analyzeFrame(into: &transitions)
|
|
104
|
+
}
|
|
105
|
+
return transitions
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
private func appendSample(low: UInt8, high: UInt8, into transitions: inout [SpeechActivityTransition]) {
|
|
109
|
+
frame.append(Float(Int16(bitPattern: UInt16(low) | UInt16(high) << 8)) / 32768)
|
|
110
|
+
if frame.count == Self.frameSamples {
|
|
111
|
+
analyzeFrame(into: &transitions)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private func analyzeFrame(into transitions: inout [SpeechActivityTransition]) {
|
|
116
|
+
detecting = classifier.isSpeech(afterAccepting: frame)
|
|
117
|
+
analyzedSamples += Int64(frame.count)
|
|
118
|
+
frame.removeAll(keepingCapacity: true)
|
|
119
|
+
if detecting, !speaking {
|
|
120
|
+
speaking = true
|
|
121
|
+
transitions.append(SpeechActivityTransition(speaking: true, silentForMs: 0))
|
|
122
|
+
} else if !detecting, speaking {
|
|
123
|
+
// The detector only turns off after `minSilenceMs` of silence.
|
|
124
|
+
speaking = false
|
|
125
|
+
transitions.append(SpeechActivityTransition(speaking: false, silentForMs: minSilenceMs))
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/// Runs a `SpeechActivityTracker` on its own queue while enabled. Enabling creates the classifier
|
|
131
|
+
/// (loads the model); disabling drops it. Audio is accepted from any thread.
|
|
132
|
+
final class SpeechActivityMonitor: @unchecked Sendable {
|
|
133
|
+
struct Event: Equatable {
|
|
134
|
+
let speaking: Bool
|
|
135
|
+
let silentForMs: Int
|
|
136
|
+
/// Unix epoch milliseconds.
|
|
137
|
+
let timestamp: Int64
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
enum MonitorError: LocalizedError {
|
|
141
|
+
case modelUnavailable
|
|
142
|
+
|
|
143
|
+
var errorDescription: String? {
|
|
144
|
+
"Could not load the speech activity model"
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
private let queue: DispatchQueue
|
|
149
|
+
private let makeClassifier: (_ minSilenceMs: Int) -> SpeechActivityClassifier?
|
|
150
|
+
private let emit: (Event) -> Void
|
|
151
|
+
private let monotonicMs: () -> Int64
|
|
152
|
+
private let epochMs: () -> Int64
|
|
153
|
+
|
|
154
|
+
private let lock = NSLock()
|
|
155
|
+
private var enabled = false
|
|
156
|
+
private var generation: UInt64 = 0
|
|
157
|
+
|
|
158
|
+
// Queue only.
|
|
159
|
+
private var tracker: SpeechActivityTracker?
|
|
160
|
+
private var trackerGeneration: UInt64 = 0
|
|
161
|
+
private var gapCheckScheduled = false
|
|
162
|
+
|
|
163
|
+
init(
|
|
164
|
+
queue: DispatchQueue = DispatchQueue(label: "com.mentra.speech-activity", qos: .userInitiated),
|
|
165
|
+
makeClassifier: @escaping (_ minSilenceMs: Int) -> SpeechActivityClassifier?,
|
|
166
|
+
emit: @escaping (Event) -> Void,
|
|
167
|
+
monotonicMs: @escaping () -> Int64 = { Int64(ProcessInfo.processInfo.systemUptime * 1000) },
|
|
168
|
+
epochMs: @escaping () -> Int64 = { Int64(Date().timeIntervalSince1970 * 1000) }
|
|
169
|
+
) {
|
|
170
|
+
self.queue = queue
|
|
171
|
+
self.makeClassifier = makeClassifier
|
|
172
|
+
self.emit = emit
|
|
173
|
+
self.monotonicMs = monotonicMs
|
|
174
|
+
self.epochMs = epochMs
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
var isEnabled: Bool {
|
|
178
|
+
lock.lock()
|
|
179
|
+
defer { lock.unlock() }
|
|
180
|
+
return enabled
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/// Whether a classifier (model) is currently held. Queue-serialized; for tests.
|
|
184
|
+
func hasClassifier() -> Bool {
|
|
185
|
+
queue.sync { tracker != nil }
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/// Enable with `minSilenceMs` (default 300), or disable and release the model. Enabling
|
|
189
|
+
/// again replaces the detector, so a new `minSilenceMs` takes effect. Throws when the model
|
|
190
|
+
/// can't be loaded.
|
|
191
|
+
func setEnabled(_ value: Bool, minSilenceMs: Int?) async throws {
|
|
192
|
+
let token = beginDemandChange(enabled: value)
|
|
193
|
+
let silence = max(0, minSilenceMs ?? SpeechActivityTracker.defaultMinSilenceMs)
|
|
194
|
+
let loaded: Bool = await withCheckedContinuation { continuation in
|
|
195
|
+
queue.async {
|
|
196
|
+
// Release before loading a replacement, so two models are never held.
|
|
197
|
+
self.tracker = nil
|
|
198
|
+
guard value, self.isCurrent(token) else {
|
|
199
|
+
continuation.resume(returning: true)
|
|
200
|
+
return
|
|
201
|
+
}
|
|
202
|
+
guard let classifier = self.makeClassifier(silence) else {
|
|
203
|
+
continuation.resume(returning: false)
|
|
204
|
+
return
|
|
205
|
+
}
|
|
206
|
+
if self.isCurrent(token) {
|
|
207
|
+
self.tracker = SpeechActivityTracker(classifier: classifier, minSilenceMs: silence)
|
|
208
|
+
self.trackerGeneration = token
|
|
209
|
+
}
|
|
210
|
+
continuation.resume(returning: true)
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if !loaded {
|
|
214
|
+
disableIfCurrent(token)
|
|
215
|
+
throw MonitorError.modelUnavailable
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private func beginDemandChange(enabled value: Bool) -> UInt64 {
|
|
220
|
+
lock.lock()
|
|
221
|
+
defer { lock.unlock() }
|
|
222
|
+
generation &+= 1
|
|
223
|
+
enabled = value
|
|
224
|
+
return generation
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private func disableIfCurrent(_ token: UInt64) {
|
|
228
|
+
lock.lock()
|
|
229
|
+
defer { lock.unlock() }
|
|
230
|
+
if generation == token { enabled = false }
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
func accept(_ pcm: Data) {
|
|
234
|
+
guard !pcm.isEmpty, isEnabled else { return }
|
|
235
|
+
let now = monotonicMs()
|
|
236
|
+
queue.async {
|
|
237
|
+
guard let tracker = self.tracker, self.isCurrent(self.trackerGeneration) else { return }
|
|
238
|
+
self.report(tracker.accept(pcm, nowMs: now))
|
|
239
|
+
self.scheduleGapCheck()
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/// Run the gap-fill check now. Queue-serialized; for tests.
|
|
244
|
+
func checkGapNow() {
|
|
245
|
+
queue.sync {
|
|
246
|
+
guard let tracker = self.tracker else { return }
|
|
247
|
+
self.report(tracker.fillGap(nowMs: self.monotonicMs()))
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
private func isCurrent(_ token: UInt64) -> Bool {
|
|
252
|
+
lock.lock()
|
|
253
|
+
defer { lock.unlock() }
|
|
254
|
+
return enabled && generation == token
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/// Queue only. At most one check is pending; it always works on the current tracker.
|
|
258
|
+
private func scheduleGapCheck() {
|
|
259
|
+
guard !gapCheckScheduled, let tracker, let due = tracker.nextGapFillDueMs(nowMs: monotonicMs()) else { return }
|
|
260
|
+
gapCheckScheduled = true
|
|
261
|
+
let delayMs = max(1, due - monotonicMs())
|
|
262
|
+
queue.asyncAfter(deadline: .now() + .milliseconds(Int(delayMs))) { [weak self] in
|
|
263
|
+
guard let self else { return }
|
|
264
|
+
self.gapCheckScheduled = false
|
|
265
|
+
guard let current = self.tracker, self.isCurrent(self.trackerGeneration) else { return }
|
|
266
|
+
self.report(current.fillGap(nowMs: self.monotonicMs()))
|
|
267
|
+
self.scheduleGapCheck()
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/// Queue only.
|
|
272
|
+
private func report(_ transitions: [SpeechActivityTransition]) {
|
|
273
|
+
for transition in transitions {
|
|
274
|
+
emit(Event(speaking: transition.speaking, silentForMs: transition.silentForMs, timestamp: epochMs()))
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
@@ -143,6 +143,44 @@ public struct OtaStatusEvent: CustomStringConvertible {
|
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
145
|
|
|
146
|
+
/// Mentra Live stored a BES crash incident; `values` is the glasses message unchanged.
|
|
147
|
+
public struct BesCrashDetectedEvent: CustomStringConvertible {
|
|
148
|
+
public let values: [String: Any]
|
|
149
|
+
|
|
150
|
+
public init(values: [String: Any]) {
|
|
151
|
+
var values = values
|
|
152
|
+
// JavaScript sees null, not undefined, before the incident has a report.
|
|
153
|
+
if stringValue(values, "reportId")?.isEmpty ?? true {
|
|
154
|
+
values["reportId"] = NSNull()
|
|
155
|
+
}
|
|
156
|
+
self.values = values
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
public var incidentKey: String {
|
|
160
|
+
stringValue(values, "incidentKey") ?? ""
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
public var reason: String {
|
|
164
|
+
stringValue(values, "reason") ?? ""
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
public var state: String {
|
|
168
|
+
stringValue(values, "state") ?? ""
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
public var reportId: String? {
|
|
172
|
+
stringValue(values, "reportId")
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
public var summary: [String: Any] {
|
|
176
|
+
values["summary"] as? [String: Any] ?? [:]
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
public var description: String {
|
|
180
|
+
"BesCrashDetectedEvent(incidentKey: \(incidentKey), state: \(state))"
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
146
184
|
public struct OtaQueryResult: CustomStringConvertible {
|
|
147
185
|
public let values: [String: Any]
|
|
148
186
|
|
|
@@ -273,6 +311,7 @@ public enum BluetoothEvent: CustomStringConvertible {
|
|
|
273
311
|
case keepAliveAck(KeepAliveAckEvent)
|
|
274
312
|
case otaStartAck(OtaStartAckEvent)
|
|
275
313
|
case otaStatus(OtaStatusEvent)
|
|
314
|
+
case besCrashDetected(BesCrashDetectedEvent)
|
|
276
315
|
case settingsAck(SettingsAckEvent)
|
|
277
316
|
case versionInfo(VersionInfoResult)
|
|
278
317
|
case localTranscription(LocalTranscriptionEvent)
|
|
@@ -316,6 +355,8 @@ public enum BluetoothEvent: CustomStringConvertible {
|
|
|
316
355
|
event.description
|
|
317
356
|
case let .otaStatus(event):
|
|
318
357
|
event.description
|
|
358
|
+
case let .besCrashDetected(event):
|
|
359
|
+
event.description
|
|
319
360
|
case let .settingsAck(event):
|
|
320
361
|
event.description
|
|
321
362
|
case let .versionInfo(event):
|
|
@@ -32,12 +32,14 @@ enum BleTraceLogger {
|
|
|
32
32
|
return
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
let type = extractType(from: payload)
|
|
36
|
+
if isQuietType(type) { return }
|
|
35
37
|
let sanitized = sanitizeDictionary(payload)
|
|
36
38
|
emit(format(
|
|
37
39
|
direction: direction,
|
|
38
40
|
layer: layer,
|
|
39
41
|
source: source(file: sourceFile, function: sourceFunction, line: sourceLine),
|
|
40
|
-
type:
|
|
42
|
+
type: type,
|
|
41
43
|
bytes: bytes,
|
|
42
44
|
payload: jsonString(sanitized)
|
|
43
45
|
), forwardToBridge: forwardToBridge)
|
|
@@ -104,6 +106,17 @@ enum BleTraceLogger {
|
|
|
104
106
|
return "BLE_TRACE direction=\(direction) layer=\(layer) source=\(source) type=\(type)\(bytesText) payload=\(truncate(payload))"
|
|
105
107
|
}
|
|
106
108
|
|
|
109
|
+
/// Messages sent every few seconds; tracing each would push everything else out of the
|
|
110
|
+
/// logs attached to bug reports.
|
|
111
|
+
static func isQuietType(_ type: String?) -> Bool {
|
|
112
|
+
type == "hotspot_keepalive"
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/// Cheap check on a raw inbound JSON string, before it is parsed.
|
|
116
|
+
static func isQuietJson(_ json: String) -> Bool {
|
|
117
|
+
json.count <= 256 && json.contains("\"hotspot_keepalive\"")
|
|
118
|
+
}
|
|
119
|
+
|
|
107
120
|
private static func extractType(from payload: [String: Any]) -> String {
|
|
108
121
|
if let type = payload["type"] as? String, !type.isEmpty {
|
|
109
122
|
return type
|
|
@@ -5,9 +5,18 @@ final class BluetoothAvailability: NSObject, CBCentralManagerDelegate {
|
|
|
5
5
|
static let shared = BluetoothAvailability()
|
|
6
6
|
|
|
7
7
|
private var centralManager: CBCentralManager?
|
|
8
|
-
private var
|
|
8
|
+
private var systemState: CBManagerState = .unknown
|
|
9
9
|
private var listeners: [UUID: (CBManagerState) -> Void] = [:]
|
|
10
10
|
|
|
11
|
+
/// Test seam: while set, listeners and availability checks see this state instead of the
|
|
12
|
+
/// host's radio, so a test does not depend on the machine's Bluetooth. Set it before the SDK
|
|
13
|
+
/// under test registers its listener; the system's own updates are not delivered meanwhile.
|
|
14
|
+
var stateOverride: CBManagerState?
|
|
15
|
+
|
|
16
|
+
private var state: CBManagerState {
|
|
17
|
+
stateOverride ?? systemState
|
|
18
|
+
}
|
|
19
|
+
|
|
11
20
|
override private init() {
|
|
12
21
|
super.init()
|
|
13
22
|
centralManager = CBCentralManager(
|
|
@@ -15,11 +24,12 @@ final class BluetoothAvailability: NSObject, CBCentralManagerDelegate {
|
|
|
15
24
|
queue: .main,
|
|
16
25
|
options: [CBCentralManagerOptionShowPowerAlertKey: false]
|
|
17
26
|
)
|
|
18
|
-
|
|
27
|
+
systemState = centralManager?.state ?? .unknown
|
|
19
28
|
}
|
|
20
29
|
|
|
21
30
|
func centralManagerDidUpdateState(_ central: CBCentralManager) {
|
|
22
|
-
|
|
31
|
+
systemState = central.state
|
|
32
|
+
guard stateOverride == nil else { return }
|
|
23
33
|
for listener in Array(listeners.values) {
|
|
24
34
|
listener(state)
|
|
25
35
|
}
|
|
@@ -44,7 +54,7 @@ final class BluetoothAvailability: NSObject, CBCentralManagerDelegate {
|
|
|
44
54
|
/// Whether phone Bluetooth is switched off right now. Read on the main thread,
|
|
45
55
|
/// where the central manager delivers its state.
|
|
46
56
|
var isPoweredOff: Bool {
|
|
47
|
-
(centralManager?.state ??
|
|
57
|
+
(stateOverride ?? centralManager?.state ?? systemState) == .poweredOff
|
|
48
58
|
}
|
|
49
59
|
|
|
50
60
|
/// Read-only system lookup. It neither connects nor claims ownership.
|
|
@@ -56,7 +66,7 @@ final class BluetoothAvailability: NSObject, CBCentralManagerDelegate {
|
|
|
56
66
|
|
|
57
67
|
func requirePoweredOn(operation: String) throws {
|
|
58
68
|
if let current = centralManager?.state {
|
|
59
|
-
|
|
69
|
+
systemState = current
|
|
60
70
|
}
|
|
61
71
|
switch state {
|
|
62
72
|
case .poweredOn:
|
|
@@ -112,6 +112,11 @@ enum GlassesAudioSetupPolicy {
|
|
|
112
112
|
static func decide(_ inputs: GlassesAudioSetupInputs, nowMs: Int) -> GlassesAudioSetupDecision {
|
|
113
113
|
guard inputs.sessionReady else { return GlassesAudioSetupDecision(state: .idle, nextDeadlineMs: nil) }
|
|
114
114
|
if audioUp(inputs) { return GlassesAudioSetupDecision(state: .connected, nextDeadlineMs: nil) }
|
|
115
|
+
// Glasses on the pairing protocol report classic_link. After setup they page their owner's
|
|
116
|
+
// Classic link themselves, so a settings step can neither speed audio up nor fix it.
|
|
117
|
+
if inputs.phase == .reconnect && inputs.glassesReportsClassicLink {
|
|
118
|
+
return GlassesAudioSetupDecision(state: .connecting, nextDeadlineMs: nil)
|
|
119
|
+
}
|
|
115
120
|
// A report of A2DP and HFP both down does not shorten the wait: iOS may still be
|
|
116
121
|
// bringing the link up.
|
|
117
122
|
let deadline = inputs.phaseStartedAtMs + waitMs(inputs.phase)
|