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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/MIGRATION.md +61 -0
  2. package/README.md +111 -11
  3. package/android/build.gradle +60 -51
  4. package/android/gradle.properties +3 -0
  5. package/android/settings.gradle +47 -3
  6. package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -2
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +89 -6
  9. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +35 -1
  10. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +159 -110
  11. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +21 -0
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +2 -1
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +35 -2
  15. package/android/src/main/java/com/mentra/bluetoothsdk/TouchGesture.kt +19 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/connection/ConnectionModels.kt +5 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicy.kt +64 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +1002 -157
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +227 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +19 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicy.kt +94 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachine.kt +411 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateStore.kt +124 -0
  25. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +54 -59
  26. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +5 -32
  27. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +8 -1
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +3 -10
  29. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  30. package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +50 -0
  31. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  32. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  33. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  34. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  35. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  36. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  38. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  39. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  40. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  41. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  42. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  43. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  44. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  45. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  46. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerOwnerLossTest.kt +146 -0
  47. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusAudioSetupTest.kt +51 -0
  48. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusClassicAudioTest.kt +2 -0
  49. package/android/src/test/java/com/mentra/bluetoothsdk/TouchGestureCommandTest.kt +112 -0
  50. package/android/src/test/java/com/mentra/bluetoothsdk/WifiAdbPeerIntentTest.kt +19 -0
  51. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicyTest.kt +65 -0
  52. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveAudioSetupReadinessTest.kt +231 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
  54. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +368 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +20 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicyTest.kt +136 -0
  58. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachineTest.kt +346 -0
  59. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
  60. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  61. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  62. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  63. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  64. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  65. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  66. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  67. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  68. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  69. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  70. package/build/BluetoothSdk.types.d.ts +207 -2
  71. package/build/BluetoothSdk.types.d.ts.map +1 -1
  72. package/build/BluetoothSdk.types.js.map +1 -1
  73. package/build/_private/BluetoothSdkModule.d.ts +45 -6
  74. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  75. package/build/_private/BluetoothSdkModule.js +2 -0
  76. package/build/_private/BluetoothSdkModule.js.map +1 -1
  77. package/build/generated/changelogCatalog.d.ts +4 -1
  78. package/build/generated/changelogCatalog.d.ts.map +1 -1
  79. package/build/generated/changelogCatalog.js +5 -1
  80. package/build/generated/changelogCatalog.js.map +1 -1
  81. package/build/generated/releaseMetadata.js +6 -6
  82. package/build/generated/releaseMetadata.js.map +1 -1
  83. package/build/index.d.ts +1 -1
  84. package/build/index.d.ts.map +1 -1
  85. package/build/index.js +10 -0
  86. package/build/index.js.map +1 -1
  87. package/ios/BluetoothSdkModule.swift +84 -12
  88. package/ios/MentraBluetoothSDK.podspec +4 -0
  89. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  90. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  91. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  92. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  93. package/ios/Source/Bridge.swift +11 -3
  94. package/ios/Source/DeviceManager.swift +135 -18
  95. package/ios/Source/DeviceStore.swift +27 -0
  96. package/ios/Source/GeneratedChangelogCatalog.swift +2 -1
  97. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  98. package/ios/Source/MentraBluetoothSDK.swift +51 -5
  99. package/ios/Source/TouchGesture.swift +13 -0
  100. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  101. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  102. package/ios/Source/audio/SpeechActivity.swift +277 -0
  103. package/ios/Source/errors/BluetoothSdkError.swift +5 -1
  104. package/ios/Source/events/BluetoothEvents.swift +45 -0
  105. package/ios/Source/internal/BleTraceLogger.swift +9 -6
  106. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  107. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +186 -0
  108. package/ios/Source/sgcs/MentraLive.swift +1366 -212
  109. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +260 -1
  110. package/ios/Source/sgcs/MentraLivePairingStateMachine.swift +385 -0
  111. package/ios/Source/sgcs/MentraLivePairingStateStore.swift +121 -0
  112. package/ios/Source/sgcs/Nimo.swift +10 -3
  113. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +39 -9
  114. package/ios/Source/sgcs/SGCManager.swift +13 -0
  115. package/ios/Source/sgcs/Simulated.swift +2 -0
  116. package/ios/Source/status/DeviceStatus.swift +35 -0
  117. package/ios/Source/stt/STTTools.swift +13 -31
  118. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  119. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  120. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  121. package/ios/Source/types/DeviceModels.swift +8 -1
  122. package/ios/Source/utils/AudioSessionMonitor.swift +158 -5
  123. package/ios/Source/utils/BoundedWait.swift +44 -0
  124. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  125. package/ios/Source/utils/SttModelTraits.swift +62 -0
  126. package/ios/Tests/BesCrashReportTests.swift +142 -0
  127. package/ios/Tests/BluetoothAudioRouteTests.swift +82 -0
  128. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  129. package/ios/Tests/DeviceManagerReconnectTests.swift +4 -2
  130. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +197 -0
  131. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  132. package/ios/Tests/MentraLiveAudioSetupTests.swift +209 -0
  133. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  134. package/ios/Tests/MentraLiveConnectionOptionsTests.swift +55 -0
  135. package/ios/Tests/MentraLivePairingAdvertisementTests.swift +327 -0
  136. package/ios/Tests/MentraLivePairingStateMachineTests.swift +402 -0
  137. package/ios/Tests/MentraLiveSessionReadinessTests.swift +497 -26
  138. package/ios/Tests/NimoCanvasTransportTests.swift +58 -0
  139. package/ios/Tests/PcmStreamTests.swift +299 -0
  140. package/ios/Tests/SpeechActivityTests.swift +238 -0
  141. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  142. package/ios/Tests/TouchGestureCommandTests.swift +87 -0
  143. package/ios/Tests/WifiAdbDispatchTests.swift +118 -0
  144. package/package.json +3 -2
  145. package/plugin/build/withAndroid.js +9 -11
  146. package/plugin/build/withKotlinVersion.d.ts +2 -0
  147. package/plugin/build/withKotlinVersion.js +46 -0
  148. package/src/BluetoothSdk.types.ts +216 -1
  149. package/src/_private/BluetoothSdkModule.ts +49 -5
  150. package/src/generated/changelogCatalog.ts +5 -1
  151. package/src/generated/releaseMetadata.ts +6 -6
  152. package/src/index.ts +24 -0
  153. package/android/silero/LICENSE.md +0 -17
  154. package/android/silero/build.gradle +0 -50
  155. package/android/silero/proguard-rules.pro +0 -24
  156. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  157. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  158. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  159. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  160. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  161. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  162. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  163. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  164. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  165. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  166. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  167. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  168. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  169. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  170. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  171. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  172. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -288
  173. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  174. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -4,23 +4,38 @@ import Foundation
4
4
  * SherpaOnnxTranscriber handles real-time audio transcription using Sherpa-ONNX.
5
5
  *
6
6
  * It works fully offline and processes PCM audio in real-time to provide partial and final ASR results.
7
- * This class runs on a background thread, processes short PCM chunks, and emits transcribed text using a delegate.
7
+ * The recognizer exists only while on-device transcription is in demand: the demand-driven worker
8
+ * loads the model Speech settings selected when demand starts and releases it when demand ends.
8
9
  */
9
10
  class SherpaOnnxTranscriber {
10
11
  private static let TAG = "SherpaOnnxTranscriber"
11
12
 
12
13
  private static let SAMPLE_RATE = 16000 // Sherpa-ONNX model's required sample rate
14
+ /// Bounded wait for `finishUtterance`, matching Android.
15
+ private static let FINISH_TIMEOUT_SECONDS: TimeInterval = 3
16
+
13
17
  private final class Session {
14
18
  let recognizer: SherpaOnnxRecognizer
19
+ let modelPath: String
20
+ let language: String
21
+ let traits: SttModelTraits
15
22
  var lastPartialResult = ""
16
23
 
17
- init(_ recognizer: SherpaOnnxRecognizer) {
24
+ init(_ recognizer: SherpaOnnxRecognizer, modelPath: String, language: String, traits: SttModelTraits) {
18
25
  self.recognizer = recognizer
26
+ self.modelPath = modelPath
27
+ self.language = language
28
+ self.traits = traits
19
29
  }
20
30
  }
21
31
 
32
+ // Path of the most recent successful load. Combined with the worker's `initialized` flag it
33
+ // answers `isModelLoaded` without waiting on the worker queue, which may be mid-load.
34
+ private let loadedLock = NSLock()
35
+ private var loadedModelPath: String?
36
+
22
37
  private lazy var worker = DemandDrivenAudioWorker<Session>(
23
- makeProcessor: { Self.makeRecognizer().map(Session.init) },
38
+ makeProcessor: { [weak self] in self?.makeSession() },
24
39
  process: { [weak self] session, data, generation in
25
40
  self?.process(session, data: data, generation: generation)
26
41
  }
@@ -35,28 +50,24 @@ class SherpaOnnxTranscriber {
35
50
  worker.setActive(active)
36
51
  }
37
52
 
38
- /// Dynamic model path support
39
- private static var customModelPath: String? {
40
- guard let storedPath = UserDefaults.standard.string(forKey: "STTModelPath") else {
41
- return nil
53
+ /// The application container changes between development builds, so a stored absolute path
54
+ /// is re-rooted under the current Documents directory.
55
+ private static func resolveModelPath(_ storedPath: String) -> String {
56
+ guard let range = storedPath.range(of: "/Documents/"),
57
+ let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
58
+ else {
59
+ return storedPath
42
60
  }
61
+ let relativePath = String(storedPath[range.upperBound...]) // e.g. "stt_models/..."
62
+ return documentsURL.appendingPathComponent(relativePath).path
63
+ }
43
64
 
44
- // Always resolve current Documents directory
45
- let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
46
-
47
- // Extract relative subpath after "Documents/"
48
- // NOTE: Doing this because the application id changes between the development builds and files can't be found.
49
- if let range = storedPath.range(of: "/Documents/") {
50
- let relativePath = String(storedPath[range.upperBound...]) // e.g. "stt_models/..."
51
- let fixedPath = documentsURL.appendingPathComponent(relativePath).path
52
-
53
- Bridge.log("Reconstructed STTModelPath: \(fixedPath)")
54
- return fixedPath
65
+ /// Model selected in Speech settings, if any.
66
+ private static var selectedModelPath: String? {
67
+ guard let storedPath = UserDefaults.standard.string(forKey: "STTModelPath"), !storedPath.isEmpty else {
68
+ return nil
55
69
  }
56
-
57
- // If nothing matched, just return as-is
58
- Bridge.log("STTModelPath (raw): \(storedPath)")
59
- return storedPath
70
+ return resolveModelPath(storedPath)
60
71
  }
61
72
 
62
73
  private static func firstExistingFile(in directory: String, candidates: [String]) -> String? {
@@ -71,152 +82,195 @@ class SherpaOnnxTranscriber {
71
82
  }
72
83
 
73
84
  /// Runs exclusively on the worker queue, never on the main/audio delivery thread.
74
- private static func makeRecognizer() -> SherpaOnnxRecognizer? {
75
- var recognizer: SherpaOnnxRecognizer?
85
+ private static func makeRecognizer(modelPath customPath: String) -> (SherpaOnnxRecognizer, SttModelTraits)? {
76
86
  do {
77
- var tokensPath: String
78
- var modelType = "unknown"
79
87
  let fileManager = FileManager.default
88
+ // Detect model type based on available files
89
+ let ctcModelPath = Self.firstExistingFile(
90
+ in: customPath,
91
+ candidates: ["model.int8.onnx", "model.onnx"]
92
+ )
93
+ let transducerEncoderPath = Self.firstExistingFile(
94
+ in: customPath,
95
+ candidates: ["encoder.int8.onnx", "encoder.onnx"]
96
+ )
97
+
98
+ let tokensPath = (customPath as NSString).appendingPathComponent("tokens.txt")
99
+
100
+ // Verify tokens file exists
101
+ guard fileManager.fileExists(atPath: tokensPath) else {
102
+ throw NSError(domain: "SherpaOnnxTranscriber", code: 1, userInfo: [
103
+ NSLocalizedDescriptionKey: "tokens.txt not found at path: \(customPath)",
104
+ ])
105
+ }
106
+ let tokens = (try? String(contentsOfFile: tokensPath, encoding: .utf8)) ?? ""
80
107
 
81
- // Check if we have a custom model path set
82
- if let customPath = SherpaOnnxTranscriber.customModelPath {
83
- // Detect model type based on available files
84
- let ctcModelPath = Self.firstExistingFile(
108
+ let traits: SttModelTraits
109
+ var modelConfig: SherpaOnnxOnlineModelConfig
110
+ if let ctcModelPath {
111
+ traits = SttModelTraits(kind: .ctc, tokensFileContents: tokens)
112
+ Bridge.log("Detected CTC model at \(customPath)")
113
+
114
+ let nemoCtc = sherpaOnnxOnlineNemoCtcModelConfig(
115
+ model: ctcModelPath
116
+ )
117
+ modelConfig = sherpaOnnxOnlineModelConfig(
118
+ tokens: tokensPath,
119
+ numThreads: traits.numThreads,
120
+ nemoCtc: nemoCtc
121
+ )
122
+ } else if let transducerEncoderPath {
123
+ traits = SttModelTraits(kind: .transducer, tokensFileContents: tokens)
124
+ Bridge.log("Detected transducer model at \(customPath)")
125
+
126
+ let decoderPath = Self.firstExistingFile(
85
127
  in: customPath,
86
- candidates: ["model.int8.onnx", "model.onnx"]
128
+ candidates: ["decoder.int8.onnx", "decoder.onnx"]
87
129
  )
88
- let transducerEncoderPath = Self.firstExistingFile(
130
+ let joinerPath = Self.firstExistingFile(
89
131
  in: customPath,
90
- candidates: ["encoder.int8.onnx", "encoder.onnx"]
132
+ candidates: ["joiner.int8.onnx", "joiner.onnx"]
91
133
  )
92
134
 
93
- tokensPath = (customPath as NSString).appendingPathComponent("tokens.txt")
94
-
95
- // Verify tokens file exists
96
- guard fileManager.fileExists(atPath: tokensPath) else {
135
+ // Verify all transducer files exist
136
+ guard let decoderPath,
137
+ let joinerPath
138
+ else {
97
139
  throw NSError(domain: "SherpaOnnxTranscriber", code: 1, userInfo: [
98
- NSLocalizedDescriptionKey: "tokens.txt not found at path: \(customPath)",
140
+ NSLocalizedDescriptionKey: "Transducer model files incomplete at path: \(customPath)",
99
141
  ])
100
142
  }
101
143
 
102
- if let ctcModelPath {
103
- // CTC model detected
104
- modelType = "ctc"
105
- Bridge.log("Detected CTC model at \(customPath)")
106
-
107
- // Create CTC model config using Zipformer2Ctc
108
- var nemoCtc = sherpaOnnxOnlineNemoCtcModelConfig(
109
- model: ctcModelPath
110
- )
111
-
112
- // Create model config with CTC
113
- var modelConfig = sherpaOnnxOnlineModelConfig(
114
- tokens: tokensPath,
115
- numThreads: 1,
116
- nemoCtc: nemoCtc
117
- )
118
-
119
- // Configure recognizer
120
- var featureConfig = sherpaOnnxFeatureConfig()
121
-
122
- var config = sherpaOnnxOnlineRecognizerConfig(
123
- featConfig: featureConfig,
124
- modelConfig: modelConfig,
125
- enableEndpoint: true,
126
- rule1MinTrailingSilence: 1.2,
127
- rule2MinTrailingSilence: 0.8,
128
- rule3MinUtteranceLength: 10.0
129
- )
130
-
131
- // Create recognizer with the wrapper
132
- recognizer = SherpaOnnxRecognizer(config: &config)
133
-
134
- } else if let transducerEncoderPath {
135
- // Transducer model detected
136
- modelType = "transducer"
137
- Bridge.log("Detected transducer model at \(customPath)")
138
-
139
- let decoderPath = Self.firstExistingFile(
140
- in: customPath,
141
- candidates: ["decoder.int8.onnx", "decoder.onnx"]
142
- )
143
- let joinerPath = Self.firstExistingFile(
144
- in: customPath,
145
- candidates: ["joiner.int8.onnx", "joiner.onnx"]
146
- )
147
-
148
- // Verify all transducer files exist
149
- guard let decoderPath,
150
- let joinerPath
151
- else {
152
- throw NSError(domain: "SherpaOnnxTranscriber", code: 1, userInfo: [
153
- NSLocalizedDescriptionKey: "Transducer model files incomplete at path: \(customPath)",
154
- ])
155
- }
156
-
157
- // Create Sherpa-ONNX transducer model config
158
- var transducer = sherpaOnnxOnlineTransducerModelConfig(
159
- encoder: transducerEncoderPath,
160
- decoder: decoderPath,
161
- joiner: joinerPath
162
- )
163
-
164
- // Create model config
165
- var modelConfig = sherpaOnnxOnlineModelConfig(
166
- tokens: tokensPath,
167
- transducer: transducer,
168
- numThreads: 1
169
- )
170
-
171
- // Configure recognizer
172
- var featureConfig = sherpaOnnxFeatureConfig()
173
-
174
- var config = sherpaOnnxOnlineRecognizerConfig(
175
- featConfig: featureConfig,
176
- modelConfig: modelConfig,
177
- enableEndpoint: true,
178
- rule1MinTrailingSilence: 1.2,
179
- rule2MinTrailingSilence: 0.8,
180
- rule3MinUtteranceLength: 10.0
181
- )
182
-
183
- // Create recognizer with the wrapper
184
- recognizer = SherpaOnnxRecognizer(config: &config)
185
-
186
- } else {
187
- throw NSError(domain: "SherpaOnnxTranscriber", code: 1, userInfo: [
188
- NSLocalizedDescriptionKey: "No valid model files found at path: \(customPath)",
189
- ])
190
- }
144
+ let transducer = sherpaOnnxOnlineTransducerModelConfig(
145
+ encoder: transducerEncoderPath,
146
+ decoder: decoderPath,
147
+ joiner: joinerPath
148
+ )
149
+ modelConfig = sherpaOnnxOnlineModelConfig(
150
+ tokens: tokensPath,
151
+ transducer: transducer,
152
+ numThreads: traits.numThreads
153
+ )
191
154
  } else {
192
- Bridge.log("No Sherpa ONNX model available. Transcription will be disabled.")
193
- Bridge.log("Please download a model using the model downloader in settings.")
194
- recognizer = nil
195
- return nil
155
+ throw NSError(domain: "SherpaOnnxTranscriber", code: 1, userInfo: [
156
+ NSLocalizedDescriptionKey: "No valid model files found at path: \(customPath)",
157
+ ])
196
158
  }
197
159
 
198
- if recognizer == nil {
199
- throw NSError(domain: "SherpaOnnxTranscriber", code: 2, userInfo: [NSLocalizedDescriptionKey: "Failed to create recognizer"])
200
- }
201
-
202
- Bridge.log("Sherpa-ONNX ASR initialized successfully with \(modelType) model")
203
- return recognizer
204
-
160
+ let featureConfig = sherpaOnnxFeatureConfig()
161
+ var config = sherpaOnnxOnlineRecognizerConfig(
162
+ featConfig: featureConfig,
163
+ modelConfig: modelConfig,
164
+ enableEndpoint: true,
165
+ rule1MinTrailingSilence: 1.2,
166
+ rule2MinTrailingSilence: 0.8,
167
+ rule3MinUtteranceLength: 10.0
168
+ )
169
+ let recognizer = SherpaOnnxRecognizer(config: &config)
170
+
171
+ Bridge.log(
172
+ "Sherpa-ONNX ASR initialized with \(traits.kind.rawValue) model, threads=\(traits.numThreads), " +
173
+ "finalizeEarly=\(traits.canFinalizeEarly), lowercase=\(traits.uppercaseOnlyVocabulary)"
174
+ )
175
+ return (recognizer, traits)
205
176
  } catch {
206
177
  Bridge.log("Failed to initialize Sherpa-ONNX: \(error.localizedDescription)")
207
178
  return nil
208
179
  }
209
180
  }
210
181
 
211
- private func handleTranscriptionResult(text: String, isFinal: Bool, generation: UInt64) {
182
+ /// Worker queue only. Loads the model Speech settings selects right now.
183
+ private func makeSession() -> Session? {
184
+ setLoadedModelPath(nil)
185
+ guard let path = Self.selectedModelPath else {
186
+ Bridge.log("No Sherpa ONNX model available. Transcription will be disabled.")
187
+ Bridge.log("Please download a model using the model downloader in settings.")
188
+ return nil
189
+ }
190
+ Bridge.log("Loading STT model: \(path)")
191
+ let language = UserDefaults.standard.string(forKey: "STTModelLanguageCode") ?? "en-US"
192
+ guard let loaded = Self.makeRecognizer(modelPath: path) else { return nil }
193
+ setLoadedModelPath(path)
194
+ return Session(loaded.0, modelPath: path, language: language, traits: loaded.1)
195
+ }
196
+
197
+ private func setLoadedModelPath(_ path: String?) {
198
+ loadedLock.lock()
199
+ loadedModelPath = path
200
+ loadedLock.unlock()
201
+ }
202
+
203
+ /// Whether on-device demand currently has `path` loaded. Never waits for a load.
204
+ func isModelLoaded(_ path: String) -> Bool {
205
+ guard worker.snapshot().initialized else { return false }
206
+ loadedLock.lock()
207
+ defer { loadedLock.unlock() }
208
+ return loadedModelPath == Self.resolveModelPath(path)
209
+ }
210
+
211
+ /// Reload the selected model when on-device transcription is in demand. Returns false only
212
+ /// when the reload failed; true once it loaded or when there is no demand.
213
+ func restart() async -> Bool {
214
+ let state = await worker.restartAndAwaitLoad()
215
+ return state != .failed
216
+ }
217
+
218
+ /**
219
+ * End the active recognizer's current utterance now, after all audio queued before the call.
220
+ * Returns the final text once its `local_transcription` event has been sent ("" if nothing was
221
+ * pending), or nil when there is no active streaming model, the model can't finalize early, or
222
+ * the bounded wait expires.
223
+ */
224
+ func finishUtterance() async -> String? {
225
+ await withBoundedWait(timeout: Self.FINISH_TIMEOUT_SECONDS, timeoutValue: nil) { resolver in
226
+ Task {
227
+ let started = await self.worker.withCurrentProcessor { session, generation -> Bool in
228
+ // A late run after the caller gave up must not cut the utterance.
229
+ guard !resolver.isSettled, session.traits.canFinalizeEarly else { return false }
230
+ let text = self.flush(session)
231
+ DispatchQueue.main.async {
232
+ guard self.worker.isCurrent(generation) else {
233
+ resolver.resolve(nil)
234
+ return
235
+ }
236
+ if !text.isEmpty {
237
+ STTTools.sendTranscription(text, isFinal: true, language: session.language)
238
+ }
239
+ resolver.resolve(text)
240
+ }
241
+ return true
242
+ }
243
+ if started != true { resolver.resolve(nil) }
244
+ }
245
+ }
246
+ }
247
+
248
+ /// Worker queue only. Decodes everything the stream holds and replaces the ended stream.
249
+ private func flush(_ session: Session) -> String {
250
+ let startedAt = Date()
251
+ let recognizer = session.recognizer
252
+ // Sherpa's streaming file decoder uses 660 ms of padding before inputFinished.
253
+ // This is synthetic context, decoded immediately; it is not a wall-clock wait.
254
+ recognizer.acceptWaveform(samples: [Float](repeating: 0, count: Self.SAMPLE_RATE * 66 / 100), sampleRate: Self.SAMPLE_RATE)
255
+ recognizer.inputFinished()
256
+ while recognizer.isReady() {
257
+ recognizer.decode()
258
+ }
259
+ let text = session.traits.format(recognizer.getResult().text.trimmingCharacters(in: .whitespacesAndNewlines))
260
+ // An ended stream cannot accept new samples. Keep the model and replace only its stream.
261
+ if !recognizer.recreateStream() {
262
+ recognizer.reset()
263
+ }
264
+ session.lastPartialResult = ""
265
+ Bridge.log("STT_FINISH elapsedMs=\(Int(Date().timeIntervalSince(startedAt) * 1000)) characters=\(text.count)")
266
+ return text
267
+ }
268
+
269
+ private func handleTranscriptionResult(text: String, isFinal: Bool, language: String, generation: UInt64) {
212
270
  DispatchQueue.main.async { [weak self] in
213
271
  // A decode or main-queue delivery may finish after stop/model replacement.
214
272
  guard let self, self.worker.isCurrent(generation) else { return }
215
- if isFinal {
216
- STTTools.didReceiveFinalTranscription(text)
217
- } else {
218
- STTTools.didReceivePartialTranscription(text)
219
- }
273
+ STTTools.sendTranscription(text, isFinal: isFinal, language: language)
220
274
  }
221
275
  }
222
276
 
@@ -233,15 +287,15 @@ class SherpaOnnxTranscriber {
233
287
  recognizer.decode()
234
288
  }
235
289
  guard worker.isCurrent(generation) else { return }
236
- let text = recognizer.getResult().text.trimmingCharacters(in: .whitespacesAndNewlines)
290
+ let text = session.traits.format(recognizer.getResult().text.trimmingCharacters(in: .whitespacesAndNewlines))
237
291
  if recognizer.isEndpoint() {
238
292
  if !text.isEmpty {
239
- handleTranscriptionResult(text: text, isFinal: true, generation: generation)
293
+ handleTranscriptionResult(text: text, isFinal: true, language: session.language, generation: generation)
240
294
  }
241
295
  recognizer.reset()
242
296
  session.lastPartialResult = ""
243
297
  } else if !text.isEmpty, text != session.lastPartialResult {
244
- handleTranscriptionResult(text: text, isFinal: false, generation: generation)
298
+ handleTranscriptionResult(text: text, isFinal: false, language: session.language, generation: generation)
245
299
  session.lastPartialResult = text
246
300
  }
247
301
  }
@@ -254,17 +308,9 @@ class SherpaOnnxTranscriber {
254
308
  var samples = [Float](repeating: 0, count: count)
255
309
 
256
310
  pcmData.withUnsafeBytes { (bufferPointer: UnsafeRawBufferPointer) in
257
- if let address = bufferPointer.baseAddress {
258
- let int16Pointer = address.bindMemory(to: Int16.self, capacity: count)
259
-
260
- for i in 0 ..< count {
261
- // Convert from little-endian if needed
262
- var sample = int16Pointer[i]
263
- if CFByteOrderGetCurrent() == CFByteOrder(CFByteOrderBigEndian.rawValue) {
264
- sample = Int16(littleEndian: sample)
265
- }
266
- samples[i] = Float(sample) / 32768.0
267
- }
311
+ for i in 0 ..< count {
312
+ let bits = UInt16(bufferPointer[i * 2]) | (UInt16(bufferPointer[i * 2 + 1]) << 8)
313
+ samples[i] = Float(Int16(bitPattern: bits)) / 32768.0
268
314
  }
269
315
  }
270
316
 
@@ -274,8 +320,4 @@ class SherpaOnnxTranscriber {
274
320
  func shutdown() {
275
321
  worker.setActive(false)
276
322
  }
277
-
278
- func restart() {
279
- worker.restart()
280
- }
281
323
  }
@@ -0,0 +1,87 @@
1
+ import Foundation
2
+
3
+ /// Silero voice activity detection through sherpa-onnx, one 512-sample frame at a time.
4
+ final class SileroSpeechActivityClassifier: SpeechActivityClassifier {
5
+ /// Resource bundle declared in MentraBluetoothSDK.podspec.
6
+ private static let bundleName = "MentraSileroVad"
7
+ /// Long enough that real speech is never split. sherpa-onnx raises its threshold past this
8
+ /// to force a split, which bounds the speech it buffers during continuous noise.
9
+ private static let maxSpeechSeconds: Float = 30
10
+ private static let minSpeechSeconds: Float = 0.25
11
+ private static let threshold: Float = 0.5
12
+
13
+ private let vad: SherpaOnnxVoiceActivityDetectorWrapper
14
+
15
+ init?(modelPath: String, minSilenceMs: Int) {
16
+ guard FileManager.default.fileExists(atPath: modelPath) else {
17
+ Bridge.log("SPEECH_ACTIVITY: Silero model missing at \(modelPath)")
18
+ return nil
19
+ }
20
+ let silero = sherpaOnnxSileroVadModelConfig(
21
+ model: modelPath,
22
+ threshold: Self.threshold,
23
+ minSilenceDuration: Float(minSilenceMs) / 1000,
24
+ minSpeechDuration: Self.minSpeechSeconds,
25
+ windowSize: SpeechActivityTracker.frameSamples,
26
+ maxSpeechDuration: Self.maxSpeechSeconds
27
+ )
28
+ var config = sherpaOnnxVadModelConfig(
29
+ sileroVad: silero,
30
+ sampleRate: Int32(SpeechActivityTracker.sampleRate),
31
+ numThreads: 1
32
+ )
33
+ guard let vad = SherpaOnnxVoiceActivityDetectorWrapper(
34
+ config: &config,
35
+ buffer_size_in_seconds: Self.maxSpeechSeconds + 2
36
+ ) else {
37
+ Bridge.log("SPEECH_ACTIVITY: sherpa-onnx rejected the Silero model")
38
+ return nil
39
+ }
40
+ self.vad = vad
41
+ }
42
+
43
+ func isSpeech(afterAccepting frame: [Float]) -> Bool {
44
+ vad.acceptWaveform(samples: frame)
45
+ // Only the live state matters; drop finished segments so they don't accumulate.
46
+ while !vad.isEmpty() {
47
+ vad.pop()
48
+ }
49
+ return vad.isSpeechDetected()
50
+ }
51
+
52
+ static var bundledModelPath: String? {
53
+ let candidates = [Bundle(for: SileroSpeechActivityClassifier.self), Bundle.main]
54
+ for bundle in candidates {
55
+ if let url = bundle.url(forResource: bundleName, withExtension: "bundle"),
56
+ let resources = Bundle(url: url),
57
+ let path = resources.path(forResource: "silero_vad", ofType: "onnx")
58
+ {
59
+ return path
60
+ }
61
+ if let path = bundle.path(forResource: "silero_vad", ofType: "onnx") {
62
+ return path
63
+ }
64
+ }
65
+ return nil
66
+ }
67
+ }
68
+
69
+ extension SpeechActivityMonitor {
70
+ /// Phone-side speech activity on the microphone PCM the wake word and STT also see.
71
+ static let shared = SpeechActivityMonitor(
72
+ makeClassifier: { minSilenceMs in
73
+ guard let path = SileroSpeechActivityClassifier.bundledModelPath else {
74
+ Bridge.log("SPEECH_ACTIVITY: silero_vad.onnx is not bundled")
75
+ return nil
76
+ }
77
+ return SileroSpeechActivityClassifier(modelPath: path, minSilenceMs: minSilenceMs)
78
+ },
79
+ emit: { event in
80
+ Bridge.sendTypedMessage("speech_activity", body: [
81
+ "speaking": event.speaking,
82
+ "silentForMs": event.silentForMs,
83
+ "timestamp": event.timestamp,
84
+ ])
85
+ }
86
+ )
87
+ }