You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiConference.js 139KB

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