-
-
Notifications
You must be signed in to change notification settings - Fork 592
/
call.ts
2448 lines (2098 loc) · 90.4 KB
/
call.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 2015, 2016 OpenMarket Ltd
Copyright 2017 New Vector Ltd
Copyright 2019, 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* This is an internal module. See {@link createNewMatrixCall} for the public API.
* @module webrtc/call
*/
import { logger } from '../logger';
import { EventEmitter } from 'events';
import * as utils from '../utils';
import { MatrixEvent } from '../models/event';
import { EventType } from '../@types/event';
import { RoomMember } from '../models/room-member';
import { randomString } from '../randomstring';
import {
MCallReplacesEvent,
MCallAnswer,
MCallInviteNegotiate,
CallCapabilities,
SDPStreamMetadataPurpose,
SDPStreamMetadata,
SDPStreamMetadataKey,
MCallSDPStreamMetadataChanged,
MCallSelectAnswer,
MCAllAssertedIdentity,
MCallCandidates,
MCallBase,
MCallHangupReject,
} from './callEventTypes';
import { CallFeed } from './callFeed';
import { MatrixClient } from "../client";
import { ISendEventResponse } from "../@types/requests";
// events: hangup, error(err), replaced(call), state(state, oldState)
/**
* Fires whenever an error occurs when call.js encounters an issue with setting up the call.
* <p>
* The error given will have a code equal to either `MatrixCall.ERR_LOCAL_OFFER_FAILED` or
* `MatrixCall.ERR_NO_USER_MEDIA`. `ERR_LOCAL_OFFER_FAILED` is emitted when the local client
* fails to create an offer. `ERR_NO_USER_MEDIA` is emitted when the user has denied access
* to their audio/video hardware.
*
* @event module:webrtc/call~MatrixCall#"error"
* @param {Error} err The error raised by MatrixCall.
* @example
* matrixCall.on("error", function(err){
* console.error(err.code, err);
* });
*/
interface CallOpts {
roomId?: string;
invitee?: string;
client?: any; // Fix when client is TSified
forceTURN?: boolean;
turnServers?: Array<TurnServer>;
opponentDeviceId?: string;
opponentSessionId?: string;
groupCallId?: string;
}
interface TurnServer {
urls: Array<string>;
username?: string;
password?: string;
ttl?: number;
}
interface AssertedIdentity {
id: string;
displayName: string;
}
export enum CallState {
Fledgling = 'fledgling',
InviteSent = 'invite_sent',
WaitLocalMedia = 'wait_local_media',
CreateOffer = 'create_offer',
CreateAnswer = 'create_answer',
Connecting = 'connecting',
Connected = 'connected',
Ringing = 'ringing',
Ended = 'ended',
}
export enum CallType {
Voice = 'voice',
Video = 'video',
}
export enum CallDirection {
Inbound = 'inbound',
Outbound = 'outbound',
}
export enum CallParty {
Local = 'local',
Remote = 'remote',
}
export enum CallEvent {
Hangup = 'hangup',
State = 'state',
Error = 'error',
Replaced = 'replaced',
// The value of isLocalOnHold() has changed
LocalHoldUnhold = 'local_hold_unhold',
// The value of isRemoteOnHold() has changed
RemoteHoldUnhold = 'remote_hold_unhold',
// backwards compat alias for LocalHoldUnhold: remove in a major version bump
HoldUnhold = 'hold_unhold',
// Feeds have changed
FeedsChanged = 'feeds_changed',
AssertedIdentityChanged = 'asserted_identity_changed',
LengthChanged = 'length_changed',
DataChannel = 'datachannel',
SendVoipEvent = "send_voip_event",
}
export enum CallErrorCode {
/** The user chose to end the call */
UserHangup = 'user_hangup',
/** An error code when the local client failed to create an offer. */
LocalOfferFailed = 'local_offer_failed',
/**
* An error code when there is no local mic/camera to use. This may be because
* the hardware isn't plugged in, or the user has explicitly denied access.
*/
NoUserMedia = 'no_user_media',
/**
* Error code used when a call event failed to send
* because unknown devices were present in the room
*/
UnknownDevices = 'unknown_devices',
/**
* Error code used when we fail to send the invite
* for some reason other than there being unknown devices
*/
SendInvite = 'send_invite',
/**
* An answer could not be created
*/
CreateAnswer = 'create_answer',
/**
* Error code used when we fail to send the answer
* for some reason other than there being unknown devices
*/
SendAnswer = 'send_answer',
/**
* The session description from the other side could not be set
*/
SetRemoteDescription = 'set_remote_description',
/**
* The session description from this side could not be set
*/
SetLocalDescription = 'set_local_description',
/**
* A different device answered the call
*/
AnsweredElsewhere = 'answered_elsewhere',
/**
* No media connection could be established to the other party
*/
IceFailed = 'ice_failed',
/**
* The invite timed out whilst waiting for an answer
*/
InviteTimeout = 'invite_timeout',
/**
* The call was replaced by another call
*/
Replaced = 'replaced',
/**
* Signalling for the call could not be sent (other than the initial invite)
*/
SignallingFailed = 'signalling_timeout',
/**
* The remote party is busy
*/
UserBusy = 'user_busy',
/**
* We transferred the call off to somewhere else
*/
Transfered = 'transferred',
/**
* A call from the same user was found with a new session id
*/
NewSession = 'new_session',
}
/**
* The version field that we set in m.call.* events
*/
const VOIP_PROTO_VERSION = 1;
/** The fallback ICE server to use for STUN or TURN protocols. */
const FALLBACK_ICE_SERVER = 'stun:turn.matrix.org';
/** The length of time a call can be ringing for. */
const CALL_TIMEOUT_MS = 60000;
export class CallError extends Error {
code: string;
constructor(code: CallErrorCode, msg: string, err: Error) {
// Still don't think there's any way to have proper nested errors
super(msg + ": " + err);
this.code = code;
}
}
export function genCallID(): string {
return Date.now().toString() + randomString(16);
}
/**
* Construct a new Matrix Call.
* @constructor
* @param {Object} opts Config options.
* @param {string} opts.roomId The room ID for this call.
* @param {Object} opts.webRtc The WebRTC globals from the browser.
* @param {boolean} opts.forceTURN whether relay through TURN should be forced.
* @param {Object} opts.URL The URL global.
* @param {Array<Object>} opts.turnServers Optional. A list of TURN servers.
* @param {MatrixClient} opts.client The Matrix Client instance to send events to.
*/
export class MatrixCall extends EventEmitter {
public roomId: string;
public callId: string;
public invitee?: string;
public state = CallState.Fledgling;
public hangupParty: CallParty;
public hangupReason: string;
public direction: CallDirection;
public ourPartyId: string;
public peerConn?: RTCPeerConnection;
public toDeviceSeq = 0;
private client: MatrixClient;
private forceTURN: boolean;
private turnServers: Array<TurnServer>;
// A queue for candidates waiting to go out.
// We try to amalgamate candidates into a single candidate message where
// possible
private candidateSendQueue: Array<RTCIceCandidate> = [];
private candidateSendTries = 0;
private sentEndOfCandidates = false;
private feeds: Array<CallFeed> = [];
private usermediaSenders: Array<RTCRtpSender> = [];
private screensharingSenders: Array<RTCRtpSender> = [];
private inviteOrAnswerSent = false;
private waitForLocalAVStream: boolean;
private successor: MatrixCall;
private opponentMember: RoomMember;
private opponentVersion: number | string;
// The party ID of the other side: undefined if we haven't chosen a partner
// yet, null if we have but they didn't send a party ID.
private opponentPartyId: string;
private opponentCaps: CallCapabilities;
private inviteTimeout: number;
private iceDisconnectedTimeout: number;
// The logic of when & if a call is on hold is nontrivial and explained in is*OnHold
// This flag represents whether we want the other party to be on hold
private remoteOnHold = false;
// the stats for the call at the point it ended. We can't get these after we
// tear the call down, so we just grab a snapshot before we stop the call.
// The typescript definitions have this type as 'any' :(
private callStatsAtEnd: any[];
// Perfect negotiation state: https://www.w3.org/TR/webrtc/#perfect-negotiation-example
private makingOffer = false;
private ignoreOffer: boolean;
private responsePromiseChain?: Promise<void>;
// If candidates arrive before we've picked an opponent (which, in particular,
// will happen if the opponent sends candidates eagerly before the user answers
// the call) we buffer them up here so we can then add the ones from the party we pick
private remoteCandidateBuffer = new Map<string, RTCIceCandidate[]>();
private remoteAssertedIdentity: AssertedIdentity;
private remoteSDPStreamMetadata: SDPStreamMetadata;
private callLengthInterval: number;
private callLength = 0;
private opponentDeviceId: string;
private opponentSessionId: string;
public groupCallId: string;
constructor(opts: CallOpts) {
super();
this.roomId = opts.roomId;
this.invitee = opts.invitee;
this.client = opts.client;
this.forceTURN = opts.forceTURN;
this.ourPartyId = this.client.deviceId;
this.opponentDeviceId = opts.opponentDeviceId;
this.opponentSessionId = opts.opponentSessionId;
this.groupCallId = opts.groupCallId;
// Array of Objects with urls, username, credential keys
this.turnServers = opts.turnServers || [];
if (this.turnServers.length === 0 && this.client.isFallbackICEServerAllowed()) {
this.turnServers.push({
urls: [FALLBACK_ICE_SERVER],
});
}
for (const server of this.turnServers) {
utils.checkObjectHasKeys(server, ["urls"]);
}
this.callId = genCallID();
}
/**
* Place a voice call to this room.
* @throws If you have not specified a listener for 'error' events.
*/
public async placeVoiceCall(): Promise<void> {
await this.placeCall(true, false);
}
/**
* Place a video call to this room.
* @throws If you have not specified a listener for 'error' events.
*/
public async placeVideoCall(): Promise<void> {
await this.placeCall(true, true);
}
/**
* Create a datachannel using this call's peer connection.
* @param label A human readable label for this datachannel
* @param options An object providing configuration options for the data channel.
*/
public createDataChannel(label: string, options: RTCDataChannelInit) {
const dataChannel = this.peerConn.createDataChannel(label, options);
this.emit(CallEvent.DataChannel, dataChannel);
return dataChannel;
}
public getOpponentMember(): RoomMember {
return this.opponentMember;
}
public getOpponentSessionId(): string {
return this.opponentSessionId;
}
public opponentCanBeTransferred(): boolean {
return Boolean(this.opponentCaps && this.opponentCaps["m.call.transferee"]);
}
public opponentSupportsDTMF(): boolean {
return Boolean(this.opponentCaps && this.opponentCaps["m.call.dtmf"]);
}
public getRemoteAssertedIdentity(): AssertedIdentity {
return this.remoteAssertedIdentity;
}
public get type(): CallType {
return (this.hasLocalUserMediaVideoTrack || this.hasRemoteUserMediaVideoTrack)
? CallType.Video
: CallType.Voice;
}
public get hasLocalUserMediaVideoTrack(): boolean {
return this.localUsermediaStream?.getVideoTracks().length > 0;
}
public get hasRemoteUserMediaVideoTrack(): boolean {
return this.getRemoteFeeds().some((feed) => {
return (
feed.purpose === SDPStreamMetadataPurpose.Usermedia &&
feed.stream.getVideoTracks().length > 0
);
});
}
public get hasLocalUserMediaAudioTrack(): boolean {
return this.localUsermediaStream?.getAudioTracks().length > 0;
}
public get hasRemoteUserMediaAudioTrack(): boolean {
return this.getRemoteFeeds().some((feed) => {
return (
feed.purpose === SDPStreamMetadataPurpose.Usermedia &&
feed.stream.getAudioTracks().length > 0
);
});
}
public get localUsermediaFeed(): CallFeed {
return this.getLocalFeeds().find((feed) => feed.purpose === SDPStreamMetadataPurpose.Usermedia);
}
public get localScreensharingFeed(): CallFeed {
return this.getLocalFeeds().find((feed) => feed.purpose === SDPStreamMetadataPurpose.Screenshare);
}
public get localUsermediaStream(): MediaStream {
return this.localUsermediaFeed?.stream;
}
public get localScreensharingStream(): MediaStream {
return this.localScreensharingFeed?.stream;
}
public get remoteUsermediaFeed(): CallFeed {
return this.getRemoteFeeds().find((feed) => feed.purpose === SDPStreamMetadataPurpose.Usermedia);
}
public get remoteScreensharingFeed(): CallFeed {
return this.getRemoteFeeds().find((feed) => feed.purpose === SDPStreamMetadataPurpose.Screenshare);
}
public get remoteUsermediaStream(): MediaStream {
return this.remoteUsermediaFeed?.stream;
}
public get remoteScreensharingStream(): MediaStream {
return this.remoteScreensharingFeed?.stream;
}
private getFeedByStreamId(streamId: string): CallFeed {
return this.getFeeds().find((feed) => feed.stream.id === streamId);
}
/**
* Returns an array of all CallFeeds
* @returns {Array<CallFeed>} CallFeeds
*/
public getFeeds(): Array<CallFeed> {
return this.feeds;
}
/**
* Returns an array of all local CallFeeds
* @returns {Array<CallFeed>} local CallFeeds
*/
public getLocalFeeds(): Array<CallFeed> {
return this.feeds.filter((feed) => feed.isLocal());
}
/**
* Returns an array of all remote CallFeeds
* @returns {Array<CallFeed>} remote CallFeeds
*/
public getRemoteFeeds(): Array<CallFeed> {
return this.feeds.filter((feed) => !feed.isLocal());
}
/**
* Generates and returns localSDPStreamMetadata
* @returns {SDPStreamMetadata} localSDPStreamMetadata
*/
private getLocalSDPStreamMetadata(updateStreamIds = false): SDPStreamMetadata {
const metadata: SDPStreamMetadata = {};
for (const localFeed of this.getLocalFeeds()) {
if (updateStreamIds) {
localFeed.sdpMetadataStreamId = localFeed.stream.id;
}
metadata[localFeed.sdpMetadataStreamId] = {
purpose: localFeed.purpose,
audio_muted: localFeed.isAudioMuted(),
video_muted: localFeed.isVideoMuted(),
};
}
return metadata;
}
/**
* Returns true if there are no incoming feeds,
* otherwise returns false
* @returns {boolean} no incoming feeds
*/
public noIncomingFeeds(): boolean {
return !this.feeds.some((feed) => !feed.isLocal());
}
private pushRemoteFeed(stream: MediaStream): void {
// Fallback to old behavior if the other side doesn't support SDPStreamMetadata
if (!this.opponentSupportsSDPStreamMetadata()) {
this.pushRemoteFeedWithoutMetadata(stream);
return;
}
const userId = this.getOpponentMember().userId;
const purpose = this.remoteSDPStreamMetadata[stream.id].purpose;
const audioMuted = this.remoteSDPStreamMetadata[stream.id].audio_muted;
const videoMuted = this.remoteSDPStreamMetadata[stream.id].video_muted;
if (!purpose) {
logger.warn(`Ignoring stream with id ${stream.id} because we didn't get any metadata about it`);
return;
}
// Try to find a feed with the same purpose as the new stream,
// if we find it replace the old stream with the new one
const existingFeed = this.getRemoteFeeds().find((feed) => feed.purpose === purpose);
if (existingFeed) {
existingFeed.setNewStream(stream);
} else {
this.feeds.push(new CallFeed({
client: this.client,
roomId: this.roomId,
userId,
stream,
purpose,
audioMuted,
videoMuted,
}));
this.emit(CallEvent.FeedsChanged, this.feeds);
}
logger.info(`Pushed remote stream (id="${stream.id}", active="${stream.active}", purpose=${purpose})`);
}
/**
* This method is used ONLY if the other client doesn't support sending SDPStreamMetadata
*/
private pushRemoteFeedWithoutMetadata(stream: MediaStream): void {
const userId = this.getOpponentMember().userId;
// We can guess the purpose here since the other client can only send one stream
const purpose = SDPStreamMetadataPurpose.Usermedia;
const oldRemoteStream = this.feeds.find((feed) => !feed.isLocal())?.stream;
// Note that we check by ID and always set the remote stream: Chrome appears
// to make new stream objects when transceiver directionality is changed and the 'active'
// status of streams change - Dave
// If we already have a stream, check this stream has the same id
if (oldRemoteStream && stream.id !== oldRemoteStream.id) {
logger.warn(`Ignoring new stream ID ${stream.id}: we already have stream ID ${oldRemoteStream.id}`);
return;
}
// Try to find a feed with the same stream id as the new stream,
// if we find it replace the old stream with the new one
const feed = this.getFeedByStreamId(stream.id);
if (feed) {
feed.setNewStream(stream);
} else {
this.feeds.push(new CallFeed({
client: this.client,
roomId: this.roomId,
audioMuted: false,
videoMuted: false,
userId,
stream,
purpose,
}));
this.emit(CallEvent.FeedsChanged, this.feeds);
}
logger.info(`Pushed remote stream (id="${stream.id}", active="${stream.active}")`);
}
private pushNewLocalFeed(stream: MediaStream, purpose: SDPStreamMetadataPurpose, addToPeerConnection = true): void {
const userId = this.client.getUserId();
// TODO: Find out what is going on here
// why do we enable audio (and only audio) tracks here? -- matthew
setTracksEnabled(stream.getAudioTracks(), true);
// We try to replace an existing feed if there already is one with the same purpose
const existingFeed = this.getLocalFeeds().find((feed) => feed.purpose === purpose);
if (existingFeed) {
existingFeed.setNewStream(stream);
} else {
this.pushLocalFeed(
new CallFeed({
client: this.client,
roomId: this.roomId,
audioMuted: stream.getAudioTracks().length === 0,
videoMuted: stream.getVideoTracks().length === 0,
userId,
stream,
purpose,
}),
addToPeerConnection,
);
this.emit(CallEvent.FeedsChanged, this.feeds);
}
}
/**
* Pushes supplied feed to the call
* @param {CallFeed} callFeed to push
* @param {boolean} addToPeerConnection whether to add the tracks to the peer connection
*/
public pushLocalFeed(callFeed: CallFeed, addToPeerConnection = true): void {
if (this.feeds.some((feed) => callFeed.stream.id === feed.stream.id)) {
logger.info(`Ignoring duplicate local stream ${callFeed.stream.id} in call ${this.callId}`);
return;
}
this.feeds.push(callFeed);
if (addToPeerConnection) {
const senderArray = callFeed.purpose === SDPStreamMetadataPurpose.Usermedia ?
this.usermediaSenders : this.screensharingSenders;
// Empty the array
senderArray.splice(0, senderArray.length);
for (const track of callFeed.stream.getTracks()) {
logger.info(
`Adding track (` +
`id="${track.id}", ` +
`kind="${track.kind}", ` +
`streamId="${callFeed.stream.id}", ` +
`streamPurpose="${callFeed.purpose}"` +
`) to peer connection`,
);
senderArray.push(this.peerConn.addTrack(track, callFeed.stream));
}
}
logger.info(
`Pushed local stream `+
`(id="${callFeed.stream.id}", `+
`active="${callFeed.stream.active}", `+
`purpose="${callFeed.purpose}")`,
);
this.emit(CallEvent.FeedsChanged, this.feeds);
}
/**
* Removes local call feed from the call and its tracks from the peer
* connection
* @param callFeed to remove
*/
public removeLocalFeed(callFeed: CallFeed): void {
const senderArray = callFeed.purpose === SDPStreamMetadataPurpose.Usermedia
? this.usermediaSenders
: this.screensharingSenders;
for (const sender of senderArray) {
this.peerConn.removeTrack(sender);
}
if (callFeed.purpose === SDPStreamMetadataPurpose.Screenshare) {
this.client.getMediaHandler().stopScreensharingStream(callFeed.stream);
}
// Empty the array
senderArray.splice(0, senderArray.length);
this.deleteFeed(callFeed);
}
private deleteAllFeeds(): void {
for (const feed of this.feeds) {
if (!feed.isLocal() || !this.groupCallId) {
feed.dispose();
}
}
this.feeds = [];
this.emit(CallEvent.FeedsChanged, this.feeds);
}
private deleteFeedByStream(stream: MediaStream): void {
const feed = this.getFeedByStreamId(stream.id);
if (!feed) {
logger.warn(`Didn't find the feed with stream id ${stream.id} to delete`);
return;
}
this.deleteFeed(feed);
}
private deleteFeed(feed: CallFeed): void {
feed.dispose();
this.feeds.splice(this.feeds.indexOf(feed), 1);
this.emit(CallEvent.FeedsChanged, this.feeds);
}
// The typescript definitions have this type as 'any' :(
public async getCurrentCallStats(): Promise<any[]> {
if (this.callHasEnded()) {
return this.callStatsAtEnd;
}
return this.collectCallStats();
}
private async collectCallStats(): Promise<any[]> {
// This happens when the call fails before it starts.
// For example when we fail to get capture sources
if (!this.peerConn) return;
const statsReport = await this.peerConn.getStats();
const stats = [];
for (const item of statsReport) {
stats.push(item[1]);
}
return stats;
}
/**
* Configure this call from an invite event. Used by MatrixClient.
* @param {MatrixEvent} event The m.call.invite event
*/
public async initWithInvite(event: MatrixEvent): Promise<void> {
const invite = event.getContent<MCallInviteNegotiate>();
this.direction = CallDirection.Inbound;
// make sure we have valid turn creds. Unless something's gone wrong, it should
// poll and keep the credentials valid so this should be instant.
const haveTurnCreds = await this.client.checkTurnServers();
if (!haveTurnCreds) {
logger.warn("Failed to get TURN credentials! Proceeding with call anyway...");
}
const sdpStreamMetadata = invite[SDPStreamMetadataKey];
if (sdpStreamMetadata) {
this.updateRemoteSDPStreamMetadata(sdpStreamMetadata);
} else {
logger.debug("Did not get any SDPStreamMetadata! Can not send/receive multiple streams");
}
this.peerConn = this.createPeerConnection();
// we must set the party ID before await-ing on anything: the call event
// handler will start giving us more call events (eg. candidates) so if
// we haven't set the party ID, we'll ignore them.
this.chooseOpponent(event);
try {
await this.peerConn.setRemoteDescription(invite.offer);
await this.addBufferedIceCandidates();
} catch (e) {
logger.debug("Failed to set remote description", e);
this.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);
return;
}
const remoteStream = this.feeds.find((feed) => !feed.isLocal())?.stream;
// According to previous comments in this file, firefox at some point did not
// add streams until media started arriving on them. Testing latest firefox
// (81 at time of writing), this is no longer a problem, so let's do it the correct way.
if (!remoteStream || remoteStream.getTracks().length === 0) {
logger.error("No remote stream or no tracks after setting remote description!");
this.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);
return;
}
this.setState(CallState.Ringing);
if (event.getLocalAge()) {
setTimeout(() => {
if (this.state == CallState.Ringing) {
logger.debug("Call invite has expired. Hanging up.");
this.hangupParty = CallParty.Remote; // effectively
this.setState(CallState.Ended);
this.stopAllMedia();
if (this.peerConn.signalingState != 'closed') {
this.peerConn.close();
}
this.emit(CallEvent.Hangup);
}
}, invite.lifetime - event.getLocalAge());
}
}
/**
* Configure this call from a hangup or reject event. Used by MatrixClient.
* @param {MatrixEvent} event The m.call.hangup event
*/
public initWithHangup(event: MatrixEvent): void {
// perverse as it may seem, sometimes we want to instantiate a call with a
// hangup message (because when getting the state of the room on load, events
// come in reverse order and we want to remember that a call has been hung up)
this.setState(CallState.Ended);
}
private shouldAnswerWithMediaType(
wantedValue: boolean | undefined, valueOfTheOtherSide: boolean | undefined, type: "audio" | "video",
): boolean {
if (wantedValue && !valueOfTheOtherSide) {
// TODO: Figure out how to do this
logger.warn(`Unable to answer with ${type} because the other side isn't sending it either.`);
return false;
} else if (
!utils.isNullOrUndefined(wantedValue) &&
wantedValue !== valueOfTheOtherSide &&
!this.opponentSupportsSDPStreamMetadata()
) {
logger.warn(
`Unable to answer with ${type}=${wantedValue} because the other side doesn't support it. ` +
`Answering with ${type}=${valueOfTheOtherSide}.`,
);
return valueOfTheOtherSide;
}
return wantedValue ?? valueOfTheOtherSide;
}
/**
* Answer a call.
*/
public async answer(audio?: boolean, video?: boolean): Promise<void> {
if (this.inviteOrAnswerSent) return;
// TODO: Figure out how to do this
if (audio === false && video === false) throw new Error("You CANNOT answer a call without media");
if (!this.localUsermediaStream && !this.waitForLocalAVStream) {
const prevState = this.state;
const answerWithAudio = this.shouldAnswerWithMediaType(audio, this.hasRemoteUserMediaAudioTrack, "audio");
const answerWithVideo = this.shouldAnswerWithMediaType(video, this.hasRemoteUserMediaVideoTrack, "video");
this.setState(CallState.WaitLocalMedia);
this.waitForLocalAVStream = true;
try {
const stream = await this.client.getMediaHandler().getUserMediaStream(
answerWithAudio, answerWithVideo,
);
this.waitForLocalAVStream = false;
const usermediaFeed = new CallFeed({
client: this.client,
roomId: this.roomId,
userId: this.client.getUserId(),
stream,
purpose: SDPStreamMetadataPurpose.Usermedia,
audioMuted: stream.getAudioTracks().length === 0,
videoMuted: stream.getVideoTracks().length === 0,
});
const feeds = [usermediaFeed];
if (this.localScreensharingFeed) {
feeds.push(this.localScreensharingFeed);
}
this.answerWithCallFeeds(feeds);
} catch (e) {
if (answerWithVideo) {
// Try to answer without video
logger.warn("Failed to getUserMedia(), trying to getUserMedia() without video");
this.setState(prevState);
this.waitForLocalAVStream = false;
await this.answer(answerWithAudio, false);
} else {
this.getUserMediaFailed(e);
return;
}
}
} else if (this.waitForLocalAVStream) {
this.setState(CallState.WaitLocalMedia);
}
}
public answerWithCallFeeds(callFeeds: CallFeed[]): void {
if (this.inviteOrAnswerSent) return;
logger.debug(`Answering call ${this.callId}`);
this.queueGotCallFeedsForAnswer(callFeeds);
}
/**
* Replace this call with a new call, e.g. for glare resolution. Used by
* MatrixClient.
* @param {MatrixCall} newCall The new call.
*/
public replacedBy(newCall: MatrixCall): void {
if (this.state === CallState.WaitLocalMedia) {
logger.debug("Telling new call to wait for local media");
newCall.waitForLocalAVStream = true;
} else if ([CallState.CreateOffer, CallState.InviteSent].includes(this.state)) {
if (newCall.direction === CallDirection.Outbound) {
newCall.queueGotCallFeedsForAnswer([]);
} else {
logger.debug("Handing local stream to new call");
newCall.queueGotCallFeedsForAnswer(this.getLocalFeeds().map(feed => feed.clone()));
}
}
this.successor = newCall;
this.emit(CallEvent.Replaced, newCall);
this.hangup(CallErrorCode.Replaced, true);
}
/**
* Hangup a call.
* @param {string} reason The reason why the call is being hung up.
* @param {boolean} suppressEvent True to suppress emitting an event.
*/
public hangup(reason: CallErrorCode, suppressEvent: boolean): void {
if (this.callHasEnded()) return;
logger.debug("Ending call " + this.callId);
this.terminate(CallParty.Local, reason, !suppressEvent);
// We don't want to send hangup here if we didn't even get to sending an invite
if (this.state === CallState.WaitLocalMedia) return;
const content = {};
// Don't send UserHangup reason to older clients
if ((this.opponentVersion && this.opponentVersion >= 1) || reason !== CallErrorCode.UserHangup) {
content["reason"] = reason;
}
this.sendVoipEvent(EventType.CallHangup, content);
}
/**
* Reject a call
* This used to be done by calling hangup, but is a separate method and protocol
* event as of MSC2746.
*/
public reject(): void {
if (this.state !== CallState.Ringing) {
throw Error("Call must be in 'ringing' state to reject!");
}
if (this.opponentVersion < 1) {
logger.info(
`Opponent version is less than 1 (${this.opponentVersion}): sending hangup instead of reject`,
);
this.hangup(CallErrorCode.UserHangup, true);
return;
}
logger.debug("Rejecting call: " + this.callId);
this.terminate(CallParty.Local, CallErrorCode.UserHangup, true);
this.sendVoipEvent(EventType.CallReject, {});
}
/**
* Adds an audio and/or video track - upgrades the call
* @param {boolean} audio should add an audio track
* @param {boolean} video should add an video track
*/
private async upgradeCall(
audio: boolean, video: boolean,
): Promise<void> {
// We don't do call downgrades
if (!audio && !video) return;
if (!this.opponentSupportsSDPStreamMetadata()) return;
try {
const upgradeAudio = audio && !this.hasLocalUserMediaAudioTrack;
const upgradeVideo = video && !this.hasLocalUserMediaVideoTrack;
logger.debug(`Upgrading call: audio?=${upgradeAudio} video?=${upgradeVideo}`);
const stream = await this.client.getMediaHandler().getUserMediaStream(upgradeAudio, upgradeVideo);
if (upgradeAudio && upgradeVideo) {
if (this.hasLocalUserMediaAudioTrack) return;
if (this.hasLocalUserMediaVideoTrack) return;
this.pushNewLocalFeed(stream, SDPStreamMetadataPurpose.Usermedia);
} else if (upgradeAudio) {
if (this.hasLocalUserMediaAudioTrack) return;
const audioTrack = stream.getAudioTracks()[0];
this.localUsermediaStream.addTrack(audioTrack);
this.peerConn.addTrack(audioTrack, this.localUsermediaStream);
} else if (upgradeVideo) {
if (this.hasLocalUserMediaVideoTrack) return;
const videoTrack = stream.getVideoTracks()[0];
this.localUsermediaStream.addTrack(videoTrack);