Welcome to mirror list, hosted at ThFree Co, Russian Federation.

webrtc.js « webrtc « utils « src - github.com/nextcloud/spreed.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e06bba446f2de380d09c149c06c03f4f5343e66c (plain)
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
/**
 * @copyright Copyright (c) 2019 Daniel Calviño Sánchez <danxuliu@gmail.com>
 *
 * @copyright Copyright (c) 2019 Ivan Sein <ivan@nextcloud.com>
 *
 * @copyright Copyright (c) 2019 Joachim Bauch <bauch@struktur.de>
 *
 * @copyright Copyright (c) 2019 Joas Schilling <coding@schilljs.com>
 *
 * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
 *
 * @author Ivan Sein <ivan@nextcloud.com>
 *
 * @author Joachim Bauch <bauch@struktur.de>
 *
 * @author Joas Schilling <coding@schilljs.com>
 *
 * @license AGPL-3.0-or-later
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

import SimpleWebRTC from './simplewebrtc/simplewebrtc'
import { PARTICIPANT } from '../../constants.js'
import store from '../../store/index.js'
import {
	showError,
	TOAST_PERMANENT_TIMEOUT,
	TOAST_DEFAULT_TIMEOUT,
} from '@nextcloud/dialogs'
import { Sounds } from '../sounds.js'

let webrtc
const spreedPeerConnectionTable = []

let previousUsersInRoom = []
let usersInCallMapping = {}
let ownPeer = null
let ownScreenPeer = null
let selfInCall = PARTICIPANT.CALL_FLAG.DISCONNECTED
// Special variable to know when the local user explicitly joined and left the
// call; this is needed to know when the user was kicked out from the call by a
// moderator.
let localUserInCall = false
const delayedConnectionToPeer = []
let callParticipantCollection = null
let localCallParticipantModel = null
let showedTURNWarning = false
let sendCurrentStateWithRepetitionTimeout = null
let startedWithMedia

/**
 * @param {Array} a Source object
 * @param {Array} b Object to find all items in
 */
function arrayDiff(a, b) {
	return a.filter(function(i) {
		return b.indexOf(i) < 0
	})
}

/**
 * @param {object} signaling The signaling object
 * @param {string} sessionId The user's sessionId
 */
function createScreensharingPeer(signaling, sessionId) {
	const currentSessionId = signaling.getSessionId()
	const useMcu = signaling.hasFeature('mcu')

	if (useMcu && !webrtc.webrtc.getPeers(currentSessionId, 'screen').length) {
		if (ownScreenPeer) {
			ownScreenPeer.end()
		}

		// Create own publishing stream.
		ownScreenPeer = webrtc.webrtc.createPeer({
			id: currentSessionId,
			type: 'screen',
			sharemyscreen: true,
			enableDataChannels: false,
			enableSimulcast: signaling.hasFeature('simulcast'),
			receiveMedia: {
				offerToReceiveAudio: 0,
				offerToReceiveVideo: 0,
			},
			broadcaster: currentSessionId,
		})
		webrtc.emit('createdPeer', ownScreenPeer)
		ownScreenPeer.start()

		localCallParticipantModel.setScreenPeer(ownScreenPeer)
	}

	if (sessionId === currentSessionId) {
		return
	}

	if (useMcu) {
		// TODO(jojo): Already create peer object to avoid duplicate offers.
		// TODO(jojo): We should use "requestOffer" as with regular
		// audio/video peers. Not possible right now as there is no way
		// for clients to know that screensharing is active and an offer
		// from the MCU should be requested.
		signaling.sendOffer(sessionId, 'screen')
	} else if (!useMcu) {
		const screenPeers = webrtc.webrtc.getPeers(sessionId, 'screen')
		const screenPeerSharedTo = screenPeers.find(function(screenPeer) {
			return screenPeer.sharemyscreen === true
		})
		if (!screenPeerSharedTo) {
			const peer = webrtc.webrtc.createPeer({
				id: sessionId,
				type: 'screen',
				sharemyscreen: true,
				enableDataChannels: false,
				enableSimulcast: signaling.hasFeature('simulcast'),
				receiveMedia: {
					offerToReceiveAudio: 0,
					offerToReceiveVideo: 0,
				},
				broadcaster: currentSessionId,
			})
			webrtc.emit('createdPeer', peer)
			peer.start()
		}
	}
}

/**
 * @param {object} signaling The signaling object
 */
function checkStartPublishOwnPeer(signaling) {
	'use strict'
	const currentSessionId = signaling.getSessionId()
	if (!webrtc.webrtc.localStreams.length || webrtc.webrtc.getPeers(currentSessionId, 'video').length) {
		// No media yet or already publishing.
		return
	}

	if (ownPeer) {
		if (delayedConnectionToPeer[ownPeer.id]) {
			clearInterval(delayedConnectionToPeer[ownPeer.id])
			delete delayedConnectionToPeer[ownPeer.id]
		}
		ownPeer.end()

		// The peer does not need to be nullified in the
		// localCallParticipantModel as a new peer will be immediately set by
		// createPeer() below.
	}

	const createPeer = function() {
		// Create own publishing stream.
		ownPeer = webrtc.webrtc.createPeer({
			id: currentSessionId,
			type: 'video',
			enableDataChannels: true,
			enableSimulcast: signaling.hasFeature('simulcast'),
			receiveMedia: {
				offerToReceiveAudio: 0,
				offerToReceiveVideo: 0,
			},
			sendVideoIfAvailable: signaling.getSendVideoIfAvailable(),
		})
		webrtc.emit('createdPeer', ownPeer)
		ownPeer.start()

		localCallParticipantModel.setPeer(ownPeer)
	}

	createPeer()

	delayedConnectionToPeer[ownPeer.id] = setInterval(function() {
		// New offers are periodically sent until a connection is established.
		// As an offer can not be sent again from an existing peer it must be
		// removed and a new one must be created from scratch.
		if (ownPeer) {
			ownPeer.end()
		}

		console.debug('No answer received for own peer, sending offer again')
		createPeer()
	}, 10000)
}

/**
 *
 */
function sendCurrentMediaState() {
	if (!webrtc.webrtc.isVideoEnabled()) {
		webrtc.webrtc.emit('videoOff')
	} else {
		webrtc.webrtc.emit('videoOn')
	}
	if (!webrtc.webrtc.isAudioEnabled()) {
		webrtc.webrtc.emit('audioOff')
	} else {
		webrtc.webrtc.emit('audioOn')
	}
}

// TODO The participant name should be got from the participant list, but it is
// not currently possible to associate a Nextcloud ID with a standalone
// signaling ID for guests.
/**
 *
 */
function sendCurrentNick() {
	webrtc.webrtc.emit('nickChanged', store.getters.getDisplayName())
}

/**
 * @param {number} timeout Time until we give up retrying
 */
function sendCurrentStateWithRepetition(timeout) {
	if (!timeout) {
		timeout = 0

		clearTimeout(sendCurrentStateWithRepetitionTimeout)
	}

	sendCurrentStateWithRepetitionTimeout = setTimeout(function() {
		sendCurrentMediaState()
		sendCurrentNick()

		if (!timeout) {
			timeout = 1000
		} else {
			timeout *= 2
		}

		if (timeout > 16000) {
			sendCurrentStateWithRepetitionTimeout = null
			return
		}

		sendCurrentStateWithRepetition(timeout)
	}, timeout)
}

/**
 * @param {object} user The user to check
 * @return {boolean} True if the user has an audio or video stream
 */
function userHasStreams(user) {
	let flags = user
	if (Object.prototype.hasOwnProperty.call(flags, 'inCall')) {
		flags = flags.inCall
	}
	flags = flags || PARTICIPANT.CALL_FLAG.DISCONNECTED
	const REQUIRED_FLAGS = PARTICIPANT.CALL_FLAG.WITH_AUDIO | PARTICIPANT.CALL_FLAG.WITH_VIDEO
	return (flags & REQUIRED_FLAGS) !== 0
}

/**
 * @param {object} signaling The signaling object
 * @param {Array} newUsers Newly added participants
 * @param {Array} disconnectedSessionIds Remove participants
 */
function usersChanged(signaling, newUsers, disconnectedSessionIds) {
	'use strict'
	const currentSessionId = signaling.getSessionId()

	const useMcu = signaling.hasFeature('mcu')
	if (useMcu && newUsers.length) {
		checkStartPublishOwnPeer(signaling)
	}

	let playJoinSound = false
	let playLeaveSound = false

	newUsers.forEach(function(user) {
		if (!user.inCall) {
			return
		}

		// TODO(fancycode): Adjust property name of internal PHP backend to be all lowercase.
		const sessionId = user.sessionId || user.sessionid
		if (!sessionId || sessionId === currentSessionId || previousUsersInRoom.indexOf(sessionId) !== -1) {
			if (sessionId === currentSessionId && previousUsersInRoom.indexOf(sessionId) !== -1) {
				Sounds.playJoin(true, newUsers.length === 1)
			}
			return
		}

		previousUsersInRoom.push(sessionId)

		// Use null to differentiate between guest (null) and not known yet
		// (undefined).
		// TODO(fancycode): Adjust property name of internal PHP backend to be all lowercase.
		const userId = user.userId || user.userid || null

		// When the external signaling server is used the Nextcloud session id
		// will be provided in its own property. When the internal signaling
		// server is used the Nextcloud session id and the signaling session id
		// are the same and thus set from the signaling session id.
		const nextcloudSessionId = user.nextcloudSessionId || user.nextcloudsessionid || sessionId

		let callParticipantModel = callParticipantCollection.get(sessionId)
		if (!callParticipantModel) {
			callParticipantModel = callParticipantCollection.add({
				peerId: sessionId,
				webRtc: webrtc,
			})
		}
		callParticipantModel.setUserId(userId)
		callParticipantModel.setNextcloudSessionId(nextcloudSessionId)
		if (user.internal) {
			callParticipantModel.set('internal', true)
		}

		// When the MCU is used and the other participant has no streams or
		// when no MCU is used and neither the local participant nor the
		// other one has no streams there will be no Peer for that other
		// participant, so a null Peer needs to be explicitly set now.
		if ((signaling.hasFeature('mcu') && user && !userHasStreams(user))
				|| (!signaling.hasFeature('mcu') && user && !userHasStreams(user) && !webrtc.webrtc.localStreams.length)) {
			callParticipantModel.setPeer(null)

			// As there is no Peer for the other participant the current state
			// will not be sent once it is connected, so it needs to be sent
			// now.
			// When there is no MCU this is only needed for the nick; as the
			// local participant has no streams it will be automatically marked
			// with audio and video not available on the other end, so there is
			// no need to send the media state.
			if (signaling.hasFeature('mcu')) {
				sendCurrentStateWithRepetition()
			} else {
				sendCurrentNick()
			}
		}

		playJoinSound = true

		const createPeer = function() {
			const peer = webrtc.webrtc.createPeer({
				id: sessionId,
				type: 'video',
				enableDataChannels: true,
				enableSimulcast: signaling.hasFeature('simulcast'),
				receiveMedia: {
					offerToReceiveAudio: 1,
					offerToReceiveVideo: 1,
				},
				sendVideoIfAvailable: signaling.getSendVideoIfAvailable(),
			})
			webrtc.emit('createdPeer', peer)
			peer.start()
		}

		if (!webrtc.webrtc.getPeers(sessionId, 'video').length) {
			if (useMcu && userHasStreams(user)) {
				// TODO(jojo): Already create peer object to avoid duplicate offers.
				signaling.requestOffer(user, 'video')

				delayedConnectionToPeer[user.sessionId] = setInterval(function() {
					console.debug('No offer received for new peer, request offer again')

					signaling.requestOffer(user, 'video')
				}, 10000)
			} else if (!useMcu && userHasStreams(selfInCall) && (!userHasStreams(user) || sessionId < currentSessionId)) {
				// To avoid overloading the user joining a room (who previously called
				// all the other participants), we decide who calls who by comparing
				// the session ids of the users: "larger" ids call "smaller" ones.
				console.debug('Starting call with', user)
				createPeer()
			} else if (!useMcu && userHasStreams(selfInCall) && userHasStreams(user) && sessionId > currentSessionId) {
				// If the remote peer is not aware that it was disconnected
				// from the current peer the remote peer will not send a new
				// offer; thus, if the current peer does not receive a new
				// offer in a reasonable time, the current peer calls the
				// remote peer instead of waiting to be called to
				// reestablish the connection.
				delayedConnectionToPeer[sessionId] = setInterval(function() {
					// New offers are periodically sent until a connection
					// is established. As an offer can not be sent again
					// from an existing peer it must be removed and a new
					// one must be created from scratch.
					webrtc.webrtc.getPeers(sessionId, 'video').forEach(function(peer) {
						peer.end()
					})

					console.debug('No offer nor answer received, sending offer again')
					createPeer()
				}, 10000)
			} else {
				console.debug('User has no streams, not sending another offer')
			}
		}

		// Send shared screen to new participants
		if (webrtc.getLocalScreen()) {
			createScreensharingPeer(signaling, sessionId)
		}
	})

	disconnectedSessionIds.forEach(function(sessionId) {
		console.debug('Remove disconnected peer', sessionId)
		webrtc.removePeers(sessionId)

		if (callParticipantCollection.remove(sessionId)) {
			playLeaveSound = true
		}

		if (delayedConnectionToPeer[sessionId]) {
			clearInterval(delayedConnectionToPeer[sessionId])
			delete delayedConnectionToPeer[sessionId]
			playLeaveSound = true
		}
	})

	previousUsersInRoom = arrayDiff(previousUsersInRoom, disconnectedSessionIds)

	if (selfInCall !== PARTICIPANT.CALL_FLAG.DISCONNECTED) {
		if (playJoinSound) {
			Sounds.playJoin()
		} else if (playLeaveSound) {
			Sounds.playLeave(false, previousUsersInRoom.length === 0)
		}
	}
}

/**
 * @param {object} signaling The signaling object
 * @param {object} users Participant list with sessionId as key
 */
function usersInCallChanged(signaling, users) {
	const previousSelfInCall = selfInCall

	// The passed list are the users that are currently in the room,
	// i.e. that are in the call and should call each other.
	const currentSessionId = signaling.getSessionId()
	const currentUsersInRoom = []
	const userMapping = {}
	selfInCall = PARTICIPANT.CALL_FLAG.DISCONNECTED
	let sessionId
	for (sessionId in users) {
		if (!Object.prototype.hasOwnProperty.call(users, sessionId)) {
			continue
		}
		const user = users[sessionId]
		if (!user.inCall) {
			continue
		}

		if (sessionId === currentSessionId) {
			selfInCall = user.inCall
			continue
		}

		currentUsersInRoom.push(sessionId)
		userMapping[sessionId] = user
	}

	if (previousSelfInCall === PARTICIPANT.CALL_FLAG.DISCONNECTED
		&& selfInCall !== PARTICIPANT.CALL_FLAG.DISCONNECTED) {
		Sounds.playJoin(true, Object.keys(userMapping).length === 0)
	} else if (previousSelfInCall !== PARTICIPANT.CALL_FLAG.DISCONNECTED
		&& selfInCall === PARTICIPANT.CALL_FLAG.DISCONNECTED) {
		Sounds.playLeave(true)
	}

	// Besides the participant state it also needs to be checked whether the
	// local user left the call already or not (either explicitly or due to a
	// forced reconnection) to avoid trying to leave the call twice in the
	// store.
	if (previousSelfInCall !== PARTICIPANT.CALL_FLAG.DISCONNECTED
		&& selfInCall === PARTICIPANT.CALL_FLAG.DISCONNECTED
		&& localUserInCall) {
		console.info('Force leaving the call for current participant')

		store.dispatch('leaveCall', {
			token: store.getters.getToken(),
			participantIdentifier: store.getters.getParticipantIdentifier(),
		})

		// Do not return to disconnect already from the other participants
		// without waiting for another signaling event about changed users.
	}

	if (selfInCall === PARTICIPANT.CALL_FLAG.DISCONNECTED) {
		// Own session is no longer in the call, disconnect from all others.
		usersChanged(signaling, [], previousUsersInRoom)
		return
	}

	const newSessionIds = arrayDiff(currentUsersInRoom, previousUsersInRoom)
	const disconnectedSessionIds = arrayDiff(previousUsersInRoom, currentUsersInRoom)
	const newUsers = []
	newSessionIds.forEach(function(sessionId) {
		newUsers.push(userMapping[sessionId])
	})
	if (newUsers.length || disconnectedSessionIds.length) {
		usersChanged(signaling, newUsers, disconnectedSessionIds)
	}
}

/**
 * @param {object} signaling The signaling object
 * @param {object} _callParticipantCollection Collection with participants
 * @param {object} _localCallParticipantModel The local participant
 */
export default function initWebRtc(signaling, _callParticipantCollection, _localCallParticipantModel) {
	callParticipantCollection = _callParticipantCollection
	localCallParticipantModel = _localCallParticipantModel

	signaling.on('usersLeft', function(users) {
		users.forEach(function(user) {
			delete usersInCallMapping[user]
		})
		usersChanged(signaling, [], users)
	})
	signaling.on('usersChanged', function(users) {
		users.forEach(function(user) {
			const sessionId = user.sessionId || user.sessionid
			usersInCallMapping[sessionId] = user
		})
		usersInCallChanged(signaling, usersInCallMapping)
	})
	signaling.on('participantFlagsChanged', function(event) {
		/**
		 * event {
		 *   roomid: "1609407087",
		 *   sessionid: "…",
		 *   flags: 1
		 * }
		 */
		const callParticipantModel = callParticipantCollection.get(event.sessionid)
		if (callParticipantModel) {
			callParticipantModel.set('speaking', (event.flags & PARTICIPANT.SIP_FLAG.SPEAKING) > 0)
			callParticipantModel.set('audioAvailable', (event.flags & PARTICIPANT.SIP_FLAG.MUTE_MICROPHONE) === 0)
			callParticipantModel.set('raisedHand', {
				state: (event.flags & PARTICIPANT.SIP_FLAG.RAISE_HAND) !== 0,
				timestamp: Date.now(),
			})
		}
	})
	signaling.on('usersInRoom', function(users) {
		usersInCallMapping = {}
		users.forEach(function(user) {
			const sessionId = user.sessionId || user.sessionid
			usersInCallMapping[sessionId] = user
		})
		usersInCallChanged(signaling, usersInCallMapping)
	})
	signaling.on('beforeJoinCall', function(token, reconnect) {
		// The user needs to be set as in the call before the request is
		// actually done to also cover the (unlikely) case that the request
		// takes too long to return and the associated signaling message
		// is received before the "join call" request ends.
		localUserInCall = true
	})
	signaling.on('beforeLeaveCall', function(token, reconnect) {
		// The user needs to be set as not in the call before the request is
		// actually done to also cover the (unlikely) case that the request
		// takes too long to return and the associated signaling message
		// is received before the "leave call" request ends.
		localUserInCall = false
	})
	signaling.on('leaveCall', function(token, reconnect) {
		// When the MCU is used and there is a connection error the call is
		// left and then joined again to perform the reconnection. In those
		// cases the call should be kept active from the point of view of
		// WebRTC.
		if (reconnect) {
			return
		}

		clearErrorNotification()
		Sounds.playLeave(true)

		// The delayed connection for the own peer needs to be explicitly
		// stopped, as the current own session is not passed along with the
		// sessions of the other participants as "disconnected" to
		// "usersChanged" when a call is left.
		// The peer, on the other hand, is automatically ended by "leaveCall"
		// below.
		if (ownPeer && delayedConnectionToPeer[ownPeer.id]) {
			clearInterval(delayedConnectionToPeer[ownPeer.id])
			delete delayedConnectionToPeer[ownPeer.id]
		}

		webrtc.leaveCall()
	})

	signaling.on('message', function(message) {
		if (message.type === 'answer' && message.roomType === 'video' && delayedConnectionToPeer[message.from]) {
			clearInterval(delayedConnectionToPeer[message.from])
			delete delayedConnectionToPeer[message.from]

			return
		}

		if (message.type !== 'offer') {
			return
		}

		const peers = webrtc.webrtc.peers
		const stalePeer = peers.find(function(peer) {
			if (peer.sharemyscreen) {
				return false
			}

			return peer.id === message.from && peer.type === message.roomType && peer.sid !== message.sid
		})

		if (stalePeer) {
			stalePeer.end()
		}

		if (message.roomType === 'video' && delayedConnectionToPeer[message.from]) {
			clearInterval(delayedConnectionToPeer[message.from])
			delete delayedConnectionToPeer[message.from]
		}

		if (!selfInCall) {
			console.debug('Offer received when not in the call, ignore')

			message.type = 'offer-to-ignore'
		}

		// MCU screen offers do not include the "broadcaster" property,
		// which is expected by SimpleWebRTC in screen offers from a remote
		// peer, so it needs to be explicitly added.
		if (signaling.hasFeature('mcu') && message.roomType === 'screen') {
			message.broadcaster = message.from
		}
	})

	webrtc = new SimpleWebRTC({
		remoteVideosEl: '',
		autoRequestMedia: true,
		debug: false,
		autoAdjustMic: false,
		audioFallback: true,
		connection: signaling,
		enableDataChannels: true,
		enableSimulcast: signaling.hasFeature('simulcast'),
		nick: store.getters.getDisplayName(),
	})

	if (!window.OCA.Talk) {
		window.OCA.Talk = {}
	}
	window.OCA.Talk.SimpleWebRTC = webrtc

	signaling.on('pullMessagesStoppedOnFail', function() {
		// Force leaving the call in WebRTC; when pulling messages stops due
		// to failures the room is left, and leaving the room indirectly
		// runs signaling.leaveCurrentCall(), but if the signaling fails to
		// leave the call (which is likely due to the messages failing to be
		// received) no event will be triggered and the call will not be
		// left from WebRTC point of view.
		webrtc.leaveCall()
	})

	webrtc.startMedia = function(token, flags) {
		startedWithMedia = undefined

		// If no flags are provided try to enable both audio and video.
		// Otherwise, try to enable only that allowed by the flags.
		const mediaConstraints = {
			audio: !flags || !!(flags & PARTICIPANT.CALL_FLAG.WITH_AUDIO),
			video: !flags || !!(flags & PARTICIPANT.CALL_FLAG.WITH_VIDEO),
		}

		webrtc.joinCall(token, mediaConstraints)
	}

	const sendDataChannelToAll = function(channel, message, payload) {
		// If running with MCU, the message must be sent through the
		// publishing peer and will be distributed by the MCU to subscribers.
		if (ownPeer && signaling.hasFeature && signaling.hasFeature('mcu')) {
			ownPeer.sendDirectly(channel, message, payload)
			return
		}
		webrtc.sendDirectlyToAll(channel, message, payload)
	}

	/**
	 * @param {object} peer The peer connection to handle the state on
	 */
	function handleIceConnectionStateConnected(peer) {
		// Send the current information about the state.
		if (!signaling.hasFeature('mcu')) {
			// Only the media state needs to be sent, the nick was already sent
			// in the offer/answer.
			sendCurrentMediaState()
		} else {
			sendCurrentStateWithRepetition()
		}

		// Reset ice restart counter for peer
		if (spreedPeerConnectionTable[peer.id] > 0) {
			spreedPeerConnectionTable[peer.id] = 0
		}
	}

	/**
	 * @param {object} peer The peer connection to handle the state on
	 */
	function handleIceConnectionStateDisconnected(peer) {
		setTimeout(function() {
			if (peer.pc.iceConnectionState !== 'disconnected') {
				return
			}

			peer.emit('extendedIceConnectionStateChange', 'disconnected-long')

			if (!signaling.hasFeature('mcu')) {
				// Disconnections are not handled with the MCU, only
				// failures.

				// If the peer is still disconnected after 5 seconds we try
				// ICE restart.
				if (spreedPeerConnectionTable[peer.id] < 5) {
					if (peer.pc.localDescription.type === 'offer'
							&& peer.pc.signalingState === 'stable') {
						spreedPeerConnectionTable[peer.id]++
						console.debug('ICE restart after disconnect.', peer)
						peer.icerestart()
					}
				}
			}
		}, 5000)
	}

	/**
	 * @param {object} peer The peer connection to handle the state on
	 */
	function handleIceConnectionStateFailed(peer) {
		if (!showedTURNWarning && !signaling.settings.turnservers.length) {
			showError(
				t('spreed', 'Could not establish a connection with at least one participant. A TURN server might be needed for your scenario. Please ask your administrator to set one up following {linkstart}this documentation{linkend}.')
					.replace('{linkstart}', '<a  target="_blank" rel="noreferrer nofollow" class="external" href="https://nextcloud-talk.readthedocs.io/en/latest/TURN/">')
					.replace('{linkend}', ' ↗</a>'),
				{
					timeout: TOAST_PERMANENT_TIMEOUT,
					isHTML: true,
				}
			)
			showedTURNWarning = true
		}

		if (!signaling.hasFeature('mcu')) {
			if (spreedPeerConnectionTable[peer.id] < 5) {
				if (peer.pc.localDescription.type === 'offer'
						&& peer.pc.signalingState === 'stable') {
					spreedPeerConnectionTable[peer.id]++
					console.debug('ICE restart after failure.', peer)
					peer.icerestart()
				}
			} else {
				console.error('ICE failed after 5 tries.', peer)

				peer.emit('extendedIceConnectionStateChange', 'failed-no-restart')
			}
		} else {
			// This handles ICE failures of a receiver peer; ICE failures of
			// the sender peer are handled in the "iceFailed" event.
			console.debug('Request offer again', peer)

			signaling.requestOffer(peer.id, 'video')

			delayedConnectionToPeer[peer.id] = setInterval(function() {
				console.debug('No offer received, request offer again', peer)

				signaling.requestOffer(peer.id, 'video')
			}, 10000)
		}
	}

	/**
	 * @param {object} peer The peer connection to handle the state on
	 */
	function setHandlerForIceConnectionStateChange(peer) {
		// Initialize ice restart counter for peer
		spreedPeerConnectionTable[peer.id] = 0

		peer.pc.addEventListener('iceconnectionstatechange', function() {
			peer.emit('extendedIceConnectionStateChange', peer.pc.iceConnectionState)

			switch (peer.pc.iceConnectionState) {
			case 'checking':
				console.debug('Connecting to peer...', peer)

				break
			case 'connected':
			case 'completed': // on caller side
				console.debug('Connection established.', peer)

				handleIceConnectionStateConnected(peer)
				break
			case 'disconnected':
				console.debug('Disconnected.', peer)

				handleIceConnectionStateDisconnected(peer)
				break
			case 'failed':
				console.debug('Connection failed.', peer)

				handleIceConnectionStateFailed(peer)
				break
			case 'closed':
				console.debug('Connection closed.', peer)

				break
			}
		})
	}

	/**
	 * @param {object} peer The peer connection to handle the state on
	 */
	function setHandlerForConnectionStateChange(peer) {
		peer.pc.addEventListener('connectionstatechange', function() {
			if (peer.pc.connectionState !== 'failed') {
				return
			}

			if (peer.pc.iceConnectionState === 'failed') {
				return
			}

			// Work around Chromium bug where "iceConnectionState" never changes
			// to "failed" (it stays as "disconnected"). When that happens
			// "connectionState" actually does change to "failed", so the normal
			// handling of "iceConnectionState === failed" is triggered here.

			peer.emit('extendedIceConnectionStateChange', peer.pc.connectionState)

			handleIceConnectionStateFailed(peer)
		})
	}

	/**
	 * @param {object} peer The peer connection to handle the state on
	 */
	function setHandlerForOwnIceConnectionStateChange(peer) {
		peer.pc.addEventListener('iceconnectionstatechange', function() {
			peer.emit('extendedIceConnectionStateChange', peer.pc.iceConnectionState)

			switch (peer.pc.iceConnectionState) {
			case 'checking':
				console.debug('Connecting own peer...', peer)

				break
			case 'connected':
			case 'completed':
				console.debug('Connection established (own peer).', peer)

				break
			case 'disconnected':
				console.debug('Disconnected (own peer).', peer)

				setTimeout(function() {
					if (peer.pc.iceConnectionState !== 'disconnected') {
						return
					}

					peer.emit('extendedIceConnectionStateChange', 'disconnected-long')
				}, 5000)
				break
			case 'failed':
				console.debug('Connection failed (own peer).', peer)

				break
			case 'closed':
				console.debug('Connection closed (own peer).', peer)

				break
			}
		})
	}

	const forceReconnect = function(signaling, flags) {
		if (ownPeer) {
			if (delayedConnectionToPeer[ownPeer.id]) {
				clearInterval(delayedConnectionToPeer[ownPeer.id])
				delete delayedConnectionToPeer[ownPeer.id]
			}
			ownPeer.end()
			ownPeer = null

			localCallParticipantModel.setPeer(ownPeer)
		}

		usersChanged(signaling, [], previousUsersInRoom)
		usersInCallMapping = {}
		previousUsersInRoom = []

		// Reconnects with a new session id will trigger "usersChanged"
		// with the users in the room and that will re-establish the
		// peerconnection streams.
		// If flags are undefined the current call flags are used.
		signaling.forceReconnect(true, flags)
	}

	/**
	 * @param {object} peer The peer connection to handle the state on
	 */
	function setHandlerForNegotiationNeeded(peer) {
		peer.pc.addEventListener('negotiationneeded', function() {
			// Negotiation needed will be first triggered before the connection
			// is established, but forcing a reconnection should be done only
			// once the connection was established.
			if (peer.pc.iceConnectionState !== 'new' && peer.pc.iceConnectionState !== 'checking') {
				// Update the media flags if needed, as the renegotiation could
				// have been caused by tracks being added or removed.
				const audioSender = peer.pc.getSenders().find((sender) => sender.track && sender.track.kind === 'audio')
				const videoSender = peer.pc.getSenders().find((sender) => sender.track && sender.track.kind === 'video')

				let flags = signaling.getCurrentCallFlags()
				if (audioSender) {
					flags |= PARTICIPANT.CALL_FLAG.WITH_AUDIO
				} else {
					flags &= ~PARTICIPANT.CALL_FLAG.WITH_AUDIO
				}
				if (videoSender) {
					flags |= PARTICIPANT.CALL_FLAG.WITH_VIDEO
				} else {
					flags &= ~PARTICIPANT.CALL_FLAG.WITH_VIDEO
				}

				// Negotiation is expected to be needed only when a new track is
				// added to or removed from a peer. Therefore if the HPB is used
				// the negotiation will be needed in the own peer, but if the
				// HPB is not used it will be needed in all peers. However, in
				// that case as soon as the forced reconnection is triggered all
				// the peers will be cleared, so in practice there will be just
				// one forced reconnection even if there are several peers.
				// FIXME: despite all of the above this is a dirty and ugly hack
				// that should be fixed with proper renegotiation.
				forceReconnect(signaling, flags)
			}
		})
	}

	const reconnectOnPermissionsChange = (users) => {
		const currentParticipant = users.find(user => {
			const sessionId = user.sessionId || user.sessionid
			return sessionId === signaling.getSessionId()
		})

		if (!currentParticipant) {
			return
		}

		if (!currentParticipant.inCall) {
			return
		}

		if (currentParticipant.participantPermissions === undefined) {
			return
		}

		if ((currentParticipant.participantPermissions & PARTICIPANT.PERMISSIONS.PUBLISH_AUDIO)
			&& (currentParticipant.participantPermissions & PARTICIPANT.PERMISSIONS.PUBLISH_VIDEO)
			&& webrtc.webrtc.isLocalMediaActive()) {
			return
		}

		if (!(currentParticipant.participantPermissions & PARTICIPANT.PERMISSIONS.PUBLISH_AUDIO)
			&& !(currentParticipant.participantPermissions & PARTICIPANT.PERMISSIONS.PUBLISH_VIDEO)
			&& !webrtc.webrtc.isLocalMediaActive()) {
			return
		}

		// FIXME handle case where only one of the permissions is given
		if (!(currentParticipant.participantPermissions & PARTICIPANT.PERMISSIONS.PUBLISH_AUDIO)
			&& !(currentParticipant.participantPermissions & PARTICIPANT.PERMISSIONS.PUBLISH_VIDEO)) {
			startedWithMedia = undefined

			webrtc.stopLocalVideo()

			// If the MCU is used and there is no sending peer there is no need
			// to force a reconnection, as there will be no connection that
			// needs to be stopped.
			if (!signaling.hasFeature('mcu') || ownPeer) {
				forceReconnect(signaling, PARTICIPANT.CALL_FLAG.IN_CALL)
			}

			return
		}

		const forceReconnectOnceLocalMediaStarted = (constraints) => {
			webrtc.off('localMediaStarted', forceReconnectOnceLocalMediaStarted)
			webrtc.off('localMediaError', forceReconnectOnceLocalMediaError)

			startedWithMedia = true

			let flags = PARTICIPANT.CALL_FLAG.IN_CALL
			if (constraints) {
				if (constraints.audio) {
					flags |= PARTICIPANT.CALL_FLAG.WITH_AUDIO
				}
				if (constraints.video && signaling.getSendVideoIfAvailable()) {
					flags |= PARTICIPANT.CALL_FLAG.WITH_VIDEO
				}
			}

			forceReconnect(signaling, flags)
		}
		const forceReconnectOnceLocalMediaError = () => {
			webrtc.off('localMediaStarted', forceReconnectOnceLocalMediaStarted)
			webrtc.off('localMediaError', forceReconnectOnceLocalMediaError)

			startedWithMedia = false

			// If the media fails to start there will be no media, so no need to
			// reconnect. A reconnection will happen once the user selects a
			// different device.
		}

		webrtc.on('localMediaStarted', forceReconnectOnceLocalMediaStarted)
		webrtc.on('localMediaError', forceReconnectOnceLocalMediaError)

		startedWithMedia = undefined

		webrtc.startLocalVideo()
	}

	signaling.on('usersInRoom', function(users) {
		reconnectOnPermissionsChange(users)
	})
	signaling.on('usersChanged', function(users) {
		reconnectOnPermissionsChange(users)
	})

	webrtc.on('createdPeer', function(peer) {
		console.debug('Peer created', peer)

		if (peer.id !== signaling.getSessionId() && !peer.sharemyscreen) {
			// In some strange cases a Peer can be added before its
			// participant is found in the list of participants.
			let callParticipantModel = callParticipantCollection.get(peer.id)
			if (!callParticipantModel) {
				callParticipantModel = callParticipantCollection.add({
					peerId: peer.id,
					webRtc: webrtc,
				})
			}

			if (peer.type === 'video') {
				callParticipantModel.setPeer(peer)
			} else {
				callParticipantModel.setScreenPeer(peer)
			}
		}

		if (peer.type === 'video') {
			if (peer.id === signaling.getSessionId()) {
				setHandlerForOwnIceConnectionStateChange(peer)
			} else {
				setHandlerForIceConnectionStateChange(peer)
				setHandlerForConnectionStateChange(peer)
			}

			setHandlerForNegotiationNeeded(peer)

			// Make sure required data channels exist for all peers. This
			// is required for peers that get created by SimpleWebRTC from
			// received "Offer" messages. Otherwise the "channelMessage"
			// will not be called.
			peer.getDataChannel('status')
		}
	})

	/**
	 * @param {object} peer The peer connection to check media on
	 * @param {object} track The track to check the media on
	 * @param {string} mediaType "video" or "audio"
	 */
	function checkPeerMedia(peer, track, mediaType) {
		return new Promise((resolve, reject) => {
			peer.pc.getStats(track).then(function(stats) {
				let result = false
				stats.forEach(function(statsReport) {
					if (result || statsReport.mediaType !== mediaType || !Object.prototype.hasOwnProperty.call(statsReport, 'bytesReceived')) {
						return
					}

					if (statsReport.bytesReceived > 0) {
						if (mediaType === 'video' && statsReport.bytesReceived < 2000) {
							// A video with less than 2000 bytes is an empty single frame of the MCU
							// console.debug('Participant is registered with with video but didn\'t send a lot of data, so we assume the video is disabled for now.')
							result = true
							return
						}
						webrtc.emit('unmute', {
							id: peer.id,
							name: mediaType,
						})
						result = true
					}
				})
				if (result) {
					resolve()
				} else {
					reject(new Error('No bytes received'))
				}
			})
		})
	}

	/**
	 * @param {object} peer The peer connection to check media on
	 */
	function stopPeerCheckAudioMedia(peer) {
		clearInterval(peer.check_audio_interval)
		peer.check_audio_interval = null
	}

	/**
	 * @param {object} peer The peer connection to check media on
	 */
	function stopPeerCheckVideoMedia(peer) {
		clearInterval(peer.check_video_interval)
		peer.check_video_interval = null
	}

	/**
	 * @param {string} peerId ID to get the peer for
	 * @param {string} mediaType "video" or "audio"
	 */
	function stopPeerIdCheckMediaType(peerId, mediaType) {
		// There should be just one video peer with that id, but iterating is
		// safer.
		const peers = webrtc.getPeers(peerId, 'video')
		peers.forEach(function(peer) {
			if (mediaType === 'audio') {
				stopPeerCheckAudioMedia(peer)
			} else if (mediaType === 'video') {
				stopPeerCheckVideoMedia(peer)
			}
		})
	}

	if (signaling.hasFeature('mcu')) {
		webrtc.on('mute', function(data) {
			stopPeerIdCheckMediaType(data.id, data.name)
		})
		webrtc.on('unmute', function(data) {
			stopPeerIdCheckMediaType(data.id, data.name)
		})
	}

	/**
	 * @param {object} peer The peer connection to check media on
	 */
	function stopPeerCheckMedia(peer) {
		stopPeerCheckAudioMedia(peer)
		stopPeerCheckVideoMedia(peer)
	}

	/**
	 * @param {object} peer The peer connection to check media on
	 * @param {object} stream The stream to check
	 */
	function startPeerCheckMedia(peer, stream) {
		stopPeerCheckMedia(peer)
		peer.check_video_interval = setInterval(function() {
			stream.getVideoTracks().forEach(function(video) {
				checkPeerMedia(peer, video, 'video').then(function() {
					stopPeerCheckVideoMedia(peer)
				}).catch(() => {
				})
			})
		}, 1000)
		peer.check_audio_interval = setInterval(function() {
			stream.getAudioTracks().forEach(function(audio) {
				checkPeerMedia(peer, audio, 'audio').then(function() {
					stopPeerCheckAudioMedia(peer)
				}).catch(() => {
				})
			})
		}, 1000)
	}

	webrtc.on('peerStreamAdded', function(peer) {
		// With the MCU, a newly subscribed stream might not get the
		// "audioOn"/"videoOn" messages as they are only sent when
		// a user starts publishing. Instead wait for initial data
		// and trigger events locally.
		if (!signaling.hasFeature('mcu')) {
			return
		}

		if (peer.type === 'screen') {
			return
		}

		startPeerCheckMedia(peer, peer.stream)
	})

	webrtc.on('peerStreamRemoved', function(peer) {
		stopPeerCheckMedia(peer)
	})

	webrtc.webrtc.on('videoOn', function() {
		if (signaling.getSendVideoIfAvailable()) {
			return
		}

		// When enabling the local video if the video is not being sent a
		// reconnection is forced to start sending it.
		signaling.setSendVideoIfAvailable(true)

		startedWithMedia = true

		let flags = signaling.getCurrentCallFlags()
		flags |= PARTICIPANT.CALL_FLAG.WITH_VIDEO

		forceReconnect(signaling, flags)
	})

	webrtc.webrtc.on('iceFailed', function(/* peer */) {
		if (!signaling.hasFeature('mcu')) {
			// ICE restarts will be handled by "iceConnectionStateChange"
			// above.
			return
		}

		// For now assume the connection to the MCU is interrupted on ICE
		// failures and force a reconnection of all streams.
		forceReconnect(signaling)
	})

	let localStreamRequestedTimeout = null
	let localStreamRequestedTimeoutNotification = null

	let errorNotificationHandle = null

	const clearLocalStreamRequestedTimeoutAndHideNotification = function() {
		clearTimeout(localStreamRequestedTimeout)
		localStreamRequestedTimeout = null

		if (localStreamRequestedTimeoutNotification) {
			localStreamRequestedTimeoutNotification.hideToast()
			localStreamRequestedTimeoutNotification = null
		}

	}

	const clearErrorNotification = function() {
		if (errorNotificationHandle) {
			errorNotificationHandle.hideToast()
			errorNotificationHandle = null
		}
	}

	// In some cases the browser may enter in a faulty state in which
	// "getUserMedia" does not return neither successfully nor with an
	// error. It is not possible to detect this except by guessing when some
	// time passes and the user has not granted nor rejected the media
	// permissions.
	webrtc.on('localStreamRequested', function() {
		clearLocalStreamRequestedTimeoutAndHideNotification()

		localStreamRequestedTimeout = setTimeout(function() {
			// FIXME emit an event and handle it as needed instead of
			// calling UI code from here.
			localStreamRequestedTimeoutNotification = showError(t('spreed', 'This is taking longer than expected. Are the media permissions already granted (or rejected)? If yes please restart your browser, as audio and video are failing'), {
				timeout: TOAST_PERMANENT_TIMEOUT,
			})
		}, 10000)
	})

	signaling.on('leaveRoom', function(token) {
		if (signaling.currentRoomToken === token) {
			clearLocalStreamRequestedTimeoutAndHideNotification()
			clearErrorNotification()
		}
	})

	webrtc.on('localTrackReplaced', function(newTrack, oldTrack/*, stream */) {
		// Device disabled, just update the call flags.
		if (!newTrack) {
			if (oldTrack && oldTrack.kind === 'audio') {
				signaling.updateCurrentCallFlags(signaling.getCurrentCallFlags() & ~PARTICIPANT.CALL_FLAG.WITH_AUDIO)
			} else if (oldTrack && oldTrack.kind === 'video') {
				signaling.updateCurrentCallFlags(signaling.getCurrentCallFlags() & ~PARTICIPANT.CALL_FLAG.WITH_VIDEO)
			}

			return
		}

		// If the call was started with media the connections will be already
		// established. The flags need to be updated if a device was enabled
		// (but not if it was switched to another one).
		if (startedWithMedia) {
			if (newTrack.kind === 'audio' && !oldTrack) {
				signaling.updateCurrentCallFlags(signaling.getCurrentCallFlags() | PARTICIPANT.CALL_FLAG.WITH_AUDIO)
			} else if (newTrack.kind === 'video' && !oldTrack) {
				signaling.updateCurrentCallFlags(signaling.getCurrentCallFlags() | PARTICIPANT.CALL_FLAG.WITH_VIDEO)
			}

			return
		}

		// If the call has not started with media yet the connections will be
		// established once started, as well as the flags.
		if (startedWithMedia === undefined) {
			return
		}

		// If the call was originally started without media the participant
		// needs to reconnect to establish the sender connections.
		startedWithMedia = true

		let flags = signaling.getCurrentCallFlags()
		if (newTrack.kind === 'audio') {
			flags |= PARTICIPANT.CALL_FLAG.WITH_AUDIO
		} else if (newTrack.kind === 'video') {
			flags |= PARTICIPANT.CALL_FLAG.WITH_VIDEO
		}

		forceReconnect(signaling, flags)
	})

	webrtc.on('localMediaStarted', function(/* configuration */) {
		console.info('localMediaStarted')

		startedWithMedia = true

		clearLocalStreamRequestedTimeoutAndHideNotification()

		if (signaling.hasFeature('mcu')) {
			checkStartPublishOwnPeer(signaling)
		}
	})

	webrtc.on('localMediaError', function(error) {
		console.warn('Access to microphone & camera failed', error)

		startedWithMedia = false

		clearLocalStreamRequestedTimeoutAndHideNotification()

		if (error.name === 'TypeError') {
			// Both audio and video were explicitly disabled, no need to show an
			// error.
			return
		}

		let message
		let timeout = TOAST_PERMANENT_TIMEOUT
		if ((error.name === 'NotSupportedError'
				&& webrtc.capabilities.supportRTCPeerConnection)
			|| (error.name === 'NotAllowedError'
				&& error.message && error.message.indexOf('Only secure origins') !== -1)) {
			message = t('spreed', 'Access to microphone & camera is only possible with HTTPS')
			message += ': ' + t('spreed', 'Please move your setup to HTTPS')
		} else if (error.name === 'NotAllowedError') {
			message = t('spreed', 'Access to microphone & camera was denied')
			timeout = TOAST_DEFAULT_TIMEOUT
		} else if (!webrtc.capabilities.support) {
			console.error('WebRTC not supported')

			message = t('spreed', 'WebRTC is not supported in your browser')
			message += ': ' + t('spreed', 'Please use a different browser like Firefox or Chrome')
		} else {
			// Mostly happens in Chrome (NotFoundError): when no audio device available
			// not sure what else can cause this
			message = t('spreed', 'Error while accessing microphone & camera')
			console.error('Error while accessing microphone & camera: ', error.message, error.name)
		}

		errorNotificationHandle = showError(message, {
			timeout,
		})
	})

	webrtc.on('channelOpen', function(channel) {
		console.debug('%s datachannel is open', channel.label)
	})

	webrtc.on('channelMessage', function(peer, label, data) {
		if (label === 'status' || label === 'JanusDataChannel') {
			if (data.type === 'audioOn') {
				webrtc.emit('unmute', { id: peer.id, name: 'audio' })
			} else if (data.type === 'audioOff') {
				webrtc.emit('mute', { id: peer.id, name: 'audio' })
			} else if (data.type === 'videoOn') {
				webrtc.emit('unmute', { id: peer.id, name: 'video' })
			} else if (data.type === 'videoOff') {
				webrtc.emit('mute', { id: peer.id, name: 'video' })
			} else if (data.type === 'nickChanged') {
				const name = typeof (data.payload) === 'string' ? data.payload : data.payload.name
				webrtc.emit('nick', { id: peer.id, name })
			} else if (data.type === 'speaking' || data.type === 'stoppedSpeaking') {
				// Valid known messages, but handled elsewhere
			} else {
				console.debug('Unknown message type %s from %s datachannel', data.type, label, data)
			}
		} else {
			console.debug('Unknown message from %s datachannel', label, data)
		}
	})

	webrtc.on('sendToAll', function(messageType, payload) {
		const sessionIdsForParticipantsWithPeers = {}
		webrtc.webrtc.peers.forEach(peer => {
			sessionIdsForParticipantsWithPeers[peer.id] = peer
		})

		// "webrtc.sendToAll" only sends the signaling message to participants
		// for which there is a Peer object. Therefore the message needs to be
		// explicitly sent here too to participants without audio and video.
		for (const sessionId in usersInCallMapping) {
			if (sessionIdsForParticipantsWithPeers[sessionId]) {
				continue
			} else if (!usersInCallMapping[sessionId].inCall) {
				continue
			} else if (sessionId === signaling.getSessionId()) {
				continue
			}

			// "roomType" is not really relevant without a peer, but it is
			// nevertheless expected in the message. As the signaling messages
			// currently sent to all participants are related to video peers
			// "video" is used as the room type.
			const message = {
				to: sessionId,
				roomType: 'video',
				type: messageType,
				payload,
			}
			signaling.emit('message', message)
		}
	})

	webrtc.on('speaking', function() {
		sendDataChannelToAll('status', 'speaking')
	})

	webrtc.on('stoppedSpeaking', function() {
		sendDataChannelToAll('status', 'stoppedSpeaking')
	})

	// Send the audio on and off events via data channel
	webrtc.on('audioOn', function() {
		sendDataChannelToAll('status', 'audioOn')
	})
	webrtc.on('audioOff', function() {
		sendDataChannelToAll('status', 'audioOff')
	})
	webrtc.on('videoOn', function() {
		sendDataChannelToAll('status', 'videoOn')
	})
	webrtc.on('videoOff', function() {
		sendDataChannelToAll('status', 'videoOff')
	})

	// Send the nick changed event via data channel and signaling
	//
	// The message format is different in each case. Due to historical reasons
	// the payload of the data channel message is either a string that contains
	// the name (if the participant is a guest) or an object with "name" and
	// "userid" string fields (when the participant is a user).
	//
	// In the newer signaling message, on the other hand, the payload is always
	// an object with only a "name" string field.
	webrtc.on('nickChanged', function(name) {
		let payload
		if (signaling.settings.userId === null) {
			payload = name
		} else {
			payload = {
				name,
				userid: signaling.settings.userId,
			}
		}

		sendDataChannelToAll('status', 'nickChanged', payload)

		webrtc.sendToAll('nickChanged', { name })
	})

	// Local screen added.
	webrtc.on('localScreenAdded', function(/* video */) {
		const currentSessionId = signaling.getSessionId()
		for (const sessionId in usersInCallMapping) {
			if (!Object.prototype.hasOwnProperty.call(usersInCallMapping, sessionId)) {
				continue
			} else if (!usersInCallMapping[sessionId].inCall) {
				continue
			} else if (sessionId === currentSessionId) {
				// Running with MCU, no need to create screensharing
				// subscriber for client itself.
				continue
			}

			createScreensharingPeer(signaling, sessionId)
		}
	})

	webrtc.on('localScreenStopped', function() {
		if (!signaling.hasFeature('mcu')) {
			// Only need to notify clients here if running with MCU.
			// Otherwise SimpleWebRTC will notify each client on its own.
			return
		}

		if (ownScreenPeer) {
			ownScreenPeer = null

			localCallParticipantModel.setScreenPeer(ownScreenPeer)

			signaling.sendRoomMessage({
				roomType: 'screen',
				type: 'unshareScreen',
			})
		}
	})

	webrtc.on('disconnected', function() {
		if (ownPeer) {
			if (delayedConnectionToPeer[ownPeer.id]) {
				clearInterval(delayedConnectionToPeer[ownPeer.id])
				delete delayedConnectionToPeer[ownPeer.id]
			}

			ownPeer.end()
			ownPeer = null

			localCallParticipantModel.setPeer(ownPeer)
		}

		if (ownScreenPeer) {
			ownScreenPeer.end()
			ownScreenPeer = null

			localCallParticipantModel.setScreenPeer(ownScreenPeer)
		}

		selfInCall = PARTICIPANT.CALL_FLAG.DISCONNECTED

		usersChanged(signaling, [], previousUsersInRoom)
		usersInCallMapping = {}
		previousUsersInRoom = []
	})

	return webrtc
}