CallViewModel.kt
15.9 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/*
* Copyright 2023-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.sample
import android.annotation.SuppressLint
import android.app.Application
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Build
import androidx.annotation.OptIn
import androidx.camera.camera2.interop.ExperimentalCamera2Interop
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.viewModelScope
import com.github.ajalt.timberkt.Timber
import io.livekit.android.AudioOptions
import io.livekit.android.LiveKit
import io.livekit.android.LiveKitOverrides
import io.livekit.android.RoomOptions
import io.livekit.android.audio.AudioProcessorOptions
import io.livekit.android.audio.AudioSwitchHandler
import io.livekit.android.e2ee.E2EEOptions
import io.livekit.android.events.RoomEvent
import io.livekit.android.events.collect
import io.livekit.android.room.Room
import io.livekit.android.room.participant.LocalParticipant
import io.livekit.android.room.participant.Participant
import io.livekit.android.room.participant.RemoteParticipant
import io.livekit.android.room.track.CameraPosition
import io.livekit.android.room.track.LocalScreencastVideoTrack
import io.livekit.android.room.track.LocalVideoTrack
import io.livekit.android.room.track.Track
import io.livekit.android.room.track.screencapture.ScreenCaptureParams
import io.livekit.android.room.track.video.CameraCapturerUtils
import io.livekit.android.sample.model.StressTest
import io.livekit.android.sample.service.ForegroundService
import io.livekit.android.util.LKLog
import io.livekit.android.util.flow
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import livekit.org.webrtc.CameraXHelper
@OptIn(ExperimentalCamera2Interop::class)
class CallViewModel(
val url: String,
val token: String,
application: Application,
val e2ee: Boolean = false,
val e2eeKey: String? = "",
val audioProcessorOptions: AudioProcessorOptions? = null,
val stressTest: StressTest = StressTest.None,
) : AndroidViewModel(application) {
private fun getE2EEOptions(): E2EEOptions? {
var e2eeOptions: E2EEOptions? = null
if (e2ee && e2eeKey != null) {
e2eeOptions = E2EEOptions()
}
e2eeOptions?.keyProvider?.setSharedKey(e2eeKey!!)
return e2eeOptions
}
private fun getRoomOptions(): RoomOptions {
return RoomOptions(
adaptiveStream = true,
dynacast = true,
e2eeOptions = getE2EEOptions(),
)
}
val room = LiveKit.create(
appContext = application,
options = getRoomOptions(),
overrides = LiveKitOverrides(
audioOptions = AudioOptions(
audioProcessorOptions = audioProcessorOptions,
),
),
)
private var cameraProvider: CameraCapturerUtils.CameraProvider? = null
val audioHandler = room.audioHandler as AudioSwitchHandler
val participants = room::remoteParticipants.flow
.map { remoteParticipants ->
listOf<Participant>(room.localParticipant) +
remoteParticipants
.keys
.sortedBy { it.value }
.mapNotNull { remoteParticipants[it] }
}
private val mutableError = MutableStateFlow<Throwable?>(null)
val error = mutableError.hide()
private val mutablePrimarySpeaker = MutableStateFlow<Participant?>(null)
val primarySpeaker: StateFlow<Participant?> = mutablePrimarySpeaker
val activeSpeakers = room::activeSpeakers.flow
private var localScreencastTrack: LocalScreencastVideoTrack? = null
// Controls
val micEnabled = room.localParticipant::isMicrophoneEnabled.flow
val cameraEnabled = room.localParticipant::isCameraEnabled.flow
val screenshareEnabled = room.localParticipant::isScreenShareEnabled.flow
private val mutableEnhancedNsEnabled = MutableLiveData(false)
val enhancedNsEnabled = mutableEnhancedNsEnabled.hide()
private val mutableEnableAudioProcessor = MutableLiveData(true)
val enableAudioProcessor = mutableEnableAudioProcessor.hide()
// Emits a string whenever a data message is received.
private val mutableDataReceived = MutableSharedFlow<String>()
val dataReceived = mutableDataReceived
// Whether other participants are allowed to subscribe to this participant's tracks.
private val mutablePermissionAllowed = MutableStateFlow(true)
val permissionAllowed = mutablePermissionAllowed.hide()
init {
CameraXHelper.createCameraProvider(ProcessLifecycleOwner.get()).let {
if (it.isSupported(application)) {
CameraCapturerUtils.registerCameraProvider(it)
cameraProvider = it
}
}
viewModelScope.launch(Dispatchers.Default) {
// Collect any errors.
launch {
error.collect { Timber.e(it) }
}
// Handle any changes in speakers.
launch {
combine(participants, activeSpeakers) { participants, speakers -> participants to speakers }
.collect { (participantsList, speakers) ->
handlePrimarySpeaker(
participantsList,
speakers,
room,
)
}
}
// Handle room events.
launch {
room.events.collect {
when (it) {
is RoomEvent.FailedToConnect -> mutableError.value = it.error
is RoomEvent.DataReceived -> {
val identity = it.participant?.identity ?: "server"
val message = it.data.toString(Charsets.UTF_8)
mutableDataReceived.emit("$identity: $message")
}
else -> {
Timber.e { "Room event: $it" }
}
}
}
}
when (stressTest) {
is StressTest.SwitchRoom -> launch { stressTest.execute() }
is StressTest.None -> connectToRoom()
}
}
// Start a foreground service to keep the call from being interrupted if the
// app goes into the background.
val foregroundServiceIntent = Intent(application, ForegroundService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
application.startForegroundService(foregroundServiceIntent)
} else {
application.startService(foregroundServiceIntent)
}
}
private suspend fun collectTrackStats(event: RoomEvent.TrackSubscribed) {
val pub = event.publication
while (true) {
delay(10000)
if (pub.subscribed) {
val statsReport = pub.track?.getRTCStats() ?: continue
Timber.e { "stats for ${pub.sid}:" }
for (entry in statsReport.statsMap) {
Timber.e { "${entry.key} = ${entry.value}" }
}
}
}
}
fun toggleEnhancedNs(enabled: Boolean? = null) {
if (enabled != null) {
mutableEnableAudioProcessor.postValue(enabled)
room.audioProcessingController.setBypassForCapturePostProcessing(!enabled)
return
}
if (room.audioProcessorIsEnabled) {
if (enableAudioProcessor.value == true) {
room.audioProcessingController.setBypassForCapturePostProcessing(true)
mutableEnableAudioProcessor.postValue(false)
} else {
room.audioProcessingController.setBypassForCapturePostProcessing(false)
mutableEnableAudioProcessor.postValue(true)
}
}
}
private suspend fun connectToRoom() {
try {
room.e2eeOptions = getE2EEOptions()
room.connect(
url = url,
token = token,
)
mutableEnhancedNsEnabled.postValue(room.audioProcessorIsEnabled)
mutableEnableAudioProcessor.postValue(true)
// Create and publish audio/video tracks
val localParticipant = room.localParticipant
localParticipant.setMicrophoneEnabled(true)
localParticipant.setCameraEnabled(true)
// Update the speaker
handlePrimarySpeaker(emptyList(), emptyList(), room)
} catch (e: Throwable) {
mutableError.value = e
}
}
private fun handlePrimarySpeaker(participantsList: List<Participant>, speakers: List<Participant>, room: Room?) {
var speaker = mutablePrimarySpeaker.value
// If speaker is local participant (due to defaults),
// attempt to find another remote speaker to replace with.
if (speaker is LocalParticipant) {
val remoteSpeaker = participantsList
.filterIsInstance<RemoteParticipant>() // Try not to display local participant as speaker.
.firstOrNull()
if (remoteSpeaker != null) {
speaker = remoteSpeaker
}
}
// If previous primary speaker leaves
if (!participantsList.contains(speaker)) {
// Default to another person in room, or local participant.
speaker = participantsList.filterIsInstance<RemoteParticipant>()
.firstOrNull()
?: room?.localParticipant
}
if (speakers.isNotEmpty() && !speakers.contains(speaker)) {
val remoteSpeaker = speakers
.filterIsInstance<RemoteParticipant>() // Try not to display local participant as speaker.
.firstOrNull()
if (remoteSpeaker != null) {
speaker = remoteSpeaker
}
}
mutablePrimarySpeaker.value = speaker
}
/**
* Start a screen capture with the result intent from
* [MediaProjectionManager.createScreenCaptureIntent]
*/
fun startScreenCapture(mediaProjectionPermissionResultData: Intent) {
val localParticipant = room.localParticipant
viewModelScope.launch(Dispatchers.IO) {
localParticipant.setScreenShareEnabled(true, ScreenCaptureParams(mediaProjectionPermissionResultData))
val screencastTrack = localParticipant.getTrackPublication(Track.Source.SCREEN_SHARE)?.track as? LocalScreencastVideoTrack
this@CallViewModel.localScreencastTrack = screencastTrack
}
}
fun stopScreenCapture() {
viewModelScope.launch(Dispatchers.IO) {
localScreencastTrack?.let { localScreencastVideoTrack ->
localScreencastVideoTrack.stop()
room.localParticipant.unpublishTrack(localScreencastVideoTrack)
}
}
}
override fun onCleared() {
super.onCleared()
// Make sure to release any resources associated with LiveKit
room.disconnect()
room.release()
// Clean up foreground service
val application = getApplication<Application>()
val foregroundServiceIntent = Intent(application, ForegroundService::class.java)
application.stopService(foregroundServiceIntent)
cameraProvider?.let {
CameraCapturerUtils.unregisterCameraProvider(it)
}
}
fun setMicEnabled(enabled: Boolean) {
viewModelScope.launch(Dispatchers.IO) {
room.localParticipant.setMicrophoneEnabled(enabled)
}
}
fun setCameraEnabled(enabled: Boolean) {
viewModelScope.launch(Dispatchers.IO) {
room.localParticipant.setCameraEnabled(enabled)
}
}
fun flipCamera() {
val videoTrack = room.localParticipant.getTrackPublication(Track.Source.CAMERA)
?.track as? LocalVideoTrack
?: return
val newPosition = when (videoTrack.options.position) {
CameraPosition.FRONT -> CameraPosition.BACK
CameraPosition.BACK -> CameraPosition.FRONT
else -> null
}
videoTrack.switchCamera(position = newPosition)
}
fun dismissError() {
mutableError.value = null
}
fun sendData(message: String) {
viewModelScope.launch(Dispatchers.IO) {
room.localParticipant.publishData(message.toByteArray(Charsets.UTF_8))
}
}
fun toggleSubscriptionPermissions() {
mutablePermissionAllowed.value = !mutablePermissionAllowed.value
room.localParticipant.setTrackSubscriptionPermissions(mutablePermissionAllowed.value)
}
// Debug functions
fun simulateMigration() {
room.sendSimulateScenario(Room.SimulateScenario.MIGRATION)
}
fun simulateNodeFailure() {
room.sendSimulateScenario(Room.SimulateScenario.NODE_FAILURE)
}
fun simulateServerLeaveFullReconnect() {
room.sendSimulateScenario(Room.SimulateScenario.SERVER_LEAVE_FULL_RECONNECT)
}
fun updateAttribute(key: String, value: String) {
room.localParticipant.updateAttributes(mapOf(key to value))
}
fun reconnect() {
Timber.e { "Reconnecting." }
mutablePrimarySpeaker.value = null
room.disconnect()
viewModelScope.launch(Dispatchers.IO) {
connectToRoom()
}
}
private suspend fun StressTest.SwitchRoom.execute() = coroutineScope {
launch(Dispatchers.Default) {
while (isActive) {
delay(2000)
dumpReferenceTables()
}
}
while (isActive) {
Timber.d { "Stress test -> connect to first room" }
launch(Dispatchers.IO) { quickConnectToRoom(firstToken) }
delay(200)
room.disconnect()
delay(50)
Timber.d { "Stress test -> connect to second room" }
launch(Dispatchers.IO) { quickConnectToRoom(secondToken) }
delay(200)
room.disconnect()
delay(50)
}
}
private suspend fun quickConnectToRoom(token: String) {
try {
room.connect(
url = url,
token = token,
)
} catch (e: Throwable) {
Timber.e(e) { "Failed to connect to room" }
}
}
@SuppressLint("DiscouragedPrivateApi")
private fun dumpReferenceTables() {
try {
val cls = Class.forName("android.os.Debug")
val method = cls.getDeclaredMethod("dumpReferenceTables")
val con = cls.getDeclaredConstructor().apply {
isAccessible = true
}
method.invoke(con.newInstance())
} catch (e: Exception) {
LKLog.e(e) { "Unable to dump reference tables, you can try `adb shell settings put global hidden_api_policy 1`" }
}
}
}
private fun <T> LiveData<T>.hide(): LiveData<T> = this
private fun <T> MutableStateFlow<T>.hide(): StateFlow<T> = this
private fun <T> Flow<T>.hide(): Flow<T> = this