-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathJitsiConference.ts
More file actions
5329 lines (4598 loc) · 199 KB
/
Copy pathJitsiConference.ts
File metadata and controls
5329 lines (4598 loc) · 199 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
import { getLogger } from '@jitsi/logger';
import { isEqual } from 'lodash-es';
import { $msg, Strophe } from 'strophe.js';
import { JitsiAudioTranslationErrors } from './JitsiAudioTranslationErrors';
import * as JitsiConferenceErrors from './JitsiConferenceErrors';
import JitsiConferenceEventManager from './JitsiConferenceEventManager';
import { JitsiConferenceEvents } from './JitsiConferenceEvents';
import type JitsiConnection from './JitsiConnection';
import { JitsiConnectionEvents } from './JitsiConnectionEvents';
import JitsiParticipant from './JitsiParticipant';
import JitsiTrackError from './JitsiTrackError';
import * as JitsiTrackErrors from './JitsiTrackErrors';
import { JitsiTrackEvents } from './JitsiTrackEvents';
import type JitsiLocalTrack from './modules/RTC/JitsiLocalTrack';
import type JitsiRemoteTrack from './modules/RTC/JitsiRemoteTrack';
import JitsiTrack from './modules/RTC/JitsiTrack';
import RTC from './modules/RTC/RTC';
import { SS_DEFAULT_FRAME_RATE } from './modules/RTC/ScreenObtainer';
import type TraceablePeerConnection from './modules/RTC/TraceablePeerConnection';
import browser from './modules/browser';
import ConnectionQuality from './modules/connectivity/ConnectionQuality';
import IceFailedHandling from './modules/connectivity/IceFailedHandling';
import { DetectionEvents } from './modules/detection/DetectionEvents';
import NoAudioSignalDetection from './modules/detection/NoAudioSignalDetection';
import P2PDominantSpeakerDetection from './modules/detection/P2PDominantSpeakerDetection';
import VADAudioAnalyser, { IVADProcessor } from './modules/detection/VADAudioAnalyser';
import VADNoiseDetection from './modules/detection/VADNoiseDetection';
import VADTalkMutedDetection from './modules/detection/VADTalkMutedDetection';
import { E2EEncryption } from './modules/e2ee/E2EEncryption';
import E2ePing from './modules/e2eping/e2eping';
import FeatureFlags from './modules/flags/FeatureFlags';
import { LiteModeContext } from './modules/litemode/LiteModeContext';
import { QualityController } from './modules/qualitycontrol/QualityController';
import { IReceiverVideoConstraints } from './modules/qualitycontrol/ReceiveVideoController';
import JibriSession from './modules/recording/JibriSession';
import RecordingManager, { IRecordingOptions } from './modules/recording/RecordingManager';
import Settings from './modules/settings/Settings';
import AvgRTPStatsReporter from './modules/statistics/AvgRTPStatsReporter';
import LocalStatsCollector from './modules/statistics/LocalStatsCollector';
import SpeakerStats from './modules/statistics/SpeakerStats';
import SpeakerStatsCollector from './modules/statistics/SpeakerStatsCollector';
import Statistics from './modules/statistics/statistics';
import Listenable from './modules/util/Listenable';
import { isValidNumber, safeSubtract } from './modules/util/MathUtil';
import RandomUtil from './modules/util/RandomUtil';
import { getJitterDelay } from './modules/util/Retry';
import { findAll, findFirst, getAttribute } from './modules/util/XMLUtils';
import ComponentsVersions from './modules/version/ComponentsVersions';
import JitsiVideoSIPGWSession from './modules/videosipgw/JitsiVideoSIPGWSession';
import VideoSIPGW from './modules/videosipgw/VideoSIPGW';
import * as VideoSIPGWConstants from './modules/videosipgw/VideoSIPGWConstants';
import BreakoutRooms from './modules/xmpp/BreakoutRooms';
import type { ChatRoom, PresenceHandler } from './modules/xmpp/ChatRoom';
import FileSharing from './modules/xmpp/FileSharing';
import type JingleSessionPC from './modules/xmpp/JingleSessionPC';
import { MediaSessionEvents } from './modules/xmpp/MediaSessionEvents';
import Polls from './modules/xmpp/Polls';
import RoomMetadata from './modules/xmpp/RoomMetadata';
import SignalingLayerImpl from './modules/xmpp/SignalingLayerImpl';
import XMPP, {
FEATURE_E2EE,
FEATURE_JIGASI,
IFaceLandmarksPayload,
JITSI_MEET_MUC_TYPE
} from './modules/xmpp/xmpp';
import { BridgeVideoType } from './service/RTC/BridgeVideoType';
import { CodecMimeType } from './service/RTC/CodecMimeType';
import { IceRestartReason } from './service/RTC/IceRestartReason';
import { MediaType } from './service/RTC/MediaType';
import { RTCEvents } from './service/RTC/RTCEvents';
import {
ILegacyReceiverAudioSubscriptionMessage,
IReceiverAudioSubscriptionMessage
} from './service/RTC/ReceiverAudioSubscription';
import { SignalingEvents } from './service/RTC/SignalingEvents';
import {
getMediaTypeFromSourceName,
getSourceNameForJitsiTrack,
isTranslatedSourceName
} from './service/RTC/SignalingLayer';
import { VideoType } from './service/RTC/VideoType';
import { MAX_CONNECTION_RETRIES } from './service/connectivity/Constants';
import {
AnalyticsEvents,
createConferenceEvent,
createJingleEvent,
createJvbIceFailedEvent,
createP2PEvent
} from './service/statistics/AnalyticsEvents';
import { XMPPEvents } from './service/xmpp/XMPPEvents';
export interface IConferenceOptions {
config: {
_p2pConnStatusRtcMuteTimeout?: number;
_peerConnStatusOutOfLastNTimeout?: number;
_peerConnStatusRtcMuteTimeout?: number;
analytics?: {
rtcstatsEnabled?: boolean;
rtcstatsEndpoint?: string;
};
applicationName?: string;
audioTranslation?: {
enabled?: boolean;
};
avgRtpStatsN?: number;
channelLastN?: number;
confID?: string;
createVADProcessor?: () => IVADProcessor;
deploymentInfo?: {
userRegion?: string;
};
disableAudioLevels?: boolean;
disableLocalStats?: boolean;
disableLocalStatsBroadcast?: boolean;
e2eping?: {
enabled?: boolean;
};
enableIceRestart?: boolean;
enableNoAudioDetection?: boolean;
enableNoisyMicDetection?: boolean;
enableTalkWhileMuted?: boolean;
hiddenDomain?: string;
p2p?: {
backToP2PDelay?: number;
codecPreferenceOrder?: string[];
disabledCodec?: string;
enabled?: boolean;
mobileCodecPreferenceOrder?: string[];
mobileScreenshareCodec?: string;
preferredCodec?: string;
screenshareCodec?: string;
};
pcStatsInterval?: number;
startAudioMuted?: number;
startLastN?: number;
startSilent?: boolean;
startVideoMuted?: number;
statisticsDisplayName?: string;
statisticsId?: string;
testing?: {
allowMultipleTracks?: boolean;
enableAV1ForFF?: boolean;
enableFirefoxP2p?: boolean;
forceInitiator?: boolean;
forceResponder?: boolean;
lastNRampupTime?: number;
p2pTestMode?: boolean;
};
transcriptionLanguage?: string;
videoQuality?: {
codecPreferenceOrder?: string[];
disabledCodec?: string;
enableAdaptiveMode?: boolean;
mobileCodecPreferenceOrder?: string[];
mobileScreenshareCodec?: string;
preferredCodec?: string;
screenshareCodec?: string;
};
};
connection: JitsiConnection;
customDomain?: string;
name: string;
}
export interface IStartMutedPolicy {
audio: boolean;
video: boolean;
}
export interface IConferenceProperties {
'audio-limit-reached'?: string;
'bridge-count'?: string;
'video-limit-reached'?: string;
'visitor-codecs'?: string;
'visitor-count'?: number;
}
export interface IStatisticsOptions {
aliasName?: string;
applicationName?: string;
confID?: string;
roomName?: string;
userName?: string;
}
export interface IStopSessionOptions {
reason?: string;
reasonDescription?: string;
requestRestart?: boolean;
sendSessionTerminate?: boolean;
}
const logger = getLogger('core:JitsiConference');
/**
* How long (ms) to keep an in-flight translation request around for error correlation. The component only
* replies on failure, so a request with no reply within this window is assumed to have succeeded.
*/
const TRANSLATION_REQUEST_TIMEOUT = 15000;
/**
* How long since Jicofo is supposed to send a session-initiate, before
* {@link ACTION_JINGLE_SI_TIMEOUT} analytics event is sent (in ms).
* @type {number}
*/
const JINGLE_SI_TIMEOUT: number = 5000;
/**
* How long (ms) to wait for ICE to recover after an in-place ICE restart (triggered by an ICE failure) before
* falling back to a session restart.
*/
const JVB_ICE_RESTART_RECOVERY_TIMEOUT = 15000;
/**
* Default source language for transcribing the local participant.
*/
const DEFAULT_TRANSCRIPTION_LANGUAGE: string = 'en-US';
/**
* Checks if a given string is a valid video codec mime type.
*
* @param {string} codec the codec string that needs to be validated.
* @returns {CodecMimeType|null} mime type if valid, null otherwise.
* @private
*/
function _getCodecMimeType(codec: string): Nullable<CodecMimeType> {
if (typeof codec === 'string') {
return Object.values(CodecMimeType).find(value => value === codec.toLowerCase()) || null;
}
return null;
}
/**
* Error returned by authenticateAndUpgradeRole when authentication or connection fails.
*/
interface IUpgradeRoleError {
authenticationError?: string;
connectionError?: JitsiConnectionEvents;
credentials?: {
jid?: string;
password?: string;
};
message?: string;
}
/**
* Options for authenticateAndUpgradeRole.
*/
interface IAuthenticateAndUpgradeRoleOptions {
id: string;
onCreateResource?: typeof JitsiConference.resourceCreator;
onLoginSuccessful?: () => void;
password: string;
}
interface IProcessWithCancel extends Promise<void> {
cancel: () => void;
}
/**
* Creates a JitsiConference object with the given name and properties.
* Note: this constructor is not a part of the public API (objects should be
* created using JitsiConnection.createConference).
* @param options.config properties / settings related to the conference that
* will be created.
* @param options.name the name of the conference
* @param options.connection the JitsiConnection object for this
* JitsiConference.
* @param {number} [options.config.avgRtpStatsN=15] how many samples are to be
* collected by `AvgRTPStatsReporter`, before arithmetic mean is
* calculated and submitted to the analytics module.
* @param {boolean} [options.config.p2p.enabled] when set to <tt>true</tt>
* the peer to peer mode will be enabled. It means that when there are only 2
* participants in the conference an attempt to make direct connection will be
* made. If the connection succeeds the conference will stop sending data
* through the JVB connection and will use the direct one instead.
* @param {number} [options.config.p2p.backToP2PDelay=5] a delay given in
* seconds, before the conference switches back to P2P, after the 3rd
* participant has left the room.
* @param {number} [options.config.channelLastN=-1] The requested amount of
* videos are going to be delivered after the value is in effect. Set to -1 for
* unlimited or all available videos.
*
* @noInheritDoc
*/
export default class JitsiConference extends Listenable {
private _transcribingEnabled?: boolean;
private _visitorCodecs?: string[];
private _hasVisitors?: boolean;
private _sessionInitiateTimeout?: number;
private _desktopSharingFrameRate?: number;
private _numberOfParticipantsOnJoin?: number;
private _delayedIceFailed?: IceFailedHandling;
private _audioAnalyser?: VADAudioAnalyser;
private _noAudioSignalDetection?: NoAudioSignalDetection;
private _signalingLayer: SignalingLayerImpl;
/**
* The default language remote audio is translated into for every speaker, or null when off.
* Per-participant overrides in {@link _participantTranslationLanguages} take precedence over this.
*/
private _receiverTranslationLanguage: string | null = null;
/**
* Per-participant translation overrides (endpointId -> language, or null to explicitly disable for
* that speaker). An entry present here wins over {@link _receiverTranslationLanguage}; an absent entry
* inherits the default. Set via {@link setParticipantTranslationLanguage}.
*/
private _participantTranslationLanguages: Map<string, string | null> = new Map();
/**
* Translation requests last advertised to the audio-translation module (endpointId -> language),
* used to send only the delta on roster changes.
*/
private _translationRequests: Map<string, string> = new Map();
/**
* In-flight translation-request deltas keyed by stanza id. The component only replies on failure
* (success is silent), so this maps an error reply back to the endpoints the failed request touched.
*/
private _pendingTranslationRequests: Map<string, { [endpointId: string]: string; }> = new Map();
/**
* The registered Strophe handler for translation-request error replies, or undefined when not registered.
* Stored so it can be removed from the (connection-scoped) handler list on {@link leave}.
*/
private _translationErrorHandler?: ReturnType<Strophe.Connection['addHandler']>;
// Stored so the (connection-scoped) translation-listeners handler can be removed on leave().
private _translationListenersHandler?: ReturnType<Strophe.Connection['addHandler']>;
/**
* Monotonic counter used to mint translation-request stanza ids for error correlation.
*/
private _translationRequestSeq = 0;
private _conferenceJoinAnalyticsEventSent?: number;
private _e2eEncryption?: E2EEncryption;
private _liteModeContext?: LiteModeContext;
private _audioSenderLimitReached?: boolean;
private _videoSenderLimitReached?: boolean;
private _firefoxP2pEnabled: boolean;
private _iceRestarts: number;
private _unsubscribers: Array<() => void>;
private _xmpp: XMPP;
/**
* @internal
*/
_statsCurrentId: string;
public options: IConferenceOptions;
public connection: JitsiConnection;
public eventManager: JitsiConferenceEventManager;
public participants: Map<string, JitsiParticipant>;
public componentsVersions: ComponentsVersions;
public jvbJingleSession?: JingleSessionPC;
public lastDominantSpeaker?: string;
public dtmfManager?: object;
public somebodySupportsDTMF: boolean;
public authEnabled: boolean;
public startMutedPolicy: IStartMutedPolicy;
public isMutedByFocus: boolean;
public mutedByFocusActor?: string;
public isVideoMutedByFocus: boolean;
public mutedVideoByFocusActor?: string;
public wasStopped: boolean;
public properties: IConferenceProperties;
public connectionQuality: ConnectionQuality;
public avgRtpStatsReporter?: AvgRTPStatsReporter;
public isJvbConnectionInterrupted: boolean;
public speakerStatsCollector: SpeakerStatsCollector;
public deferredStartP2PTask?: number;
public backToP2PDelay: number;
public isP2PConnectionInterrupted: boolean;
public p2p: boolean;
public p2pJingleSession?: JingleSessionPC;
public videoSIPGWHandler: VideoSIPGW;
public recordingManager: RecordingManager;
public room?: ChatRoom;
public e2eping?: E2ePing;
public rtc?: RTC;
public qualityController?: QualityController;
public statistics?: Statistics;
public p2pDominantSpeakerDetection?: P2PDominantSpeakerDetection;
public authIdentity?: string;
public p2pEstablishmentDuration?: number;
public jvbEstablishmentDuration?: number;
public isDesktopMutedByFocus: boolean;
public mutedDesktopByFocusActor?: string;
public dominantSpeakerIsSilent?: boolean;
/**
* @param {IConferenceOptions} options
*/
constructor(options: IConferenceOptions) {
super();
if (!options.name || options.name.toLowerCase() !== options.name.toString()) {
const errmsg
= 'Invalid conference name (no conference name passed or it '
+ 'contains invalid characters like capital letters)!';
const additionalLogMsg = options.name
? `roomName=${options.name}; condition - ${options.name.toLowerCase()}!==${options.name.toString()}`
: 'No room name passed!';
logger.error(`${errmsg} ${additionalLogMsg}`);
throw new Error(errmsg);
}
this.connection = options.connection;
this._xmpp = this.connection?.xmpp;
if (this._xmpp.isRoomCreated(options.name, options.customDomain)) {
const errmsg = 'A conference with the same name has already been created!';
delete this.connection;
delete this._xmpp;
logger.error(errmsg);
throw new Error(errmsg);
}
this.options = options;
this.eventManager = new JitsiConferenceEventManager(this);
/**
* List of all the participants in the conference.
* @type {Map<string, JitsiParticipant>}
*/
this.participants = new Map();
/**
* The signaling layer instance.
* @type {SignalingLayerImpl}
* @private
*/
this._signalingLayer = new SignalingLayerImpl();
this._init(options);
this.componentsVersions = new ComponentsVersions(this);
/**
* Jingle session instance for the JVB connection.
* @type {JingleSessionPC}
*/
this.jvbJingleSession = null;
this.lastDominantSpeaker = null;
this.dtmfManager = null;
this.somebodySupportsDTMF = false;
this.authEnabled = false;
this.startMutedPolicy = {
audio: false,
video: false
};
// AV Moderation.
this.isMutedByFocus = false;
this.isVideoMutedByFocus = false;
this.isDesktopMutedByFocus = false;
this.mutedByFocusActor = null;
this.mutedVideoByFocusActor = null;
this.mutedDesktopByFocusActor = null;
// Flag indicates if the 'onCallEnded' method was ever called on this
// instance. Used to log extra analytics event for debugging purpose.
// We need to know if the potential issue happened before or after
// the restart.
this.wasStopped = false;
// Conference properties, maintained by jicofo.
this.properties = {};
/**
* The object which monitors local and remote connection statistics (e.g.
* sending bitrate) and calculates a number which represents the connection
* quality.
*/
this.connectionQuality = new ConnectionQuality(this, this.eventEmitter, options);
/**
* Reports average RTP statistics to the analytics module.
* @type {AvgRTPStatsReporter}
*/
this.avgRtpStatsReporter = new AvgRTPStatsReporter(this, options.config.avgRtpStatsN || 15);
/**
* Indicates whether the connection is interrupted or not.
*/
this.isJvbConnectionInterrupted = false;
/**
* The object which tracks active speaker times
*/
this.speakerStatsCollector = new SpeakerStatsCollector(this);
/* P2P related fields below: */
/**
* Stores reference to deferred start P2P task. It's created when 3rd
* participant leaves the room in order to avoid ping pong effect (it
* could be just a page reload).
* @type {number|null}
*/
this.deferredStartP2PTask = null;
const delay = Number.parseInt(String(options.config.p2p?.backToP2PDelay || 5), 10);
/**
* A delay given in seconds, before the conference switches back to P2P
* after the 3rd participant has left.
* @type {number}
*/
this.backToP2PDelay = isValidNumber(delay) ? delay : 5;
logger.info(`backToP2PDelay: ${this.backToP2PDelay}`);
/**
* If set to <tt>true</tt> it means the P2P ICE is no longer connected.
* When <tt>false</tt> it means that P2P ICE (media) connection is up
* and running.
* @type {boolean}
*/
this.isP2PConnectionInterrupted = false;
/**
* Flag set to <tt>true</tt> when P2P session has been established
* (ICE has been connected) and this conference is currently in the peer to
* peer mode (P2P connection is the active one).
* @type {boolean}
*/
this.p2p = false;
/**
* A JingleSession for the direct peer to peer connection.
* @type {JingleSessionPC}
*/
this.p2pJingleSession = null;
this.videoSIPGWHandler = new VideoSIPGW(this.room);
this.recordingManager = new RecordingManager(this.room);
/**
* If the conference.joined event has been sent this will store the timestamp when it happened.
*
* @type {undefined|number}
* @private
*/
this._conferenceJoinAnalyticsEventSent = undefined;
/**
* End-to-End Encryption. Make it available if supported.
*/
if (this.isE2EESupported()) {
logger.info('End-to-End Encryption is supported');
this._e2eEncryption = new E2EEncryption(this);
}
if (FeatureFlags.isRunInLiteModeEnabled()) {
logger.info('Lite mode enabled');
this._liteModeContext = new LiteModeContext(this);
}
/**
* Flag set to <tt>true</tt> when Jicofo sends a presence message indicating that the max audio sender limit has
* been reached for the call. Once this is set, unmuting audio will be disabled
* from the client until it gets reset
* again by Jicofo.
*/
this._audioSenderLimitReached = undefined;
/**
* Flag set to <tt>true</tt> when Jicofo sends a presence message indicating that the max video sender limit has
* been reached for the call. Once this is set, unmuting video will be disabled
* from the client until it gets reset
* again by Jicofo.
*/
this._videoSenderLimitReached = undefined;
this._firefoxP2pEnabled = browser.isVersionGreaterThan(109)
&& (this.options.config.testing?.enableFirefoxP2p ?? true);
/**
* Number of times ICE restarts that have been attempted after ICE connectivity with the JVB was lost.
*/
this._iceRestarts = 0;
this._unsubscribers = [];
}
/**
* Create a resource for the a jid. We use the room nickname (the resource part
* of the occupant JID, see XEP-0045) as the endpoint ID in colibri. We require
* endpoint IDs to be 8 hex digits because in some cases they get serialized
* into a 32bit field.
*
* @param {string} jid - The id set onto the XMPP connection.
* @param {boolean} isAuthenticatedUser - Whether or not the user has connected
* to the XMPP service with a password.
* @returns {string}
*/
static resourceCreator(jid: string, isAuthenticatedUser: boolean): string {
let mucNickname: string;
if (isAuthenticatedUser) {
// For authenticated users generate a random ID.
mucNickname = RandomUtil.randomHexString(8).toLowerCase();
} else {
// Use first part of node for anonymous users if it matches format
mucNickname = Strophe.getNodeFromJid(jid)?.substr(0, 8)
.toLowerCase();
// But if this doesn't have the required format we just generate a new
// random nickname.
const re = /[0-9a-f]{8}/g;
if (!mucNickname || !re.test(mucNickname)) {
mucNickname = RandomUtil.randomHexString(8).toLowerCase();
}
}
return mucNickname;
}
/**
* Initializes the conference object properties
* @param options {object}
* @param options.connection {JitsiConnection} overrides this.connection
*/
private _init(options: IConferenceOptions): void {
this.eventManager.setupXMPPListeners();
const { config } = this.options;
this._statsCurrentId = config.statisticsId ?? Settings.callStatsUserName;
this.room = this._xmpp.createRoom(
this.options.name, {
...config,
statsId: this._statsCurrentId
},
JitsiConference.resourceCreator
);
this._signalingLayer.setChatRoom(this.room);
this._signalingLayer.on(
SignalingEvents.SOURCE_UPDATED,
(sourceName, endpointId, muted, videoType) => {
const participant = this.participants.get(endpointId);
const mediaType = getMediaTypeFromSourceName(sourceName);
if (participant) {
participant._setSources(mediaType, muted, sourceName, videoType);
this.eventEmitter.emit(JitsiConferenceEvents.PARTICIPANT_SOURCE_UPDATED, participant);
}
});
// ICE Connection interrupted/restored listeners.
this._onIceConnectionEstablished = this._onIceConnectionEstablished.bind(this);
this.room.addListener(XMPPEvents.CONNECTION_ESTABLISHED, this._onIceConnectionEstablished);
this._onIceConnectionFailed = this._onIceConnectionFailed.bind(this);
this.room.addListener(XMPPEvents.CONNECTION_ICE_FAILED, this._onIceConnectionFailed);
this._onIceConnectionInterrupted = this._onIceConnectionInterrupted.bind(this);
this.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, this._onIceConnectionInterrupted);
this._onIceConnectionRestored = this._onIceConnectionRestored.bind(this);
this.room.addListener(XMPPEvents.CONNECTION_RESTORED, this._onIceConnectionRestored);
this._onP2PTerminationRequired = this._onP2PTerminationRequired.bind(this);
this.room.addListener(XMPPEvents.P2P_TERMINATION_REQUIRED, this._onP2PTerminationRequired);
this._updateProperties = this._updateProperties.bind(this);
this.room.addListener(XMPPEvents.CONFERENCE_PROPERTIES_CHANGED, this._updateProperties);
this._sendConferenceJoinAnalyticsEvent = this._sendConferenceJoinAnalyticsEvent.bind(this);
this.room.addListener(XMPPEvents.MEETING_ID_SET, this._sendConferenceJoinAnalyticsEvent);
this._removeLocalSourceOnReject = this._removeLocalSourceOnReject.bind(this);
this._updateRoomPresence = this._updateRoomPresence.bind(this);
this.room.addListener(XMPPEvents.SESSION_ACCEPT, this._updateRoomPresence);
this.room.addListener(XMPPEvents.SOURCE_ADD, this._updateRoomPresence);
this.room.addListener(XMPPEvents.SOURCE_ADD_ERROR, this._removeLocalSourceOnReject);
this.room.addListener(XMPPEvents.SOURCE_REMOVE, this._updateRoomPresence);
if (config.e2eping?.enabled) {
this.e2eping = new E2ePing(
this,
config,
(message, to) => {
try {
this.sendMessage(message, to, true /* sendThroughVideobridge */);
} catch (error) {
logger.warn('Failed to send E2E ping request or response.', error?.msg);
}
});
}
if (!this.rtc) {
this.rtc = new RTC(this, options);
this.eventManager.setupRTCListeners();
this._registerRtcListeners(this.rtc);
}
// Get the codec preference settings from config.js.
const qualityOptions = {
enableAdaptiveMode: config.videoQuality?.enableAdaptiveMode,
jvb: {
disabledCodec: _getCodecMimeType(config.videoQuality?.disabledCodec),
enableAV1ForFF: config.testing?.enableAV1ForFF,
preferenceOrder: browser.isMobileDevice()
? config.videoQuality?.mobileCodecPreferenceOrder
: config.videoQuality?.codecPreferenceOrder,
preferredCodec: _getCodecMimeType(config.videoQuality?.preferredCodec),
screenshareCodec: browser.isMobileDevice()
? _getCodecMimeType(config.videoQuality?.mobileScreenshareCodec)
: _getCodecMimeType(config.videoQuality?.screenshareCodec)
},
lastNRampupTime: config.testing?.lastNRampupTime ?? 60000,
p2p: {
disabledCodec: _getCodecMimeType(config.p2p?.disabledCodec),
enableAV1ForFF: true, // For P2P no simulcast is needed, therefore AV1 can be used.
preferenceOrder: browser.isMobileDevice()
? config.p2p?.mobileCodecPreferenceOrder
: config.p2p?.codecPreferenceOrder,
preferredCodec: _getCodecMimeType(config.p2p?.preferredCodec),
screenshareCodec: browser.isMobileDevice()
? _getCodecMimeType(config.p2p?.mobileScreenshareCodec)
: _getCodecMimeType(config.p2p?.screenshareCodec)
}
};
this.qualityController = new QualityController(this, qualityOptions);
if (!this.statistics) {
this.statistics = new Statistics(this, {
// @ts-ignore
aliasName: this._statsCurrentId,
applicationName: config.applicationName,
confID: config.confID ?? `${this.connection.options.hosts.domain}/${this.options.name}`,
roomName: this.options.name,
userName: config.statisticsDisplayName ?? this.myUserId()
});
Statistics.analytics.addPermanentProperties({
'callstats_name': this._statsCurrentId
});
}
this.eventManager.setupChatRoomListeners();
// Always add listeners because on reload we are executing leave and the
// listeners are removed from statistics module.
this.eventManager.setupStatisticsListeners();
// Disable VAD processing on Safari since it causes audio input to
// fail on some of the mobile devices.
if (config.enableTalkWhileMuted && browser.supportsVADDetection()) {
// If VAD processor factory method is provided uses VAD based detection, otherwise fallback to audio level
// based detection.
if (config.createVADProcessor) {
logger.info('Using VAD detection for generating talk while muted events');
if (!this._audioAnalyser) {
this._audioAnalyser = new VADAudioAnalyser(this, config.createVADProcessor);
}
const vadTalkMutedDetection = new VADTalkMutedDetection();
vadTalkMutedDetection.on(DetectionEvents.VAD_TALK_WHILE_MUTED, () =>
this.eventEmitter.emit(JitsiConferenceEvents.TALK_WHILE_MUTED));
this._audioAnalyser.addVADDetectionService(vadTalkMutedDetection);
} else {
logger.warn('No VAD Processor was provided. Talk while muted detection service was not initialized!');
}
}
// Disable noisy mic detection on safari since it causes the audio input to
// fail on Safari on iPadOS.
if (config.enableNoisyMicDetection && browser.supportsVADDetection()) {
if (config.createVADProcessor) {
if (!this._audioAnalyser) {
this._audioAnalyser = new VADAudioAnalyser(this, config.createVADProcessor);
}
const vadNoiseDetection = new VADNoiseDetection();
vadNoiseDetection.on(DetectionEvents.VAD_NOISY_DEVICE, () =>
this.eventEmitter.emit(JitsiConferenceEvents.NOISY_MIC));
this._audioAnalyser.addVADDetectionService(vadNoiseDetection);
} else {
logger.warn('No VAD Processor was provided. Noisy microphone detection service was not initialized!');
}
}
// Generates events based on no audio input detector.
if (config.enableNoAudioDetection && !config.disableAudioLevels
&& LocalStatsCollector.isLocalStatsSupported()) {
this._noAudioSignalDetection = new NoAudioSignalDetection(this);
this._noAudioSignalDetection.on(DetectionEvents.NO_AUDIO_INPUT, () =>
this.eventEmitter.emit(JitsiConferenceEvents.NO_AUDIO_INPUT));
this._noAudioSignalDetection.on(DetectionEvents.AUDIO_INPUT_STATE_CHANGE, hasAudioSignal =>
this.eventEmitter.emit(JitsiConferenceEvents.AUDIO_INPUT_STATE_CHANGE, hasAudioSignal));
}
if ('channelLastN' in config) {
this.setLastN(config.channelLastN);
}
// creates dominant speaker detection that works only in p2p mode
this.p2pDominantSpeakerDetection = new P2PDominantSpeakerDetection(this);
// TODO: Drop this after the change to use the region from the http requests
// to prosody is propagated to majority of deployments
if (config?.deploymentInfo?.userRegion) {
this.setLocalParticipantProperty('region', config.deploymentInfo.userRegion);
}
// Publish the codec preference to presence.
this.setLocalParticipantProperty('codecList',
this.qualityController.codecController.getCodecPreferenceList('jvb'));
// Set transcription language presence extension.
// In case the language config is undefined or has the default value that the transcriber uses
// (in our case Jigasi uses 'en-US'), don't set the participant property in order to avoid
// needlessly polluting the presence stanza.
const transcriptionLanguage = config?.transcriptionLanguage ?? DEFAULT_TRANSCRIPTION_LANGUAGE;
if (transcriptionLanguage !== DEFAULT_TRANSCRIPTION_LANGUAGE) {
this.setTranscriptionLanguage(transcriptionLanguage);
}
}
/**
* Registers event listeners on the RTC instance.
* @param {RTC} rtc - the RTC module instance used by this conference.
* @private
* @returns {void}
*/
private _registerRtcListeners(rtc: RTC): void {
rtc.addListener(RTCEvents.DATA_CHANNEL_OPEN, () => {
for (const localTrack of this.rtc.localTracks) {
localTrack.isVideoTrack() && this._sendBridgeVideoTypeMessage(localTrack);
}
// (Re)establish the audio subscription on the bridge whenever the channel opens. Defaults to ALL
// until translation is enabled, at which point the Include list is sent instead. Only when the
// audio-translation feature is enabled — otherwise leave the bridge's default subscription untouched.
if (this.options.config.audioTranslation?.enabled) {
this.qualityController.audioController.resendSubscription();
}
});
}
/**
* Sends a conference.join analytics event.
*
* @returns {void}
*/
private _sendConferenceJoinAnalyticsEvent(): void {
const meetingId = this.getMeetingUniqueId();
if (this._conferenceJoinAnalyticsEventSent || !meetingId || this.getActivePeerConnection() === null) {
return;
}
const conferenceConnectionTimes = this.getConnectionTimes();
const xmppConnectionTimes = this.connection.getConnectionTimes();
const gumStart = window.connectionTimes['firstObtainPermissions.start'];
const gumEnd = window.connectionTimes['firstObtainPermissions.end'];
const globalNSConnectionTimes = window.JitsiMeetJS?.app?.connectionTimes ?? {};
const connectionTimes = {
...conferenceConnectionTimes,
...xmppConnectionTimes,
...globalNSConnectionTimes,
connectedToMUCJoinedTime: safeSubtract(
conferenceConnectionTimes['muc.joined'], xmppConnectionTimes.connected),
connectingToMUCJoinedTime: safeSubtract(
conferenceConnectionTimes['muc.joined'], xmppConnectionTimes.connecting),
gumDuration: safeSubtract(gumEnd, gumStart),
numberOfParticipantsOnJoin: this._numberOfParticipantsOnJoin,
xmppConnectingTime: safeSubtract(xmppConnectionTimes.connected, xmppConnectionTimes.connecting)
};
Statistics.sendAnalytics(createConferenceEvent('joined', {
...connectionTimes,
meetingId,
participantId: `${meetingId}.${this._statsCurrentId}`,
supportsTurnInRoomMetadata: true
}));
this._conferenceJoinAnalyticsEventSent = Date.now();
}
/**
* Sends conference.left analytics event.
* @private
*/
private _sendConferenceLeftAnalyticsEvent(): void {
const meetingId = this.getMeetingUniqueId();
if (!meetingId || !this._conferenceJoinAnalyticsEventSent) {
return;
}
Statistics.sendAnalytics(createConferenceEvent('left', {
meetingId,
participantId: `${meetingId}.${this._statsCurrentId}`,
stats: {
duration: Math.floor((Date.now() - this._conferenceJoinAnalyticsEventSent) / 1000)
}
}));
}
/**
* Restarts all active media sessions.
*
* @returns {void}
*/
private _restartMediaSessions(): void {
if (this.p2pJingleSession) {
this._stopP2PSession({
reasonDescription: 'restart',
requestRestart: true
});
}
if (this.jvbJingleSession) {
this._stopJvbSession({
reason: 'success',
reasonDescription: 'restart required',
requestRestart: true,
sendSessionTerminate: true
});
}
this._maybeStartOrStopP2P(false);
}
/**
* Fires TRACK_AUDIO_LEVEL_CHANGED change conference event (for local tracks).
* @param {number} audioLevel - The audio level.
* @param {TraceablePeerConnection} [tpc] - The peer connection.
* @private
*/
private _fireAudioLevelChangeEvent(audioLevel: number, tpc: TraceablePeerConnection): void {
const activeTpc = this.getActivePeerConnection();
// There will be no TraceablePeerConnection if audio levels do not come from
// a peerconnection. LocalStatsCollector.js measures audio levels using Web
// Audio Analyser API and emits local audio levels events through
// JitsiTrack.setAudioLevel, but does not provide TPC instance which is
// optional.
if (!tpc || activeTpc === tpc) {
this.eventEmitter.emit(
JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
this.myUserId(), audioLevel);
}
}
/**
* Fires TRACK_MUTE_CHANGED change conference event.
* @param {JitsiLocalTrack} track - The JitsiTrack object related to the event.
*/
private _fireMuteChangeEvent(track: JitsiLocalTrack): void {
// check if track was muted by focus and now is unmuted by user
if (this.isMutedByFocus && track.isAudioTrack() && !track.isMuted()) {
this.isMutedByFocus = false;
// unmute local user on server
this.room.muteParticipant(this.room.myroomjid, false, MediaType.AUDIO);
} else if (this.isVideoMutedByFocus && track.isVideoTrack()
&& track.getVideoType() !== VideoType.DESKTOP && !track.isMuted()) {
this.isVideoMutedByFocus = false;
// unmute local user on server
this.room.muteParticipant(this.room.myroomjid, false, MediaType.VIDEO);
} else if (this.isDesktopMutedByFocus && track.isVideoTrack()
&& track.getVideoType() === VideoType.DESKTOP && !track.isMuted()) {
this.isDesktopMutedByFocus = false;
// unmute local user on server
this.room.muteParticipant(this.room.myroomjid, false, MediaType.DESKTOP);
}
let actorParticipant;
if (this.mutedByFocusActor && track.isAudioTrack()) {
const actorId = Strophe.getResourceFromJid(this.mutedByFocusActor);
actorParticipant = this.participants.get(actorId);
} else if (this.mutedVideoByFocusActor && track.isVideoTrack()
&& track.getVideoType() !== VideoType.DESKTOP) {
const actorId = Strophe.getResourceFromJid(this.mutedVideoByFocusActor);
actorParticipant = this.participants.get(actorId);
} else if (this.mutedDesktopByFocusActor && track.isVideoTrack()
&& track.getVideoType() === VideoType.DESKTOP) {
const actorId = Strophe.getResourceFromJid(this.mutedDesktopByFocusActor);
actorParticipant = this.participants.get(actorId);