Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

RTCUtils.js 50KB

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