@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
|
@@ -1,36 +1,56 @@
|
|
|
1
1
|
package com.mentra.bluetoothsdk.stt
|
|
2
2
|
|
|
3
3
|
import android.content.Context
|
|
4
|
-
import android.content.SharedPreferences
|
|
5
4
|
import android.os.Handler
|
|
6
5
|
import android.os.Looper
|
|
7
|
-
import com.
|
|
8
|
-
import com.k2fsa.sherpa.onnx
|
|
6
|
+
import com.k2fsa.sherpa.onnx.OnlineModelConfig
|
|
7
|
+
import com.k2fsa.sherpa.onnx.OnlineNeMoCtcModelConfig
|
|
8
|
+
import com.k2fsa.sherpa.onnx.OnlineRecognizer
|
|
9
|
+
import com.k2fsa.sherpa.onnx.OnlineRecognizerConfig
|
|
10
|
+
import com.k2fsa.sherpa.onnx.OnlineStream
|
|
11
|
+
import com.k2fsa.sherpa.onnx.OnlineTransducerModelConfig
|
|
9
12
|
import com.mentra.bluetoothsdk.Bridge
|
|
13
|
+
import com.mentra.bluetoothsdk.utils.NativeLog as Log
|
|
10
14
|
import java.io.File
|
|
11
15
|
import java.nio.ByteBuffer
|
|
12
16
|
import java.nio.ByteOrder
|
|
13
|
-
import java.util.concurrent.
|
|
14
|
-
import java.util.concurrent.
|
|
15
|
-
import java.util.concurrent.atomic.AtomicBoolean
|
|
17
|
+
import java.util.concurrent.CompletableFuture
|
|
18
|
+
import java.util.concurrent.TimeUnit
|
|
16
19
|
|
|
17
20
|
/**
|
|
18
|
-
*
|
|
21
|
+
* Real-time on-device transcription with Sherpa-ONNX.
|
|
19
22
|
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
+
* Each loaded model is a session with its own worker thread. Audio and control requests
|
|
24
|
+
* (finish, reset, release) go through one bounded queue, and the session's native recognizer
|
|
25
|
+
* and stream are only ever touched on that worker, including when they are released. Replacing
|
|
26
|
+
* or shutting down a session therefore never frees native memory that a decode is still using:
|
|
27
|
+
* the release runs on the worker after the audio already queued to it.
|
|
23
28
|
*
|
|
24
|
-
*
|
|
29
|
+
* [initialModelPath] / [initialModelLanguage] pin a specific model; without them the model
|
|
30
|
+
* stored by [STTTools.setSttModelDetails] is used.
|
|
25
31
|
*/
|
|
26
|
-
class SherpaOnnxTranscriber
|
|
32
|
+
class SherpaOnnxTranscriber
|
|
33
|
+
@JvmOverloads
|
|
34
|
+
constructor(
|
|
35
|
+
private val context: Context,
|
|
36
|
+
private var initialModelPath: String? = null,
|
|
37
|
+
private var initialModelLanguage: String? = null,
|
|
38
|
+
) {
|
|
27
39
|
companion object {
|
|
28
40
|
private const val TAG = "SherpaOnnxTranscriber"
|
|
29
41
|
private const val SAMPLE_RATE = 16000 // Sherpa-ONNX model's required sample rate
|
|
30
42
|
private const val QUEUE_CAPACITY = 100 // Max number of audio buffers to keep in queue
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Streaming transducers (Zipformer, including Kroko) decode in real time on low-end
|
|
46
|
+
* phones only with several threads. Decided by model type, never by folder name, and
|
|
47
|
+
* the same on iOS.
|
|
48
|
+
*/
|
|
49
|
+
internal const val TRANSDUCER_THREADS = 4
|
|
50
|
+
internal const val CTC_THREADS = 1
|
|
51
|
+
|
|
52
|
+
/** How long [finishUtterance] waits for the worker before giving up. */
|
|
53
|
+
internal const val FINISH_TIMEOUT_MS = 3_000L
|
|
34
54
|
}
|
|
35
55
|
|
|
36
56
|
/** Interface to receive transcription results from Sherpa-ONNX */
|
|
@@ -42,187 +62,270 @@ class SherpaOnnxTranscriber(private val context: Context) {
|
|
|
42
62
|
fun onFinalResult(text: String, language: String)
|
|
43
63
|
}
|
|
44
64
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
65
|
+
internal enum class ModelType {
|
|
66
|
+
/** Streaming transducer: can be finalized early. */
|
|
67
|
+
TRANSDUCER,
|
|
68
|
+
/** Streaming NeMo CTC. */
|
|
69
|
+
CTC,
|
|
70
|
+
}
|
|
48
71
|
|
|
49
|
-
private
|
|
50
|
-
|
|
51
|
-
|
|
72
|
+
private sealed class Item {
|
|
73
|
+
class Audio(val pcm: ByteArray) : Item()
|
|
74
|
+
class Finish(val result: CompletableFuture<String?>) : Item()
|
|
75
|
+
object Reset : Item()
|
|
76
|
+
object Close : Item()
|
|
77
|
+
}
|
|
52
78
|
|
|
53
|
-
private
|
|
79
|
+
private val mainHandler = Handler(Looper.getMainLooper())
|
|
54
80
|
@Volatile private var transcriptListener: TranscriptListener? = null
|
|
81
|
+
@Volatile private var session: Session? = null
|
|
82
|
+
private val lifecycleLock = Any()
|
|
83
|
+
|
|
84
|
+
/** One loaded model and its worker. */
|
|
85
|
+
private inner class Session(
|
|
86
|
+
/** Path as selected (before resolving a stale Documents prefix). */
|
|
87
|
+
val requestedPath: String,
|
|
88
|
+
/** Directory the model was loaded from. */
|
|
89
|
+
val modelPath: String,
|
|
90
|
+
val language: String,
|
|
91
|
+
val modelType: ModelType,
|
|
92
|
+
val casing: SttTextFormatter.Casing,
|
|
93
|
+
private val recognizer: OnlineRecognizer,
|
|
94
|
+
private var stream: OnlineStream,
|
|
95
|
+
) {
|
|
96
|
+
private val queue = BoundedAudioQueue<Item>(QUEUE_CAPACITY) { it is Item.Audio }
|
|
97
|
+
@Volatile var closed = false
|
|
98
|
+
private set
|
|
99
|
+
private var lastPartialResult = ""
|
|
100
|
+
private var lastDropLogAt = 0L
|
|
101
|
+
private val worker = Thread({ runLoop() }, "SherpaOnnxProcessor").apply { isDaemon = true }
|
|
102
|
+
|
|
103
|
+
fun start() = worker.start()
|
|
104
|
+
|
|
105
|
+
fun accept(pcm: ByteArray) {
|
|
106
|
+
if (closed) return
|
|
107
|
+
if (queue.offer(Item.Audio(pcm)) != null) {
|
|
108
|
+
val now = System.currentTimeMillis()
|
|
109
|
+
if (now - lastDropLogAt > 5_000) {
|
|
110
|
+
lastDropLogAt = now
|
|
111
|
+
Bridge.log("STT: audio queue full; dropped ${queue.droppedAudio} buffer(s) so far")
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
55
115
|
|
|
56
|
-
|
|
57
|
-
|
|
116
|
+
fun finish(): CompletableFuture<String?> {
|
|
117
|
+
val result = CompletableFuture<String?>()
|
|
118
|
+
if (closed) {
|
|
119
|
+
result.complete(null)
|
|
120
|
+
} else {
|
|
121
|
+
queue.offer(Item.Finish(result))
|
|
122
|
+
}
|
|
123
|
+
return result
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
fun reset() {
|
|
127
|
+
if (closed) return
|
|
128
|
+
queue.clearAudio()
|
|
129
|
+
queue.offer(Item.Reset)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Release after the audio already queued; returns immediately. */
|
|
133
|
+
fun close() {
|
|
134
|
+
if (closed) return
|
|
135
|
+
closed = true
|
|
136
|
+
queue.offer(Item.Close)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private fun runLoop() {
|
|
140
|
+
try {
|
|
141
|
+
while (true) {
|
|
142
|
+
when (val item = queue.poll(1_000) ?: continue) {
|
|
143
|
+
is Item.Audio -> decode(item.pcm)
|
|
144
|
+
is Item.Finish -> finishStream(item.result)
|
|
145
|
+
Item.Reset -> resetStream()
|
|
146
|
+
Item.Close -> return
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
} finally {
|
|
150
|
+
for (item in queue.drain()) {
|
|
151
|
+
if (item is Item.Finish) item.result.complete(null)
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
stream.release()
|
|
155
|
+
recognizer.release()
|
|
156
|
+
} catch (e: Exception) {
|
|
157
|
+
Log.e(TAG, "Error releasing Sherpa resources", e)
|
|
158
|
+
}
|
|
159
|
+
Bridge.log("STT: released model at $modelPath")
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
private fun decode(pcm: ByteArray) {
|
|
164
|
+
try {
|
|
165
|
+
stream.acceptWaveform(toFloatArray(pcm), SAMPLE_RATE)
|
|
166
|
+
while (recognizer.isReady(stream)) {
|
|
167
|
+
recognizer.decode(stream)
|
|
168
|
+
}
|
|
169
|
+
val text = recognizer.getResult(stream).text.trim()
|
|
170
|
+
if (recognizer.isEndpoint(stream)) {
|
|
171
|
+
if (text.isNotEmpty()) deliver(this, text, isFinal = true, onDelivered = null)
|
|
172
|
+
recognizer.reset(stream) // Start new utterance
|
|
173
|
+
lastPartialResult = ""
|
|
174
|
+
} else if (text.isNotEmpty() && text != lastPartialResult) {
|
|
175
|
+
deliver(this, text, isFinal = false, onDelivered = null)
|
|
176
|
+
lastPartialResult = text
|
|
177
|
+
}
|
|
178
|
+
} catch (e: Exception) {
|
|
179
|
+
Log.e(TAG, "Error processing audio", e)
|
|
180
|
+
resetStream()
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
private fun finishStream(result: CompletableFuture<String?>) {
|
|
185
|
+
if (modelType != ModelType.TRANSDUCER) {
|
|
186
|
+
result.complete(null)
|
|
187
|
+
return
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
val startedAt = System.currentTimeMillis()
|
|
191
|
+
val current = stream
|
|
192
|
+
// Sherpa's streaming file decoder uses 660 ms of padding before inputFinished.
|
|
193
|
+
// This is synthetic context, decoded immediately; it is not a wall-clock wait.
|
|
194
|
+
current.acceptWaveform(FloatArray(SAMPLE_RATE * 66 / 100), SAMPLE_RATE)
|
|
195
|
+
current.inputFinished()
|
|
196
|
+
while (recognizer.isReady(current)) recognizer.decode(current)
|
|
197
|
+
val text = recognizer.getResult(current).text.trim()
|
|
198
|
+
// An ended stream cannot accept new samples. Keep the model, replace the stream.
|
|
199
|
+
stream = recognizer.createStream("")
|
|
200
|
+
current.release()
|
|
201
|
+
lastPartialResult = ""
|
|
202
|
+
Bridge.log(
|
|
203
|
+
"STT_FINISH elapsedMs=${System.currentTimeMillis() - startedAt} characters=${text.length}"
|
|
204
|
+
)
|
|
205
|
+
if (text.isEmpty()) {
|
|
206
|
+
result.complete("")
|
|
207
|
+
} else {
|
|
208
|
+
// Resolve only once the final event has been handed to the bridge.
|
|
209
|
+
deliver(this, text, isFinal = true) { formatted -> result.complete(formatted) }
|
|
210
|
+
}
|
|
211
|
+
} catch (e: Exception) {
|
|
212
|
+
Log.e(TAG, "Error finishing utterance", e)
|
|
213
|
+
result.complete(null)
|
|
214
|
+
resetStream()
|
|
215
|
+
}
|
|
216
|
+
}
|
|
58
217
|
|
|
59
|
-
|
|
60
|
-
|
|
218
|
+
private fun resetStream() {
|
|
219
|
+
try {
|
|
220
|
+
recognizer.reset(stream)
|
|
221
|
+
lastPartialResult = ""
|
|
222
|
+
} catch (e: Exception) {
|
|
223
|
+
Log.e(TAG, "Failed to reset stream", e)
|
|
224
|
+
}
|
|
225
|
+
}
|
|
61
226
|
}
|
|
62
227
|
|
|
63
228
|
/**
|
|
64
|
-
* Get the custom model path from SharedPreferences Resolves
|
|
65
|
-
* directory
|
|
229
|
+
* Get the custom model path from SharedPreferences. Resolves a stale Documents prefix
|
|
230
|
+
* (app id changes between dev builds) against the current files directory.
|
|
66
231
|
*/
|
|
67
|
-
private fun
|
|
68
|
-
val storedPath = prefs.getString(KEY_STT_MODEL_PATH, null) ?: return null
|
|
69
|
-
|
|
70
|
-
// Always resolve to absolute path if it contains "Documents/"
|
|
71
|
-
// This handles app ID changes between dev builds
|
|
232
|
+
private fun resolveModelPath(storedPath: String): String {
|
|
72
233
|
if (storedPath.contains("/Documents/")) {
|
|
73
|
-
val documentsDir =
|
|
74
|
-
context.filesDir // In Android, this is the app's private files directory
|
|
75
234
|
val relativePath = storedPath.substringAfter("/Documents/")
|
|
76
|
-
val fixedPath = File(
|
|
235
|
+
val fixedPath = File(context.filesDir, relativePath).absolutePath
|
|
77
236
|
Bridge.log("Reconstructed STTModelPath: $fixedPath")
|
|
78
237
|
return fixedPath
|
|
79
238
|
}
|
|
80
|
-
|
|
81
|
-
Bridge.log("STTModelPath (raw): $storedPath")
|
|
82
239
|
return storedPath
|
|
83
240
|
}
|
|
84
241
|
|
|
85
|
-
/** Get the model language code from SharedPreferences */
|
|
86
|
-
private fun getModelLanguage(): String {
|
|
87
|
-
return prefs.getString(KEY_STT_MODEL_LANGUAGE, "en-US") ?: "en-US"
|
|
88
|
-
}
|
|
89
|
-
|
|
90
242
|
/**
|
|
91
|
-
*
|
|
92
|
-
*
|
|
243
|
+
* Load the model now (synchronously, on the calling thread), replacing any loaded one.
|
|
244
|
+
* The previous model is released on its own worker after the audio queued to it.
|
|
245
|
+
* Throws when there is no model or it can't be loaded.
|
|
93
246
|
*/
|
|
94
|
-
fun
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
if (!modelDir.exists() || !modelDir.isDirectory) {
|
|
108
|
-
Bridge.log("Model path does not exist or is not a directory: $modelPath")
|
|
109
|
-
recognizer = null
|
|
110
|
-
stream = null
|
|
111
|
-
return
|
|
247
|
+
internal fun load() {
|
|
248
|
+
val requestedPath =
|
|
249
|
+
initialModelPath?.takeIf { it.isNotBlank() }
|
|
250
|
+
?: STTTools.getSttModelPath(context).takeIf { it.isNotBlank() }
|
|
251
|
+
?: throw IllegalStateException("No on-device speech model is selected")
|
|
252
|
+
val language = initialModelLanguage ?: STTTools.getSttModelLanguage(context)
|
|
253
|
+
val modelPath = resolveModelPath(requestedPath)
|
|
254
|
+
val next = createSession(requestedPath, modelPath, language)
|
|
255
|
+
val previous =
|
|
256
|
+
synchronized(lifecycleLock) {
|
|
257
|
+
val old = session
|
|
258
|
+
session = next
|
|
259
|
+
old
|
|
112
260
|
}
|
|
261
|
+
next.start()
|
|
262
|
+
previous?.close()
|
|
263
|
+
Bridge.log("Sherpa-ONNX ASR initialized with ${next.modelType} model at $modelPath")
|
|
264
|
+
}
|
|
113
265
|
|
|
114
|
-
|
|
115
|
-
|
|
266
|
+
private fun createSession(requestedPath: String, modelPath: String, language: String): Session {
|
|
267
|
+
val modelDir = File(modelPath)
|
|
268
|
+
if (!modelDir.isDirectory) {
|
|
269
|
+
throw IllegalStateException("Model path does not exist or is not a directory: $modelPath")
|
|
270
|
+
}
|
|
271
|
+
val tokensFile = File(modelDir, "tokens.txt")
|
|
272
|
+
if (!tokensFile.isFile) {
|
|
273
|
+
throw IllegalStateException("tokens.txt not found at path: $modelPath")
|
|
274
|
+
}
|
|
116
275
|
|
|
117
|
-
|
|
118
|
-
|
|
276
|
+
val modelConfig = OnlineModelConfig()
|
|
277
|
+
modelConfig.tokens = tokensFile.absolutePath
|
|
278
|
+
val ctcModelFile = findReadableFile(modelDir, listOf("model.int8.onnx", "model.onnx"))
|
|
279
|
+
val encoderFile = findReadableFile(modelDir, listOf("encoder.onnx", "encoder.int8.onnx"))
|
|
280
|
+
val modelType: ModelType
|
|
281
|
+
when {
|
|
282
|
+
ctcModelFile.exists() -> {
|
|
283
|
+
modelType = ModelType.CTC
|
|
284
|
+
val nemoCtc = OnlineNeMoCtcModelConfig()
|
|
285
|
+
nemoCtc.model = ctcModelFile.absolutePath
|
|
286
|
+
modelConfig.neMoCtc = nemoCtc
|
|
287
|
+
modelConfig.numThreads = CTC_THREADS
|
|
119
288
|
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
val transducerEncoderFile =
|
|
127
|
-
findReadableFile(modelDir, listOf("encoder.onnx", "encoder.int8.onnx"))
|
|
128
|
-
|
|
129
|
-
when {
|
|
130
|
-
ctcModelFile.exists() -> {
|
|
131
|
-
// CTC model detected
|
|
132
|
-
modelType = "ctc"
|
|
133
|
-
Bridge.log("Detected CTC model at $modelPath")
|
|
134
|
-
|
|
135
|
-
val nemoCtc = OnlineNeMoCtcModelConfig()
|
|
136
|
-
nemoCtc.model = ctcModelFile.absolutePath
|
|
137
|
-
|
|
138
|
-
modelConfig.tokens = tokensPath
|
|
139
|
-
modelConfig.numThreads = 1
|
|
140
|
-
modelConfig.neMoCtc = nemoCtc
|
|
141
|
-
}
|
|
142
|
-
transducerEncoderFile.exists() -> {
|
|
143
|
-
// Transducer model detected
|
|
144
|
-
modelType = "transducer"
|
|
145
|
-
Bridge.log("Detected transducer model at $modelPath")
|
|
146
|
-
|
|
147
|
-
val decoderFile =
|
|
148
|
-
findReadableFile(modelDir, listOf("decoder.onnx", "decoder.int8.onnx"))
|
|
149
|
-
val joinerFile =
|
|
150
|
-
findReadableFile(modelDir, listOf("joiner.onnx", "joiner.int8.onnx"))
|
|
151
|
-
|
|
152
|
-
if (!decoderFile.exists() || !joinerFile.exists()) {
|
|
153
|
-
throw IllegalStateException(
|
|
154
|
-
"Transducer model files incomplete at path: $modelPath"
|
|
155
|
-
)
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
val transducer = OnlineTransducerModelConfig()
|
|
159
|
-
transducer.encoder = transducerEncoderFile.absolutePath
|
|
160
|
-
transducer.decoder = decoderFile.absolutePath
|
|
161
|
-
transducer.joiner = joinerFile.absolutePath
|
|
162
|
-
|
|
163
|
-
modelConfig.tokens = tokensPath
|
|
164
|
-
modelConfig.transducer = transducer
|
|
165
|
-
modelConfig.numThreads = 1
|
|
289
|
+
encoderFile.exists() -> {
|
|
290
|
+
modelType = ModelType.TRANSDUCER
|
|
291
|
+
val decoderFile = findReadableFile(modelDir, listOf("decoder.onnx", "decoder.int8.onnx"))
|
|
292
|
+
val joinerFile = findReadableFile(modelDir, listOf("joiner.onnx", "joiner.int8.onnx"))
|
|
293
|
+
if (!decoderFile.exists() || !joinerFile.exists()) {
|
|
294
|
+
throw IllegalStateException("Transducer model files incomplete at path: $modelPath")
|
|
166
295
|
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
val config = OnlineRecognizerConfig()
|
|
174
|
-
config.modelConfig = modelConfig
|
|
175
|
-
config.decodingMethod = "greedy_search"
|
|
176
|
-
config.enableEndpoint = true
|
|
177
|
-
|
|
178
|
-
// Create recognizer (pass null for AssetManager since we're using file paths)
|
|
179
|
-
recognizer =
|
|
180
|
-
try {
|
|
181
|
-
OnlineRecognizer(null, config)
|
|
182
|
-
} catch (e: Exception) {
|
|
183
|
-
Log.e(
|
|
184
|
-
TAG,
|
|
185
|
-
"Failed to create OnlineRecognizer - model file may be corrupted or incomplete",
|
|
186
|
-
e
|
|
187
|
-
)
|
|
188
|
-
null
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
if (recognizer == null) {
|
|
192
|
-
throw IllegalStateException("Failed to create recognizer")
|
|
296
|
+
val transducer = OnlineTransducerModelConfig()
|
|
297
|
+
transducer.encoder = encoderFile.absolutePath
|
|
298
|
+
transducer.decoder = decoderFile.absolutePath
|
|
299
|
+
transducer.joiner = joinerFile.absolutePath
|
|
300
|
+
modelConfig.transducer = transducer
|
|
301
|
+
modelConfig.numThreads = TRANSDUCER_THREADS
|
|
193
302
|
}
|
|
303
|
+
else -> throw IllegalStateException("No valid model files found at path: $modelPath")
|
|
304
|
+
}
|
|
194
305
|
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
Bridge.log("Sherpa-ONNX ASR initialized successfully with $modelType model")
|
|
201
|
-
} catch (e: Exception) {
|
|
202
|
-
Bridge.log("Failed to initialize Sherpa-ONNX: ${e.message}")
|
|
203
|
-
Log.e(TAG, "Failed to initialize Sherpa-ONNX", e)
|
|
204
|
-
|
|
205
|
-
// Clean up any partially initialized resources
|
|
206
|
-
stream?.let {
|
|
207
|
-
try {
|
|
208
|
-
it.release()
|
|
209
|
-
} catch (releaseEx: Exception) {
|
|
210
|
-
Log.e(TAG, "Error releasing stream after initialization failure", releaseEx)
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
stream = null
|
|
306
|
+
val config = OnlineRecognizerConfig()
|
|
307
|
+
config.modelConfig = modelConfig
|
|
308
|
+
config.decodingMethod = "greedy_search"
|
|
309
|
+
config.enableEndpoint = true
|
|
214
310
|
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
311
|
+
// Null AssetManager: the model is loaded from file paths.
|
|
312
|
+
val recognizer = OnlineRecognizer(null, config)
|
|
313
|
+
val stream =
|
|
314
|
+
try {
|
|
315
|
+
recognizer.createStream("")
|
|
316
|
+
} catch (e: Exception) {
|
|
317
|
+
recognizer.release()
|
|
318
|
+
throw e
|
|
221
319
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
320
|
+
return Session(
|
|
321
|
+
requestedPath = requestedPath,
|
|
322
|
+
modelPath = modelPath,
|
|
323
|
+
language = language,
|
|
324
|
+
modelType = modelType,
|
|
325
|
+
casing = SttTextFormatter.casingForModel(modelDir),
|
|
326
|
+
recognizer = recognizer,
|
|
327
|
+
stream = stream,
|
|
328
|
+
)
|
|
226
329
|
}
|
|
227
330
|
|
|
228
331
|
private fun findReadableFile(modelDir: File, candidates: List<String>): File {
|
|
@@ -232,210 +335,117 @@ class SherpaOnnxTranscriber(private val context: Context) {
|
|
|
232
335
|
}
|
|
233
336
|
|
|
234
337
|
/**
|
|
235
|
-
*
|
|
236
|
-
*
|
|
237
|
-
*
|
|
238
|
-
* Audio is queued directly; microphone VAD gating is not applied in the SDK.
|
|
338
|
+
* Initialize the Sherpa-ONNX recognizer. Loads the model and starts its worker. On failure
|
|
339
|
+
* the transcriber stays uninitialized (see [isInitialized]).
|
|
239
340
|
*/
|
|
240
|
-
fun
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
if (!pcmQueue.offer(pcm16le.copyOf())) {
|
|
247
|
-
// Queue is full, drop oldest and try again
|
|
248
|
-
pcmQueue.poll()
|
|
249
|
-
pcmQueue.offer(pcm16le.copyOf())
|
|
250
|
-
Bridge.log("โ ๏ธ Audio queue overflow - dropped buffer")
|
|
341
|
+
fun initialize() {
|
|
342
|
+
try {
|
|
343
|
+
load()
|
|
344
|
+
} catch (e: Exception) {
|
|
345
|
+
Bridge.log("Failed to initialize Sherpa-ONNX: ${e.message}")
|
|
346
|
+
Log.e(TAG, "Failed to initialize Sherpa-ONNX", e)
|
|
251
347
|
}
|
|
252
348
|
}
|
|
253
349
|
|
|
254
|
-
/** Start a background thread to continuously consume audio and decode using Sherpa */
|
|
255
|
-
private fun startProcessingThread() {
|
|
256
|
-
Bridge.log("๐ Starting Sherpa-ONNX processing thread...")
|
|
257
|
-
|
|
258
|
-
workerThread =
|
|
259
|
-
Thread({ runLoop() }, "SherpaOnnxProcessor").apply {
|
|
260
|
-
isDaemon = true
|
|
261
|
-
start()
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
350
|
/**
|
|
266
|
-
*
|
|
267
|
-
*
|
|
351
|
+
* Feed PCM audio data (16-bit little endian, 16 kHz mono). Never blocks and never touches
|
|
352
|
+
* native code on the calling thread.
|
|
268
353
|
*/
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
while (running.get()) {
|
|
273
|
-
try {
|
|
274
|
-
val currentRecognizer = recognizer
|
|
275
|
-
val currentStream = stream
|
|
276
|
-
|
|
277
|
-
if (currentRecognizer == null || currentStream == null) {
|
|
278
|
-
Bridge.log("โ ๏ธ Recognizer or stream not available, skipping audio chunk")
|
|
279
|
-
Thread.sleep(100)
|
|
280
|
-
continue
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
// Pull data from queue with timeout
|
|
284
|
-
val audioData = pcmQueue.poll(50, java.util.concurrent.TimeUnit.MILLISECONDS)
|
|
285
|
-
|
|
286
|
-
if (audioData != null) {
|
|
287
|
-
// Convert PCM to float [-1.0, 1.0]
|
|
288
|
-
val floatBuf = toFloatArray(audioData)
|
|
289
|
-
|
|
290
|
-
// Pass audio data to the Sherpa-ONNX stream
|
|
291
|
-
currentStream.acceptWaveform(floatBuf, SAMPLE_RATE)
|
|
354
|
+
fun acceptAudio(pcm16le: ByteArray) {
|
|
355
|
+
session?.accept(pcm16le.copyOf())
|
|
356
|
+
}
|
|
292
357
|
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
currentRecognizer.decode(currentStream)
|
|
297
|
-
decodeCount++
|
|
298
|
-
}
|
|
358
|
+
/** Whether the loaded model can finish its current utterance early (streaming transducer). */
|
|
359
|
+
internal val canFinalize: Boolean
|
|
360
|
+
get() = session?.modelType == ModelType.TRANSDUCER
|
|
299
361
|
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
val finalText = result.text.trim()
|
|
362
|
+
/** The selected path of the loaded model, or null. Lock-free. */
|
|
363
|
+
internal val loadedModelPath: String?
|
|
364
|
+
get() = session?.requestedPath
|
|
304
365
|
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
366
|
+
/** Whether [path] is the loaded model. Lock-free. */
|
|
367
|
+
internal fun isModelLoaded(path: String): Boolean {
|
|
368
|
+
val current = session ?: return false
|
|
369
|
+
return current.requestedPath == path || current.modelPath == path
|
|
370
|
+
}
|
|
308
371
|
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
} catch (e: Exception) {
|
|
327
|
-
Log.e(TAG, "Error processing audio", e)
|
|
328
|
-
// Attempt stream reset to recover
|
|
329
|
-
try {
|
|
330
|
-
recognizer?.let { rec -> stream?.let { str -> rec.reset(str) } }
|
|
331
|
-
} catch (resetEx: Exception) {
|
|
332
|
-
Log.e(TAG, "Failed to reset stream after error", resetEx)
|
|
333
|
-
}
|
|
334
|
-
}
|
|
372
|
+
/**
|
|
373
|
+
* Finish the current utterance after all PCM queued before this call. Returns the final
|
|
374
|
+
* text once its final result has been delivered to the listener, `""` when nothing was
|
|
375
|
+
* pending, or null when no model is loaded, the model can't finalize early (not a
|
|
376
|
+
* streaming transducer), or the worker didn't answer within [timeoutMs].
|
|
377
|
+
*/
|
|
378
|
+
internal fun finishUtterance(timeoutMs: Long = FINISH_TIMEOUT_MS): String? {
|
|
379
|
+
val current = session ?: return null
|
|
380
|
+
if (current.modelType != ModelType.TRANSDUCER) return null
|
|
381
|
+
return try {
|
|
382
|
+
current.finish().get(timeoutMs, TimeUnit.MILLISECONDS)
|
|
383
|
+
} catch (e: java.util.concurrent.TimeoutException) {
|
|
384
|
+
Bridge.log("STT: finishUtterance timed out after ${timeoutMs}ms")
|
|
385
|
+
null
|
|
386
|
+
} catch (e: Exception) {
|
|
387
|
+
Bridge.log("STT: finishUtterance failed: ${e.message}")
|
|
388
|
+
null
|
|
335
389
|
}
|
|
336
|
-
|
|
337
|
-
Bridge.log("ASR processing thread stopped")
|
|
338
390
|
}
|
|
339
391
|
|
|
340
392
|
/** Convert 16-bit PCM byte data (little-endian) to float array [-1.0, 1.0] */
|
|
341
393
|
private fun toFloatArray(pcmData: ByteArray): FloatArray {
|
|
342
394
|
val count = pcmData.size / 2
|
|
343
395
|
val samples = FloatArray(count)
|
|
344
|
-
|
|
345
396
|
val buffer = ByteBuffer.wrap(pcmData).order(ByteOrder.LITTLE_ENDIAN)
|
|
346
|
-
|
|
347
397
|
for (i in 0 until count) {
|
|
348
398
|
samples[i] = buffer.short / 32768.0f
|
|
349
399
|
}
|
|
350
|
-
|
|
351
400
|
return samples
|
|
352
401
|
}
|
|
353
402
|
|
|
354
|
-
/**
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
403
|
+
/**
|
|
404
|
+
* Format with the loaded model's casing and deliver on the main thread. [onDelivered] runs
|
|
405
|
+
* right after the listener, with the delivered text.
|
|
406
|
+
*/
|
|
407
|
+
private fun deliver(
|
|
408
|
+
from: Session,
|
|
409
|
+
text: String,
|
|
410
|
+
isFinal: Boolean,
|
|
411
|
+
onDelivered: ((String) -> Unit)?,
|
|
412
|
+
) {
|
|
413
|
+
val formatted = SttTextFormatter.format(text, from.casing)
|
|
359
414
|
mainHandler.post {
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
415
|
+
try {
|
|
416
|
+
transcriptListener?.let { listener ->
|
|
417
|
+
if (isFinal) {
|
|
418
|
+
listener.onFinalResult(formatted, from.language)
|
|
419
|
+
} else {
|
|
420
|
+
listener.onPartialResult(formatted, from.language)
|
|
421
|
+
}
|
|
365
422
|
}
|
|
423
|
+
} finally {
|
|
424
|
+
onDelivered?.invoke(formatted)
|
|
366
425
|
}
|
|
367
426
|
}
|
|
368
427
|
}
|
|
369
428
|
|
|
370
429
|
/**
|
|
371
|
-
* Stop transcription
|
|
372
|
-
*
|
|
430
|
+
* Stop transcription. Returns immediately; the model is released on its worker after the
|
|
431
|
+
* audio already queued to it.
|
|
373
432
|
*/
|
|
374
433
|
fun shutdown() {
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
thread.interrupt()
|
|
381
|
-
try {
|
|
382
|
-
thread.join(500)
|
|
383
|
-
} catch (e: InterruptedException) {
|
|
384
|
-
Thread.currentThread().interrupt()
|
|
434
|
+
val previous =
|
|
435
|
+
synchronized(lifecycleLock) {
|
|
436
|
+
val old = session
|
|
437
|
+
session = null
|
|
438
|
+
old
|
|
385
439
|
}
|
|
386
|
-
|
|
387
|
-
workerThread = null
|
|
388
|
-
|
|
389
|
-
try {
|
|
390
|
-
stream?.let {
|
|
391
|
-
Bridge.log("๐งน Cleaning up Sherpa-ONNX stream")
|
|
392
|
-
it.release()
|
|
393
|
-
}
|
|
394
|
-
stream = null
|
|
395
|
-
|
|
396
|
-
recognizer?.let {
|
|
397
|
-
Bridge.log("๐งน Cleaning up Sherpa-ONNX recognizer")
|
|
398
|
-
it.release()
|
|
399
|
-
}
|
|
400
|
-
recognizer = null
|
|
401
|
-
} catch (e: Exception) {
|
|
402
|
-
Log.e(TAG, "Error releasing Sherpa resources", e)
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
// Clear any remaining audio buffers
|
|
406
|
-
val remainingBuffers = pcmQueue.size
|
|
407
|
-
if (remainingBuffers > 0) {
|
|
408
|
-
Bridge.log("๐๏ธ Clearing $remainingBuffers remaining audio buffers")
|
|
409
|
-
}
|
|
410
|
-
pcmQueue.clear()
|
|
411
|
-
|
|
412
|
-
Bridge.log("โ
SherpaOnnxTranscriber shutdown complete")
|
|
440
|
+
previous?.close()
|
|
413
441
|
}
|
|
414
442
|
|
|
415
|
-
/**
|
|
416
|
-
* Restarts the transcriber after a model change. Shuts down existing resources, clears buffers,
|
|
417
|
-
* and reinitializes the recognizer.
|
|
418
|
-
*/
|
|
443
|
+
/** Reload the selected model (for example after a model change). */
|
|
419
444
|
fun restart() {
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
}
|
|
425
|
-
restartRunning = true
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
try {
|
|
429
|
-
Bridge.log("โป๏ธ Restarting SherpaOnnxTranscriber...")
|
|
430
|
-
shutdown()
|
|
431
|
-
// Small delay to ensure cleanup completes
|
|
432
|
-
Thread.sleep(100)
|
|
433
|
-
initialize()
|
|
434
|
-
} catch (e: Exception) {
|
|
435
|
-
Log.e(TAG, "Error during transcriber restart", e)
|
|
436
|
-
} finally {
|
|
437
|
-
synchronized(restartLock) { restartRunning = false }
|
|
438
|
-
}
|
|
445
|
+
initialModelPath = null
|
|
446
|
+
initialModelLanguage = null
|
|
447
|
+
Bridge.log("Restarting SherpaOnnxTranscriber")
|
|
448
|
+
initialize()
|
|
439
449
|
}
|
|
440
450
|
|
|
441
451
|
/** Register a listener to receive partial and final transcription updates */
|
|
@@ -444,29 +454,10 @@ class SherpaOnnxTranscriber(private val context: Context) {
|
|
|
444
454
|
}
|
|
445
455
|
|
|
446
456
|
/** Check if the transcriber was successfully initialized */
|
|
447
|
-
fun isInitialized(): Boolean
|
|
448
|
-
return recognizer != null && stream != null
|
|
449
|
-
}
|
|
457
|
+
fun isInitialized(): Boolean = session != null
|
|
450
458
|
|
|
451
|
-
/** Handle microphone state changes */
|
|
459
|
+
/** Handle microphone state changes: turning off drops queued audio and starts a new utterance. */
|
|
452
460
|
fun microphoneStateChanged(state: Boolean) {
|
|
453
|
-
if (!state)
|
|
454
|
-
// Microphone turned off - clear queue and reset stream
|
|
455
|
-
pcmQueue.clear()
|
|
456
|
-
|
|
457
|
-
recognizer?.let { rec ->
|
|
458
|
-
stream?.let { str ->
|
|
459
|
-
try {
|
|
460
|
-
rec.reset(str)
|
|
461
|
-
lastPartialResult = ""
|
|
462
|
-
Log.d(TAG, "Microphone off โ stream reset")
|
|
463
|
-
} catch (e: Exception) {
|
|
464
|
-
Log.e(TAG, "Error resetting stream on mic off", e)
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
} else {
|
|
469
|
-
Log.d(TAG, "Microphone on")
|
|
470
|
-
}
|
|
461
|
+
if (!state) session?.reset()
|
|
471
462
|
}
|
|
472
463
|
}
|