modified lib-jitsi-meet dev repo
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

RTCUtils.js 51KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  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. rejectWithWebRTCNotSupported(
  682. `Firefox version too old: ${FFversion}.`
  683. + ' Required >= 40.',
  684. reject);
  685. return;
  686. }
  687. this.peerconnection = mozRTCPeerConnection;
  688. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  689. this.enumerateDevices = wrapEnumerateDevices(
  690. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  691. );
  692. this.pc_constraints = {};
  693. this.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  694. // srcObject is being standardized and FF will eventually
  695. // support that unprefixed. FF also supports the
  696. // "element.src = URL.createObjectURL(...)" combo, but that
  697. // will be deprecated in favour of srcObject.
  698. //
  699. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  700. // https://github.com/webrtc/samples/issues/302
  701. if (element) {
  702. defaultSetVideoSrc(element, stream);
  703. if (stream)
  704. element.play();
  705. }
  706. return element;
  707. });
  708. this.getStreamID = function (stream) {
  709. var id = stream.id;
  710. if (!id) {
  711. var tracks = stream.getVideoTracks();
  712. if (!tracks || tracks.length === 0) {
  713. tracks = stream.getAudioTracks();
  714. }
  715. id = tracks[0].id;
  716. }
  717. return SDPUtil.filter_special_chars(id);
  718. };
  719. RTCSessionDescription = mozRTCSessionDescription; // eslint-disable-line
  720. RTCIceCandidate = mozRTCIceCandidate; // eslint-disable-line
  721. } else if (RTCBrowserType.isChrome() ||
  722. RTCBrowserType.isOpera() ||
  723. RTCBrowserType.isNWJS() ||
  724. RTCBrowserType.isElectron() ||
  725. RTCBrowserType.isReactNative()) {
  726. this.peerconnection = webkitRTCPeerConnection;
  727. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  728. if (navigator.mediaDevices) {
  729. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  730. this.enumerateDevices = wrapEnumerateDevices(
  731. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  732. );
  733. } else {
  734. this.getUserMedia = getUserMedia;
  735. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  736. }
  737. this.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  738. defaultSetVideoSrc(element, stream);
  739. return element;
  740. });
  741. this.getStreamID = function (stream) {
  742. // A. MediaStreams from FF endpoints have the characters '{'
  743. // and '}' that make jQuery choke.
  744. // B. The react-native-webrtc implementation that we use on
  745. // React Native at the time of this writing returns a number
  746. // for the id of MediaStream. Let's just say that a number
  747. // contains no special characters.
  748. var id = stream.id;
  749. // XXX The return statement is affected by automatic
  750. // semicolon insertion (ASI). No line terminator is allowed
  751. // between the return keyword and the expression.
  752. return (
  753. (typeof id === 'number')
  754. ? id
  755. : SDPUtil.filter_special_chars(id));
  756. };
  757. this.pc_constraints = {optional: [] };
  758. // Allows sending of video to be suspended if the bandwidth
  759. // estimation is too low.
  760. if (!options.disableSuspendVideo) {
  761. this.pc_constraints.optional.push(
  762. {googSuspendBelowMinBitrate: true});
  763. }
  764. if (options.useIPv6) {
  765. // https://code.google.com/p/webrtc/issues/detail?id=2828
  766. this.pc_constraints.optional.push({googIPv6: true});
  767. }
  768. if (!webkitMediaStream.prototype.getVideoTracks) {
  769. webkitMediaStream.prototype.getVideoTracks = function () {
  770. return this.videoTracks;
  771. };
  772. }
  773. if (!webkitMediaStream.prototype.getAudioTracks) {
  774. webkitMediaStream.prototype.getAudioTracks = function () {
  775. return this.audioTracks;
  776. };
  777. }
  778. }
  779. // Detect IE/Safari
  780. else if (RTCBrowserType.isTemasysPluginUsed()) {
  781. //AdapterJS.WebRTCPlugin.setLogLevel(
  782. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  783. var self = this;
  784. AdapterJS.webRTCReady(function () {
  785. self.peerconnection = RTCPeerConnection;
  786. self.getUserMedia = window.getUserMedia;
  787. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  788. self.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  789. if (stream) {
  790. if (stream.id === "dummyAudio"
  791. || stream.id === "dummyVideo") {
  792. return;
  793. }
  794. // The container must be visible in order to play or
  795. // attach the stream when Temasys plugin is in use
  796. var containerSel = $(element);
  797. if (RTCBrowserType.isTemasysPluginUsed()
  798. && !containerSel.is(':visible')) {
  799. containerSel.show();
  800. }
  801. var video = !!stream.getVideoTracks().length;
  802. if (video && !$(element).is(':visible')) {
  803. throw new Error(
  804. 'video element must be visible to attach'
  805. + ' video stream');
  806. }
  807. }
  808. return attachMediaStream(element, stream);
  809. });
  810. self.getStreamID = function (stream) {
  811. return SDPUtil.filter_special_chars(stream.label);
  812. };
  813. onReady(options,
  814. self.getUserMediaWithConstraints.bind(self));
  815. resolve();
  816. });
  817. } else {
  818. rejectWithWebRTCNotSupported(
  819. 'Browser does not appear to be WebRTC-capable',
  820. reject);
  821. return;
  822. }
  823. // Call onReady() if Temasys plugin is not used
  824. if (!RTCBrowserType.isTemasysPluginUsed()) {
  825. onReady(options, this.getUserMediaWithConstraints.bind(this));
  826. resolve();
  827. }
  828. }.bind(this));
  829. }
  830. /**
  831. * @param {string[]} um required user media types
  832. * @param {function} success_callback
  833. * @param {Function} failure_callback
  834. * @param {Object} [options] optional parameters
  835. * @param {string} options.resolution
  836. * @param {number} options.bandwidth
  837. * @param {number} options.fps
  838. * @param {string} options.desktopStream
  839. * @param {string} options.cameraDeviceId
  840. * @param {string} options.micDeviceId
  841. **/
  842. getUserMediaWithConstraints( um, success_callback, failure_callback, options) {
  843. options = options || {};
  844. var constraints = getConstraints(um, options);
  845. logger.info("Get media constraints", constraints);
  846. try {
  847. this.getUserMedia(constraints,
  848. function (stream) {
  849. logger.log('onUserMediaSuccess');
  850. setAvailableDevices(um, stream);
  851. success_callback(stream);
  852. },
  853. function (error) {
  854. setAvailableDevices(um, undefined);
  855. logger.warn('Failed to get access to local media. Error ',
  856. error, constraints);
  857. if (failure_callback) {
  858. failure_callback(
  859. new JitsiTrackError(error, constraints, um));
  860. }
  861. });
  862. } catch (e) {
  863. logger.error('GUM failed: ', e);
  864. if (failure_callback) {
  865. failure_callback(new JitsiTrackError(e, constraints, um));
  866. }
  867. }
  868. }
  869. /**
  870. * Creates the local MediaStreams.
  871. * @param {Object} [options] optional parameters
  872. * @param {Array} options.devices the devices that will be requested
  873. * @param {string} options.resolution resolution constraints
  874. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  875. * type: "audio" or "video", videoType: "camera" or "desktop"}
  876. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  877. * @param {string} options.cameraDeviceId
  878. * @param {string} options.micDeviceId
  879. * @returns {*} Promise object that will receive the new JitsiTracks
  880. */
  881. obtainAudioAndVideoPermissions (options) {
  882. var self = this;
  883. options = options || {};
  884. var dsOptions = options.desktopSharingExtensionExternalInstallation;
  885. return new Promise(function (resolve, reject) {
  886. var successCallback = function (stream) {
  887. resolve(handleLocalStream(stream, options.resolution));
  888. };
  889. options.devices = options.devices || ['audio', 'video'];
  890. if(!screenObtainer.isSupported()
  891. && options.devices.indexOf("desktop") !== -1){
  892. reject(new Error("Desktop sharing is not supported!"));
  893. }
  894. if (RTCBrowserType.isFirefox()
  895. // XXX The react-native-webrtc implementation that we
  896. // utilize on React Native at the time of this writing does
  897. // not support the MediaStream constructors defined by
  898. // https://www.w3.org/TR/mediacapture-streams/#constructors
  899. // and instead has a single constructor which expects (an
  900. // NSNumber as) a MediaStream ID.
  901. || RTCBrowserType.isReactNative()
  902. || RTCBrowserType.isTemasysPluginUsed()) {
  903. var GUM = function (device, s, e) {
  904. this.getUserMediaWithConstraints(device, s, e, options);
  905. };
  906. var deviceGUM = {
  907. "audio": GUM.bind(self, ["audio"]),
  908. "video": GUM.bind(self, ["video"])
  909. };
  910. if(screenObtainer.isSupported()){
  911. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  912. screenObtainer,
  913. dsOptions);
  914. }
  915. // With FF/IE we can't split the stream into audio and video because FF
  916. // doesn't support media stream constructors. So, we need to get the
  917. // audio stream separately from the video stream using two distinct GUM
  918. // calls. Not very user friendly :-( but we don't have many other
  919. // options neither.
  920. //
  921. // Note that we pack those 2 streams in a single object and pass it to
  922. // the successCallback method.
  923. obtainDevices({
  924. devices: options.devices,
  925. streams: [],
  926. successCallback: successCallback,
  927. errorCallback: reject,
  928. deviceGUM: deviceGUM
  929. });
  930. } else {
  931. var hasDesktop = options.devices.indexOf('desktop') > -1;
  932. if (hasDesktop) {
  933. options.devices.splice(options.devices.indexOf("desktop"), 1);
  934. }
  935. options.resolution = options.resolution || '360';
  936. if(options.devices.length) {
  937. this.getUserMediaWithConstraints(
  938. options.devices,
  939. function (stream) {
  940. var audioDeviceRequested = options.devices.indexOf("audio") !== -1;
  941. var videoDeviceRequested = options.devices.indexOf("video") !== -1;
  942. var audioTracksReceived = !!stream.getAudioTracks().length;
  943. var videoTracksReceived = !!stream.getVideoTracks().length;
  944. if((audioDeviceRequested && !audioTracksReceived) ||
  945. (videoDeviceRequested && !videoTracksReceived))
  946. {
  947. self.stopMediaStream(stream);
  948. // We are getting here in case if we requested
  949. // 'audio' or 'video' devices or both, but
  950. // didn't get corresponding MediaStreamTrack in
  951. // response stream. We don't know the reason why
  952. // this happened, so reject with general error.
  953. var devices = [];
  954. if (audioDeviceRequested && !audioTracksReceived) {
  955. devices.push("audio");
  956. }
  957. if (videoDeviceRequested && !videoTracksReceived) {
  958. devices.push("video");
  959. }
  960. // we are missing one of the media we requested
  961. // in order to get the actual error that caused
  962. // this missing media we will call one more time
  963. // getUserMedia so we can obtain the actual
  964. // error (Example usecases are requesting
  965. // audio and video and video device is missing
  966. // or device is denied to be used and chrome is
  967. // set to not ask for permissions)
  968. self.getUserMediaWithConstraints(
  969. devices,
  970. function () {
  971. // we already failed to obtain this
  972. // media, so we are not supposed in any
  973. // way to receive success for this call
  974. // any way we will throw an error to be
  975. // sure the promise will finish
  976. reject(new JitsiTrackError(
  977. { name: "UnknownError" },
  978. getConstraints(
  979. options.devices, options),
  980. devices)
  981. );
  982. },
  983. function (error) {
  984. // rejects with real error for not
  985. // obtaining the media
  986. reject(error);
  987. },options);
  988. return;
  989. }
  990. if(hasDesktop) {
  991. screenObtainer.obtainStream(
  992. dsOptions,
  993. function (desktopStream) {
  994. successCallback({audioVideo: stream,
  995. desktopStream: desktopStream});
  996. }, function (error) {
  997. self.stopMediaStream(stream);
  998. reject(error);
  999. });
  1000. } else {
  1001. successCallback({audioVideo: stream});
  1002. }
  1003. },
  1004. function (error) {
  1005. reject(error);
  1006. },
  1007. options);
  1008. } else if (hasDesktop) {
  1009. screenObtainer.obtainStream(
  1010. dsOptions,
  1011. function (stream) {
  1012. successCallback({desktopStream: stream});
  1013. }, function (error) {
  1014. reject(error);
  1015. });
  1016. }
  1017. }
  1018. }.bind(this));
  1019. }
  1020. getDeviceAvailability () {
  1021. return devices;
  1022. }
  1023. isRTCReady () {
  1024. return rtcReady;
  1025. }
  1026. _isDeviceListAvailable () {
  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 () {
  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 () {
  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 (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. RTCBrowserType.isElectron();
  1088. }
  1089. /**
  1090. * A method to handle stopping of the stream.
  1091. * One point to handle the differences in various implementations.
  1092. * @param mediaStream MediaStream object to stop.
  1093. */
  1094. stopMediaStream (mediaStream) {
  1095. mediaStream.getTracks().forEach(function (track) {
  1096. // stop() not supported with IE
  1097. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  1098. track.stop();
  1099. }
  1100. });
  1101. // leave stop for implementation still using it
  1102. if (mediaStream.stop) {
  1103. mediaStream.stop();
  1104. }
  1105. // The MediaStream implementation of the react-native-webrtc project has
  1106. // an explicit release method that is to be invoked in order to release
  1107. // used resources such as memory.
  1108. if (mediaStream.release) {
  1109. mediaStream.release();
  1110. }
  1111. // if we have done createObjectURL, lets clean it
  1112. var url = mediaStream.jitsiObjectURL;
  1113. if (url) {
  1114. delete mediaStream.jitsiObjectURL;
  1115. (URL || webkitURL).revokeObjectURL(url);
  1116. }
  1117. }
  1118. /**
  1119. * Returns whether the desktop sharing is enabled or not.
  1120. * @returns {boolean}
  1121. */
  1122. isDesktopSharingEnabled () {
  1123. return screenObtainer.isSupported();
  1124. }
  1125. /**
  1126. * Sets current audio output device.
  1127. * @param {string} deviceId - id of 'audiooutput' device from
  1128. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  1129. * device
  1130. * @returns {Promise} - resolves when audio output is changed, is rejected
  1131. * otherwise
  1132. */
  1133. setAudioOutputDevice (deviceId) {
  1134. if (!this.isDeviceChangeAvailable('output')) {
  1135. Promise.reject(
  1136. new Error('Audio output device change is not supported'));
  1137. }
  1138. return featureDetectionAudioEl.setSinkId(deviceId)
  1139. .then(function() {
  1140. audioOutputDeviceId = deviceId;
  1141. audioOutputChanged = true;
  1142. logger.log('Audio output device set to ' + deviceId);
  1143. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1144. deviceId);
  1145. });
  1146. }
  1147. /**
  1148. * Returns currently used audio output device id, '' stands for default
  1149. * device
  1150. * @returns {string}
  1151. */
  1152. getAudioOutputDevice () {
  1153. return audioOutputDeviceId;
  1154. }
  1155. /**
  1156. * Returns list of available media devices if its obtained, otherwise an
  1157. * empty array is returned/
  1158. * @returns {Array} list of available media devices.
  1159. */
  1160. getCurrentlyAvailableMediaDevices () {
  1161. return currentlyAvailableMediaDevices;
  1162. }
  1163. /**
  1164. * Returns event data for device to be reported to stats.
  1165. * @returns {MediaDeviceInfo} device.
  1166. */
  1167. getEventDataForActiveDevice (device) {
  1168. var devices = [];
  1169. var deviceData = {
  1170. "deviceId": device.deviceId,
  1171. "kind": device.kind,
  1172. "label": device.label,
  1173. "groupId": device.groupId
  1174. };
  1175. devices.push(deviceData);
  1176. return { deviceList: devices };
  1177. }
  1178. }
  1179. /**
  1180. * Rejects a Promise because WebRTC is not supported.
  1181. *
  1182. * @param {string} errorMessage - The human-readable message of the Error which
  1183. * is the reason for the rejection.
  1184. * @param {Function} reject - The reject function of the Promise.
  1185. * @returns {void}
  1186. */
  1187. function rejectWithWebRTCNotSupported(errorMessage, reject) {
  1188. const error = new Error(errorMessage);
  1189. // WebRTC is not supported either natively or via a known plugin such as
  1190. // Temasys.
  1191. // XXX The Error class already has a property name which is commonly used to
  1192. // detail the represented error in a non-human-readable way (in contrast to
  1193. // the human-readable property message). I explicitly did not want to
  1194. // introduce a new specific property.
  1195. // FIXME None of the existing JitsiXXXErrors seemed to be appropriate
  1196. // recipients of the constant WEBRTC_NOT_SUPPORTED so I explicitly chose to
  1197. // leave it as a magic string at the time of this writing.
  1198. error.name = 'WEBRTC_NOT_SUPPORTED';
  1199. logger.error(errorMessage);
  1200. reject(error);
  1201. }
  1202. const rtcUtils = new RTCUtils();
  1203. export default rtcUtils;