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

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