You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 110KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113
  1. /* global APP, JitsiMeetJS, config, interfaceConfig */
  2. import { jitsiLocalStorage } from '@jitsi/js-utils';
  3. import EventEmitter from 'events';
  4. import Logger from 'jitsi-meet-logger';
  5. import { openConnection } from './connection';
  6. import { ENDPOINT_TEXT_MESSAGE_NAME } from './modules/API/constants';
  7. import { AUDIO_ONLY_SCREEN_SHARE_NO_TRACK } from './modules/UI/UIErrors';
  8. import AuthHandler from './modules/UI/authentication/AuthHandler';
  9. import UIUtil from './modules/UI/util/UIUtil';
  10. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  11. import Recorder from './modules/recorder/Recorder';
  12. import { createTaskQueue } from './modules/util/helpers';
  13. import {
  14. createDeviceChangedEvent,
  15. createStartSilentEvent,
  16. createScreenSharingEvent,
  17. createTrackMutedEvent,
  18. sendAnalytics
  19. } from './react/features/analytics';
  20. import {
  21. maybeRedirectToWelcomePage,
  22. redirectToStaticPage,
  23. reloadWithStoredParams
  24. } from './react/features/app/actions';
  25. import {
  26. AVATAR_URL_COMMAND,
  27. EMAIL_COMMAND,
  28. authStatusChanged,
  29. commonUserJoinedHandling,
  30. commonUserLeftHandling,
  31. conferenceFailed,
  32. conferenceJoined,
  33. conferenceLeft,
  34. conferenceSubjectChanged,
  35. conferenceTimestampChanged,
  36. conferenceUniqueIdSet,
  37. conferenceWillJoin,
  38. conferenceWillLeave,
  39. dataChannelOpened,
  40. getConferenceOptions,
  41. kickedOut,
  42. lockStateChanged,
  43. onStartMutedPolicyChanged,
  44. p2pStatusChanged,
  45. sendLocalParticipant
  46. } from './react/features/base/conference';
  47. import { getReplaceParticipant } from './react/features/base/config/functions';
  48. import {
  49. checkAndNotifyForNewDevice,
  50. getAvailableDevices,
  51. getDefaultDeviceId,
  52. notifyCameraError,
  53. notifyMicError,
  54. setAudioOutputDeviceId,
  55. updateDeviceList
  56. } from './react/features/base/devices';
  57. import {
  58. browser,
  59. isFatalJitsiConnectionError,
  60. JitsiConferenceErrors,
  61. JitsiConferenceEvents,
  62. JitsiConnectionErrors,
  63. JitsiConnectionEvents,
  64. JitsiMediaDevicesEvents,
  65. JitsiParticipantConnectionStatus,
  66. JitsiTrackErrors,
  67. JitsiTrackEvents
  68. } from './react/features/base/lib-jitsi-meet';
  69. import {
  70. getStartWithAudioMuted,
  71. getStartWithVideoMuted,
  72. isVideoMutedByUser,
  73. MEDIA_TYPE,
  74. setAudioAvailable,
  75. setAudioMuted,
  76. setVideoAvailable,
  77. setVideoMuted
  78. } from './react/features/base/media';
  79. import {
  80. dominantSpeakerChanged,
  81. getLocalParticipant,
  82. getNormalizedDisplayName,
  83. getParticipantById,
  84. localParticipantConnectionStatusChanged,
  85. localParticipantRoleChanged,
  86. participantConnectionStatusChanged,
  87. participantKicked,
  88. participantMutedUs,
  89. participantPresenceChanged,
  90. participantRoleChanged,
  91. participantUpdated,
  92. updateRemoteParticipantFeatures
  93. } from './react/features/base/participants';
  94. import {
  95. getUserSelectedCameraDeviceId,
  96. updateSettings
  97. } from './react/features/base/settings';
  98. import {
  99. createLocalPresenterTrack,
  100. createLocalTracksF,
  101. destroyLocalTracks,
  102. getLocalJitsiAudioTrack,
  103. getLocalJitsiVideoTrack,
  104. getLocalTracks,
  105. isLocalCameraTrackMuted,
  106. isLocalTrackMuted,
  107. isUserInteractionRequiredForUnmute,
  108. replaceLocalTrack,
  109. trackAdded,
  110. trackRemoved
  111. } from './react/features/base/tracks';
  112. import { downloadJSON } from './react/features/base/util/downloadJSON';
  113. import { showDesktopPicker } from './react/features/desktop-picker';
  114. import { appendSuffix } from './react/features/display-name';
  115. import {
  116. maybeOpenFeedbackDialog,
  117. submitFeedback
  118. } from './react/features/feedback';
  119. import { showNotification } from './react/features/notifications';
  120. import { mediaPermissionPromptVisibilityChanged, toggleSlowGUMOverlay } from './react/features/overlay';
  121. import { suspendDetected } from './react/features/power-monitor';
  122. import {
  123. initPrejoin,
  124. isPrejoinPageEnabled,
  125. isPrejoinPageVisible,
  126. makePrecallTest
  127. } from './react/features/prejoin';
  128. import { disableReceiver, stopReceiver } from './react/features/remote-control';
  129. import { setScreenAudioShareState, isScreenAudioShared } from './react/features/screen-share/';
  130. import { toggleScreenshotCaptureEffect } from './react/features/screenshot-capture';
  131. import { AudioMixerEffect } from './react/features/stream-effects/audio-mixer/AudioMixerEffect';
  132. import { createPresenterEffect } from './react/features/stream-effects/presenter';
  133. import { createRnnoiseProcessor } from './react/features/stream-effects/rnnoise';
  134. import { endpointMessageReceived } from './react/features/subtitles';
  135. import UIEvents from './service/UI/UIEvents';
  136. const logger = Logger.getLogger(__filename);
  137. const eventEmitter = new EventEmitter();
  138. let room;
  139. let connection;
  140. /**
  141. * The promise is used when the prejoin screen is shown.
  142. * While the user configures the devices the connection can be made.
  143. *
  144. * @type {Promise<Object>}
  145. * @private
  146. */
  147. let _connectionPromise;
  148. /**
  149. * This promise is used for chaining mutePresenterVideo calls in order to avoid calling GUM multiple times if it takes
  150. * a while to finish.
  151. *
  152. * @type {Promise<void>}
  153. * @private
  154. */
  155. let _prevMutePresenterVideo = Promise.resolve();
  156. /*
  157. * Logic to open a desktop picker put on the window global for
  158. * lib-jitsi-meet to detect and invoke
  159. */
  160. window.JitsiMeetScreenObtainer = {
  161. openDesktopPicker(options, onSourceChoose) {
  162. APP.store.dispatch(showDesktopPicker(options, onSourceChoose));
  163. }
  164. };
  165. /**
  166. * Known custom conference commands.
  167. */
  168. const commands = {
  169. AVATAR_URL: AVATAR_URL_COMMAND,
  170. CUSTOM_ROLE: 'custom-role',
  171. EMAIL: EMAIL_COMMAND,
  172. ETHERPAD: 'etherpad'
  173. };
  174. /**
  175. * Open Connection. When authentication failed it shows auth dialog.
  176. * @param roomName the room name to use
  177. * @returns Promise<JitsiConnection>
  178. */
  179. function connect(roomName) {
  180. return openConnection({
  181. retry: true,
  182. roomName
  183. })
  184. .catch(err => {
  185. if (err === JitsiConnectionErrors.PASSWORD_REQUIRED) {
  186. APP.UI.notifyTokenAuthFailed();
  187. } else {
  188. APP.UI.notifyConnectionFailed(err);
  189. }
  190. throw err;
  191. });
  192. }
  193. /**
  194. * Share data to other users.
  195. * @param command the command
  196. * @param {string} value new value
  197. */
  198. function sendData(command, value) {
  199. if (!room) {
  200. return;
  201. }
  202. room.removeCommand(command);
  203. room.sendCommand(command, { value });
  204. }
  205. /**
  206. * Get user nickname by user id.
  207. * @param {string} id user id
  208. * @returns {string?} user nickname or undefined if user is unknown.
  209. */
  210. function getDisplayName(id) {
  211. const participant = getParticipantById(APP.store.getState(), id);
  212. return participant && participant.name;
  213. }
  214. /**
  215. * Mute or unmute local audio stream if it exists.
  216. * @param {boolean} muted - if audio stream should be muted or unmuted.
  217. */
  218. function muteLocalAudio(muted) {
  219. APP.store.dispatch(setAudioMuted(muted));
  220. }
  221. /**
  222. * Mute or unmute local video stream if it exists.
  223. * @param {boolean} muted if video stream should be muted or unmuted.
  224. *
  225. */
  226. function muteLocalVideo(muted) {
  227. APP.store.dispatch(setVideoMuted(muted));
  228. }
  229. /**
  230. * A queue for the async replaceLocalTrack action so that multiple audio
  231. * replacements cannot happen simultaneously. This solves the issue where
  232. * replaceLocalTrack is called multiple times with an oldTrack of null, causing
  233. * multiple local tracks of the same type to be used.
  234. *
  235. * @private
  236. * @type {Object}
  237. */
  238. const _replaceLocalAudioTrackQueue = createTaskQueue();
  239. /**
  240. * A task queue for replacement local video tracks. This separate queue exists
  241. * so video replacement is not blocked by audio replacement tasks in the queue
  242. * {@link _replaceLocalAudioTrackQueue}.
  243. *
  244. * @private
  245. * @type {Object}
  246. */
  247. const _replaceLocalVideoTrackQueue = createTaskQueue();
  248. /**
  249. *
  250. */
  251. class ConferenceConnector {
  252. /**
  253. *
  254. */
  255. constructor(resolve, reject) {
  256. this._resolve = resolve;
  257. this._reject = reject;
  258. this.reconnectTimeout = null;
  259. room.on(JitsiConferenceEvents.CONFERENCE_JOINED,
  260. this._handleConferenceJoined.bind(this));
  261. room.on(JitsiConferenceEvents.CONFERENCE_FAILED,
  262. this._onConferenceFailed.bind(this));
  263. }
  264. /**
  265. *
  266. */
  267. _handleConferenceFailed(err) {
  268. this._unsubscribe();
  269. this._reject(err);
  270. }
  271. /**
  272. *
  273. */
  274. _onConferenceFailed(err, ...params) {
  275. APP.store.dispatch(conferenceFailed(room, err, ...params));
  276. logger.error('CONFERENCE FAILED:', err, ...params);
  277. switch (err) {
  278. case JitsiConferenceErrors.NOT_ALLOWED_ERROR: {
  279. // let's show some auth not allowed page
  280. APP.store.dispatch(redirectToStaticPage('static/authError.html'));
  281. break;
  282. }
  283. // not enough rights to create conference
  284. case JitsiConferenceErrors.AUTHENTICATION_REQUIRED: {
  285. const replaceParticipant = getReplaceParticipant(APP.store.getState());
  286. // Schedule reconnect to check if someone else created the room.
  287. this.reconnectTimeout = setTimeout(() => {
  288. APP.store.dispatch(conferenceWillJoin(room));
  289. room.join(null, replaceParticipant);
  290. }, 5000);
  291. const { password }
  292. = APP.store.getState()['features/base/conference'];
  293. AuthHandler.requireAuth(room, password);
  294. break;
  295. }
  296. case JitsiConferenceErrors.RESERVATION_ERROR: {
  297. const [ code, msg ] = params;
  298. APP.UI.notifyReservationError(code, msg);
  299. break;
  300. }
  301. case JitsiConferenceErrors.GRACEFUL_SHUTDOWN:
  302. APP.UI.notifyGracefulShutdown();
  303. break;
  304. // FIXME FOCUS_DISCONNECTED is a confusing event name.
  305. // What really happens there is that the library is not ready yet,
  306. // because Jicofo is not available, but it is going to give it another
  307. // try.
  308. case JitsiConferenceErrors.FOCUS_DISCONNECTED: {
  309. const [ focus, retrySec ] = params;
  310. APP.UI.notifyFocusDisconnected(focus, retrySec);
  311. break;
  312. }
  313. case JitsiConferenceErrors.FOCUS_LEFT:
  314. case JitsiConferenceErrors.ICE_FAILED:
  315. case JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  316. case JitsiConferenceErrors.OFFER_ANSWER_FAILED:
  317. APP.store.dispatch(conferenceWillLeave(room));
  318. // FIXME the conference should be stopped by the library and not by
  319. // the app. Both the errors above are unrecoverable from the library
  320. // perspective.
  321. room.leave().then(() => connection.disconnect());
  322. break;
  323. case JitsiConferenceErrors.CONFERENCE_MAX_USERS:
  324. connection.disconnect();
  325. APP.UI.notifyMaxUsersLimitReached();
  326. break;
  327. case JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  328. APP.store.dispatch(reloadWithStoredParams());
  329. break;
  330. default:
  331. this._handleConferenceFailed(err, ...params);
  332. }
  333. }
  334. /**
  335. *
  336. */
  337. _unsubscribe() {
  338. room.off(
  339. JitsiConferenceEvents.CONFERENCE_JOINED,
  340. this._handleConferenceJoined);
  341. room.off(
  342. JitsiConferenceEvents.CONFERENCE_FAILED,
  343. this._onConferenceFailed);
  344. if (this.reconnectTimeout !== null) {
  345. clearTimeout(this.reconnectTimeout);
  346. }
  347. }
  348. /**
  349. *
  350. */
  351. _handleConferenceJoined() {
  352. this._unsubscribe();
  353. this._resolve();
  354. }
  355. /**
  356. *
  357. */
  358. connect() {
  359. const replaceParticipant = getReplaceParticipant(APP.store.getState());
  360. // the local storage overrides here and in connection.js can be used by jibri
  361. room.join(jitsiLocalStorage.getItem('xmpp_conference_password_override'), replaceParticipant);
  362. }
  363. }
  364. /**
  365. * Disconnects the connection.
  366. * @returns resolved Promise. We need this in order to make the Promise.all
  367. * call in hangup() to resolve when all operations are finished.
  368. */
  369. function disconnect() {
  370. const onDisconnected = () => {
  371. APP.API.notifyConferenceLeft(APP.conference.roomName);
  372. return Promise.resolve();
  373. };
  374. if (!connection) {
  375. return onDisconnected();
  376. }
  377. return connection.disconnect().then(onDisconnected, onDisconnected);
  378. }
  379. /**
  380. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  381. *
  382. * @param {JitsiConnectionError} error - The reported error.
  383. * @returns {void}
  384. * @private
  385. */
  386. function _connectionFailedHandler(error) {
  387. if (isFatalJitsiConnectionError(error)) {
  388. APP.connection.removeEventListener(
  389. JitsiConnectionEvents.CONNECTION_FAILED,
  390. _connectionFailedHandler);
  391. if (room) {
  392. APP.store.dispatch(conferenceWillLeave(room));
  393. room.leave();
  394. }
  395. }
  396. }
  397. export default {
  398. /**
  399. * Flag used to delay modification of the muted status of local media tracks
  400. * until those are created (or not, but at that point it's certain that
  401. * the tracks won't exist).
  402. */
  403. _localTracksInitialized: false,
  404. isSharingScreen: false,
  405. /**
  406. * The local audio track (if any).
  407. * FIXME tracks from redux store should be the single source of truth
  408. * @type {JitsiLocalTrack|null}
  409. */
  410. localAudio: null,
  411. /**
  412. * The local presenter video track (if any).
  413. * @type {JitsiLocalTrack|null}
  414. */
  415. localPresenterVideo: null,
  416. /**
  417. * The local video track (if any).
  418. * FIXME tracks from redux store should be the single source of truth, but
  419. * more refactoring is required around screen sharing ('localVideo' usages).
  420. * @type {JitsiLocalTrack|null}
  421. */
  422. localVideo: null,
  423. /**
  424. * Returns an object containing a promise which resolves with the created tracks &
  425. * the errors resulting from that process.
  426. *
  427. * @returns {Promise<JitsiLocalTrack[]>, Object}
  428. */
  429. createInitialLocalTracks(options = {}) {
  430. const errors = {};
  431. // Always get a handle on the audio input device so that we have statistics (such as "No audio input" or
  432. // "Are you trying to speak?" ) even if the user joins the conference muted.
  433. const initialDevices = config.disableInitialGUM ? [] : [ 'audio' ];
  434. const requestedAudio = !config.disableInitialGUM;
  435. let requestedVideo = false;
  436. if (!config.disableInitialGUM
  437. && !options.startWithVideoMuted
  438. && !options.startAudioOnly
  439. && !options.startScreenSharing) {
  440. initialDevices.push('video');
  441. requestedVideo = true;
  442. }
  443. if (!config.disableInitialGUM) {
  444. JitsiMeetJS.mediaDevices.addEventListener(
  445. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  446. browserName =>
  447. APP.store.dispatch(
  448. mediaPermissionPromptVisibilityChanged(true, browserName))
  449. );
  450. }
  451. JitsiMeetJS.mediaDevices.addEventListener(
  452. JitsiMediaDevicesEvents.SLOW_GET_USER_MEDIA,
  453. () => APP.store.dispatch(toggleSlowGUMOverlay(true))
  454. );
  455. let tryCreateLocalTracks;
  456. // On Electron there is no permission prompt for granting permissions. That's why we don't need to
  457. // spend much time displaying the overlay screen. If GUM is not resolved within 15 seconds it will
  458. // probably never resolve.
  459. const timeout = browser.isElectron() ? 15000 : 60000;
  460. // FIXME is there any simpler way to rewrite this spaghetti below ?
  461. if (options.startScreenSharing) {
  462. tryCreateLocalTracks = this._createDesktopTrack()
  463. .then(([ desktopStream ]) => {
  464. if (!requestedAudio) {
  465. return [ desktopStream ];
  466. }
  467. return createLocalTracksF({
  468. devices: [ 'audio' ],
  469. timeout,
  470. firePermissionPromptIsShownEvent: true,
  471. fireSlowPromiseEvent: true
  472. })
  473. .then(([ audioStream ]) =>
  474. [ desktopStream, audioStream ])
  475. .catch(error => {
  476. errors.audioOnlyError = error;
  477. return [ desktopStream ];
  478. });
  479. })
  480. .catch(error => {
  481. logger.error('Failed to obtain desktop stream', error);
  482. errors.screenSharingError = error;
  483. return requestedAudio
  484. ? createLocalTracksF({
  485. devices: [ 'audio' ],
  486. timeout,
  487. firePermissionPromptIsShownEvent: true,
  488. fireSlowPromiseEvent: true
  489. })
  490. : [];
  491. })
  492. .catch(error => {
  493. errors.audioOnlyError = error;
  494. return [];
  495. });
  496. } else if (!requestedAudio && !requestedVideo) {
  497. // Resolve with no tracks
  498. tryCreateLocalTracks = Promise.resolve([]);
  499. } else {
  500. tryCreateLocalTracks = createLocalTracksF({
  501. devices: initialDevices,
  502. timeout,
  503. firePermissionPromptIsShownEvent: true,
  504. fireSlowPromiseEvent: true
  505. })
  506. .catch(err => {
  507. if (requestedAudio && requestedVideo) {
  508. // Try audio only...
  509. errors.audioAndVideoError = err;
  510. if (err.name === JitsiTrackErrors.TIMEOUT && !browser.isElectron()) {
  511. // In this case we expect that the permission prompt is still visible. There is no point of
  512. // executing GUM with different source. Also at the time of writing the following
  513. // inconsistency have been noticed in some browsers - if the permissions prompt is visible
  514. // and another GUM is executed the prompt does not change its content but if the user
  515. // clicks allow the user action isassociated with the latest GUM call.
  516. errors.audioOnlyError = err;
  517. errors.videoOnlyError = err;
  518. return [];
  519. }
  520. return (
  521. createLocalTracksF({
  522. devices: [ 'audio' ],
  523. timeout,
  524. firePermissionPromptIsShownEvent: true,
  525. fireSlowPromiseEvent: true
  526. }));
  527. } else if (requestedAudio && !requestedVideo) {
  528. errors.audioOnlyError = err;
  529. return [];
  530. } else if (requestedVideo && !requestedAudio) {
  531. errors.videoOnlyError = err;
  532. return [];
  533. }
  534. logger.error('Should never happen');
  535. })
  536. .catch(err => {
  537. // Log this just in case...
  538. if (!requestedAudio) {
  539. logger.error('The impossible just happened', err);
  540. }
  541. errors.audioOnlyError = err;
  542. // Try video only...
  543. return requestedVideo
  544. ? createLocalTracksF({
  545. devices: [ 'video' ],
  546. firePermissionPromptIsShownEvent: true,
  547. fireSlowPromiseEvent: true
  548. })
  549. : [];
  550. })
  551. .catch(err => {
  552. // Log this just in case...
  553. if (!requestedVideo) {
  554. logger.error('The impossible just happened', err);
  555. }
  556. errors.videoOnlyError = err;
  557. return [];
  558. });
  559. }
  560. // Hide the permissions prompt/overlay as soon as the tracks are
  561. // created. Don't wait for the connection to be made, since in some
  562. // cases, when auth is required, for instance, that won't happen until
  563. // the user inputs their credentials, but the dialog would be
  564. // overshadowed by the overlay.
  565. tryCreateLocalTracks.then(tracks => {
  566. APP.store.dispatch(toggleSlowGUMOverlay(false));
  567. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false));
  568. return tracks;
  569. });
  570. return {
  571. tryCreateLocalTracks,
  572. errors
  573. };
  574. },
  575. /**
  576. * Displays error notifications according to the state carried by {@code errors} object returned
  577. * by {@link createInitialLocalTracks}.
  578. * @param {Object} errors - the errors (if any) returned by {@link createInitialLocalTracks}.
  579. *
  580. * @returns {void}
  581. * @private
  582. */
  583. _displayErrorsForCreateInitialLocalTracks(errors) {
  584. const {
  585. audioAndVideoError,
  586. audioOnlyError,
  587. screenSharingError,
  588. videoOnlyError
  589. } = errors;
  590. // FIXME If there will be microphone error it will cover any screensharing dialog, but it's still better than in
  591. // the reverse order where the screensharing dialog will sometimes be closing the microphone alert
  592. // ($.prompt.close(); is called). Need to figure out dialogs chaining to fix that.
  593. if (screenSharingError) {
  594. this._handleScreenSharingError(screenSharingError);
  595. }
  596. if (audioAndVideoError || audioOnlyError) {
  597. if (audioOnlyError || videoOnlyError) {
  598. // If both requests for 'audio' + 'video' and 'audio' only failed, we assume that there are some
  599. // problems with user's microphone and show corresponding dialog.
  600. APP.store.dispatch(notifyMicError(audioOnlyError));
  601. APP.store.dispatch(notifyCameraError(videoOnlyError));
  602. } else {
  603. // If request for 'audio' + 'video' failed, but request for 'audio' only was OK, we assume that we had
  604. // problems with camera and show corresponding dialog.
  605. APP.store.dispatch(notifyCameraError(audioAndVideoError));
  606. }
  607. }
  608. },
  609. /**
  610. * Creates local media tracks and connects to a room. Will show error
  611. * dialogs in case accessing the local microphone and/or camera failed. Will
  612. * show guidance overlay for users on how to give access to camera and/or
  613. * microphone.
  614. * @param {string} roomName
  615. * @param {object} options
  616. * @param {boolean} options.startAudioOnly=false - if <tt>true</tt> then
  617. * only audio track will be created and the audio only mode will be turned
  618. * on.
  619. * @param {boolean} options.startScreenSharing=false - if <tt>true</tt>
  620. * should start with screensharing instead of camera video.
  621. * @param {boolean} options.startWithAudioMuted - will start the conference
  622. * without any audio tracks.
  623. * @param {boolean} options.startWithVideoMuted - will start the conference
  624. * without any video tracks.
  625. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  626. */
  627. createInitialLocalTracksAndConnect(roomName, options = {}) {
  628. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(options);
  629. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  630. .then(([ tracks, con ]) => {
  631. this._displayErrorsForCreateInitialLocalTracks(errors);
  632. return [ tracks, con ];
  633. });
  634. },
  635. startConference(con, tracks) {
  636. tracks.forEach(track => {
  637. if ((track.isAudioTrack() && this.isLocalAudioMuted())
  638. || (track.isVideoTrack() && this.isLocalVideoMuted())) {
  639. const mediaType = track.getType();
  640. sendAnalytics(
  641. createTrackMutedEvent(mediaType, 'initial mute'));
  642. logger.log(`${mediaType} mute: initially muted.`);
  643. track.mute();
  644. }
  645. });
  646. logger.log(`Initialized with ${tracks.length} local tracks`);
  647. this._localTracksInitialized = true;
  648. con.addEventListener(JitsiConnectionEvents.CONNECTION_FAILED, _connectionFailedHandler);
  649. APP.connection = connection = con;
  650. this._createRoom(tracks);
  651. // if user didn't give access to mic or camera or doesn't have
  652. // them at all, we mark corresponding toolbar buttons as muted,
  653. // so that the user can try unmute later on and add audio/video
  654. // to the conference
  655. if (!tracks.find(t => t.isAudioTrack())) {
  656. this.setAudioMuteStatus(true);
  657. }
  658. if (!tracks.find(t => t.isVideoTrack())) {
  659. this.setVideoMuteStatus();
  660. }
  661. if (config.iAmRecorder) {
  662. this.recorder = new Recorder();
  663. }
  664. if (config.startSilent) {
  665. sendAnalytics(createStartSilentEvent());
  666. APP.store.dispatch(showNotification({
  667. descriptionKey: 'notify.startSilentDescription',
  668. titleKey: 'notify.startSilentTitle'
  669. }));
  670. }
  671. // XXX The API will take care of disconnecting from the XMPP
  672. // server (and, thus, leaving the room) on unload.
  673. return new Promise((resolve, reject) => {
  674. (new ConferenceConnector(resolve, reject)).connect();
  675. });
  676. },
  677. /**
  678. * Open new connection and join the conference when prejoin page is not enabled.
  679. * If prejoin page is enabled open an new connection in the background
  680. * and create local tracks.
  681. *
  682. * @param {{ roomName: string }} options
  683. * @returns {Promise}
  684. */
  685. async init({ roomName }) {
  686. const initialOptions = {
  687. startAudioOnly: config.startAudioOnly,
  688. startScreenSharing: config.startScreenSharing,
  689. startWithAudioMuted: getStartWithAudioMuted(APP.store.getState())
  690. || config.startSilent
  691. || isUserInteractionRequiredForUnmute(APP.store.getState()),
  692. startWithVideoMuted: getStartWithVideoMuted(APP.store.getState())
  693. || isUserInteractionRequiredForUnmute(APP.store.getState())
  694. };
  695. this.roomName = roomName;
  696. try {
  697. // Initialize the device list first. This way, when creating tracks
  698. // based on preferred devices, loose label matching can be done in
  699. // cases where the exact ID match is no longer available, such as
  700. // when the camera device has switched USB ports.
  701. // when in startSilent mode we want to start with audio muted
  702. await this._initDeviceList();
  703. } catch (error) {
  704. logger.warn('initial device list initialization failed', error);
  705. }
  706. if (isPrejoinPageEnabled(APP.store.getState())) {
  707. _connectionPromise = connect(roomName).then(c => {
  708. // we want to initialize it early, in case of errors to be able
  709. // to gather logs
  710. APP.connection = c;
  711. return c;
  712. });
  713. APP.store.dispatch(makePrecallTest(this._getConferenceOptions()));
  714. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(initialOptions);
  715. const tracks = await tryCreateLocalTracks;
  716. // Initialize device list a second time to ensure device labels
  717. // get populated in case of an initial gUM acceptance; otherwise
  718. // they may remain as empty strings.
  719. this._initDeviceList(true);
  720. if (isPrejoinPageVisible(APP.store.getState())) {
  721. return APP.store.dispatch(initPrejoin(tracks, errors));
  722. }
  723. logger.debug('Prejoin screen no longer displayed at the time when tracks were created');
  724. this._displayErrorsForCreateInitialLocalTracks(errors);
  725. return this._setLocalAudioVideoStreams(tracks);
  726. }
  727. const [ tracks, con ] = await this.createInitialLocalTracksAndConnect(roomName, initialOptions);
  728. let localTracks = tracks;
  729. this._initDeviceList(true);
  730. if (initialOptions.startWithAudioMuted) {
  731. localTracks = localTracks.filter(track => track.getType() !== MEDIA_TYPE.AUDIO);
  732. }
  733. return this.startConference(con, localTracks);
  734. },
  735. /**
  736. * Joins conference after the tracks have been configured in the prejoin screen.
  737. *
  738. * @param {Object[]} tracks - An array with the configured tracks
  739. * @returns {Promise}
  740. */
  741. async prejoinStart(tracks) {
  742. const con = await _connectionPromise;
  743. return this.startConference(con, tracks);
  744. },
  745. /**
  746. * Check if id is id of the local user.
  747. * @param {string} id id to check
  748. * @returns {boolean}
  749. */
  750. isLocalId(id) {
  751. return this.getMyUserId() === id;
  752. },
  753. /**
  754. * Tells whether the local video is muted or not.
  755. * @return {boolean}
  756. */
  757. isLocalVideoMuted() {
  758. // If the tracks are not ready, read from base/media state
  759. return this._localTracksInitialized
  760. ? isLocalCameraTrackMuted(
  761. APP.store.getState()['features/base/tracks'])
  762. : isVideoMutedByUser(APP.store);
  763. },
  764. /**
  765. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  766. * @param {boolean} mute true for mute and false for unmute.
  767. * @param {boolean} [showUI] when set to false will not display any error
  768. * dialogs in case of media permissions error.
  769. */
  770. muteAudio(mute, showUI = true) {
  771. if (!mute
  772. && isUserInteractionRequiredForUnmute(APP.store.getState())) {
  773. logger.error('Unmuting audio requires user interaction');
  774. return;
  775. }
  776. // Not ready to modify track's state yet
  777. if (!this._localTracksInitialized) {
  778. // This will only modify base/media.audio.muted which is then synced
  779. // up with the track at the end of local tracks initialization.
  780. muteLocalAudio(mute);
  781. this.setAudioMuteStatus(mute);
  782. return;
  783. } else if (this.isLocalAudioMuted() === mute) {
  784. // NO-OP
  785. return;
  786. }
  787. if (!this.localAudio && !mute) {
  788. const maybeShowErrorDialog = error => {
  789. showUI && APP.store.dispatch(notifyMicError(error));
  790. };
  791. createLocalTracksF({ devices: [ 'audio' ] })
  792. .then(([ audioTrack ]) => audioTrack)
  793. .catch(error => {
  794. maybeShowErrorDialog(error);
  795. // Rollback the audio muted status by using null track
  796. return null;
  797. })
  798. .then(audioTrack => this.useAudioStream(audioTrack));
  799. } else {
  800. muteLocalAudio(mute);
  801. }
  802. },
  803. /**
  804. * Returns whether local audio is muted or not.
  805. * @returns {boolean}
  806. */
  807. isLocalAudioMuted() {
  808. // If the tracks are not ready, read from base/media state
  809. return this._localTracksInitialized
  810. ? isLocalTrackMuted(
  811. APP.store.getState()['features/base/tracks'],
  812. MEDIA_TYPE.AUDIO)
  813. : Boolean(
  814. APP.store.getState()['features/base/media'].audio.muted);
  815. },
  816. /**
  817. * Simulates toolbar button click for audio mute. Used by shortcuts
  818. * and API.
  819. * @param {boolean} [showUI] when set to false will not display any error
  820. * dialogs in case of media permissions error.
  821. */
  822. toggleAudioMuted(showUI = true) {
  823. this.muteAudio(!this.isLocalAudioMuted(), showUI);
  824. },
  825. /**
  826. * Simulates toolbar button click for presenter video mute. Used by
  827. * shortcuts and API.
  828. * @param mute true for mute and false for unmute.
  829. * @param {boolean} [showUI] when set to false will not display any error
  830. * dialogs in case of media permissions error.
  831. */
  832. async mutePresenter(mute, showUI = true) {
  833. const maybeShowErrorDialog = error => {
  834. showUI && APP.store.dispatch(notifyCameraError(error));
  835. };
  836. if (mute) {
  837. try {
  838. await this.localVideo.setEffect(undefined);
  839. } catch (err) {
  840. logger.error('Failed to remove the presenter effect', err);
  841. maybeShowErrorDialog(err);
  842. }
  843. } else {
  844. try {
  845. await this.localVideo.setEffect(await this._createPresenterStreamEffect());
  846. } catch (err) {
  847. logger.error('Failed to apply the presenter effect', err);
  848. maybeShowErrorDialog(err);
  849. }
  850. }
  851. },
  852. /**
  853. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  854. * @param mute true for mute and false for unmute.
  855. * @param {boolean} [showUI] when set to false will not display any error
  856. * dialogs in case of media permissions error.
  857. */
  858. muteVideo(mute, showUI = true) {
  859. if (!mute
  860. && isUserInteractionRequiredForUnmute(APP.store.getState())) {
  861. logger.error('Unmuting video requires user interaction');
  862. return;
  863. }
  864. if (this.isSharingScreen) {
  865. // Chain _mutePresenterVideo calls
  866. _prevMutePresenterVideo = _prevMutePresenterVideo.then(() => this._mutePresenterVideo(mute));
  867. return;
  868. }
  869. // If not ready to modify track's state yet adjust the base/media
  870. if (!this._localTracksInitialized) {
  871. // This will only modify base/media.video.muted which is then synced
  872. // up with the track at the end of local tracks initialization.
  873. muteLocalVideo(mute);
  874. this.setVideoMuteStatus();
  875. return;
  876. } else if (this.isLocalVideoMuted() === mute) {
  877. // NO-OP
  878. return;
  879. }
  880. if (!this.localVideo && !mute) {
  881. const maybeShowErrorDialog = error => {
  882. showUI && APP.store.dispatch(notifyCameraError(error));
  883. };
  884. // Try to create local video if there wasn't any.
  885. // This handles the case when user joined with no video
  886. // (dismissed screen sharing screen or in audio only mode), but
  887. // decided to add it later on by clicking on muted video icon or
  888. // turning off the audio only mode.
  889. //
  890. // FIXME when local track creation is moved to react/redux
  891. // it should take care of the use case described above
  892. createLocalTracksF({ devices: [ 'video' ] })
  893. .then(([ videoTrack ]) => videoTrack)
  894. .catch(error => {
  895. // FIXME should send some feedback to the API on error ?
  896. maybeShowErrorDialog(error);
  897. // Rollback the video muted status by using null track
  898. return null;
  899. })
  900. .then(videoTrack => {
  901. logger.debug(`muteVideo: calling useVideoStream for track: ${videoTrack}`);
  902. return this.useVideoStream(videoTrack);
  903. });
  904. } else {
  905. // FIXME show error dialog if it fails (should be handled by react)
  906. muteLocalVideo(mute);
  907. }
  908. },
  909. /**
  910. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  911. * @param {boolean} [showUI] when set to false will not display any error
  912. * dialogs in case of media permissions error.
  913. */
  914. toggleVideoMuted(showUI = true) {
  915. this.muteVideo(!this.isLocalVideoMuted(), showUI);
  916. },
  917. /**
  918. * Retrieve list of ids of conference participants (without local user).
  919. * @returns {string[]}
  920. */
  921. listMembersIds() {
  922. return room.getParticipants().map(p => p.getId());
  923. },
  924. /**
  925. * Checks whether the participant identified by id is a moderator.
  926. * @id id to search for participant
  927. * @return {boolean} whether the participant is moderator
  928. */
  929. isParticipantModerator(id) {
  930. const user = room.getParticipantById(id);
  931. return user && user.isModerator();
  932. },
  933. /**
  934. * Retrieve list of conference participants (without local user).
  935. * @returns {JitsiParticipant[]}
  936. *
  937. * NOTE: Used by jitsi-meet-torture!
  938. */
  939. listMembers() {
  940. return room.getParticipants();
  941. },
  942. get membersCount() {
  943. return room.getParticipants().length + 1;
  944. },
  945. /**
  946. * Returns true if the callstats integration is enabled, otherwise returns
  947. * false.
  948. *
  949. * @returns true if the callstats integration is enabled, otherwise returns
  950. * false.
  951. */
  952. isCallstatsEnabled() {
  953. return room && room.isCallstatsEnabled();
  954. },
  955. /**
  956. * Get speaker stats that track total dominant speaker time.
  957. *
  958. * @returns {object} A hash with keys being user ids and values being the
  959. * library's SpeakerStats model used for calculating time as dominant
  960. * speaker.
  961. */
  962. getSpeakerStats() {
  963. return room.getSpeakerStats();
  964. },
  965. /**
  966. * Returns the connection times stored in the library.
  967. */
  968. getConnectionTimes() {
  969. return room.getConnectionTimes();
  970. },
  971. // used by torture currently
  972. isJoined() {
  973. return room && room.isJoined();
  974. },
  975. getConnectionState() {
  976. return room && room.getConnectionState();
  977. },
  978. /**
  979. * Obtains current P2P ICE connection state.
  980. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  981. * P2P connection
  982. */
  983. getP2PConnectionState() {
  984. return room && room.getP2PConnectionState();
  985. },
  986. /**
  987. * Starts P2P (for tests only)
  988. * @private
  989. */
  990. _startP2P() {
  991. try {
  992. room && room.startP2PSession();
  993. } catch (error) {
  994. logger.error('Start P2P failed', error);
  995. throw error;
  996. }
  997. },
  998. /**
  999. * Stops P2P (for tests only)
  1000. * @private
  1001. */
  1002. _stopP2P() {
  1003. try {
  1004. room && room.stopP2PSession();
  1005. } catch (error) {
  1006. logger.error('Stop P2P failed', error);
  1007. throw error;
  1008. }
  1009. },
  1010. /**
  1011. * Checks whether or not our connection is currently in interrupted and
  1012. * reconnect attempts are in progress.
  1013. *
  1014. * @returns {boolean} true if the connection is in interrupted state or
  1015. * false otherwise.
  1016. */
  1017. isConnectionInterrupted() {
  1018. return room.isConnectionInterrupted();
  1019. },
  1020. /**
  1021. * Obtains the local display name.
  1022. * @returns {string|undefined}
  1023. */
  1024. getLocalDisplayName() {
  1025. return getDisplayName(this.getMyUserId());
  1026. },
  1027. /**
  1028. * Finds JitsiParticipant for given id.
  1029. *
  1030. * @param {string} id participant's identifier(MUC nickname).
  1031. *
  1032. * @returns {JitsiParticipant|null} participant instance for given id or
  1033. * null if not found.
  1034. */
  1035. getParticipantById(id) {
  1036. return room ? room.getParticipantById(id) : null;
  1037. },
  1038. /**
  1039. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  1040. * the given <tt>id</tt>.
  1041. *
  1042. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  1043. *
  1044. * @return {string} the participant's display name or the default string if
  1045. * absent.
  1046. */
  1047. getParticipantDisplayName(id) {
  1048. const displayName = getDisplayName(id);
  1049. if (displayName) {
  1050. return displayName;
  1051. }
  1052. if (APP.conference.isLocalId(id)) {
  1053. return APP.translation.generateTranslationHTML(
  1054. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  1055. }
  1056. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  1057. },
  1058. getMyUserId() {
  1059. return room && room.myUserId();
  1060. },
  1061. /**
  1062. * Will be filled with values only when config.debug is enabled.
  1063. * Its used by torture to check audio levels.
  1064. */
  1065. audioLevelsMap: {},
  1066. /**
  1067. * Returns the stored audio level (stored only if config.debug is enabled)
  1068. * @param id the id for the user audio level to return (the id value is
  1069. * returned for the participant using getMyUserId() method)
  1070. */
  1071. getPeerSSRCAudioLevel(id) {
  1072. return this.audioLevelsMap[id];
  1073. },
  1074. /**
  1075. * @return {number} the number of participants in the conference with at
  1076. * least one track.
  1077. */
  1078. getNumberOfParticipantsWithTracks() {
  1079. return room.getParticipants()
  1080. .filter(p => p.getTracks().length > 0)
  1081. .length;
  1082. },
  1083. /**
  1084. * Returns the stats.
  1085. */
  1086. getStats() {
  1087. return room.connectionQuality.getStats();
  1088. },
  1089. // end used by torture
  1090. /**
  1091. * Download logs, a function that can be called from console while
  1092. * debugging.
  1093. * @param filename (optional) specify target filename
  1094. */
  1095. saveLogs(filename = 'meetlog.json') {
  1096. // this can be called from console and will not have reference to this
  1097. // that's why we reference the global var
  1098. const logs = APP.connection.getLogs();
  1099. downloadJSON(logs, filename);
  1100. },
  1101. /**
  1102. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  1103. * desire to keep room private to this instance and (2) the need of other
  1104. * modules to send and receive commands to and from participants.
  1105. * Eventually, this instance remains in control with respect to the
  1106. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  1107. * JitsiConference) is to be used in the implementation of the Command(s)
  1108. * API of this instance.
  1109. */
  1110. commands: {
  1111. /**
  1112. * Known custom conference commands.
  1113. */
  1114. defaults: commands,
  1115. /**
  1116. * Receives notifications from other participants about commands aka
  1117. * custom events (sent by sendCommand or sendCommandOnce methods).
  1118. * @param command {String} the name of the command
  1119. * @param handler {Function} handler for the command
  1120. */
  1121. addCommandListener() {
  1122. // eslint-disable-next-line prefer-rest-params
  1123. room.addCommandListener(...arguments);
  1124. },
  1125. /**
  1126. * Removes command.
  1127. * @param name {String} the name of the command.
  1128. */
  1129. removeCommand() {
  1130. // eslint-disable-next-line prefer-rest-params
  1131. room.removeCommand(...arguments);
  1132. },
  1133. /**
  1134. * Sends command.
  1135. * @param name {String} the name of the command.
  1136. * @param values {Object} with keys and values that will be sent.
  1137. */
  1138. sendCommand() {
  1139. // eslint-disable-next-line prefer-rest-params
  1140. room.sendCommand(...arguments);
  1141. },
  1142. /**
  1143. * Sends command one time.
  1144. * @param name {String} the name of the command.
  1145. * @param values {Object} with keys and values that will be sent.
  1146. */
  1147. sendCommandOnce() {
  1148. // eslint-disable-next-line prefer-rest-params
  1149. room.sendCommandOnce(...arguments);
  1150. }
  1151. },
  1152. _createRoom(localTracks) {
  1153. room
  1154. = connection.initJitsiConference(
  1155. APP.conference.roomName,
  1156. this._getConferenceOptions());
  1157. APP.store.dispatch(conferenceWillJoin(room));
  1158. // Filter out the tracks that are muted.
  1159. const tracks = localTracks.filter(track => !track.isMuted());
  1160. this._setLocalAudioVideoStreams(tracks);
  1161. this._room = room; // FIXME do not use this
  1162. sendLocalParticipant(APP.store, room);
  1163. this._setupListeners();
  1164. },
  1165. /**
  1166. * Sets local video and audio streams.
  1167. * @param {JitsiLocalTrack[]} tracks=[]
  1168. * @returns {Promise[]}
  1169. * @private
  1170. */
  1171. _setLocalAudioVideoStreams(tracks = []) {
  1172. return tracks.map(track => {
  1173. if (track.isAudioTrack()) {
  1174. return this.useAudioStream(track);
  1175. } else if (track.isVideoTrack()) {
  1176. logger.debug(`_setLocalAudioVideoStreams is calling useVideoStream with track: ${track}`);
  1177. return this.useVideoStream(track);
  1178. }
  1179. logger.error(
  1180. 'Ignored not an audio nor a video track: ', track);
  1181. return Promise.resolve();
  1182. });
  1183. },
  1184. _getConferenceOptions() {
  1185. const options = getConferenceOptions(APP.store.getState());
  1186. options.createVADProcessor = createRnnoiseProcessor;
  1187. return options;
  1188. },
  1189. /**
  1190. * Start using provided video stream.
  1191. * Stops previous video stream.
  1192. * @param {JitsiLocalTrack} newTrack - new track to use or null
  1193. * @returns {Promise}
  1194. */
  1195. useVideoStream(newTrack) {
  1196. logger.debug(`useVideoStream: ${newTrack}`);
  1197. return new Promise((resolve, reject) => {
  1198. _replaceLocalVideoTrackQueue.enqueue(onFinish => {
  1199. const state = APP.store.getState();
  1200. // When the prejoin page is displayed localVideo is not set
  1201. // so just replace the video track from the store with the new one.
  1202. if (isPrejoinPageVisible(state)) {
  1203. const oldTrack = getLocalJitsiVideoTrack(state);
  1204. logger.debug(`useVideoStream on the prejoin screen: Replacing ${oldTrack} with ${newTrack}`);
  1205. return APP.store.dispatch(replaceLocalTrack(oldTrack, newTrack))
  1206. .then(resolve)
  1207. .catch(error => {
  1208. logger.error(`useVideoStream failed on the prejoin screen: ${error}`);
  1209. reject(error);
  1210. })
  1211. .then(onFinish);
  1212. }
  1213. logger.debug(`useVideoStream: Replacing ${this.localVideo} with ${newTrack}`);
  1214. APP.store.dispatch(
  1215. replaceLocalTrack(this.localVideo, newTrack, room))
  1216. .then(() => {
  1217. this.localVideo = newTrack;
  1218. this._setSharingScreen(newTrack);
  1219. this.setVideoMuteStatus();
  1220. })
  1221. .then(resolve)
  1222. .catch(error => {
  1223. logger.error(`useVideoStream failed: ${error}`);
  1224. reject(error);
  1225. })
  1226. .then(onFinish);
  1227. });
  1228. });
  1229. },
  1230. /**
  1231. * Sets `this.isSharingScreen` depending on provided video stream.
  1232. * In case new screen sharing status is not equal previous one
  1233. * it updates desktop sharing buttons in UI
  1234. * and notifies external application.
  1235. *
  1236. * @param {JitsiLocalTrack} [newStream] new stream to use or null
  1237. * @private
  1238. * @returns {void}
  1239. */
  1240. _setSharingScreen(newStream) {
  1241. const wasSharingScreen = this.isSharingScreen;
  1242. this.isSharingScreen = newStream && newStream.videoType === 'desktop';
  1243. if (wasSharingScreen !== this.isSharingScreen) {
  1244. const details = {};
  1245. if (this.isSharingScreen) {
  1246. details.sourceType = newStream.sourceType;
  1247. }
  1248. APP.API.notifyScreenSharingStatusChanged(
  1249. this.isSharingScreen, details);
  1250. }
  1251. },
  1252. /**
  1253. * Start using provided audio stream.
  1254. * Stops previous audio stream.
  1255. * @param {JitsiLocalTrack} newTrack - new track to use or null
  1256. * @returns {Promise}
  1257. */
  1258. useAudioStream(newTrack) {
  1259. return new Promise((resolve, reject) => {
  1260. _replaceLocalAudioTrackQueue.enqueue(onFinish => {
  1261. const state = APP.store.getState();
  1262. // When the prejoin page is displayed localAudio is not set
  1263. // so just replace the audio track from the store with the new one.
  1264. if (isPrejoinPageVisible(state)) {
  1265. const oldTrack = getLocalJitsiAudioTrack(state);
  1266. return APP.store.dispatch(replaceLocalTrack(oldTrack, newTrack))
  1267. .then(resolve)
  1268. .catch(reject)
  1269. .then(onFinish);
  1270. }
  1271. APP.store.dispatch(
  1272. replaceLocalTrack(this.localAudio, newTrack, room))
  1273. .then(() => {
  1274. this.localAudio = newTrack;
  1275. this.setAudioMuteStatus(this.isLocalAudioMuted());
  1276. })
  1277. .then(resolve)
  1278. .catch(reject)
  1279. .then(onFinish);
  1280. });
  1281. });
  1282. },
  1283. /**
  1284. * Returns whether or not the conference is currently in audio only mode.
  1285. *
  1286. * @returns {boolean}
  1287. */
  1288. isAudioOnly() {
  1289. return Boolean(APP.store.getState()['features/base/audio-only'].enabled);
  1290. },
  1291. videoSwitchInProgress: false,
  1292. /**
  1293. * This fields stores a handler which will create a Promise which turns off
  1294. * the screen sharing and restores the previous video state (was there
  1295. * any video, before switching to screen sharing ? was it muted ?).
  1296. *
  1297. * Once called this fields is cleared to <tt>null</tt>.
  1298. * @type {Function|null}
  1299. */
  1300. _untoggleScreenSharing: null,
  1301. /**
  1302. * Creates a Promise which turns off the screen sharing and restores
  1303. * the previous state described by the arguments.
  1304. *
  1305. * This method is bound to the appropriate values, after switching to screen
  1306. * sharing and stored in {@link _untoggleScreenSharing}.
  1307. *
  1308. * @param {boolean} didHaveVideo indicates if there was a camera video being
  1309. * used, before switching to screen sharing.
  1310. * @param {boolean} wasVideoMuted indicates if the video was muted, before
  1311. * switching to screen sharing.
  1312. * @return {Promise} resolved after the screen sharing is turned off, or
  1313. * rejected with some error (no idea what kind of error, possible GUM error)
  1314. * in case it fails.
  1315. * @private
  1316. */
  1317. async _turnScreenSharingOff(didHaveVideo) {
  1318. this._untoggleScreenSharing = null;
  1319. this.videoSwitchInProgress = true;
  1320. APP.store.dispatch(stopReceiver());
  1321. this._stopProxyConnection();
  1322. if (config.enableScreenshotCapture) {
  1323. APP.store.dispatch(toggleScreenshotCaptureEffect(false));
  1324. }
  1325. // It can happen that presenter GUM is in progress while screensharing is being turned off. Here it needs to
  1326. // wait for that GUM to be resolved in order to prevent leaking the presenter track(this.localPresenterVideo
  1327. // will be null when SS is being turned off, but it will initialize once GUM resolves).
  1328. let promise = _prevMutePresenterVideo = _prevMutePresenterVideo.then(() => {
  1329. // mute the presenter track if it exists.
  1330. if (this.localPresenterVideo) {
  1331. APP.store.dispatch(setVideoMuted(true, MEDIA_TYPE.PRESENTER));
  1332. return this.localPresenterVideo.dispose().then(() => {
  1333. APP.store.dispatch(trackRemoved(this.localPresenterVideo));
  1334. this.localPresenterVideo = null;
  1335. });
  1336. }
  1337. });
  1338. // If system audio was also shared stop the AudioMixerEffect and dispose of the desktop audio track.
  1339. if (this._mixerEffect) {
  1340. await this.localAudio.setEffect(undefined);
  1341. await this._desktopAudioStream.dispose();
  1342. this._mixerEffect = undefined;
  1343. this._desktopAudioStream = undefined;
  1344. // In case there was no local audio when screen sharing was started the fact that we set the audio stream to
  1345. // null will take care of the desktop audio stream cleanup.
  1346. } else if (this._desktopAudioStream) {
  1347. await this.useAudioStream(null);
  1348. this._desktopAudioStream = undefined;
  1349. }
  1350. APP.store.dispatch(setScreenAudioShareState(false));
  1351. if (didHaveVideo) {
  1352. promise = promise.then(() => createLocalTracksF({ devices: [ 'video' ] }))
  1353. .then(([ stream ]) => {
  1354. logger.debug(`_turnScreenSharingOff using ${stream} for useVideoStream`);
  1355. return this.useVideoStream(stream);
  1356. })
  1357. .catch(error => {
  1358. logger.error('failed to switch back to local video', error);
  1359. return this.useVideoStream(null).then(() =>
  1360. // Still fail with the original err
  1361. Promise.reject(error)
  1362. );
  1363. });
  1364. } else {
  1365. promise = promise.then(() => {
  1366. logger.debug('_turnScreenSharingOff using null for useVideoStream');
  1367. return this.useVideoStream(null);
  1368. });
  1369. }
  1370. return promise.then(
  1371. () => {
  1372. this.videoSwitchInProgress = false;
  1373. sendAnalytics(createScreenSharingEvent('stopped'));
  1374. logger.info('Screen sharing stopped.');
  1375. },
  1376. error => {
  1377. this.videoSwitchInProgress = false;
  1378. logger.error(`_turnScreenSharingOff failed: ${error}`);
  1379. throw error;
  1380. });
  1381. },
  1382. /**
  1383. * Toggles between screen sharing and camera video if the toggle parameter
  1384. * is not specified and starts the procedure for obtaining new screen
  1385. * sharing/video track otherwise.
  1386. *
  1387. * @param {boolean} [toggle] - If true - new screen sharing track will be
  1388. * obtained. If false - new video track will be obtain. If not specified -
  1389. * toggles between screen sharing and camera video.
  1390. * @param {Object} [options] - Screen sharing options that will be passed to
  1391. * createLocalTracks.
  1392. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  1393. * sources that have to be displayed in the desktop picker window ('screen',
  1394. * 'window', etc.).
  1395. * @return {Promise.<T>}
  1396. */
  1397. async toggleScreenSharing(toggle = !this._untoggleScreenSharing, options = {}) {
  1398. logger.debug(`toggleScreenSharing: ${toggle}`);
  1399. if (this.videoSwitchInProgress) {
  1400. return Promise.reject('Switch in progress.');
  1401. }
  1402. if (!JitsiMeetJS.isDesktopSharingEnabled()) {
  1403. return Promise.reject('Cannot toggle screen sharing: not supported.');
  1404. }
  1405. if (this.isAudioOnly()) {
  1406. return Promise.reject('No screensharing in audio only mode');
  1407. }
  1408. if (toggle) {
  1409. try {
  1410. await this._switchToScreenSharing(options);
  1411. return;
  1412. } catch (err) {
  1413. logger.error('Failed to switch to screensharing', err);
  1414. return;
  1415. }
  1416. }
  1417. return this._untoggleScreenSharing
  1418. ? this._untoggleScreenSharing()
  1419. : Promise.resolve();
  1420. },
  1421. /**
  1422. * Creates desktop (screensharing) {@link JitsiLocalTrack}
  1423. *
  1424. * @param {Object} [options] - Screen sharing options that will be passed to
  1425. * createLocalTracks.
  1426. * @param {Object} [options.desktopSharing]
  1427. * @param {Object} [options.desktopStream] - An existing desktop stream to
  1428. * use instead of creating a new desktop stream.
  1429. * @return {Promise.<JitsiLocalTrack>} - A Promise resolved with
  1430. * {@link JitsiLocalTrack} for the screensharing or rejected with
  1431. * {@link JitsiTrackError}.
  1432. *
  1433. * @private
  1434. */
  1435. _createDesktopTrack(options = {}) {
  1436. const didHaveVideo = !this.isLocalVideoMuted();
  1437. const getDesktopStreamPromise = options.desktopStream
  1438. ? Promise.resolve([ options.desktopStream ])
  1439. : createLocalTracksF({
  1440. desktopSharingSourceDevice: options.desktopSharingSources
  1441. ? null : config._desktopSharingSourceDevice,
  1442. desktopSharingSources: options.desktopSharingSources,
  1443. devices: [ 'desktop' ]
  1444. });
  1445. return getDesktopStreamPromise.then(desktopStreams => {
  1446. // Stores the "untoggle" handler which remembers whether was
  1447. // there any video before and whether was it muted.
  1448. this._untoggleScreenSharing
  1449. = this._turnScreenSharingOff.bind(this, didHaveVideo);
  1450. const desktopVideoStream = desktopStreams.find(stream => stream.getType() === MEDIA_TYPE.VIDEO);
  1451. const dekstopAudioStream = desktopStreams.find(stream => stream.getType() === MEDIA_TYPE.AUDIO);
  1452. if (dekstopAudioStream) {
  1453. dekstopAudioStream.on(
  1454. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1455. () => {
  1456. logger.debug(`Local screensharing audio track stopped. ${this.isSharingScreen}`);
  1457. // Handle case where screen share was stopped from the browsers 'screen share in progress'
  1458. // window. If audio screen sharing is stopped via the normal UX flow this point shouldn't
  1459. // be reached.
  1460. isScreenAudioShared(APP.store.getState())
  1461. && this._untoggleScreenSharing
  1462. && this._untoggleScreenSharing();
  1463. }
  1464. );
  1465. }
  1466. if (desktopVideoStream) {
  1467. desktopVideoStream.on(
  1468. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1469. () => {
  1470. logger.debug(`Local screensharing track stopped. ${this.isSharingScreen}`);
  1471. // If the stream was stopped during screen sharing
  1472. // session then we should switch back to video.
  1473. this.isSharingScreen
  1474. && this._untoggleScreenSharing
  1475. && this._untoggleScreenSharing();
  1476. }
  1477. );
  1478. }
  1479. return desktopStreams;
  1480. }, error => {
  1481. throw error;
  1482. });
  1483. },
  1484. /**
  1485. * Creates a new instance of presenter effect. A new video track is created
  1486. * using the new set of constraints that are calculated based on
  1487. * the height of the desktop that is being currently shared.
  1488. *
  1489. * @param {number} height - The height of the desktop stream that is being
  1490. * currently shared.
  1491. * @param {string} cameraDeviceId - The device id of the camera to be used.
  1492. * @return {Promise<JitsiStreamPresenterEffect>} - A promise resolved with
  1493. * {@link JitsiStreamPresenterEffect} if it succeeds.
  1494. */
  1495. async _createPresenterStreamEffect(height = null, cameraDeviceId = null) {
  1496. if (!this.localPresenterVideo) {
  1497. const camera = cameraDeviceId ?? getUserSelectedCameraDeviceId(APP.store.getState());
  1498. try {
  1499. this.localPresenterVideo = await createLocalPresenterTrack({ cameraDeviceId: camera }, height);
  1500. } catch (err) {
  1501. logger.error('Failed to create a camera track for presenter', err);
  1502. return;
  1503. }
  1504. APP.store.dispatch(trackAdded(this.localPresenterVideo));
  1505. }
  1506. try {
  1507. const effect = await createPresenterEffect(this.localPresenterVideo.stream);
  1508. return effect;
  1509. } catch (err) {
  1510. logger.error('Failed to create the presenter effect', err);
  1511. }
  1512. },
  1513. /**
  1514. * Tries to turn the presenter video track on or off. If a presenter track
  1515. * doesn't exist, a new video track is created.
  1516. *
  1517. * @param mute - true for mute and false for unmute.
  1518. *
  1519. * @private
  1520. */
  1521. async _mutePresenterVideo(mute) {
  1522. const maybeShowErrorDialog = error => {
  1523. APP.store.dispatch(notifyCameraError(error));
  1524. };
  1525. // Check for NO-OP
  1526. if (mute && (!this.localPresenterVideo || this.localPresenterVideo.isMuted())) {
  1527. return;
  1528. } else if (!mute && this.localPresenterVideo && !this.localPresenterVideo.isMuted()) {
  1529. return;
  1530. }
  1531. // Create a new presenter track and apply the presenter effect.
  1532. if (!this.localPresenterVideo && !mute) {
  1533. const { height, width } = this.localVideo.track.getSettings() ?? this.localVideo.track.getConstraints();
  1534. const isPortrait = height >= width;
  1535. const DESKTOP_STREAM_CAP = 720;
  1536. const highResolutionTrack
  1537. = (isPortrait && width > DESKTOP_STREAM_CAP) || (!isPortrait && height > DESKTOP_STREAM_CAP);
  1538. // Resizing the desktop track for presenter is causing blurriness of the desktop share on chrome.
  1539. // Disable resizing by default, enable it only when config.js setting is enabled.
  1540. const resizeDesktopStream = highResolutionTrack && config.videoQuality?.resizeDesktopForPresenter;
  1541. if (resizeDesktopStream) {
  1542. let desktopResizeConstraints = {};
  1543. if (height && width) {
  1544. const advancedConstraints = [ { aspectRatio: (width / height).toPrecision(4) } ];
  1545. const constraint = isPortrait ? { width: DESKTOP_STREAM_CAP } : { height: DESKTOP_STREAM_CAP };
  1546. advancedConstraints.push(constraint);
  1547. desktopResizeConstraints.advanced = advancedConstraints;
  1548. } else {
  1549. desktopResizeConstraints = {
  1550. width: 1280,
  1551. height: 720
  1552. };
  1553. }
  1554. // Apply the constraints on the desktop track.
  1555. try {
  1556. await this.localVideo.track.applyConstraints(desktopResizeConstraints);
  1557. } catch (err) {
  1558. logger.error('Failed to apply constraints on the desktop stream for presenter mode', err);
  1559. return;
  1560. }
  1561. }
  1562. const trackHeight = resizeDesktopStream
  1563. ? this.localVideo.track.getSettings().height ?? DESKTOP_STREAM_CAP
  1564. : height;
  1565. let effect;
  1566. try {
  1567. effect = await this._createPresenterStreamEffect(trackHeight);
  1568. } catch (err) {
  1569. logger.error('Failed to unmute Presenter Video', err);
  1570. maybeShowErrorDialog(err);
  1571. return;
  1572. }
  1573. // Replace the desktop track on the peerconnection.
  1574. try {
  1575. await this.localVideo.setEffect(effect);
  1576. APP.store.dispatch(setVideoMuted(mute, MEDIA_TYPE.PRESENTER));
  1577. this.setVideoMuteStatus();
  1578. } catch (err) {
  1579. logger.error('Failed to apply the Presenter effect', err);
  1580. }
  1581. } else {
  1582. APP.store.dispatch(setVideoMuted(mute, MEDIA_TYPE.PRESENTER));
  1583. }
  1584. },
  1585. /**
  1586. * Tries to switch to the screensharing mode by disposing camera stream and
  1587. * replacing it with a desktop one.
  1588. *
  1589. * @param {Object} [options] - Screen sharing options that will be passed to
  1590. * createLocalTracks.
  1591. *
  1592. * @return {Promise} - A Promise resolved if the operation succeeds or
  1593. * rejected with some unknown type of error in case it fails. Promise will
  1594. * be rejected immediately if {@link videoSwitchInProgress} is true.
  1595. *
  1596. * @private
  1597. */
  1598. _switchToScreenSharing(options = {}) {
  1599. if (this.videoSwitchInProgress) {
  1600. return Promise.reject('Switch in progress.');
  1601. }
  1602. this.videoSwitchInProgress = true;
  1603. return this._createDesktopTrack(options)
  1604. .then(async streams => {
  1605. let desktopVideoStream = streams.find(stream => stream.getType() === MEDIA_TYPE.VIDEO);
  1606. this._desktopAudioStream = streams.find(stream => stream.getType() === MEDIA_TYPE.AUDIO);
  1607. const { audioOnly = false } = options;
  1608. // If we're in audio only mode dispose of the video track otherwise the screensharing state will be
  1609. // inconsistent.
  1610. if (audioOnly) {
  1611. desktopVideoStream.dispose();
  1612. desktopVideoStream = undefined;
  1613. if (!this._desktopAudioStream) {
  1614. return Promise.reject(AUDIO_ONLY_SCREEN_SHARE_NO_TRACK);
  1615. }
  1616. }
  1617. if (desktopVideoStream) {
  1618. logger.debug(`_switchToScreenSharing is using ${desktopVideoStream} for useVideoStream`);
  1619. await this.useVideoStream(desktopVideoStream);
  1620. }
  1621. if (this._desktopAudioStream) {
  1622. // If there is a localAudio stream, mix in the desktop audio stream captured by the screen sharing
  1623. // api.
  1624. if (this.localAudio) {
  1625. this._mixerEffect = new AudioMixerEffect(this._desktopAudioStream);
  1626. await this.localAudio.setEffect(this._mixerEffect);
  1627. } else {
  1628. // If no local stream is present ( i.e. no input audio devices) we use the screen share audio
  1629. // stream as we would use a regular stream.
  1630. await this.useAudioStream(this._desktopAudioStream);
  1631. }
  1632. APP.store.dispatch(setScreenAudioShareState(true));
  1633. }
  1634. })
  1635. .then(() => {
  1636. this.videoSwitchInProgress = false;
  1637. if (config.enableScreenshotCapture) {
  1638. APP.store.dispatch(toggleScreenshotCaptureEffect(true));
  1639. }
  1640. sendAnalytics(createScreenSharingEvent('started'));
  1641. logger.log('Screen sharing started');
  1642. })
  1643. .catch(error => {
  1644. this.videoSwitchInProgress = false;
  1645. // Pawel: With this call I'm trying to preserve the original
  1646. // behaviour although it is not clear why would we "untoggle"
  1647. // on failure. I suppose it was to restore video in case there
  1648. // was some problem during "this.useVideoStream(desktopStream)".
  1649. // It's important to note that the handler will not be available
  1650. // if we fail early on trying to get desktop media (which makes
  1651. // sense, because the camera video is still being used, so
  1652. // nothing to "untoggle").
  1653. if (this._untoggleScreenSharing) {
  1654. this._untoggleScreenSharing();
  1655. }
  1656. // FIXME the code inside of _handleScreenSharingError is
  1657. // asynchronous, but does not return a Promise and is not part
  1658. // of the current Promise chain.
  1659. this._handleScreenSharingError(error);
  1660. return Promise.reject(error);
  1661. });
  1662. },
  1663. /**
  1664. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1665. * trying to create screensharing track. It will either do nothing if
  1666. * the dialog was canceled on user's request or display an error if
  1667. * screensharing couldn't be started.
  1668. * @param {JitsiTrackError} error - The error returned by
  1669. * {@link _createDesktopTrack} Promise.
  1670. * @private
  1671. */
  1672. _handleScreenSharingError(error) {
  1673. if (error.name === JitsiTrackErrors.SCREENSHARING_USER_CANCELED) {
  1674. return;
  1675. }
  1676. logger.error('failed to share local desktop', error);
  1677. // Handling:
  1678. // JitsiTrackErrors.CONSTRAINT_FAILED
  1679. // JitsiTrackErrors.PERMISSION_DENIED
  1680. // JitsiTrackErrors.SCREENSHARING_GENERIC_ERROR
  1681. // and any other
  1682. let descriptionKey;
  1683. let titleKey;
  1684. if (error.name === JitsiTrackErrors.PERMISSION_DENIED) {
  1685. descriptionKey = 'dialog.screenSharingPermissionDeniedError';
  1686. titleKey = 'dialog.screenSharingFailedTitle';
  1687. } else if (error.name === JitsiTrackErrors.CONSTRAINT_FAILED) {
  1688. descriptionKey = 'dialog.cameraConstraintFailedError';
  1689. titleKey = 'deviceError.cameraError';
  1690. } else if (error.name === JitsiTrackErrors.SCREENSHARING_GENERIC_ERROR) {
  1691. descriptionKey = 'dialog.screenSharingFailed';
  1692. titleKey = 'dialog.screenSharingFailedTitle';
  1693. } else if (error === AUDIO_ONLY_SCREEN_SHARE_NO_TRACK) {
  1694. descriptionKey = 'notify.screenShareNoAudio';
  1695. titleKey = 'notify.screenShareNoAudioTitle';
  1696. }
  1697. APP.UI.messageHandler.showError({
  1698. descriptionKey,
  1699. titleKey
  1700. });
  1701. },
  1702. /**
  1703. * Setup interaction between conference and UI.
  1704. */
  1705. _setupListeners() {
  1706. // add local streams when joined to the conference
  1707. room.on(JitsiConferenceEvents.CONFERENCE_JOINED, () => {
  1708. this._onConferenceJoined();
  1709. });
  1710. room.on(
  1711. JitsiConferenceEvents.CONFERENCE_LEFT,
  1712. (...args) => {
  1713. APP.store.dispatch(conferenceTimestampChanged(0));
  1714. APP.store.dispatch(conferenceLeft(room, ...args));
  1715. });
  1716. room.on(
  1717. JitsiConferenceEvents.CONFERENCE_UNIQUE_ID_SET,
  1718. (...args) => {
  1719. // Preserve the sessionId so that the value is accessible even after room
  1720. // is disconnected.
  1721. room.sessionId = room.getMeetingUniqueId();
  1722. APP.store.dispatch(conferenceUniqueIdSet(room, ...args));
  1723. });
  1724. room.on(
  1725. JitsiConferenceEvents.AUTH_STATUS_CHANGED,
  1726. (authEnabled, authLogin) =>
  1727. APP.store.dispatch(authStatusChanged(authEnabled, authLogin)));
  1728. room.on(JitsiConferenceEvents.PARTCIPANT_FEATURES_CHANGED, user => {
  1729. APP.store.dispatch(updateRemoteParticipantFeatures(user));
  1730. });
  1731. room.on(JitsiConferenceEvents.USER_JOINED, (id, user) => {
  1732. // The logic shared between RN and web.
  1733. commonUserJoinedHandling(APP.store, room, user);
  1734. if (user.isHidden()) {
  1735. return;
  1736. }
  1737. APP.store.dispatch(updateRemoteParticipantFeatures(user));
  1738. logger.log(`USER ${id} connected:`, user);
  1739. APP.UI.addUser(user);
  1740. });
  1741. room.on(JitsiConferenceEvents.USER_LEFT, (id, user) => {
  1742. // The logic shared between RN and web.
  1743. commonUserLeftHandling(APP.store, room, user);
  1744. if (user.isHidden()) {
  1745. return;
  1746. }
  1747. logger.log(`USER ${id} LEFT:`, user);
  1748. });
  1749. room.on(JitsiConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1750. APP.store.dispatch(participantPresenceChanged(id, status));
  1751. const user = room.getParticipantById(id);
  1752. if (user) {
  1753. APP.UI.updateUserStatus(user, status);
  1754. }
  1755. });
  1756. room.on(JitsiConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1757. if (this.isLocalId(id)) {
  1758. logger.info(`My role changed, new role: ${role}`);
  1759. APP.store.dispatch(localParticipantRoleChanged(role));
  1760. APP.API.notifyUserRoleChanged(id, role);
  1761. } else {
  1762. APP.store.dispatch(participantRoleChanged(id, role));
  1763. }
  1764. });
  1765. room.on(JitsiConferenceEvents.TRACK_ADDED, track => {
  1766. if (!track || track.isLocal()) {
  1767. return;
  1768. }
  1769. APP.store.dispatch(trackAdded(track));
  1770. });
  1771. room.on(JitsiConferenceEvents.TRACK_REMOVED, track => {
  1772. if (!track || track.isLocal()) {
  1773. return;
  1774. }
  1775. APP.store.dispatch(trackRemoved(track));
  1776. });
  1777. room.on(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1778. let newLvl = lvl;
  1779. if (this.isLocalId(id)
  1780. && this.localAudio && this.localAudio.isMuted()) {
  1781. newLvl = 0;
  1782. }
  1783. if (config.debug) {
  1784. this.audioLevelsMap[id] = newLvl;
  1785. if (config.debugAudioLevels) {
  1786. logger.log(`AudioLevel:${id}/${newLvl}`);
  1787. }
  1788. }
  1789. APP.UI.setAudioLevel(id, newLvl);
  1790. });
  1791. room.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED, (track, participantThatMutedUs) => {
  1792. if (participantThatMutedUs) {
  1793. APP.store.dispatch(participantMutedUs(participantThatMutedUs, track));
  1794. if (this.isSharingScreen && track.isVideoTrack()) {
  1795. logger.debug('TRACK_MUTE_CHANGED while screen sharing');
  1796. this._turnScreenSharingOff(false);
  1797. }
  1798. }
  1799. });
  1800. room.on(JitsiConferenceEvents.SUBJECT_CHANGED,
  1801. subject => APP.store.dispatch(conferenceSubjectChanged(subject)));
  1802. room.on(
  1803. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1804. (leavingIds, enteringIds) =>
  1805. APP.UI.handleLastNEndpoints(leavingIds, enteringIds));
  1806. room.on(
  1807. JitsiConferenceEvents.P2P_STATUS,
  1808. (jitsiConference, p2p) =>
  1809. APP.store.dispatch(p2pStatusChanged(p2p)));
  1810. room.on(
  1811. JitsiConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1812. (id, connectionStatus) => APP.store.dispatch(
  1813. participantConnectionStatusChanged(id, connectionStatus)));
  1814. room.on(
  1815. JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED,
  1816. (dominant, previous) => APP.store.dispatch(dominantSpeakerChanged(dominant, previous, room)));
  1817. room.on(
  1818. JitsiConferenceEvents.CONFERENCE_CREATED_TIMESTAMP,
  1819. conferenceTimestamp => APP.store.dispatch(conferenceTimestampChanged(conferenceTimestamp)));
  1820. room.on(JitsiConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1821. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1822. JitsiParticipantConnectionStatus.INTERRUPTED));
  1823. });
  1824. room.on(JitsiConferenceEvents.CONNECTION_RESTORED, () => {
  1825. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1826. JitsiParticipantConnectionStatus.ACTIVE));
  1827. });
  1828. room.on(
  1829. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1830. (id, displayName) => {
  1831. const formattedDisplayName
  1832. = getNormalizedDisplayName(displayName);
  1833. APP.store.dispatch(participantUpdated({
  1834. conference: room,
  1835. id,
  1836. name: formattedDisplayName
  1837. }));
  1838. APP.API.notifyDisplayNameChanged(id, {
  1839. displayName: formattedDisplayName,
  1840. formattedDisplayName:
  1841. appendSuffix(
  1842. formattedDisplayName
  1843. || interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME)
  1844. });
  1845. }
  1846. );
  1847. room.on(
  1848. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1849. (id, botType) => {
  1850. APP.store.dispatch(participantUpdated({
  1851. conference: room,
  1852. id,
  1853. botType
  1854. }));
  1855. }
  1856. );
  1857. room.on(
  1858. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1859. (...args) => {
  1860. APP.store.dispatch(endpointMessageReceived(...args));
  1861. if (args && args.length >= 2) {
  1862. const [ sender, eventData ] = args;
  1863. if (eventData.name === ENDPOINT_TEXT_MESSAGE_NAME) {
  1864. APP.API.notifyEndpointTextMessageReceived({
  1865. senderInfo: {
  1866. jid: sender._jid,
  1867. id: sender._id
  1868. },
  1869. eventData
  1870. });
  1871. }
  1872. }
  1873. });
  1874. room.on(
  1875. JitsiConferenceEvents.LOCK_STATE_CHANGED,
  1876. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1877. room.on(JitsiConferenceEvents.KICKED, (participant, reason, isReplaced) => {
  1878. if (isReplaced) {
  1879. // this event triggers when the local participant is kicked, `participant`
  1880. // is the kicker. In replace participant case, kicker is undefined,
  1881. // as the server initiated it. We mark in store the local participant
  1882. // as being replaced based on jwt.
  1883. const localParticipant = getLocalParticipant(APP.store.getState());
  1884. APP.store.dispatch(participantUpdated({
  1885. conference: room,
  1886. id: localParticipant.id,
  1887. isReplaced
  1888. }));
  1889. // we send readyToClose when kicked participant is replace so that
  1890. // embedding app can choose to dispose the iframe API on the handler.
  1891. APP.API.notifyReadyToClose();
  1892. }
  1893. APP.store.dispatch(kickedOut(room, participant));
  1894. });
  1895. room.on(JitsiConferenceEvents.PARTICIPANT_KICKED, (kicker, kicked) => {
  1896. APP.store.dispatch(participantKicked(kicker, kicked));
  1897. });
  1898. room.on(JitsiConferenceEvents.SUSPEND_DETECTED, () => {
  1899. APP.store.dispatch(suspendDetected());
  1900. });
  1901. APP.UI.addListener(UIEvents.AUDIO_MUTED, muted => {
  1902. this.muteAudio(muted);
  1903. });
  1904. APP.UI.addListener(UIEvents.VIDEO_MUTED, muted => {
  1905. this.muteVideo(muted);
  1906. });
  1907. room.addCommandListener(this.commands.defaults.ETHERPAD,
  1908. ({ value }) => {
  1909. APP.UI.initEtherpad(value);
  1910. }
  1911. );
  1912. APP.UI.addListener(UIEvents.EMAIL_CHANGED,
  1913. this.changeLocalEmail.bind(this));
  1914. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1915. APP.store.dispatch(participantUpdated({
  1916. conference: room,
  1917. id: from,
  1918. email: data.value
  1919. }));
  1920. });
  1921. room.addCommandListener(
  1922. this.commands.defaults.AVATAR_URL,
  1923. (data, from) => {
  1924. APP.store.dispatch(
  1925. participantUpdated({
  1926. conference: room,
  1927. id: from,
  1928. avatarURL: data.value
  1929. }));
  1930. });
  1931. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1932. this.changeLocalDisplayName.bind(this));
  1933. room.on(
  1934. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  1935. ({ audio, video }) => {
  1936. APP.store.dispatch(
  1937. onStartMutedPolicyChanged(audio, video));
  1938. }
  1939. );
  1940. room.on(JitsiConferenceEvents.STARTED_MUTED, () => {
  1941. const audioMuted = room.isStartAudioMuted();
  1942. const videoMuted = room.isStartVideoMuted();
  1943. const localTracks = getLocalTracks(APP.store.getState()['features/base/tracks']);
  1944. const promises = [];
  1945. APP.store.dispatch(setAudioMuted(audioMuted));
  1946. APP.store.dispatch(setVideoMuted(videoMuted));
  1947. // Remove the tracks from the peerconnection.
  1948. for (const track of localTracks) {
  1949. if (audioMuted && track.jitsiTrack?.getType() === MEDIA_TYPE.AUDIO) {
  1950. promises.push(this.useAudioStream(null));
  1951. }
  1952. if (videoMuted && track.jitsiTrack?.getType() === MEDIA_TYPE.VIDEO) {
  1953. promises.push(this.useVideoStream(null));
  1954. }
  1955. }
  1956. Promise.allSettled(promises)
  1957. .then(() => APP.UI.notifyInitiallyMuted());
  1958. });
  1959. room.on(
  1960. JitsiConferenceEvents.DATA_CHANNEL_OPENED, () => {
  1961. APP.store.dispatch(dataChannelOpened());
  1962. }
  1963. );
  1964. // call hangup
  1965. APP.UI.addListener(UIEvents.HANGUP, () => {
  1966. this.hangup(true);
  1967. });
  1968. // logout
  1969. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1970. AuthHandler.logout(room).then(url => {
  1971. if (url) {
  1972. UIUtil.redirect(url);
  1973. } else {
  1974. this.hangup(true);
  1975. }
  1976. });
  1977. });
  1978. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1979. AuthHandler.authenticate(room);
  1980. });
  1981. APP.UI.addListener(
  1982. UIEvents.VIDEO_DEVICE_CHANGED,
  1983. cameraDeviceId => {
  1984. const videoWasMuted = this.isLocalVideoMuted();
  1985. sendAnalytics(createDeviceChangedEvent('video', 'input'));
  1986. // If both screenshare and video are in progress, restart the
  1987. // presenter mode with the new camera device.
  1988. if (this.isSharingScreen && !videoWasMuted) {
  1989. const { height } = this.localVideo.track.getSettings();
  1990. // dispose the existing presenter track and create a new
  1991. // camera track.
  1992. // FIXME JitsiLocalTrack.dispose is async and should be waited for
  1993. this.localPresenterVideo && this.localPresenterVideo.dispose();
  1994. this.localPresenterVideo = null;
  1995. return this._createPresenterStreamEffect(height, cameraDeviceId)
  1996. .then(effect => this.localVideo.setEffect(effect))
  1997. .then(() => {
  1998. this.setVideoMuteStatus();
  1999. logger.log('Switched local video device while screen sharing and the video is unmuted');
  2000. this._updateVideoDeviceId();
  2001. })
  2002. .catch(err => APP.store.dispatch(notifyCameraError(err)));
  2003. // If screenshare is in progress but video is muted, update the default device
  2004. // id for video, dispose the existing presenter track and create a new effect
  2005. // that can be applied on un-mute.
  2006. } else if (this.isSharingScreen && videoWasMuted) {
  2007. logger.log('Switched local video device: while screen sharing and the video is muted');
  2008. const { height } = this.localVideo.track.getSettings();
  2009. this._updateVideoDeviceId();
  2010. // FIXME JitsiLocalTrack.dispose is async and should be waited for
  2011. this.localPresenterVideo && this.localPresenterVideo.dispose();
  2012. this.localPresenterVideo = null;
  2013. this._createPresenterStreamEffect(height, cameraDeviceId);
  2014. // if there is only video, switch to the new camera stream.
  2015. } else {
  2016. createLocalTracksF({
  2017. devices: [ 'video' ],
  2018. cameraDeviceId,
  2019. micDeviceId: null
  2020. })
  2021. .then(([ stream ]) => {
  2022. // if we are in audio only mode or video was muted before
  2023. // changing device, then mute
  2024. if (this.isAudioOnly() || videoWasMuted) {
  2025. return stream.mute()
  2026. .then(() => stream);
  2027. }
  2028. return stream;
  2029. })
  2030. .then(stream => {
  2031. logger.log('Switching the local video device.');
  2032. return this.useVideoStream(stream);
  2033. })
  2034. .then(() => {
  2035. logger.log('Switched local video device.');
  2036. this._updateVideoDeviceId();
  2037. })
  2038. .catch(error => {
  2039. logger.error(`Switching the local video device failed: ${error}`);
  2040. return APP.store.dispatch(notifyCameraError(error));
  2041. });
  2042. }
  2043. }
  2044. );
  2045. APP.UI.addListener(
  2046. UIEvents.AUDIO_DEVICE_CHANGED,
  2047. micDeviceId => {
  2048. const audioWasMuted = this.isLocalAudioMuted();
  2049. // When the 'default' mic needs to be selected, we need to
  2050. // pass the real device id to gUM instead of 'default' in order
  2051. // to get the correct MediaStreamTrack from chrome because of the
  2052. // following bug.
  2053. // https://bugs.chromium.org/p/chromium/issues/detail?id=997689
  2054. const hasDefaultMicChanged = micDeviceId === 'default';
  2055. sendAnalytics(createDeviceChangedEvent('audio', 'input'));
  2056. createLocalTracksF({
  2057. devices: [ 'audio' ],
  2058. cameraDeviceId: null,
  2059. micDeviceId: hasDefaultMicChanged
  2060. ? getDefaultDeviceId(APP.store.getState(), 'audioInput')
  2061. : micDeviceId
  2062. })
  2063. .then(([ stream ]) => {
  2064. // if audio was muted before changing the device, mute
  2065. // with the new device
  2066. if (audioWasMuted) {
  2067. return stream.mute()
  2068. .then(() => stream);
  2069. }
  2070. return stream;
  2071. })
  2072. .then(async stream => {
  2073. // In case screen sharing audio is also shared we mix it with new input stream. The old _mixerEffect
  2074. // will be cleaned up when the existing track is replaced.
  2075. if (this._mixerEffect) {
  2076. this._mixerEffect = new AudioMixerEffect(this._desktopAudioStream);
  2077. await stream.setEffect(this._mixerEffect);
  2078. }
  2079. return this.useAudioStream(stream);
  2080. })
  2081. .then(() => {
  2082. if (this.localAudio && hasDefaultMicChanged) {
  2083. // workaround for the default device to be shown as selected in the
  2084. // settings even when the real device id was passed to gUM because of the
  2085. // above mentioned chrome bug.
  2086. this.localAudio._realDeviceId = this.localAudio.deviceId = 'default';
  2087. }
  2088. logger.log(`switched local audio device: ${this.localAudio?.getDeviceId()}`);
  2089. this._updateAudioDeviceId();
  2090. })
  2091. .catch(err => {
  2092. APP.store.dispatch(notifyMicError(err));
  2093. });
  2094. }
  2095. );
  2096. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  2097. // FIXME On web video track is stored both in redux and in
  2098. // 'localVideo' field, video is attempted to be unmuted twice when
  2099. // turning off the audio only mode. This will crash the app with
  2100. // 'unmute operation is already in progress'.
  2101. // Because there's no logic in redux about creating new track in
  2102. // case unmute when not track exists the things have to go through
  2103. // muteVideo logic in such case.
  2104. const tracks = APP.store.getState()['features/base/tracks'];
  2105. const isTrackInRedux
  2106. = Boolean(
  2107. tracks.find(
  2108. track => track.jitsiTrack
  2109. && track.jitsiTrack.getType() === 'video'));
  2110. if (!isTrackInRedux) {
  2111. this.muteVideo(audioOnly);
  2112. }
  2113. // Immediately update the UI by having remote videos and the large
  2114. // video update themselves instead of waiting for some other event
  2115. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  2116. // There is no guarantee another event will trigger the update
  2117. // immediately and in all situations, for example because a remote
  2118. // participant is having connection trouble so no status changes.
  2119. const displayedUserId = APP.UI.getLargeVideoID();
  2120. if (displayedUserId) {
  2121. APP.UI.updateLargeVideo(displayedUserId, true);
  2122. }
  2123. });
  2124. APP.UI.addListener(
  2125. UIEvents.TOGGLE_SCREENSHARING, ({ enabled, audioOnly }) => {
  2126. this.toggleScreenSharing(enabled, { audioOnly });
  2127. }
  2128. );
  2129. },
  2130. /**
  2131. * Cleanups local conference on suspend.
  2132. */
  2133. onSuspendDetected() {
  2134. // After wake up, we will be in a state where conference is left
  2135. // there will be dialog shown to user.
  2136. // We do not want video/audio as we show an overlay and after it
  2137. // user need to rejoin or close, while waking up we can detect
  2138. // camera wakeup as a problem with device.
  2139. // We also do not care about device change, which happens
  2140. // on resume after suspending PC.
  2141. if (this.deviceChangeListener) {
  2142. JitsiMeetJS.mediaDevices.removeEventListener(
  2143. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2144. this.deviceChangeListener);
  2145. }
  2146. this.localVideo = null;
  2147. this.localAudio = null;
  2148. },
  2149. /**
  2150. * Callback invoked when the conference has been successfully joined.
  2151. * Initializes the UI and various other features.
  2152. *
  2153. * @private
  2154. * @returns {void}
  2155. */
  2156. _onConferenceJoined() {
  2157. APP.UI.initConference();
  2158. if (!config.disableShortcuts) {
  2159. APP.keyboardshortcut.init();
  2160. }
  2161. APP.store.dispatch(conferenceJoined(room));
  2162. },
  2163. /**
  2164. * Updates the list of current devices.
  2165. * @param {boolean} setDeviceListChangeHandler - Whether to add the deviceList change handlers.
  2166. * @private
  2167. * @returns {Promise}
  2168. */
  2169. _initDeviceList(setDeviceListChangeHandler = false) {
  2170. const { mediaDevices } = JitsiMeetJS;
  2171. if (mediaDevices.isDeviceListAvailable()
  2172. && mediaDevices.isDeviceChangeAvailable()) {
  2173. if (setDeviceListChangeHandler) {
  2174. this.deviceChangeListener = devices =>
  2175. window.setTimeout(() => this._onDeviceListChanged(devices), 0);
  2176. mediaDevices.addEventListener(
  2177. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2178. this.deviceChangeListener);
  2179. }
  2180. const { dispatch } = APP.store;
  2181. return dispatch(getAvailableDevices())
  2182. .then(devices => {
  2183. // Ugly way to synchronize real device IDs with local
  2184. // storage and settings menu. This is a workaround until
  2185. // getConstraints() method will be implemented in browsers.
  2186. this._updateAudioDeviceId();
  2187. this._updateVideoDeviceId();
  2188. APP.UI.onAvailableDevicesChanged(devices);
  2189. });
  2190. }
  2191. return Promise.resolve();
  2192. },
  2193. /**
  2194. * Updates the settings for the currently used video device, extracting
  2195. * the device id from the used track.
  2196. * @private
  2197. */
  2198. _updateVideoDeviceId() {
  2199. if (this.localVideo
  2200. && this.localVideo.videoType === 'camera') {
  2201. APP.store.dispatch(updateSettings({
  2202. cameraDeviceId: this.localVideo.getDeviceId()
  2203. }));
  2204. }
  2205. // If screenshare is in progress, get the device id from the presenter track.
  2206. if (this.localPresenterVideo) {
  2207. APP.store.dispatch(updateSettings({
  2208. cameraDeviceId: this.localPresenterVideo.getDeviceId()
  2209. }));
  2210. }
  2211. },
  2212. /**
  2213. * Updates the settings for the currently used audio device, extracting
  2214. * the device id from the used track.
  2215. * @private
  2216. */
  2217. _updateAudioDeviceId() {
  2218. if (this.localAudio) {
  2219. APP.store.dispatch(updateSettings({
  2220. micDeviceId: this.localAudio.getDeviceId()
  2221. }));
  2222. }
  2223. },
  2224. /**
  2225. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  2226. * handle change of available media devices.
  2227. * @private
  2228. * @param {MediaDeviceInfo[]} devices
  2229. * @returns {Promise}
  2230. */
  2231. _onDeviceListChanged(devices) {
  2232. const oldDevices = APP.store.getState()['features/base/devices'].availableDevices;
  2233. APP.store.dispatch(updateDeviceList(devices));
  2234. const newDevices
  2235. = mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  2236. devices,
  2237. this.isSharingScreen,
  2238. this.localVideo,
  2239. this.localAudio);
  2240. const promises = [];
  2241. const audioWasMuted = this.isLocalAudioMuted();
  2242. const videoWasMuted = this.isLocalVideoMuted();
  2243. const requestedInput = {
  2244. audio: Boolean(newDevices.audioinput),
  2245. video: Boolean(newDevices.videoinput)
  2246. };
  2247. if (typeof newDevices.audiooutput !== 'undefined') {
  2248. const { dispatch } = APP.store;
  2249. const setAudioOutputPromise
  2250. = setAudioOutputDeviceId(newDevices.audiooutput, dispatch)
  2251. .catch(); // Just ignore any errors in catch block.
  2252. promises.push(setAudioOutputPromise);
  2253. }
  2254. // Handles the use case when the default device is changed (we are always stopping the streams because it's
  2255. // simpler):
  2256. // If the default device is changed we need to first stop the local streams and then call GUM. Otherwise GUM
  2257. // will return a stream using the old default device.
  2258. if (requestedInput.audio && this.localAudio) {
  2259. this.localAudio.stopStream();
  2260. }
  2261. if (requestedInput.video && this.localVideo) {
  2262. this.localVideo.stopStream();
  2263. }
  2264. // Let's handle unknown/non-preferred devices
  2265. const newAvailDevices
  2266. = APP.store.getState()['features/base/devices'].availableDevices;
  2267. let newAudioDevices = [];
  2268. let oldAudioDevices = [];
  2269. if (typeof newDevices.audiooutput === 'undefined') {
  2270. newAudioDevices = newAvailDevices.audioOutput;
  2271. oldAudioDevices = oldDevices.audioOutput;
  2272. }
  2273. if (!requestedInput.audio) {
  2274. newAudioDevices = newAudioDevices.concat(newAvailDevices.audioInput);
  2275. oldAudioDevices = oldAudioDevices.concat(oldDevices.audioInput);
  2276. }
  2277. // check for audio
  2278. if (newAudioDevices.length > 0) {
  2279. APP.store.dispatch(
  2280. checkAndNotifyForNewDevice(newAudioDevices, oldAudioDevices));
  2281. }
  2282. // check for video
  2283. if (!requestedInput.video) {
  2284. APP.store.dispatch(
  2285. checkAndNotifyForNewDevice(newAvailDevices.videoInput, oldDevices.videoInput));
  2286. }
  2287. // When the 'default' mic needs to be selected, we need to
  2288. // pass the real device id to gUM instead of 'default' in order
  2289. // to get the correct MediaStreamTrack from chrome because of the
  2290. // following bug.
  2291. // https://bugs.chromium.org/p/chromium/issues/detail?id=997689
  2292. const hasDefaultMicChanged = newDevices.audioinput === 'default';
  2293. // This is the case when the local video is muted and a preferred device is connected.
  2294. if (requestedInput.video && this.isLocalVideoMuted()) {
  2295. // We want to avoid creating a new video track in order to prevent turning on the camera.
  2296. requestedInput.video = false;
  2297. APP.store.dispatch(updateSettings({ // Update the current selected camera for the device selection dialog.
  2298. cameraDeviceId: newDevices.videoinput
  2299. }));
  2300. delete newDevices.videoinput;
  2301. // Removing the current video track in order to force the unmute to select the preferred device.
  2302. logger.debug('_onDeviceListChanged: Removing the current video track.');
  2303. this.useVideoStream(null);
  2304. }
  2305. promises.push(
  2306. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  2307. createLocalTracksF,
  2308. newDevices.videoinput,
  2309. hasDefaultMicChanged
  2310. ? getDefaultDeviceId(APP.store.getState(), 'audioInput')
  2311. : newDevices.audioinput)
  2312. .then(tracks => {
  2313. // If audio or video muted before, or we unplugged current
  2314. // device and selected new one, then mute new track.
  2315. const muteSyncPromises = tracks.map(track => {
  2316. if ((track.isVideoTrack() && videoWasMuted)
  2317. || (track.isAudioTrack() && audioWasMuted)) {
  2318. return track.mute();
  2319. }
  2320. return Promise.resolve();
  2321. });
  2322. return Promise.all(muteSyncPromises)
  2323. .then(() =>
  2324. Promise.all(Object.keys(requestedInput).map(mediaType => {
  2325. if (requestedInput[mediaType]) {
  2326. const useStream
  2327. = mediaType === 'audio'
  2328. ? this.useAudioStream.bind(this)
  2329. : this.useVideoStream.bind(this);
  2330. // Use the new stream or null if we failed to obtain it.
  2331. return useStream(tracks.find(track => track.getType() === mediaType) || null)
  2332. .then(() => {
  2333. if (this.localAudio && hasDefaultMicChanged) {
  2334. // workaround for the default device to be shown as selected in the
  2335. // settings even when the real device id was passed to gUM because of
  2336. // the above mentioned chrome bug.
  2337. this.localAudio._realDeviceId = this.localAudio.deviceId = 'default';
  2338. }
  2339. mediaType === 'audio'
  2340. ? this._updateAudioDeviceId()
  2341. : this._updateVideoDeviceId();
  2342. });
  2343. }
  2344. return Promise.resolve();
  2345. })));
  2346. })
  2347. .then(() => {
  2348. // Log and sync known mute state.
  2349. if (audioWasMuted) {
  2350. sendAnalytics(createTrackMutedEvent(
  2351. 'audio',
  2352. 'device list changed'));
  2353. logger.log('Audio mute: device list changed');
  2354. muteLocalAudio(true);
  2355. }
  2356. if (!this.isSharingScreen && videoWasMuted) {
  2357. sendAnalytics(createTrackMutedEvent(
  2358. 'video',
  2359. 'device list changed'));
  2360. logger.log('Video mute: device list changed');
  2361. muteLocalVideo(true);
  2362. }
  2363. }));
  2364. return Promise.all(promises)
  2365. .then(() => {
  2366. APP.UI.onAvailableDevicesChanged(devices);
  2367. });
  2368. },
  2369. /**
  2370. * Determines whether or not the audio button should be enabled.
  2371. */
  2372. updateAudioIconEnabled() {
  2373. const audioMediaDevices
  2374. = APP.store.getState()['features/base/devices'].availableDevices.audioInput;
  2375. const audioDeviceCount
  2376. = audioMediaDevices ? audioMediaDevices.length : 0;
  2377. // The audio functionality is considered available if there are any
  2378. // audio devices detected or if the local audio stream already exists.
  2379. const available = audioDeviceCount > 0 || Boolean(this.localAudio);
  2380. APP.store.dispatch(setAudioAvailable(available));
  2381. APP.API.notifyAudioAvailabilityChanged(available);
  2382. },
  2383. /**
  2384. * Determines whether or not the video button should be enabled.
  2385. */
  2386. updateVideoIconEnabled() {
  2387. const videoMediaDevices
  2388. = APP.store.getState()['features/base/devices'].availableDevices.videoInput;
  2389. const videoDeviceCount
  2390. = videoMediaDevices ? videoMediaDevices.length : 0;
  2391. // The video functionality is considered available if there are any
  2392. // video devices detected or if there is local video stream already
  2393. // active which could be either screensharing stream or a video track
  2394. // created before the permissions were rejected (through browser
  2395. // config).
  2396. const available = videoDeviceCount > 0 || Boolean(this.localVideo);
  2397. APP.store.dispatch(setVideoAvailable(available));
  2398. APP.API.notifyVideoAvailabilityChanged(available);
  2399. },
  2400. /**
  2401. * Disconnect from the conference and optionally request user feedback.
  2402. * @param {boolean} [requestFeedback=false] if user feedback should be
  2403. * requested
  2404. */
  2405. hangup(requestFeedback = false) {
  2406. APP.store.dispatch(disableReceiver());
  2407. this._stopProxyConnection();
  2408. APP.store.dispatch(destroyLocalTracks());
  2409. this._localTracksInitialized = false;
  2410. this.localVideo = null;
  2411. this.localAudio = null;
  2412. // Remove unnecessary event listeners from firing callbacks.
  2413. if (this.deviceChangeListener) {
  2414. JitsiMeetJS.mediaDevices.removeEventListener(
  2415. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2416. this.deviceChangeListener);
  2417. }
  2418. APP.UI.removeAllListeners();
  2419. let requestFeedbackPromise;
  2420. if (requestFeedback) {
  2421. requestFeedbackPromise
  2422. = APP.store.dispatch(maybeOpenFeedbackDialog(room))
  2423. // false because the thank you dialog shouldn't be displayed
  2424. .catch(() => Promise.resolve(false));
  2425. } else {
  2426. requestFeedbackPromise = Promise.resolve(true);
  2427. }
  2428. Promise.all([
  2429. requestFeedbackPromise,
  2430. this.leaveRoomAndDisconnect()
  2431. ])
  2432. .then(values => {
  2433. this._room = undefined;
  2434. room = undefined;
  2435. /**
  2436. * Don't call {@code notifyReadyToClose} if the promotional page flag is set
  2437. * and let the page take care of sending the message, since there will be
  2438. * a redirect to the page regardlessly.
  2439. */
  2440. if (!interfaceConfig.SHOW_PROMOTIONAL_CLOSE_PAGE) {
  2441. APP.API.notifyReadyToClose();
  2442. }
  2443. APP.store.dispatch(maybeRedirectToWelcomePage(values[0]));
  2444. });
  2445. },
  2446. /**
  2447. * Leaves the room and calls JitsiConnection.disconnect.
  2448. *
  2449. * @returns {Promise}
  2450. */
  2451. leaveRoomAndDisconnect() {
  2452. APP.store.dispatch(conferenceWillLeave(room));
  2453. if (room && room.isJoined()) {
  2454. return room.leave().then(disconnect, disconnect);
  2455. }
  2456. return disconnect();
  2457. },
  2458. /**
  2459. * Changes the email for the local user
  2460. * @param email {string} the new email
  2461. */
  2462. changeLocalEmail(email = '') {
  2463. const localParticipant = getLocalParticipant(APP.store.getState());
  2464. const formattedEmail = String(email).trim();
  2465. if (formattedEmail === localParticipant.email) {
  2466. return;
  2467. }
  2468. const localId = localParticipant.id;
  2469. APP.store.dispatch(participantUpdated({
  2470. // XXX Only the local participant is allowed to update without
  2471. // stating the JitsiConference instance (i.e. participant property
  2472. // `conference` for a remote participant) because the local
  2473. // participant is uniquely identified by the very fact that there is
  2474. // only one local participant.
  2475. id: localId,
  2476. local: true,
  2477. email: formattedEmail
  2478. }));
  2479. APP.store.dispatch(updateSettings({
  2480. email: formattedEmail
  2481. }));
  2482. APP.API.notifyEmailChanged(localId, {
  2483. email: formattedEmail
  2484. });
  2485. sendData(commands.EMAIL, formattedEmail);
  2486. },
  2487. /**
  2488. * Changes the avatar url for the local user
  2489. * @param url {string} the new url
  2490. */
  2491. changeLocalAvatarUrl(url = '') {
  2492. const { avatarURL, id } = getLocalParticipant(APP.store.getState());
  2493. const formattedUrl = String(url).trim();
  2494. if (formattedUrl === avatarURL) {
  2495. return;
  2496. }
  2497. APP.store.dispatch(participantUpdated({
  2498. // XXX Only the local participant is allowed to update without
  2499. // stating the JitsiConference instance (i.e. participant property
  2500. // `conference` for a remote participant) because the local
  2501. // participant is uniquely identified by the very fact that there is
  2502. // only one local participant.
  2503. id,
  2504. local: true,
  2505. avatarURL: formattedUrl
  2506. }));
  2507. APP.store.dispatch(updateSettings({
  2508. avatarURL: formattedUrl
  2509. }));
  2510. sendData(commands.AVATAR_URL, url);
  2511. },
  2512. /**
  2513. * Sends a message via the data channel.
  2514. * @param {string} to the id of the endpoint that should receive the
  2515. * message. If "" - the message will be sent to all participants.
  2516. * @param {object} payload the payload of the message.
  2517. * @throws NetworkError or InvalidStateError or Error if the operation
  2518. * fails.
  2519. */
  2520. sendEndpointMessage(to, payload) {
  2521. room.sendEndpointMessage(to, payload);
  2522. },
  2523. /**
  2524. * Adds new listener.
  2525. * @param {String} eventName the name of the event
  2526. * @param {Function} listener the listener.
  2527. */
  2528. addListener(eventName, listener) {
  2529. eventEmitter.addListener(eventName, listener);
  2530. },
  2531. /**
  2532. * Removes listener.
  2533. * @param {String} eventName the name of the event that triggers the
  2534. * listener
  2535. * @param {Function} listener the listener.
  2536. */
  2537. removeListener(eventName, listener) {
  2538. eventEmitter.removeListener(eventName, listener);
  2539. },
  2540. /**
  2541. * Changes the display name for the local user
  2542. * @param nickname {string} the new display name
  2543. */
  2544. changeLocalDisplayName(nickname = '') {
  2545. const formattedNickname = getNormalizedDisplayName(nickname);
  2546. const { id, name } = getLocalParticipant(APP.store.getState());
  2547. if (formattedNickname === name) {
  2548. return;
  2549. }
  2550. APP.store.dispatch(participantUpdated({
  2551. // XXX Only the local participant is allowed to update without
  2552. // stating the JitsiConference instance (i.e. participant property
  2553. // `conference` for a remote participant) because the local
  2554. // participant is uniquely identified by the very fact that there is
  2555. // only one local participant.
  2556. id,
  2557. local: true,
  2558. name: formattedNickname
  2559. }));
  2560. APP.store.dispatch(updateSettings({
  2561. displayName: formattedNickname
  2562. }));
  2563. },
  2564. /**
  2565. * Callback invoked by the external api create or update a direct connection
  2566. * from the local client to an external client.
  2567. *
  2568. * @param {Object} event - The object containing information that should be
  2569. * passed to the {@code ProxyConnectionService}.
  2570. * @returns {void}
  2571. */
  2572. onProxyConnectionEvent(event) {
  2573. if (!this._proxyConnection) {
  2574. this._proxyConnection = new JitsiMeetJS.ProxyConnectionService({
  2575. /**
  2576. * Pass the {@code JitsiConnection} instance which will be used
  2577. * to fetch TURN credentials.
  2578. */
  2579. jitsiConnection: APP.connection,
  2580. /**
  2581. * The proxy connection feature is currently tailored towards
  2582. * taking a proxied video stream and showing it as a local
  2583. * desktop screen.
  2584. */
  2585. convertVideoToDesktop: true,
  2586. /**
  2587. * Callback invoked when the connection has been closed
  2588. * automatically. Triggers cleanup of screensharing if active.
  2589. *
  2590. * @returns {void}
  2591. */
  2592. onConnectionClosed: () => {
  2593. if (this._untoggleScreenSharing) {
  2594. this._untoggleScreenSharing();
  2595. }
  2596. },
  2597. /**
  2598. * Callback invoked to pass messages from the local client back
  2599. * out to the external client.
  2600. *
  2601. * @param {string} peerJid - The jid of the intended recipient
  2602. * of the message.
  2603. * @param {Object} data - The message that should be sent. For
  2604. * screensharing this is an iq.
  2605. * @returns {void}
  2606. */
  2607. onSendMessage: (peerJid, data) =>
  2608. APP.API.sendProxyConnectionEvent({
  2609. data,
  2610. to: peerJid
  2611. }),
  2612. /**
  2613. * Callback invoked when the remote peer of the proxy connection
  2614. * has provided a video stream, intended to be used as a local
  2615. * desktop stream.
  2616. *
  2617. * @param {JitsiLocalTrack} remoteProxyStream - The media
  2618. * stream to use as a local desktop stream.
  2619. * @returns {void}
  2620. */
  2621. onRemoteStream: desktopStream => {
  2622. if (desktopStream.videoType !== 'desktop') {
  2623. logger.warn('Received a non-desktop stream to proxy.');
  2624. desktopStream.dispose();
  2625. return;
  2626. }
  2627. this.toggleScreenSharing(undefined, { desktopStream });
  2628. }
  2629. });
  2630. }
  2631. this._proxyConnection.processMessage(event);
  2632. },
  2633. /**
  2634. * Sets the video muted status.
  2635. */
  2636. setVideoMuteStatus() {
  2637. APP.UI.setVideoMuted(this.getMyUserId());
  2638. },
  2639. /**
  2640. * Sets the audio muted status.
  2641. *
  2642. * @param {boolean} muted - New muted status.
  2643. */
  2644. setAudioMuteStatus(muted) {
  2645. APP.UI.setAudioMuted(this.getMyUserId(), muted);
  2646. APP.API.notifyAudioMutedStatusChanged(muted);
  2647. },
  2648. /**
  2649. * Dispatches the passed in feedback for submission. The submitted score
  2650. * should be a number inclusively between 1 through 5, or -1 for no score.
  2651. *
  2652. * @param {number} score - a number between 1 and 5 (inclusive) or -1 for no
  2653. * score.
  2654. * @param {string} message - An optional message to attach to the feedback
  2655. * in addition to the score.
  2656. * @returns {void}
  2657. */
  2658. submitFeedback(score = -1, message = '') {
  2659. if (score === -1 || (score >= 1 && score <= 5)) {
  2660. APP.store.dispatch(submitFeedback(score, message, room));
  2661. }
  2662. },
  2663. /**
  2664. * Terminates any proxy screensharing connection that is active.
  2665. *
  2666. * @private
  2667. * @returns {void}
  2668. */
  2669. _stopProxyConnection() {
  2670. if (this._proxyConnection) {
  2671. this._proxyConnection.stop();
  2672. }
  2673. this._proxyConnection = null;
  2674. }
  2675. };