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

JitsiConference.js 136KB

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