Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

JitsiConference.js 135KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056
  1. import { getLogger } from '@jitsi/logger';
  2. import $ from 'jquery';
  3. import isEqual from 'lodash.isequal';
  4. import { Strophe } from 'strophe.js';
  5. import * as JitsiConferenceErrors from './JitsiConferenceErrors';
  6. import JitsiConferenceEventManager from './JitsiConferenceEventManager';
  7. import * as JitsiConferenceEvents from './JitsiConferenceEvents';
  8. import JitsiParticipant from './JitsiParticipant';
  9. import JitsiTrackError from './JitsiTrackError';
  10. import * as JitsiTrackErrors from './JitsiTrackErrors';
  11. import * as JitsiTrackEvents from './JitsiTrackEvents';
  12. import authenticateAndUpgradeRole from './authenticateAndUpgradeRole';
  13. import { CodecSelection } from './modules/RTC/CodecSelection';
  14. import RTC from './modules/RTC/RTC';
  15. import { SS_DEFAULT_FRAME_RATE } from './modules/RTC/ScreenObtainer';
  16. import browser from './modules/browser';
  17. import ConnectionQuality from './modules/connectivity/ConnectionQuality';
  18. import IceFailedHandling from './modules/connectivity/IceFailedHandling';
  19. import * as DetectionEvents from './modules/detection/DetectionEvents';
  20. import NoAudioSignalDetection from './modules/detection/NoAudioSignalDetection';
  21. import P2PDominantSpeakerDetection from './modules/detection/P2PDominantSpeakerDetection';
  22. import VADAudioAnalyser from './modules/detection/VADAudioAnalyser';
  23. import VADNoiseDetection from './modules/detection/VADNoiseDetection';
  24. import VADTalkMutedDetection from './modules/detection/VADTalkMutedDetection';
  25. import { E2EEncryption } from './modules/e2ee/E2EEncryption';
  26. import E2ePing from './modules/e2eping/e2eping';
  27. import Jvb121EventGenerator from './modules/event/Jvb121EventGenerator';
  28. import FeatureFlags from './modules/flags/FeatureFlags';
  29. import { LiteModeContext } from './modules/litemode/LiteModeContext';
  30. import ReceiveVideoController from './modules/qualitycontrol/ReceiveVideoController';
  31. import SendVideoController from './modules/qualitycontrol/SendVideoController';
  32. import RecordingManager from './modules/recording/RecordingManager';
  33. import Settings from './modules/settings/Settings';
  34. import AudioOutputProblemDetector from './modules/statistics/AudioOutputProblemDetector';
  35. import AvgRTPStatsReporter from './modules/statistics/AvgRTPStatsReporter';
  36. import LocalStatsCollector from './modules/statistics/LocalStatsCollector';
  37. import SpeakerStatsCollector from './modules/statistics/SpeakerStatsCollector';
  38. import Statistics from './modules/statistics/statistics';
  39. import EventEmitter from './modules/util/EventEmitter';
  40. import { safeSubtract } from './modules/util/MathUtil';
  41. import RandomUtil from './modules/util/RandomUtil';
  42. import ComponentsVersions from './modules/version/ComponentsVersions';
  43. import VideoSIPGW from './modules/videosipgw/VideoSIPGW';
  44. import * as VideoSIPGWConstants from './modules/videosipgw/VideoSIPGWConstants';
  45. import SignalingLayerImpl from './modules/xmpp/SignalingLayerImpl';
  46. import {
  47. FEATURE_E2EE,
  48. FEATURE_JIGASI,
  49. JITSI_MEET_MUC_TYPE
  50. } from './modules/xmpp/xmpp';
  51. import BridgeVideoType from './service/RTC/BridgeVideoType';
  52. import CodecMimeType from './service/RTC/CodecMimeType';
  53. import { MediaType } from './service/RTC/MediaType';
  54. import RTCEvents from './service/RTC/RTCEvents';
  55. import { SignalingEvents } from './service/RTC/SignalingEvents';
  56. import { getMediaTypeFromSourceName, getSourceNameForJitsiTrack } from './service/RTC/SignalingLayer';
  57. import { VideoType } from './service/RTC/VideoType';
  58. import {
  59. ACTION_JINGLE_RESTART,
  60. ACTION_JINGLE_SI_RECEIVED,
  61. ACTION_JINGLE_SI_TIMEOUT,
  62. ACTION_JINGLE_TERMINATE,
  63. ACTION_P2P_DECLINED,
  64. ACTION_P2P_ESTABLISHED,
  65. ACTION_P2P_FAILED,
  66. ACTION_P2P_SWITCH_TO_JVB,
  67. ICE_ESTABLISHMENT_DURATION_DIFF,
  68. createConferenceEvent,
  69. createJingleEvent,
  70. createP2PEvent
  71. } from './service/statistics/AnalyticsEvents';
  72. import { XMPPEvents } from './service/xmpp/XMPPEvents';
  73. const logger = getLogger(__filename);
  74. /**
  75. * How long since Jicofo is supposed to send a session-initiate, before
  76. * {@link ACTION_JINGLE_SI_TIMEOUT} analytics event is sent (in ms).
  77. * @type {number}
  78. */
  79. const JINGLE_SI_TIMEOUT = 5000;
  80. /**
  81. * Checks if a given string is a valid video codec mime type.
  82. *
  83. * @param {string} codec the codec string that needs to be validated.
  84. * @returns {CodecMimeType|null} mime type if valid, null otherwise.
  85. * @private
  86. */
  87. function _getCodecMimeType(codec) {
  88. if (typeof codec === 'string') {
  89. return Object.values(CodecMimeType).find(value => value === codec.toLowerCase());
  90. }
  91. return null;
  92. }
  93. /**
  94. * Creates a JitsiConference object with the given name and properties.
  95. * Note: this constructor is not a part of the public API (objects should be
  96. * created using JitsiConnection.createConference).
  97. * @param options.config properties / settings related to the conference that
  98. * will be created.
  99. * @param options.name the name of the conference
  100. * @param options.connection the JitsiConnection object for this
  101. * JitsiConference.
  102. * @param {number} [options.config.avgRtpStatsN=15] how many samples are to be
  103. * collected by {@link AvgRTPStatsReporter}, before arithmetic mean is
  104. * calculated and submitted to the analytics module.
  105. * @param {boolean} [options.config.enableIceRestart=false] - enables the ICE
  106. * restart logic.
  107. * @param {boolean} [options.config.p2p.enabled] when set to <tt>true</tt>
  108. * the peer to peer mode will be enabled. It means that when there are only 2
  109. * participants in the conference an attempt to make direct connection will be
  110. * made. If the connection succeeds the conference will stop sending data
  111. * through the JVB connection and will use the direct one instead.
  112. * @param {number} [options.config.p2p.backToP2PDelay=5] a delay given in
  113. * seconds, before the conference switches back to P2P, after the 3rd
  114. * participant has left the room.
  115. * @param {number} [options.config.channelLastN=-1] The requested amount of
  116. * videos are going to be delivered after the value is in effect. Set to -1 for
  117. * unlimited or all available videos.
  118. * @constructor
  119. *
  120. * FIXME Make all methods which are called from lib-internal classes
  121. * to non-public (use _). To name a few:
  122. * {@link JitsiConference.onLocalRoleChanged}
  123. * {@link JitsiConference.onUserRoleChanged}
  124. * {@link JitsiConference.onMemberLeft}
  125. * and so on...
  126. */
  127. export default function JitsiConference(options) {
  128. if (!options.name || options.name.toLowerCase() !== options.name.toString()) {
  129. const errmsg
  130. = 'Invalid conference name (no conference name passed or it '
  131. + 'contains invalid characters like capital letters)!';
  132. logger.error(errmsg);
  133. throw new Error(errmsg);
  134. }
  135. this.connection = options.connection;
  136. this.xmpp = this.connection?.xmpp;
  137. if (this.xmpp.isRoomCreated(options.name, options.customDomain)) {
  138. const errmsg = 'A conference with the same name has already been created!';
  139. delete this.connection;
  140. delete this.xmpp;
  141. logger.error(errmsg);
  142. throw new Error(errmsg);
  143. }
  144. this.eventEmitter = new EventEmitter();
  145. this.options = options;
  146. this.eventManager = new JitsiConferenceEventManager(this);
  147. /**
  148. * List of all the participants in the conference.
  149. * @type {Map<string, JitsiParticipant>};
  150. */
  151. this.participants = new Map();
  152. /**
  153. * The signaling layer instance.
  154. * @type {SignalingLayerImpl}
  155. * @private
  156. */
  157. this._signalingLayer = new SignalingLayerImpl();
  158. this._init(options);
  159. this.componentsVersions = new ComponentsVersions(this);
  160. /**
  161. * Jingle session instance for the JVB connection.
  162. * @type {JingleSessionPC}
  163. */
  164. this.jvbJingleSession = null;
  165. this.lastDominantSpeaker = null;
  166. this.dtmfManager = null;
  167. this.somebodySupportsDTMF = false;
  168. this.authEnabled = false;
  169. this.startAudioMuted = false;
  170. this.startVideoMuted = false;
  171. this.startMutedPolicy = {
  172. audio: false,
  173. video: false
  174. };
  175. this.isMutedByFocus = false;
  176. // when muted by focus we receive the jid of the initiator of the mute
  177. this.mutedByFocusActor = null;
  178. this.isVideoMutedByFocus = false;
  179. // when video muted by focus we receive the jid of the initiator of the mute
  180. this.mutedVideoByFocusActor = null;
  181. // Flag indicates if the 'onCallEnded' method was ever called on this
  182. // instance. Used to log extra analytics event for debugging purpose.
  183. // We need to know if the potential issue happened before or after
  184. // the restart.
  185. this.wasStopped = false;
  186. // Conference properties, maintained by jicofo.
  187. this.properties = {};
  188. /**
  189. * The object which monitors local and remote connection statistics (e.g.
  190. * sending bitrate) and calculates a number which represents the connection
  191. * quality.
  192. */
  193. this.connectionQuality
  194. = new ConnectionQuality(this, this.eventEmitter, options);
  195. /**
  196. * Reports average RTP statistics to the analytics module.
  197. * @type {AvgRTPStatsReporter}
  198. */
  199. this.avgRtpStatsReporter
  200. = new AvgRTPStatsReporter(this, options.config.avgRtpStatsN || 15);
  201. /**
  202. * Detects issues with the audio of remote participants.
  203. * @type {AudioOutputProblemDetector}
  204. */
  205. if (!options.config.disableAudioLevels) {
  206. this._audioOutputProblemDetector = new AudioOutputProblemDetector(this);
  207. }
  208. /**
  209. * Indicates whether the connection is interrupted or not.
  210. */
  211. this.isJvbConnectionInterrupted = false;
  212. /**
  213. * The object which tracks active speaker times
  214. */
  215. this.speakerStatsCollector = new SpeakerStatsCollector(this);
  216. /* P2P related fields below: */
  217. /**
  218. * Stores reference to deferred start P2P task. It's created when 3rd
  219. * participant leaves the room in order to avoid ping pong effect (it
  220. * could be just a page reload).
  221. * @type {number|null}
  222. */
  223. this.deferredStartP2PTask = null;
  224. const delay
  225. = parseInt(options.config.p2p && options.config.p2p.backToP2PDelay, 10);
  226. /**
  227. * A delay given in seconds, before the conference switches back to P2P
  228. * after the 3rd participant has left.
  229. * @type {number}
  230. */
  231. this.backToP2PDelay = isNaN(delay) ? 5 : delay;
  232. logger.info(`backToP2PDelay: ${this.backToP2PDelay}`);
  233. /**
  234. * If set to <tt>true</tt> it means the P2P ICE is no longer connected.
  235. * When <tt>false</tt> it means that P2P ICE (media) connection is up
  236. * and running.
  237. * @type {boolean}
  238. */
  239. this.isP2PConnectionInterrupted = false;
  240. /**
  241. * Flag set to <tt>true</tt> when P2P session has been established
  242. * (ICE has been connected) and this conference is currently in the peer to
  243. * peer mode (P2P connection is the active one).
  244. * @type {boolean}
  245. */
  246. this.p2p = false;
  247. /**
  248. * A JingleSession for the direct peer to peer connection.
  249. * @type {JingleSessionPC}
  250. */
  251. this.p2pJingleSession = null;
  252. this.videoSIPGWHandler = new VideoSIPGW(this.room);
  253. this.recordingManager = new RecordingManager(this.room);
  254. /**
  255. * If the conference.joined event has been sent this will store the timestamp when it happened.
  256. *
  257. * @type {undefined|number}
  258. * @private
  259. */
  260. this._conferenceJoinAnalyticsEventSent = undefined;
  261. /**
  262. * End-to-End Encryption. Make it available if supported.
  263. */
  264. if (this.isE2EESupported()) {
  265. logger.info('End-to-End Encryption is supported');
  266. this._e2eEncryption = new E2EEncryption(this);
  267. }
  268. if (FeatureFlags.isRunInLiteModeEnabled()) {
  269. logger.info('Lite mode enabled');
  270. this._liteModeContext = new LiteModeContext(this);
  271. }
  272. /**
  273. * Flag set to <tt>true</tt> when Jicofo sends a presence message indicating that the max audio sender limit has
  274. * been reached for the call. Once this is set, unmuting audio will be disabled from the client until it gets reset
  275. * again by Jicofo.
  276. */
  277. this._audioSenderLimitReached = undefined;
  278. /**
  279. * Flag set to <tt>true</tt> when Jicofo sends a presence message indicating that the max video sender limit has
  280. * been reached for the call. Once this is set, unmuting video will be disabled from the client until it gets reset
  281. * again by Jicofo.
  282. */
  283. this._videoSenderLimitReached = undefined;
  284. this._firefoxP2pEnabled = browser.isVersionGreaterThan(109)
  285. && (this.options.config.testing?.enableFirefoxP2p ?? true);
  286. }
  287. // FIXME convert JitsiConference to ES6 - ASAP !
  288. JitsiConference.prototype.constructor = JitsiConference;
  289. /**
  290. * Create a resource for the a jid. We use the room nickname (the resource part
  291. * of the occupant JID, see XEP-0045) as the endpoint ID in colibri. We require
  292. * endpoint IDs to be 8 hex digits because in some cases they get serialized
  293. * into a 32bit field.
  294. *
  295. * @param {string} jid - The id set onto the XMPP connection.
  296. * @param {boolean} isAuthenticatedUser - Whether or not the user has connected
  297. * to the XMPP service with a password.
  298. * @returns {string}
  299. * @static
  300. */
  301. JitsiConference.resourceCreator = function(jid, isAuthenticatedUser) {
  302. let mucNickname;
  303. if (isAuthenticatedUser) {
  304. // For authenticated users generate a random ID.
  305. mucNickname = RandomUtil.randomHexString(8).toLowerCase();
  306. } else {
  307. // We try to use the first part of the node (which for anonymous users
  308. // on prosody is a UUID) to match the previous behavior (and maybe make
  309. // debugging easier).
  310. mucNickname = Strophe.getNodeFromJid(jid)?.substr(0, 8)
  311. .toLowerCase();
  312. // But if this doesn't have the required format we just generate a new
  313. // random nickname.
  314. const re = /[0-9a-f]{8}/g;
  315. if (!mucNickname || !re.test(mucNickname)) {
  316. mucNickname = RandomUtil.randomHexString(8).toLowerCase();
  317. }
  318. }
  319. return mucNickname;
  320. };
  321. /**
  322. * Initializes the conference object properties
  323. * @param options {object}
  324. * @param options.connection {JitsiConnection} overrides this.connection
  325. */
  326. JitsiConference.prototype._init = function(options = {}) {
  327. this.eventManager.setupXMPPListeners();
  328. const { config } = this.options;
  329. // Get the codec preference settings from config.js.
  330. const codecSettings = {
  331. jvb: {
  332. preferenceOrder: browser.isMobileDevice() && config.videoQuality?.mobileCodecPreferenceOrder
  333. ? config.videoQuality.mobileCodecPreferenceOrder
  334. : config.videoQuality?.codecPreferenceOrder,
  335. disabledCodec: _getCodecMimeType(config.videoQuality?.disabledCodec),
  336. preferredCodec: _getCodecMimeType(config.videoQuality?.preferredCodec),
  337. supportsAv1: config.testing?.enableAv1Support
  338. },
  339. p2p: {
  340. preferenceOrder: browser.isMobileDevice() && config.p2p?.mobileCodecPreferenceOrder
  341. ? config.p2p.mobileCodecPreferenceOrder
  342. : config.p2p?.codecPreferenceOrder,
  343. disabledCodec: _getCodecMimeType(config.p2p?.disabledCodec),
  344. preferredCodec: _getCodecMimeType(config.p2p?.preferredCodec)
  345. }
  346. };
  347. this.codecSelection = new CodecSelection(this, codecSettings);
  348. this._statsCurrentId = config.statisticsId ? config.statisticsId : Settings.callStatsUserName;
  349. this.room = this.xmpp.createRoom(
  350. this.options.name, {
  351. ...config,
  352. statsId: this._statsCurrentId
  353. },
  354. JitsiConference.resourceCreator
  355. );
  356. this._signalingLayer.setChatRoom(this.room);
  357. this._signalingLayer.on(
  358. SignalingEvents.SOURCE_UPDATED,
  359. (sourceName, endpointId, muted, videoType) => {
  360. const participant = this.participants.get(endpointId);
  361. const mediaType = getMediaTypeFromSourceName(sourceName);
  362. if (participant) {
  363. participant._setSources(mediaType, muted, sourceName, videoType);
  364. this.eventEmitter.emit(JitsiConferenceEvents.PARTICIPANT_SOURCE_UPDATED, participant);
  365. }
  366. });
  367. // Connection interrupted/restored listeners
  368. this._onIceConnectionInterrupted
  369. = this._onIceConnectionInterrupted.bind(this);
  370. this.room.addListener(
  371. XMPPEvents.CONNECTION_INTERRUPTED, this._onIceConnectionInterrupted);
  372. this._onIceConnectionRestored = this._onIceConnectionRestored.bind(this);
  373. this.room.addListener(
  374. XMPPEvents.CONNECTION_RESTORED, this._onIceConnectionRestored);
  375. this._onIceConnectionEstablished
  376. = this._onIceConnectionEstablished.bind(this);
  377. this.room.addListener(
  378. XMPPEvents.CONNECTION_ESTABLISHED, this._onIceConnectionEstablished);
  379. this._updateProperties = this._updateProperties.bind(this);
  380. this.room.addListener(XMPPEvents.CONFERENCE_PROPERTIES_CHANGED,
  381. this._updateProperties);
  382. this._sendConferenceJoinAnalyticsEvent = this._sendConferenceJoinAnalyticsEvent.bind(this);
  383. this.room.addListener(XMPPEvents.MEETING_ID_SET, this._sendConferenceJoinAnalyticsEvent);
  384. this._removeLocalSourceOnReject = this._removeLocalSourceOnReject.bind(this);
  385. this._updateRoomPresence = this._updateRoomPresence.bind(this);
  386. this.room.addListener(XMPPEvents.SESSION_ACCEPT, this._updateRoomPresence);
  387. this.room.addListener(XMPPEvents.SOURCE_ADD, this._updateRoomPresence);
  388. this.room.addListener(XMPPEvents.SOURCE_ADD_ERROR, this._removeLocalSourceOnReject);
  389. this.room.addListener(XMPPEvents.SOURCE_REMOVE, this._updateRoomPresence);
  390. if (config.e2eping?.enabled) {
  391. this.e2eping = new E2ePing(
  392. this,
  393. config,
  394. (message, to) => {
  395. try {
  396. this.sendMessage(message, to, true /* sendThroughVideobridge */);
  397. } catch (error) {
  398. logger.warn('Failed to send E2E ping request or response.', error && error.msg);
  399. }
  400. });
  401. }
  402. if (!this.rtc) {
  403. this.rtc = new RTC(this, options);
  404. this.eventManager.setupRTCListeners();
  405. this._registerRtcListeners(this.rtc);
  406. }
  407. this.receiveVideoController = new ReceiveVideoController(this, this.rtc);
  408. this.sendVideoController = new SendVideoController(this, this.rtc);
  409. if (!this.statistics) {
  410. this.statistics = new Statistics(this, {
  411. aliasName: this._statsCurrentId,
  412. userName: config.statisticsDisplayName ? config.statisticsDisplayName : this.myUserId(),
  413. confID: config.confID || `${this.connection.options.hosts.domain}/${this.options.name}`,
  414. siteID: config.siteID,
  415. roomName: this.options.name,
  416. applicationName: config.applicationName
  417. });
  418. Statistics.analytics.addPermanentProperties({
  419. 'callstats_name': this._statsCurrentId
  420. });
  421. // Start performance observer for monitoring long tasks
  422. if (config.longTasksStatsInterval) {
  423. this.statistics.attachLongTasksStats();
  424. }
  425. }
  426. this.eventManager.setupChatRoomListeners();
  427. // Always add listeners because on reload we are executing leave and the
  428. // listeners are removed from statistics module.
  429. this.eventManager.setupStatisticsListeners();
  430. // Disable VAD processing on Safari since it causes audio input to
  431. // fail on some of the mobile devices.
  432. if (config.enableTalkWhileMuted && browser.supportsVADDetection()) {
  433. // If VAD processor factory method is provided uses VAD based detection, otherwise fallback to audio level
  434. // based detection.
  435. if (config.createVADProcessor) {
  436. logger.info('Using VAD detection for generating talk while muted events');
  437. if (!this._audioAnalyser) {
  438. this._audioAnalyser = new VADAudioAnalyser(this, config.createVADProcessor);
  439. }
  440. const vadTalkMutedDetection = new VADTalkMutedDetection();
  441. vadTalkMutedDetection.on(DetectionEvents.VAD_TALK_WHILE_MUTED, () =>
  442. this.eventEmitter.emit(JitsiConferenceEvents.TALK_WHILE_MUTED));
  443. this._audioAnalyser.addVADDetectionService(vadTalkMutedDetection);
  444. } else {
  445. logger.warn('No VAD Processor was provided. Talk while muted detection service was not initialized!');
  446. }
  447. }
  448. // Disable noisy mic detection on safari since it causes the audio input to
  449. // fail on Safari on iPadOS.
  450. if (config.enableNoisyMicDetection && browser.supportsVADDetection()) {
  451. if (config.createVADProcessor) {
  452. if (!this._audioAnalyser) {
  453. this._audioAnalyser = new VADAudioAnalyser(this, config.createVADProcessor);
  454. }
  455. const vadNoiseDetection = new VADNoiseDetection();
  456. vadNoiseDetection.on(DetectionEvents.VAD_NOISY_DEVICE, () =>
  457. this.eventEmitter.emit(JitsiConferenceEvents.NOISY_MIC));
  458. this._audioAnalyser.addVADDetectionService(vadNoiseDetection);
  459. } else {
  460. logger.warn('No VAD Processor was provided. Noisy microphone detection service was not initialized!');
  461. }
  462. }
  463. // Generates events based on no audio input detector.
  464. if (config.enableNoAudioDetection && !config.disableAudioLevels && LocalStatsCollector.isLocalStatsSupported()) {
  465. this._noAudioSignalDetection = new NoAudioSignalDetection(this);
  466. this._noAudioSignalDetection.on(DetectionEvents.NO_AUDIO_INPUT, () => {
  467. this.eventEmitter.emit(JitsiConferenceEvents.NO_AUDIO_INPUT);
  468. });
  469. this._noAudioSignalDetection.on(DetectionEvents.AUDIO_INPUT_STATE_CHANGE, hasAudioSignal => {
  470. this.eventEmitter.emit(JitsiConferenceEvents.AUDIO_INPUT_STATE_CHANGE, hasAudioSignal);
  471. });
  472. }
  473. if ('channelLastN' in config) {
  474. this.setLastN(config.channelLastN);
  475. }
  476. /**
  477. * Emits {@link JitsiConferenceEvents.JVB121_STATUS}.
  478. * @type {Jvb121EventGenerator}
  479. */
  480. this.jvb121Status = new Jvb121EventGenerator(this);
  481. // creates dominant speaker detection that works only in p2p mode
  482. this.p2pDominantSpeakerDetection = new P2PDominantSpeakerDetection(this);
  483. if (config && config.deploymentInfo && config.deploymentInfo.userRegion) {
  484. this.setLocalParticipantProperty(
  485. 'region', config.deploymentInfo.userRegion);
  486. }
  487. // Publish the codec preference to presence.
  488. this.setLocalParticipantProperty('codecList', this.codecSelection.getCodecPreferenceList('jvb'));
  489. // Set transcription language presence extension.
  490. // In case the language config is undefined or has the default value that the transcriber uses
  491. // (in our case Jigasi uses 'en-US'), don't set the participant property in order to avoid
  492. // needlessly polluting the presence stanza.
  493. if (config && config.transcriptionLanguage && config.transcriptionLanguage !== 'en-US') {
  494. this.setLocalParticipantProperty('transcription_language', config.transcriptionLanguage);
  495. }
  496. };
  497. /**
  498. * Joins the conference.
  499. * @param password {string} the password
  500. * @param replaceParticipant {boolean} whether the current join replaces
  501. * an existing participant with same jwt from the meeting.
  502. */
  503. JitsiConference.prototype.join = function(password, replaceParticipant = false) {
  504. if (this.room) {
  505. this.room.join(password, replaceParticipant).then(() => this._maybeSetSITimeout());
  506. }
  507. };
  508. /**
  509. * Authenticates and upgrades the role of the local participant/user.
  510. *
  511. * @returns {Object} A <tt>thenable</tt> which (1) settles when the process of
  512. * authenticating and upgrading the role of the local participant/user finishes
  513. * and (2) has a <tt>cancel</tt> method that allows the caller to interrupt the
  514. * process.
  515. */
  516. JitsiConference.prototype.authenticateAndUpgradeRole = function(options) {
  517. return authenticateAndUpgradeRole.call(this, {
  518. ...options,
  519. onCreateResource: JitsiConference.resourceCreator
  520. });
  521. };
  522. /**
  523. * Check if joined to the conference.
  524. */
  525. JitsiConference.prototype.isJoined = function() {
  526. return this.room && this.room.joined;
  527. };
  528. /**
  529. * Tells whether or not the P2P mode is enabled in the configuration.
  530. * @return {boolean}
  531. */
  532. JitsiConference.prototype.isP2PEnabled = function() {
  533. return Boolean(this.options.config.p2p && this.options.config.p2p.enabled)
  534. // FIXME: remove once we have a default config template. -saghul
  535. || typeof this.options.config.p2p === 'undefined';
  536. };
  537. /**
  538. * When in P2P test mode, the conference will not automatically switch to P2P
  539. * when there 2 participants.
  540. * @return {boolean}
  541. */
  542. JitsiConference.prototype.isP2PTestModeEnabled = function() {
  543. return Boolean(this.options.config.testing
  544. && this.options.config.testing.p2pTestMode);
  545. };
  546. /**
  547. * Leaves the conference.
  548. * @param reason {string|undefined} The reason for leaving the conference.
  549. * @returns {Promise}
  550. */
  551. JitsiConference.prototype.leave = async function(reason) {
  552. if (this.avgRtpStatsReporter) {
  553. this.avgRtpStatsReporter.dispose();
  554. this.avgRtpStatsReporter = null;
  555. }
  556. if (this._audioOutputProblemDetector) {
  557. this._audioOutputProblemDetector.dispose();
  558. this._audioOutputProblemDetector = null;
  559. }
  560. if (this.e2eping) {
  561. this.e2eping.stop();
  562. this.e2eping = null;
  563. }
  564. this.getLocalTracks().forEach(track => this.onLocalTrackRemoved(track));
  565. this.rtc.closeBridgeChannel();
  566. this._sendConferenceLeftAnalyticsEvent();
  567. if (this.statistics) {
  568. this.statistics.dispose();
  569. }
  570. this._delayedIceFailed && this._delayedIceFailed.cancel();
  571. this._maybeClearSITimeout();
  572. // Close both JVb and P2P JingleSessions
  573. if (this.jvbJingleSession) {
  574. this.jvbJingleSession.close();
  575. this.jvbJingleSession = null;
  576. }
  577. if (this.p2pJingleSession) {
  578. this.p2pJingleSession.close();
  579. this.p2pJingleSession = null;
  580. }
  581. // Leave the conference. If this.room == null we are calling second time leave().
  582. if (!this.room) {
  583. throw new Error('You have already left the conference');
  584. }
  585. const room = this.room;
  586. // Unregister connection state listeners
  587. room.removeListener(
  588. XMPPEvents.CONNECTION_INTERRUPTED,
  589. this._onIceConnectionInterrupted);
  590. room.removeListener(
  591. XMPPEvents.CONNECTION_RESTORED,
  592. this._onIceConnectionRestored);
  593. room.removeListener(
  594. XMPPEvents.CONNECTION_ESTABLISHED,
  595. this._onIceConnectionEstablished);
  596. room.removeListener(
  597. XMPPEvents.CONFERENCE_PROPERTIES_CHANGED,
  598. this._updateProperties);
  599. room.removeListener(XMPPEvents.MEETING_ID_SET, this._sendConferenceJoinAnalyticsEvent);
  600. room.removeListener(XMPPEvents.SESSION_ACCEPT, this._updateRoomPresence);
  601. room.removeListener(XMPPEvents.SOURCE_ADD, this._updateRoomPresence);
  602. room.removeListener(XMPPEvents.SOURCE_ADD_ERROR, this._removeLocalSourceOnReject);
  603. room.removeListener(XMPPEvents.SOURCE_REMOVE, this._updateRoomPresence);
  604. this.eventManager.removeXMPPListeners();
  605. this._signalingLayer.setChatRoom(null);
  606. this.room = null;
  607. let leaveError;
  608. try {
  609. await room.leave(reason);
  610. } catch (err) {
  611. leaveError = err;
  612. // Remove all participants because currently the conference
  613. // won't be usable anyway. This is done on success automatically
  614. // by the ChatRoom instance.
  615. this.getParticipants().forEach(
  616. participant => this.onMemberLeft(participant.getJid()));
  617. }
  618. if (this.rtc) {
  619. this.rtc.destroy();
  620. }
  621. if (leaveError) {
  622. throw leaveError;
  623. }
  624. };
  625. /**
  626. * Returns <tt>true</tt> if end conference support is enabled in the backend.
  627. *
  628. * @returns {boolean} whether end conference is supported in the backend.
  629. */
  630. JitsiConference.prototype.isEndConferenceSupported = function() {
  631. return Boolean(this.room && this.room.xmpp.endConferenceComponentAddress);
  632. };
  633. /**
  634. * Ends the conference.
  635. */
  636. JitsiConference.prototype.end = function() {
  637. if (!this.isEndConferenceSupported()) {
  638. logger.warn('Cannot end conference: is not supported.');
  639. return;
  640. }
  641. if (!this.room) {
  642. throw new Error('You have already left the conference');
  643. }
  644. this.room.end();
  645. };
  646. /**
  647. * Returns the currently active media session if any.
  648. *
  649. * @returns {JingleSessionPC|undefined}
  650. */
  651. JitsiConference.prototype.getActiveMediaSession = function() {
  652. return this.isP2PActive() ? this.p2pJingleSession : this.jvbJingleSession;
  653. };
  654. /**
  655. * Returns an array containing all media sessions existing in this conference.
  656. *
  657. * @returns {Array<JingleSessionPC>}
  658. */
  659. JitsiConference.prototype.getMediaSessions = function() {
  660. const sessions = [];
  661. this.jvbJingleSession && sessions.push(this.jvbJingleSession);
  662. this.p2pJingleSession && sessions.push(this.p2pJingleSession);
  663. return sessions;
  664. };
  665. /**
  666. * Registers event listeners on the RTC instance.
  667. * @param {RTC} rtc - the RTC module instance used by this conference.
  668. * @private
  669. * @returns {void}
  670. */
  671. JitsiConference.prototype._registerRtcListeners = function(rtc) {
  672. rtc.addListener(RTCEvents.DATA_CHANNEL_OPEN, () => {
  673. for (const localTrack of this.rtc.localTracks) {
  674. localTrack.isVideoTrack() && this._sendBridgeVideoTypeMessage(localTrack);
  675. }
  676. });
  677. };
  678. /**
  679. * Sends the 'VideoTypeMessage' to the bridge on the bridge channel so that the bridge can make bitrate allocation
  680. * decisions based on the video type of the local source.
  681. *
  682. * @param {JitsiLocalTrack} localtrack - The track associated with the local source signaled to the bridge.
  683. * @returns {void}
  684. * @private
  685. */
  686. JitsiConference.prototype._sendBridgeVideoTypeMessage = function(localtrack) {
  687. let videoType = !localtrack || localtrack.isMuted() ? BridgeVideoType.NONE : localtrack.getVideoType();
  688. if (videoType === BridgeVideoType.DESKTOP && this._desktopSharingFrameRate > SS_DEFAULT_FRAME_RATE) {
  689. videoType = BridgeVideoType.DESKTOP_HIGH_FPS;
  690. }
  691. localtrack && this.rtc.sendSourceVideoType(localtrack.getSourceName(), videoType);
  692. };
  693. /**
  694. * Returns name of this conference.
  695. */
  696. JitsiConference.prototype.getName = function() {
  697. return this.options.name.toString();
  698. };
  699. /**
  700. * Returns the {@link JitsiConnection} used by this this conference.
  701. */
  702. JitsiConference.prototype.getConnection = function() {
  703. return this.connection;
  704. };
  705. /**
  706. * Check if authentication is enabled for this conference.
  707. */
  708. JitsiConference.prototype.isAuthEnabled = function() {
  709. return this.authEnabled;
  710. };
  711. /**
  712. * Check if user is logged in.
  713. */
  714. JitsiConference.prototype.isLoggedIn = function() {
  715. return Boolean(this.authIdentity);
  716. };
  717. /**
  718. * Get authorized login.
  719. */
  720. JitsiConference.prototype.getAuthLogin = function() {
  721. return this.authIdentity;
  722. };
  723. /**
  724. * Returns the local tracks of the given media type, or all local tracks if no
  725. * specific type is given.
  726. * @param {MediaType} [mediaType] Optional media type (audio or video).
  727. */
  728. JitsiConference.prototype.getLocalTracks = function(mediaType) {
  729. let tracks = [];
  730. if (this.rtc) {
  731. tracks = this.rtc.getLocalTracks(mediaType);
  732. }
  733. return tracks;
  734. };
  735. /**
  736. * Obtains local audio track.
  737. * @return {JitsiLocalTrack|null}
  738. */
  739. JitsiConference.prototype.getLocalAudioTrack = function() {
  740. return this.rtc ? this.rtc.getLocalAudioTrack() : null;
  741. };
  742. /**
  743. * Obtains local video track.
  744. * @return {JitsiLocalTrack|null}
  745. */
  746. JitsiConference.prototype.getLocalVideoTrack = function() {
  747. return this.rtc ? this.rtc.getLocalVideoTrack() : null;
  748. };
  749. /**
  750. * Returns all the local video tracks.
  751. * @returns {Array<JitsiLocalTrack>}
  752. */
  753. JitsiConference.prototype.getLocalVideoTracks = function() {
  754. return this.rtc ? this.rtc.getLocalVideoTracks() : null;
  755. };
  756. /**
  757. * Obtains the performance statistics.
  758. * @returns {Object|null}
  759. */
  760. JitsiConference.prototype.getPerformanceStats = function() {
  761. return {
  762. longTasksStats: this.statistics.getLongTasksStats()
  763. };
  764. };
  765. /**
  766. * Attaches a handler for events(For example - "participant joined".) in the
  767. * conference. All possible event are defined in JitsiConferenceEvents.
  768. * @param eventId the event ID.
  769. * @param handler handler for the event.
  770. *
  771. * Note: consider adding eventing functionality by extending an EventEmitter
  772. * impl, instead of rolling ourselves
  773. */
  774. JitsiConference.prototype.on = function(eventId, handler) {
  775. if (this.eventEmitter) {
  776. this.eventEmitter.on(eventId, handler);
  777. }
  778. };
  779. /**
  780. * Adds a one-time`listener` function for the event.
  781. * @param eventId the event ID.
  782. * @param handler handler for the event.
  783. *
  784. */
  785. JitsiConference.prototype.once = function(eventId, handler) {
  786. if (this.eventEmitter) {
  787. this.eventEmitter.once(eventId, handler);
  788. }
  789. };
  790. /**
  791. * Removes event listener
  792. * @param eventId the event ID.
  793. * @param [handler] optional, the specific handler to unbind
  794. *
  795. * Note: consider adding eventing functionality by extending an EventEmitter
  796. * impl, instead of rolling ourselves
  797. */
  798. JitsiConference.prototype.off = function(eventId, handler) {
  799. if (this.eventEmitter) {
  800. this.eventEmitter.removeListener(eventId, handler);
  801. }
  802. };
  803. // Common aliases for event emitter
  804. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  805. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  806. /**
  807. * Receives notifications from other participants about commands / custom events
  808. * (sent by sendCommand or sendCommandOnce methods).
  809. * @param command {String} the name of the command
  810. * @param handler {Function} handler for the command
  811. */
  812. JitsiConference.prototype.addCommandListener = function(command, handler) {
  813. if (this.room) {
  814. this.room.addPresenceListener(command, handler);
  815. }
  816. };
  817. /**
  818. * Removes command listener
  819. * @param command {String} the name of the command
  820. * @param handler {Function} handler to remove for the command
  821. */
  822. JitsiConference.prototype.removeCommandListener = function(command, handler) {
  823. if (this.room) {
  824. this.room.removePresenceListener(command, handler);
  825. }
  826. };
  827. /**
  828. * Sends text message to the other participants in the conference
  829. * @param message the text message.
  830. * @param elementName the element name to encapsulate the message.
  831. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  832. */
  833. JitsiConference.prototype.sendTextMessage = function(message, elementName = 'body') {
  834. if (this.room) {
  835. this.room.sendMessage(message, elementName);
  836. }
  837. };
  838. /**
  839. * Send private text message to another participant of the conference
  840. * @param id the id of the participant to send a private message.
  841. * @param message the text message.
  842. * @param elementName the element name to encapsulate the message.
  843. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  844. */
  845. JitsiConference.prototype.sendPrivateTextMessage = function(id, message, elementName = 'body') {
  846. if (this.room) {
  847. this.room.sendPrivateMessage(id, message, elementName);
  848. }
  849. };
  850. /**
  851. * Send presence command.
  852. * @param name {String} the name of the command.
  853. * @param values {Object} with keys and values that will be sent.
  854. **/
  855. JitsiConference.prototype.sendCommand = function(name, values) {
  856. if (this.room) {
  857. this.room.addOrReplaceInPresence(name, values) && this.room.sendPresence();
  858. } else {
  859. logger.warn('Not sending a command, room not initialized.');
  860. }
  861. };
  862. /**
  863. * Send presence command one time.
  864. * @param name {String} the name of the command.
  865. * @param values {Object} with keys and values that will be sent.
  866. **/
  867. JitsiConference.prototype.sendCommandOnce = function(name, values) {
  868. this.sendCommand(name, values);
  869. this.removeCommand(name);
  870. };
  871. /**
  872. * Removes presence command.
  873. * @param name {String} the name of the command.
  874. **/
  875. JitsiConference.prototype.removeCommand = function(name) {
  876. if (this.room) {
  877. this.room.removeFromPresence(name);
  878. }
  879. };
  880. /**
  881. * Sets the display name for this conference.
  882. * @param name the display name to set
  883. */
  884. JitsiConference.prototype.setDisplayName = function(name) {
  885. if (this.room) {
  886. const nickKey = 'nick';
  887. if (name) {
  888. this.room.addOrReplaceInPresence(nickKey, {
  889. attributes: { xmlns: 'http://jabber.org/protocol/nick' },
  890. value: name
  891. }) && this.room.sendPresence();
  892. } else if (this.room.getFromPresence(nickKey)) {
  893. this.room.removeFromPresence(nickKey);
  894. this.room.sendPresence();
  895. }
  896. }
  897. };
  898. /**
  899. * Set new subject for this conference. (available only for moderator)
  900. * @param {string} subject new subject
  901. */
  902. JitsiConference.prototype.setSubject = function(subject) {
  903. if (this.room && this.isModerator()) {
  904. this.room.setSubject(subject);
  905. } else {
  906. logger.warn(`Failed to set subject, ${this.room ? '' : 'not in a room, '}${
  907. this.isModerator() ? '' : 'participant is not a moderator'}`);
  908. }
  909. };
  910. /**
  911. * Returns the transcription status.
  912. *
  913. * @returns {String} "on" or "off".
  914. */
  915. JitsiConference.prototype.getTranscriptionStatus = function() {
  916. return this.room.transcriptionStatus;
  917. };
  918. /**
  919. * Adds JitsiLocalTrack object to the conference.
  920. * @param {JitsiLocalTrack} track the JitsiLocalTrack object.
  921. * @returns {Promise<JitsiLocalTrack>}
  922. * @throws {Error} if the specified track is a video track and there is already
  923. * another video track in the conference.
  924. */
  925. JitsiConference.prototype.addTrack = function(track) {
  926. if (!track) {
  927. throw new Error('addTrack - a track is required');
  928. }
  929. const mediaType = track.getType();
  930. const localTracks = this.rtc.getLocalTracks(mediaType);
  931. // Ensure there's exactly 1 local track of each media type in the conference.
  932. if (localTracks.length > 0) {
  933. // Don't be excessively harsh and severe if the API client happens to attempt to add the same local track twice.
  934. if (track === localTracks[0]) {
  935. return Promise.resolve(track);
  936. }
  937. // Currently, only adding multiple video streams of different video types is supported.
  938. // TODO - remove this limitation once issues with jitsi-meet trying to add multiple camera streams is fixed.
  939. if (mediaType === MediaType.VIDEO
  940. && !localTracks.find(t => t.getVideoType() === track.getVideoType())) {
  941. const sourceName = getSourceNameForJitsiTrack(
  942. this.myUserId(),
  943. mediaType,
  944. this.getLocalTracks(mediaType)?.length);
  945. track.setSourceName(sourceName);
  946. const addTrackPromises = [];
  947. this.p2pJingleSession && addTrackPromises.push(this.p2pJingleSession.addTracks([ track ]));
  948. this.jvbJingleSession && addTrackPromises.push(this.jvbJingleSession.addTracks([ track ]));
  949. return Promise.all(addTrackPromises)
  950. .then(() => {
  951. this._setupNewTrack(track);
  952. this._sendBridgeVideoTypeMessage(track);
  953. this._updateRoomPresence(this.getActiveMediaSession());
  954. if (this.isMutedByFocus || this.isVideoMutedByFocus) {
  955. this._fireMuteChangeEvent(track);
  956. }
  957. });
  958. }
  959. return Promise.reject(new Error(`Cannot add second ${mediaType} track to the conference`));
  960. }
  961. return this.replaceTrack(null, track)
  962. .then(() => {
  963. // Presence needs to be sent here for desktop track since we need the presence to reach the remote peer
  964. // before signaling so that a fake participant tile is created for screenshare. Otherwise, presence will
  965. // only be sent after a session-accept or source-add is ack'ed.
  966. if (track.getVideoType() === VideoType.DESKTOP) {
  967. this._updateRoomPresence(this.getActiveMediaSession());
  968. }
  969. });
  970. };
  971. /**
  972. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event (for local tracks).
  973. * @param {number} audioLevel the audio level
  974. * @param {TraceablePeerConnection} [tpc]
  975. */
  976. JitsiConference.prototype._fireAudioLevelChangeEvent = function(audioLevel, tpc) {
  977. const activeTpc = this.getActivePeerConnection();
  978. // There will be no TraceablePeerConnection if audio levels do not come from
  979. // a peerconnection. LocalStatsCollector.js measures audio levels using Web
  980. // Audio Analyser API and emits local audio levels events through
  981. // JitsiTrack.setAudioLevel, but does not provide TPC instance which is
  982. // optional.
  983. if (!tpc || activeTpc === tpc) {
  984. this.eventEmitter.emit(
  985. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  986. this.myUserId(), audioLevel);
  987. }
  988. };
  989. /**
  990. * Fires TRACK_MUTE_CHANGED change conference event.
  991. * @param track the JitsiTrack object related to the event.
  992. */
  993. JitsiConference.prototype._fireMuteChangeEvent = function(track) {
  994. // check if track was muted by focus and now is unmuted by user
  995. if (this.isMutedByFocus && track.isAudioTrack() && !track.isMuted()) {
  996. this.isMutedByFocus = false;
  997. // unmute local user on server
  998. this.room.muteParticipant(this.room.myroomjid, false, MediaType.AUDIO);
  999. } else if (this.isVideoMutedByFocus && track.isVideoTrack() && !track.isMuted()) {
  1000. this.isVideoMutedByFocus = false;
  1001. // unmute local user on server
  1002. this.room.muteParticipant(this.room.myroomjid, false, MediaType.VIDEO);
  1003. }
  1004. let actorParticipant;
  1005. if (this.mutedByFocusActor && track.isAudioTrack()) {
  1006. const actorId = Strophe.getResourceFromJid(this.mutedByFocusActor);
  1007. actorParticipant = this.participants.get(actorId);
  1008. } else if (this.mutedVideoByFocusActor && track.isVideoTrack()) {
  1009. const actorId = Strophe.getResourceFromJid(this.mutedVideoByFocusActor);
  1010. actorParticipant = this.participants.get(actorId);
  1011. }
  1012. // Send the video type message to the bridge if the track is not removed/added to the pc as part of
  1013. // the mute/unmute operation.
  1014. // In React Native we mute the camera by setting track.enabled but that doesn't
  1015. // work for screen-share tracks, so do the remove-as-mute for those.
  1016. const doesVideoMuteByStreamRemove
  1017. = browser.isReactNative() ? track.videoType === VideoType.DESKTOP : browser.doesVideoMuteByStreamRemove();
  1018. if (track.isVideoTrack() && !doesVideoMuteByStreamRemove) {
  1019. this._sendBridgeVideoTypeMessage(track);
  1020. }
  1021. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track, actorParticipant);
  1022. };
  1023. /**
  1024. * Returns the list of local tracks that need to be added to the peerconnection on join.
  1025. * This takes the startAudioMuted/startVideoMuted flags into consideration since we do not
  1026. * want to add the tracks if the user joins the call audio/video muted. The tracks will be
  1027. * added when the user unmutes for the first time.
  1028. * @returns {Array<JitsiLocalTrack>} - list of local tracks that are unmuted.
  1029. */
  1030. JitsiConference.prototype._getInitialLocalTracks = function() {
  1031. // Always add the audio track on certain platforms:
  1032. // * Safari / WebKit: because of a known issue where audio playout doesn't happen
  1033. // if the user joins audio and video muted.
  1034. // * React Native: after iOS 15, if a user joins muted they won't be able to unmute.
  1035. return this.getLocalTracks()
  1036. .filter(track => {
  1037. const trackType = track.getType();
  1038. if (trackType === MediaType.AUDIO
  1039. && (!(this.isStartAudioMuted() || this.startMutedPolicy.audio)
  1040. || browser.isWebKitBased()
  1041. || browser.isReactNative())) {
  1042. return true;
  1043. } else if (trackType === MediaType.VIDEO && !this.isStartVideoMuted() && !this.startMutedPolicy.video) {
  1044. return true;
  1045. }
  1046. return false;
  1047. });
  1048. };
  1049. /**
  1050. * Clear JitsiLocalTrack properties and listeners.
  1051. * @param track the JitsiLocalTrack object.
  1052. */
  1053. JitsiConference.prototype.onLocalTrackRemoved = function(track) {
  1054. track.setConference(null);
  1055. this.rtc.removeLocalTrack(track);
  1056. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, track.muteHandler);
  1057. if (track.isAudioTrack()) {
  1058. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, track.audioLevelHandler);
  1059. }
  1060. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  1061. };
  1062. /**
  1063. * Removes JitsiLocalTrack from the conference and performs
  1064. * a new offer/answer cycle.
  1065. * @param {JitsiLocalTrack} track
  1066. * @returns {Promise}
  1067. */
  1068. JitsiConference.prototype.removeTrack = function(track) {
  1069. return this.replaceTrack(track, null);
  1070. };
  1071. /**
  1072. * Replaces oldTrack with newTrack and performs a single offer/answer
  1073. * cycle after both operations are done. Either oldTrack or newTrack
  1074. * can be null; replacing a valid 'oldTrack' with a null 'newTrack'
  1075. * effectively just removes 'oldTrack'
  1076. * @param {JitsiLocalTrack} oldTrack the current stream in use to be replaced
  1077. * @param {JitsiLocalTrack} newTrack the new stream to use
  1078. * @returns {Promise} resolves when the replacement is finished
  1079. */
  1080. JitsiConference.prototype.replaceTrack = function(oldTrack, newTrack) {
  1081. const oldVideoType = oldTrack?.getVideoType();
  1082. const mediaType = oldTrack?.getType() || newTrack?.getType();
  1083. const newVideoType = newTrack?.getVideoType();
  1084. if (oldTrack && newTrack && oldVideoType !== newVideoType) {
  1085. throw new Error(`Replacing a track of videoType=${oldVideoType} with a track of videoType=${newVideoType} is`
  1086. + ' not supported in this mode.');
  1087. }
  1088. if (newTrack) {
  1089. const sourceName = oldTrack
  1090. ? oldTrack.getSourceName()
  1091. : getSourceNameForJitsiTrack(
  1092. this.myUserId(),
  1093. mediaType,
  1094. this.getLocalTracks(mediaType)?.length);
  1095. newTrack.setSourceName(sourceName);
  1096. }
  1097. const oldTrackBelongsToConference = this === oldTrack?.conference;
  1098. if (oldTrackBelongsToConference && oldTrack.disposed) {
  1099. return Promise.reject(new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  1100. }
  1101. if (newTrack?.disposed) {
  1102. return Promise.reject(new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  1103. }
  1104. if (oldTrack && !oldTrackBelongsToConference) {
  1105. logger.warn(`JitsiConference.replaceTrack oldTrack (${oldTrack} does not belong to this conference`);
  1106. }
  1107. // Now replace the stream at the lower levels
  1108. return this._doReplaceTrack(oldTrackBelongsToConference ? oldTrack : null, newTrack)
  1109. .then(() => {
  1110. if (oldTrackBelongsToConference && !oldTrack.isMuted() && !newTrack) {
  1111. oldTrack._sendMuteStatus(true);
  1112. }
  1113. oldTrackBelongsToConference && this.onLocalTrackRemoved(oldTrack);
  1114. newTrack && this._setupNewTrack(newTrack);
  1115. // Send 'VideoTypeMessage' on the bridge channel when a video track is added/removed.
  1116. if ((oldTrackBelongsToConference && oldTrack?.isVideoTrack()) || newTrack?.isVideoTrack()) {
  1117. this._sendBridgeVideoTypeMessage(newTrack);
  1118. }
  1119. this._updateRoomPresence(this.getActiveMediaSession());
  1120. if (newTrack !== null && (this.isMutedByFocus || this.isVideoMutedByFocus)) {
  1121. this._fireMuteChangeEvent(newTrack);
  1122. }
  1123. return Promise.resolve();
  1124. })
  1125. .catch(error => {
  1126. logger.error(`replaceTrack failed: ${error?.stack}`);
  1127. return Promise.reject(error);
  1128. });
  1129. };
  1130. /**
  1131. * Replaces the tracks at the lower level by going through the Jingle session
  1132. * and WebRTC peer connection. The method will resolve immediately if there is
  1133. * currently no JingleSession started.
  1134. * @param {JitsiLocalTrack|null} oldTrack the track to be removed during
  1135. * the process or <tt>null</t> if the method should act as "add track"
  1136. * @param {JitsiLocalTrack|null} newTrack the new track to be added or
  1137. * <tt>null</tt> if the method should act as "remove track"
  1138. * @return {Promise} resolved when the process is done or rejected with a string
  1139. * which describes the error.
  1140. * @private
  1141. */
  1142. JitsiConference.prototype._doReplaceTrack = function(oldTrack, newTrack) {
  1143. const replaceTrackPromises = [];
  1144. if (this.jvbJingleSession) {
  1145. replaceTrackPromises.push(this.jvbJingleSession.replaceTrack(oldTrack, newTrack));
  1146. } else {
  1147. logger.info('_doReplaceTrack - no JVB JingleSession');
  1148. }
  1149. if (this.p2pJingleSession) {
  1150. replaceTrackPromises.push(this.p2pJingleSession.replaceTrack(oldTrack, newTrack));
  1151. } else {
  1152. logger.info('_doReplaceTrack - no P2P JingleSession');
  1153. }
  1154. return Promise.all(replaceTrackPromises);
  1155. };
  1156. /**
  1157. * Handler for when a source-add for a local source is rejected by Jicofo.
  1158. *
  1159. * @param {JingleSessionPC} jingleSession - The media session.
  1160. * @param {Error} error - The error message.
  1161. * @param {MediaType} mediaType - The media type of the track associated with the source that was rejected.
  1162. * @returns {void}
  1163. */
  1164. JitsiConference.prototype._removeLocalSourceOnReject = function(jingleSession, error, mediaType) {
  1165. if (!jingleSession) {
  1166. return;
  1167. }
  1168. logger.warn(`Source-add rejected on ${jingleSession}, reason="${error?.reason}", message="${error?.msg}"`);
  1169. const track = this.getLocalTracks(mediaType)[0];
  1170. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_UNMUTE_REJECTED, track);
  1171. };
  1172. /**
  1173. * Operations related to creating a new track
  1174. * @param {JitsiLocalTrack} newTrack the new track being created
  1175. */
  1176. JitsiConference.prototype._setupNewTrack = function(newTrack) {
  1177. const mediaType = newTrack.getType();
  1178. // Create a source name for this track if it doesn't exist.
  1179. if (!newTrack.getSourceName()) {
  1180. const sourceName = getSourceNameForJitsiTrack(
  1181. this.myUserId(),
  1182. mediaType,
  1183. this.getLocalTracks(mediaType)?.length);
  1184. newTrack.setSourceName(sourceName);
  1185. }
  1186. this.rtc.addLocalTrack(newTrack);
  1187. newTrack.setConference(this);
  1188. // Suspend media on the inactive media session since it gets automatically enabled for a newly added source.
  1189. if (this.isP2PActive()) {
  1190. this._suspendMediaTransferForJvbConnection();
  1191. }
  1192. // Add event handlers.
  1193. newTrack.muteHandler = this._fireMuteChangeEvent.bind(this, newTrack);
  1194. newTrack.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, newTrack.muteHandler);
  1195. if (newTrack.isAudioTrack()) {
  1196. newTrack.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  1197. newTrack.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, newTrack.audioLevelHandler);
  1198. }
  1199. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, newTrack);
  1200. };
  1201. /**
  1202. * Sets the video type.
  1203. * @param track
  1204. * @return <tt>true</tt> if video type was changed in presence.
  1205. * @private
  1206. */
  1207. JitsiConference.prototype._setNewVideoType = function(track) {
  1208. let videoTypeChanged = false;
  1209. if (track) {
  1210. videoTypeChanged = this._signalingLayer.setTrackVideoType(track.getSourceName(), track.videoType);
  1211. }
  1212. return videoTypeChanged;
  1213. };
  1214. /**
  1215. * Sets mute status.
  1216. * @param mediaType
  1217. * @param localTrack
  1218. * @param isMuted
  1219. * @param <tt>true</tt> when presence was changed, <tt>false</tt> otherwise.
  1220. * @private
  1221. */
  1222. JitsiConference.prototype._setTrackMuteStatus = function(mediaType, localTrack, isMuted) {
  1223. let presenceChanged = false;
  1224. if (localTrack) {
  1225. presenceChanged = this._signalingLayer.setTrackMuteStatus(localTrack.getSourceName(), isMuted);
  1226. presenceChanged && logger.debug(`Mute state of ${localTrack} changed to muted=${isMuted}`);
  1227. }
  1228. return presenceChanged;
  1229. };
  1230. /**
  1231. * Method called by the {@link JitsiLocalTrack} in order to add the underlying MediaStream to the RTCPeerConnection.
  1232. *
  1233. * @param {JitsiLocalTrack} track the local track that will be added to the pc.
  1234. * @return {Promise} resolved when the process is done or rejected with a string which describes the error.
  1235. */
  1236. JitsiConference.prototype._addLocalTrackToPc = function(track) {
  1237. const addPromises = [];
  1238. if (this.jvbJingleSession) {
  1239. addPromises.push(this.jvbJingleSession.addTrackToPc(track));
  1240. } else {
  1241. logger.debug('Add local MediaStream - no JVB Jingle session started yet');
  1242. }
  1243. if (this.p2pJingleSession) {
  1244. addPromises.push(this.p2pJingleSession.addTrackToPc(track));
  1245. } else {
  1246. logger.debug('Add local MediaStream - no P2P Jingle session started yet');
  1247. }
  1248. return Promise.allSettled(addPromises);
  1249. };
  1250. /**
  1251. * Method called by the {@link JitsiLocalTrack} in order to remove the underlying MediaStream from the
  1252. * RTCPeerConnection.
  1253. *
  1254. * @param {JitsiLocalTrack} track the local track that will be removed.
  1255. * @return {Promise} resolved when the process is done or rejected with a string which describes the error.
  1256. */
  1257. JitsiConference.prototype._removeLocalTrackFromPc = function(track) {
  1258. const removePromises = [];
  1259. if (this.jvbJingleSession) {
  1260. removePromises.push(this.jvbJingleSession.removeTrackFromPc(track));
  1261. } else {
  1262. logger.debug('Remove local MediaStream - no JVB JingleSession started yet');
  1263. }
  1264. if (this.p2pJingleSession) {
  1265. removePromises.push(this.p2pJingleSession.removeTrackFromPc(track));
  1266. } else {
  1267. logger.debug('Remove local MediaStream - no P2P JingleSession started yet');
  1268. }
  1269. return Promise.allSettled(removePromises);
  1270. };
  1271. /**
  1272. * Get role of the local user.
  1273. * @returns {string} user role: 'moderator' or 'none'
  1274. */
  1275. JitsiConference.prototype.getRole = function() {
  1276. return this.room.role;
  1277. };
  1278. /**
  1279. * Returns whether or not the current conference has been joined as a hidden
  1280. * user.
  1281. *
  1282. * @returns {boolean|null} True if hidden, false otherwise. Will return null if
  1283. * no connection is active.
  1284. */
  1285. JitsiConference.prototype.isHidden = function() {
  1286. if (!this.connection) {
  1287. return null;
  1288. }
  1289. return Strophe.getDomainFromJid(this.connection.getJid())
  1290. === this.options.config.hiddenDomain;
  1291. };
  1292. /**
  1293. * Check if local user is moderator.
  1294. * @returns {boolean|null} true if local user is moderator, false otherwise. If
  1295. * we're no longer in the conference room then <tt>null</tt> is returned.
  1296. */
  1297. JitsiConference.prototype.isModerator = function() {
  1298. return this.room ? this.room.isModerator() : null;
  1299. };
  1300. /**
  1301. * Set password for the room.
  1302. * @param {string} password new password for the room.
  1303. * @returns {Promise}
  1304. */
  1305. JitsiConference.prototype.lock = function(password) {
  1306. if (!this.isModerator()) {
  1307. return Promise.reject(new Error('You are not moderator.'));
  1308. }
  1309. return new Promise((resolve, reject) => {
  1310. this.room.lockRoom(
  1311. password || '',
  1312. () => resolve(),
  1313. err => reject(err),
  1314. () => reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED));
  1315. });
  1316. };
  1317. /**
  1318. * Remove password from the room.
  1319. * @returns {Promise}
  1320. */
  1321. JitsiConference.prototype.unlock = function() {
  1322. return this.lock();
  1323. };
  1324. /**
  1325. * Obtains the current value for "lastN". See {@link setLastN} for more info.
  1326. * @returns {number}
  1327. */
  1328. JitsiConference.prototype.getLastN = function() {
  1329. return this.receiveVideoController.getLastN();
  1330. };
  1331. /**
  1332. * Obtains the forwarded sources list in this conference.
  1333. * @return {Array<string>|null}
  1334. */
  1335. JitsiConference.prototype.getForwardedSources = function() {
  1336. return this.rtc.getForwardedSources();
  1337. };
  1338. /**
  1339. * Selects a new value for "lastN". The requested amount of videos are going
  1340. * to be delivered after the value is in effect. Set to -1 for unlimited or
  1341. * all available videos.
  1342. * @param lastN the new number of videos the user would like to receive.
  1343. * @throws Error or RangeError if the given value is not a number or is smaller
  1344. * than -1.
  1345. */
  1346. JitsiConference.prototype.setLastN = function(lastN) {
  1347. if (!Number.isInteger(lastN) && !Number.parseInt(lastN, 10)) {
  1348. throw new Error(`Invalid value for lastN: ${lastN}`);
  1349. }
  1350. const n = Number(lastN);
  1351. if (n < -1) {
  1352. throw new RangeError('lastN cannot be smaller than -1');
  1353. }
  1354. this.receiveVideoController.setLastN(n);
  1355. // If the P2P session is not fully established yet, we wait until it gets established.
  1356. if (this.p2pJingleSession) {
  1357. const isVideoActive = n !== 0;
  1358. this.p2pJingleSession
  1359. .setP2pVideoTransferActive(isVideoActive)
  1360. .catch(error => {
  1361. logger.error(`Failed to adjust video transfer status (${isVideoActive})`, error);
  1362. });
  1363. }
  1364. };
  1365. /**
  1366. * @return Array<JitsiParticipant> an array of all participants in this conference.
  1367. */
  1368. JitsiConference.prototype.getParticipants = function() {
  1369. return Array.from(this.participants.values());
  1370. };
  1371. /**
  1372. * Returns the number of participants in the conference, including the local
  1373. * participant.
  1374. * @param countHidden {boolean} Whether or not to include hidden participants
  1375. * in the count. Default: false.
  1376. **/
  1377. JitsiConference.prototype.getParticipantCount = function(countHidden = false) {
  1378. let participants = this.getParticipants();
  1379. if (!countHidden) {
  1380. participants = participants.filter(p => !p.isHidden());
  1381. }
  1382. // Add one for the local participant.
  1383. return participants.length + 1;
  1384. };
  1385. /**
  1386. * @returns {JitsiParticipant} the participant in this conference with the
  1387. * specified id (or undefined if there isn't one).
  1388. * @param id the id of the participant.
  1389. */
  1390. JitsiConference.prototype.getParticipantById = function(id) {
  1391. return this.participants.get(id);
  1392. };
  1393. /**
  1394. * Grant owner rights to the participant.
  1395. * @param {string} id id of the participant to grant owner rights to.
  1396. */
  1397. JitsiConference.prototype.grantOwner = function(id) {
  1398. const participant = this.getParticipantById(id);
  1399. if (!participant) {
  1400. return;
  1401. }
  1402. this.room.setAffiliation(participant.getConnectionJid(), 'owner');
  1403. };
  1404. /**
  1405. * Revoke owner rights to the participant or local Participant as
  1406. * the user might want to refuse to be a moderator.
  1407. * @param {string} id id of the participant to revoke owner rights to.
  1408. */
  1409. JitsiConference.prototype.revokeOwner = function(id) {
  1410. const participant = this.getParticipantById(id);
  1411. const isMyself = this.myUserId() === id;
  1412. const role = this.isMembersOnly() ? 'member' : 'none';
  1413. if (isMyself) {
  1414. this.room.setAffiliation(this.connection.getJid(), role);
  1415. } else if (participant) {
  1416. this.room.setAffiliation(participant.getConnectionJid(), role);
  1417. }
  1418. };
  1419. /**
  1420. * Kick participant from this conference.
  1421. * @param {string} id id of the participant to kick
  1422. * @param {string} reason reason of the participant to kick
  1423. */
  1424. JitsiConference.prototype.kickParticipant = function(id, reason) {
  1425. const participant = this.getParticipantById(id);
  1426. if (!participant) {
  1427. return;
  1428. }
  1429. this.room.kick(participant.getJid(), reason);
  1430. };
  1431. /**
  1432. * Maybe clears the timeout which emits {@link ACTION_JINGLE_SI_TIMEOUT}
  1433. * analytics event.
  1434. * @private
  1435. */
  1436. JitsiConference.prototype._maybeClearSITimeout = function() {
  1437. if (this._sessionInitiateTimeout
  1438. && (this.jvbJingleSession || this.getParticipantCount() < 2)) {
  1439. window.clearTimeout(this._sessionInitiateTimeout);
  1440. this._sessionInitiateTimeout = null;
  1441. }
  1442. };
  1443. /**
  1444. * Sets a timeout which will emit {@link ACTION_JINGLE_SI_TIMEOUT} analytics
  1445. * event.
  1446. * @private
  1447. */
  1448. JitsiConference.prototype._maybeSetSITimeout = function() {
  1449. // Jicofo is supposed to invite if there are at least 2 participants
  1450. if (!this.jvbJingleSession
  1451. && this.getParticipantCount() >= 2
  1452. && !this._sessionInitiateTimeout) {
  1453. this._sessionInitiateTimeout = window.setTimeout(() => {
  1454. this._sessionInitiateTimeout = null;
  1455. Statistics.sendAnalytics(createJingleEvent(
  1456. ACTION_JINGLE_SI_TIMEOUT,
  1457. {
  1458. p2p: false,
  1459. value: JINGLE_SI_TIMEOUT
  1460. }));
  1461. }, JINGLE_SI_TIMEOUT);
  1462. }
  1463. };
  1464. /**
  1465. * Mutes a participant.
  1466. * @param {string} id The id of the participant to mute.
  1467. */
  1468. JitsiConference.prototype.muteParticipant = function(id, mediaType) {
  1469. const muteMediaType = mediaType ? mediaType : MediaType.AUDIO;
  1470. if (muteMediaType !== MediaType.AUDIO && muteMediaType !== MediaType.VIDEO) {
  1471. logger.error(`Unsupported media type: ${muteMediaType}`);
  1472. return;
  1473. }
  1474. const participant = this.getParticipantById(id);
  1475. if (!participant) {
  1476. return;
  1477. }
  1478. this.room.muteParticipant(participant.getJid(), true, muteMediaType);
  1479. };
  1480. /* eslint-disable max-params */
  1481. /**
  1482. * Notifies this JitsiConference that a new member has joined its chat room.
  1483. *
  1484. * FIXME This should NOT be exposed!
  1485. *
  1486. * @param jid the jid of the participant in the MUC
  1487. * @param nick the display name of the participant
  1488. * @param role the role of the participant in the MUC
  1489. * @param isHidden indicates if this is a hidden participant (system
  1490. * participant for example a recorder).
  1491. * @param statsID the participant statsID (optional)
  1492. * @param status the initial status if any
  1493. * @param identity the member identity, if any
  1494. * @param botType the member botType, if any
  1495. * @param fullJid the member full jid, if any
  1496. * @param features the member botType, if any
  1497. * @param isReplaceParticipant whether this join replaces a participant with
  1498. * the same jwt.
  1499. */
  1500. JitsiConference.prototype.onMemberJoined = function(
  1501. jid, nick, role, isHidden, statsID, status, identity, botType, fullJid, features, isReplaceParticipant) {
  1502. const id = Strophe.getResourceFromJid(jid);
  1503. if (id === 'focus' || this.myUserId() === id) {
  1504. return;
  1505. }
  1506. const participant = new JitsiParticipant(jid, this, nick, isHidden, statsID, status, identity);
  1507. participant.setConnectionJid(fullJid);
  1508. participant.setRole(role);
  1509. participant.setBotType(botType);
  1510. participant.setFeatures(features);
  1511. participant.setIsReplacing(isReplaceParticipant);
  1512. // Set remote tracks on the participant if source signaling was received before presence.
  1513. const remoteTracks = this.isP2PActive()
  1514. ? this.p2pJingleSession?.peerconnection.getRemoteTracks(id) ?? []
  1515. : this.jvbJingleSession?.peerconnection.getRemoteTracks(id) ?? [];
  1516. for (const track of remoteTracks) {
  1517. participant._tracks.push(track);
  1518. }
  1519. this.participants.set(id, participant);
  1520. this.eventEmitter.emit(
  1521. JitsiConferenceEvents.USER_JOINED,
  1522. id,
  1523. participant);
  1524. this._updateFeatures(participant);
  1525. // maybeStart only if we had finished joining as then we will have information for the number of participants
  1526. if (this.isJoined()) {
  1527. this._maybeStartOrStopP2P();
  1528. }
  1529. this._maybeSetSITimeout();
  1530. };
  1531. /* eslint-enable max-params */
  1532. /**
  1533. * Get notified when we joined the room.
  1534. *
  1535. * @private
  1536. */
  1537. JitsiConference.prototype._onMucJoined = function() {
  1538. this._numberOfParticipantsOnJoin = this.getParticipantCount();
  1539. this._maybeStartOrStopP2P();
  1540. };
  1541. /**
  1542. * Updates features for a participant.
  1543. * @param {JitsiParticipant} participant - The participant to query for features.
  1544. * @returns {void}
  1545. * @private
  1546. */
  1547. JitsiConference.prototype._updateFeatures = function(participant) {
  1548. participant.getFeatures()
  1549. .then(features => {
  1550. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  1551. this.updateDTMFSupport();
  1552. if (features.has(FEATURE_JIGASI)) {
  1553. participant.setProperty('features_jigasi', true);
  1554. }
  1555. if (features.has(FEATURE_E2EE)) {
  1556. participant.setProperty('features_e2ee', true);
  1557. }
  1558. })
  1559. .catch(() => false);
  1560. };
  1561. /**
  1562. * Get notified when member bot type had changed.
  1563. * @param jid the member jid
  1564. * @param botType the new botType value
  1565. * @private
  1566. */
  1567. JitsiConference.prototype._onMemberBotTypeChanged = function(jid, botType) {
  1568. // find the participant and mark it as non bot, as the real one will join
  1569. // in a moment
  1570. const peers = this.getParticipants();
  1571. const botParticipant = peers.find(p => p.getJid() === jid);
  1572. if (botParticipant) {
  1573. botParticipant.setBotType(botType);
  1574. const id = Strophe.getResourceFromJid(jid);
  1575. this.eventEmitter.emit(
  1576. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1577. id,
  1578. botType);
  1579. }
  1580. // if botType changed to undefined, botType was removed, in case of
  1581. // poltergeist mode this is the moment when the poltergeist had exited and
  1582. // the real participant had already replaced it.
  1583. // In this case we can check and try p2p
  1584. if (!botParticipant.getBotType()) {
  1585. this._maybeStartOrStopP2P();
  1586. }
  1587. };
  1588. JitsiConference.prototype.onMemberLeft = function(jid, reason) {
  1589. const id = Strophe.getResourceFromJid(jid);
  1590. if (id === 'focus' || this.myUserId() === id) {
  1591. return;
  1592. }
  1593. const mediaSessions = this.getMediaSessions();
  1594. let tracksToBeRemoved = [];
  1595. for (const session of mediaSessions) {
  1596. const remoteTracks = session.peerconnection.getRemoteTracks(id);
  1597. remoteTracks && (tracksToBeRemoved = [ ...tracksToBeRemoved, ...remoteTracks ]);
  1598. // Update the SSRC owners list.
  1599. session._signalingLayer.updateSsrcOwnersOnLeave(id);
  1600. if (!FeatureFlags.isSsrcRewritingSupported()) {
  1601. // Remove the ssrcs from the remote description and renegotiate.
  1602. session.removeRemoteStreamsOnLeave(id);
  1603. }
  1604. }
  1605. tracksToBeRemoved.forEach(track => {
  1606. if (FeatureFlags.isSsrcRewritingSupported()) {
  1607. track.setSourceName(null);
  1608. track.setOwner(null);
  1609. } else {
  1610. // Fire the event before renegotiation is done so that the thumbnails can be removed immediately.
  1611. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  1612. }
  1613. });
  1614. const participant = this.participants.get(id);
  1615. if (participant) {
  1616. this.participants.delete(id);
  1617. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant, reason);
  1618. }
  1619. if (this.room !== null) { // Skip if we have left the room already.
  1620. this._maybeStartOrStopP2P(true /* triggered by user left event */);
  1621. this._maybeClearSITimeout();
  1622. }
  1623. };
  1624. /* eslint-disable max-params */
  1625. /**
  1626. * Designates an event indicating that we were kicked from the XMPP MUC.
  1627. * @param {boolean} isSelfPresence - whether it is for local participant
  1628. * or another participant.
  1629. * @param {string} actorId - the id of the participant who was initiator
  1630. * of the kick.
  1631. * @param {string?} kickedParticipantId - when it is not a kick for local participant,
  1632. * this is the id of the participant which was kicked.
  1633. * @param {string} reason - reason of the participant to kick
  1634. * @param {boolean?} isReplaceParticipant - whether this is a server initiated kick in order
  1635. * to replace it with a participant with same jwt.
  1636. */
  1637. JitsiConference.prototype.onMemberKicked = function(
  1638. isSelfPresence,
  1639. actorId,
  1640. kickedParticipantId,
  1641. reason,
  1642. isReplaceParticipant) {
  1643. // This check which be true when we kick someone else. With the introduction of lobby
  1644. // the ChatRoom KICKED event is now also emitted for ourselves (the kicker) so we want to
  1645. // avoid emitting an event where `undefined` kicked someone.
  1646. if (actorId === this.myUserId()) {
  1647. return;
  1648. }
  1649. const actorParticipant = this.participants.get(actorId);
  1650. if (isSelfPresence) {
  1651. this.leave().finally(() => this.xmpp.disconnect());
  1652. this.eventEmitter.emit(
  1653. JitsiConferenceEvents.KICKED, actorParticipant, reason, isReplaceParticipant);
  1654. return;
  1655. }
  1656. const kickedParticipant = this.participants.get(kickedParticipantId);
  1657. kickedParticipant.setIsReplaced(isReplaceParticipant);
  1658. this.eventEmitter.emit(
  1659. JitsiConferenceEvents.PARTICIPANT_KICKED, actorParticipant, kickedParticipant, reason);
  1660. };
  1661. /**
  1662. * Method called on local MUC role change.
  1663. * @param {string} role the name of new user's role as defined by XMPP MUC.
  1664. */
  1665. JitsiConference.prototype.onLocalRoleChanged = function(role) {
  1666. // Emit role changed for local JID
  1667. this.eventEmitter.emit(
  1668. JitsiConferenceEvents.USER_ROLE_CHANGED, this.myUserId(), role);
  1669. };
  1670. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  1671. const id = Strophe.getResourceFromJid(jid);
  1672. const participant = this.getParticipantById(id);
  1673. if (!participant) {
  1674. return;
  1675. }
  1676. participant.setRole(role);
  1677. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  1678. };
  1679. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  1680. const id = Strophe.getResourceFromJid(jid);
  1681. const participant = this.getParticipantById(id);
  1682. if (!participant) {
  1683. return;
  1684. }
  1685. if (participant._displayName === displayName) {
  1686. return;
  1687. }
  1688. participant._displayName = displayName;
  1689. this.eventEmitter.emit(
  1690. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1691. id,
  1692. displayName);
  1693. };
  1694. /**
  1695. * Notifies this JitsiConference that a JitsiRemoteTrack was added to the conference.
  1696. *
  1697. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this JitsiConference.
  1698. */
  1699. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  1700. if (track.isP2P && !this.isP2PActive()) {
  1701. logger.info('Trying to add remote P2P track, when not in P2P - IGNORED');
  1702. return;
  1703. } else if (!track.isP2P && this.isP2PActive()) {
  1704. logger.info('Trying to add remote JVB track, when in P2P - IGNORED');
  1705. return;
  1706. }
  1707. const id = track.getParticipantId();
  1708. const participant = this.getParticipantById(id);
  1709. // Add track to JitsiParticipant.
  1710. if (participant) {
  1711. participant._tracks.push(track);
  1712. } else {
  1713. logger.info(`Source signaling received before presence for ${id}`);
  1714. }
  1715. const emitter = this.eventEmitter;
  1716. track.addEventListener(
  1717. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  1718. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  1719. track.isAudioTrack() && track.addEventListener(
  1720. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1721. (audioLevel, tpc) => {
  1722. const activeTPC = this.getActivePeerConnection();
  1723. if (activeTPC === tpc) {
  1724. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  1725. }
  1726. }
  1727. );
  1728. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  1729. };
  1730. /**
  1731. * Callback called by the Jingle plugin when 'session-answer' is received.
  1732. * @param {JingleSessionPC} session the Jingle session for which an answer was
  1733. * received.
  1734. * @param {jQuery} answer a jQuery selector pointing to 'jingle' IQ element
  1735. */
  1736. // eslint-disable-next-line no-unused-vars
  1737. JitsiConference.prototype.onCallAccepted = function(session, answer) {
  1738. if (this.p2pJingleSession === session) {
  1739. logger.info('P2P setAnswer');
  1740. this.p2pJingleSession.setAnswer(answer);
  1741. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_STARTED, this.p2pJingleSession);
  1742. }
  1743. };
  1744. /**
  1745. * Callback called by the Jingle plugin when 'transport-info' is received.
  1746. * @param {JingleSessionPC} session the Jingle session for which the IQ was
  1747. * received
  1748. * @param {jQuery} transportInfo a jQuery selector pointing to 'jingle' IQ
  1749. * element
  1750. */
  1751. // eslint-disable-next-line no-unused-vars
  1752. JitsiConference.prototype.onTransportInfo = function(session, transportInfo) {
  1753. if (this.p2pJingleSession === session) {
  1754. logger.info('P2P addIceCandidates');
  1755. this.p2pJingleSession.addIceCandidates(transportInfo);
  1756. }
  1757. };
  1758. /**
  1759. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  1760. * the conference.
  1761. *
  1762. * @param {JitsiRemoteTrack} removedTrack
  1763. */
  1764. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  1765. this.getParticipants().forEach(participant => {
  1766. const tracks = participant.getTracks();
  1767. for (let i = 0; i < tracks.length; i++) {
  1768. if (tracks[i] === removedTrack) {
  1769. // Since the tracks have been compared and are
  1770. // considered equal the result of splice can be ignored.
  1771. participant._tracks.splice(i, 1);
  1772. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  1773. break;
  1774. }
  1775. }
  1776. }, this);
  1777. };
  1778. /**
  1779. * Handles an incoming call event for the P2P jingle session.
  1780. */
  1781. JitsiConference.prototype._onIncomingCallP2P = function(jingleSession, jingleOffer) {
  1782. let rejectReason;
  1783. const contentName = jingleOffer.find('>content').attr('name');
  1784. const peerUsesUnifiedPlan = contentName === '0' || contentName === '1';
  1785. // Reject P2P between endpoints that are not running in the same mode w.r.t to SDPs (plan-b and unified plan).
  1786. if (!peerUsesUnifiedPlan) {
  1787. rejectReason = {
  1788. reason: 'decline',
  1789. reasonDescription: 'P2P disabled',
  1790. errorMsg: 'P2P across two endpoints in different SDP modes is disabled'
  1791. };
  1792. } else if ((!this.isP2PEnabled() && !this.isP2PTestModeEnabled())
  1793. || (browser.isFirefox() && !this._firefoxP2pEnabled)) {
  1794. rejectReason = {
  1795. reason: 'decline',
  1796. reasonDescription: 'P2P disabled',
  1797. errorMsg: 'P2P mode disabled in the configuration or browser unsupported'
  1798. };
  1799. } else if (this.p2pJingleSession) {
  1800. // Reject incoming P2P call (already in progress)
  1801. rejectReason = {
  1802. reason: 'busy',
  1803. reasonDescription: 'P2P already in progress',
  1804. errorMsg: 'Duplicated P2P "session-initiate"'
  1805. };
  1806. } else if (!this._shouldBeInP2PMode()) {
  1807. rejectReason = {
  1808. reason: 'decline',
  1809. reasonDescription: 'P2P requirements not met',
  1810. errorMsg: 'Received P2P "session-initiate" when should not be in P2P mode'
  1811. };
  1812. Statistics.sendAnalytics(createJingleEvent(ACTION_P2P_DECLINED));
  1813. }
  1814. if (rejectReason) {
  1815. this._rejectIncomingCall(jingleSession, rejectReason);
  1816. } else {
  1817. this._acceptP2PIncomingCall(jingleSession, jingleOffer);
  1818. }
  1819. };
  1820. /**
  1821. * Handles an incoming call event.
  1822. */
  1823. JitsiConference.prototype.onIncomingCall = function(jingleSession, jingleOffer, now) {
  1824. // Handle incoming P2P call
  1825. if (jingleSession.isP2P) {
  1826. this._onIncomingCallP2P(jingleSession, jingleOffer);
  1827. } else {
  1828. if (!this.isFocus(jingleSession.remoteJid)) {
  1829. const description = 'Rejecting session-initiate from non-focus.';
  1830. this._rejectIncomingCall(
  1831. jingleSession, {
  1832. reason: 'security-error',
  1833. reasonDescription: description,
  1834. errorMsg: description
  1835. });
  1836. return;
  1837. }
  1838. this._acceptJvbIncomingCall(jingleSession, jingleOffer, now);
  1839. }
  1840. };
  1841. /**
  1842. * Accepts an incoming call event for the JVB jingle session.
  1843. */
  1844. JitsiConference.prototype._acceptJvbIncomingCall = function(jingleSession, jingleOffer, now) {
  1845. // Accept incoming call
  1846. this.jvbJingleSession = jingleSession;
  1847. this.room.connectionTimes['session.initiate'] = now;
  1848. this._sendConferenceJoinAnalyticsEvent();
  1849. if (this.wasStopped) {
  1850. Statistics.sendAnalyticsAndLog(createJingleEvent(ACTION_JINGLE_RESTART, { p2p: false }));
  1851. }
  1852. const serverRegion
  1853. = $(jingleOffer)
  1854. .find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]')
  1855. .attr('region');
  1856. this.eventEmitter.emit(JitsiConferenceEvents.SERVER_REGION_CHANGED, serverRegion);
  1857. this._maybeClearSITimeout();
  1858. Statistics.sendAnalytics(createJingleEvent(
  1859. ACTION_JINGLE_SI_RECEIVED,
  1860. {
  1861. p2p: false,
  1862. value: now
  1863. }));
  1864. try {
  1865. jingleSession.initialize(
  1866. this.room,
  1867. this.rtc,
  1868. this._signalingLayer,
  1869. {
  1870. ...this.options.config,
  1871. codecSettings: {
  1872. mediaType: MediaType.VIDEO,
  1873. codecList: this.codecSelection.getCodecPreferenceList('jvb')
  1874. },
  1875. enableInsertableStreams: this.isE2EEEnabled() || FeatureFlags.isRunInLiteModeEnabled()
  1876. });
  1877. } catch (error) {
  1878. logger.error(error);
  1879. return;
  1880. }
  1881. // Open a channel with the videobridge.
  1882. this._setBridgeChannel(jingleOffer, jingleSession.peerconnection);
  1883. const localTracks = this._getInitialLocalTracks();
  1884. try {
  1885. jingleSession.acceptOffer(
  1886. jingleOffer,
  1887. () => {
  1888. // If for any reason invite for the JVB session arrived after
  1889. // the P2P has been established already the media transfer needs
  1890. // to be turned off here.
  1891. if (this.isP2PActive() && this.jvbJingleSession) {
  1892. this._suspendMediaTransferForJvbConnection();
  1893. }
  1894. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_STARTED, jingleSession);
  1895. if (!this.isP2PActive()) {
  1896. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED, jingleSession);
  1897. }
  1898. },
  1899. error => {
  1900. logger.error('Failed to accept incoming Jingle session', error);
  1901. },
  1902. localTracks
  1903. );
  1904. // Set the capture fps for screenshare if it is set through the UI.
  1905. this._desktopSharingFrameRate
  1906. && jingleSession.peerconnection.setDesktopSharingFrameRate(this._desktopSharingFrameRate);
  1907. this.statistics.startRemoteStats(this.jvbJingleSession.peerconnection);
  1908. } catch (e) {
  1909. logger.error(e);
  1910. }
  1911. };
  1912. /**
  1913. * Sets the BridgeChannel.
  1914. *
  1915. * @param {jQuery} offerIq a jQuery selector pointing to the jingle element of
  1916. * the offer IQ which may carry the WebSocket URL for the 'websocket'
  1917. * BridgeChannel mode.
  1918. * @param {TraceablePeerConnection} pc the peer connection which will be used
  1919. * to listen for new WebRTC Data Channels (in the 'datachannel' mode).
  1920. */
  1921. JitsiConference.prototype._setBridgeChannel = function(offerIq, pc) {
  1922. const ignoreDomain = this.connection?.options?.bridgeChannel?.ignoreDomain;
  1923. const preferSctp = this.connection?.options?.bridgeChannel?.preferSctp ?? false;
  1924. const sctpOffered = $(offerIq).find('>content[name="data"]')
  1925. .first().length === 1;
  1926. let wsUrl = null;
  1927. logger.info(`SCTP: offered=${sctpOffered}, prefered=${preferSctp}`);
  1928. if (!(sctpOffered && preferSctp)) {
  1929. $(offerIq).find('>content>transport>web-socket')
  1930. .toArray()
  1931. .map(e => e.getAttribute('url'))
  1932. .forEach(url => {
  1933. if (!wsUrl && (!ignoreDomain || ignoreDomain !== new URL(url).hostname)) {
  1934. wsUrl = url;
  1935. logger.info(`Using colibri-ws url ${url}`);
  1936. } else if (!wsUrl) {
  1937. logger.info(`Ignoring colibri-ws url with domain ${ignoreDomain}`);
  1938. }
  1939. });
  1940. if (!wsUrl) {
  1941. const firstWsUrl = $(offerIq).find('>content>transport>web-socket')
  1942. .first();
  1943. if (firstWsUrl.length === 1) {
  1944. wsUrl = firstWsUrl[0].getAttribute('url');
  1945. logger.info(`Falling back to ${wsUrl}`);
  1946. }
  1947. }
  1948. }
  1949. if (wsUrl && !(sctpOffered && preferSctp)) {
  1950. // If the offer contains a websocket and we don't prefer SCTP use it.
  1951. this.rtc.initializeBridgeChannel(null, wsUrl);
  1952. } else if (sctpOffered) {
  1953. // Otherwise, fall back to an attempt to use SCTP.
  1954. this.rtc.initializeBridgeChannel(pc, null);
  1955. } else {
  1956. logger.warn('Neither SCTP nor a websocket is available. Will not initialize bridge channel.');
  1957. }
  1958. };
  1959. /**
  1960. * Rejects incoming Jingle call.
  1961. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1962. * @param {object} [options]
  1963. * @param {string} options.reason the name of the reason element as defined
  1964. * by Jingle
  1965. * @param {string} options.reasonDescription the reason description which will
  1966. * be included in Jingle 'session-terminate' message.
  1967. * @param {string} options.errorMsg an error message to be logged on global
  1968. * error handler
  1969. * @private
  1970. */
  1971. JitsiConference.prototype._rejectIncomingCall = function(jingleSession, options) {
  1972. if (options?.errorMsg) {
  1973. logger.warn(options.errorMsg);
  1974. }
  1975. // Terminate the jingle session with a reason
  1976. jingleSession.terminate(
  1977. null /* success callback => we don't care */,
  1978. error => {
  1979. logger.warn(
  1980. 'An error occurred while trying to terminate'
  1981. + ' invalid Jingle session', error);
  1982. }, {
  1983. reason: options && options.reason,
  1984. reasonDescription: options && options.reasonDescription,
  1985. sendSessionTerminate: true
  1986. });
  1987. };
  1988. /**
  1989. * Handles the call ended event.
  1990. * XXX is this due to the remote side terminating the Jingle session?
  1991. *
  1992. * @param {JingleSessionPC} jingleSession the jingle session which has been
  1993. * terminated.
  1994. * @param {String} reasonCondition the Jingle reason condition.
  1995. * @param {String|null} reasonText human readable reason text which may provide
  1996. * more details about why the call has been terminated.
  1997. */
  1998. JitsiConference.prototype.onCallEnded = function(jingleSession, reasonCondition, reasonText) {
  1999. logger.info(
  2000. `Call ended: ${reasonCondition} - ${reasonText} P2P ?${
  2001. jingleSession.isP2P}`);
  2002. if (jingleSession === this.jvbJingleSession) {
  2003. this.wasStopped = true;
  2004. Statistics.sendAnalytics(
  2005. createJingleEvent(ACTION_JINGLE_TERMINATE, { p2p: false }));
  2006. // Stop the stats
  2007. if (this.statistics) {
  2008. this.statistics.stopRemoteStats(this.jvbJingleSession.peerconnection);
  2009. }
  2010. // Current JVB JingleSession is no longer valid, so set it to null
  2011. this.jvbJingleSession = null;
  2012. // Let the RTC service do any cleanups
  2013. this.rtc.onCallEnded();
  2014. } else if (jingleSession === this.p2pJingleSession) {
  2015. const stopOptions = {};
  2016. if (reasonCondition === 'connectivity-error' && reasonText === 'ICE FAILED') {
  2017. // It can happen that the other peer detects ICE failed and terminates the session, before we get the event
  2018. // on our side. But we are able to parse the reason and mark it here.
  2019. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  2020. } else if (reasonCondition === 'success' && reasonText === 'restart') {
  2021. // When we are restarting media sessions we don't want to switch the tracks to the JVB just yet.
  2022. stopOptions.requestRestart = true;
  2023. }
  2024. this._stopP2PSession(stopOptions);
  2025. } else {
  2026. logger.error(
  2027. 'Received onCallEnded for invalid session',
  2028. jingleSession.sid,
  2029. jingleSession.remoteJid,
  2030. reasonCondition,
  2031. reasonText);
  2032. }
  2033. };
  2034. /**
  2035. * Handles the suspend detected event. Leaves the room and fires suspended.
  2036. * @param {JingleSessionPC} jingleSession
  2037. */
  2038. JitsiConference.prototype.onSuspendDetected = function(jingleSession) {
  2039. if (!jingleSession.isP2P) {
  2040. this.leave();
  2041. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  2042. }
  2043. };
  2044. JitsiConference.prototype.updateDTMFSupport = function() {
  2045. let somebodySupportsDTMF = false;
  2046. const participants = this.getParticipants();
  2047. // check if at least 1 participant supports DTMF
  2048. for (let i = 0; i < participants.length; i += 1) {
  2049. if (participants[i].supportsDTMF()) {
  2050. somebodySupportsDTMF = true;
  2051. break;
  2052. }
  2053. }
  2054. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  2055. this.somebodySupportsDTMF = somebodySupportsDTMF;
  2056. this.eventEmitter.emit(
  2057. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  2058. somebodySupportsDTMF);
  2059. }
  2060. };
  2061. /**
  2062. * Allows to check if there is at least one user in the conference
  2063. * that supports DTMF.
  2064. * @returns {boolean} true if somebody supports DTMF, false otherwise
  2065. */
  2066. JitsiConference.prototype.isDTMFSupported = function() {
  2067. return this.somebodySupportsDTMF;
  2068. };
  2069. /**
  2070. * Returns the local user's ID
  2071. * @return {string} local user's ID
  2072. */
  2073. JitsiConference.prototype.myUserId = function() {
  2074. return (
  2075. this.room && this.room.myroomjid
  2076. ? Strophe.getResourceFromJid(this.room.myroomjid)
  2077. : null);
  2078. };
  2079. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  2080. const peerConnection = this.getActivePeerConnection();
  2081. if (peerConnection) {
  2082. peerConnection.sendTones(tones, duration, pause);
  2083. } else {
  2084. logger.warn('cannot sendTones: no peer connection');
  2085. }
  2086. };
  2087. /**
  2088. * Starts recording the current conference.
  2089. *
  2090. * @param {Object} options - Configuration for the recording. See
  2091. * {@link Chatroom#startRecording} for more info.
  2092. * @returns {Promise} See {@link Chatroom#startRecording} for more info.
  2093. */
  2094. JitsiConference.prototype.startRecording = function(options) {
  2095. if (this.room) {
  2096. return this.recordingManager.startRecording(options);
  2097. }
  2098. return Promise.reject(new Error('The conference is not created yet!'));
  2099. };
  2100. /**
  2101. * Stop a recording session.
  2102. *
  2103. * @param {string} sessionID - The ID of the recording session that
  2104. * should be stopped.
  2105. * @returns {Promise} See {@link Chatroom#stopRecording} for more info.
  2106. */
  2107. JitsiConference.prototype.stopRecording = function(sessionID) {
  2108. if (this.room) {
  2109. return this.recordingManager.stopRecording(sessionID);
  2110. }
  2111. return Promise.reject(new Error('The conference is not created yet!'));
  2112. };
  2113. /**
  2114. * Returns true if the SIP calls are supported and false otherwise
  2115. */
  2116. JitsiConference.prototype.isSIPCallingSupported = function() {
  2117. return this.room?.xmpp?.moderator?.isSipGatewayEnabled() ?? false;
  2118. };
  2119. /**
  2120. * Dials a number.
  2121. * @param number the number
  2122. */
  2123. JitsiConference.prototype.dial = function(number) {
  2124. if (this.room) {
  2125. return this.room.dial(number);
  2126. }
  2127. return Promise.reject(new Error('The conference is not created yet!'));
  2128. };
  2129. /**
  2130. * Hangup an existing call
  2131. */
  2132. JitsiConference.prototype.hangup = function() {
  2133. if (this.room) {
  2134. return this.room.hangup();
  2135. }
  2136. return Promise.resolve();
  2137. };
  2138. /**
  2139. * Returns the phone number for joining the conference.
  2140. */
  2141. JitsiConference.prototype.getPhoneNumber = function() {
  2142. if (this.room) {
  2143. return this.room.getPhoneNumber();
  2144. }
  2145. return null;
  2146. };
  2147. /**
  2148. * Returns the pin for joining the conference with phone.
  2149. */
  2150. JitsiConference.prototype.getPhonePin = function() {
  2151. if (this.room) {
  2152. return this.room.getPhonePin();
  2153. }
  2154. return null;
  2155. };
  2156. /**
  2157. * Returns the meeting unique ID if any.
  2158. *
  2159. * @returns {string|undefined}
  2160. */
  2161. JitsiConference.prototype.getMeetingUniqueId = function() {
  2162. if (this.room) {
  2163. return this.room.getMeetingId();
  2164. }
  2165. };
  2166. /**
  2167. * Will return P2P or JVB <tt>TraceablePeerConnection</tt> depending on
  2168. * which connection is currently active.
  2169. *
  2170. * @return {TraceablePeerConnection|null} null if there isn't any active
  2171. * <tt>TraceablePeerConnection</tt> currently available.
  2172. * @public (FIXME how to make package local ?)
  2173. */
  2174. JitsiConference.prototype.getActivePeerConnection = function() {
  2175. const session = this.isP2PActive() ? this.p2pJingleSession : this.jvbJingleSession;
  2176. return session ? session.peerconnection : null;
  2177. };
  2178. /**
  2179. * Returns the connection state for the current room. Its ice connection state
  2180. * for its session.
  2181. * NOTE that "completed" ICE state which can appear on the P2P connection will
  2182. * be converted to "connected".
  2183. * @return {string|null} ICE state name or <tt>null</tt> if there is no active
  2184. * peer connection at this time.
  2185. */
  2186. JitsiConference.prototype.getConnectionState = function() {
  2187. const peerConnection = this.getActivePeerConnection();
  2188. return peerConnection ? peerConnection.getConnectionState() : null;
  2189. };
  2190. /**
  2191. * Make all new participants mute their audio/video on join.
  2192. * @param policy {Object} object with 2 boolean properties for video and audio:
  2193. * @param {boolean} audio if audio should be muted.
  2194. * @param {boolean} video if video should be muted.
  2195. */
  2196. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  2197. if (!this.isModerator()) {
  2198. logger.warn(`Failed to set start muted policy, ${this.room ? '' : 'not in a room, '}${
  2199. this.isModerator() ? '' : 'participant is not a moderator'}`);
  2200. return;
  2201. }
  2202. // Do not apply the startMutedPolicy locally on the moderator, the moderator should join with available local
  2203. // sources and the policy needs to be applied only on users that join the call after.
  2204. // this.startMutedPolicy = policy;
  2205. this.room.addOrReplaceInPresence('startmuted', {
  2206. attributes: {
  2207. audio: policy.audio,
  2208. video: policy.video,
  2209. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  2210. }
  2211. }) && this.room.sendPresence();
  2212. };
  2213. /**
  2214. * Returns current start muted policy
  2215. * @returns {Object} with 2 properties - audio and video.
  2216. */
  2217. JitsiConference.prototype.getStartMutedPolicy = function() {
  2218. return this.startMutedPolicy;
  2219. };
  2220. /**
  2221. * Check if audio is muted on join.
  2222. */
  2223. JitsiConference.prototype.isStartAudioMuted = function() {
  2224. return this.startAudioMuted;
  2225. };
  2226. /**
  2227. * Check if video is muted on join.
  2228. */
  2229. JitsiConference.prototype.isStartVideoMuted = function() {
  2230. return this.startVideoMuted;
  2231. };
  2232. /**
  2233. * Returns measured connectionTimes.
  2234. */
  2235. JitsiConference.prototype.getConnectionTimes = function() {
  2236. return this.room.connectionTimes;
  2237. };
  2238. /**
  2239. * Sets a property for the local participant.
  2240. */
  2241. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  2242. this.sendCommand(`jitsi_participant_${name}`, { value });
  2243. };
  2244. /**
  2245. * Removes a property for the local participant and sends the updated presence.
  2246. */
  2247. JitsiConference.prototype.removeLocalParticipantProperty = function(name) {
  2248. this.removeCommand(`jitsi_participant_${name}`);
  2249. this.room.sendPresence();
  2250. };
  2251. /**
  2252. * Gets a local participant property.
  2253. *
  2254. * @return value of the local participant property if the tagName exists in the
  2255. * list of properties, otherwise returns undefined.
  2256. */
  2257. JitsiConference.prototype.getLocalParticipantProperty = function(name) {
  2258. const property = this.room.presMap.nodes.find(prop =>
  2259. prop.tagName === `jitsi_participant_${name}`
  2260. );
  2261. return property ? property.value : undefined;
  2262. };
  2263. /**
  2264. * Sends the given feedback if enabled.
  2265. *
  2266. * @param overallFeedback an integer between 1 and 5 indicating the
  2267. * user feedback
  2268. * @param detailedFeedback detailed feedback from the user. Not yet used
  2269. * @returns {Promise} Resolves if feedback is submitted successfully.
  2270. */
  2271. JitsiConference.prototype.sendFeedback = function(overallFeedback, detailedFeedback) {
  2272. return this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  2273. };
  2274. /**
  2275. * @returns false, since callstats in not supported anymore.
  2276. * @deprecated
  2277. */
  2278. JitsiConference.prototype.isCallstatsEnabled = function() {
  2279. logger.warn('Callstats is no longer supported');
  2280. return false;
  2281. };
  2282. /**
  2283. * Finds the SSRC of a given track
  2284. *
  2285. * @param track
  2286. * @returns {number|undefined} the SSRC of the specificed track, otherwise undefined.
  2287. */
  2288. JitsiConference.prototype.getSsrcByTrack = function(track) {
  2289. return track.isLocal() ? this.getActivePeerConnection()?.getLocalSSRC(track) : track.getSSRC();
  2290. };
  2291. /**
  2292. * This is a no-op since callstats is no longer supported.
  2293. */
  2294. // eslint-disable-next-line no-empty-function
  2295. JitsiConference.prototype.sendApplicationLog = function() { };
  2296. /**
  2297. * Checks if the user identified by given <tt>mucJid</tt> is the conference focus.
  2298. * @param mucJid the full MUC address of the user to be checked.
  2299. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  2300. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  2301. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  2302. */
  2303. JitsiConference.prototype.isFocus = function(mucJid) {
  2304. return this.room ? this.room.isFocus(mucJid) : null;
  2305. };
  2306. /**
  2307. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  2308. */
  2309. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  2310. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  2311. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  2312. };
  2313. /**
  2314. * Sends a message via the data channel.
  2315. * @param to {string} the id of the endpoint that should receive the message.
  2316. * If "" the message will be sent to all participants.
  2317. * @param payload {object} the payload of the message.
  2318. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2319. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2320. */
  2321. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  2322. this.rtc.sendChannelMessage(to, payload);
  2323. };
  2324. /**
  2325. * Sends local stats via the bridge channel which then forwards to other endpoints selectively.
  2326. * @param {Object} payload The payload of the message.
  2327. * @throws NetworkError/InvalidStateError/Error if the operation fails or if there is no data channel created.
  2328. */
  2329. JitsiConference.prototype.sendEndpointStatsMessage = function(payload) {
  2330. this.rtc.sendEndpointStatsMessage(payload);
  2331. };
  2332. /**
  2333. * Sends a broadcast message via the data channel.
  2334. * @param payload {object} the payload of the message.
  2335. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2336. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2337. */
  2338. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  2339. this.sendEndpointMessage('', payload);
  2340. };
  2341. /**
  2342. * Sends a message to a given endpoint (if 'to' is a non-empty string), or
  2343. * broadcasts it to all endpoints in the conference.
  2344. * @param {string} to The ID of the endpoint/participant which is to receive
  2345. * the message, or '' to broadcast the message to all endpoints in the
  2346. * conference.
  2347. * @param {string|object} message the message to send. If this is of type
  2348. * 'string' it will be sent as a chat message. If it is of type 'object', it
  2349. * will be encapsulated in a format recognized by jitsi-meet and converted to
  2350. * JSON before being sent.
  2351. * @param {boolean} sendThroughVideobridge Whether to send the message through
  2352. * jitsi-videobridge (via the COLIBRI data channel or web socket), or through
  2353. * the XMPP MUC. Currently only objects can be sent through jitsi-videobridge.
  2354. */
  2355. JitsiConference.prototype.sendMessage = function(message, to = '', sendThroughVideobridge = false) {
  2356. const messageType = typeof message;
  2357. // Through videobridge we support only objects. Through XMPP we support
  2358. // objects (encapsulated in a specific JSON format) and strings (i.e.
  2359. // regular chat messages).
  2360. if (messageType !== 'object'
  2361. && (sendThroughVideobridge || messageType !== 'string')) {
  2362. logger.error(`Can not send a message of type ${messageType}`);
  2363. return;
  2364. }
  2365. if (sendThroughVideobridge) {
  2366. this.sendEndpointMessage(to, message);
  2367. } else {
  2368. let messageToSend = message;
  2369. // Name of packet extension of message stanza to send the required
  2370. // message in.
  2371. let elementName = 'body';
  2372. if (messageType === 'object') {
  2373. elementName = 'json-message';
  2374. // Mark as valid JSON message if not already
  2375. if (!messageToSend.hasOwnProperty(JITSI_MEET_MUC_TYPE)) {
  2376. messageToSend[JITSI_MEET_MUC_TYPE] = '';
  2377. }
  2378. try {
  2379. messageToSend = JSON.stringify(messageToSend);
  2380. } catch (e) {
  2381. logger.error('Can not send a message, stringify failed: ', e);
  2382. return;
  2383. }
  2384. }
  2385. if (to) {
  2386. this.sendPrivateTextMessage(to, messageToSend, elementName);
  2387. } else {
  2388. // Broadcast
  2389. this.sendTextMessage(messageToSend, elementName);
  2390. }
  2391. }
  2392. };
  2393. JitsiConference.prototype.isConnectionInterrupted = function() {
  2394. return this.isP2PActive()
  2395. ? this.isP2PConnectionInterrupted : this.isJvbConnectionInterrupted;
  2396. };
  2397. /**
  2398. * Handles {@link XMPPEvents.CONNECTION_RESTARTED} event. This happens when the bridge goes down
  2399. * and Jicofo moves conferences away to a different bridge.
  2400. * @param {JingleSessionPC} session
  2401. * @private
  2402. */
  2403. JitsiConference.prototype._onConferenceRestarted = function(session) {
  2404. if (!session.isP2P && this.options.config.enableForcedReload) {
  2405. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONFERENCE_RESTARTED);
  2406. }
  2407. };
  2408. /**
  2409. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  2410. * @param {JingleSessionPC} session
  2411. * @private
  2412. */
  2413. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  2414. if (session.isP2P) {
  2415. this.isP2PConnectionInterrupted = true;
  2416. } else {
  2417. this.isJvbConnectionInterrupted = true;
  2418. }
  2419. if (session.isP2P === this.isP2PActive()) {
  2420. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  2421. }
  2422. };
  2423. /**
  2424. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  2425. * @param {JingleSessionPC} session
  2426. * @private
  2427. */
  2428. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  2429. // We do nothing for the JVB connection, because it's up to the Jicofo to
  2430. // eventually come up with the new offer (at least for the time being).
  2431. if (session.isP2P) {
  2432. // Add p2pFailed property to analytics to distinguish, between "good"
  2433. // and "bad" connection
  2434. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  2435. if (this.p2pJingleSession) {
  2436. Statistics.sendAnalyticsAndLog(
  2437. createP2PEvent(
  2438. ACTION_P2P_FAILED,
  2439. {
  2440. initiator: this.p2pJingleSession.isInitiator
  2441. }));
  2442. }
  2443. this._stopP2PSession({
  2444. reason: 'connectivity-error',
  2445. reasonDescription: 'ICE FAILED'
  2446. });
  2447. } else if (session && this.jvbJingleSession === session) {
  2448. this._delayedIceFailed = new IceFailedHandling(this);
  2449. this._delayedIceFailed.start(session);
  2450. }
  2451. };
  2452. /**
  2453. * Handles {@link XMPPEvents.CONNECTION_RESTORED}
  2454. * @param {JingleSessionPC} session
  2455. * @private
  2456. */
  2457. JitsiConference.prototype._onIceConnectionRestored = function(session) {
  2458. if (session.isP2P) {
  2459. this.isP2PConnectionInterrupted = false;
  2460. } else {
  2461. this.isJvbConnectionInterrupted = false;
  2462. this._delayedIceFailed && this._delayedIceFailed.cancel();
  2463. }
  2464. if (session.isP2P === this.isP2PActive()) {
  2465. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  2466. }
  2467. };
  2468. /**
  2469. * Accept incoming P2P Jingle call.
  2470. * @param {JingleSessionPC} jingleSession the session instance
  2471. * @param {jQuery} jingleOffer a jQuery selector pointing to 'jingle' IQ element
  2472. * @private
  2473. */
  2474. JitsiConference.prototype._acceptP2PIncomingCall = function(jingleSession, jingleOffer) {
  2475. this.isP2PConnectionInterrupted = false;
  2476. // Accept the offer
  2477. this.p2pJingleSession = jingleSession;
  2478. this._sendConferenceJoinAnalyticsEvent();
  2479. this.p2pJingleSession.initialize(
  2480. this.room,
  2481. this.rtc,
  2482. this._signalingLayer,
  2483. {
  2484. ...this.options.config,
  2485. codecSettings: {
  2486. mediaType: MediaType.VIDEO,
  2487. codecList: this.codecSelection.getCodecPreferenceList('p2p')
  2488. },
  2489. enableInsertableStreams: this.isE2EEEnabled() || FeatureFlags.isRunInLiteModeEnabled()
  2490. });
  2491. const localTracks = this._getInitialLocalTracks();
  2492. this.p2pJingleSession.acceptOffer(
  2493. jingleOffer,
  2494. () => {
  2495. logger.debug('Got RESULT for P2P "session-accept"');
  2496. this.eventEmitter.emit(
  2497. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  2498. jingleSession);
  2499. },
  2500. error => {
  2501. logger.error(
  2502. 'Failed to accept incoming P2P Jingle session', error);
  2503. },
  2504. localTracks);
  2505. };
  2506. /**
  2507. * Adds remote tracks to the conference associated with the JVB session.
  2508. * @private
  2509. */
  2510. JitsiConference.prototype._addRemoteJVBTracks = function() {
  2511. this._addRemoteTracks('JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2512. };
  2513. /**
  2514. * Adds remote tracks to the conference associated with the P2P session.
  2515. * @private
  2516. */
  2517. JitsiConference.prototype._addRemoteP2PTracks = function() {
  2518. this._addRemoteTracks('P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2519. };
  2520. /**
  2521. * Generates fake "remote track added" events for given Jingle session.
  2522. * @param {string} logName the session's nickname which will appear in log messages.
  2523. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be added
  2524. * @private
  2525. */
  2526. JitsiConference.prototype._addRemoteTracks = function(logName, remoteTracks) {
  2527. for (const track of remoteTracks) {
  2528. // There will be orphan (with no owner) tracks when ssrc-rewriting is enabled and all of them need to be addded
  2529. // back to the conference.
  2530. if (FeatureFlags.isSsrcRewritingSupported() || this.participants.has(track.ownerEndpointId)) {
  2531. logger.info(`Adding remote ${logName} track: ${track}`);
  2532. this.onRemoteTrackAdded(track);
  2533. }
  2534. }
  2535. };
  2536. /**
  2537. * Called when {@link XMPPEvents.CONNECTION_ESTABLISHED} event is
  2538. * triggered for a {@link JingleSessionPC}. Switches the conference to use
  2539. * the P2P connection if the event comes from the P2P session.
  2540. * @param {JingleSessionPC} jingleSession the session instance.
  2541. * @private
  2542. */
  2543. JitsiConference.prototype._onIceConnectionEstablished = function(jingleSession) {
  2544. if (this.p2pJingleSession !== null) {
  2545. // store the establishment time of the p2p session as a field of the
  2546. // JitsiConference because the p2pJingleSession might get disposed (thus
  2547. // the value is lost).
  2548. this.p2pEstablishmentDuration
  2549. = this.p2pJingleSession.establishmentDuration;
  2550. }
  2551. if (this.jvbJingleSession !== null) {
  2552. this.jvbEstablishmentDuration
  2553. = this.jvbJingleSession.establishmentDuration;
  2554. }
  2555. let done = false;
  2556. // We don't care about the JVB case, there's nothing to be done
  2557. if (!jingleSession.isP2P) {
  2558. done = true;
  2559. } else if (this.p2pJingleSession !== jingleSession) {
  2560. logger.error('CONNECTION_ESTABLISHED - wrong P2P session instance ?!');
  2561. done = true;
  2562. }
  2563. if (!isNaN(this.p2pEstablishmentDuration)
  2564. && !isNaN(this.jvbEstablishmentDuration)) {
  2565. const establishmentDurationDiff
  2566. = this.p2pEstablishmentDuration - this.jvbEstablishmentDuration;
  2567. Statistics.sendAnalytics(
  2568. ICE_ESTABLISHMENT_DURATION_DIFF,
  2569. { value: establishmentDurationDiff });
  2570. }
  2571. if (jingleSession.isP2P === this.isP2PActive()) {
  2572. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_ESTABLISHED);
  2573. }
  2574. if (done) {
  2575. return;
  2576. }
  2577. // Update P2P status and emit events
  2578. this._setP2PStatus(true);
  2579. // Remove remote tracks
  2580. if (this.jvbJingleSession) {
  2581. this._removeRemoteJVBTracks();
  2582. } else {
  2583. logger.info('Not removing remote JVB tracks - no session yet');
  2584. }
  2585. this._addRemoteP2PTracks();
  2586. // Stop media transfer over the JVB connection
  2587. if (this.jvbJingleSession) {
  2588. this._suspendMediaTransferForJvbConnection();
  2589. }
  2590. logger.info('Starting remote stats with p2p connection');
  2591. this.statistics.startRemoteStats(this.p2pJingleSession.peerconnection);
  2592. Statistics.sendAnalyticsAndLog(
  2593. createP2PEvent(
  2594. ACTION_P2P_ESTABLISHED,
  2595. {
  2596. initiator: this.p2pJingleSession.isInitiator
  2597. }));
  2598. };
  2599. /**
  2600. * Called when the chat room reads a new list of properties from jicofo's
  2601. * presence. The properties may have changed, but they don't have to.
  2602. *
  2603. * @param {Object} properties - The properties keyed by the property name
  2604. * ('key').
  2605. * @private
  2606. */
  2607. JitsiConference.prototype._updateProperties = function(properties = {}) {
  2608. const changed = !isEqual(properties, this.properties);
  2609. this.properties = properties;
  2610. if (changed) {
  2611. this.eventEmitter.emit(JitsiConferenceEvents.PROPERTIES_CHANGED, this.properties);
  2612. const audioLimitReached = this.properties['audio-limit-reached'] === 'true';
  2613. const videoLimitReached = this.properties['video-limit-reached'] === 'true';
  2614. if (this._audioSenderLimitReached !== audioLimitReached) {
  2615. this._audioSenderLimitReached = audioLimitReached;
  2616. this.eventEmitter.emit(JitsiConferenceEvents.AUDIO_UNMUTE_PERMISSIONS_CHANGED, audioLimitReached);
  2617. logger.info(`Audio unmute permissions set by Jicofo to ${audioLimitReached}`);
  2618. }
  2619. if (this._videoSenderLimitReached !== videoLimitReached) {
  2620. this._videoSenderLimitReached = videoLimitReached;
  2621. this.eventEmitter.emit(JitsiConferenceEvents.VIDEO_UNMUTE_PERMISSIONS_CHANGED, videoLimitReached);
  2622. logger.info(`Video unmute permissions set by Jicofo to ${videoLimitReached}`);
  2623. }
  2624. // Some of the properties need to be added to analytics events.
  2625. const analyticsKeys = [
  2626. // The number of jitsi-videobridge instances currently used for the
  2627. // conference.
  2628. 'bridge-count'
  2629. ];
  2630. analyticsKeys.forEach(key => {
  2631. if (properties[key] !== undefined) {
  2632. Statistics.analytics.addPermanentProperties({
  2633. [key.replace('-', '_')]: properties[key]
  2634. });
  2635. }
  2636. });
  2637. const oldValue = this._hasVisitors;
  2638. this._hasVisitors = this.properties['visitor-count'] > 0;
  2639. oldValue !== this._hasVisitors && this._maybeStartOrStopP2P(true);
  2640. }
  2641. };
  2642. /**
  2643. * Gets a conference property with a given key.
  2644. *
  2645. * @param {string} key - The key.
  2646. * @returns {*} The value
  2647. */
  2648. JitsiConference.prototype.getProperty = function(key) {
  2649. return this.properties[key];
  2650. };
  2651. /**
  2652. * Clears the deferred start P2P task if it has been scheduled.
  2653. * @private
  2654. */
  2655. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  2656. if (this.deferredStartP2PTask) {
  2657. logger.info('Cleared deferred start P2P task');
  2658. clearTimeout(this.deferredStartP2PTask);
  2659. this.deferredStartP2PTask = null;
  2660. }
  2661. };
  2662. /**
  2663. * Removes from the conference remote tracks associated with the JVB
  2664. * connection.
  2665. * @private
  2666. */
  2667. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  2668. this._removeRemoteTracks(
  2669. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2670. };
  2671. /**
  2672. * Removes from the conference remote tracks associated with the P2P
  2673. * connection.
  2674. * @private
  2675. */
  2676. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  2677. this._removeRemoteTracks(
  2678. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2679. };
  2680. /**
  2681. * Generates fake "remote track removed" events for given Jingle session.
  2682. * @param {string} sessionNickname the session's nickname which will appear in
  2683. * log messages.
  2684. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  2685. * @private
  2686. */
  2687. JitsiConference.prototype._removeRemoteTracks = function(sessionNickname, remoteTracks) {
  2688. for (const track of remoteTracks) {
  2689. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  2690. this.onRemoteTrackRemoved(track);
  2691. }
  2692. };
  2693. /**
  2694. * Resumes media transfer over the JVB connection.
  2695. * @private
  2696. */
  2697. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  2698. logger.info('Resuming media transfer over the JVB connection...');
  2699. this.jvbJingleSession.setMediaTransferActive(true)
  2700. .then(() => {
  2701. logger.info('Resumed media transfer over the JVB connection!');
  2702. })
  2703. .catch(error => {
  2704. logger.error('Failed to resume media transfer over the JVB connection:', error);
  2705. });
  2706. };
  2707. /**
  2708. * Sets new P2P status and updates some events/states hijacked from
  2709. * the <tt>JitsiConference</tt>.
  2710. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  2711. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  2712. * @private
  2713. */
  2714. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  2715. if (this.p2p === newStatus) {
  2716. logger.debug(`Called _setP2PStatus with the same status: ${newStatus}`);
  2717. return;
  2718. }
  2719. this.p2p = newStatus;
  2720. if (newStatus) {
  2721. logger.info('Peer to peer connection established!');
  2722. // When we end up in a valid P2P session need to reset the properties
  2723. // in case they have persisted, after session with another peer.
  2724. Statistics.analytics.addPermanentProperties({
  2725. p2pFailed: false
  2726. });
  2727. // Sync up video transfer active in case p2pJingleSession not existed
  2728. // when the lastN value was being adjusted.
  2729. const isVideoActive = this.getLastN() !== 0;
  2730. this.p2pJingleSession.setP2pVideoTransferActive(isVideoActive)
  2731. .catch(error => {
  2732. logger.error(`Failed to sync up P2P video transfer status (${isVideoActive}), ${error}`);
  2733. });
  2734. } else {
  2735. logger.info('Peer to peer connection closed!');
  2736. }
  2737. // Clear dtmfManager, so that it can be recreated with new connection
  2738. this.dtmfManager = null;
  2739. // Update P2P status
  2740. this.eventEmitter.emit(
  2741. JitsiConferenceEvents.P2P_STATUS,
  2742. this,
  2743. this.p2p);
  2744. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED, this.getActiveMediaSession());
  2745. // Refresh connection interrupted/restored
  2746. this.eventEmitter.emit(
  2747. this.isConnectionInterrupted()
  2748. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  2749. : JitsiConferenceEvents.CONNECTION_RESTORED);
  2750. };
  2751. /**
  2752. * Starts new P2P session.
  2753. * @param {string} remoteJid the JID of the remote participant
  2754. * @private
  2755. */
  2756. JitsiConference.prototype._startP2PSession = function(remoteJid) {
  2757. this._maybeClearDeferredStartP2P();
  2758. if (this.p2pJingleSession) {
  2759. logger.error('P2P session already started!');
  2760. return;
  2761. }
  2762. this.isP2PConnectionInterrupted = false;
  2763. this.p2pJingleSession
  2764. = this.xmpp.connection.jingle.newP2PJingleSession(
  2765. this.room.myroomjid,
  2766. remoteJid);
  2767. logger.info(
  2768. 'Created new P2P JingleSession', this.room.myroomjid, remoteJid);
  2769. this._sendConferenceJoinAnalyticsEvent();
  2770. this.p2pJingleSession.initialize(
  2771. this.room,
  2772. this.rtc,
  2773. this._signalingLayer,
  2774. {
  2775. ...this.options.config,
  2776. codecSettings: {
  2777. mediaType: MediaType.VIDEO,
  2778. codecList: this.codecSelection.getCodecPreferenceList('p2p')
  2779. },
  2780. enableInsertableStreams: this.isE2EEEnabled() || FeatureFlags.isRunInLiteModeEnabled()
  2781. });
  2782. const localTracks = this.getLocalTracks();
  2783. this.p2pJingleSession.invite(localTracks);
  2784. };
  2785. /**
  2786. * Suspends media transfer over the JVB connection.
  2787. * @private
  2788. */
  2789. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  2790. logger.info('Suspending media transfer over the JVB connection...');
  2791. this.jvbJingleSession.setMediaTransferActive(false)
  2792. .then(() => {
  2793. logger.info('Suspended media transfer over the JVB connection !');
  2794. })
  2795. .catch(error => {
  2796. logger.error('Failed to suspend media transfer over the JVB connection:', error);
  2797. });
  2798. };
  2799. /**
  2800. * Method when called will decide whether it's the time to start or stop
  2801. * the P2P session.
  2802. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  2803. * originates from the user left event.
  2804. * @private
  2805. */
  2806. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  2807. if (!this.isP2PEnabled()
  2808. || this.isP2PTestModeEnabled()
  2809. || (browser.isFirefox() && !this._firefoxP2pEnabled)
  2810. || this.isE2EEEnabled()) {
  2811. logger.info('Auto P2P disabled');
  2812. return;
  2813. }
  2814. const peers = this.getParticipants();
  2815. const peerCount = peers.length;
  2816. // FIXME 1 peer and it must *support* P2P switching
  2817. const shouldBeInP2P = this._shouldBeInP2PMode();
  2818. // Clear deferred "start P2P" task
  2819. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  2820. this._maybeClearDeferredStartP2P();
  2821. }
  2822. // Start peer to peer session
  2823. if (!this.p2pJingleSession && shouldBeInP2P) {
  2824. const peer = peerCount && peers[0];
  2825. const myId = this.myUserId();
  2826. const peersId = peer.getId();
  2827. if (myId > peersId) {
  2828. logger.debug(
  2829. 'I\'m the bigger peersId - '
  2830. + 'the other peer should start P2P', myId, peersId);
  2831. return;
  2832. } else if (myId === peersId) {
  2833. logger.error('The same IDs ? ', myId, peersId);
  2834. return;
  2835. }
  2836. const jid = peer.getJid();
  2837. if (userLeftEvent) {
  2838. if (this.deferredStartP2PTask) {
  2839. logger.error('Deferred start P2P task\'s been set already!');
  2840. return;
  2841. }
  2842. logger.info(
  2843. `Will start P2P with: ${jid} after ${
  2844. this.backToP2PDelay} seconds...`);
  2845. this.deferredStartP2PTask = setTimeout(
  2846. this._startP2PSession.bind(this, jid),
  2847. this.backToP2PDelay * 1000);
  2848. } else {
  2849. logger.info(`Will start P2P with: ${jid}`);
  2850. this._startP2PSession(jid);
  2851. }
  2852. } else if (this.p2pJingleSession && !shouldBeInP2P) {
  2853. logger.info(`Will stop P2P with: ${this.p2pJingleSession.remoteJid}`);
  2854. // Log that there will be a switch back to the JVB connection
  2855. if (this.p2pJingleSession.isInitiator && peerCount > 1) {
  2856. Statistics.sendAnalyticsAndLog(
  2857. createP2PEvent(ACTION_P2P_SWITCH_TO_JVB));
  2858. }
  2859. this._stopP2PSession();
  2860. }
  2861. };
  2862. /**
  2863. * Tells whether or not this conference should be currently in the P2P mode.
  2864. *
  2865. * @private
  2866. * @returns {boolean}
  2867. */
  2868. JitsiConference.prototype._shouldBeInP2PMode = function() {
  2869. const peers = this.getParticipants();
  2870. const peerCount = peers.length;
  2871. const hasBotPeer = peers.find(p => p.getBotType() === 'poltergeist' || p.hasFeature(FEATURE_JIGASI)) !== undefined;
  2872. const shouldBeInP2P = peerCount === 1 && !hasBotPeer && !this._hasVisitors;
  2873. logger.debug(`P2P? peerCount: ${peerCount}, hasBotPeer: ${hasBotPeer} => ${shouldBeInP2P}`);
  2874. return shouldBeInP2P;
  2875. };
  2876. /**
  2877. * Stops the current P2P session.
  2878. * @param {Object} options - Options for stopping P2P.
  2879. * @param {string} options.reason - One of the Jingle "reason" element
  2880. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  2881. * @param {string} options.reasonDescription - Text
  2882. * description that will be included in the session terminate message
  2883. * @param {boolean} requestRestart - Whether this is due to a session restart, in which case
  2884. * media will not be resumed on the JVB.
  2885. * @private
  2886. */
  2887. JitsiConference.prototype._stopP2PSession = function(options = {}) {
  2888. const {
  2889. reason = 'success',
  2890. reasonDescription = 'Turning off P2P session',
  2891. requestRestart = false
  2892. } = options;
  2893. if (!this.p2pJingleSession) {
  2894. logger.error('No P2P session to be stopped!');
  2895. return;
  2896. }
  2897. const wasP2PEstablished = this.isP2PActive();
  2898. // Swap remote tracks, but only if the P2P has been fully established
  2899. if (wasP2PEstablished) {
  2900. if (this.jvbJingleSession && !requestRestart) {
  2901. this._resumeMediaTransferForJvbConnection();
  2902. }
  2903. // Remove remote P2P tracks
  2904. this._removeRemoteP2PTracks();
  2905. }
  2906. // Stop P2P stats
  2907. logger.info('Stopping remote stats for P2P connection');
  2908. this.statistics.stopRemoteStats(this.p2pJingleSession.peerconnection);
  2909. this.p2pJingleSession.terminate(
  2910. () => {
  2911. logger.info('P2P session terminate RESULT');
  2912. },
  2913. error => {
  2914. // Because both initiator and responder are simultaneously
  2915. // terminating their JingleSessions in case of the 'to JVB switch'
  2916. // when 3rd participant joins, both will dispose their sessions and
  2917. // reply with 'item-not-found' (see strophe.jingle.js). We don't
  2918. // want to log this as an error since it's expected behaviour.
  2919. //
  2920. // We want them both to terminate, because in case of initiator's
  2921. // crash the responder would stay in P2P mode until ICE fails which
  2922. // could take up to 20 seconds.
  2923. //
  2924. // NOTE: whilst this is an error callback, 'success' as a reason is
  2925. // considered as graceful session terminate
  2926. // where both initiator and responder terminate their sessions
  2927. // simultaneously.
  2928. if (reason !== 'success') {
  2929. logger.error('An error occurred while trying to terminate P2P Jingle session', error);
  2930. }
  2931. }, {
  2932. reason,
  2933. reasonDescription,
  2934. sendSessionTerminate: this.room
  2935. && this.getParticipantById(
  2936. Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid))
  2937. });
  2938. this.p2pJingleSession = null;
  2939. // Update P2P status and other affected events/states
  2940. this._setP2PStatus(false);
  2941. if (wasP2PEstablished) {
  2942. // Add back remote JVB tracks
  2943. if (this.jvbJingleSession && !requestRestart) {
  2944. this._addRemoteJVBTracks();
  2945. } else {
  2946. logger.info('Not adding remote JVB tracks - no session yet');
  2947. }
  2948. }
  2949. };
  2950. /**
  2951. * Updates room presence if needed and send the packet in case of a modification.
  2952. * @param {JingleSessionPC} jingleSession the session firing the event, contains the peer connection which
  2953. * tracks we will check.
  2954. * @param {Object|null} ctx a context object we can distinguish multiple calls of the same pass of updating tracks.
  2955. */
  2956. JitsiConference.prototype._updateRoomPresence = function(jingleSession, ctx) {
  2957. if (!jingleSession) {
  2958. return;
  2959. }
  2960. // skips sending presence twice for the same pass of updating ssrcs
  2961. if (ctx) {
  2962. if (ctx.skip) {
  2963. return;
  2964. }
  2965. ctx.skip = true;
  2966. }
  2967. let presenceChanged = false;
  2968. let muteStatusChanged, videoTypeChanged;
  2969. const localTracks = jingleSession.peerconnection.getLocalTracks();
  2970. // Set presence for all the available local tracks.
  2971. for (const track of localTracks) {
  2972. const muted = track.isMuted();
  2973. muteStatusChanged = this._setTrackMuteStatus(track.getType(), track, muted);
  2974. muteStatusChanged && logger.debug(`Updating mute state of ${track} in presence to muted=${muted}`);
  2975. if (track.getType() === MediaType.VIDEO) {
  2976. videoTypeChanged = this._setNewVideoType(track);
  2977. videoTypeChanged && logger.debug(`Updating videoType in presence to ${track.getVideoType()}`);
  2978. }
  2979. presenceChanged = presenceChanged || muteStatusChanged || videoTypeChanged;
  2980. }
  2981. presenceChanged && this.room.sendPresence();
  2982. };
  2983. /**
  2984. * Checks whether or not the conference is currently in the peer to peer mode.
  2985. * Being in peer to peer mode means that the direct connection has been
  2986. * established and the P2P connection is being used for media transmission.
  2987. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  2988. */
  2989. JitsiConference.prototype.isP2PActive = function() {
  2990. return this.p2p;
  2991. };
  2992. /**
  2993. * Returns the current ICE state of the P2P connection.
  2994. * NOTE: method is used by the jitsi-meet-torture tests.
  2995. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  2996. * no P2P connection.
  2997. */
  2998. JitsiConference.prototype.getP2PConnectionState = function() {
  2999. if (this.isP2PActive()) {
  3000. return this.p2pJingleSession.peerconnection.getConnectionState();
  3001. }
  3002. return null;
  3003. };
  3004. /**
  3005. * Configures the peerconnection so that a given framre rate can be achieved for desktop share.
  3006. *
  3007. * @param {number} maxFps The capture framerate to be used for desktop tracks.
  3008. * @returns {boolean} true if the operation is successful, false otherwise.
  3009. */
  3010. JitsiConference.prototype.setDesktopSharingFrameRate = function(maxFps) {
  3011. if (typeof maxFps !== 'number' || isNaN(maxFps)) {
  3012. logger.error(`Invalid value ${maxFps} specified for desktop capture frame rate`);
  3013. return false;
  3014. }
  3015. this._desktopSharingFrameRate = maxFps;
  3016. // Set capture fps for screenshare.
  3017. this.jvbJingleSession && this.jvbJingleSession.peerconnection.setDesktopSharingFrameRate(maxFps);
  3018. // Set the capture rate for desktop sharing.
  3019. this.rtc.setDesktopSharingFrameRate(maxFps);
  3020. return true;
  3021. };
  3022. /**
  3023. * Manually starts new P2P session (should be used only in the tests).
  3024. */
  3025. JitsiConference.prototype.startP2PSession = function() {
  3026. const peers = this.getParticipants();
  3027. // Start peer to peer session
  3028. if (peers.length === 1) {
  3029. const peerJid = peers[0].getJid();
  3030. this._startP2PSession(peerJid);
  3031. } else {
  3032. throw new Error(
  3033. 'There must be exactly 1 participant to start the P2P session !');
  3034. }
  3035. };
  3036. /**
  3037. * Manually stops the current P2P session (should be used only in the tests).
  3038. */
  3039. JitsiConference.prototype.stopP2PSession = function(options) {
  3040. this._stopP2PSession(options);
  3041. };
  3042. /**
  3043. * Get a summary of how long current participants have been the dominant speaker
  3044. * @returns {object}
  3045. */
  3046. JitsiConference.prototype.getSpeakerStats = function() {
  3047. return this.speakerStatsCollector.getStats();
  3048. };
  3049. /**
  3050. * Sends a face landmarks object to the xmpp server.
  3051. * @param {Object} payload
  3052. */
  3053. JitsiConference.prototype.sendFaceLandmarks = function(payload) {
  3054. if (payload.faceExpression) {
  3055. this.xmpp.sendFaceLandmarksEvent(this.room.roomjid, payload);
  3056. }
  3057. };
  3058. /**
  3059. * Sets the constraints for the video that is requested from the bridge.
  3060. *
  3061. * @param {Object} videoConstraints The constraints which are specified in the following format. The message updates
  3062. * the fields that are present and leaves the rest unchanged on the bridge. Therefore, any field that is not applicable
  3063. * anymore should be cleared by passing an empty object or list (whatever is applicable).
  3064. * {
  3065. * 'lastN': 20,
  3066. * 'selectedSources': ['A', 'B', 'C'],
  3067. * 'onStageSources': ['A'],
  3068. * 'defaultConstraints': { 'maxHeight': 180 },
  3069. * 'constraints': {
  3070. * 'A': { 'maxHeight': 720 }
  3071. * }
  3072. * }
  3073. * Where A, B and C are source-names of the remote tracks that are being requested from the bridge.
  3074. */
  3075. JitsiConference.prototype.setReceiverConstraints = function(videoConstraints) {
  3076. this.receiveVideoController.setReceiverConstraints(videoConstraints);
  3077. };
  3078. /**
  3079. * Sets the assumed bandwidth bps for the video that is requested from the bridge.
  3080. *
  3081. * @param {Number} assumedBandwidthBps - The bandwidth value expressed in bits per second.
  3082. */
  3083. JitsiConference.prototype.setAssumedBandwidthBps = function(assumedBandwidthBps) {
  3084. this.receiveVideoController.setAssumedBandwidthBps(assumedBandwidthBps);
  3085. };
  3086. /**
  3087. * Sets the maximum video size the local participant should receive from remote
  3088. * participants.
  3089. *
  3090. * @param {number} maxFrameHeight - the maximum frame height, in pixels,
  3091. * this receiver is willing to receive.
  3092. * @returns {void}
  3093. */
  3094. JitsiConference.prototype.setReceiverVideoConstraint = function(maxFrameHeight) {
  3095. this.receiveVideoController.setPreferredReceiveMaxFrameHeight(maxFrameHeight);
  3096. };
  3097. /**
  3098. * Sets the maximum video size the local participant should send to remote
  3099. * participants.
  3100. * @param {number} maxFrameHeight - The user preferred max frame height.
  3101. * @returns {Promise} promise that will be resolved when the operation is
  3102. * successful and rejected otherwise.
  3103. */
  3104. JitsiConference.prototype.setSenderVideoConstraint = function(maxFrameHeight) {
  3105. return this.sendVideoController.setPreferredSendMaxFrameHeight(maxFrameHeight);
  3106. };
  3107. /**
  3108. * Creates a video SIP GW session and returns it if service is enabled. Before
  3109. * creating a session one need to check whether video SIP GW service is
  3110. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  3111. * if there are available nodes to serve this request, after creating the
  3112. * session those nodes can be taken and the request about using the
  3113. * created session can fail.
  3114. *
  3115. * @param {string} sipAddress - The sip address to be used.
  3116. * @param {string} displayName - The display name to be used for this session.
  3117. * @returns {JitsiVideoSIPGWSession|Error} Returns null if conference is not
  3118. * initialised and there is no room.
  3119. */
  3120. JitsiConference.prototype.createVideoSIPGWSession = function(sipAddress, displayName) {
  3121. if (!this.room) {
  3122. return new Error(VideoSIPGWConstants.ERROR_NO_CONNECTION);
  3123. }
  3124. return this.videoSIPGWHandler
  3125. .createVideoSIPGWSession(sipAddress, displayName);
  3126. };
  3127. /**
  3128. * Sends a conference.join analytics event.
  3129. *
  3130. * @returns {void}
  3131. */
  3132. JitsiConference.prototype._sendConferenceJoinAnalyticsEvent = function() {
  3133. const meetingId = this.getMeetingUniqueId();
  3134. if (this._conferenceJoinAnalyticsEventSent || !meetingId || this.getActivePeerConnection() === null) {
  3135. return;
  3136. }
  3137. const conferenceConnectionTimes = this.getConnectionTimes();
  3138. const xmppConnectionTimes = this.connection.getConnectionTimes();
  3139. const gumStart = window.connectionTimes['firstObtainPermissions.start'];
  3140. const gumEnd = window.connectionTimes['firstObtainPermissions.end'];
  3141. const globalNSConnectionTimes = window.JitsiMeetJS?.app?.connectionTimes ?? {};
  3142. const connectionTimes = {
  3143. ...conferenceConnectionTimes,
  3144. ...xmppConnectionTimes,
  3145. ...globalNSConnectionTimes,
  3146. gumDuration: safeSubtract(gumEnd, gumStart),
  3147. xmppConnectingTime: safeSubtract(xmppConnectionTimes.connected, xmppConnectionTimes.connecting),
  3148. connectedToMUCJoinedTime: safeSubtract(
  3149. conferenceConnectionTimes['muc.joined'], xmppConnectionTimes.connected),
  3150. connectingToMUCJoinedTime: safeSubtract(
  3151. conferenceConnectionTimes['muc.joined'], xmppConnectionTimes.connecting),
  3152. numberOfParticipantsOnJoin: this._numberOfParticipantsOnJoin
  3153. };
  3154. Statistics.sendAnalytics(createConferenceEvent('joined', {
  3155. ...connectionTimes,
  3156. meetingId,
  3157. participantId: `${meetingId}.${this._statsCurrentId}`
  3158. }));
  3159. this._conferenceJoinAnalyticsEventSent = Date.now();
  3160. };
  3161. /**
  3162. * Sends conference.left analytics event.
  3163. * @private
  3164. */
  3165. JitsiConference.prototype._sendConferenceLeftAnalyticsEvent = function() {
  3166. const meetingId = this.getMeetingUniqueId();
  3167. if (!meetingId || !this._conferenceJoinAnalyticsEventSent) {
  3168. return;
  3169. }
  3170. Statistics.sendAnalytics(createConferenceEvent('left', {
  3171. meetingId,
  3172. participantId: `${meetingId}.${this._statsCurrentId}`,
  3173. stats: {
  3174. duration: Math.floor((Date.now() - this._conferenceJoinAnalyticsEventSent) / 1000),
  3175. perf: this.getPerformanceStats()
  3176. }
  3177. }));
  3178. };
  3179. /**
  3180. * Restarts all active media sessions.
  3181. *
  3182. * @returns {void}
  3183. */
  3184. JitsiConference.prototype._restartMediaSessions = function() {
  3185. if (this.p2pJingleSession) {
  3186. this._stopP2PSession({
  3187. reasonDescription: 'restart',
  3188. requestRestart: true
  3189. });
  3190. }
  3191. if (this.jvbJingleSession) {
  3192. this.jvbJingleSession.terminate(
  3193. null /* success callback => we don't care */,
  3194. error => {
  3195. logger.warn('An error occurred while trying to terminate the JVB session', error);
  3196. }, {
  3197. reason: 'success',
  3198. reasonDescription: 'restart required',
  3199. requestRestart: true,
  3200. sendSessionTerminate: true
  3201. });
  3202. }
  3203. this._maybeStartOrStopP2P(false);
  3204. };
  3205. /**
  3206. * Returns whether End-To-End encryption is enabled.
  3207. *
  3208. * @returns {boolean}
  3209. */
  3210. JitsiConference.prototype.isE2EEEnabled = function() {
  3211. return Boolean(this._e2eEncryption && this._e2eEncryption.isEnabled());
  3212. };
  3213. /**
  3214. * Returns whether End-To-End encryption is supported. Note that not all participants
  3215. * in the conference may support it.
  3216. *
  3217. * @returns {boolean}
  3218. */
  3219. JitsiConference.prototype.isE2EESupported = function() {
  3220. return E2EEncryption.isSupported(this.options.config);
  3221. };
  3222. /**
  3223. * Enables / disables End-to-End encryption.
  3224. *
  3225. * @param {boolean} enabled whether to enable E2EE or not.
  3226. * @returns {void}
  3227. */
  3228. JitsiConference.prototype.toggleE2EE = function(enabled) {
  3229. if (!this.isE2EESupported()) {
  3230. logger.warn('Cannot enable / disable E2EE: platform is not supported.');
  3231. return;
  3232. }
  3233. this._e2eEncryption.setEnabled(enabled);
  3234. };
  3235. /**
  3236. * Sets the key and index for End-to-End encryption.
  3237. *
  3238. * @param {CryptoKey} [keyInfo.encryptionKey] - encryption key.
  3239. * @param {Number} [keyInfo.index] - the index of the encryption key.
  3240. * @returns {void}
  3241. */
  3242. JitsiConference.prototype.setMediaEncryptionKey = function(keyInfo) {
  3243. this._e2eEncryption.setEncryptionKey(keyInfo);
  3244. };
  3245. /**
  3246. * Starts the participant verification process.
  3247. *
  3248. * @param {string} participantId The participant which will be marked as verified.
  3249. * @returns {void}
  3250. */
  3251. JitsiConference.prototype.startVerification = function(participantId) {
  3252. const participant = this.getParticipantById(participantId);
  3253. if (!participant) {
  3254. return;
  3255. }
  3256. this._e2eEncryption.startVerification(participant);
  3257. };
  3258. /**
  3259. * Marks the given participant as verified. After this is done, MAC verification will
  3260. * be performed and an event will be emitted with the result.
  3261. *
  3262. * @param {string} participantId The participant which will be marked as verified.
  3263. * @param {boolean} isVerified - whether the verification was succesfull.
  3264. * @returns {void}
  3265. */
  3266. JitsiConference.prototype.markParticipantVerified = function(participantId, isVerified) {
  3267. const participant = this.getParticipantById(participantId);
  3268. if (!participant) {
  3269. return;
  3270. }
  3271. this._e2eEncryption.markParticipantVerified(participant, isVerified);
  3272. };
  3273. /**
  3274. * Returns <tt>true</tt> if lobby support is enabled in the backend.
  3275. *
  3276. * @returns {boolean} whether lobby is supported in the backend.
  3277. */
  3278. JitsiConference.prototype.isLobbySupported = function() {
  3279. return Boolean(this.room && this.room.getLobby().isSupported());
  3280. };
  3281. /**
  3282. * Returns <tt>true</tt> if the room has members only enabled.
  3283. *
  3284. * @returns {boolean} whether conference room is members only.
  3285. */
  3286. JitsiConference.prototype.isMembersOnly = function() {
  3287. return Boolean(this.room && this.room.membersOnlyEnabled);
  3288. };
  3289. /**
  3290. * Enables lobby by moderators
  3291. *
  3292. * @returns {Promise} resolves when lobby room is joined or rejects with the error.
  3293. */
  3294. JitsiConference.prototype.enableLobby = function() {
  3295. if (this.room && this.isModerator()) {
  3296. return this.room.getLobby().enable();
  3297. }
  3298. return Promise.reject(
  3299. new Error('The conference not started or user is not moderator'));
  3300. };
  3301. /**
  3302. * Disabled lobby by moderators
  3303. *
  3304. * @returns {void}
  3305. */
  3306. JitsiConference.prototype.disableLobby = function() {
  3307. if (this.room && this.isModerator()) {
  3308. this.room.getLobby().disable();
  3309. } else {
  3310. logger.warn(`Failed to disable lobby, ${this.room ? '' : 'not in a room, '}${
  3311. this.isModerator() ? '' : 'participant is not a moderator'}`);
  3312. }
  3313. };
  3314. /**
  3315. * Joins the lobby room with display name and optional email or with a shared password to skip waiting.
  3316. *
  3317. * @param {string} displayName Display name should be set to show it to moderators.
  3318. * @param {string} email Optional email is used to present avatar to the moderator.
  3319. * @returns {Promise<never>}
  3320. */
  3321. JitsiConference.prototype.joinLobby = function(displayName, email) {
  3322. if (this.room) {
  3323. return this.room.getLobby().join(displayName, email);
  3324. }
  3325. return Promise.reject(new Error('The conference not started'));
  3326. };
  3327. /**
  3328. * Gets the local id for a participant in a lobby room.
  3329. * Returns undefined when current participant is not in the lobby room.
  3330. * This is used for lobby room private chat messages.
  3331. *
  3332. * @returns {string}
  3333. */
  3334. JitsiConference.prototype.myLobbyUserId = function() {
  3335. if (this.room) {
  3336. return this.room.getLobby().getLocalId();
  3337. }
  3338. };
  3339. /**
  3340. * Sends a message to a lobby room.
  3341. * When id is specified it sends a private message.
  3342. * Otherwise it sends the message to all moderators.
  3343. * @param {message} Object The message to send
  3344. * @param {string} id The participant id.
  3345. *
  3346. * @returns {void}
  3347. */
  3348. JitsiConference.prototype.sendLobbyMessage = function(message, id) {
  3349. if (this.room) {
  3350. if (id) {
  3351. return this.room.getLobby().sendPrivateMessage(id, message);
  3352. }
  3353. return this.room.getLobby().sendMessage(message);
  3354. }
  3355. };
  3356. /**
  3357. * Adds a message listener to the lobby room
  3358. * @param {Function} listener The listener function,
  3359. * called when a new message is received in the lobby room.
  3360. *
  3361. * @returns {Function} Handler returned to be able to remove it later.
  3362. */
  3363. JitsiConference.prototype.addLobbyMessageListener = function(listener) {
  3364. if (this.room) {
  3365. return this.room.getLobby().addMessageListener(listener);
  3366. }
  3367. };
  3368. /**
  3369. * Removes a message handler from the lobby room
  3370. * @param {Function} handler The handler function to remove.
  3371. *
  3372. * @returns {void}
  3373. */
  3374. JitsiConference.prototype.removeLobbyMessageHandler = function(handler) {
  3375. if (this.room) {
  3376. return this.room.getLobby().removeMessageHandler(handler);
  3377. }
  3378. };
  3379. /**
  3380. * Denies an occupant in the lobby room access to the conference.
  3381. * @param {string} id The participant id.
  3382. */
  3383. JitsiConference.prototype.lobbyDenyAccess = function(id) {
  3384. if (this.room) {
  3385. this.room.getLobby().denyAccess(id);
  3386. }
  3387. };
  3388. /**
  3389. * Approves the request to join the conference to a participant waiting in the lobby.
  3390. *
  3391. * @param {string} id The participant id.
  3392. */
  3393. JitsiConference.prototype.lobbyApproveAccess = function(id) {
  3394. if (this.room) {
  3395. this.room.getLobby().approveAccess(id);
  3396. }
  3397. };
  3398. /**
  3399. * Returns <tt>true</tt> if AV Moderation support is enabled in the backend.
  3400. *
  3401. * @returns {boolean} whether AV Moderation is supported in the backend.
  3402. */
  3403. JitsiConference.prototype.isAVModerationSupported = function() {
  3404. return Boolean(this.room && this.room.getAVModeration().isSupported());
  3405. };
  3406. /**
  3407. * Enables AV Moderation.
  3408. * @param {MediaType} mediaType "audio" or "video"
  3409. */
  3410. JitsiConference.prototype.enableAVModeration = function(mediaType) {
  3411. if (this.room && this.isModerator()
  3412. && (mediaType === MediaType.AUDIO || mediaType === MediaType.VIDEO)) {
  3413. this.room.getAVModeration().enable(true, mediaType);
  3414. } else {
  3415. logger.warn(`Failed to enable AV moderation, ${this.room ? '' : 'not in a room, '}${
  3416. this.isModerator() ? '' : 'participant is not a moderator, '}${
  3417. this.room && this.isModerator() ? 'wrong media type passed' : ''}`);
  3418. }
  3419. };
  3420. /**
  3421. * Disables AV Moderation.
  3422. * @param {MediaType} mediaType "audio" or "video"
  3423. */
  3424. JitsiConference.prototype.disableAVModeration = function(mediaType) {
  3425. if (this.room && this.isModerator()
  3426. && (mediaType === MediaType.AUDIO || mediaType === MediaType.VIDEO)) {
  3427. this.room.getAVModeration().enable(false, mediaType);
  3428. } else {
  3429. logger.warn(`Failed to disable AV moderation, ${this.room ? '' : 'not in a room, '}${
  3430. this.isModerator() ? '' : 'participant is not a moderator, '}${
  3431. this.room && this.isModerator() ? 'wrong media type passed' : ''}`);
  3432. }
  3433. };
  3434. /**
  3435. * Approve participant access to certain media, allows unmuting audio or video.
  3436. *
  3437. * @param {MediaType} mediaType "audio" or "video"
  3438. * @param id the id of the participant.
  3439. */
  3440. JitsiConference.prototype.avModerationApprove = function(mediaType, id) {
  3441. if (this.room && this.isModerator()
  3442. && (mediaType === MediaType.AUDIO || mediaType === MediaType.VIDEO)) {
  3443. const participant = this.getParticipantById(id);
  3444. if (!participant) {
  3445. return;
  3446. }
  3447. this.room.getAVModeration().approve(mediaType, participant.getJid());
  3448. } else {
  3449. logger.warn(`AV moderation approve skipped , ${this.room ? '' : 'not in a room, '}${
  3450. this.isModerator() ? '' : 'participant is not a moderator, '}${
  3451. this.room && this.isModerator() ? 'wrong media type passed' : ''}`);
  3452. }
  3453. };
  3454. /**
  3455. * Reject participant access to certain media, blocks unmuting audio or video.
  3456. *
  3457. * @param {MediaType} mediaType "audio" or "video"
  3458. * @param id the id of the participant.
  3459. */
  3460. JitsiConference.prototype.avModerationReject = function(mediaType, id) {
  3461. if (this.room && this.isModerator()
  3462. && (mediaType === MediaType.AUDIO || mediaType === MediaType.VIDEO)) {
  3463. const participant = this.getParticipantById(id);
  3464. if (!participant) {
  3465. return;
  3466. }
  3467. this.room.getAVModeration().reject(mediaType, participant.getJid());
  3468. } else {
  3469. logger.warn(`AV moderation reject skipped , ${this.room ? '' : 'not in a room, '}${
  3470. this.isModerator() ? '' : 'participant is not a moderator, '}${
  3471. this.room && this.isModerator() ? 'wrong media type passed' : ''}`);
  3472. }
  3473. };
  3474. /**
  3475. * Returns the breakout rooms manager object.
  3476. *
  3477. * @returns {Object} the breakout rooms manager.
  3478. */
  3479. JitsiConference.prototype.getBreakoutRooms = function() {
  3480. return this.room?.getBreakoutRooms();
  3481. };
  3482. /**
  3483. * Returns the metadata handler object.
  3484. *
  3485. * @returns {Object} the room metadata handler.
  3486. */
  3487. JitsiConference.prototype.getMetadataHandler = function() {
  3488. return this.room?.getMetadataHandler();
  3489. };