您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiConference.js 136KB

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