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 50KB

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