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

JitsiConference.js 139KB

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