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

JitsiConference.js 138KB

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