@mentra/bluetooth-sdk 3.4.0-dev.1169 → 3.4.0-dev.1171

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 (79) hide show
  1. package/android/build.gradle +6 -36
  2. package/android/settings.gradle +1 -4
  3. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +61 -3
  4. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +27 -0
  5. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +89 -104
  6. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
  7. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  8. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  9. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  10. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  11. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  12. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  13. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  14. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  15. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  17. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  18. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  19. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  20. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  21. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  22. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  23. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  24. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  25. package/build/BluetoothSdk.types.d.ts +49 -0
  26. package/build/BluetoothSdk.types.d.ts.map +1 -1
  27. package/build/BluetoothSdk.types.js.map +1 -1
  28. package/build/_private/BluetoothSdkModule.d.ts +31 -4
  29. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  30. package/build/_private/BluetoothSdkModule.js.map +1 -1
  31. package/build/generated/releaseMetadata.js +5 -5
  32. package/build/generated/releaseMetadata.js.map +1 -1
  33. package/build/index.d.ts +1 -1
  34. package/build/index.d.ts.map +1 -1
  35. package/build/index.js +5 -0
  36. package/build/index.js.map +1 -1
  37. package/ios/BluetoothSdkModule.swift +58 -8
  38. package/ios/MentraBluetoothSDK.podspec +4 -0
  39. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  40. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  41. package/ios/Source/BluetoothSdkDefaults.swift +1 -1
  42. package/ios/Source/DeviceManager.swift +30 -12
  43. package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
  44. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  45. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  46. package/ios/Source/audio/SpeechActivity.swift +277 -0
  47. package/ios/Source/stt/STTTools.swift +13 -31
  48. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  49. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  50. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  51. package/ios/Source/utils/BoundedWait.swift +44 -0
  52. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  53. package/ios/Source/utils/SttModelTraits.swift +62 -0
  54. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  55. package/ios/Tests/PcmStreamTests.swift +299 -0
  56. package/ios/Tests/SpeechActivityTests.swift +238 -0
  57. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  58. package/package.json +2 -2
  59. package/plugin/build/withAndroid.js +7 -11
  60. package/src/BluetoothSdk.types.ts +49 -0
  61. package/src/_private/BluetoothSdkModule.ts +33 -4
  62. package/src/generated/releaseMetadata.ts +5 -5
  63. package/src/index.ts +7 -0
  64. package/android/silero/LICENSE.md +0 -17
  65. package/android/silero/build.gradle +0 -50
  66. package/android/silero/proguard-rules.pro +0 -24
  67. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  68. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  69. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  70. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  71. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  72. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  73. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  74. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  75. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  76. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  77. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  78. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  79. /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
+ }
@@ -3,46 +3,28 @@ import Foundation
3
3
  class STTTools {
4
4
  // MARK: - SherpaOnnxTranscriber / STT Model Management
5
5
 
6
- static func didReceivePartialTranscription(_ text: String) {
7
- // Send partial result to server witgetConnectedBluetoothNameh proper formatting
8
- let transcriptionLanguage =
9
- UserDefaults.standard.string(forKey: "STTModelLanguageCode") ?? "en-US"
10
- // Bridge.log("Mentra: Sending partial transcription: \(text), \(transcriptionLanguage)")
6
+ /// Send a transcript the loaded model produced. `text` is already formatted for that model,
7
+ /// and `language` is the language it was loaded for.
8
+ static func sendTranscription(_ text: String, isFinal: Bool, language: String) {
9
+ guard !text.isEmpty else { return }
10
+ if isFinal {
11
+ Bridge.log("Mentra: Sending final transcription: \(text), \(language)")
12
+ }
13
+ let now = Int(Date().timeIntervalSince1970 * 1000)
11
14
  let transcription: [String: Any] = [
12
15
  "type": "local_transcription",
13
- "text": transcriptionLanguage == "en-US" ? text.lowercased() : text,
14
- "isFinal": false,
15
- "startTime": Int(Date().timeIntervalSince1970 * 1000) - 1000, // 1 second ago
16
- "endTime": Int(Date().timeIntervalSince1970 * 1000),
16
+ "text": text,
17
+ "isFinal": isFinal,
18
+ "startTime": now - (isFinal ? 2000 : 1000),
19
+ "endTime": now,
17
20
  "speakerId": 0,
18
- "transcribeLanguage": transcriptionLanguage,
21
+ "transcribeLanguage": language,
19
22
  "provider": "sherpa-onnx",
20
23
  ]
21
24
 
22
25
  Bridge.sendLocalTranscription(transcription: transcription)
23
26
  }
24
27
 
25
- static func didReceiveFinalTranscription(_ text: String) {
26
- // Send final result to server with proper formatting
27
- let transcriptionLanguage =
28
- UserDefaults.standard.string(forKey: "STTModelLanguageCode") ?? "en-US"
29
- Bridge.log("Mentra: Sending final transcription: \(text), \(transcriptionLanguage)")
30
- if !text.isEmpty {
31
- let transcription: [String: Any] = [
32
- "type": "local_transcription",
33
- "text": transcriptionLanguage == "en-US" ? text.lowercased() : text,
34
- "isFinal": true,
35
- "startTime": Int(Date().timeIntervalSince1970 * 1000) - 2000, // 2 seconds ago
36
- "endTime": Int(Date().timeIntervalSince1970 * 1000),
37
- "speakerId": 0,
38
- "transcribeLanguage": transcriptionLanguage,
39
- "provider": "sherpa-onnx",
40
- ]
41
-
42
- Bridge.sendLocalTranscription(transcription: transcription)
43
- }
44
- }
45
-
46
28
  static func setSttModelDetails(_ path: String, _ languageCode: String) {
47
29
  UserDefaults.standard.set(path, forKey: "STTModelPath")
48
30
  UserDefaults.standard.set(languageCode, forKey: "STTModelLanguageCode")