forked from jitsi/lib-jitsi-meet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JitsiConference.js
2559 lines (2224 loc) · 81.5 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
/* global __filename, Strophe, Promise */
import AvgRTPStatsReporter from './modules/statistics/AvgRTPStatsReporter';
import ComponentsVersions from './modules/version/ComponentsVersions';
import ConnectionQuality from './modules/connectivity/ConnectionQuality';
import { getLogger } from 'jitsi-meet-logger';
import GlobalOnErrorHandler from './modules/util/GlobalOnErrorHandler';
import EventEmitter from 'events';
import * as JitsiConferenceErrors from './JitsiConferenceErrors';
import JitsiConferenceEventManager from './JitsiConferenceEventManager';
import * as JitsiConferenceEvents from './JitsiConferenceEvents';
import JitsiDTMFManager from './modules/DTMF/JitsiDTMFManager';
import JitsiParticipant from './JitsiParticipant';
import JitsiTrackError from './JitsiTrackError';
import * as JitsiTrackErrors from './JitsiTrackErrors';
import * as JitsiTrackEvents from './JitsiTrackEvents';
import Jvb121EventGenerator from './modules/event/Jvb121EventGenerator';
import * as MediaType from './service/RTC/MediaType';
import ParticipantConnectionStatusHandler
from './modules/connectivity/ParticipantConnectionStatus';
import P2PDominantSpeakerDetection from './modules/P2PDominantSpeakerDetection';
import RTC from './modules/RTC/RTC';
import RTCBrowserType from './modules/RTC/RTCBrowserType';
import * as RTCEvents from './service/RTC/RTCEvents';
import Statistics from './modules/statistics/statistics';
import TalkMutedDetection from './modules/TalkMutedDetection';
import Transcriber from './modules/transcription/transcriber';
import VideoType from './service/RTC/VideoType';
import VideoSIPGW from './modules/videosipgw/VideoSIPGW';
import * as XMPPEvents from './service/xmpp/XMPPEvents';
import SpeakerStatsCollector from './modules/statistics/SpeakerStatsCollector';
const logger = getLogger(__filename);
/**
* 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.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.
* @param {number} [options.config.forceJVB121Ratio]
* "Math.random() < forceJVB121Ratio" will determine whether a 2 people
* conference should be moved to the JVB instead of P2P. The decision is made on
* the responder side, after ICE succeeds on the P2P connection.
* @param {*} [options.config.openBridgeChannel] Which kind of communication to
* open with the videobridge. Values can be "datachannel", "websocket", true
* (treat it as "datachannel"), undefined (treat it as "datachannel") and false
* (don't open any channel).
* @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) {
const errmsg
= 'Invalid conference name (no conference name passed or it '
+ 'contains invalid characters like capital letters)!';
logger.error(errmsg);
throw new Error(errmsg);
}
this.eventEmitter = new EventEmitter();
this.options = options;
this.eventManager = new JitsiConferenceEventManager(this);
this.participants = {};
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.availableDevices = {
audio: undefined,
video: undefined
};
this.isMutedByFocus = false;
// 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;
/**
* 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
= 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;
}
// FIXME convert JitsiConference to ES6 - ASAP !
JitsiConference.prototype.constructor = JitsiConference;
/**
* Initializes the conference object properties
* @param options {object}
* @param options.connection {JitsiConnection} overrides this.connection
*/
JitsiConference.prototype._init = function(options = {}) {
// Override connection and xmpp properties (Useful if the connection
// reloaded)
if (options.connection) {
this.connection = options.connection;
this.xmpp = this.connection.xmpp;
// Setup XMPP events only if we have new connection object.
this.eventManager.setupXMPPListeners();
}
this.room = this.xmpp.createRoom(this.options.name, this.options.config);
// 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.room.updateDeviceAvailability(RTC.getDeviceAvailability());
if (!this.rtc) {
this.rtc = new RTC(this, options);
this.eventManager.setupRTCListeners();
}
this.participantConnectionStatus
= new ParticipantConnectionStatusHandler(
this.rtc,
this,
{ // Both these options are not public API, leaving it here only
// as an entry point through config for tuning up purposes.
// Default values should be adjusted as soon as optimal values
// are discovered.
rtcMuteTimeout:
this.options.config._peerConnStatusRtcMuteTimeout,
outOfLastNTimeout:
this.options.config._peerConnStatusOutOfLastNTimeout
});
this.participantConnectionStatus.init();
if (!this.statistics) {
this.statistics = new Statistics(this.xmpp, {
callStatsID: this.options.config.callStatsID,
callStatsSecret: this.options.config.callStatsSecret,
callStatsConfIDNamespace:
this.options.config.callStatsConfIDNamespace
|| window.location.hostname,
callStatsCustomScriptUrl:
this.options.config.callStatsCustomScriptUrl,
callStatsAliasName: this.myUserId(),
roomName: this.options.name
});
}
this.eventManager.setupChatRoomListeners();
// Always add listeners because on reload we are executing leave and the
// listeners are removed from statistics module.
this.eventManager.setupStatisticsListeners();
if (this.options.config.enableTalkWhileMuted) {
// eslint-disable-next-line no-new
new TalkMutedDetection(
this,
() =>
this.eventEmitter.emit(JitsiConferenceEvents.TALK_WHILE_MUTED));
}
if ('channelLastN' in options.config) {
this.setLastN(options.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);
};
/**
* Joins the conference.
* @param password {string} the password
*/
JitsiConference.prototype.join = function(password) {
if (this.room) {
this.room.join(password);
}
};
/**
* Check if joined to the conference.
*/
JitsiConference.prototype.isJoined = function() {
return this.room && this.room.joined;
};
/**
* Leaves the conference.
* @returns {Promise}
*/
JitsiConference.prototype.leave = function() {
if (this.participantConnectionStatus) {
this.participantConnectionStatus.dispose();
this.participantConnectionStatus = null;
}
if (this.avgRtpStatsReporter) {
this.avgRtpStatsReporter.dispose();
this.avgRtpStatsReporter = null;
}
this.getLocalTracks().forEach(track => this.onLocalTrackRemoved(track));
this.rtc.closeBridgeChannel();
if (this.statistics) {
this.statistics.dispose();
}
// 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) {
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);
this.room = null;
return room.leave().catch(() => {
// 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.room == null we are calling second time leave().
return Promise.reject(
new Error('The conference is has been already left'));
};
/**
* Returns name of this conference.
*/
JitsiConference.prototype.getName = function() {
return this.options.name;
};
/**
* 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;
};
/**
* Check if external authentication is enabled for this conference.
*/
JitsiConference.prototype.isExternalAuthEnabled = function() {
return this.room && this.room.moderator.isExternalAuthEnabled();
};
/**
* Get url for external authentication.
* @param {boolean} [urlForPopup] if true then return url for login popup,
* else url of login page.
* @returns {Promise}
*/
JitsiConference.prototype.getExternalAuthUrl = function(urlForPopup) {
return new Promise((resolve, reject) => {
if (!this.isExternalAuthEnabled()) {
reject();
return;
}
if (urlForPopup) {
this.room.moderator.getPopupLoginUrl(resolve, reject);
} else {
this.room.moderator.getLoginUrl(resolve, reject);
}
});
};
/**
* 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;
};
/**
* 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);
}
};
/**
* 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
*/
JitsiConference.prototype.removeCommandListener = function(command) {
if (this.room) {
this.room.removePresenceListener(command);
}
};
/**
* Sends text message to the other participants in the conference
* @param message the text message.
*/
JitsiConference.prototype.sendTextMessage = function(message) {
if (this.room) {
this.room.sendMessage(message);
}
};
/**
* 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) {
this.room.addToPresence(name, values);
this.room.sendPresence();
}
};
/**
* Send presence command one time.
* @param name {String} the name of the command.
* @param values {Object} with keys and values that will be sent.
**/
JitsiConference.prototype.sendCommandOnce = function(name, values) {
this.sendCommand(name, values);
this.removeCommand(name);
};
/**
* Removes presence command.
* @param name {String} the name of the command.
**/
JitsiConference.prototype.removeCommand = function(name) {
if (this.room) {
this.room.removeFromPresence(name);
}
};
/**
* Sets the display name for this conference.
* @param name the display name to set
*/
JitsiConference.prototype.setDisplayName = function(name) {
if (this.room) {
// remove previously set nickname
this.room.removeFromPresence('nick');
this.room.addToPresence('nick', {
attributes: { xmlns: 'http://jabber.org/protocol/nick' },
value: name
});
this.room.sendPresence();
}
};
/**
* Set new subject for this conference. (available only for moderator)
* @param {string} subject new subject
*/
JitsiConference.prototype.setSubject = function(subject) {
if (this.room && this.isModerator()) {
this.room.setSubject(subject);
}
};
/**
* Get a transcriber object for all current participants in this conference
* @return {Transcriber} the transcriber object
*/
JitsiConference.prototype.getTranscriber = function() {
if (this.transcriber === undefined) {
this.transcriber = new Transcriber();
// add all existing local audio tracks to the transcriber
const localAudioTracks = this.getLocalTracks(MediaType.AUDIO);
for (const localAudio of localAudioTracks) {
this.transcriber.addTrack(localAudio);
}
// and all remote audio tracks
const remoteAudioTracks = this.rtc.getRemoteTracks(MediaType.AUDIO);
for (const remoteTrack of remoteAudioTracks) {
this.transcriber.addTrack(remoteTrack);
}
}
return this.transcriber;
};
/**
* Adds JitsiLocalTrack object to the conference.
* @param track the JitsiLocalTrack object.
* @returns {Promise<JitsiLocalTrack>}
* @throws {Error} if the specified track is a video track and there is already
* another video track in the conference.
*/
JitsiConference.prototype.addTrack = function(track) {
if (track.isVideoTrack()) {
// Ensure there's exactly 1 local video track in the conference.
const localVideoTrack = this.rtc.getLocalVideoTrack();
if (localVideoTrack) {
// Don't be excessively harsh and severe if the API client happens
// to attempt to add the same local video track twice.
if (track === localVideoTrack) {
return Promise.resolve(track);
}
return Promise.reject(new Error(
'cannot add second video track to the conference'));
}
}
return this.replaceTrack(null, track);
};
/**
* Fires TRACK_AUDIO_LEVEL_CHANGED change conference event (for local tracks).
* @param {number} audioLevel the audio level
* @param {TraceablePeerConnection} [tpc]
*/
JitsiConference.prototype._fireAudioLevelChangeEvent
= function(audioLevel, tpc) {
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 track the JitsiTrack object related to the event.
*/
JitsiConference.prototype._fireMuteChangeEvent = function(track) {
// 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);
}
this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
};
/**
* Clear JitsiLocalTrack properties and listeners.
* @param track the JitsiLocalTrack object.
*/
JitsiConference.prototype.onLocalTrackRemoved = function(track) {
track._setConference(null);
this.rtc.removeLocalTrack(track);
track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
track.muteHandler);
track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
track.audioLevelHandler);
// send event for stopping screen sharing
// FIXME: we assume we have only one screen sharing track
// if we change this we need to fix this check
if (track.isVideoTrack() && track.videoType === VideoType.DESKTOP) {
this.statistics.sendScreenSharingEvent(false);
}
this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
};
/**
* Removes JitsiLocalTrack from the conference and performs
* a new offer/answer cycle.
* @param {JitsiLocalTrack} track
* @returns {Promise}
*/
JitsiConference.prototype.removeTrack = function(track) {
return this.replaceTrack(track, null);
};
/**
* Replaces oldTrack with newTrack and performs a single offer/answer
* cycle after both operations are done. Either oldTrack or newTrack
* can be null; replacing a valid 'oldTrack' with a null 'newTrack'
* effectively just removes 'oldTrack'
* @param {JitsiLocalTrack} oldTrack the current stream in use to be replaced
* @param {JitsiLocalTrack} newTrack the new stream to use
* @returns {Promise} resolves when the replacement is finished
*/
JitsiConference.prototype.replaceTrack = function(oldTrack, newTrack) {
// First do the removal of the oldTrack at the JitsiConference level
if (oldTrack) {
if (oldTrack.disposed) {
return Promise.reject(
new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
}
}
if (newTrack) {
if (newTrack.disposed) {
return Promise.reject(
new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
}
}
// Now replace the stream at the lower levels
return this._doReplaceTrack(oldTrack, newTrack)
.then(() => {
if (oldTrack) {
this.onLocalTrackRemoved(oldTrack);
}
if (newTrack) {
// Now handle the addition of the newTrack at the
// JitsiConference level
this._setupNewTrack(newTrack);
}
return Promise.resolve();
}, error => Promise.reject(new Error(error)));
};
/**
* Replaces the tracks at the lower level by going through the Jingle session
* and WebRTC peer connection. The method will resolve immediately if there is
* currently no JingleSession started.
* @param {JitsiLocalTrack|null} oldTrack the track to be removed during
* the process or <tt>null</t> if the method should act as "add track"
* @param {JitsiLocalTrack|null} newTrack the new track to be added or
* <tt>null</tt> if the method should act as "remove track"
* @return {Promise} resolved when the process is done or rejected with a string
* which describes the error.
* @private
*/
JitsiConference.prototype._doReplaceTrack = function(oldTrack, newTrack) {
const replaceTrackPromises = [];
if (this.jvbJingleSession) {
replaceTrackPromises.push(
this.jvbJingleSession.replaceTrack(oldTrack, newTrack));
} else {
logger.info('_doReplaceTrack - no JVB JingleSession');
}
if (this.p2pJingleSession) {
replaceTrackPromises.push(
this.p2pJingleSession.replaceTrack(oldTrack, newTrack));
} else {
logger.info('_doReplaceTrack - no P2P JingleSession');
}
return Promise.all(replaceTrackPromises);
};
/**
* Operations related to creating a new track
* @param {JitsiLocalTrack} newTrack the new track being created
*/
JitsiConference.prototype._setupNewTrack = function(newTrack) {
if (newTrack.isAudioTrack() || (newTrack.isVideoTrack()
&& newTrack.videoType !== VideoType.DESKTOP)) {
// Report active device to statistics
const devices = RTC.getCurrentlyAvailableMediaDevices();
const device
= devices.find(
d =>
d.kind === `${newTrack.getTrack().kind}input`
&& d.label === newTrack.getTrack().label);
if (device) {
Statistics.sendActiveDeviceListEvent(
RTC.getEventDataForActiveDevice(device));
}
}
if (newTrack.isVideoTrack()) {
this.removeCommand('videoType');
this.sendCommand('videoType', {
value: newTrack.videoType,
attributes: {
xmlns: 'http://jitsi.org/jitmeet/video'
}
});
}
this.rtc.addLocalTrack(newTrack);
// ensure that we're sharing proper "is muted" state
if (newTrack.isAudioTrack()) {
this.room.setAudioMute(newTrack.isMuted());
} else {
this.room.setVideoMute(newTrack.isMuted());
}
newTrack.muteHandler = this._fireMuteChangeEvent.bind(this, newTrack);
newTrack.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
newTrack.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
newTrack.muteHandler);
newTrack.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
newTrack.audioLevelHandler);
newTrack._setConference(this);
// send event for starting screen sharing
// FIXME: we assume we have only one screen sharing track
// if we change this we need to fix this check
if (newTrack.isVideoTrack() && newTrack.videoType === VideoType.DESKTOP) {
this.statistics.sendScreenSharingEvent(true);
}
this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, newTrack);
};
/**
* Method called by the {@link JitsiLocalTrack} (a video one) in order to add
* back the underlying WebRTC MediaStream to the PeerConnection (which has
* removed on video mute).
* @param {JitsiLocalTrack} track the local track that will be added as part of
* the unmute operation.
* @return {Promise} resolved when the process is done or rejected with a string
* which describes the error.
*/
JitsiConference.prototype._addLocalTrackAsUnmute = function(track) {
const addAsUnmutePromises = [];
if (this.jvbJingleSession) {
addAsUnmutePromises.push(this.jvbJingleSession.addTrackAsUnmute(track));
} else {
logger.info(
'Add local MediaStream as unmute -'
+ ' no JVB Jingle session started yet');
}
if (this.p2pJingleSession) {
addAsUnmutePromises.push(this.p2pJingleSession.addTrackAsUnmute(track));
} else {
logger.info(
'Add local MediaStream as unmute -'
+ ' no P2P Jingle session started yet');
}
return Promise.all(addAsUnmutePromises);
};
/**
* Method called by the {@link JitsiLocalTrack} (a video one) in order to remove
* the underlying WebRTC MediaStream from the PeerConnection. The purpose of
* that is to stop sending any data and turn off the HW camera device.
* @param {JitsiLocalTrack} track the local track that will be removed.
* @return {Promise}
*/
JitsiConference.prototype._removeLocalTrackAsMute = function(track) {
const removeAsMutePromises = [];
if (this.jvbJingleSession) {
removeAsMutePromises.push(
this.jvbJingleSession.removeTrackAsMute(track));
} else {
logger.info(
'Remove local MediaStream - no JVB JingleSession started yet');
}
if (this.p2pJingleSession) {
removeAsMutePromises.push(
this.p2pJingleSession.removeTrackAsMute(track));
} else {
logger.info(
'Remove local MediaStream - no P2P JingleSession started yet');
}
return Promise.all(removeAsMutePromises);
};
/**
* Get role of the local user.
* @returns {string} user role: 'moderator' or 'none'
*/
JitsiConference.prototype.getRole = function() {
return this.room.role;
};
/**
* Check if local user is moderator.
* @returns {boolean|null} true if local user is moderator, false otherwise. If
* we're no longer in the conference room then <tt>null</tt> is returned.
*/
JitsiConference.prototype.isModerator = function() {
return this.room ? this.room.isModerator() : null;
};
/**
* Set password for the room.
* @param {string} password new password for the room.
* @returns {Promise}
*/
JitsiConference.prototype.lock = function(password) {
if (!this.isModerator()) {
return Promise.reject();
}
return new Promise((resolve, reject) => {
this.room.lockRoom(
password || '',
() => resolve(),
err => reject(err),
() => reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED));
});
};
/**
* Remove password from the room.
* @returns {Promise}
*/
JitsiConference.prototype.unlock = function() {
return this.lock();
};
/**
* Elects the participant with the given id to be the selected participant in
* order to receive higher video quality (if simulcast is enabled).
* Or cache it if channel is not created and send it once channel is available.
* @param participantId the identifier of the participant
* @throws NetworkError or InvalidStateError or Error if the operation fails.
*/
JitsiConference.prototype.selectParticipant = function(participantId) {
this.rtc.selectEndpoint(participantId);
};
/**
* Elects the participant with the given id to be the pinned participant in
* order to always receive video for this participant (even when last n is
* enabled).
* @param participantId the identifier of the participant
* @throws NetworkError or InvalidStateError or Error if the operation fails.
*/
JitsiConference.prototype.pinParticipant = function(participantId) {
this.rtc.pinEndpoint(participantId);
};
/**
* Selects a new value for "lastN". 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.
* @param lastN the new number of videos the user would like to receive.
* @throws Error or RangeError if the given value is not a number or is smaller
* than -1.
*/
JitsiConference.prototype.setLastN = function(lastN) {
if (!Number.isInteger(lastN) && !Number.parseInt(lastN, 10)) {
throw new Error(`Invalid value for lastN: ${lastN}`);
}
const n = Number(lastN);
if (n < -1) {
throw new RangeError('lastN cannot be smaller than -1');
}
this.rtc.setLastN(n);
// If the P2P session is not fully established yet, we wait until it gets
// established.
if (this.p2pJingleSession) {
const isVideoActive = n !== 0;
this.p2pJingleSession
.setMediaTransferActive(true, isVideoActive)
.catch(error => {
logger.error(
`Failed to adjust video transfer status (${isVideoActive})`,
error);
});
}
};
/**
* Checks if the participant given by participantId is currently included in
* the last N.
* @param {string} participantId the identifier of the participant we would
* like to check.
* @return {boolean} true if the participant with id is in the last N set or
* if there's no last N set, false otherwise.
* @deprecated this method should never be used to figure out the UI, but
* {@link ParticipantConnectionStatus} should be used instead.
*/
JitsiConference.prototype.isInLastN = function(participantId) {
return this.rtc.isInLastN(participantId);
};