CallActivity.kt
19.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
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
package io.livekit.android.composesample
import android.app.Activity
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import android.os.Parcelable
import android.view.WindowManager
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import androidx.lifecycle.lifecycleScope
import io.livekit.android.audio.AudioSwitchHandler
import io.livekit.android.composesample.ui.DebugMenuDialog
import io.livekit.android.composesample.ui.SelectAudioDeviceDialog
import io.livekit.android.composesample.ui.theme.AppTheme
import io.livekit.android.room.Room
import io.livekit.android.room.participant.Participant
import io.livekit.android.sample.CallViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.parcelize.Parcelize
class CallActivity : AppCompatActivity() {
private val viewModel: CallViewModel by viewModelByFactory {
val args = intent.getParcelableExtra<BundleArgs>(KEY_ARGS)
?: throw NullPointerException("args is null!")
CallViewModel(args.url, args.token, application)
}
private val screenCaptureIntentLauncher =
registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
val resultCode = result.resultCode
val data = result.data
if (resultCode != Activity.RESULT_OK || data == null) {
return@registerForActivityResult
}
viewModel.startScreenCapture(data)
}
@OptIn(ExperimentalMaterialApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// Setup compose view.
setContent {
val room = viewModel.room
val participants by viewModel.participants.collectAsState(initial = emptyList())
val primarySpeaker by viewModel.primarySpeaker.collectAsState()
val activeSpeakers by viewModel.activeSpeakers.collectAsState(initial = emptyList())
val micEnabled by viewModel.micEnabled.observeAsState(true)
val videoEnabled by viewModel.cameraEnabled.observeAsState(true)
val flipButtonEnabled by viewModel.flipButtonVideoEnabled.observeAsState(true)
val screencastEnabled by viewModel.screenshareEnabled.observeAsState(false)
val permissionAllowed by viewModel.permissionAllowed.collectAsState()
Content(
room,
participants,
primarySpeaker,
activeSpeakers,
micEnabled,
videoEnabled,
flipButtonEnabled,
screencastEnabled,
audioSwitchHandler = viewModel.audioHandler,
permissionAllowed = permissionAllowed,
onExitClick = { finish() },
onSendMessage = { viewModel.sendData(it) },
onSimulateMigration = { viewModel.simulateMigration() },
fullReconnect = { viewModel.reconnect() },
)
}
}
override fun onResume() {
super.onResume()
lifecycleScope.launchWhenResumed {
viewModel.error.collect {
if (it != null) {
Toast.makeText(this@CallActivity, "Error: $it", Toast.LENGTH_LONG).show()
viewModel.dismissError()
}
}
}
lifecycleScope.launchWhenResumed {
viewModel.dataReceived.collect {
Toast.makeText(this@CallActivity, "Data received: $it", Toast.LENGTH_LONG).show()
}
}
}
private fun requestMediaProjection() {
val mediaProjectionManager =
getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
screenCaptureIntentLauncher.launch(mediaProjectionManager.createScreenCaptureIntent())
}
val previewParticipant = Participant("asdf", "asdf", Dispatchers.Main)
@ExperimentalMaterialApi
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun Content(
room: Room? = null,
participants: List<Participant> = listOf(previewParticipant),
primarySpeaker: Participant? = previewParticipant,
activeSpeakers: List<Participant> = listOf(previewParticipant),
micEnabled: Boolean = true,
videoEnabled: Boolean = true,
flipButtonEnabled: Boolean = true,
screencastEnabled: Boolean = false,
permissionAllowed: Boolean = true,
audioSwitchHandler: AudioSwitchHandler? = null,
onExitClick: () -> Unit = {},
error: Throwable? = null,
onSnackbarDismiss: () -> Unit = {},
onSendMessage: (String) -> Unit = {},
onSimulateMigration: () -> Unit = {},
fullReconnect: () -> Unit = {},
) {
AppTheme(darkTheme = true) {
ConstraintLayout(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colors.background)
) {
val (speakerView, audienceRow, buttonBar) = createRefs()
// Primary speaker view
Surface(modifier = Modifier.constrainAs(speakerView) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
bottom.linkTo(audienceRow.top)
width = Dimension.fillToConstraints
height = Dimension.fillToConstraints
}) {
if (room != null && primarySpeaker != null) {
ParticipantItem(
room = room,
participant = primarySpeaker,
isSpeaking = activeSpeakers.contains(primarySpeaker)
)
}
}
// Audience row to display all participants.
LazyRow(
modifier = Modifier
.constrainAs(audienceRow) {
top.linkTo(speakerView.bottom)
bottom.linkTo(buttonBar.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
width = Dimension.fillToConstraints
height = Dimension.value(120.dp)
}
) {
if (room != null) {
items(
count = participants.size,
key = { index -> participants[index].sid }
) { index ->
ParticipantItem(
room = room,
participant = participants[index],
isSpeaking = activeSpeakers.contains(participants[index]),
modifier = Modifier
.fillMaxHeight()
.aspectRatio(1.0f, true)
)
}
}
}
// Control bar for any switches such as mic/camera enable/disable.
Column(
modifier = Modifier
.padding(top = 10.dp, bottom = 20.dp)
.fillMaxWidth()
.constrainAs(buttonBar) {
bottom.linkTo(parent.bottom)
width = Dimension.fillToConstraints
height = Dimension.wrapContent
},
verticalArrangement = Arrangement.SpaceEvenly,
horizontalAlignment = Alignment.CenterHorizontally
) {
val controlSize = 40.dp
val controlPadding = 4.dp
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.Bottom,
) {
Surface(
onClick = { viewModel.setMicEnabled(!micEnabled) },
modifier = Modifier
.size(controlSize)
.padding(controlPadding)
) {
val resource =
if (micEnabled) R.drawable.outline_mic_24 else R.drawable.outline_mic_off_24
Icon(
painterResource(id = resource),
contentDescription = "Mic",
tint = Color.White,
)
}
Surface(
onClick = { viewModel.setCameraEnabled(!videoEnabled) },
modifier = Modifier
.size(controlSize)
.padding(controlPadding)
) {
val resource =
if (videoEnabled) R.drawable.outline_videocam_24 else R.drawable.outline_videocam_off_24
Icon(
painterResource(id = resource),
contentDescription = "Video",
tint = Color.White,
)
}
Surface(
onClick = { viewModel.flipCamera() },
modifier = Modifier
.size(controlSize)
.padding(controlPadding)
) {
Icon(
painterResource(id = R.drawable.outline_flip_camera_android_24),
contentDescription = "Flip Camera",
tint = Color.White,
)
}
Surface(
onClick = {
if (!screencastEnabled) {
requestMediaProjection()
} else {
viewModel.stopScreenCapture()
}
},
modifier = Modifier
.size(controlSize)
.padding(controlPadding)
) {
val resource =
if (screencastEnabled) R.drawable.baseline_cast_connected_24 else R.drawable.baseline_cast_24
Icon(
painterResource(id = resource),
contentDescription = "Flip Camera",
tint = Color.White,
)
}
var showMessageDialog by remember { mutableStateOf(false) }
var messageToSend by remember { mutableStateOf("") }
Surface(
onClick = { showMessageDialog = true },
modifier = Modifier
.size(controlSize)
.padding(controlPadding)
) {
Icon(
painterResource(id = R.drawable.baseline_chat_24),
contentDescription = "Send Message",
tint = Color.White,
)
}
if (showMessageDialog) {
AlertDialog(
onDismissRequest = {
showMessageDialog = false
messageToSend = ""
},
title = {
Text(text = "Send Message")
},
text = {
OutlinedTextField(
value = messageToSend,
onValueChange = { messageToSend = it },
label = { Text("Message") },
modifier = Modifier.fillMaxWidth(),
)
},
confirmButton = {
Button(
onClick = {
onSendMessage(messageToSend)
showMessageDialog = false
messageToSend = ""
}
) { Text("Send") }
},
dismissButton = {
Button(
onClick = {
showMessageDialog = false
messageToSend = ""
}
) { Text("Cancel") }
},
backgroundColor = Color.Black,
)
}
Surface(
onClick = { onExitClick() },
modifier = Modifier
.size(controlSize)
.padding(controlPadding)
) {
Icon(
painterResource(id = R.drawable.ic_baseline_cancel_24),
contentDescription = "Flip Camera",
tint = Color.White,
)
}
}
Spacer(modifier = Modifier.height(10.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.Bottom,
) {
var showAudioDeviceDialog by remember { mutableStateOf(false) }
Surface(
onClick = { showAudioDeviceDialog = true },
modifier = Modifier
.size(controlSize)
.padding(controlPadding)
) {
val resource = R.drawable.volume_up_48px
Icon(
painterResource(id = resource),
contentDescription = "Select Audio Device",
tint = Color.White,
)
}
if (showAudioDeviceDialog) {
SelectAudioDeviceDialog(
onDismissRequest = { showAudioDeviceDialog = false },
selectDevice = { audioSwitchHandler?.selectDevice(it) },
currentDevice = audioSwitchHandler?.selectedAudioDevice,
availableDevices = audioSwitchHandler?.availableAudioDevices ?: emptyList()
)
}
Surface(
onClick = { viewModel.toggleSubscriptionPermissions() },
modifier = Modifier
.size(controlSize)
.padding(controlPadding)
) {
val resource =
if (permissionAllowed) R.drawable.account_cancel_outline else R.drawable.account_cancel
Icon(
painterResource(id = resource),
contentDescription = "Permissions",
tint = Color.White,
)
}
var showDebugDialog by remember { mutableStateOf(false) }
Surface(
onClick = { showDebugDialog = true },
modifier = Modifier
.size(controlSize)
.padding(controlPadding)
) {
val resource = R.drawable.dots_horizontal_circle_outline
Icon(
painterResource(id = resource),
contentDescription = "Permissions",
tint = Color.White,
)
}
if (showDebugDialog) {
DebugMenuDialog(
onDismissRequest = { showDebugDialog = false },
simulateMigration = { onSimulateMigration() },
fullReconnect = { fullReconnect() },
)
}
}
}
// Snack bar for errors
val scaffoldState = rememberScaffoldState()
val scope = rememberCoroutineScope()
if (error != null) {
Scaffold(
scaffoldState = scaffoldState,
floatingActionButton = {
ExtendedFloatingActionButton(
text = { Text("Show snackbar") },
onClick = {
// show snackbar as a suspend function
scope.launch {
scaffoldState.snackbarHostState.showSnackbar(error?.toString() ?: "")
}
}
)
},
content = { innerPadding ->
Text(
text = "Body content",
modifier = Modifier
.padding(innerPadding)
.fillMaxSize()
.wrapContentSize()
)
}
)
}
}
}
}
companion object {
const val KEY_ARGS = "args"
}
@Parcelize
data class BundleArgs(val url: String, val token: String) : Parcelable
}