-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathclient.ts
More file actions
1254 lines (1051 loc) · 44.4 KB
/
client.ts
File metadata and controls
1254 lines (1051 loc) · 44.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
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 (c) 2020-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
// eslint-disable max-lines
// eslint-disable-next-line simple-import-sort/imports
import {parseRTCStats, RTCMonitor, RTCPeer} from '@mattermost/calls-common';
import type {EmojiData, CallsClientJoinData, TrackInfo, RTPEncodingParameters} from '@mattermost/calls-common/lib/types';
import {EventEmitter} from 'events';
import {zlibSync, strToU8} from 'fflate';
import {MediaDevices, CallsClientConfig, CallsClientStats, TrackMetadata} from 'src/types/types';
import {logDebug, logErr, logInfo, logWarn, persistClientLogs, flushLogsToAccumulated} from './log';
import {getScreenStream, getPersistentStorage} from './utils';
import {WebSocketClient, WebSocketError, WebSocketErrorType} from './websocket';
import {
STORAGE_CALLS_CLIENT_STATS_KEY,
STORAGE_CALLS_DEFAULT_AUDIO_INPUT_KEY,
STORAGE_CALLS_DEFAULT_AUDIO_OUTPUT_KEY,
STORAGE_CALLS_DEFAULT_VIDEO_INPUT_KEY,
} from 'src/constants';
import {type BgBlurData, getBgBlurData} from 'src/local_storage';
import Segmenter from 'src/segmenter';
export const AudioInputPermissionsError = new Error('missing audio input permissions');
export const AudioInputMissingError = new Error('no audio input available');
export const VideoInputPermissionsError = new Error('missing video input permissions');
export const VideoInputMissingError = new Error('no video input available');
export const rtcPeerErr = new Error('rtc peer error');
export const rtcPeerTimeoutErr = new Error('timed out waiting for rtc connection');
export const rtcPeerCloseErr = new Error('rtc peer close');
export const insecureContextErr = new Error('insecure context');
export const userRemovedFromChannelErr = new Error('user was removed from channel');
export const userLeftChannelErr = new Error('user has left channel');
export const DefaultVideoTrackOptions: MediaTrackConstraints = {
// TODO: consider exposing in user preferences
frameRate: {
ideal: 30,
},
width: {
ideal: 640,
},
height: {
ideal: 360,
},
};
const rtcMonitorInterval = 10000;
export default class CallsClient extends EventEmitter {
public channelID: string;
private readonly config: CallsClientConfig;
private peer: RTCPeer | null;
public ws: WebSocketClient | null;
private localScreenTrack: MediaStreamTrack | null = null;
public localVideoStream: MediaStream | null = null;
private remoteScreenTrack: MediaStreamTrack | null = null;
private remoteVoiceTracks: MediaStreamTrack[];
private remoteVideoTracks: MediaStreamTrack[];
public currentAudioInputDevice: MediaDeviceInfo | null = null;
public currentAudioOutputDevice: MediaDeviceInfo | null = null;
public currentVideoInputDevice: MediaDeviceInfo | null = null;
private voiceTrackAdded: boolean;
private videoTrackAdded: boolean;
private streams: MediaStream[];
private stream: MediaStream | null;
private audioDevices: MediaDevices;
private videoDevices: MediaDeviceInfo[];
public audioTrack: MediaStreamTrack | null;
private readonly onDeviceChange: () => void;
private readonly onBeforeUnload: () => void;
private closed = false;
private connected = false;
public initTime = Date.now();
private rtcMonitor: RTCMonitor | null = null;
private av1Codec: RTCRtpCodecCapability | null = null;
private defaultAudioTrackOptions: MediaTrackConstraints;
private defaultVideoTrackOptions: MediaTrackConstraints;
private defaultVideoTrackEncodings: RTPEncodingParameters[];
private segmenter: Segmenter | null = null;
constructor(config: CallsClientConfig) {
logDebug('creating new calls client', JSON.stringify(config));
super();
this.ws = null;
this.peer = null;
this.audioTrack = null;
this.currentAudioInputDevice = null;
this.currentAudioInputDevice = null;
this.currentVideoInputDevice = null;
this.voiceTrackAdded = false;
this.videoTrackAdded = false;
this.streams = [];
this.remoteVoiceTracks = [];
this.remoteVideoTracks = [];
this.stream = null;
this.audioDevices = {inputs: [], outputs: []};
this.videoDevices = [];
this.channelID = '';
this.config = config;
this.defaultAudioTrackOptions = {
autoGainControl: true,
echoCancellation: true,
noiseSuppression: true,
};
this.defaultVideoTrackOptions = DefaultVideoTrackOptions;
this.defaultVideoTrackEncodings = [
{maxBitrate: 1000 * 1000, maxFramerate: 30, scaleResolutionDownBy: 1.0},
];
this.onDeviceChange = async () => {
await this.updateDevices();
};
this.onBeforeUnload = () => {
logDebug('unload');
this.disconnect();
};
window.addEventListener('beforeunload', this.onBeforeUnload);
}
private async updateDevices() {
logDebug('a/v device change detected');
try {
const devices = await navigator.mediaDevices.enumerateDevices();
logDebug('enumerated devices', devices);
const inputs = devices.filter((device) => device.kind === 'audioinput');
const outputs = devices.filter((device) => device.kind === 'audiooutput');
this.audioDevices = {
inputs,
outputs,
};
if (this.config.enableVideo) {
this.videoDevices = devices.filter((device) => device.kind === 'videoinput');
}
if (this.currentAudioInputDevice) {
await this.handleAudioDeviceFallback('input');
}
if (this.currentAudioOutputDevice) {
await this.handleAudioDeviceFallback('output');
}
this.emit('devicechange', this.audioDevices, this.videoDevices);
} catch (err) {
logErr(err);
}
}
private async handleAudioDeviceFallback(deviceType: string) {
const currentDevice = deviceType === 'input' ? this.currentAudioInputDevice : this.currentAudioOutputDevice;
const devices = deviceType === 'input' ? this.audioDevices.inputs : this.audioDevices.outputs;
const missingCurrentDevice = !devices.some(device => currentDevice?.deviceId === device.deviceId);
// Fallback to the system default device if the current one is not available.
if (missingCurrentDevice && devices.length > 0) {
logDebug(`selected audio ${deviceType} device not available, falling back to system default`, currentDevice, devices[0]);
if (deviceType === 'input') {
await this.setAudioInputDevice(devices[0], false);
} else if (deviceType === 'output') {
await this.setAudioOutputDevice(devices[0], false);
}
this.emit('devicefallback', devices[0]);
return;
}
// If the user selected (i.g. stored) device comes back, we want to switch to it.
const selectedDevice = this.getSelectedAudioDevice(deviceType);
if (selectedDevice && selectedDevice.label !== currentDevice?.label) {
logDebug(`selected audio ${deviceType} device is back, switching`, selectedDevice, currentDevice);
if (deviceType === 'input') {
await this.setAudioInputDevice(selectedDevice, false);
} else if (deviceType === 'output') {
await this.setAudioOutputDevice(selectedDevice, false);
}
this.emit('devicefallback', selectedDevice);
}
}
private getSelectedAudioDevice(deviceType: string) {
let selectedDevice: {deviceId: string; label?: string} = {
deviceId: '',
};
const deviceKey = deviceType === 'input' ? STORAGE_CALLS_DEFAULT_AUDIO_INPUT_KEY : STORAGE_CALLS_DEFAULT_AUDIO_OUTPUT_KEY;
const data = window.localStorage.getItem(deviceKey);
if (data) {
try {
selectedDevice = JSON.parse(data);
} catch {
// Backwards compatibility case when we used to store the device id directly (before MM-63274).
selectedDevice = {
deviceId: data,
};
}
}
if (!selectedDevice.deviceId) {
return null;
}
let devices = deviceType === 'input' ? this.audioDevices.inputs : this.audioDevices.outputs;
devices = devices.filter((dev) => {
return dev.deviceId === selectedDevice.deviceId || dev.label === selectedDevice.label;
});
if (devices.length > 1) {
// If there are multiple devices with the same label, we select the selected device by ID.
logInfo(`getSelectedAudioDevice: multiple audio ${deviceType} devices found with the same label, checking by id`, devices);
return devices.find((dev) => dev.deviceId === selectedDevice.deviceId) || null;
} else if (devices.length === 1) {
logDebug(`getSelectedAudioDevice: found selected audio ${deviceType} device to use`, devices[0]);
return devices[0];
}
logDebug(`getSelectedAudioDevice: audio ${deviceType} device not found`, selectedDevice);
return null;
}
private async initVideo(startVideo: boolean, deviceId?: string) {
const videoOptions: MediaTrackConstraints = {
...this.defaultVideoTrackOptions,
};
if (deviceId) {
videoOptions.deviceId = {
exact: deviceId,
};
} else if (this.currentVideoInputDevice) {
videoOptions.deviceId = {
exact: this.currentVideoInputDevice.deviceId,
};
} else {
let defaultInputDevice: {deviceId: string; label?: string} = {
deviceId: '',
};
const defaultVideoInputData = window.localStorage.getItem(STORAGE_CALLS_DEFAULT_VIDEO_INPUT_KEY);
if (defaultVideoInputData) {
try {
defaultInputDevice = JSON.parse(defaultVideoInputData);
} catch (err) {
logErr('failed to parse default video input device', err);
}
}
if (defaultInputDevice.deviceId) {
let devices = this.videoDevices.filter((dev) => {
return dev.deviceId === defaultInputDevice.deviceId || dev.label === defaultInputDevice.label;
});
if (devices.length > 1) {
// If there are multiple devices with the same label, we select the default device by ID.
logInfo('multiple video input devices found with the same label, checking by id', devices);
devices = devices.filter((dev) => dev.deviceId === defaultInputDevice.deviceId);
}
if (devices && devices.length === 1) {
logDebug(`found default video input device to use: ${devices[0].label}`);
videoOptions.deviceId = {
exact: devices[0].deviceId,
};
this.currentVideoInputDevice = devices[0];
} else {
logDebug('video input device not found');
window.localStorage.removeItem(STORAGE_CALLS_DEFAULT_VIDEO_INPUT_KEY);
}
}
}
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: videoOptions,
audio: false,
});
// updating the devices again cause some browsers (e.g Firefox) will
// return empty labels unless permissions were previously granted.
await this.updateDevices();
// Video should be off by default (for now). We initialize it to ensure permissions are there but
// don't need to keep it active until the user explicitly starts it from UI.
if (startVideo) {
this.localVideoStream = stream;
this.streams.push(stream);
stream.getVideoTracks()[0].enabled = false;
} else {
stream.getVideoTracks()[0].stop();
stream.getVideoTracks()[0].dispatchEvent(new Event('ended'));
}
this.emit('initvideo');
} catch (err) {
logErr(err);
if (this.videoDevices.length > 0) {
throw VideoInputPermissionsError;
}
throw VideoInputMissingError;
}
}
private async initAudio(deviceId?: string) {
const audioOptions: MediaTrackConstraints = {
...this.defaultAudioTrackOptions,
};
if (deviceId) {
audioOptions.deviceId = {
exact: deviceId,
};
}
try {
this.stream = await navigator.mediaDevices.getUserMedia({
video: false,
audio: audioOptions,
});
// If no deviceId is provided, we use the getUserMedia call purely to get permissions.
// This is because if permissions were missing upon joining, we may have not gotten the right device labels
// which would cause us to potentially fail to initialize a previously saved input device.
// Now that we have permission, we update the devices once more and try again to see if we can use the stored input device.
if (!deviceId) {
this.stream.getAudioTracks().forEach((track) => {
track.stop();
track.dispatchEvent(new Event('ended'));
});
}
// updating the devices again cause some browsers will
// return empty labels unless permissions were previously granted.
await this.updateDevices();
if (!deviceId) {
const selectedAudioInputDevice = this.getSelectedAudioDevice('input');
if (selectedAudioInputDevice) {
audioOptions.deviceId = {
exact: selectedAudioInputDevice.deviceId,
};
this.currentAudioInputDevice = selectedAudioInputDevice;
}
const selectedAudioOutputDevice = this.getSelectedAudioDevice('output');
if (selectedAudioOutputDevice) {
this.currentAudioOutputDevice = selectedAudioOutputDevice;
}
this.stream = await navigator.mediaDevices.getUserMedia({
video: false,
audio: audioOptions,
});
}
this.audioTrack = this.stream.getAudioTracks()[0];
this.streams.push(this.stream);
this.audioTrack.enabled = false;
this.emit('initaudio');
} catch (err) {
logErr(err);
if (this.audioDevices.inputs.length > 0) {
throw AudioInputPermissionsError;
}
throw AudioInputMissingError;
}
}
private collectICEStats() {
const start = Date.now();
const seenMap: {[key: string]: string} = {};
const gatherStats = async () => {
if (!this.ws || !this.peer) {
return;
}
try {
const stats = parseRTCStats(await this.peer.getStats()).iceStats;
for (const state of Object.keys(stats)) {
for (const pair of stats[state]) {
const seenState = seenMap[pair.id];
seenMap[pair.id] = pair.state;
if (seenState !== pair.state) {
logDebug('ice candidate pair stats', JSON.stringify(pair));
}
if (seenState === 'succeeded' || state !== 'succeeded') {
continue;
}
if (!pair.local || !pair.remote) {
continue;
}
this.ws.send('metric', {
metric_name: 'client_ice_candidate_pair',
data: JSON.stringify({
state: pair.state,
local: {
type: pair.local.candidateType,
protocol: pair.local.protocol,
},
remote: {
type: pair.remote.candidateType,
protocol: pair.remote.protocol,
},
}),
});
}
}
} catch (err) {
logErr('failed to parse ICE stats', err);
}
// Repeat the check for at most 30 seconds.
if (Date.now() < start + 30000) {
// We check every two seconds.
setTimeout(gatherStats, 2000);
}
};
gatherStats();
}
public async init(joinData: CallsClientJoinData) {
this.channelID = joinData.channelID;
if (this.config.enableAV1 && !this.config.simulcast) {
this.av1Codec = await RTCPeer.getVideoCodec('video/AV1');
if (this.av1Codec) {
logDebug('client has AV1 support');
joinData.av1Support = true;
}
} else if (this.config.enableAV1 && this.config.simulcast) {
logWarn('both simulcast and av1 support are enabled');
}
if (this.config.dcSignaling) {
logDebug('enabling DC signaling on client');
joinData.dcSignaling = true;
}
if (!window.isSecureContext) {
throw insecureContextErr;
}
await this.updateDevices();
navigator.mediaDevices.addEventListener('devicechange', this.onDeviceChange);
try {
const initializers = [this.initAudio()];
if (this.config.enableVideo) {
initializers.push(this.initVideo(false));
}
await Promise.all(initializers);
if (this.closed) {
this.cleanup();
return;
}
} catch (err) {
this.emit('error', err);
}
const ws = new WebSocketClient(this.config.wsURL, this.config.authToken);
this.ws = ws;
ws.on('error', (err: WebSocketError) => {
logErr('ws error', err);
switch (err.type) {
case WebSocketErrorType.Native:
break;
case WebSocketErrorType.ReconnectTimeout:
this.ws = null;
this.disconnect(err);
break;
case WebSocketErrorType.Join:
this.disconnect(err);
break;
default:
}
});
ws.on('close', (code?: number) => {
logDebug(`ws close: ${code}`);
});
ws.on('open', (originalConnID: string, prevConnID: string, isReconnect: boolean) => {
if (isReconnect) {
logDebug('ws reconnect, sending reconnect msg');
ws.send('reconnect', {
channelID: joinData.channelID,
originalConnID,
prevConnID,
});
} else {
logDebug('ws open, sending join msg');
ws.send('join', joinData);
}
});
ws.on('join', async () => {
logDebug('join ack received, initializing connection');
const peer = new RTCPeer({
iceServers: this.config.iceServers || [],
logger: {
logDebug,
logErr,
logWarn,
logInfo,
},
simulcast: this.config.simulcast,
dcSignaling: this.config.dcSignaling,
dcLocking: this.config.dcLocking,
});
this.peer = peer;
this.collectICEStats();
this.rtcMonitor = new RTCMonitor({
peer,
logger: {
logDebug,
logErr,
logWarn,
logInfo,
},
monitorInterval: rtcMonitorInterval,
});
this.rtcMonitor.on('mos', (mos: number) => this.emit('mos', mos));
const sdpHandler = (sdp: RTCSessionDescription) => {
const payload = JSON.stringify(sdp);
// SDP data is compressed using zlib since it's text based
// and can grow substantially, potentially hitting the maximum
// message size (4KB).
ws.send('sdp', {
data: zlibSync(strToU8(payload)),
}, true);
};
peer.on('offer', sdpHandler);
peer.on('answer', sdpHandler);
peer.on('candidate', (candidate) => {
ws.send('ice', {
data: JSON.stringify(candidate),
});
});
peer.on('error', (err) => {
logErr('peer error', err);
if (!this.closed) {
this.disconnect(err === rtcPeerTimeoutErr.message ? rtcPeerTimeoutErr : rtcPeerErr);
}
});
peer.on('stream', (remoteStream: MediaStream, trackInfo: TrackInfo) => {
logDebug('new remote stream received', remoteStream.id, 'trackInfo:', trackInfo);
for (const track of remoteStream.getTracks()) {
logDebug('remote track', track.kind, track.id, 'label:', track.label);
}
this.streams.push(remoteStream);
const audioTracks = remoteStream.getAudioTracks();
const videoTracks = remoteStream.getVideoTracks();
logDebug('stream has', audioTracks.length, 'audio tracks and', videoTracks.length, 'video tracks');
// Handle audio tracks based on type
if (audioTracks.length > 0) {
if (trackInfo?.type === 'screen-audio') {
// Screen share audio - emit as voice stream so it gets played
logDebug('received screen-audio track, emitting as remoteVoiceStream');
this.emit('remoteVoiceStream', new MediaStream(audioTracks));
this.remoteVoiceTracks.push(...audioTracks);
} else if (trackInfo?.type === 'voice' || !trackInfo?.type) {
// Regular voice audio
logDebug('received voice track, emitting as remoteVoiceStream');
this.emit('remoteVoiceStream', remoteStream);
this.remoteVoiceTracks.push(...audioTracks);
} else {
logDebug('unexpected audio track type:', trackInfo?.type);
}
}
// Handle video tracks based on type
if (videoTracks.length > 0) {
if (trackInfo?.type === 'video') {
logDebug('received video track, emitting as remoteVideoStream');
this.emit('remoteVideoStream', remoteStream);
this.remoteVideoTracks.push(videoTracks[0]);
} else if (trackInfo?.type === 'screen') {
logDebug('received screen track, emitting as remoteScreenStream');
this.emit('remoteScreenStream', remoteStream);
this.remoteScreenTrack = videoTracks[0];
} else {
logDebug('unexpected video track type:', trackInfo?.type);
}
}
});
peer.on('connect', () => {
logDebug('rtc connected');
this.emit('connect');
this.rtcMonitor?.start();
this.connected = true;
});
peer.on('close', () => {
logDebug('rtc closed');
if (!this.closed) {
this.disconnect(rtcPeerCloseErr);
}
});
});
ws.on('message', async ({data}) => {
try {
const msg = JSON.parse(data);
if (!msg) {
return;
}
if (msg.type === 'answer' || msg.type === 'offer' || msg.type === 'candidate') {
if (this.peer) {
await this.peer.signal(data);
}
}
} catch (err) {
logErr('ws.on(message): failed to handle message', err, 'data:', data);
}
});
}
public destroy() {
this.removeAllListeners('close');
this.removeAllListeners('connect');
this.removeAllListeners('remoteVoiceStream');
this.removeAllListeners('remoteScreenStream');
this.removeAllListeners('localScreenStream');
this.removeAllListeners('localVideoStream');
this.removeAllListeners('devicechange');
this.removeAllListeners('devicefallback');
this.removeAllListeners('error');
this.removeAllListeners('initaudio');
this.removeAllListeners('initvideo');
this.removeAllListeners('mute');
this.removeAllListeners('unmute');
this.removeAllListeners('raise_hand');
this.removeAllListeners('lower_hand');
this.removeAllListeners('mos');
this.removeAllListeners('video_on');
this.removeAllListeners('video_off');
window.removeEventListener('beforeunload', this.onBeforeUnload);
navigator.mediaDevices?.removeEventListener('devicechange', this.onDeviceChange);
this.segmenter?.stop();
this.segmenter = null;
persistClientLogs();
}
public async setAudioInputDevice(device: MediaDeviceInfo, store: boolean = true) {
if (!this.peer) {
return;
}
if (store) {
window.localStorage.setItem(STORAGE_CALLS_DEFAULT_AUDIO_INPUT_KEY, JSON.stringify(device));
}
this.currentAudioInputDevice = device;
// We emit this event so it's easier to keep state in sync between widget and pop out.
this.emit('devicechange', this.audioDevices, this.videoDevices);
// If no track/stream exists we need to initialize again.
// This edge case can happen if the default input device failed
// but there are potentially more valid ones to choose (MM-48822).
if (!this.audioTrack || !this.stream) {
await this.initAudio(device.deviceId);
return;
}
const isEnabled = this.audioTrack.enabled;
const oldTrack = this.audioTrack;
try {
const newStream = await navigator.mediaDevices.getUserMedia({
video: false,
audio: {
...this.defaultAudioTrackOptions,
deviceId: {
exact: device.deviceId,
},
},
});
this.streams.push(newStream);
const newTrack = newStream.getAudioTracks()[0];
// Stop old track only after successfully getting new track
oldTrack.stop();
this.stream.removeTrack(oldTrack);
this.stream.addTrack(newTrack);
newTrack.enabled = isEnabled;
if (isEnabled) {
// voiceTrackAdded must be true if the track is enabled.
logDebug('replacing track to peer', newTrack.id);
this.peer.replaceTrack(oldTrack.id, newTrack);
} else {
this.voiceTrackAdded = false;
}
this.audioTrack = newTrack;
} catch (err) {
logErr('setAudioInputDevice: failed to switch audio input device', device.deviceId, err);
throw err;
}
}
public async setVideoInputDevice(device: MediaDeviceInfo) {
if (!this.peer) {
return;
}
window.localStorage.setItem(STORAGE_CALLS_DEFAULT_VIDEO_INPUT_KEY, JSON.stringify(device));
this.currentVideoInputDevice = device;
// We emit this event so it's easier to keep state in sync between widget and pop out.
this.emit('devicechange', this.audioDevices, this.videoDevices);
// If no track/stream exists we need to initialize again.
// This edge case can happen if the default input device failed
// but there are potentially more valid ones to choose (MM-48822).
if (!this.localVideoStream) {
await this.initVideo(false, device.deviceId);
return;
}
const videoTrack = this.localVideoStream.getVideoTracks()[0];
const isEnabled = videoTrack.enabled;
const oldSegmenter = this.segmenter;
try {
const newStream = await navigator.mediaDevices.getUserMedia({
audio: false,
video: {
...this.defaultVideoTrackOptions,
deviceId: {
exact: device.deviceId,
},
},
});
this.streams.push(newStream);
let newTrack = newStream.getVideoTracks()[0];
const bgBlurData = getBgBlurData();
if (bgBlurData.blurBackground && bgBlurData.blurIntensity > 0) {
logDebug('background blur enabled', bgBlurData);
newTrack = await this.initBgBackgroundTrack(newStream, bgBlurData);
}
// Stop old track and segmenter only after successfully getting and processing new track
videoTrack.stop();
videoTrack.dispatchEvent(new Event('ended'));
if (oldSegmenter) {
oldSegmenter.stop();
// Clear segmenter reference if blur is now disabled
if (!bgBlurData.blurBackground) {
this.segmenter = null;
}
}
this.localVideoStream.removeTrack(videoTrack);
this.localVideoStream.addTrack(newTrack);
this.localVideoStream = newStream;
newTrack.enabled = isEnabled;
if (isEnabled) {
// videoTrackAdded must be true if the track is enabled.
logDebug('replacing track to peer', newTrack.id);
this.peer.replaceTrack(videoTrack.id, newTrack);
this.emit('localVideoStream', newStream);
} else {
this.videoTrackAdded = false;
}
} catch (err) {
logErr('setVideoInputDevice: failed to switch video input device', device.deviceId, err);
throw err;
}
}
public async setAudioOutputDevice(device: MediaDeviceInfo, store: boolean = true) {
if (!this.peer) {
return;
}
if (store) {
window.localStorage.setItem(STORAGE_CALLS_DEFAULT_AUDIO_OUTPUT_KEY, JSON.stringify(device));
}
this.currentAudioOutputDevice = device;
// We emit this event so it's easier to keep state in sync between widget and pop out.
this.emit('devicechange', this.audioDevices, this.videoDevices);
}
public disconnect(err?: Error) {
logDebug('disconnect');
if (this.closed) {
logErr('client already disconnected');
return;
}
this.rtcMonitor?.stop();
this.closed = true;
if (this.peer) {
this.getStats().then((stats) => {
// Flush logs with stats to accumulated buffer
flushLogsToAccumulated(stats);
// Also save to stats storage for backwards compatibility
getPersistentStorage().setItem(STORAGE_CALLS_CLIENT_STATS_KEY, JSON.stringify(stats));
}).catch((statsErr) => {
logErr(statsErr);
// Still flush logs even if stats failed
flushLogsToAccumulated();
});
this.peer.destroy();
this.peer = null;
}
this.cleanup();
if (this.ws) {
this.ws.send('leave');
this.ws.close();
this.ws = null;
}
this.emit('close', err);
}
private cleanup() {
this.streams.forEach((s) => {
s.getTracks().forEach((track) => {
track.stop();
track.dispatchEvent(new Event('ended'));
});
});
}
public mute() {
if (!this.peer || !this.audioTrack || !this.stream) {
return;
}
logDebug('replacing track to peer', null);
// @ts-ignore: we actually mean (and need) to pass null here
this.peer.replaceTrack(this.audioTrack.id, null);
this.audioTrack.enabled = false;
this.emit('mute');
if (this.ws) {
this.ws.send('mute');
}
}
public async unmute() {
if (!this.peer) {
return;
}
if (!this.audioTrack) {
try {
await this.initAudio();
} catch (err) {
this.emit('error', err);
return;
}
}
// NOTE: we purposely clear the monitor's stats cache upon unmuting
// in order to skip some calculations since upon muting we actually
// stop sending packets which would result in stats to be skewed as
// soon as we resume sending.
// This is not perfect but it avoids having to constantly send
// silence frames when muted.
this.rtcMonitor?.clearCache();
if (this.audioTrack) {
if (this.voiceTrackAdded) {
logDebug('replacing track to peer', this.audioTrack.id);
this.peer.replaceTrack(this.audioTrack.id, this.audioTrack);
} else if (this.stream) {
logDebug('adding track to peer', this.audioTrack.id, this.stream.id);
await this.peer.addTrack(this.audioTrack, this.stream);
this.voiceTrackAdded = true;
}
this.audioTrack.enabled = true;
}
this.emit('unmute');
if (this.ws) {
this.ws.send('unmute');
}
}
public getLocalScreenStream(): MediaStream|null {
if (!this.localScreenTrack) {
return null;
}
return new MediaStream([this.localScreenTrack]);
}
public getRemoteScreenStream(): MediaStream|null {
if (!this.remoteScreenTrack || this.remoteScreenTrack.readyState !== 'live') {
return null;
}
return new MediaStream([this.remoteScreenTrack]);
}
public getRemoteVideoStream(): MediaStream|null {
if (this.remoteVideoTracks.length < 1 || this.remoteVideoTracks[this.remoteVideoTracks.length - 1].readyState !== 'live') {
return null;
}
return new MediaStream([this.remoteVideoTracks[this.remoteVideoTracks.length - 1]]);
}
public getRemoteVoiceTracks(): MediaStreamTrack[] {
const tracks = [];
for (const track of this.remoteVoiceTracks) {
if (track.readyState === 'live') {
tracks.push(track);
}
}
return tracks;
}
public async setScreenStream(screenStream: MediaStream) {
if (!this.ws || !this.peer || this.localScreenTrack || !screenStream) {
return;
}
const screenTrack = screenStream.getVideoTracks()[0];
this.localScreenTrack = screenTrack;
const screenAudioTrack = screenStream.getAudioTracks()[0];
if (screenAudioTrack) {
logDebug(`screen sharing with audio - track id: ${screenAudioTrack.id}, kind: ${screenAudioTrack.kind}, label: ${screenAudioTrack.label}`);
screenStream = new MediaStream([screenTrack, screenAudioTrack]);
} else {
logDebug('screen sharing WITHOUT audio');
screenStream = new MediaStream([screenTrack]);
}
this.streams.push(screenStream);
screenTrack.onended = async () => {
if (screenAudioTrack) {
screenAudioTrack.stop();
}
this.localScreenTrack = null;
if (!this.ws || !this.peer) {
return;
}
try {
await this.peer.removeTrack(screenTrack.id);
if (screenAudioTrack) {
await this.peer.removeTrack(screenAudioTrack.id);