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.

RTCUtils.js 52KB

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