@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.
- package/android/build.gradle +6 -36
- package/android/settings.gradle +1 -4
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +61 -3
- package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +27 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +89 -104
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
- 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/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/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 +49 -0
- package/build/BluetoothSdk.types.d.ts.map +1 -1
- package/build/BluetoothSdk.types.js.map +1 -1
- package/build/_private/BluetoothSdkModule.d.ts +31 -4
- package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
- package/build/_private/BluetoothSdkModule.js.map +1 -1
- package/build/generated/releaseMetadata.js +5 -5
- 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 +5 -0
- package/build/index.js.map +1 -1
- package/ios/BluetoothSdkModule.swift +58 -8
- package/ios/MentraBluetoothSDK.podspec +4 -0
- package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
- package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
- package/ios/Source/BluetoothSdkDefaults.swift +1 -1
- package/ios/Source/DeviceManager.swift +30 -12
- package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
- 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/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/DemandDrivenAudioWorkerTests.swift +171 -0
- package/ios/Tests/PcmStreamTests.swift +299 -0
- package/ios/Tests/SpeechActivityTests.swift +238 -0
- package/ios/Tests/SttModelTraitsTests.swift +62 -0
- package/package.json +2 -2
- package/plugin/build/withAndroid.js +7 -11
- package/src/BluetoothSdk.types.ts +49 -0
- package/src/_private/BluetoothSdkModule.ts +33 -4
- package/src/generated/releaseMetadata.ts +5 -5
- package/src/index.ts +7 -0
- 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/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
- /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
- /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
package com.mentra.bluetoothsdk.utils.audio
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import android.media.AudioDeviceCallback
|
|
5
|
+
import android.media.AudioDeviceInfo
|
|
6
|
+
import android.media.AudioManager
|
|
7
|
+
import android.os.Build
|
|
8
|
+
import android.os.Handler
|
|
9
|
+
import android.os.Looper
|
|
10
|
+
import com.mentra.bluetoothsdk.Bridge
|
|
11
|
+
import com.mentra.bluetoothsdk.utils.NativeLog as Log
|
|
12
|
+
import java.util.concurrent.atomic.AtomicLong
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Notices audio route changes for [PcmStreamManager]: the set of output devices changing
|
|
16
|
+
* (glasses or other Bluetooth audio, wired or USB headsets connecting or disconnecting) and a
|
|
17
|
+
* phone call starting or ending. Each change bumps [currentGeneration] and aborts streams that
|
|
18
|
+
* haven't received audio yet.
|
|
19
|
+
*
|
|
20
|
+
* Other audio-mode changes (communication mode toggled for a microphone or by a player) are not
|
|
21
|
+
* route changes: the engine reconfigures audio before playback and on wake-word detections, and
|
|
22
|
+
* counting those would close a prewarmed stream exactly when it is needed. Same rule as iOS,
|
|
23
|
+
* which only reacts when the route's output ports change, a call starts or ends, or the audio
|
|
24
|
+
* session is interrupted.
|
|
25
|
+
*
|
|
26
|
+
* Android 12+ reports mode changes through a listener; on older versions the call state is
|
|
27
|
+
* compared whenever [currentGeneration] is read, which [PcmStreamManager] does before a
|
|
28
|
+
* stream's first write.
|
|
29
|
+
*/
|
|
30
|
+
internal object AudioRouteWatcher {
|
|
31
|
+
private const val TAG = "AudioRouteWatcher"
|
|
32
|
+
|
|
33
|
+
private val generation = AtomicLong(0)
|
|
34
|
+
@Volatile private var audioManager: AudioManager? = null
|
|
35
|
+
private var knownOutputs: Set<String> = emptySet()
|
|
36
|
+
private var inCall = false
|
|
37
|
+
|
|
38
|
+
/** Audio modes that mean a phone call is ringing or active. */
|
|
39
|
+
private fun isCallMode(mode: Int): Boolean =
|
|
40
|
+
mode == AudioManager.MODE_RINGTONE ||
|
|
41
|
+
mode == AudioManager.MODE_IN_CALL ||
|
|
42
|
+
mode == AudioManager.MODE_CALL_SCREENING ||
|
|
43
|
+
mode == AudioManager.MODE_CALL_REDIRECT
|
|
44
|
+
|
|
45
|
+
/** Start listening (idempotent). Without a context (no host), routes are not watched. */
|
|
46
|
+
fun ensureStarted() {
|
|
47
|
+
if (audioManager != null) return
|
|
48
|
+
val context =
|
|
49
|
+
try {
|
|
50
|
+
Bridge.getContext()
|
|
51
|
+
} catch (_: IllegalStateException) {
|
|
52
|
+
return
|
|
53
|
+
}
|
|
54
|
+
start(context)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
@Synchronized
|
|
58
|
+
private fun start(context: Context) {
|
|
59
|
+
if (audioManager != null) return
|
|
60
|
+
val manager = context.getSystemService(AudioManager::class.java) ?: return
|
|
61
|
+
val handler = Handler(Looper.getMainLooper())
|
|
62
|
+
knownOutputs = outputs(manager)
|
|
63
|
+
inCall = isCallMode(manager.mode)
|
|
64
|
+
audioManager = manager
|
|
65
|
+
try {
|
|
66
|
+
manager.registerAudioDeviceCallback(
|
|
67
|
+
object : AudioDeviceCallback() {
|
|
68
|
+
override fun onAudioDevicesAdded(addedDevices: Array<out AudioDeviceInfo>?) =
|
|
69
|
+
checkOutputs()
|
|
70
|
+
|
|
71
|
+
override fun onAudioDevicesRemoved(removedDevices: Array<out AudioDeviceInfo>?) =
|
|
72
|
+
checkOutputs()
|
|
73
|
+
},
|
|
74
|
+
handler,
|
|
75
|
+
)
|
|
76
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
|
77
|
+
manager.addOnModeChangedListener({ command -> handler.post(command) }) { checkCall() }
|
|
78
|
+
}
|
|
79
|
+
} catch (e: Exception) {
|
|
80
|
+
Log.w(TAG, "could not watch audio routes", e)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Route generation; changes on every detected route change. */
|
|
85
|
+
fun currentGeneration(): Long {
|
|
86
|
+
checkCall()
|
|
87
|
+
return generation.get()
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private fun outputs(manager: AudioManager): Set<String> =
|
|
91
|
+
manager.getDevices(AudioManager.GET_DEVICES_OUTPUTS)
|
|
92
|
+
.map { "${it.type}:${it.id}" }
|
|
93
|
+
.toSet()
|
|
94
|
+
|
|
95
|
+
private fun checkOutputs() {
|
|
96
|
+
val manager = audioManager ?: return
|
|
97
|
+
val current = outputs(manager)
|
|
98
|
+
synchronized(this) {
|
|
99
|
+
// Registration replays the connected devices; only a real difference counts.
|
|
100
|
+
if (current == knownOutputs) return
|
|
101
|
+
knownOutputs = current
|
|
102
|
+
}
|
|
103
|
+
changed("output devices changed")
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private fun checkCall() {
|
|
107
|
+
val manager = audioManager ?: return
|
|
108
|
+
val call = isCallMode(manager.mode)
|
|
109
|
+
synchronized(this) {
|
|
110
|
+
if (call == inCall) return
|
|
111
|
+
inCall = call
|
|
112
|
+
}
|
|
113
|
+
changed(if (call) "phone call started" else "phone call ended")
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
private fun changed(reason: String) {
|
|
117
|
+
generation.incrementAndGet()
|
|
118
|
+
PcmStreamManager.abortStreamsWithoutAudio(reason)
|
|
119
|
+
}
|
|
120
|
+
}
|
|
@@ -3,6 +3,7 @@ package com.mentra.bluetoothsdk.utils.audio
|
|
|
3
3
|
import android.media.AudioAttributes
|
|
4
4
|
import android.media.AudioFormat
|
|
5
5
|
import android.media.AudioTrack
|
|
6
|
+
import android.os.Build
|
|
6
7
|
import android.util.Base64
|
|
7
8
|
import com.mentra.bluetoothsdk.utils.NativeLog as Log
|
|
8
9
|
import java.util.ArrayDeque
|
|
@@ -24,12 +25,19 @@ import kotlin.math.max
|
|
|
24
25
|
* track underruns (queue empty), AudioTrack plays silence and playback resumes
|
|
25
26
|
* seamlessly on the next chunk; no stop/start pops.
|
|
26
27
|
*/
|
|
27
|
-
class PcmStreamPlayer
|
|
28
|
+
class PcmStreamPlayer
|
|
29
|
+
@JvmOverloads
|
|
30
|
+
constructor(
|
|
28
31
|
private val streamId: String,
|
|
29
32
|
private val sampleRate: Int,
|
|
30
33
|
channels: Int,
|
|
31
34
|
volume: Float,
|
|
32
35
|
jitterMs: Int = TRACK_BUFFER_MS,
|
|
36
|
+
/**
|
|
37
|
+
* Abort this stream if the audio route changes before its first write (see
|
|
38
|
+
* [PcmStreamManager.abortStreamsWithoutAudio]). False for streams fed natively.
|
|
39
|
+
*/
|
|
40
|
+
internal val abortOnRouteChangeBeforeAudio: Boolean = true,
|
|
33
41
|
) {
|
|
34
42
|
companion object {
|
|
35
43
|
private const val TAG = "PcmStreamPlayer"
|
|
@@ -40,8 +48,8 @@ class PcmStreamPlayer(
|
|
|
40
48
|
/** Hard cap — writes that would exceed this are rejected outright. */
|
|
41
49
|
private const val MAX_BACKLOG_MS = 10_000L
|
|
42
50
|
|
|
43
|
-
/**
|
|
44
|
-
|
|
51
|
+
/** Default playout headroom, which is also how much audio is queued before playback starts. */
|
|
52
|
+
internal const val TRACK_BUFFER_MS = 500
|
|
45
53
|
|
|
46
54
|
/**
|
|
47
55
|
* Floor on the requested headroom.
|
|
@@ -85,8 +93,15 @@ class PcmStreamPlayer(
|
|
|
85
93
|
private var finalPlayedFrames: Long? = null
|
|
86
94
|
private var endedError: String? = null
|
|
87
95
|
|
|
96
|
+
/** False until the first chunk is accepted. Guarded by [lock]. */
|
|
97
|
+
private var receivedAudio = false
|
|
98
|
+
|
|
99
|
+
/** Route generation when the stream opened ([AudioRouteWatcher]). */
|
|
100
|
+
internal val openedRouteGeneration: Long = AudioRouteWatcher.currentGeneration()
|
|
101
|
+
|
|
88
102
|
private val audioTrack: AudioTrack
|
|
89
103
|
private val feeder: Thread
|
|
104
|
+
@Volatile private var playbackStarted = false
|
|
90
105
|
|
|
91
106
|
init {
|
|
92
107
|
val minBuf =
|
|
@@ -119,8 +134,8 @@ class PcmStreamPlayer(
|
|
|
119
134
|
throw IllegalStateException("AudioTrack failed to initialize (rate=$sampleRate)")
|
|
120
135
|
}
|
|
121
136
|
audioTrack.setVolume(volume.coerceIn(0f, 1f))
|
|
122
|
-
|
|
123
|
-
|
|
137
|
+
// An allocated cue may wait silently for a wake. Start only when its
|
|
138
|
+
// first PCM arrives, so prewarming does not activate Bluetooth output.
|
|
124
139
|
feeder =
|
|
125
140
|
Thread({ feedLoop() }, "PcmStreamPlayer-$streamId").apply {
|
|
126
141
|
isDaemon = true
|
|
@@ -144,8 +159,17 @@ class PcmStreamPlayer(
|
|
|
144
159
|
* Append base64-encoded 16-bit LE PCM. Blocks while the backlog is above
|
|
145
160
|
* the backpressure ceiling. Returns the backlog in ms after this chunk.
|
|
146
161
|
*/
|
|
147
|
-
fun write(base64: String): Long
|
|
148
|
-
|
|
162
|
+
fun write(base64: String): Long = writePcm(Base64.decode(base64, Base64.DEFAULT))
|
|
163
|
+
|
|
164
|
+
/** Whether any audio has been written yet. */
|
|
165
|
+
val hasReceivedAudio: Boolean
|
|
166
|
+
get() = lock.withLock { receivedAudio }
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Append raw 16-bit LE PCM. Blocks while the backlog is above the backpressure
|
|
170
|
+
* ceiling. Returns the backlog in ms after this chunk.
|
|
171
|
+
*/
|
|
172
|
+
fun writePcm(bytes: ByteArray): Long {
|
|
149
173
|
require(bytes.isNotEmpty()) { "PCM chunk is empty" }
|
|
150
174
|
require(bytes.size % bytesPerFrame == 0) {
|
|
151
175
|
"PCM chunk length ${bytes.size} is not aligned to a $bytesPerFrame-byte frame"
|
|
@@ -158,6 +182,7 @@ class PcmStreamPlayer(
|
|
|
158
182
|
}
|
|
159
183
|
queue.add(bytes)
|
|
160
184
|
queuedBytes += bytes.size
|
|
185
|
+
receivedAudio = true
|
|
161
186
|
queueChanged.signalAll()
|
|
162
187
|
// Backpressure: hold the caller until the feeder drains below the
|
|
163
188
|
// ceiling. Caller is a background dispatcher, never the UI thread.
|
|
@@ -172,6 +197,10 @@ class PcmStreamPlayer(
|
|
|
172
197
|
/**
|
|
173
198
|
* Drain everything queued, then stop. Blocks until played out. Returns the
|
|
174
199
|
* total played duration in ms.
|
|
200
|
+
*
|
|
201
|
+
* Playback starts once the track's buffer (the jitter headroom) is full. A
|
|
202
|
+
* stream shorter than that is topped up with silence here, so a short sound
|
|
203
|
+
* still plays instead of waiting for audio that will never come.
|
|
175
204
|
*/
|
|
176
205
|
fun close(): Long {
|
|
177
206
|
lock.withLock {
|
|
@@ -182,6 +211,17 @@ class PcmStreamPlayer(
|
|
|
182
211
|
while ((queue.isNotEmpty() || writeInProgress) && endedError == null && !aborted) {
|
|
183
212
|
queueChanged.await()
|
|
184
213
|
}
|
|
214
|
+
if (aborted) return playedMsLocked()
|
|
215
|
+
}
|
|
216
|
+
if (!playbackStarted) {
|
|
217
|
+
// Nothing was ever written (a prewarmed stream closed unused).
|
|
218
|
+
releaseInternals()
|
|
219
|
+
return 0
|
|
220
|
+
}
|
|
221
|
+
try {
|
|
222
|
+
startShortStream()
|
|
223
|
+
} catch (e: Exception) {
|
|
224
|
+
Log.w(TAG, "[$streamId] could not start a short stream", e)
|
|
185
225
|
}
|
|
186
226
|
// ...then for the track to play it out while AudioTrack is still in
|
|
187
227
|
// PLAYSTATE_PLAYING. Calling stop() first flushes pending MODE_STREAM
|
|
@@ -203,18 +243,63 @@ class PcmStreamPlayer(
|
|
|
203
243
|
} finally {
|
|
204
244
|
releaseInternals()
|
|
205
245
|
}
|
|
206
|
-
|
|
246
|
+
// Silence padding a short stream may have played past the real audio.
|
|
247
|
+
return lock.withLock { minOf(playedMsLocked(), framesWritten * 1000L / sampleRate) }
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Write silence up to the track's start threshold when less audio than that was
|
|
252
|
+
* written, so the track starts. Only called from [close] once the feeder is done.
|
|
253
|
+
*/
|
|
254
|
+
private fun startShortStream() {
|
|
255
|
+
val written = lock.withLock { framesWritten }
|
|
256
|
+
val threshold =
|
|
257
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
|
258
|
+
audioTrack.startThresholdInFrames
|
|
259
|
+
} else {
|
|
260
|
+
audioTrack.bufferSizeInFrames
|
|
261
|
+
}.toLong()
|
|
262
|
+
val padFrames = threshold - written
|
|
263
|
+
if (written <= 0 || padFrames <= 0) return
|
|
264
|
+
val silence = ByteArray((padFrames * bytesPerFrame).toInt())
|
|
265
|
+
var off = 0
|
|
266
|
+
while (off < silence.size) {
|
|
267
|
+
val n = audioTrack.write(silence, off, silence.size - off)
|
|
268
|
+
if (n <= 0) break
|
|
269
|
+
off += n
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Abort if no audio has been written yet (for example a prewarmed stream when the
|
|
275
|
+
* audio route changes). Returns whether it aborted.
|
|
276
|
+
*/
|
|
277
|
+
internal fun abortIfNoAudio(): Boolean {
|
|
278
|
+
lock.withLock {
|
|
279
|
+
if (receivedAudio || closing || aborted) return false
|
|
280
|
+
markAbortedLocked()
|
|
281
|
+
}
|
|
282
|
+
stopAndRelease()
|
|
283
|
+
return true
|
|
207
284
|
}
|
|
208
285
|
|
|
209
286
|
/** Stop now, dropping the backlog. Idempotent. */
|
|
210
287
|
fun abort() {
|
|
211
288
|
lock.withLock {
|
|
212
289
|
if (aborted) return
|
|
213
|
-
|
|
214
|
-
queue.clear()
|
|
215
|
-
queuedBytes = 0
|
|
216
|
-
queueChanged.signalAll()
|
|
290
|
+
markAbortedLocked()
|
|
217
291
|
}
|
|
292
|
+
stopAndRelease()
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
private fun markAbortedLocked() {
|
|
296
|
+
aborted = true
|
|
297
|
+
queue.clear()
|
|
298
|
+
queuedBytes = 0
|
|
299
|
+
queueChanged.signalAll()
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
private fun stopAndRelease() {
|
|
218
303
|
try {
|
|
219
304
|
audioTrack.pause()
|
|
220
305
|
audioTrack.flush()
|
|
@@ -251,6 +336,12 @@ class PcmStreamPlayer(
|
|
|
251
336
|
if (queue.isEmpty() && closing) return
|
|
252
337
|
queue.poll()!!.also { writeInProgress = true }
|
|
253
338
|
}
|
|
339
|
+
// The track can be allocated ahead of time without starting an
|
|
340
|
+
// empty output stream or elevating the glasses microphone gate.
|
|
341
|
+
if (!playbackStarted) {
|
|
342
|
+
audioTrack.play()
|
|
343
|
+
playbackStarted = true
|
|
344
|
+
}
|
|
254
345
|
// Blocking write OUTSIDE the lock so write()/abort() stay responsive.
|
|
255
346
|
var off = 0
|
|
256
347
|
while (off < chunk.size) {
|
|
@@ -310,17 +401,32 @@ class PcmStreamPlayer(
|
|
|
310
401
|
* Registry of active [PcmStreamPlayer] sessions, keyed by streamId. All
|
|
311
402
|
* methods are safe to call with unknown ids (write throws, abort no-ops) so
|
|
312
403
|
* races with teardown resolve cleanly.
|
|
404
|
+
*
|
|
405
|
+
* A stream that hasn't received audio yet (for example one prewarmed before a
|
|
406
|
+
* wake word) is aborted when the audio route changes, so its next write fails
|
|
407
|
+
* with "not open" and the caller reopens on the current route instead of
|
|
408
|
+
* playing on a stale one. See [AudioRouteWatcher].
|
|
313
409
|
*/
|
|
314
410
|
object PcmStreamManager {
|
|
411
|
+
private const val TAG = "PcmStreamManager"
|
|
315
412
|
private val players = java.util.concurrent.ConcurrentHashMap<String, PcmStreamPlayer>()
|
|
413
|
+
private val urlPlaybacks = java.util.concurrent.ConcurrentHashMap<String, PcmUrlPlayback>()
|
|
316
414
|
|
|
317
|
-
fun
|
|
415
|
+
private fun validate(streamId: String, sampleRate: Int, channels: Int) {
|
|
318
416
|
require(streamId.isNotBlank()) { "streamId is required" }
|
|
319
417
|
require(sampleRate == 16000 || sampleRate == 24000 || sampleRate == 48000) {
|
|
320
418
|
"unsupported PCM sample rate $sampleRate"
|
|
321
419
|
}
|
|
322
420
|
require(channels == 1) { "only mono PCM is supported" }
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
private fun notOpen(streamId: String) = IllegalStateException("pcm stream $streamId is not open")
|
|
424
|
+
|
|
425
|
+
fun open(streamId: String, sampleRate: Int, channels: Int, volume: Float, jitterMs: Int? = null) {
|
|
426
|
+
validate(streamId, sampleRate, channels)
|
|
427
|
+
AudioRouteWatcher.ensureStarted()
|
|
323
428
|
// Replacing an id is a caller bug, but never leak the old track.
|
|
429
|
+
urlPlaybacks.remove(streamId)?.cancel()
|
|
324
430
|
players.remove(streamId)?.abort()
|
|
325
431
|
players[streamId] =
|
|
326
432
|
if (jitterMs == null) {
|
|
@@ -331,15 +437,25 @@ object PcmStreamManager {
|
|
|
331
437
|
}
|
|
332
438
|
|
|
333
439
|
fun write(streamId: String, base64: String): Long {
|
|
334
|
-
val player =
|
|
335
|
-
|
|
440
|
+
val player = players[streamId] ?: throw notOpen(streamId)
|
|
441
|
+
// A route change since open that no listener reported yet (for example a call
|
|
442
|
+
// starting on Android < 12) still invalidates a stream that has no audio.
|
|
443
|
+
if (player.abortOnRouteChangeBeforeAudio &&
|
|
444
|
+
!player.hasReceivedAudio &&
|
|
445
|
+
AudioRouteWatcher.currentGeneration() != player.openedRouteGeneration &&
|
|
446
|
+
player.abortIfNoAudio()
|
|
447
|
+
) {
|
|
448
|
+
players.remove(streamId, player)
|
|
449
|
+
Log.d(TAG, "[$streamId] aborted before its first write: the audio route changed")
|
|
450
|
+
throw notOpen(streamId)
|
|
451
|
+
}
|
|
336
452
|
return player.write(base64)
|
|
337
453
|
}
|
|
338
454
|
|
|
339
455
|
fun close(streamId: String): Long {
|
|
340
456
|
val player =
|
|
341
457
|
players[streamId]
|
|
342
|
-
?: throw
|
|
458
|
+
?: throw notOpen(streamId)
|
|
343
459
|
return try {
|
|
344
460
|
player.close()
|
|
345
461
|
} finally {
|
|
@@ -351,12 +467,61 @@ object PcmStreamManager {
|
|
|
351
467
|
}
|
|
352
468
|
|
|
353
469
|
fun abort(streamId: String) {
|
|
470
|
+
urlPlaybacks.remove(streamId)?.cancel()
|
|
354
471
|
players.remove(streamId)?.abort()
|
|
355
472
|
}
|
|
356
473
|
|
|
357
474
|
fun abortAll() {
|
|
475
|
+
val playbacks = urlPlaybacks.values.toList()
|
|
476
|
+
urlPlaybacks.clear()
|
|
477
|
+
playbacks.forEach { it.cancel() }
|
|
358
478
|
val active = players.values.toList()
|
|
359
479
|
players.clear()
|
|
360
480
|
active.forEach { it.abort() }
|
|
361
481
|
}
|
|
482
|
+
|
|
483
|
+
/** Abort every stream that hasn't received audio yet. Called on an audio route change. */
|
|
484
|
+
internal fun abortStreamsWithoutAudio(reason: String) {
|
|
485
|
+
for ((streamId, player) in players) {
|
|
486
|
+
if (player.abortOnRouteChangeBeforeAudio && player.abortIfNoAudio()) {
|
|
487
|
+
players.remove(streamId, player)
|
|
488
|
+
Log.d(TAG, "[$streamId] aborted before its first write: $reason")
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* Fetch [url] and play its body (raw 16-bit LE mono PCM at [sampleRate]) as it
|
|
495
|
+
* arrives, through a [PcmStreamPlayer] registered under [streamId]. Blocks the
|
|
496
|
+
* calling (background) thread until the whole body has played and returns the
|
|
497
|
+
* played duration in ms. Throws [PcmUrlPlaybackException]: code "aborted" after
|
|
498
|
+
* [abort], "http_error" on a non-2xx response, "unsupported_format" for
|
|
499
|
+
* compressed audio, "network_error" when the connection fails (audio already
|
|
500
|
+
* received still plays out first).
|
|
501
|
+
*/
|
|
502
|
+
fun playUrl(streamId: String, url: String, sampleRate: Int, volume: Float, jitterMs: Int?): Long {
|
|
503
|
+
validate(streamId, sampleRate, 1)
|
|
504
|
+
val playback =
|
|
505
|
+
PcmUrlPlayback(url) { player ->
|
|
506
|
+
// Register so pcmStreamAbort(streamId) and teardown reach the player.
|
|
507
|
+
players.put(streamId, player)?.abort()
|
|
508
|
+
}
|
|
509
|
+
urlPlaybacks.put(streamId, playback)?.cancel()
|
|
510
|
+
players.remove(streamId)?.abort()
|
|
511
|
+
try {
|
|
512
|
+
return playback.run {
|
|
513
|
+
PcmStreamPlayer(
|
|
514
|
+
streamId,
|
|
515
|
+
sampleRate,
|
|
516
|
+
1,
|
|
517
|
+
volume,
|
|
518
|
+
jitterMs ?: PcmStreamPlayer.TRACK_BUFFER_MS,
|
|
519
|
+
abortOnRouteChangeBeforeAudio = false,
|
|
520
|
+
)
|
|
521
|
+
}
|
|
522
|
+
} finally {
|
|
523
|
+
urlPlaybacks.remove(streamId, playback)
|
|
524
|
+
playback.player?.let { players.remove(streamId, it) }
|
|
525
|
+
}
|
|
526
|
+
}
|
|
362
527
|
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
package com.mentra.bluetoothsdk.utils.audio
|
|
2
|
+
|
|
3
|
+
import com.mentra.bluetoothsdk.utils.NativeLog as Log
|
|
4
|
+
import java.io.IOException
|
|
5
|
+
import java.io.InputStream
|
|
6
|
+
import java.util.concurrent.TimeUnit
|
|
7
|
+
import okhttp3.Call
|
|
8
|
+
import okhttp3.OkHttpClient
|
|
9
|
+
import okhttp3.Request
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A URL playback failure. [code] is "aborted", "http_error" (non-2xx), "unsupported_format"
|
|
13
|
+
* (compressed audio instead of raw PCM) or "network_error".
|
|
14
|
+
*/
|
|
15
|
+
class PcmUrlPlaybackException(val code: String, message: String, cause: Throwable? = null) :
|
|
16
|
+
Exception(message, cause)
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Re-frames a byte stream into whole 16-bit samples: a trailing odd byte is carried over
|
|
20
|
+
* to the next chunk instead of being written (or dropped) mid-sample.
|
|
21
|
+
*/
|
|
22
|
+
internal class Pcm16ByteCarry {
|
|
23
|
+
private var pending = -1
|
|
24
|
+
|
|
25
|
+
/** Whether a byte is waiting for its pair. */
|
|
26
|
+
val hasPendingByte: Boolean
|
|
27
|
+
get() = pending >= 0
|
|
28
|
+
|
|
29
|
+
/** Whole samples from the carried byte plus `buffer[0, length)`, or null if none. */
|
|
30
|
+
fun push(buffer: ByteArray, length: Int): ByteArray? {
|
|
31
|
+
if (length <= 0) return null
|
|
32
|
+
val carried = if (pending >= 0) 1 else 0
|
|
33
|
+
val total = carried + length
|
|
34
|
+
val even = total - (total % 2)
|
|
35
|
+
if (even == 0) {
|
|
36
|
+
pending = buffer[0].toInt() and 0xff
|
|
37
|
+
return null
|
|
38
|
+
}
|
|
39
|
+
val out = ByteArray(even)
|
|
40
|
+
var start = 0
|
|
41
|
+
if (carried == 1) {
|
|
42
|
+
out[0] = pending.toByte()
|
|
43
|
+
start = 1
|
|
44
|
+
}
|
|
45
|
+
System.arraycopy(buffer, 0, out, start, even - start)
|
|
46
|
+
pending = if (total % 2 == 1) buffer[length - 1].toInt() and 0xff else -1
|
|
47
|
+
return out
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* One `pcmStreamPlayUrl` request: an HTTP GET whose body is raw s16le mono PCM, written
|
|
53
|
+
* into a [PcmStreamPlayer] as it arrives. Audio never crosses into JavaScript.
|
|
54
|
+
*/
|
|
55
|
+
internal class PcmUrlPlayback(
|
|
56
|
+
private val url: String,
|
|
57
|
+
private val onPlayer: (PcmStreamPlayer) -> Unit,
|
|
58
|
+
) {
|
|
59
|
+
companion object {
|
|
60
|
+
private const val TAG = "PcmUrlPlayback"
|
|
61
|
+
private const val READ_BUFFER_BYTES = 8 * 1024
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Compressed audio would play as noise. Same list as iOS; anything else (audio/L16,
|
|
65
|
+
* audio/pcm, application/octet-stream, no type) is played as raw PCM.
|
|
66
|
+
*/
|
|
67
|
+
private val COMPRESSED_CONTENT_TYPES =
|
|
68
|
+
setOf("audio/mpeg", "audio/mp3", "audio/aac", "audio/ogg", "audio/opus", "audio/webm")
|
|
69
|
+
|
|
70
|
+
/** The media type of a Content-Type header, lower-cased and without parameters. */
|
|
71
|
+
internal fun mediaType(contentType: String?): String? =
|
|
72
|
+
contentType?.substringBefore(';')?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }
|
|
73
|
+
|
|
74
|
+
internal fun isCompressedAudio(contentType: String?): Boolean =
|
|
75
|
+
mediaType(contentType) in COMPRESSED_CONTENT_TYPES
|
|
76
|
+
|
|
77
|
+
private val client: OkHttpClient by lazy {
|
|
78
|
+
OkHttpClient.Builder()
|
|
79
|
+
.connectTimeout(15, TimeUnit.SECONDS)
|
|
80
|
+
.readTimeout(20, TimeUnit.SECONDS)
|
|
81
|
+
.build()
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Copy [input] to [write] in whole samples. Returns the bytes written. */
|
|
85
|
+
internal fun pump(input: InputStream, write: (ByteArray) -> Unit): Long {
|
|
86
|
+
val carry = Pcm16ByteCarry()
|
|
87
|
+
val buffer = ByteArray(READ_BUFFER_BYTES)
|
|
88
|
+
var written = 0L
|
|
89
|
+
while (true) {
|
|
90
|
+
val n = input.read(buffer)
|
|
91
|
+
if (n < 0) break
|
|
92
|
+
val chunk = carry.push(buffer, n) ?: continue
|
|
93
|
+
write(chunk)
|
|
94
|
+
written += chunk.size
|
|
95
|
+
}
|
|
96
|
+
if (carry.hasPendingByte) Log.w(TAG, "response ended mid-sample; dropped 1 byte")
|
|
97
|
+
return written
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
@Volatile private var cancelled = false
|
|
102
|
+
@Volatile private var call: Call? = null
|
|
103
|
+
|
|
104
|
+
@Volatile
|
|
105
|
+
var player: PcmStreamPlayer? = null
|
|
106
|
+
private set
|
|
107
|
+
|
|
108
|
+
/** Stop the download and the audio. [run] then throws code "aborted". */
|
|
109
|
+
fun cancel() {
|
|
110
|
+
cancelled = true
|
|
111
|
+
call?.cancel()
|
|
112
|
+
player?.abort()
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private fun aborted() = PcmUrlPlaybackException("aborted", "aborted")
|
|
116
|
+
|
|
117
|
+
private fun downloadFailed(error: Exception) =
|
|
118
|
+
PcmUrlPlaybackException(
|
|
119
|
+
"network_error",
|
|
120
|
+
"PCM stream download failed: ${error.message ?: error.javaClass.simpleName}",
|
|
121
|
+
error,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Download and play. Blocks until the body has played; returns the played ms.
|
|
126
|
+
* [makePlayer] runs once the response headers arrived with a 2xx status.
|
|
127
|
+
*/
|
|
128
|
+
fun run(makePlayer: () -> PcmStreamPlayer): Long {
|
|
129
|
+
if (cancelled) throw aborted()
|
|
130
|
+
val request = Request.Builder().url(url).get().build()
|
|
131
|
+
val pending = client.newCall(request)
|
|
132
|
+
call = pending
|
|
133
|
+
if (cancelled) throw aborted()
|
|
134
|
+
val response =
|
|
135
|
+
try {
|
|
136
|
+
pending.execute()
|
|
137
|
+
} catch (e: IOException) {
|
|
138
|
+
if (cancelled) throw aborted()
|
|
139
|
+
throw downloadFailed(e)
|
|
140
|
+
}
|
|
141
|
+
response.use {
|
|
142
|
+
if (!response.isSuccessful) {
|
|
143
|
+
throw PcmUrlPlaybackException(
|
|
144
|
+
"http_error",
|
|
145
|
+
"PCM stream request failed with HTTP ${response.code}",
|
|
146
|
+
)
|
|
147
|
+
}
|
|
148
|
+
val contentType = response.header("Content-Type")
|
|
149
|
+
if (isCompressedAudio(contentType)) {
|
|
150
|
+
throw PcmUrlPlaybackException(
|
|
151
|
+
"unsupported_format",
|
|
152
|
+
"PCM stream URL returned ${mediaType(contentType)}, not raw PCM",
|
|
153
|
+
)
|
|
154
|
+
}
|
|
155
|
+
val body = response.body ?: throw PcmUrlPlaybackException("http_error", "empty response body")
|
|
156
|
+
val output = makePlayer()
|
|
157
|
+
player = output
|
|
158
|
+
onPlayer(output)
|
|
159
|
+
if (cancelled) {
|
|
160
|
+
output.abort()
|
|
161
|
+
throw aborted()
|
|
162
|
+
}
|
|
163
|
+
var failure: Exception? = null
|
|
164
|
+
try {
|
|
165
|
+
pump(body.byteStream()) { chunk -> output.writePcm(chunk) }
|
|
166
|
+
} catch (e: Exception) {
|
|
167
|
+
failure = e
|
|
168
|
+
}
|
|
169
|
+
if (cancelled) throw aborted()
|
|
170
|
+
// Play out what arrived, including after a dropped connection.
|
|
171
|
+
val playedMs = output.close()
|
|
172
|
+
if (cancelled) throw aborted()
|
|
173
|
+
failure?.let { error -> throw downloadFailed(error) }
|
|
174
|
+
return playedMs
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|