-
Notifications
You must be signed in to change notification settings - Fork 416
/
webrtc.js
1742 lines (1489 loc) · 55.2 KB
/
webrtc.js
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
/**
* @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 {
showError,
TOAST_PERMANENT_TIMEOUT,
TOAST_DEFAULT_TIMEOUT,
} from '@nextcloud/dialogs'
import { PARTICIPANT } from '../../constants.js'
import store from '../../store/index.js'
import { Sounds } from '../sounds.js'
import SimpleWebRTC from './simplewebrtc/simplewebrtc.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 and discard signaling events if received when not in the call.
let localUserInCall = false
const delayedConnectionToPeer = []
let callParticipantCollection = null
let localCallParticipantModel = null
let showedTURNWarning = false
let sendCurrentStateWithRepetitionTimeout = null
/**
* @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()
}
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()
}
if (currentSessionId !== signaling.getSessionId()) {
console.debug('No answer received for own peer but current session id changed, not sending offer again', currentSessionId, signaling.getSessionId())
clearInterval(delayedConnectionToPeer[currentSessionId])
delete delayedConnectionToPeer[currentSessionId]
return
}
console.debug('No answer received for own peer, sending offer again', currentSessionId)
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')
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')
// Clearing the previous delayedConnectionToPeer should not be
// needed here, but just in case.
clearInterval(delayedConnectionToPeer[user.sessionId])
delayedConnectionToPeer[user.sessionId] = setInterval(function() {
console.debug('No offer received for new peer, request offer again', sessionId)
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, sessionId)
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', sessionId)
createPeer()
}, 10000)
} else {
console.debug('User has no streams, not sending another offer', sessionId)
}
}
// 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 (signaling.hasFeature('mcu') && (ownPeer || (currentUsersInRoom.length > 0 && webrtc.webrtc.localStreams.length))) {
checkStartPublishOwnPeer(signaling)
localCallParticipantModel.setPeerNeeded(true)
} else {
localCallParticipantModel.setPeerNeeded(false)
}
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) {
if (!localUserInCall) {
return
}
users.forEach(function(user) {
delete usersInCallMapping[user]
})
usersChanged(signaling, [], users)
})
signaling.on('usersChanged', function(users) {
if (!localUserInCall) {
return
}
users.forEach(function(user) {
const sessionId = user.sessionId || user.sessionid
usersInCallMapping[sessionId] = user
})
usersInCallChanged(signaling, usersInCallMapping)
})
signaling.on('allUsersChangedInCallToDisconnected', function() {
if (!localUserInCall) {
return
}
// "End meeting for all" was used, we don't have a user list but everyone disconnects from the call
usersInCallMapping = {}
usersInCallChanged(signaling, usersInCallMapping)
})
signaling.on('participantFlagsChanged', function(event) {
if (!localUserInCall) {
return
}
/**
* 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) {
if (!localUserInCall) {
return
}
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 ended by the calls below.
if (ownPeer && delayedConnectionToPeer[ownPeer.id]) {
clearInterval(delayedConnectionToPeer[ownPeer.id])
delete delayedConnectionToPeer[ownPeer.id]
}
// Besides stopping the media "leaveCall" would end the peers, but it
// does not stop the timers for pending connections, removes models or
// clears the call data, so this needs to be explicitly done here
// instead.
selfInCall = PARTICIPANT.CALL_FLAG.DISCONNECTED
usersChanged(signaling, [], previousUsersInRoom)
usersInCallMapping = {}
webrtc.leaveCall()
})
signaling.on('message', function(message) {
if (!localUserInCall) {
console.debug('Message received when not in the call, ignore', message.type, message)
message.type = 'message-to-ignore'
return
}
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]
}
// 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({
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) {
// 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 (signaling.hasFeature && signaling.hasFeature('mcu')) {
if (ownPeer) {
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.id, 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.id, peer)
peer.icerestart()
}
} else {
console.error('ICE failed after 5 tries.', peer.id, 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.id, peer)
signaling.requestOffer(peer.id, 'video')
clearInterval(delayedConnectionToPeer[peer.id])
delayedConnectionToPeer[peer.id] = setInterval(function() {
console.debug('No offer received, request offer again', peer.id, 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.id, peer)
break
case 'connected':
case 'completed': // on caller side
console.debug('Connection established.', peer.id, peer)
handleIceConnectionStateConnected(peer)
break
case 'disconnected':
console.debug('Disconnected.', peer.id, peer)
handleIceConnectionStateDisconnected(peer)
break
case 'failed':
console.debug('Connection failed.', peer.id, peer)
handleIceConnectionStateFailed(peer)
break
case 'closed':
console.debug('Connection closed.', peer.id, 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 setHandlerForSignalingStateChange(peer) {
peer.pc.addEventListener('signalingstatechange', function() {
peer.emit('signalingStateChange', peer.pc.signalingState)
})
}
/**
* @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.id, peer)
break
case 'connected':
case 'completed':
console.debug('Connection established (own peer).', peer.id, peer)
break
case 'disconnected':
console.debug('Disconnected (own peer).', peer.id, 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.id, peer)
break
case 'closed':
console.debug('Connection closed (own peer).', peer.id, peer)
break
}
})
}
const forceReconnect = function(signaling, flags) {
if (ownPeer) {
if (delayedConnectionToPeer[ownPeer.id]) {
clearInterval(delayedConnectionToPeer[ownPeer.id])
delete delayedConnectionToPeer[ownPeer.id]
}
ownPeer.end()
}
usersChanged(signaling, [], previousUsersInRoom)
usersInCallMapping = {}
// 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() {
// When the HPB is used and the negotiation is needed for a receiver
// peer (for example, to block the received video) there is no need
// to force a full reconnection, it is enough to reconnect only that
// peer.
if (signaling.hasFeature('mcu') && peer.id !== signaling.getSessionId()) {
// If possible update connection rather than creating a new one.
let update = signaling.hasFeature('update-sdp')
// Create a connection if the current one has failed, as it
// would require an ICE restart rather than update to recover.
if (update && (peer.pc.iceConnectionState === 'failed' || peer.pc.connectionState === 'failed')) {
update = false
}
// If the connection needs to be updated but a new connection
// (or another update) is already pending ignore the new update.
// If a new connection needs to be created rather than updated
// then force it even if there is another one already pending.
if (update && delayedConnectionToPeer[peer.id]) {
return
}
signaling.requestOffer(peer.id, 'video', update ? peer.sid : undefined)
clearInterval(delayedConnectionToPeer[peer.id])
delayedConnectionToPeer[peer.id] = setInterval(function() {
console.debug('No offer received, request offer again' + update ? '(update)' : '', peer.id, peer)