modified lib-jitsi-meet dev repo
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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