您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RTCUtils.js 50KB

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