-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
calling.ts
1501 lines (1317 loc) · 44.9 KB
/
calling.ts
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 2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
/* eslint-disable class-methods-use-this */
import {
Call,
CallEndedReason,
CallId,
CallingMessage,
CallLogLevel,
CallSettings,
CallState,
CanvasVideoRenderer,
ConnectionState,
JoinState,
HttpMethod,
DeviceId,
GroupCall,
GroupMemberInfo,
GumVideoCapturer,
HangupMessage,
HangupType,
OfferType,
OpaqueMessage,
PeekInfo,
RingRTC,
UserId,
VideoFrameSource,
VideoRequest,
} from 'ringrtc';
import { uniqBy, noop } from 'lodash';
import {
ActionsType as UxActionsType,
GroupCallPeekInfoType,
} from '../state/ducks/calling';
import { getConversationCallMode } from '../state/ducks/conversations';
import { EnvelopeClass } from '../textsecure.d';
import {
CallMode,
AudioDevice,
MediaDeviceSettings,
GroupCallConnectionState,
GroupCallJoinState,
} from '../types/Calling';
import { ConversationModel } from '../models/conversations';
import {
base64ToArrayBuffer,
uuidToArrayBuffer,
arrayBufferToUuid,
} from '../Crypto';
import { getOwn } from '../util/getOwn';
import { fetchMembershipProof, getMembershipList } from '../groups';
import { missingCaseError } from '../util/missingCaseError';
import { normalizeGroupCallTimestamp } from '../util/ringrtc/normalizeGroupCallTimestamp';
const RINGRTC_HTTP_METHOD_TO_OUR_HTTP_METHOD: Map<
HttpMethod,
'GET' | 'PUT' | 'POST' | 'DELETE'
> = new Map([
[HttpMethod.Get, 'GET'],
[HttpMethod.Put, 'PUT'],
[HttpMethod.Post, 'POST'],
[HttpMethod.Delete, 'DELETE'],
]);
// We send group call update messages to tell other clients to peek, which triggers
// notifications, timeline messages, big green "Join" buttons, and so on. This enum
// represents the three possible states we can be in. This helps ensure that we don't
// send an update on disconnect if we never sent one when we joined.
enum GroupCallUpdateMessageState {
SentNothing,
SentJoin,
SentLeft,
}
export {
CallState,
CanvasVideoRenderer,
GumVideoCapturer,
VideoCapturer,
VideoRenderer,
} from 'ringrtc';
export class CallingClass {
readonly videoCapturer: GumVideoCapturer;
readonly videoRenderer: CanvasVideoRenderer;
private uxActions?: UxActionsType;
private sfuUrl?: string;
private lastMediaDeviceSettings?: MediaDeviceSettings;
private deviceReselectionTimer?: NodeJS.Timeout;
private callsByConversation: { [conversationId: string]: Call | GroupCall };
constructor() {
this.videoCapturer = new GumVideoCapturer(640, 480, 30);
this.videoRenderer = new CanvasVideoRenderer();
this.callsByConversation = {};
}
initialize(uxActions: UxActionsType, sfuUrl: string): void {
this.uxActions = uxActions;
if (!uxActions) {
throw new Error('CallingClass.initialize: Invalid uxActions.');
}
this.sfuUrl = sfuUrl;
RingRTC.handleOutgoingSignaling = this.handleOutgoingSignaling.bind(this);
RingRTC.handleIncomingCall = this.handleIncomingCall.bind(this);
RingRTC.handleAutoEndedIncomingCallRequest = this.handleAutoEndedIncomingCallRequest.bind(
this
);
RingRTC.handleLogMessage = this.handleLogMessage.bind(this);
RingRTC.handleSendHttpRequest = this.handleSendHttpRequest.bind(this);
RingRTC.handleSendCallMessage = this.handleSendCallMessage.bind(this);
}
async startCallingLobby(
conversation: ConversationModel,
isVideoCall: boolean
): Promise<void> {
window.log.info('CallingClass.startCallingLobby()');
const conversationProps = conversation.format();
const callMode = getConversationCallMode(conversationProps);
switch (callMode) {
case CallMode.None:
window.log.error(
'Conversation does not support calls, new call not allowed.'
);
return;
case CallMode.Direct:
if (!this.getRemoteUserIdFromConversation(conversation)) {
window.log.error(
'Missing remote user identifier, new call not allowed.'
);
return;
}
break;
case CallMode.Group:
break;
default:
throw missingCaseError(callMode);
}
if (!this.uxActions) {
window.log.error('Missing uxActions, new call not allowed.');
return;
}
if (!this.localDeviceId) {
window.log.error(
'Missing local device identifier, new call not allowed.'
);
return;
}
const haveMediaPermissions = await this.requestPermissions(isVideoCall);
if (!haveMediaPermissions) {
window.log.info('Permissions were denied, new call not allowed.');
return;
}
window.log.info('CallingClass.startCallingLobby(): Starting lobby');
switch (callMode) {
case CallMode.Direct:
this.uxActions.showCallLobby({
callMode: CallMode.Direct,
conversationId: conversationProps.id,
hasLocalAudio: true,
hasLocalVideo: isVideoCall,
});
break;
case CallMode.Group: {
if (
!conversationProps.groupId ||
!conversationProps.publicParams ||
!conversationProps.secretParams
) {
window.log.error(
'Conversation is missing required parameters. Cannot connect group call'
);
return;
}
const groupCall = this.connectGroupCall(conversationProps.id, {
groupId: conversationProps.groupId,
publicParams: conversationProps.publicParams,
secretParams: conversationProps.secretParams,
});
groupCall.setOutgoingAudioMuted(false);
groupCall.setOutgoingVideoMuted(!isVideoCall);
this.uxActions.showCallLobby({
callMode: CallMode.Group,
conversationId: conversationProps.id,
...this.formatGroupCallForRedux(groupCall),
});
break;
}
default:
throw missingCaseError(callMode);
}
await this.startDeviceReselectionTimer();
if (isVideoCall) {
this.enableLocalCamera();
}
}
stopCallingLobby(conversationId?: string): void {
this.disableLocalCamera();
this.stopDeviceReselectionTimer();
this.lastMediaDeviceSettings = undefined;
if (conversationId) {
this.getGroupCall(conversationId)?.disconnect();
}
}
async startOutgoingDirectCall(
conversationId: string,
hasLocalAudio: boolean,
hasLocalVideo: boolean
): Promise<void> {
window.log.info('CallingClass.startOutgoingDirectCall()');
if (!this.uxActions) {
throw new Error('Redux actions not available');
}
const conversation = window.ConversationController.get(conversationId);
if (!conversation) {
window.log.error('Could not find conversation, cannot start call');
this.stopCallingLobby();
return;
}
const remoteUserId = this.getRemoteUserIdFromConversation(conversation);
if (!remoteUserId || !this.localDeviceId) {
window.log.error('Missing identifier, new call not allowed.');
this.stopCallingLobby();
return;
}
const haveMediaPermissions = await this.requestPermissions(hasLocalVideo);
if (!haveMediaPermissions) {
window.log.info('Permissions were denied, new call not allowed.');
this.stopCallingLobby();
return;
}
window.log.info(
'CallingClass.startOutgoingDirectCall(): Getting call settings'
);
const callSettings = await this.getCallSettings(conversation);
// Check state after awaiting to debounce call button.
if (RingRTC.call && RingRTC.call.state !== CallState.Ended) {
window.log.info('Call already in progress, new call not allowed.');
this.stopCallingLobby();
return;
}
window.log.info(
'CallingClass.startOutgoingDirectCall(): Starting in RingRTC'
);
// We could make this faster by getting the call object
// from the RingRTC before we lookup the ICE servers.
const call = RingRTC.startOutgoingCall(
remoteUserId,
hasLocalVideo,
this.localDeviceId,
callSettings
);
RingRTC.setOutgoingAudio(call.callId, hasLocalAudio);
RingRTC.setVideoCapturer(call.callId, this.videoCapturer);
RingRTC.setVideoRenderer(call.callId, this.videoRenderer);
this.attachToCall(conversation, call);
this.uxActions.outgoingCall({
conversationId: conversation.id,
hasLocalAudio,
hasLocalVideo,
});
await this.startDeviceReselectionTimer();
}
private getDirectCall(conversationId: string): undefined | Call {
const call = getOwn(this.callsByConversation, conversationId);
return call instanceof Call ? call : undefined;
}
private getGroupCall(conversationId: string): undefined | GroupCall {
const call = getOwn(this.callsByConversation, conversationId);
return call instanceof GroupCall ? call : undefined;
}
private getGroupCallMembers(conversationId: string) {
return getMembershipList(conversationId).map(
member =>
new GroupMemberInfo(
uuidToArrayBuffer(member.uuid),
member.uuidCiphertext
)
);
}
public async peekGroupCall(conversationId: string): Promise<PeekInfo> {
// This can be undefined in two cases:
//
// 1. There is no group call instance. This is "stateless peeking", and is expected
// when we want to peek on a call that we've never connected to.
// 2. There is a group call instance but RingRTC doesn't have the peek info yet. This
// should only happen for a brief period as you connect to the call. (You probably
// don't want to call this function while a group call is connected—you should
// instead be grabbing the peek info off of the instance—but we handle it here
// to avoid possible race conditions.)
const statefulPeekInfo = this.getGroupCall(conversationId)?.getPeekInfo();
if (statefulPeekInfo) {
return statefulPeekInfo;
}
if (!this.sfuUrl) {
throw new Error('Missing SFU URL; not peeking group call');
}
const conversation = window.ConversationController.get(conversationId);
if (!conversation) {
throw new Error('Missing conversation; not peeking group call');
}
const publicParams = conversation.get('publicParams');
const secretParams = conversation.get('secretParams');
if (!publicParams || !secretParams) {
throw new Error(
'Conversation is missing required parameters. Cannot peek group call'
);
}
const proof = await fetchMembershipProof({ publicParams, secretParams });
if (!proof) {
throw new Error('No membership proof. Cannot peek group call');
}
const membershipProof = new TextEncoder().encode(proof).buffer;
return RingRTC.peekGroupCall(
this.sfuUrl,
membershipProof,
this.getGroupCallMembers(conversationId)
);
}
/**
* Connect to a conversation's group call and connect it to Redux.
*
* Should only be called with group call-compatible conversations.
*
* Idempotent.
*/
connectGroupCall(
conversationId: string,
{
groupId,
publicParams,
secretParams,
}: {
groupId: string;
publicParams: string;
secretParams: string;
}
): GroupCall {
const existing = this.getGroupCall(conversationId);
if (existing) {
const isExistingCallNotConnected =
existing.getLocalDeviceState().connectionState ===
ConnectionState.NotConnected;
if (isExistingCallNotConnected) {
existing.connect();
}
return existing;
}
if (!this.sfuUrl) {
throw new Error('Missing SFU URL; not connecting group call');
}
const groupIdBuffer = base64ToArrayBuffer(groupId);
let updateMessageState = GroupCallUpdateMessageState.SentNothing;
let isRequestingMembershipProof = false;
const outerGroupCall = RingRTC.getGroupCall(groupIdBuffer, this.sfuUrl, {
onLocalDeviceStateChanged: groupCall => {
const localDeviceState = groupCall.getLocalDeviceState();
const { eraId } = groupCall.getPeekInfo() || {};
if (localDeviceState.connectionState === ConnectionState.NotConnected) {
// NOTE: This assumes that only one call is active at a time. For example, if
// there are two calls using the camera, this will disable both of them.
// That's fine for now, but this will break if that assumption changes.
this.disableLocalCamera();
delete this.callsByConversation[conversationId];
if (
updateMessageState === GroupCallUpdateMessageState.SentJoin &&
eraId
) {
updateMessageState = GroupCallUpdateMessageState.SentLeft;
this.sendGroupCallUpdateMessage(conversationId, eraId);
}
} else {
this.callsByConversation[conversationId] = groupCall;
// NOTE: This assumes only one active call at a time. See comment above.
if (localDeviceState.videoMuted) {
this.disableLocalCamera();
} else {
this.videoCapturer.enableCaptureAndSend(groupCall);
}
if (
updateMessageState === GroupCallUpdateMessageState.SentNothing &&
localDeviceState.joinState === JoinState.Joined &&
eraId
) {
updateMessageState = GroupCallUpdateMessageState.SentJoin;
this.sendGroupCallUpdateMessage(conversationId, eraId);
}
}
this.syncGroupCallToRedux(conversationId, groupCall);
},
onRemoteDeviceStatesChanged: groupCall => {
this.syncGroupCallToRedux(conversationId, groupCall);
},
onPeekChanged: groupCall => {
this.syncGroupCallToRedux(conversationId, groupCall);
},
async requestMembershipProof(groupCall) {
if (isRequestingMembershipProof) {
return;
}
isRequestingMembershipProof = true;
try {
const proof = await fetchMembershipProof({
publicParams,
secretParams,
});
if (proof) {
const proofArray = new TextEncoder().encode(proof);
groupCall.setMembershipProof(proofArray.buffer);
}
} catch (err) {
window.log.error('Failed to fetch membership proof', err);
} finally {
isRequestingMembershipProof = false;
}
},
requestGroupMembers: groupCall => {
groupCall.setGroupMembers(this.getGroupCallMembers(conversationId));
},
onEnded: noop,
});
if (!outerGroupCall) {
// This should be very rare, likely due to RingRTC not being able to get a lock
// or memory or something like that.
throw new Error('Failed to get a group call instance; cannot start call');
}
outerGroupCall.connect();
this.syncGroupCallToRedux(conversationId, outerGroupCall);
return outerGroupCall;
}
public joinGroupCall(
conversationId: string,
hasLocalAudio: boolean,
hasLocalVideo: boolean
): void {
const conversation = window.ConversationController.get(
conversationId
)?.format();
if (!conversation) {
window.log.error('Missing conversation; not joining group call');
return;
}
if (
!conversation.groupId ||
!conversation.publicParams ||
!conversation.secretParams
) {
window.log.error(
'Conversation is missing required parameters. Cannot join group call'
);
return;
}
const groupCall = this.connectGroupCall(conversationId, {
groupId: conversation.groupId,
publicParams: conversation.publicParams,
secretParams: conversation.secretParams,
});
groupCall.setOutgoingAudioMuted(!hasLocalAudio);
groupCall.setOutgoingVideoMuted(!hasLocalVideo);
this.videoCapturer.enableCaptureAndSend(groupCall);
groupCall.join();
}
private getCallIdForConversation(conversationId: string): undefined | CallId {
return this.getDirectCall(conversationId)?.callId;
}
public setGroupCallVideoRequest(
conversationId: string,
resolutions: Array<VideoRequest>
): void {
this.getGroupCall(conversationId)?.requestVideo(resolutions);
}
// See the comment in types/Calling.ts to explain why we have to do this conversion.
private convertRingRtcConnectionState(
connectionState: ConnectionState
): GroupCallConnectionState {
switch (connectionState) {
case ConnectionState.NotConnected:
return GroupCallConnectionState.NotConnected;
case ConnectionState.Connecting:
return GroupCallConnectionState.Connecting;
case ConnectionState.Connected:
return GroupCallConnectionState.Connected;
case ConnectionState.Reconnecting:
return GroupCallConnectionState.Reconnecting;
default:
throw missingCaseError(connectionState);
}
}
// See the comment in types/Calling.ts to explain why we have to do this conversion.
private convertRingRtcJoinState(joinState: JoinState): GroupCallJoinState {
switch (joinState) {
case JoinState.NotJoined:
return GroupCallJoinState.NotJoined;
case JoinState.Joining:
return GroupCallJoinState.Joining;
case JoinState.Joined:
return GroupCallJoinState.Joined;
default:
throw missingCaseError(joinState);
}
}
public formatGroupCallPeekInfoForRedux(
peekInfo: PeekInfo
): GroupCallPeekInfoType {
return {
uuids: peekInfo.joinedMembers.map(uuidBuffer => {
let uuid = arrayBufferToUuid(uuidBuffer);
if (!uuid) {
window.log.error(
'Calling.formatGroupCallPeekInfoForRedux: could not convert peek UUID ArrayBuffer to string; using fallback UUID'
);
uuid = '00000000-0000-0000-0000-000000000000';
}
return uuid;
}),
creatorUuid: peekInfo.creator && arrayBufferToUuid(peekInfo.creator),
eraId: peekInfo.eraId,
maxDevices: peekInfo.maxDevices ?? Infinity,
deviceCount: peekInfo.deviceCount,
};
}
private formatGroupCallForRedux(groupCall: GroupCall) {
const localDeviceState = groupCall.getLocalDeviceState();
const peekInfo = groupCall.getPeekInfo();
// RingRTC doesn't ensure that the demux ID is unique. This can happen if someone
// leaves the call and quickly rejoins; RingRTC will tell us that there are two
// participants with the same demux ID in the call. This should be rare.
const remoteDeviceStates = uniqBy(
groupCall.getRemoteDeviceStates() || [],
remoteDeviceState => remoteDeviceState.demuxId
);
// It should be impossible to be disconnected and Joining or Joined. Just in case, we
// try to handle that case.
const joinState: GroupCallJoinState =
localDeviceState.connectionState === ConnectionState.NotConnected
? GroupCallJoinState.NotJoined
: this.convertRingRtcJoinState(localDeviceState.joinState);
return {
connectionState: this.convertRingRtcConnectionState(
localDeviceState.connectionState
),
joinState,
hasLocalAudio: !localDeviceState.audioMuted,
hasLocalVideo: !localDeviceState.videoMuted,
peekInfo: peekInfo
? this.formatGroupCallPeekInfoForRedux(peekInfo)
: undefined,
remoteParticipants: remoteDeviceStates.map(remoteDeviceState => {
let uuid = arrayBufferToUuid(remoteDeviceState.userId);
if (!uuid) {
window.log.error(
'Calling.formatGroupCallForRedux: could not convert remote participant UUID ArrayBuffer to string; using fallback UUID'
);
uuid = '00000000-0000-0000-0000-000000000000';
}
return {
uuid,
demuxId: remoteDeviceState.demuxId,
hasRemoteAudio: !remoteDeviceState.audioMuted,
hasRemoteVideo: !remoteDeviceState.videoMuted,
speakerTime: normalizeGroupCallTimestamp(
remoteDeviceState.speakerTime
),
// If RingRTC doesn't send us an aspect ratio, we make a guess.
videoAspectRatio:
remoteDeviceState.videoAspectRatio ||
(remoteDeviceState.videoMuted ? 1 : 4 / 3),
};
}),
};
}
public getGroupCallVideoFrameSource(
conversationId: string,
demuxId: number
): VideoFrameSource {
const groupCall = this.getGroupCall(conversationId);
if (!groupCall) {
throw new Error('Could not find matching call');
}
return groupCall.getVideoSource(demuxId);
}
private syncGroupCallToRedux(
conversationId: string,
groupCall: GroupCall
): void {
this.uxActions?.groupCallStateChange({
conversationId,
...this.formatGroupCallForRedux(groupCall),
});
}
private sendGroupCallUpdateMessage(
conversationId: string,
eraId: string
): void {
const conversation = window.ConversationController.get(conversationId);
if (!conversation) {
window.log.error(
'Unable to send group call update message for non-existent conversation'
);
return;
}
const groupV2 = conversation.getGroupV2Info();
const sendOptions = conversation.getSendOptions();
if (!groupV2) {
window.log.error(
'Unable to send group call update message for conversation that lacks groupV2 info'
);
return;
}
// We "fire and forget" because sending this message is non-essential.
window.textsecure.messaging
.sendGroupCallUpdate({ eraId, groupV2 }, sendOptions)
.catch(err => {
window.log.error('Failed to send group call update', err);
});
}
async accept(conversationId: string, asVideoCall: boolean): Promise<void> {
window.log.info('CallingClass.accept()');
const callId = this.getCallIdForConversation(conversationId);
if (!callId) {
window.log.warn('Trying to accept a non-existent call');
return;
}
const haveMediaPermissions = await this.requestPermissions(asVideoCall);
if (haveMediaPermissions) {
await this.startDeviceReselectionTimer();
RingRTC.setVideoCapturer(callId, this.videoCapturer);
RingRTC.setVideoRenderer(callId, this.videoRenderer);
RingRTC.accept(callId, asVideoCall);
} else {
window.log.info('Permissions were denied, call not allowed, hanging up.');
RingRTC.hangup(callId);
}
}
decline(conversationId: string): void {
window.log.info('CallingClass.decline()');
const callId = this.getCallIdForConversation(conversationId);
if (!callId) {
window.log.warn('Trying to decline a non-existent call');
return;
}
RingRTC.decline(callId);
}
hangup(conversationId: string): void {
window.log.info('CallingClass.hangup()');
const call = getOwn(this.callsByConversation, conversationId);
if (!call) {
window.log.warn('Trying to hang up a non-existent call');
return;
}
if (call instanceof Call) {
RingRTC.hangup(call.callId);
} else if (call instanceof GroupCall) {
// This ensures that we turn off our devices.
call.setOutgoingAudioMuted(true);
call.setOutgoingVideoMuted(true);
call.disconnect();
} else {
throw missingCaseError(call);
}
}
setOutgoingAudio(conversationId: string, enabled: boolean): void {
const call = getOwn(this.callsByConversation, conversationId);
if (!call) {
window.log.warn('Trying to set outgoing audio for a non-existent call');
return;
}
if (call instanceof Call) {
RingRTC.setOutgoingAudio(call.callId, enabled);
} else if (call instanceof GroupCall) {
call.setOutgoingAudioMuted(!enabled);
} else {
throw missingCaseError(call);
}
}
setOutgoingVideo(conversationId: string, enabled: boolean): void {
const call = getOwn(this.callsByConversation, conversationId);
if (!call) {
window.log.warn('Trying to set outgoing video for a non-existent call');
return;
}
if (call instanceof Call) {
RingRTC.setOutgoingVideo(call.callId, enabled);
} else if (call instanceof GroupCall) {
call.setOutgoingVideoMuted(!enabled);
} else {
throw missingCaseError(call);
}
}
private async startDeviceReselectionTimer(): Promise<void> {
// Poll once
await this.pollForMediaDevices();
// Start the timer
if (!this.deviceReselectionTimer) {
this.deviceReselectionTimer = setInterval(async () => {
await this.pollForMediaDevices();
}, 3000);
}
}
private stopDeviceReselectionTimer() {
if (this.deviceReselectionTimer) {
clearInterval(this.deviceReselectionTimer);
this.deviceReselectionTimer = undefined;
}
}
private mediaDeviceSettingsEqual(
a?: MediaDeviceSettings,
b?: MediaDeviceSettings
): boolean {
if (!a && !b) {
return true;
}
if (!a || !b) {
return false;
}
if (
a.availableCameras.length !== b.availableCameras.length ||
a.availableMicrophones.length !== b.availableMicrophones.length ||
a.availableSpeakers.length !== b.availableSpeakers.length
) {
return false;
}
for (let i = 0; i < a.availableCameras.length; i += 1) {
if (
a.availableCameras[i].deviceId !== b.availableCameras[i].deviceId ||
a.availableCameras[i].groupId !== b.availableCameras[i].groupId ||
a.availableCameras[i].label !== b.availableCameras[i].label
) {
return false;
}
}
for (let i = 0; i < a.availableMicrophones.length; i += 1) {
if (
a.availableMicrophones[i].name !== b.availableMicrophones[i].name ||
a.availableMicrophones[i].uniqueId !==
b.availableMicrophones[i].uniqueId
) {
return false;
}
}
for (let i = 0; i < a.availableSpeakers.length; i += 1) {
if (
a.availableSpeakers[i].name !== b.availableSpeakers[i].name ||
a.availableSpeakers[i].uniqueId !== b.availableSpeakers[i].uniqueId
) {
return false;
}
}
if (
(a.selectedCamera && !b.selectedCamera) ||
(!a.selectedCamera && b.selectedCamera) ||
(a.selectedMicrophone && !b.selectedMicrophone) ||
(!a.selectedMicrophone && b.selectedMicrophone) ||
(a.selectedSpeaker && !b.selectedSpeaker) ||
(!a.selectedSpeaker && b.selectedSpeaker)
) {
return false;
}
if (
a.selectedCamera &&
b.selectedCamera &&
a.selectedCamera !== b.selectedCamera
) {
return false;
}
if (
a.selectedMicrophone &&
b.selectedMicrophone &&
a.selectedMicrophone.index !== b.selectedMicrophone.index
) {
return false;
}
if (
a.selectedSpeaker &&
b.selectedSpeaker &&
a.selectedSpeaker.index !== b.selectedSpeaker.index
) {
return false;
}
return true;
}
private async pollForMediaDevices(): Promise<void> {
const newSettings = await this.getMediaDeviceSettings();
if (
!this.mediaDeviceSettingsEqual(this.lastMediaDeviceSettings, newSettings)
) {
window.log.info(
'MediaDevice: available devices changed (from->to)',
this.lastMediaDeviceSettings,
newSettings
);
await this.selectPreferredDevices(newSettings);
this.lastMediaDeviceSettings = newSettings;
this.uxActions?.refreshIODevices(newSettings);
}
}
async getMediaDeviceSettings(): Promise<MediaDeviceSettings> {
const availableMicrophones = RingRTC.getAudioInputs();
const preferredMicrophone = window.storage.get(
'preferred-audio-input-device'
);
const selectedMicIndex = this.findBestMatchingDeviceIndex(
availableMicrophones,
preferredMicrophone
);
const selectedMicrophone =
selectedMicIndex !== undefined
? availableMicrophones[selectedMicIndex]
: undefined;
const availableSpeakers = RingRTC.getAudioOutputs();
const preferredSpeaker = window.storage.get(
'preferred-audio-output-device'
);
const selectedSpeakerIndex = this.findBestMatchingDeviceIndex(
availableSpeakers,
preferredSpeaker
);
const selectedSpeaker =
selectedSpeakerIndex !== undefined
? availableSpeakers[selectedSpeakerIndex]
: undefined;
const availableCameras = await this.videoCapturer.enumerateDevices();
const preferredCamera = window.storage.get('preferred-video-input-device');
const selectedCamera = this.findBestMatchingCamera(
availableCameras,
preferredCamera
);
return {
availableMicrophones,
availableSpeakers,
selectedMicrophone,
selectedSpeaker,
availableCameras,
selectedCamera,
};
}
findBestMatchingDeviceIndex(
available: Array<AudioDevice>,
preferred: AudioDevice | undefined
): number | undefined {
if (preferred) {
// Match by uniqueId first, if available
if (preferred.uniqueId) {
const matchIndex = available.findIndex(
d => d.uniqueId === preferred.uniqueId
);
if (matchIndex !== -1) {
return matchIndex;
}
}
// Match by name second
const matchingNames = available.filter(d => d.name === preferred.name);
if (matchingNames.length > 0) {
return matchingNames[0].index;
}
}
// Nothing matches or no preference; take the first device if there are any
return available.length > 0 ? 0 : undefined;
}
findBestMatchingCamera(
available: Array<MediaDeviceInfo>,
preferred?: string
): string | undefined {
const matchingId = available.filter(d => d.deviceId === preferred);
const nonInfrared = available.filter(d => !d.label.includes('IR Camera'));
// By default, pick the first non-IR camera (but allow the user to pick the
// infrared if they so desire)
if (matchingId.length > 0) {
return matchingId[0].deviceId;
}
if (nonInfrared.length > 0) {
return nonInfrared[0].deviceId;
}
return undefined;
}
setPreferredMicrophone(device: AudioDevice): void {
window.log.info('MediaDevice: setPreferredMicrophone', device);
window.storage.put('preferred-audio-input-device', device);
RingRTC.setAudioInput(device.index);
}
setPreferredSpeaker(device: AudioDevice): void {
window.log.info('MediaDevice: setPreferredSpeaker', device);
window.storage.put('preferred-audio-output-device', device);
RingRTC.setAudioOutput(device.index);
}
enableLocalCamera(): void {
this.videoCapturer.enableCapture();
}
disableLocalCamera(): void {