Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

JitsiConference.js 135KB

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