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

JitsiConference.js 135KB

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