forked from jitsi/lib-jitsi-meet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JitsiConference.js
4134 lines (3556 loc) · 139 KB
/
JitsiConference.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { getLogger } from '@jitsi/logger';
import $ from 'jquery';
import isEqual from 'lodash.isequal';
import { Strophe } from 'strophe.js';
import * as JitsiConferenceErrors from './JitsiConferenceErrors';
import JitsiConferenceEventManager from './JitsiConferenceEventManager';
import * as JitsiConferenceEvents from './JitsiConferenceEvents';
import JitsiParticipant from './JitsiParticipant';
import JitsiTrackError from './JitsiTrackError';
import * as JitsiTrackErrors from './JitsiTrackErrors';
import * as JitsiTrackEvents from './JitsiTrackEvents';
import authenticateAndUpgradeRole from './authenticateAndUpgradeRole';
import { CodecSelection } from './modules/RTC/CodecSelection';
import RTC from './modules/RTC/RTC';
import { SS_DEFAULT_FRAME_RATE } from './modules/RTC/ScreenObtainer';
import browser from './modules/browser';
import ConnectionQuality from './modules/connectivity/ConnectionQuality';
import IceFailedHandling from './modules/connectivity/IceFailedHandling';
import * as DetectionEvents from './modules/detection/DetectionEvents';
import NoAudioSignalDetection from './modules/detection/NoAudioSignalDetection';
import P2PDominantSpeakerDetection from './modules/detection/P2PDominantSpeakerDetection';
import VADAudioAnalyser 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 Jvb121EventGenerator from './modules/event/Jvb121EventGenerator';
import FeatureFlags from './modules/flags/FeatureFlags';
import { LiteModeContext } from './modules/litemode/LiteModeContext';
import ReceiveVideoController from './modules/qualitycontrol/ReceiveVideoController';
import SendVideoController from './modules/qualitycontrol/SendVideoController';
import RecordingManager from './modules/recording/RecordingManager';
import Settings from './modules/settings/Settings';
import AudioOutputProblemDetector from './modules/statistics/AudioOutputProblemDetector';
import AvgRTPStatsReporter from './modules/statistics/AvgRTPStatsReporter';
import LocalStatsCollector from './modules/statistics/LocalStatsCollector';
import SpeakerStatsCollector from './modules/statistics/SpeakerStatsCollector';
import Statistics from './modules/statistics/statistics';
import EventEmitter from './modules/util/EventEmitter';
import { safeSubtract } from './modules/util/MathUtil';
import RandomUtil from './modules/util/RandomUtil';
import ComponentsVersions from './modules/version/ComponentsVersions';
import VideoSIPGW from './modules/videosipgw/VideoSIPGW';
import * as VideoSIPGWConstants from './modules/videosipgw/VideoSIPGWConstants';
import SignalingLayerImpl from './modules/xmpp/SignalingLayerImpl';
import {
FEATURE_E2EE,
FEATURE_JIGASI,
JITSI_MEET_MUC_TYPE
} from './modules/xmpp/xmpp';
import { BridgeVideoType } from './service/RTC/BridgeVideoType';
import { CodecMimeType } from './service/RTC/CodecMimeType';
import { MediaType } from './service/RTC/MediaType';
import RTCEvents from './service/RTC/RTCEvents';
import { SignalingEvents } from './service/RTC/SignalingEvents';
import { getMediaTypeFromSourceName, getSourceNameForJitsiTrack } from './service/RTC/SignalingLayer';
import { VideoType } from './service/RTC/VideoType';
import {
ACTION_JINGLE_RESTART,
ACTION_JINGLE_SI_RECEIVED,
ACTION_JINGLE_SI_TIMEOUT,
ACTION_JINGLE_TERMINATE,
ACTION_P2P_DECLINED,
ACTION_P2P_ESTABLISHED,
ACTION_P2P_FAILED,
ACTION_P2P_SWITCH_TO_JVB,
ICE_ESTABLISHMENT_DURATION_DIFF,
createConferenceEvent,
createJingleEvent,
createP2PEvent
} from './service/statistics/AnalyticsEvents';
import { XMPPEvents } from './service/xmpp/XMPPEvents';
const logger = getLogger(__filename);
/**
* 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 = 5000;
/**
* 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) {
if (typeof codec === 'string') {
return Object.values(CodecMimeType).find(value => value === codec.toLowerCase());
}
return null;
}
/**
* 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 {@link AvgRTPStatsReporter}, before arithmetic mean is
* calculated and submitted to the analytics module.
* @param {boolean} [options.config.enableIceRestart=false] - enables the ICE
* restart logic.
* @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.
* @constructor
*
* FIXME Make all methods which are called from lib-internal classes
* to non-public (use _). To name a few:
* {@link JitsiConference.onLocalRoleChanged}
* {@link JitsiConference.onUserRoleChanged}
* {@link JitsiConference.onMemberLeft}
* and so on...
*/
export default function JitsiConference(options) {
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.eventEmitter = new EventEmitter();
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.startAudioMuted = false;
this.startVideoMuted = false;
this.startMutedPolicy = {
audio: false,
video: false
};
this.isMutedByFocus = false;
// when muted by focus we receive the jid of the initiator of the mute
this.mutedByFocusActor = null;
this.isVideoMutedByFocus = false;
// when video muted by focus we receive the jid of the initiator of the mute
this.mutedVideoByFocusActor = 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);
/**
* Detects issues with the audio of remote participants.
* @type {AudioOutputProblemDetector}
*/
if (!options.config.disableAudioLevels) {
this._audioOutputProblemDetector = new AudioOutputProblemDetector(this);
}
/**
* 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
= parseInt(options.config.p2p && options.config.p2p.backToP2PDelay, 10);
/**
* A delay given in seconds, before the conference switches back to P2P
* after the 3rd participant has left.
* @type {number}
*/
this.backToP2PDelay = isNaN(delay) ? 5 : delay;
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);
}
// FIXME convert JitsiConference to ES6 - ASAP !
JitsiConference.prototype.constructor = JitsiConference;
/**
* 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
*/
JitsiConference.resourceCreator = function(jid, isAuthenticatedUser) {
let mucNickname;
if (isAuthenticatedUser) {
// For authenticated users generate a random ID.
mucNickname = RandomUtil.randomHexString(8).toLowerCase();
} else {
// We try to use the first part of the node (which for anonymous users
// on prosody is a UUID) to match the previous behavior (and maybe make
// debugging easier).
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
*/
JitsiConference.prototype._init = function(options = {}) {
this.eventManager.setupXMPPListeners();
const { config } = this.options;
// Get the codec preference settings from config.js.
const codecSettings = {
jvb: {
preferenceOrder: browser.isMobileDevice() && config.videoQuality?.mobileCodecPreferenceOrder
? config.videoQuality.mobileCodecPreferenceOrder
: config.videoQuality?.codecPreferenceOrder,
disabledCodec: _getCodecMimeType(config.videoQuality?.disabledCodec),
preferredCodec: _getCodecMimeType(config.videoQuality?.preferredCodec),
supportsAv1: config.testing?.enableAv1Support
},
p2p: {
preferenceOrder: browser.isMobileDevice() && config.p2p?.mobileCodecPreferenceOrder
? config.p2p.mobileCodecPreferenceOrder
: config.p2p?.codecPreferenceOrder,
disabledCodec: _getCodecMimeType(config.p2p?.disabledCodec),
preferredCodec: _getCodecMimeType(config.p2p?.preferredCodec)
}
};
this.codecSelection = new CodecSelection(this, codecSettings);
this._statsCurrentId = config.statisticsId ? 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);
}
});
// Connection interrupted/restored listeners
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._onIceConnectionEstablished
= this._onIceConnectionEstablished.bind(this);
this.room.addListener(
XMPPEvents.CONNECTION_ESTABLISHED, this._onIceConnectionEstablished);
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 && error.msg);
}
});
}
if (!this.rtc) {
this.rtc = new RTC(this, options);
this.eventManager.setupRTCListeners();
this._registerRtcListeners(this.rtc);
}
this.receiveVideoController = new ReceiveVideoController(this, this.rtc);
this.sendVideoController = new SendVideoController(this, this.rtc);
if (!this.statistics) {
this.statistics = new Statistics(this, {
aliasName: this._statsCurrentId,
userName: config.statisticsDisplayName ? config.statisticsDisplayName : this.myUserId(),
confID: config.confID || `${this.connection.options.hosts.domain}/${this.options.name}`,
roomName: this.options.name,
applicationName: config.applicationName
});
Statistics.analytics.addPermanentProperties({
'callstats_name': this._statsCurrentId
});
// Start performance observer for monitoring long tasks
if (config.longTasksStatsInterval) {
this.statistics.attachLongTasksStats();
}
}
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);
}
/**
* Emits {@link JitsiConferenceEvents.JVB121_STATUS}.
* @type {Jvb121EventGenerator}
*/
this.jvb121Status = new Jvb121EventGenerator(this);
// creates dominant speaker detection that works only in p2p mode
this.p2pDominantSpeakerDetection = new P2PDominantSpeakerDetection(this);
if (config && config.deploymentInfo && config.deploymentInfo.userRegion) {
this.setLocalParticipantProperty(
'region', config.deploymentInfo.userRegion);
}
// Publish the codec preference to presence.
this.setLocalParticipantProperty('codecList', this.codecSelection.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.
if (config && config.transcriptionLanguage && config.transcriptionLanguage !== 'en-US') {
this.setLocalParticipantProperty('transcription_language', config.transcriptionLanguage);
}
};
/**
* Joins the conference.
* @param password {string} the password
* @param replaceParticipant {boolean} whether the current join replaces
* an existing participant with same jwt from the meeting.
*/
JitsiConference.prototype.join = function(password, replaceParticipant = false) {
if (this.room) {
this.room.join(password, replaceParticipant).then(() => this._maybeSetSITimeout());
}
};
/**
* Authenticates and upgrades the role of the local participant/user.
*
* @returns {Object} A <tt>thenable</tt> which (1) settles when the process of
* authenticating and upgrading the role of the local participant/user finishes
* and (2) has a <tt>cancel</tt> method that allows the caller to interrupt the
* process.
*/
JitsiConference.prototype.authenticateAndUpgradeRole = function(options) {
return authenticateAndUpgradeRole.call(this, {
...options,
onCreateResource: JitsiConference.resourceCreator
});
};
/**
* Check if joined to the conference.
*/
JitsiConference.prototype.isJoined = function() {
return this.room && this.room.joined;
};
/**
* Tells whether or not the P2P mode is enabled in the configuration.
* @return {boolean}
*/
JitsiConference.prototype.isP2PEnabled = function() {
return Boolean(this.options.config.p2p && this.options.config.p2p.enabled)
// FIXME: remove once we have a default config template. -saghul
|| typeof this.options.config.p2p === 'undefined';
};
/**
* When in P2P test mode, the conference will not automatically switch to P2P
* when there 2 participants.
* @return {boolean}
*/
JitsiConference.prototype.isP2PTestModeEnabled = function() {
return Boolean(this.options.config.testing
&& this.options.config.testing.p2pTestMode);
};
/**
* Leaves the conference.
* @param reason {string|undefined} The reason for leaving the conference.
* @returns {Promise}
*/
JitsiConference.prototype.leave = async function(reason) {
if (this.avgRtpStatsReporter) {
this.avgRtpStatsReporter.dispose();
this.avgRtpStatsReporter = null;
}
if (this._audioOutputProblemDetector) {
this._audioOutputProblemDetector.dispose();
this._audioOutputProblemDetector = null;
}
if (this.e2eping) {
this.e2eping.stop();
this.e2eping = null;
}
this.getLocalTracks().forEach(track => this.onLocalTrackRemoved(track));
this.rtc.closeBridgeChannel();
this._sendConferenceLeftAnalyticsEvent();
if (this.statistics) {
this.statistics.dispose();
}
this._delayedIceFailed && this._delayedIceFailed.cancel();
this._maybeClearSITimeout();
// Close both JVb and P2P JingleSessions
if (this.jvbJingleSession) {
this.jvbJingleSession.close();
this.jvbJingleSession = null;
}
if (this.p2pJingleSession) {
this.p2pJingleSession.close();
this.p2pJingleSession = null;
}
// Leave the conference. If this.room == null we are calling second time leave().
if (!this.room) {
throw new Error('You have already left the conference');
}
const room = this.room;
// Unregister connection state listeners
room.removeListener(
XMPPEvents.CONNECTION_INTERRUPTED,
this._onIceConnectionInterrupted);
room.removeListener(
XMPPEvents.CONNECTION_RESTORED,
this._onIceConnectionRestored);
room.removeListener(
XMPPEvents.CONNECTION_ESTABLISHED,
this._onIceConnectionEstablished);
room.removeListener(
XMPPEvents.CONFERENCE_PROPERTIES_CHANGED,
this._updateProperties);
room.removeListener(XMPPEvents.MEETING_ID_SET, this._sendConferenceJoinAnalyticsEvent);
room.removeListener(XMPPEvents.SESSION_ACCEPT, this._updateRoomPresence);
room.removeListener(XMPPEvents.SOURCE_ADD, this._updateRoomPresence);
room.removeListener(XMPPEvents.SOURCE_ADD_ERROR, this._removeLocalSourceOnReject);
room.removeListener(XMPPEvents.SOURCE_REMOVE, this._updateRoomPresence);
this.eventManager.removeXMPPListeners();
this._signalingLayer.setChatRoom(null);
this.room = null;
let leaveError;
try {
await room.leave(reason);
} catch (err) {
leaveError = err;
// Remove all participants because currently the conference
// won't be usable anyway. This is done on success automatically
// by the ChatRoom instance.
this.getParticipants().forEach(
participant => this.onMemberLeft(participant.getJid()));
}
if (this.rtc) {
this.rtc.destroy();
}
if (leaveError) {
throw leaveError;
}
};
/**
* Returns <tt>true</tt> if end conference support is enabled in the backend.
*
* @returns {boolean} whether end conference is supported in the backend.
*/
JitsiConference.prototype.isEndConferenceSupported = function() {
return Boolean(this.room && this.room.xmpp.endConferenceComponentAddress);
};
/**
* Ends the conference.
*/
JitsiConference.prototype.end = function() {
if (!this.isEndConferenceSupported()) {
logger.warn('Cannot end conference: is not supported.');
return;
}
if (!this.room) {
throw new Error('You have already left the conference');
}
this.room.end();
};
/**
* Returns the currently active media session if any.
*
* @returns {JingleSessionPC|undefined}
*/
JitsiConference.prototype.getActiveMediaSession = function() {
return this.isP2PActive() ? this.p2pJingleSession : this.jvbJingleSession;
};
/**
* Returns an array containing all media sessions existing in this conference.
*
* @returns {Array<JingleSessionPC>}
*/
JitsiConference.prototype.getMediaSessions = function() {
const sessions = [];
this.jvbJingleSession && sessions.push(this.jvbJingleSession);
this.p2pJingleSession && sessions.push(this.p2pJingleSession);
return sessions;
};
/**
* Registers event listeners on the RTC instance.
* @param {RTC} rtc - the RTC module instance used by this conference.
* @private
* @returns {void}
*/
JitsiConference.prototype._registerRtcListeners = function(rtc) {
rtc.addListener(RTCEvents.DATA_CHANNEL_OPEN, () => {
for (const localTrack of this.rtc.localTracks) {
localTrack.isVideoTrack() && this._sendBridgeVideoTypeMessage(localTrack);
}
});
};
/**
* Sends the 'VideoTypeMessage' to the bridge on the bridge channel so that the bridge can make bitrate allocation
* decisions based on the video type of the local source.
*
* @param {JitsiLocalTrack} localtrack - The track associated with the local source signaled to the bridge.
* @returns {void}
* @private
*/
JitsiConference.prototype._sendBridgeVideoTypeMessage = function(localtrack) {
let videoType = !localtrack || localtrack.isMuted() ? BridgeVideoType.NONE : localtrack.getVideoType();
if (videoType === BridgeVideoType.DESKTOP && this._desktopSharingFrameRate > SS_DEFAULT_FRAME_RATE) {
videoType = BridgeVideoType.DESKTOP_HIGH_FPS;
}
localtrack && this.rtc.sendSourceVideoType(localtrack.getSourceName(), videoType);
};
/**
* Returns name of this conference.
*/
JitsiConference.prototype.getName = function() {
return this.options.name.toString();
};
/**
* Returns the {@link JitsiConnection} used by this this conference.
*/
JitsiConference.prototype.getConnection = function() {
return this.connection;
};
/**
* Check if authentication is enabled for this conference.
*/
JitsiConference.prototype.isAuthEnabled = function() {
return this.authEnabled;
};
/**
* Check if user is logged in.
*/
JitsiConference.prototype.isLoggedIn = function() {
return Boolean(this.authIdentity);
};
/**
* Get authorized login.
*/
JitsiConference.prototype.getAuthLogin = function() {
return this.authIdentity;
};
/**
* Returns the local tracks of the given media type, or all local tracks if no
* specific type is given.
* @param {MediaType} [mediaType] Optional media type (audio or video).
*/
JitsiConference.prototype.getLocalTracks = function(mediaType) {
let tracks = [];
if (this.rtc) {
tracks = this.rtc.getLocalTracks(mediaType);
}
return tracks;
};
/**
* Obtains local audio track.
* @return {JitsiLocalTrack|null}
*/
JitsiConference.prototype.getLocalAudioTrack = function() {
return this.rtc ? this.rtc.getLocalAudioTrack() : null;
};
/**
* Obtains local video track.
* @return {JitsiLocalTrack|null}
*/
JitsiConference.prototype.getLocalVideoTrack = function() {
return this.rtc ? this.rtc.getLocalVideoTrack() : null;
};
/**
* Returns all the local video tracks.
* @returns {Array<JitsiLocalTrack>}
*/
JitsiConference.prototype.getLocalVideoTracks = function() {
return this.rtc ? this.rtc.getLocalVideoTracks() : null;
};
/**
* Obtains the performance statistics.
* @returns {Object|null}
*/
JitsiConference.prototype.getPerformanceStats = function() {
return {
longTasksStats: this.statistics.getLongTasksStats()
};
};
/**
* Attaches a handler for events(For example - "participant joined".) in the
* conference. All possible event are defined in JitsiConferenceEvents.
* @param eventId the event ID.
* @param handler handler for the event.
*
* Note: consider adding eventing functionality by extending an EventEmitter
* impl, instead of rolling ourselves
*/
JitsiConference.prototype.on = function(eventId, handler) {
if (this.eventEmitter) {
this.eventEmitter.on(eventId, handler);
}
};
/**
* Adds a one-time`listener` function for the event.
* @param eventId the event ID.
* @param handler handler for the event.
*
*/
JitsiConference.prototype.once = function(eventId, handler) {
if (this.eventEmitter) {
this.eventEmitter.once(eventId, handler);
}
};
/**
* Removes event listener
* @param eventId the event ID.
* @param [handler] optional, the specific handler to unbind
*
* Note: consider adding eventing functionality by extending an EventEmitter
* impl, instead of rolling ourselves
*/
JitsiConference.prototype.off = function(eventId, handler) {
if (this.eventEmitter) {
this.eventEmitter.removeListener(eventId, handler);
}
};
// Common aliases for event emitter
JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
/**
* Receives notifications from other participants about commands / custom events
* (sent by sendCommand or sendCommandOnce methods).
* @param command {String} the name of the command
* @param handler {Function} handler for the command
*/
JitsiConference.prototype.addCommandListener = function(command, handler) {
if (this.room) {
this.room.addPresenceListener(command, handler);
}
};
/**
* Removes command listener
* @param command {String} the name of the command
* @param handler {Function} handler to remove for the command
*/
JitsiConference.prototype.removeCommandListener = function(command, handler) {
if (this.room) {
this.room.removePresenceListener(command, handler);
}
};
/**
* Sends text message to the other participants in the conference
* @param message the text message.
* @param elementName the element name to encapsulate the message.
* @deprecated Use 'sendMessage' instead. TODO: this should be private.
*/
JitsiConference.prototype.sendTextMessage = function(message, elementName = 'body') {
if (this.room) {
this.room.sendMessage(message, elementName);
}
};
/**
* Send private text message to another participant of the conference
* @param id the id of the participant to send a private message.
* @param message the text message.
* @param elementName the element name to encapsulate the message.
* @deprecated Use 'sendMessage' instead. TODO: this should be private.
*/
JitsiConference.prototype.sendPrivateTextMessage = function(id, message, elementName = 'body') {
if (this.room) {
this.room.sendPrivateMessage(id, message, elementName);
}
};
/**
* Send presence command.
* @param name {String} the name of the command.
* @param values {Object} with keys and values that will be sent.
**/
JitsiConference.prototype.sendCommand = function(name, values) {
if (this.room) {