PreconnectAudioBuffer.kt
9.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/*
* Copyright 2025 LiveKit, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.livekit.android.audio
import android.os.SystemClock
import io.livekit.android.audio.PreconnectAudioBuffer.Companion.DEFAULT_TOPIC
import io.livekit.android.audio.PreconnectAudioBuffer.Companion.TIMEOUT
import io.livekit.android.events.RoomEvent
import io.livekit.android.events.collect
import io.livekit.android.room.ConnectionState
import io.livekit.android.room.Room
import io.livekit.android.room.datastream.StreamBytesOptions
import io.livekit.android.room.participant.Participant
import io.livekit.android.util.LKLog
import io.livekit.android.util.flow
import kotlinx.coroutines.cancel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.launch
import livekit.org.webrtc.AudioTrackSink
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import kotlin.math.min
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
internal class PreconnectAudioBuffer
internal constructor(timeout: Duration) : AudioTrackSink {
companion object {
const val DEFAULT_TOPIC = "lk.agent.pre-connect-audio-buffer"
val TIMEOUT = 10.seconds
}
private val outputStreamLock = Any()
private val outputStream by lazy {
ByteArrayOutputStream()
}
private lateinit var collectedBytes: ByteArray
private val tempArray = ByteArray(1024)
private var initialTime = -1L
private var bitsPerSample = 16
private var sampleRate = 48000 // default sampleRate from JavaAudioDeviceModule
private var numberOfChannels = 1 // default channels from JavaAudioDeviceModule
private var isRecording = true
private val timeoutMs = timeout.inWholeMilliseconds
fun startRecording() {
isRecording = true
}
fun stopRecording() {
synchronized(outputStreamLock) {
if (isRecording) {
collectedBytes = outputStream.toByteArray()
isRecording = false
}
}
}
fun clear() {
stopRecording()
collectedBytes = ByteArray(0)
}
override fun onData(
audioData: ByteBuffer,
bitsPerSample: Int,
sampleRate: Int,
numberOfChannels: Int,
numberOfFrames: Int,
absoluteCaptureTimestampMs: Long,
) {
if (!isRecording) {
return
}
if (initialTime == -1L) {
initialTime = SystemClock.elapsedRealtime()
}
this.bitsPerSample = bitsPerSample
this.sampleRate = sampleRate
this.numberOfChannels = numberOfChannels
val currentTime = SystemClock.elapsedRealtime()
// Limit reached, don't buffer any more.
if (currentTime - initialTime > timeoutMs) {
return
}
audioData.rewind()
synchronized(outputStreamLock) {
if (audioData.hasArray()) {
outputStream.write(audioData.array())
} else {
while (audioData.hasRemaining()) {
val readBytes = min(tempArray.size, audioData.remaining())
audioData.get(tempArray, 0, readBytes)
outputStream.write(tempArray)
}
}
}
}
suspend fun sendAudioData(room: Room, trackSid: String?, agentIdentities: List<Participant.Identity>, topic: String = DEFAULT_TOPIC) {
if (agentIdentities.isEmpty()) {
return
}
val audioData = outputStream.toByteArray()
if (audioData.size <= 1024) {
LKLog.i { "Audio data size too small, nothing to send." }
return
}
val sender = room.localParticipant.streamBytes(
StreamBytesOptions(
topic = topic,
attributes = mapOf(
"sampleRate" to "${this.sampleRate}",
"channels" to "${this.numberOfChannels}",
"trackId" to (trackSid ?: ""),
),
destinationIdentities = agentIdentities,
totalSize = audioData.size.toLong(),
name = "preconnect-audio-buffer",
),
)
try {
sender.write(audioData)
sender.close()
} catch (e: Exception) {
sender.close(e.localizedMessage)
}
val samples = audioData.size / (numberOfChannels * bitsPerSample / 8)
val duration = samples.toFloat() / sampleRate
LKLog.i { "Sent ${duration}s (${audioData.size / 1024}KB) of audio data to ${agentIdentities.size} agent(s) (${agentIdentities.joinToString(",")})" }
}
}
/**
* Starts a pre-connect audio recording that will be sent to
* any agents that connect within the [timeout]. This speeds up
* preceived connection times, as the user can start speaking
* prior to actual connection with the agent.
*
* This will automatically be cleaned up when the room disconnects or the operation fails.
*
* Example:
* ```
* try {
* room.withPreconnectAudio {
* // Audio is being captured automatically
* // Perform any other (async) setup here
* val (url, token) = tokenService.fetchConnectionDetails()
* room.connect(
* url = url,
* token = token,
* )
* room.localParticipant.setMicrophoneEnabled(true)
* }
* } catch (e: Throwable) {
* Log.e(TAG, "Error!")
* }
* ```
* @param timeout the timeout for the remote participant to subscribe to the audio track.
* The room connection needs to be established and the remote participant needs to subscribe to the audio track
* before the timeout is reached. Otherwise, the audio stream will be flushed without sending.
* @param topic the topic to send the preconnect audio buffer to. By default this is configured for
* use with LiveKit Agents.
* @param onError The error handler to call when an error occurs while sending the audio buffer.
* @param operation The connection lambda to call with the pre-connect audio.
*
*/
suspend fun <T> Room.withPreconnectAudio(
timeout: Duration = TIMEOUT,
topic: String = DEFAULT_TOPIC,
onError: ((e: Exception) -> Unit)? = null,
operation: suspend () -> T,
) = coroutineScope {
isPrerecording = true
val audioTrack = localParticipant.getOrCreateDefaultAudioTrack()
val preconnectAudioBuffer = PreconnectAudioBuffer(timeout)
LKLog.v { "Starting preconnect audio buffer" }
preconnectAudioBuffer.startRecording()
audioTrack.addSink(preconnectAudioBuffer)
audioTrack.prewarm()
fun stopRecording() {
if (!isPrerecording) {
return
}
LKLog.v { "Stopping preconnect audio buffer" }
audioTrack.removeSink(preconnectAudioBuffer)
preconnectAudioBuffer.stopRecording()
isPrerecording = false
}
// Clear the preconnect audio buffer after the timeout to free memory.
launch {
delay(TIMEOUT)
preconnectAudioBuffer.clear()
}
val sentIdentities = mutableSetOf<Participant.Identity>()
launch {
suspend fun handleSendIfNeeded(participant: Participant) {
coroutineScope inner@{
engine::connectionState.flow
.takeWhile { it != ConnectionState.CONNECTED }
.collect()
val kind = participant.kind
val state = participant.state
val identity = participant.identity
if (sentIdentities.contains(identity) || kind != Participant.Kind.AGENT || state != Participant.State.ACTIVE || identity == null) {
return@inner
}
stopRecording()
launch {
try {
preconnectAudioBuffer.sendAudioData(
room = this@withPreconnectAudio,
trackSid = audioTrack.sid,
agentIdentities = listOf(identity),
topic = topic,
)
sentIdentities.add(identity)
} catch (e: Exception) {
LKLog.w(e) { "Error occurred while sending the audio preconnect data." }
onError?.invoke(e)
}
}
}
}
events.collect { event ->
when (event) {
is RoomEvent.LocalTrackSubscribed -> {
LKLog.i { "Local audio track has been subscribed to, stopping preconnect audio recording." }
stopRecording()
}
is RoomEvent.ParticipantConnected -> {
// agents may connect with ACTIVE state and not trigger a participant state changed.
handleSendIfNeeded(event.participant)
}
is RoomEvent.ParticipantStateChanged -> {
handleSendIfNeeded(event.participant)
}
is RoomEvent.Disconnected -> {
cancel()
}
else -> {
// Intentionally blank.
}
}
}
}
val retValue: T
try {
retValue = operation.invoke()
} catch (e: Exception) {
cancel()
throw e
}
return@coroutineScope retValue
}