modified lib-jitsi-meet dev repo
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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  1. /* global $,
  2. __filename,
  3. attachMediaStream,
  4. MediaStreamTrack,
  5. RTCIceCandidate: true,
  6. RTCPeerConnection,
  7. RTCSessionDescription: true,
  8. mozRTCIceCandidate,
  9. mozRTCPeerConnection,
  10. mozRTCSessionDescription,
  11. webkitMediaStream,
  12. webkitRTCPeerConnection,
  13. webkitURL
  14. */
  15. import CameraFacingMode from '../../service/RTC/CameraFacingMode';
  16. import EventEmitter from 'events';
  17. import { getLogger } from 'jitsi-meet-logger';
  18. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  19. import JitsiTrackError from '../../JitsiTrackError';
  20. import Listenable from '../util/Listenable';
  21. import * as MediaType from '../../service/RTC/MediaType';
  22. import Resolutions from '../../service/RTC/Resolutions';
  23. import RTCBrowserType from './RTCBrowserType';
  24. import RTCEvents from '../../service/RTC/RTCEvents';
  25. import screenObtainer from './ScreenObtainer';
  26. import SDPUtil from '../xmpp/SDPUtil';
  27. import VideoType from '../../service/RTC/VideoType';
  28. const logger = getLogger(__filename);
  29. // XXX Don't require Temasys unless it's to be used because it doesn't run on
  30. // React Native, for example.
  31. const AdapterJS
  32. = RTCBrowserType.isTemasysPluginUsed()
  33. ? require('./adapter.screenshare')
  34. : undefined;
  35. const eventEmitter = new EventEmitter();
  36. const AVAILABLE_DEVICES_POLL_INTERVAL_TIME = 3000; // ms
  37. const devices = {
  38. audio: false,
  39. video: false
  40. };
  41. // Currently audio output device change is supported only in Chrome and
  42. // default output always has 'default' device ID
  43. let audioOutputDeviceId = 'default'; // default device
  44. // whether user has explicitly set a device to use
  45. let audioOutputChanged = false;
  46. // Disables Acoustic Echo Cancellation
  47. let disableAEC = false;
  48. // Disables Noise Suppression
  49. let disableNS = false;
  50. const featureDetectionAudioEl = document.createElement('audio');
  51. const isAudioOutputDeviceChangeAvailable
  52. = typeof featureDetectionAudioEl.setSinkId !== 'undefined';
  53. let currentlyAvailableMediaDevices;
  54. /**
  55. * "rawEnumerateDevicesWithCallback" will be initialized only after WebRTC is
  56. * ready. Otherwise it is too early to assume that the devices listing is not
  57. * supported.
  58. */
  59. let rawEnumerateDevicesWithCallback;
  60. /**
  61. *
  62. */
  63. function initRawEnumerateDevicesWithCallback() {
  64. rawEnumerateDevicesWithCallback = navigator.mediaDevices
  65. && navigator.mediaDevices.enumerateDevices
  66. ? function(callback) {
  67. navigator.mediaDevices.enumerateDevices().then(
  68. callback,
  69. () => callback([]));
  70. }
  71. // Safari:
  72. // "ReferenceError: Can't find variable: MediaStreamTrack"
  73. // when Temasys plugin is not installed yet, have to delay this call
  74. // until WebRTC is ready.
  75. : MediaStreamTrack && MediaStreamTrack.getSources
  76. ? function(callback) {
  77. MediaStreamTrack.getSources(
  78. sources =>
  79. callback(sources.map(convertMediaStreamTrackSource)));
  80. }
  81. : undefined;
  82. }
  83. // TODO: currently no browser supports 'devicechange' event even in nightly
  84. // builds so no feature/browser detection is used at all. However in future this
  85. // should be changed to some expression. Progress on 'devicechange' event
  86. // implementation for Chrome/Opera/NWJS can be tracked at
  87. // https://bugs.chromium.org/p/chromium/issues/detail?id=388648, for Firefox -
  88. // at https://bugzilla.mozilla.org/show_bug.cgi?id=1152383. More information on
  89. // 'devicechange' event can be found in spec -
  90. // http://w3c.github.io/mediacapture-main/#event-mediadevices-devicechange
  91. // TODO: check MS Edge
  92. const isDeviceChangeEventSupported = false;
  93. let rtcReady = false;
  94. /**
  95. *
  96. * @param constraints
  97. * @param resolution
  98. */
  99. function setResolutionConstraints(
  100. constraints, isNewStyleConstraintsSupported, resolution) {
  101. if (Resolutions[resolution]) {
  102. if (isNewStyleConstraintsSupported) {
  103. constraints.video.width = {
  104. exact: Resolutions[resolution].width
  105. };
  106. constraints.video.height = {
  107. exact: Resolutions[resolution].height
  108. };
  109. }
  110. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  111. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  112. }
  113. if (constraints.video.mandatory.minWidth) {
  114. constraints.video.mandatory.maxWidth
  115. = constraints.video.mandatory.minWidth;
  116. }
  117. if (constraints.video.mandatory.minHeight) {
  118. constraints.video.mandatory.maxHeight
  119. = constraints.video.mandatory.minHeight;
  120. }
  121. }
  122. /**
  123. * @param {string[]} um required user media types
  124. *
  125. * @param {Object} [options={}] optional parameters
  126. * @param {string} options.resolution
  127. * @param {number} options.bandwidth
  128. * @param {number} options.fps
  129. * @param {string} options.desktopStream
  130. * @param {string} options.cameraDeviceId
  131. * @param {string} options.micDeviceId
  132. * @param {CameraFacingMode} options.facingMode
  133. * @param {bool} firefox_fake_device
  134. */
  135. function getConstraints(um, options) {
  136. const constraints = { audio: false,
  137. video: false };
  138. // Don't mix new and old style settings for Chromium as this leads
  139. // to TypeError in new Chromium versions. @see
  140. // https://bugs.chromium.org/p/chromium/issues/detail?id=614716
  141. // This is a temporary solution, in future we will fully split old and
  142. // new style constraints when new versions of Chromium and Firefox will
  143. // have stable support of new constraints format. For more information
  144. // @see https://github.com/jitsi/lib-jitsi-meet/pull/136
  145. const isNewStyleConstraintsSupported
  146. = RTCBrowserType.isFirefox()
  147. || RTCBrowserType.isEdge()
  148. || RTCBrowserType.isReactNative()
  149. || RTCBrowserType.isTemasysPluginUsed();
  150. if (um.indexOf('video') >= 0) {
  151. // same behaviour as true
  152. constraints.video = { mandatory: {},
  153. optional: [] };
  154. if (options.cameraDeviceId) {
  155. if (isNewStyleConstraintsSupported) {
  156. // New style of setting device id.
  157. constraints.video.deviceId = options.cameraDeviceId;
  158. }
  159. // Old style.
  160. constraints.video.optional.push({
  161. sourceId: options.cameraDeviceId
  162. });
  163. } else {
  164. // Prefer the front i.e. user-facing camera (to the back i.e.
  165. // environment-facing camera, for example).
  166. // TODO: Maybe use "exact" syntax if options.facingMode is defined,
  167. // but this probably needs to be decided when updating other
  168. // constraints, as we currently don't use "exact" syntax anywhere.
  169. const facingMode = options.facingMode || CameraFacingMode.USER;
  170. if (isNewStyleConstraintsSupported) {
  171. constraints.video.facingMode = facingMode;
  172. }
  173. constraints.video.optional.push({
  174. facingMode
  175. });
  176. }
  177. if (options.minFps || options.maxFps || options.fps) {
  178. // for some cameras it might be necessary to request 30fps
  179. // so they choose 30fps mjpg over 10fps yuy2
  180. if (options.minFps || options.fps) {
  181. // Fall back to options.fps for backwards compatibility
  182. options.minFps = options.minFps || options.fps;
  183. constraints.video.mandatory.minFrameRate = options.minFps;
  184. }
  185. if (options.maxFps) {
  186. constraints.video.mandatory.maxFrameRate = options.maxFps;
  187. }
  188. }
  189. setResolutionConstraints(
  190. constraints, isNewStyleConstraintsSupported, options.resolution);
  191. }
  192. if (um.indexOf('audio') >= 0) {
  193. if (RTCBrowserType.isReactNative()) {
  194. // The react-native-webrtc project that we're currently using
  195. // expects the audio constraint to be a boolean.
  196. constraints.audio = true;
  197. } else if (RTCBrowserType.isFirefox()) {
  198. if (options.micDeviceId) {
  199. constraints.audio = {
  200. mandatory: {},
  201. deviceId: options.micDeviceId, // new style
  202. optional: [ {
  203. sourceId: options.micDeviceId // old style
  204. } ] };
  205. } else {
  206. constraints.audio = true;
  207. }
  208. } else {
  209. // same behaviour as true
  210. constraints.audio = { mandatory: {},
  211. optional: [] };
  212. if (options.micDeviceId) {
  213. if (isNewStyleConstraintsSupported) {
  214. // New style of setting device id.
  215. constraints.audio.deviceId = options.micDeviceId;
  216. }
  217. // Old style.
  218. constraints.audio.optional.push({
  219. sourceId: options.micDeviceId
  220. });
  221. }
  222. // if it is good enough for hangouts...
  223. constraints.audio.optional.push(
  224. { googEchoCancellation: !disableAEC },
  225. { googAutoGainControl: true },
  226. { googNoiseSupression: !disableNS },
  227. { googHighpassFilter: true },
  228. { googNoiseSuppression2: !disableNS },
  229. { googEchoCancellation2: !disableAEC },
  230. { googAutoGainControl2: true }
  231. );
  232. }
  233. }
  234. if (um.indexOf('screen') >= 0) {
  235. if (RTCBrowserType.isChrome()) {
  236. constraints.video = {
  237. mandatory: {
  238. chromeMediaSource: 'screen',
  239. maxWidth: window.screen.width,
  240. maxHeight: window.screen.height,
  241. maxFrameRate: 3
  242. },
  243. optional: []
  244. };
  245. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  246. constraints.video = {
  247. optional: [
  248. {
  249. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  250. }
  251. ]
  252. };
  253. } else if (RTCBrowserType.isFirefox()) {
  254. constraints.video = {
  255. mozMediaSource: 'window',
  256. mediaSource: 'window'
  257. };
  258. } else {
  259. const errmsg
  260. = '\'screen\' WebRTC media source is supported only in Chrome'
  261. + ' and with Temasys plugin';
  262. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  263. logger.error(errmsg);
  264. }
  265. }
  266. if (um.indexOf('desktop') >= 0) {
  267. constraints.video = {
  268. mandatory: {
  269. chromeMediaSource: 'desktop',
  270. chromeMediaSourceId: options.desktopStream,
  271. maxWidth: window.screen.width,
  272. maxHeight: window.screen.height,
  273. maxFrameRate: 3
  274. },
  275. optional: []
  276. };
  277. }
  278. if (options.bandwidth) {
  279. if (!constraints.video) {
  280. // same behaviour as true
  281. constraints.video = { mandatory: {},
  282. optional: [] };
  283. }
  284. constraints.video.optional.push({ bandwidth: options.bandwidth });
  285. }
  286. // we turn audio for both audio and video tracks, the fake audio & video
  287. // seems to work only when enabled in one getUserMedia call, we cannot get
  288. // fake audio separate by fake video this later can be a problem with some
  289. // of the tests
  290. if (RTCBrowserType.isFirefox() && options.firefox_fake_device) {
  291. // seems to be fixed now, removing this experimental fix, as having
  292. // multiple audio tracks brake the tests
  293. // constraints.audio = true;
  294. constraints.fake = true;
  295. }
  296. return constraints;
  297. }
  298. /**
  299. * Sets the availbale devices based on the options we requested and the
  300. * streams we received.
  301. * @param um the options we requested to getUserMedia.
  302. * @param stream the stream we received from calling getUserMedia.
  303. */
  304. function setAvailableDevices(um, stream) {
  305. const audioTracksReceived = stream && stream.getAudioTracks().length > 0;
  306. const videoTracksReceived = stream && stream.getVideoTracks().length > 0;
  307. if (um.indexOf('video') !== -1) {
  308. devices.video = videoTracksReceived;
  309. }
  310. if (um.indexOf('audio') !== -1) {
  311. devices.audio = audioTracksReceived;
  312. }
  313. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  314. }
  315. /**
  316. * Checks if new list of available media devices differs from previous one.
  317. * @param {MediaDeviceInfo[]} newDevices - list of new devices.
  318. * @returns {boolean} - true if list is different, false otherwise.
  319. */
  320. function compareAvailableMediaDevices(newDevices) {
  321. if (newDevices.length !== currentlyAvailableMediaDevices.length) {
  322. return true;
  323. }
  324. return (
  325. newDevices
  326. .map(mediaDeviceInfoToJSON)
  327. .sort()
  328. .join('')
  329. !== currentlyAvailableMediaDevices
  330. .map(mediaDeviceInfoToJSON)
  331. .sort()
  332. .join(''));
  333. /**
  334. *
  335. * @param info
  336. */
  337. function mediaDeviceInfoToJSON(info) {
  338. return JSON.stringify({
  339. kind: info.kind,
  340. deviceId: info.deviceId,
  341. groupId: info.groupId,
  342. label: info.label,
  343. facing: info.facing
  344. });
  345. }
  346. }
  347. /**
  348. * Periodically polls enumerateDevices() method to check if list of media
  349. * devices has changed. This is temporary workaround until 'devicechange' event
  350. * will be supported by browsers.
  351. */
  352. function pollForAvailableMediaDevices() {
  353. // Here we use plain navigator.mediaDevices.enumerateDevices instead of
  354. // wrapped because we just need to know the fact the devices changed, labels
  355. // do not matter. This fixes situation when we have no devices initially,
  356. // and then plug in a new one.
  357. if (rawEnumerateDevicesWithCallback) {
  358. rawEnumerateDevicesWithCallback(ds => {
  359. // We don't fire RTCEvents.DEVICE_LIST_CHANGED for the first time
  360. // we call enumerateDevices(). This is the initial step.
  361. if (typeof currentlyAvailableMediaDevices === 'undefined') {
  362. currentlyAvailableMediaDevices = ds.slice(0);
  363. } else if (compareAvailableMediaDevices(ds)) {
  364. onMediaDevicesListChanged(ds);
  365. }
  366. window.setTimeout(pollForAvailableMediaDevices,
  367. AVAILABLE_DEVICES_POLL_INTERVAL_TIME);
  368. });
  369. }
  370. }
  371. /**
  372. * Event handler for the 'devicechange' event.
  373. *
  374. * @param {MediaDeviceInfo[]} devices - list of media devices.
  375. * @emits RTCEvents.DEVICE_LIST_CHANGED
  376. */
  377. function onMediaDevicesListChanged(devicesReceived) {
  378. currentlyAvailableMediaDevices = devicesReceived.slice(0);
  379. logger.info(
  380. 'list of media devices has changed:',
  381. currentlyAvailableMediaDevices);
  382. const videoInputDevices
  383. = currentlyAvailableMediaDevices.filter(d => d.kind === 'videoinput');
  384. const audioInputDevices
  385. = currentlyAvailableMediaDevices.filter(d => d.kind === 'audioinput');
  386. const videoInputDevicesWithEmptyLabels
  387. = videoInputDevices.filter(d => d.label === '');
  388. const audioInputDevicesWithEmptyLabels
  389. = audioInputDevices.filter(d => d.label === '');
  390. if (videoInputDevices.length
  391. && videoInputDevices.length
  392. === videoInputDevicesWithEmptyLabels.length) {
  393. devices.video = false;
  394. }
  395. if (audioInputDevices.length
  396. && audioInputDevices.length
  397. === audioInputDevicesWithEmptyLabels.length) {
  398. devices.audio = false;
  399. }
  400. eventEmitter.emit(RTCEvents.DEVICE_LIST_CHANGED, devicesReceived);
  401. }
  402. /**
  403. * Apply function with arguments if function exists.
  404. * Do nothing if function not provided.
  405. * @param {function} [fn] function to apply
  406. * @param {Array} [args=[]] arguments for function
  407. */
  408. function maybeApply(fn, args) {
  409. fn && fn(...args);
  410. }
  411. const getUserMediaStatus = {
  412. initialized: false,
  413. callbacks: []
  414. };
  415. /**
  416. * Wrap `getUserMedia` to allow others to know if it was executed at least
  417. * once or not. Wrapper function uses `getUserMediaStatus` object.
  418. * @param {Function} getUserMedia native function
  419. * @returns {Function} wrapped function
  420. */
  421. function wrapGetUserMedia(getUserMedia, usePromises = false) {
  422. let gUM;
  423. if (usePromises) {
  424. gUM = function(constraints, successCallback, errorCallback) {
  425. return getUserMedia(constraints)
  426. .then(stream => {
  427. maybeApply(successCallback, [ stream ]);
  428. if (!getUserMediaStatus.initialized) {
  429. getUserMediaStatus.initialized = true;
  430. getUserMediaStatus.callbacks.forEach(
  431. callback => callback());
  432. getUserMediaStatus.callbacks.length = 0;
  433. }
  434. return stream;
  435. })
  436. .catch(error => {
  437. maybeApply(errorCallback, [ error ]);
  438. throw error;
  439. });
  440. };
  441. } else {
  442. gUM = function(constraints, successCallback, errorCallback) {
  443. getUserMedia(constraints, stream => {
  444. maybeApply(successCallback, [ stream ]);
  445. if (!getUserMediaStatus.initialized) {
  446. getUserMediaStatus.initialized = true;
  447. getUserMediaStatus.callbacks.forEach(
  448. callback => callback());
  449. getUserMediaStatus.callbacks.length = 0;
  450. }
  451. }, error => {
  452. maybeApply(errorCallback, [ error ]);
  453. });
  454. };
  455. }
  456. return gUM;
  457. }
  458. /**
  459. * Execute function after getUserMedia was executed at least once.
  460. * @param {Function} callback function to execute after getUserMedia
  461. */
  462. function afterUserMediaInitialized(callback) {
  463. if (getUserMediaStatus.initialized) {
  464. callback();
  465. } else {
  466. getUserMediaStatus.callbacks.push(callback);
  467. }
  468. }
  469. /**
  470. * Wrapper function which makes enumerateDevices to wait
  471. * until someone executes getUserMedia first time.
  472. * @param {Function} enumerateDevices native function
  473. * @returns {Funtion} wrapped function
  474. */
  475. function wrapEnumerateDevices(enumerateDevices) {
  476. return function(callback) {
  477. // enumerate devices only after initial getUserMedia
  478. afterUserMediaInitialized(() => {
  479. enumerateDevices().then(callback, err => {
  480. logger.error('cannot enumerate devices: ', err);
  481. callback([]);
  482. });
  483. });
  484. };
  485. }
  486. /**
  487. * Use old MediaStreamTrack to get devices list and
  488. * convert it to enumerateDevices format.
  489. * @param {Function} callback function to call when received devices list.
  490. */
  491. function enumerateDevicesThroughMediaStreamTrack(callback) {
  492. MediaStreamTrack.getSources(
  493. sources => callback(sources.map(convertMediaStreamTrackSource)));
  494. }
  495. /**
  496. * Converts MediaStreamTrack Source to enumerateDevices format.
  497. * @param {Object} source
  498. */
  499. function convertMediaStreamTrackSource(source) {
  500. const kind = (source.kind || '').toLowerCase();
  501. return {
  502. facing: source.facing || null,
  503. label: source.label,
  504. // theoretically deprecated MediaStreamTrack.getSources should
  505. // not return 'audiooutput' devices but let's handle it in any
  506. // case
  507. kind: kind
  508. ? kind === 'audiooutput' ? kind : `${kind}input`
  509. : null,
  510. deviceId: source.id,
  511. groupId: source.groupId || null
  512. };
  513. }
  514. /**
  515. * Handles the newly created Media Streams.
  516. * @param streams the new Media Streams
  517. * @param resolution the resolution of the video streams
  518. * @returns {*[]} object that describes the new streams
  519. */
  520. function handleLocalStream(streams, resolution) {
  521. let audioStream, desktopStream, videoStream;
  522. const res = [];
  523. // XXX The function obtainAudioAndVideoPermissions has examined the type of
  524. // the browser, its capabilities, etc. and has taken the decision whether to
  525. // invoke getUserMedia per device (e.g. Firefox) or once for both audio and
  526. // video (e.g. Chrome). In order to not duplicate the logic here, examine
  527. // the specified streams and figure out what we've received based on
  528. // obtainAudioAndVideoPermissions' decision.
  529. if (streams) {
  530. // As mentioned above, certian types of browser (e.g. Chrome) support
  531. // (with a result which meets our requirements expressed bellow) calling
  532. // getUserMedia once for both audio and video.
  533. const audioVideo = streams.audioVideo;
  534. if (audioVideo) {
  535. const NativeMediaStream
  536. = window.webkitMediaStream || window.MediaStream;
  537. const audioTracks = audioVideo.getAudioTracks();
  538. if (audioTracks.length) {
  539. // eslint-disable-next-line new-cap
  540. audioStream = new NativeMediaStream();
  541. for (let i = 0; i < audioTracks.length; i++) {
  542. audioStream.addTrack(audioTracks[i]);
  543. }
  544. }
  545. const videoTracks = audioVideo.getVideoTracks();
  546. if (videoTracks.length) {
  547. // eslint-disable-next-line new-cap
  548. videoStream = new NativeMediaStream();
  549. for (let j = 0; j < videoTracks.length; j++) {
  550. videoStream.addTrack(videoTracks[j]);
  551. }
  552. }
  553. } else {
  554. // On other types of browser (e.g. Firefox) we choose (namely,
  555. // obtainAudioAndVideoPermissions) to call getUserMedia per device
  556. // (type).
  557. audioStream = streams.audio;
  558. videoStream = streams.video;
  559. }
  560. // Again, different choices on different types of browser.
  561. desktopStream = streams.desktopStream || streams.desktop;
  562. }
  563. if (desktopStream) {
  564. res.push({
  565. stream: desktopStream,
  566. track: desktopStream.getVideoTracks()[0],
  567. mediaType: MediaType.VIDEO,
  568. videoType: VideoType.DESKTOP
  569. });
  570. }
  571. if (audioStream) {
  572. res.push({
  573. stream: audioStream,
  574. track: audioStream.getAudioTracks()[0],
  575. mediaType: MediaType.AUDIO,
  576. videoType: null
  577. });
  578. }
  579. if (videoStream) {
  580. res.push({
  581. stream: videoStream,
  582. track: videoStream.getVideoTracks()[0],
  583. mediaType: MediaType.VIDEO,
  584. videoType: VideoType.CAMERA,
  585. resolution
  586. });
  587. }
  588. return res;
  589. }
  590. /**
  591. * Represents a default implementation of setting a <tt>MediaStream</tt> as the
  592. * source of a video element that tries to be browser-agnostic through feature
  593. * checking. Note though that it was not completely clear from the predating
  594. * browser-specific implementations what &quot;videoSrc&quot; was because one
  595. * implementation of {@link RTCUtils#getVideoSrc} would return
  596. * <tt>MediaStream</tt> (e.g. Firefox), another a <tt>string</tt> representation
  597. * of the <tt>URL</tt> of the <tt>MediaStream</tt> (e.g. Chrome) and the return
  598. * value was only used by {@link RTCUIHelper#getVideoId} which itself did not
  599. * appear to be used anywhere. Generally, the implementation will try to follow
  600. * the related standards i.e. work with the <tt>srcObject</tt> and <tt>src</tt>
  601. * properties of the specified <tt>element</tt> taking into account vender
  602. * prefixes.
  603. *
  604. * @param element the element whose video source/src is to be set to the
  605. * specified <tt>stream</tt>
  606. * @param {MediaStream} stream the <tt>MediaStream</tt> to set as the video
  607. * source/src of <tt>element</tt>
  608. */
  609. function defaultSetVideoSrc(element, stream) {
  610. // srcObject
  611. let srcObjectPropertyName = 'srcObject';
  612. if (!(srcObjectPropertyName in element)) {
  613. srcObjectPropertyName = 'mozSrcObject';
  614. if (!(srcObjectPropertyName in element)) {
  615. srcObjectPropertyName = null;
  616. }
  617. }
  618. if (srcObjectPropertyName) {
  619. element[srcObjectPropertyName] = stream;
  620. return;
  621. }
  622. // src
  623. let src;
  624. if (stream) {
  625. src = stream.jitsiObjectURL;
  626. // Save the created URL for stream so we can reuse it and not keep
  627. // creating URLs.
  628. if (!src) {
  629. stream.jitsiObjectURL
  630. = src
  631. = (URL || webkitURL).createObjectURL(stream);
  632. }
  633. }
  634. element.src = src || '';
  635. }
  636. /**
  637. *
  638. */
  639. class RTCUtils extends Listenable {
  640. /**
  641. *
  642. */
  643. constructor() {
  644. super(eventEmitter);
  645. }
  646. /**
  647. *
  648. * @param options
  649. */
  650. init(options) {
  651. if (typeof options.disableAEC === 'boolean') {
  652. disableAEC = options.disableAEC;
  653. logger.info(`Disable AEC: ${disableAEC}`);
  654. }
  655. if (typeof options.disableNS === 'boolean') {
  656. disableNS = options.disableNS;
  657. logger.info(`Disable NS: ${disableNS}`);
  658. }
  659. return new Promise((resolve, reject) => {
  660. if (RTCBrowserType.isFirefox()) {
  661. const FFversion = RTCBrowserType.getFirefoxVersion();
  662. if (FFversion < 40) {
  663. rejectWithWebRTCNotSupported(
  664. `Firefox version too old: ${FFversion}.`
  665. + ' Required >= 40.',
  666. reject);
  667. return;
  668. }
  669. this.RTCPeerConnectionType = mozRTCPeerConnection;
  670. this.getUserMedia
  671. = wrapGetUserMedia(
  672. navigator.mozGetUserMedia.bind(navigator));
  673. this.enumerateDevices
  674. = wrapEnumerateDevices(
  675. navigator.mediaDevices.enumerateDevices.bind(
  676. navigator.mediaDevices));
  677. this.pcConstraints = {};
  678. this.attachMediaStream
  679. = wrapAttachMediaStream((element, stream) => {
  680. // srcObject is being standardized and FF will
  681. // eventually support that unprefixed. FF also supports
  682. // the "element.src = URL.createObjectURL(...)" combo,
  683. // but that will be deprecated in favour of srcObject.
  684. //
  685. // https://groups.google.com/forum/#!topic/
  686. // mozilla.dev.media/pKOiioXonJg
  687. // https://github.com/webrtc/samples/issues/302
  688. if (element) {
  689. defaultSetVideoSrc(element, stream);
  690. if (stream) {
  691. element.play();
  692. }
  693. }
  694. return element;
  695. });
  696. this.getStreamID = function(stream) {
  697. let id = stream.id;
  698. if (!id) {
  699. let tracks = stream.getVideoTracks();
  700. if (!tracks || tracks.length === 0) {
  701. tracks = stream.getAudioTracks();
  702. }
  703. id = tracks[0].id;
  704. }
  705. return SDPUtil.filterSpecialChars(id);
  706. };
  707. /* eslint-disable no-global-assign, no-native-reassign */
  708. RTCSessionDescription = mozRTCSessionDescription;
  709. RTCIceCandidate = mozRTCIceCandidate;
  710. /* eslint-enable no-global-assign, no-native-reassign */
  711. } else if (RTCBrowserType.isChrome()
  712. || RTCBrowserType.isOpera()
  713. || RTCBrowserType.isNWJS()
  714. || RTCBrowserType.isElectron()
  715. || RTCBrowserType.isReactNative()) {
  716. this.RTCPeerConnectionType = webkitRTCPeerConnection;
  717. const getUserMedia
  718. = navigator.webkitGetUserMedia.bind(navigator);
  719. if (navigator.mediaDevices) {
  720. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  721. this.enumerateDevices
  722. = wrapEnumerateDevices(
  723. navigator.mediaDevices.enumerateDevices.bind(
  724. navigator.mediaDevices));
  725. } else {
  726. this.getUserMedia = getUserMedia;
  727. this.enumerateDevices
  728. = enumerateDevicesThroughMediaStreamTrack;
  729. }
  730. this.attachMediaStream
  731. = wrapAttachMediaStream((element, stream) => {
  732. defaultSetVideoSrc(element, stream);
  733. return element;
  734. });
  735. this.getStreamID = function(stream) {
  736. // A. MediaStreams from FF endpoints have the characters '{'
  737. // and '}' that make jQuery choke.
  738. // B. The react-native-webrtc implementation that we use on
  739. // React Native at the time of this writing returns a number
  740. // for the id of MediaStream. Let's just say that a number
  741. // contains no special characters.
  742. const id = stream.id;
  743. // XXX The return statement is affected by automatic
  744. // semicolon insertion (ASI). No line terminator is allowed
  745. // between the return keyword and the expression.
  746. return (
  747. typeof id === 'number'
  748. ? id
  749. : SDPUtil.filterSpecialChars(id));
  750. };
  751. this.pcConstraints = { optional: [] };
  752. // Allows sending of video to be suspended if the bandwidth
  753. // estimation is too low.
  754. if (!options.disableSuspendVideo) {
  755. this.pcConstraints.optional.push(
  756. { googSuspendBelowMinBitrate: true });
  757. }
  758. if (options.useIPv6) {
  759. // https://code.google.com/p/webrtc/issues/detail?id=2828
  760. this.pcConstraints.optional.push({ googIPv6: true });
  761. }
  762. if (!webkitMediaStream.prototype.getVideoTracks) {
  763. webkitMediaStream.prototype.getVideoTracks = function() {
  764. return this.videoTracks;
  765. };
  766. }
  767. if (!webkitMediaStream.prototype.getAudioTracks) {
  768. webkitMediaStream.prototype.getAudioTracks = function() {
  769. return this.audioTracks;
  770. };
  771. }
  772. } else if (RTCBrowserType.isEdge()) {
  773. // TODO: Remove when EDGE is fully supported. For now ensure
  774. // that, if EDGE is detected, it's just unsupported.
  775. if (RTCBrowserType.isEdge()) {
  776. rejectWithWebRTCNotSupported(
  777. 'Microsoft EDGE not yet supported', reject);
  778. return;
  779. }
  780. // TODO: Uncomment when done. For now use the Edge native
  781. // RTCPeerConnection.
  782. // this.RTCPeerConnectionType = ortcRTCPeerConnection;
  783. this.RTCPeerConnectionType = RTCPeerConnection;
  784. this.getUserMedia
  785. = wrapGetUserMedia(
  786. navigator.mediaDevices.getUserMedia.bind(
  787. navigator.mediaDevices),
  788. true);
  789. this.enumerateDevices
  790. = wrapEnumerateDevices(
  791. navigator.mediaDevices.enumerateDevices.bind(
  792. navigator.mediaDevices));
  793. this.attachMediaStream
  794. = wrapAttachMediaStream((element, stream) => {
  795. defaultSetVideoSrc(element, stream);
  796. return element;
  797. });
  798. // TODO: needed in Edge?
  799. this.getStreamID = function(stream) {
  800. const id = stream.id;
  801. return (
  802. typeof id === 'number'
  803. ? id
  804. : SDPUtil.filterSpecialChars(id));
  805. };
  806. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  807. // Detect IE/Safari
  808. const webRTCReadyCb = () => {
  809. this.RTCPeerConnectionType = RTCPeerConnection;
  810. this.getUserMedia = window.getUserMedia;
  811. this.enumerateDevices
  812. = enumerateDevicesThroughMediaStreamTrack;
  813. this.attachMediaStream
  814. = wrapAttachMediaStream((element, stream) => {
  815. if (stream) {
  816. if (stream.id === 'dummyAudio'
  817. || stream.id === 'dummyVideo') {
  818. return;
  819. }
  820. // The container must be visible in order to
  821. // play or attach the stream when Temasys plugin
  822. // is in use
  823. const containerSel = $(element);
  824. if (RTCBrowserType.isTemasysPluginUsed()
  825. && !containerSel.is(':visible')) {
  826. containerSel.show();
  827. }
  828. const video
  829. = stream.getVideoTracks().length > 0;
  830. if (video && !$(element).is(':visible')) {
  831. throw new Error(
  832. 'video element must be visible to'
  833. + ' attach video stream');
  834. }
  835. }
  836. return attachMediaStream(element, stream);
  837. });
  838. this.getStreamID
  839. = stream => SDPUtil.filterSpecialChars(stream.label);
  840. onReady(
  841. options,
  842. this.getUserMediaWithConstraints.bind(this));
  843. };
  844. const webRTCReadyPromise
  845. = new Promise(r => AdapterJS.webRTCReady(r));
  846. // Resolve or reject depending on whether the Temasys plugin is
  847. // installed.
  848. AdapterJS.WebRTCPlugin.isPluginInstalled(
  849. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  850. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  851. AdapterJS.WebRTCPlugin.pluginInfo.type,
  852. /* installed */ () => {
  853. webRTCReadyPromise.then(() => {
  854. webRTCReadyCb();
  855. resolve();
  856. });
  857. },
  858. /* not installed */ () => {
  859. const error
  860. = new Error('Temasys plugin is not installed');
  861. error.name = 'WEBRTC_NOT_READY';
  862. error.webRTCReadyPromise = webRTCReadyPromise;
  863. reject(error);
  864. });
  865. } else {
  866. rejectWithWebRTCNotSupported(
  867. 'Browser does not appear to be WebRTC-capable',
  868. reject);
  869. return;
  870. }
  871. // Call onReady() if Temasys plugin is not used
  872. if (!RTCBrowserType.isTemasysPluginUsed()) {
  873. onReady(options, this.getUserMediaWithConstraints.bind(this));
  874. resolve();
  875. }
  876. });
  877. }
  878. /* eslint-disable max-params */
  879. /**
  880. * @param {string[]} um required user media types
  881. * @param {function} successCallback
  882. * @param {Function} failureCallback
  883. * @param {Object} [options] optional parameters
  884. * @param {string} options.resolution
  885. * @param {number} options.bandwidth
  886. * @param {number} options.fps
  887. * @param {string} options.desktopStream
  888. * @param {string} options.cameraDeviceId
  889. * @param {string} options.micDeviceId
  890. **/
  891. getUserMediaWithConstraints(
  892. um,
  893. successCallback,
  894. failureCallback,
  895. options = {}) {
  896. const constraints = getConstraints(um, options);
  897. logger.info('Get media constraints', constraints);
  898. try {
  899. this.getUserMedia(
  900. constraints,
  901. stream => {
  902. logger.log('onUserMediaSuccess');
  903. setAvailableDevices(um, stream);
  904. successCallback(stream);
  905. },
  906. error => {
  907. setAvailableDevices(um, undefined);
  908. logger.warn('Failed to get access to local media. Error ',
  909. error, constraints);
  910. if (failureCallback) {
  911. failureCallback(
  912. new JitsiTrackError(error, constraints, um));
  913. }
  914. });
  915. } catch (e) {
  916. logger.error('GUM failed: ', e);
  917. if (failureCallback) {
  918. failureCallback(new JitsiTrackError(e, constraints, um));
  919. }
  920. }
  921. }
  922. /* eslint-enable max-params */
  923. /**
  924. * Creates the local MediaStreams.
  925. * @param {Object} [options] optional parameters
  926. * @param {Array} options.devices the devices that will be requested
  927. * @param {string} options.resolution resolution constraints
  928. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with
  929. * the following structure {stream: the Media Stream, type: "audio" or
  930. * "video", videoType: "camera" or "desktop"} will be returned trough the
  931. * Promise, otherwise JitsiTrack objects will be returned.
  932. * @param {string} options.cameraDeviceId
  933. * @param {string} options.micDeviceId
  934. * @returns {*} Promise object that will receive the new JitsiTracks
  935. */
  936. obtainAudioAndVideoPermissions(options = {}) {
  937. const self = this;
  938. const dsOptions = options.desktopSharingExtensionExternalInstallation;
  939. return new Promise((resolve, reject) => {
  940. const successCallback = function(stream) {
  941. resolve(handleLocalStream(stream, options.resolution));
  942. };
  943. options.devices = options.devices || [ 'audio', 'video' ];
  944. if (!screenObtainer.isSupported()
  945. && options.devices.indexOf('desktop') !== -1) {
  946. reject(new Error('Desktop sharing is not supported!'));
  947. }
  948. if (RTCBrowserType.isFirefox()
  949. // XXX The react-native-webrtc implementation that we
  950. // utilize on React Native at the time of this writing does
  951. // not support the MediaStream constructors defined by
  952. // https://www.w3.org/TR/mediacapture-streams/#constructors
  953. // and instead has a single constructor which expects (an
  954. // NSNumber as) a MediaStream ID.
  955. || RTCBrowserType.isReactNative()
  956. || RTCBrowserType.isTemasysPluginUsed()) {
  957. const GUM = function(device, s, e) {
  958. this.getUserMediaWithConstraints(device, s, e, options);
  959. };
  960. const deviceGUM = {
  961. 'audio': GUM.bind(self, [ 'audio' ]),
  962. 'video': GUM.bind(self, [ 'video' ])
  963. };
  964. if (screenObtainer.isSupported()) {
  965. deviceGUM.desktop = screenObtainer.obtainStream.bind(
  966. screenObtainer,
  967. dsOptions);
  968. }
  969. // With FF/IE we can't split the stream into audio and video
  970. // because FF doesn't support media stream constructors. So, we
  971. // need to get the audio stream separately from the video stream
  972. // using two distinct GUM calls. Not very user friendly :-( but
  973. // we don't have many other options neither.
  974. //
  975. // Note that we pack those 2 streams in a single object and pass
  976. // it to the successCallback method.
  977. obtainDevices({
  978. devices: options.devices,
  979. streams: [],
  980. successCallback,
  981. errorCallback: reject,
  982. deviceGUM
  983. });
  984. } else {
  985. const hasDesktop = options.devices.indexOf('desktop') > -1;
  986. if (hasDesktop) {
  987. options.devices.splice(
  988. options.devices.indexOf('desktop'),
  989. 1);
  990. }
  991. options.resolution = options.resolution || '360';
  992. if (options.devices.length) {
  993. this.getUserMediaWithConstraints(
  994. options.devices,
  995. stream => {
  996. const audioDeviceRequested
  997. = options.devices.indexOf('audio') !== -1;
  998. const videoDeviceRequested
  999. = options.devices.indexOf('video') !== -1;
  1000. const audioTracksReceived
  1001. = stream.getAudioTracks().length > 0;
  1002. const videoTracksReceived
  1003. = stream.getVideoTracks().length > 0;
  1004. if ((audioDeviceRequested && !audioTracksReceived)
  1005. || (videoDeviceRequested
  1006. && !videoTracksReceived)) {
  1007. self.stopMediaStream(stream);
  1008. // We are getting here in case if we requested
  1009. // 'audio' or 'video' devices or both, but
  1010. // didn't get corresponding MediaStreamTrack in
  1011. // response stream. We don't know the reason why
  1012. // this happened, so reject with general error.
  1013. // eslint-disable-next-line no-shadow
  1014. const devices = [];
  1015. if (audioDeviceRequested
  1016. && !audioTracksReceived) {
  1017. devices.push('audio');
  1018. }
  1019. if (videoDeviceRequested
  1020. && !videoTracksReceived) {
  1021. devices.push('video');
  1022. }
  1023. // we are missing one of the media we requested
  1024. // in order to get the actual error that caused
  1025. // this missing media we will call one more time
  1026. // getUserMedia so we can obtain the actual
  1027. // error (Example usecases are requesting
  1028. // audio and video and video device is missing
  1029. // or device is denied to be used and chrome is
  1030. // set to not ask for permissions)
  1031. self.getUserMediaWithConstraints(
  1032. devices,
  1033. () => {
  1034. // we already failed to obtain this
  1035. // media, so we are not supposed in any
  1036. // way to receive success for this call
  1037. // any way we will throw an error to be
  1038. // sure the promise will finish
  1039. reject(new JitsiTrackError(
  1040. { name: 'UnknownError' },
  1041. getConstraints(
  1042. options.devices,
  1043. options),
  1044. devices)
  1045. );
  1046. },
  1047. error => {
  1048. // rejects with real error for not
  1049. // obtaining the media
  1050. reject(error);
  1051. }, options);
  1052. return;
  1053. }
  1054. if (hasDesktop) {
  1055. screenObtainer.obtainStream(
  1056. dsOptions,
  1057. desktopStream => {
  1058. successCallback({ audioVideo: stream,
  1059. desktopStream });
  1060. }, error => {
  1061. self.stopMediaStream(stream);
  1062. reject(error);
  1063. });
  1064. } else {
  1065. successCallback({ audioVideo: stream });
  1066. }
  1067. },
  1068. error => reject(error),
  1069. options);
  1070. } else if (hasDesktop) {
  1071. screenObtainer.obtainStream(
  1072. dsOptions,
  1073. stream => successCallback({ desktopStream: stream }),
  1074. error => reject(error));
  1075. }
  1076. }
  1077. });
  1078. }
  1079. /**
  1080. *
  1081. */
  1082. getDeviceAvailability() {
  1083. return devices;
  1084. }
  1085. /**
  1086. *
  1087. */
  1088. isRTCReady() {
  1089. return rtcReady;
  1090. }
  1091. /**
  1092. *
  1093. */
  1094. _isDeviceListAvailable() {
  1095. if (!rtcReady) {
  1096. throw new Error('WebRTC not ready yet');
  1097. }
  1098. return Boolean(
  1099. (navigator.mediaDevices
  1100. && navigator.mediaDevices.enumerateDevices)
  1101. || (typeof MediaStreamTrack !== 'undefined'
  1102. && MediaStreamTrack.getSources));
  1103. }
  1104. /**
  1105. * Returns a promise which can be used to make sure that the WebRTC stack
  1106. * has been initialized.
  1107. *
  1108. * @returns {Promise} which is resolved only if the WebRTC stack is ready.
  1109. * Note that currently we do not detect stack initialization failure and
  1110. * the promise is never rejected(unless unexpected error occurs).
  1111. */
  1112. onRTCReady() {
  1113. if (rtcReady) {
  1114. return Promise.resolve();
  1115. }
  1116. return new Promise(resolve => {
  1117. const listener = () => {
  1118. eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1119. resolve();
  1120. };
  1121. eventEmitter.addListener(RTCEvents.RTC_READY, listener);
  1122. // We have no failed event, so... it either resolves or nothing
  1123. // happens
  1124. });
  1125. }
  1126. /**
  1127. * Checks if its possible to enumerate available cameras/microphones.
  1128. *
  1129. * @returns {Promise<boolean>} a Promise which will be resolved only once
  1130. * the WebRTC stack is ready, either with true if the device listing is
  1131. * available available or with false otherwise.
  1132. */
  1133. isDeviceListAvailable() {
  1134. return this.onRTCReady().then(this._isDeviceListAvailable.bind(this));
  1135. }
  1136. /**
  1137. * Returns true if changing the input (camera / microphone) or output
  1138. * (audio) device is supported and false if not.
  1139. * @params {string} [deviceType] - type of device to change. Default is
  1140. * undefined or 'input', 'output' - for audio output device change.
  1141. * @returns {boolean} true if available, false otherwise.
  1142. */
  1143. isDeviceChangeAvailable(deviceType) {
  1144. return deviceType === 'output' || deviceType === 'audiooutput'
  1145. ? isAudioOutputDeviceChangeAvailable
  1146. : RTCBrowserType.isChrome()
  1147. || RTCBrowserType.isFirefox()
  1148. || RTCBrowserType.isOpera()
  1149. || RTCBrowserType.isTemasysPluginUsed()
  1150. || RTCBrowserType.isNWJS()
  1151. || RTCBrowserType.isElectron();
  1152. }
  1153. /**
  1154. * A method to handle stopping of the stream.
  1155. * One point to handle the differences in various implementations.
  1156. * @param mediaStream MediaStream object to stop.
  1157. */
  1158. stopMediaStream(mediaStream) {
  1159. mediaStream.getTracks().forEach(track => {
  1160. // stop() not supported with IE
  1161. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  1162. track.stop();
  1163. }
  1164. });
  1165. // leave stop for implementation still using it
  1166. if (mediaStream.stop) {
  1167. mediaStream.stop();
  1168. }
  1169. // The MediaStream implementation of the react-native-webrtc project has
  1170. // an explicit release method that is to be invoked in order to release
  1171. // used resources such as memory.
  1172. if (mediaStream.release) {
  1173. mediaStream.release();
  1174. }
  1175. // if we have done createObjectURL, lets clean it
  1176. const url = mediaStream.jitsiObjectURL;
  1177. if (url) {
  1178. delete mediaStream.jitsiObjectURL;
  1179. (URL || webkitURL).revokeObjectURL(url);
  1180. }
  1181. }
  1182. /**
  1183. * Returns whether the desktop sharing is enabled or not.
  1184. * @returns {boolean}
  1185. */
  1186. isDesktopSharingEnabled() {
  1187. return screenObtainer.isSupported();
  1188. }
  1189. /**
  1190. * Sets current audio output device.
  1191. * @param {string} deviceId - id of 'audiooutput' device from
  1192. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  1193. * device
  1194. * @returns {Promise} - resolves when audio output is changed, is rejected
  1195. * otherwise
  1196. */
  1197. setAudioOutputDevice(deviceId) {
  1198. if (!this.isDeviceChangeAvailable('output')) {
  1199. Promise.reject(
  1200. new Error('Audio output device change is not supported'));
  1201. }
  1202. return featureDetectionAudioEl.setSinkId(deviceId)
  1203. .then(() => {
  1204. audioOutputDeviceId = deviceId;
  1205. audioOutputChanged = true;
  1206. logger.log(`Audio output device set to ${deviceId}`);
  1207. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1208. deviceId);
  1209. });
  1210. }
  1211. /**
  1212. * Returns currently used audio output device id, '' stands for default
  1213. * device
  1214. * @returns {string}
  1215. */
  1216. getAudioOutputDevice() {
  1217. return audioOutputDeviceId;
  1218. }
  1219. /**
  1220. * Returns list of available media devices if its obtained, otherwise an
  1221. * empty array is returned/
  1222. * @returns {Array} list of available media devices.
  1223. */
  1224. getCurrentlyAvailableMediaDevices() {
  1225. return currentlyAvailableMediaDevices;
  1226. }
  1227. /**
  1228. * Returns event data for device to be reported to stats.
  1229. * @returns {MediaDeviceInfo} device.
  1230. */
  1231. getEventDataForActiveDevice(device) {
  1232. const deviceList = [];
  1233. const deviceData = {
  1234. 'deviceId': device.deviceId,
  1235. 'kind': device.kind,
  1236. 'label': device.label,
  1237. 'groupId': device.groupId
  1238. };
  1239. deviceList.push(deviceData);
  1240. return { deviceList };
  1241. }
  1242. }
  1243. /**
  1244. * Rejects a Promise because WebRTC is not supported.
  1245. *
  1246. * @param {string} errorMessage - The human-readable message of the Error which
  1247. * is the reason for the rejection.
  1248. * @param {Function} reject - The reject function of the Promise.
  1249. * @returns {void}
  1250. */
  1251. function rejectWithWebRTCNotSupported(errorMessage, reject) {
  1252. const error = new Error(errorMessage);
  1253. // WebRTC is not supported either natively or via a known plugin such as
  1254. // Temasys.
  1255. // XXX The Error class already has a property name which is commonly used to
  1256. // detail the represented error in a non-human-readable way (in contrast to
  1257. // the human-readable property message). I explicitly did not want to
  1258. // introduce a new specific property.
  1259. // FIXME None of the existing JitsiXXXErrors seemed to be appropriate
  1260. // recipients of the constant WEBRTC_NOT_SUPPORTED so I explicitly chose to
  1261. // leave it as a magic string at the time of this writing.
  1262. error.name = 'WEBRTC_NOT_SUPPORTED';
  1263. logger.error(errorMessage);
  1264. reject(error);
  1265. }
  1266. const rtcUtils = new RTCUtils();
  1267. /**
  1268. *
  1269. * @param options
  1270. */
  1271. function obtainDevices(options) {
  1272. if (!options.devices || options.devices.length === 0) {
  1273. return options.successCallback(options.streams || {});
  1274. }
  1275. const device = options.devices.splice(0, 1);
  1276. options.deviceGUM[device](
  1277. stream => {
  1278. options.streams = options.streams || {};
  1279. options.streams[device] = stream;
  1280. obtainDevices(options);
  1281. },
  1282. error => {
  1283. Object.keys(options.streams).forEach(
  1284. d => rtcUtils.stopMediaStream(options.streams[d]));
  1285. logger.error(
  1286. `failed to obtain ${device} stream - stop`, error);
  1287. options.errorCallback(error);
  1288. });
  1289. }
  1290. /**
  1291. * In case of IE we continue from 'onReady' callback passed to RTCUtils
  1292. * constructor. It will be invoked by Temasys plugin once it is initialized.
  1293. *
  1294. * @param options
  1295. * @param GUM
  1296. */
  1297. function onReady(options, GUM) {
  1298. rtcReady = true;
  1299. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1300. screenObtainer.init(options, GUM);
  1301. // Initialize rawEnumerateDevicesWithCallback
  1302. initRawEnumerateDevicesWithCallback();
  1303. if (rtcUtils.isDeviceListAvailable() && rawEnumerateDevicesWithCallback) {
  1304. rawEnumerateDevicesWithCallback(ds => {
  1305. currentlyAvailableMediaDevices = ds.splice(0);
  1306. eventEmitter.emit(RTCEvents.DEVICE_LIST_AVAILABLE,
  1307. currentlyAvailableMediaDevices);
  1308. if (isDeviceChangeEventSupported) {
  1309. navigator.mediaDevices.addEventListener(
  1310. 'devicechange',
  1311. () => rtcUtils.enumerateDevices(onMediaDevicesListChanged));
  1312. } else {
  1313. pollForAvailableMediaDevices();
  1314. }
  1315. });
  1316. }
  1317. }
  1318. /**
  1319. * Wraps original attachMediaStream function to set current audio output device
  1320. * if this is supported.
  1321. * @param {Function} origAttachMediaStream
  1322. * @returns {Function}
  1323. */
  1324. function wrapAttachMediaStream(origAttachMediaStream) {
  1325. return function(element, stream) {
  1326. // eslint-disable-next-line prefer-rest-params
  1327. const res = origAttachMediaStream.apply(rtcUtils, arguments);
  1328. if (stream
  1329. && rtcUtils.isDeviceChangeAvailable('output')
  1330. && stream.getAudioTracks
  1331. && stream.getAudioTracks().length
  1332. // we skip setting audio output if there was no explicit change
  1333. && audioOutputChanged) {
  1334. element.setSinkId(rtcUtils.getAudioOutputDevice())
  1335. .catch(function(ex) {
  1336. const err
  1337. = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  1338. GlobalOnErrorHandler.callUnhandledRejectionHandler({
  1339. promise: this, // eslint-disable-line no-invalid-this
  1340. reason: err
  1341. });
  1342. logger.warn('Failed to set audio output device for the '
  1343. + 'element. Default audio output device will be used '
  1344. + 'instead',
  1345. element, err);
  1346. });
  1347. }
  1348. return res;
  1349. };
  1350. }
  1351. export default rtcUtils;