Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

JitsiConference.js 136KB

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