Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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