Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

RTCUtils.js 52KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  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(devices => {
  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 = devices.slice(0);
  347. } else if (compareAvailableMediaDevices(devices)) {
  348. onMediaDevicesListChanged(devices);
  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(devices => {
  397. currentlyAvailableMediaDevices = devices.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. const devices = [];
  505. devices.push(device);
  506. options.deviceGUM[device](
  507. stream => {
  508. options.streams = options.streams || {};
  509. options.streams[device] = stream;
  510. obtainDevices(options);
  511. },
  512. error => {
  513. Object.keys(options.streams).forEach(device => {
  514. rtcUtils.stopMediaStream(options.streams[device]);
  515. });
  516. logger.error(
  517. `failed to obtain ${device} stream - stop`, error);
  518. options.errorCallback(error);
  519. });
  520. }
  521. /**
  522. * Handles the newly created Media Streams.
  523. * @param streams the new Media Streams
  524. * @param resolution the resolution of the video streams
  525. * @returns {*[]} object that describes the new streams
  526. */
  527. function handleLocalStream(streams, resolution) {
  528. let audioStream, desktopStream, videoStream;
  529. const res = [];
  530. // XXX The function obtainAudioAndVideoPermissions has examined the type of
  531. // the browser, its capabilities, etc. and has taken the decision whether to
  532. // invoke getUserMedia per device (e.g. Firefox) or once for both audio and
  533. // video (e.g. Chrome). In order to not duplicate the logic here, examine
  534. // the specified streams and figure out what we've received based on
  535. // obtainAudioAndVideoPermissions' decision.
  536. if (streams) {
  537. // As mentioned above, certian types of browser (e.g. Chrome) support
  538. // (with a result which meets our requirements expressed bellow) calling
  539. // getUserMedia once for both audio and video.
  540. const audioVideo = streams.audioVideo;
  541. if (audioVideo) {
  542. const audioTracks = audioVideo.getAudioTracks();
  543. if (audioTracks.length) {
  544. // eslint-disable-next-line new-cap
  545. audioStream = new webkitMediaStream();
  546. for (let i = 0; i < audioTracks.length; i++) {
  547. audioStream.addTrack(audioTracks[i]);
  548. }
  549. }
  550. const videoTracks = audioVideo.getVideoTracks();
  551. if (videoTracks.length) {
  552. // eslint-disable-next-line new-cap
  553. videoStream = new webkitMediaStream();
  554. for (let j = 0; j < videoTracks.length; j++) {
  555. videoStream.addTrack(videoTracks[j]);
  556. }
  557. }
  558. } else {
  559. // On other types of browser (e.g. Firefox) we choose (namely,
  560. // obtainAudioAndVideoPermissions) to call getUsermedia per device
  561. // (type).
  562. audioStream = streams.audio;
  563. videoStream = streams.video;
  564. }
  565. // Again, different choices on different types of browser.
  566. desktopStream = streams.desktopStream || streams.desktop;
  567. }
  568. if (desktopStream) {
  569. res.push({
  570. stream: desktopStream,
  571. track: desktopStream.getVideoTracks()[0],
  572. mediaType: MediaType.VIDEO,
  573. videoType: VideoType.DESKTOP
  574. });
  575. }
  576. if (audioStream) {
  577. res.push({
  578. stream: audioStream,
  579. track: audioStream.getAudioTracks()[0],
  580. mediaType: MediaType.AUDIO,
  581. videoType: null
  582. });
  583. }
  584. if (videoStream) {
  585. res.push({
  586. stream: videoStream,
  587. track: videoStream.getVideoTracks()[0],
  588. mediaType: MediaType.VIDEO,
  589. videoType: VideoType.CAMERA,
  590. resolution
  591. });
  592. }
  593. return res;
  594. }
  595. /**
  596. * Wraps original attachMediaStream function to set current audio output device
  597. * if this is supported.
  598. * @param {Function} origAttachMediaStream
  599. * @returns {Function}
  600. */
  601. function wrapAttachMediaStream(origAttachMediaStream) {
  602. return function(element, stream) {
  603. // eslint-disable-next-line prefer-rest-params
  604. const res = origAttachMediaStream.apply(rtcUtils, arguments);
  605. if (stream
  606. && rtcUtils.isDeviceChangeAvailable('output')
  607. && stream.getAudioTracks
  608. && stream.getAudioTracks().length
  609. // we skip setting audio output if there was no explicit change
  610. && audioOutputChanged) {
  611. element.setSinkId(rtcUtils.getAudioOutputDevice())
  612. .catch(function(ex) {
  613. const err
  614. = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  615. GlobalOnErrorHandler.callUnhandledRejectionHandler(
  616. { promise: this,
  617. reason: err });
  618. logger.warn('Failed to set audio output device for the '
  619. + 'element. Default audio output device will be used '
  620. + 'instead',
  621. element, err);
  622. });
  623. }
  624. return res;
  625. };
  626. }
  627. /**
  628. * Represents a default implementation of setting a <tt>MediaStream</tt> as the
  629. * source of a video element that tries to be browser-agnostic through feature
  630. * checking. Note though that it was not completely clear from the predating
  631. * browser-specific implementations what &quot;videoSrc&quot; was because one
  632. * implementation of {@link RTCUtils#getVideoSrc} would return
  633. * <tt>MediaStream</tt> (e.g. Firefox), another a <tt>string</tt> representation
  634. * of the <tt>URL</tt> of the <tt>MediaStream</tt> (e.g. Chrome) and the return
  635. * value was only used by {@link RTCUIHelper#getVideoId} which itself did not
  636. * appear to be used anywhere. Generally, the implementation will try to follow
  637. * the related standards i.e. work with the <tt>srcObject</tt> and <tt>src</tt>
  638. * properties of the specified <tt>element</tt> taking into account vender
  639. * prefixes.
  640. *
  641. * @param element the element whose video source/src is to be set to the
  642. * specified <tt>stream</tt>
  643. * @param {MediaStream} stream the <tt>MediaStream</tt> to set as the video
  644. * source/src of <tt>element</tt>
  645. */
  646. function defaultSetVideoSrc(element, stream) {
  647. // srcObject
  648. let srcObjectPropertyName = 'srcObject';
  649. if (!(srcObjectPropertyName in element)) {
  650. srcObjectPropertyName = 'mozSrcObject';
  651. if (!(srcObjectPropertyName in element)) {
  652. srcObjectPropertyName = null;
  653. }
  654. }
  655. if (srcObjectPropertyName) {
  656. element[srcObjectPropertyName] = stream;
  657. return;
  658. }
  659. // src
  660. let src;
  661. if (stream) {
  662. src = stream.jitsiObjectURL;
  663. // Save the created URL for stream so we can reuse it and not keep
  664. // creating URLs.
  665. if (!src) {
  666. stream.jitsiObjectURL
  667. = src
  668. = (URL || webkitURL).createObjectURL(stream);
  669. }
  670. }
  671. element.src = src || '';
  672. }
  673. // Options parameter is to pass config options. Currently uses only "useIPv6".
  674. class RTCUtils extends Listenable {
  675. constructor() {
  676. super(eventEmitter);
  677. }
  678. init(options) {
  679. if (typeof options.disableAEC === 'boolean') {
  680. disableAEC = options.disableAEC;
  681. logger.info(`Disable AEC: ${disableAEC}`);
  682. }
  683. if (typeof options.disableNS === 'boolean') {
  684. disableNS = options.disableNS;
  685. logger.info(`Disable NS: ${disableNS}`);
  686. }
  687. return new Promise((resolve, reject) => {
  688. if (RTCBrowserType.isFirefox()) {
  689. const FFversion = RTCBrowserType.getFirefoxVersion();
  690. if (FFversion < 40) {
  691. rejectWithWebRTCNotSupported(
  692. `Firefox version too old: ${FFversion}.`
  693. + ' Required >= 40.',
  694. reject);
  695. return;
  696. }
  697. this.peerconnection = mozRTCPeerConnection;
  698. this.getUserMedia
  699. = wrapGetUserMedia(
  700. navigator.mozGetUserMedia.bind(navigator));
  701. this.enumerateDevices
  702. = wrapEnumerateDevices(
  703. navigator.mediaDevices.enumerateDevices.bind(
  704. navigator.mediaDevices));
  705. this.pcConstraints = {};
  706. this.attachMediaStream
  707. = wrapAttachMediaStream((element, stream) => {
  708. // srcObject is being standardized and FF will
  709. // eventually support that unprefixed. FF also supports
  710. // the "element.src = URL.createObjectURL(...)" combo,
  711. // but that will be deprecated in favour of srcObject.
  712. //
  713. // https://groups.google.com/forum/#!topic/
  714. // mozilla.dev.media/pKOiioXonJg
  715. // https://github.com/webrtc/samples/issues/302
  716. if (element) {
  717. defaultSetVideoSrc(element, stream);
  718. if (stream) {
  719. element.play();
  720. }
  721. }
  722. return element;
  723. });
  724. this.getStreamID = function(stream) {
  725. let id = stream.id;
  726. if (!id) {
  727. let tracks = stream.getVideoTracks();
  728. if (!tracks || tracks.length === 0) {
  729. tracks = stream.getAudioTracks();
  730. }
  731. id = tracks[0].id;
  732. }
  733. return SDPUtil.filterSpecialChars(id);
  734. };
  735. /* eslint-disable no-global-assign, no-native-reassign */
  736. RTCSessionDescription = mozRTCSessionDescription;
  737. RTCIceCandidate = mozRTCIceCandidate;
  738. /* eslint-enable no-global-assign, no-native-reassign */
  739. } else if (RTCBrowserType.isChrome()
  740. || RTCBrowserType.isOpera()
  741. || RTCBrowserType.isNWJS()
  742. || RTCBrowserType.isElectron()
  743. || RTCBrowserType.isReactNative()) {
  744. this.peerconnection = webkitRTCPeerConnection;
  745. const getUserMedia
  746. = navigator.webkitGetUserMedia.bind(navigator);
  747. if (navigator.mediaDevices) {
  748. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  749. this.enumerateDevices
  750. = wrapEnumerateDevices(
  751. navigator.mediaDevices.enumerateDevices.bind(
  752. navigator.mediaDevices));
  753. } else {
  754. this.getUserMedia = getUserMedia;
  755. this.enumerateDevices
  756. = enumerateDevicesThroughMediaStreamTrack;
  757. }
  758. this.attachMediaStream
  759. = wrapAttachMediaStream((element, stream) => {
  760. defaultSetVideoSrc(element, stream);
  761. return element;
  762. });
  763. this.getStreamID = function(stream) {
  764. // A. MediaStreams from FF endpoints have the characters '{'
  765. // and '}' that make jQuery choke.
  766. // B. The react-native-webrtc implementation that we use on
  767. // React Native at the time of this writing returns a number
  768. // for the id of MediaStream. Let's just say that a number
  769. // contains no special characters.
  770. const id = stream.id;
  771. // XXX The return statement is affected by automatic
  772. // semicolon insertion (ASI). No line terminator is allowed
  773. // between the return keyword and the expression.
  774. return (
  775. typeof id === 'number'
  776. ? id
  777. : SDPUtil.filterSpecialChars(id));
  778. };
  779. this.pcConstraints = { optional: [] };
  780. // Allows sending of video to be suspended if the bandwidth
  781. // estimation is too low.
  782. if (!options.disableSuspendVideo) {
  783. this.pcConstraints.optional.push(
  784. { googSuspendBelowMinBitrate: true });
  785. }
  786. if (options.useIPv6) {
  787. // https://code.google.com/p/webrtc/issues/detail?id=2828
  788. this.pcConstraints.optional.push({ googIPv6: true });
  789. }
  790. if (!webkitMediaStream.prototype.getVideoTracks) {
  791. webkitMediaStream.prototype.getVideoTracks = function() {
  792. return this.videoTracks;
  793. };
  794. }
  795. if (!webkitMediaStream.prototype.getAudioTracks) {
  796. webkitMediaStream.prototype.getAudioTracks = function() {
  797. return this.audioTracks;
  798. };
  799. }
  800. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  801. // Detect IE/Safari
  802. const webRTCReadyCb = () => {
  803. this.peerconnection = RTCPeerConnection;
  804. this.getUserMedia = window.getUserMedia;
  805. this.enumerateDevices
  806. = enumerateDevicesThroughMediaStreamTrack;
  807. this.attachMediaStream
  808. = wrapAttachMediaStream((element, stream) => {
  809. if (stream) {
  810. if (stream.id === 'dummyAudio'
  811. || stream.id === 'dummyVideo') {
  812. return;
  813. }
  814. // The container must be visible in order to
  815. // play or attach the stream when Temasys plugin
  816. // is in use
  817. const containerSel = $(element);
  818. if (RTCBrowserType.isTemasysPluginUsed()
  819. && !containerSel.is(':visible')) {
  820. containerSel.show();
  821. }
  822. const video
  823. = stream.getVideoTracks().length > 0;
  824. if (video && !$(element).is(':visible')) {
  825. throw new Error(
  826. 'video element must be visible to'
  827. + ' attach video stream');
  828. }
  829. }
  830. return attachMediaStream(element, stream);
  831. });
  832. this.getStreamID
  833. = stream => SDPUtil.filterSpecialChars(stream.label);
  834. onReady(
  835. options,
  836. this.getUserMediaWithConstraints.bind(this));
  837. };
  838. const webRTCReadyPromise
  839. = new Promise(resolve => AdapterJS.webRTCReady(resolve));
  840. // Resolve or reject depending on whether the Temasys plugin is
  841. // installed.
  842. AdapterJS.WebRTCPlugin.isPluginInstalled(
  843. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  844. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  845. AdapterJS.WebRTCPlugin.pluginInfo.type,
  846. /* installed */ () => {
  847. webRTCReadyPromise.then(() => {
  848. webRTCReadyCb();
  849. resolve();
  850. });
  851. },
  852. /* not installed */ () => {
  853. const error
  854. = new Error('Temasys plugin is not installed');
  855. error.name = 'WEBRTC_NOT_READY';
  856. error.webRTCReadyPromise = webRTCReadyPromise;
  857. reject(error);
  858. });
  859. } else {
  860. rejectWithWebRTCNotSupported(
  861. 'Browser does not appear to be WebRTC-capable',
  862. reject);
  863. return;
  864. }
  865. // Call onReady() if Temasys plugin is not used
  866. if (!RTCBrowserType.isTemasysPluginUsed()) {
  867. onReady(options, this.getUserMediaWithConstraints.bind(this));
  868. resolve();
  869. }
  870. });
  871. }
  872. /**
  873. * @param {string[]} um required user media types
  874. * @param {function} successCallback
  875. * @param {Function} failureCallback
  876. * @param {Object} [options] optional parameters
  877. * @param {string} options.resolution
  878. * @param {number} options.bandwidth
  879. * @param {number} options.fps
  880. * @param {string} options.desktopStream
  881. * @param {string} options.cameraDeviceId
  882. * @param {string} options.micDeviceId
  883. **/
  884. getUserMediaWithConstraints(
  885. um,
  886. successCallback,
  887. failureCallback,
  888. options = {}) {
  889. const constraints = getConstraints(um, options);
  890. logger.info('Get media constraints', constraints);
  891. try {
  892. this.getUserMedia(
  893. constraints,
  894. stream => {
  895. logger.log('onUserMediaSuccess');
  896. setAvailableDevices(um, stream);
  897. successCallback(stream);
  898. },
  899. error => {
  900. setAvailableDevices(um, undefined);
  901. logger.warn('Failed to get access to local media. Error ',
  902. error, constraints);
  903. if (failureCallback) {
  904. failureCallback(
  905. new JitsiTrackError(error, constraints, um));
  906. }
  907. });
  908. } catch (e) {
  909. logger.error('GUM failed: ', e);
  910. if (failureCallback) {
  911. failureCallback(new JitsiTrackError(e, constraints, um));
  912. }
  913. }
  914. }
  915. /**
  916. * Creates the local MediaStreams.
  917. * @param {Object} [options] optional parameters
  918. * @param {Array} options.devices the devices that will be requested
  919. * @param {string} options.resolution resolution constraints
  920. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with
  921. * the following structure {stream: the Media Stream, type: "audio" or
  922. * "video", videoType: "camera" or "desktop"} will be returned trough the
  923. * Promise, otherwise JitsiTrack objects will be returned.
  924. * @param {string} options.cameraDeviceId
  925. * @param {string} options.micDeviceId
  926. * @returns {*} Promise object that will receive the new JitsiTracks
  927. */
  928. obtainAudioAndVideoPermissions(options = {}) {
  929. const self = this;
  930. const dsOptions = options.desktopSharingExtensionExternalInstallation;
  931. return new Promise((resolve, reject) => {
  932. const successCallback = function(stream) {
  933. resolve(handleLocalStream(stream, options.resolution));
  934. };
  935. options.devices = options.devices || [ 'audio', 'video' ];
  936. if (!screenObtainer.isSupported()
  937. && options.devices.indexOf('desktop') !== -1) {
  938. reject(new Error('Desktop sharing is not supported!'));
  939. }
  940. if (RTCBrowserType.isFirefox()
  941. // XXX The react-native-webrtc implementation that we
  942. // utilize on React Native at the time of this writing does
  943. // not support the MediaStream constructors defined by
  944. // https://www.w3.org/TR/mediacapture-streams/#constructors
  945. // and instead has a single constructor which expects (an
  946. // NSNumber as) a MediaStream ID.
  947. || RTCBrowserType.isReactNative()
  948. || RTCBrowserType.isTemasysPluginUsed()) {
  949. const GUM = function(device, s, e) {
  950. this.getUserMediaWithConstraints(device, s, e, options);
  951. };
  952. const deviceGUM = {
  953. 'audio': GUM.bind(self, [ 'audio' ]),
  954. 'video': GUM.bind(self, [ 'video' ])
  955. };
  956. if (screenObtainer.isSupported()) {
  957. deviceGUM.desktop = screenObtainer.obtainStream.bind(
  958. screenObtainer,
  959. dsOptions);
  960. }
  961. // With FF/IE we can't split the stream into audio and video
  962. // because FF doesn't support media stream constructors. So, we
  963. // need to get the audio stream separately from the video stream
  964. // using two distinct GUM calls. Not very user friendly :-( but
  965. // we don't have many other options neither.
  966. //
  967. // Note that we pack those 2 streams in a single object and pass
  968. // it to the successCallback method.
  969. obtainDevices({
  970. devices: options.devices,
  971. streams: [],
  972. successCallback,
  973. errorCallback: reject,
  974. deviceGUM
  975. });
  976. } else {
  977. const hasDesktop = options.devices.indexOf('desktop') > -1;
  978. if (hasDesktop) {
  979. options.devices.splice(
  980. options.devices.indexOf('desktop'),
  981. 1);
  982. }
  983. options.resolution = options.resolution || '360';
  984. if (options.devices.length) {
  985. this.getUserMediaWithConstraints(
  986. options.devices,
  987. stream => {
  988. const audioDeviceRequested
  989. = options.devices.indexOf('audio') !== -1;
  990. const videoDeviceRequested
  991. = options.devices.indexOf('video') !== -1;
  992. const audioTracksReceived
  993. = stream.getAudioTracks().length > 0;
  994. const videoTracksReceived
  995. = stream.getVideoTracks().length > 0;
  996. if ((audioDeviceRequested && !audioTracksReceived)
  997. || (videoDeviceRequested
  998. && !videoTracksReceived)) {
  999. self.stopMediaStream(stream);
  1000. // We are getting here in case if we requested
  1001. // 'audio' or 'video' devices or both, but
  1002. // didn't get corresponding MediaStreamTrack in
  1003. // response stream. We don't know the reason why
  1004. // this happened, so reject with general error.
  1005. const devices = [];
  1006. if (audioDeviceRequested
  1007. && !audioTracksReceived) {
  1008. devices.push('audio');
  1009. }
  1010. if (videoDeviceRequested
  1011. && !videoTracksReceived) {
  1012. devices.push('video');
  1013. }
  1014. // we are missing one of the media we requested
  1015. // in order to get the actual error that caused
  1016. // this missing media we will call one more time
  1017. // getUserMedia so we can obtain the actual
  1018. // error (Example usecases are requesting
  1019. // audio and video and video device is missing
  1020. // or device is denied to be used and chrome is
  1021. // set to not ask for permissions)
  1022. self.getUserMediaWithConstraints(
  1023. devices,
  1024. () => {
  1025. // we already failed to obtain this
  1026. // media, so we are not supposed in any
  1027. // way to receive success for this call
  1028. // any way we will throw an error to be
  1029. // sure the promise will finish
  1030. reject(new JitsiTrackError(
  1031. { name: 'UnknownError' },
  1032. getConstraints(
  1033. options.devices,
  1034. options),
  1035. devices)
  1036. );
  1037. },
  1038. error => {
  1039. // rejects with real error for not
  1040. // obtaining the media
  1041. reject(error);
  1042. }, options);
  1043. return;
  1044. }
  1045. if (hasDesktop) {
  1046. screenObtainer.obtainStream(
  1047. dsOptions,
  1048. desktopStream => {
  1049. successCallback({ audioVideo: stream,
  1050. desktopStream });
  1051. }, error => {
  1052. self.stopMediaStream(stream);
  1053. reject(error);
  1054. });
  1055. } else {
  1056. successCallback({ audioVideo: stream });
  1057. }
  1058. },
  1059. error => reject(error),
  1060. options);
  1061. } else if (hasDesktop) {
  1062. screenObtainer.obtainStream(
  1063. dsOptions,
  1064. stream => successCallback({ desktopStream: stream }),
  1065. error => reject(error));
  1066. }
  1067. }
  1068. });
  1069. }
  1070. getDeviceAvailability() {
  1071. return devices;
  1072. }
  1073. isRTCReady() {
  1074. return rtcReady;
  1075. }
  1076. _isDeviceListAvailable() {
  1077. if (!rtcReady) {
  1078. throw new Error('WebRTC not ready yet');
  1079. }
  1080. return Boolean(navigator.mediaDevices
  1081. && navigator.mediaDevices.enumerateDevices
  1082. && typeof MediaStreamTrack !== 'undefined'
  1083. && MediaStreamTrack.getSources);
  1084. }
  1085. /**
  1086. * Returns a promise which can be used to make sure that the WebRTC stack
  1087. * has been initialized.
  1088. *
  1089. * @returns {Promise} which is resolved only if the WebRTC stack is ready.
  1090. * Note that currently we do not detect stack initialization failure and
  1091. * the promise is never rejected(unless unexpected error occurs).
  1092. */
  1093. onRTCReady() {
  1094. if (rtcReady) {
  1095. return Promise.resolve();
  1096. }
  1097. return new Promise(resolve => {
  1098. const listener = () => {
  1099. eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1100. resolve();
  1101. };
  1102. eventEmitter.addListener(RTCEvents.RTC_READY, listener);
  1103. // We have no failed event, so... it either resolves or nothing
  1104. // happens
  1105. });
  1106. }
  1107. /**
  1108. * Checks if its possible to enumerate available cameras/microphones.
  1109. *
  1110. * @returns {Promise<boolean>} a Promise which will be resolved only once
  1111. * the WebRTC stack is ready, either with true if the device listing is
  1112. * available available or with false otherwise.
  1113. */
  1114. isDeviceListAvailable() {
  1115. return this.onRTCReady().then(this._isDeviceListAvailable.bind(this));
  1116. }
  1117. /**
  1118. * Returns true if changing the input (camera / microphone) or output
  1119. * (audio) device is supported and false if not.
  1120. * @params {string} [deviceType] - type of device to change. Default is
  1121. * undefined or 'input', 'output' - for audio output device change.
  1122. * @returns {boolean} true if available, false otherwise.
  1123. */
  1124. isDeviceChangeAvailable(deviceType) {
  1125. return deviceType === 'output' || deviceType === 'audiooutput'
  1126. ? isAudioOutputDeviceChangeAvailable
  1127. : RTCBrowserType.isChrome()
  1128. || RTCBrowserType.isFirefox()
  1129. || RTCBrowserType.isOpera()
  1130. || RTCBrowserType.isTemasysPluginUsed()
  1131. || RTCBrowserType.isNWJS()
  1132. || RTCBrowserType.isElectron();
  1133. }
  1134. /**
  1135. * A method to handle stopping of the stream.
  1136. * One point to handle the differences in various implementations.
  1137. * @param mediaStream MediaStream object to stop.
  1138. */
  1139. stopMediaStream(mediaStream) {
  1140. mediaStream.getTracks().forEach(track => {
  1141. // stop() not supported with IE
  1142. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  1143. track.stop();
  1144. }
  1145. });
  1146. // leave stop for implementation still using it
  1147. if (mediaStream.stop) {
  1148. mediaStream.stop();
  1149. }
  1150. // The MediaStream implementation of the react-native-webrtc project has
  1151. // an explicit release method that is to be invoked in order to release
  1152. // used resources such as memory.
  1153. if (mediaStream.release) {
  1154. mediaStream.release();
  1155. }
  1156. // if we have done createObjectURL, lets clean it
  1157. const url = mediaStream.jitsiObjectURL;
  1158. if (url) {
  1159. delete mediaStream.jitsiObjectURL;
  1160. (URL || webkitURL).revokeObjectURL(url);
  1161. }
  1162. }
  1163. /**
  1164. * Returns whether the desktop sharing is enabled or not.
  1165. * @returns {boolean}
  1166. */
  1167. isDesktopSharingEnabled() {
  1168. return screenObtainer.isSupported();
  1169. }
  1170. /**
  1171. * Sets current audio output device.
  1172. * @param {string} deviceId - id of 'audiooutput' device from
  1173. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  1174. * device
  1175. * @returns {Promise} - resolves when audio output is changed, is rejected
  1176. * otherwise
  1177. */
  1178. setAudioOutputDevice(deviceId) {
  1179. if (!this.isDeviceChangeAvailable('output')) {
  1180. Promise.reject(
  1181. new Error('Audio output device change is not supported'));
  1182. }
  1183. return featureDetectionAudioEl.setSinkId(deviceId)
  1184. .then(() => {
  1185. audioOutputDeviceId = deviceId;
  1186. audioOutputChanged = true;
  1187. logger.log(`Audio output device set to ${deviceId}`);
  1188. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1189. deviceId);
  1190. });
  1191. }
  1192. /**
  1193. * Returns currently used audio output device id, '' stands for default
  1194. * device
  1195. * @returns {string}
  1196. */
  1197. getAudioOutputDevice() {
  1198. return audioOutputDeviceId;
  1199. }
  1200. /**
  1201. * Returns list of available media devices if its obtained, otherwise an
  1202. * empty array is returned/
  1203. * @returns {Array} list of available media devices.
  1204. */
  1205. getCurrentlyAvailableMediaDevices() {
  1206. return currentlyAvailableMediaDevices;
  1207. }
  1208. /**
  1209. * Returns event data for device to be reported to stats.
  1210. * @returns {MediaDeviceInfo} device.
  1211. */
  1212. getEventDataForActiveDevice(device) {
  1213. const devices = [];
  1214. const deviceData = {
  1215. 'deviceId': device.deviceId,
  1216. 'kind': device.kind,
  1217. 'label': device.label,
  1218. 'groupId': device.groupId
  1219. };
  1220. devices.push(deviceData);
  1221. return { deviceList: devices };
  1222. }
  1223. }
  1224. /**
  1225. * Rejects a Promise because WebRTC is not supported.
  1226. *
  1227. * @param {string} errorMessage - The human-readable message of the Error which
  1228. * is the reason for the rejection.
  1229. * @param {Function} reject - The reject function of the Promise.
  1230. * @returns {void}
  1231. */
  1232. function rejectWithWebRTCNotSupported(errorMessage, reject) {
  1233. const error = new Error(errorMessage);
  1234. // WebRTC is not supported either natively or via a known plugin such as
  1235. // Temasys.
  1236. // XXX The Error class already has a property name which is commonly used to
  1237. // detail the represented error in a non-human-readable way (in contrast to
  1238. // the human-readable property message). I explicitly did not want to
  1239. // introduce a new specific property.
  1240. // FIXME None of the existing JitsiXXXErrors seemed to be appropriate
  1241. // recipients of the constant WEBRTC_NOT_SUPPORTED so I explicitly chose to
  1242. // leave it as a magic string at the time of this writing.
  1243. error.name = 'WEBRTC_NOT_SUPPORTED';
  1244. logger.error(errorMessage);
  1245. reject(error);
  1246. }
  1247. const rtcUtils = new RTCUtils();
  1248. export default rtcUtils;