You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RTCUtils.js 52KB

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