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 57KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627
  1. /* global
  2. __filename,
  3. MediaStreamTrack,
  4. RTCIceCandidate: true,
  5. RTCPeerConnection,
  6. RTCSessionDescription: true
  7. */
  8. import EventEmitter from 'events';
  9. import { getLogger } from 'jitsi-meet-logger';
  10. import clonedeep from 'lodash.clonedeep';
  11. import JitsiTrackError from '../../JitsiTrackError';
  12. import CameraFacingMode from '../../service/RTC/CameraFacingMode';
  13. import * as MediaType from '../../service/RTC/MediaType';
  14. import RTCEvents from '../../service/RTC/RTCEvents';
  15. import Resolutions from '../../service/RTC/Resolutions';
  16. import VideoType from '../../service/RTC/VideoType';
  17. import { AVAILABLE_DEVICE } from '../../service/statistics/AnalyticsEvents';
  18. import browser from '../browser';
  19. import Statistics from '../statistics/statistics';
  20. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  21. import Listenable from '../util/Listenable';
  22. import SDPUtil from '../xmpp/SDPUtil';
  23. import screenObtainer from './ScreenObtainer';
  24. const logger = getLogger(__filename);
  25. // Require adapter only for certain browsers. This is being done for
  26. // react-native, which has its own shims, and while browsers are being migrated
  27. // over to use adapter's shims.
  28. if (browser.usesAdapter()) {
  29. require('webrtc-adapter');
  30. }
  31. const eventEmitter = new EventEmitter();
  32. const AVAILABLE_DEVICES_POLL_INTERVAL_TIME = 3000; // ms
  33. /**
  34. * Default resolution to obtain for video tracks if no resolution is specified.
  35. * This default is used for old gum flow only, as new gum flow uses
  36. * {@link DEFAULT_CONSTRAINTS}.
  37. */
  38. const OLD_GUM_DEFAULT_RESOLUTION = 720;
  39. /**
  40. * Default devices to obtain when no specific devices are specified. This
  41. * default is used for old gum flow only.
  42. */
  43. const OLD_GUM_DEFAULT_DEVICES = [ 'audio', 'video' ];
  44. /**
  45. * Default MediaStreamConstraints to use for calls to getUserMedia.
  46. *
  47. * @private
  48. */
  49. const DEFAULT_CONSTRAINTS = {
  50. video: {
  51. height: {
  52. ideal: 720,
  53. max: 720,
  54. min: 240
  55. }
  56. }
  57. };
  58. /**
  59. * The default frame rate for Screen Sharing.
  60. */
  61. const SS_DEFAULT_FRAME_RATE = 5;
  62. // Currently audio output device change is supported only in Chrome and
  63. // default output always has 'default' device ID
  64. let audioOutputDeviceId = 'default'; // default device
  65. // whether user has explicitly set a device to use
  66. let audioOutputChanged = false;
  67. // Disables all audio processing
  68. let disableAP = false;
  69. // Disables Acoustic Echo Cancellation
  70. let disableAEC = false;
  71. // Disables Noise Suppression
  72. let disableNS = false;
  73. // Disables Automatic Gain Control
  74. let disableAGC = false;
  75. // Disables Highpass Filter
  76. let disableHPF = false;
  77. const featureDetectionAudioEl = document.createElement('audio');
  78. const isAudioOutputDeviceChangeAvailable
  79. = typeof featureDetectionAudioEl.setSinkId !== 'undefined';
  80. let availableDevices;
  81. let availableDevicesPollTimer;
  82. /**
  83. * Initialize wrapper function for enumerating devices.
  84. * TODO: remove this, it should no longer be needed.
  85. *
  86. * @returns {?Function}
  87. */
  88. function initEnumerateDevicesWithCallback() {
  89. if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
  90. return callback => {
  91. navigator.mediaDevices.enumerateDevices()
  92. .then(callback, () => callback([]));
  93. };
  94. }
  95. }
  96. /**
  97. *
  98. * @param constraints
  99. * @param isNewStyleConstraintsSupported
  100. * @param resolution
  101. */
  102. function setResolutionConstraints(
  103. constraints,
  104. isNewStyleConstraintsSupported,
  105. resolution) {
  106. if (Resolutions[resolution]) {
  107. if (isNewStyleConstraintsSupported) {
  108. constraints.video.width = {
  109. ideal: Resolutions[resolution].width
  110. };
  111. constraints.video.height = {
  112. ideal: Resolutions[resolution].height
  113. };
  114. }
  115. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  116. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  117. }
  118. if (constraints.video.mandatory.minWidth) {
  119. constraints.video.mandatory.maxWidth
  120. = constraints.video.mandatory.minWidth;
  121. }
  122. if (constraints.video.mandatory.minHeight) {
  123. constraints.video.mandatory.maxHeight
  124. = constraints.video.mandatory.minHeight;
  125. }
  126. }
  127. /**
  128. * @param {string[]} um required user media types
  129. *
  130. * @param {Object} [options={}] optional parameters
  131. * @param {string} options.resolution
  132. * @param {number} options.bandwidth
  133. * @param {number} options.fps
  134. * @param {string} options.desktopStream
  135. * @param {string} options.cameraDeviceId
  136. * @param {string} options.micDeviceId
  137. * @param {CameraFacingMode} options.facingMode
  138. * @param {bool} firefox_fake_device
  139. * @param {Object} options.frameRate - used only for dekstop sharing.
  140. * @param {Object} options.frameRate.min - Minimum fps
  141. * @param {Object} options.frameRate.max - Maximum fps
  142. * @param {bool} options.screenShareAudio - Used by electron clients to
  143. * enable system audio screen sharing.
  144. */
  145. function getConstraints(um, options = {}) {
  146. const constraints = {
  147. audio: false,
  148. video: false
  149. };
  150. // Don't mix new and old style settings for Chromium as this leads
  151. // to TypeError in new Chromium versions. @see
  152. // https://bugs.chromium.org/p/chromium/issues/detail?id=614716
  153. // This is a temporary solution, in future we will fully split old and
  154. // new style constraints when new versions of Chromium and Firefox will
  155. // have stable support of new constraints format. For more information
  156. // @see https://github.com/jitsi/lib-jitsi-meet/pull/136
  157. const isNewStyleConstraintsSupported
  158. = browser.isFirefox()
  159. || browser.isSafari()
  160. || browser.isReactNative();
  161. if (um.indexOf('video') >= 0) {
  162. // same behaviour as true
  163. constraints.video = { mandatory: {},
  164. optional: [] };
  165. if (options.cameraDeviceId) {
  166. if (isNewStyleConstraintsSupported) {
  167. // New style of setting device id.
  168. constraints.video.deviceId = options.cameraDeviceId;
  169. }
  170. // Old style.
  171. constraints.video.mandatory.sourceId = options.cameraDeviceId;
  172. } else {
  173. // Prefer the front i.e. user-facing camera (to the back i.e.
  174. // environment-facing camera, for example).
  175. // TODO: Maybe use "exact" syntax if options.facingMode is defined,
  176. // but this probably needs to be decided when updating other
  177. // constraints, as we currently don't use "exact" syntax anywhere.
  178. const facingMode = options.facingMode || CameraFacingMode.USER;
  179. if (isNewStyleConstraintsSupported) {
  180. constraints.video.facingMode = facingMode;
  181. }
  182. constraints.video.optional.push({
  183. facingMode
  184. });
  185. }
  186. if (options.minFps || options.maxFps || options.fps) {
  187. // for some cameras it might be necessary to request 30fps
  188. // so they choose 30fps mjpg over 10fps yuy2
  189. if (options.minFps || options.fps) {
  190. // Fall back to options.fps for backwards compatibility
  191. options.minFps = options.minFps || options.fps;
  192. constraints.video.mandatory.minFrameRate = options.minFps;
  193. }
  194. if (options.maxFps) {
  195. constraints.video.mandatory.maxFrameRate = options.maxFps;
  196. }
  197. }
  198. setResolutionConstraints(
  199. constraints, isNewStyleConstraintsSupported, options.resolution);
  200. }
  201. if (um.indexOf('audio') >= 0) {
  202. if (browser.isReactNative()) {
  203. // The react-native-webrtc project that we're currently using
  204. // expects the audio constraint to be a boolean.
  205. constraints.audio = true;
  206. } else if (browser.isFirefox()) {
  207. if (options.micDeviceId) {
  208. constraints.audio = {
  209. mandatory: {},
  210. deviceId: options.micDeviceId, // new style
  211. optional: [ {
  212. sourceId: options.micDeviceId // old style
  213. } ] };
  214. } else {
  215. constraints.audio = true;
  216. }
  217. } else {
  218. // same behaviour as true
  219. constraints.audio = { mandatory: {},
  220. optional: [] };
  221. if (options.micDeviceId) {
  222. if (isNewStyleConstraintsSupported) {
  223. // New style of setting device id.
  224. constraints.audio.deviceId = options.micDeviceId;
  225. }
  226. // Old style.
  227. constraints.audio.optional.push({
  228. sourceId: options.micDeviceId
  229. });
  230. }
  231. // if it is good enough for hangouts...
  232. constraints.audio.optional.push(
  233. { echoCancellation: !disableAEC && !disableAP },
  234. { googEchoCancellation: !disableAEC && !disableAP },
  235. { googAutoGainControl: !disableAGC && !disableAP },
  236. { googNoiseSuppression: !disableNS && !disableAP },
  237. { googHighpassFilter: !disableHPF && !disableAP },
  238. { googNoiseSuppression2: !disableNS && !disableAP },
  239. { googEchoCancellation2: !disableAEC && !disableAP },
  240. { googAutoGainControl2: !disableAGC && !disableAP }
  241. );
  242. }
  243. }
  244. if (um.indexOf('screen') >= 0) {
  245. if (browser.isChrome()) {
  246. constraints.video = {
  247. mandatory: getSSConstraints({
  248. ...options,
  249. source: 'screen'
  250. }),
  251. optional: []
  252. };
  253. } else if (browser.isFirefox()) {
  254. constraints.video = {
  255. mozMediaSource: 'window',
  256. mediaSource: 'window',
  257. frameRate: options.frameRate || {
  258. min: SS_DEFAULT_FRAME_RATE,
  259. max: SS_DEFAULT_FRAME_RATE
  260. }
  261. };
  262. } else {
  263. const errmsg
  264. = '\'screen\' WebRTC media source is supported only in Chrome'
  265. + ' and Firefox';
  266. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  267. logger.error(errmsg);
  268. }
  269. }
  270. if (um.indexOf('desktop') >= 0) {
  271. constraints.video = {
  272. mandatory: getSSConstraints({
  273. ...options,
  274. source: 'desktop'
  275. }),
  276. optional: []
  277. };
  278. // Audio screen sharing for electron only works for screen type devices.
  279. // i.e. when the user shares the whole desktop.
  280. if (browser.isElectron() && options.screenShareAudio
  281. && (options.desktopStream.indexOf('screen') >= 0)) {
  282. // Provide constraints as described by the electron desktop capturer
  283. // documentation here:
  284. // https://www.electronjs.org/docs/api/desktop-capturer
  285. // Note. The documentation specifies that chromeMediaSourceId should not be present
  286. // which, in the case a users has multiple monitors, leads to them being shared all
  287. // at once. However we tested with chromeMediaSourceId present and it seems to be
  288. // working properly and also takes care of the previously mentioned issue.
  289. constraints.audio = { mandatory: {
  290. chromeMediaSource: constraints.video.mandatory.chromeMediaSource
  291. } };
  292. }
  293. }
  294. if (options.bandwidth) {
  295. if (!constraints.video) {
  296. // same behaviour as true
  297. constraints.video = { mandatory: {},
  298. optional: [] };
  299. }
  300. constraints.video.optional.push({ bandwidth: options.bandwidth });
  301. }
  302. // we turn audio for both audio and video tracks, the fake audio & video
  303. // seems to work only when enabled in one getUserMedia call, we cannot get
  304. // fake audio separate by fake video this later can be a problem with some
  305. // of the tests
  306. if (browser.isFirefox() && options.firefox_fake_device) {
  307. // seems to be fixed now, removing this experimental fix, as having
  308. // multiple audio tracks brake the tests
  309. // constraints.audio = true;
  310. constraints.fake = true;
  311. }
  312. return constraints;
  313. }
  314. /**
  315. * Creates a constraints object to be passed into a call to getUserMedia.
  316. *
  317. * @param {Array} um - An array of user media types to get. The accepted
  318. * types are "video", "audio", and "desktop."
  319. * @param {Object} options - Various values to be added to the constraints.
  320. * @param {string} options.cameraDeviceId - The device id for the video
  321. * capture device to get video from.
  322. * @param {Object} options.constraints - Default constraints object to use
  323. * as a base for the returned constraints.
  324. * @param {Object} options.desktopStream - The desktop source id from which
  325. * to capture a desktop sharing video.
  326. * @param {string} options.facingMode - Which direction the camera is
  327. * pointing to.
  328. * @param {string} options.micDeviceId - The device id for the audio capture
  329. * device to get audio from.
  330. * @param {Object} options.frameRate - used only for dekstop sharing.
  331. * @param {Object} options.frameRate.min - Minimum fps
  332. * @param {Object} options.frameRate.max - Maximum fps
  333. * @private
  334. * @returns {Object}
  335. */
  336. function newGetConstraints(um = [], options = {}) {
  337. // Create a deep copy of the constraints to avoid any modification of
  338. // the passed in constraints object.
  339. const constraints = clonedeep(options.constraints || DEFAULT_CONSTRAINTS);
  340. if (um.indexOf('video') >= 0) {
  341. if (!constraints.video) {
  342. constraints.video = {};
  343. }
  344. // Override the constraints on Safari because of the following webkit bug.
  345. // https://bugs.webkit.org/show_bug.cgi?id=210932
  346. // Camera doesn't start on older macOS versions if min/max constraints are specified.
  347. // TODO: remove this hack when the bug fix is available on Mojave, Sierra and High Sierra.
  348. if (browser.isSafari()) {
  349. if (constraints.video.height && constraints.video.height.ideal) {
  350. constraints.video.height = { ideal: clonedeep(constraints.video.height.ideal) };
  351. } else {
  352. logger.warn('Ideal camera height missing, camera may not start properly');
  353. }
  354. if (constraints.video.width && constraints.video.width.ideal) {
  355. constraints.video.width = { ideal: clonedeep(constraints.video.width.ideal) };
  356. } else {
  357. logger.warn('Ideal camera width missing, camera may not start properly');
  358. }
  359. }
  360. if (options.cameraDeviceId) {
  361. constraints.video.deviceId = options.cameraDeviceId;
  362. } else {
  363. const facingMode = options.facingMode || CameraFacingMode.USER;
  364. constraints.video.facingMode = facingMode;
  365. }
  366. } else {
  367. constraints.video = false;
  368. }
  369. if (um.indexOf('audio') >= 0) {
  370. if (!constraints.audio || typeof constraints.audio === 'boolean') {
  371. constraints.audio = {};
  372. }
  373. // Use the standard audio constraints on non-chromium browsers.
  374. if (browser.isFirefox() || browser.isSafari()) {
  375. constraints.audio = {
  376. deviceId: options.micDeviceId,
  377. autoGainControl: !disableAGC && !disableAP,
  378. echoCancellation: !disableAEC && !disableAP,
  379. noiseSuppression: !disableNS && !disableAP
  380. };
  381. } else {
  382. // NOTE(brian): the new-style ('advanced' instead of 'optional')
  383. // doesn't seem to carry through the googXXX constraints
  384. // Changing back to 'optional' here (even with video using
  385. // the 'advanced' style) allows them to be passed through
  386. // but also requires the device id to capture to be set in optional
  387. // as sourceId otherwise the constraints are considered malformed.
  388. if (!constraints.audio.optional) {
  389. constraints.audio.optional = [];
  390. }
  391. constraints.audio.optional.push(
  392. { sourceId: options.micDeviceId },
  393. { echoCancellation: !disableAEC && !disableAP },
  394. { googEchoCancellation: !disableAEC && !disableAP },
  395. { googAutoGainControl: !disableAGC && !disableAP },
  396. { googNoiseSuppression: !disableNS && !disableAP },
  397. { googHighpassFilter: !disableHPF && !disableAP },
  398. { googNoiseSuppression2: !disableNS && !disableAP },
  399. { googEchoCancellation2: !disableAEC && !disableAP },
  400. { googAutoGainControl2: !disableAGC && !disableAP }
  401. );
  402. }
  403. } else {
  404. constraints.audio = false;
  405. }
  406. if (um.indexOf('desktop') >= 0) {
  407. if (!constraints.video || typeof constraints.video === 'boolean') {
  408. constraints.video = {};
  409. }
  410. constraints.video = {
  411. mandatory: getSSConstraints({
  412. ...options,
  413. source: 'desktop'
  414. })
  415. };
  416. }
  417. return constraints;
  418. }
  419. /**
  420. * Generates GUM constraints for screen sharing.
  421. *
  422. * @param {Object} options - The options passed to
  423. * <tt>obtainAudioAndVideoPermissions</tt>.
  424. * @returns {Object} - GUM constraints.
  425. *
  426. * TODO: Currently only the new GUM flow and Chrome is using the method. We
  427. * should make it work for all use cases.
  428. */
  429. function getSSConstraints(options = {}) {
  430. const {
  431. desktopStream,
  432. frameRate = {
  433. min: SS_DEFAULT_FRAME_RATE,
  434. max: SS_DEFAULT_FRAME_RATE
  435. }
  436. } = options;
  437. const { max, min } = frameRate;
  438. const constraints = {
  439. chromeMediaSource: options.source,
  440. maxWidth: window.screen.width,
  441. maxHeight: window.screen.height
  442. };
  443. if (typeof min === 'number') {
  444. constraints.minFrameRate = min;
  445. }
  446. if (typeof max === 'number') {
  447. constraints.maxFrameRate = max;
  448. }
  449. if (typeof desktopStream !== 'undefined') {
  450. constraints.chromeMediaSourceId = desktopStream;
  451. }
  452. return constraints;
  453. }
  454. /**
  455. * Generates constraints for screen sharing when using getDisplayMedia.
  456. * The constraints(MediaTrackConstraints) are applied to the resulting track.
  457. *
  458. * @returns {Object} - MediaTrackConstraints constraints.
  459. */
  460. function getTrackSSConstraints(options = {}) {
  461. // we used to set height and width in the constraints, but this can lead
  462. // to inconsistencies if the browser is on a lower resolution screen
  463. // and we share a screen with bigger resolution, so they are now not set
  464. const constraints = {
  465. frameRate: SS_DEFAULT_FRAME_RATE
  466. };
  467. const { desktopSharingFrameRate } = options;
  468. if (desktopSharingFrameRate && desktopSharingFrameRate.max) {
  469. constraints.frameRate = desktopSharingFrameRate.max;
  470. }
  471. return constraints;
  472. }
  473. /**
  474. * Updates the granted permissions based on the options we requested and the
  475. * streams we received.
  476. * @param um the options we requested to getUserMedia.
  477. * @param stream the stream we received from calling getUserMedia.
  478. */
  479. function updateGrantedPermissions(um, stream) {
  480. const audioTracksReceived
  481. = Boolean(stream) && stream.getAudioTracks().length > 0;
  482. const videoTracksReceived
  483. = Boolean(stream) && stream.getVideoTracks().length > 0;
  484. const grantedPermissions = {};
  485. if (um.indexOf('video') !== -1) {
  486. grantedPermissions.video = videoTracksReceived;
  487. }
  488. if (um.indexOf('audio') !== -1) {
  489. grantedPermissions.audio = audioTracksReceived;
  490. }
  491. eventEmitter.emit(RTCEvents.GRANTED_PERMISSIONS, grantedPermissions);
  492. }
  493. /**
  494. * Checks if new list of available media devices differs from previous one.
  495. * @param {MediaDeviceInfo[]} newDevices - list of new devices.
  496. * @returns {boolean} - true if list is different, false otherwise.
  497. */
  498. function compareAvailableMediaDevices(newDevices) {
  499. if (newDevices.length !== availableDevices.length) {
  500. return true;
  501. }
  502. /* eslint-disable newline-per-chained-call */
  503. return (
  504. newDevices.map(mediaDeviceInfoToJSON).sort().join('')
  505. !== availableDevices
  506. .map(mediaDeviceInfoToJSON).sort().join(''));
  507. /* eslint-enable newline-per-chained-call */
  508. /**
  509. *
  510. * @param info
  511. */
  512. function mediaDeviceInfoToJSON(info) {
  513. return JSON.stringify({
  514. kind: info.kind,
  515. deviceId: info.deviceId,
  516. groupId: info.groupId,
  517. label: info.label,
  518. facing: info.facing
  519. });
  520. }
  521. }
  522. /**
  523. * Sends analytics event with the passed device list.
  524. *
  525. * @param {Array<MediaDeviceInfo>} deviceList - List with info about the
  526. * available devices.
  527. * @returns {void}
  528. */
  529. function sendDeviceListToAnalytics(deviceList) {
  530. const audioInputDeviceCount
  531. = deviceList.filter(d => d.kind === 'audioinput').length;
  532. const audioOutputDeviceCount
  533. = deviceList.filter(d => d.kind === 'audiooutput').length;
  534. const videoInputDeviceCount
  535. = deviceList.filter(d => d.kind === 'videoinput').length;
  536. const videoOutputDeviceCount
  537. = deviceList.filter(d => d.kind === 'videooutput').length;
  538. deviceList.forEach(device => {
  539. const attributes = {
  540. 'audio_input_device_count': audioInputDeviceCount,
  541. 'audio_output_device_count': audioOutputDeviceCount,
  542. 'video_input_device_count': videoInputDeviceCount,
  543. 'video_output_device_count': videoOutputDeviceCount,
  544. 'device_id': device.deviceId,
  545. 'device_group_id': device.groupId,
  546. 'device_kind': device.kind,
  547. 'device_label': device.label
  548. };
  549. Statistics.sendAnalytics(AVAILABLE_DEVICE, attributes);
  550. });
  551. }
  552. /**
  553. * Event handler for the 'devicechange' event.
  554. *
  555. * @param {MediaDeviceInfo[]} devices - list of media devices.
  556. * @emits RTCEvents.DEVICE_LIST_CHANGED
  557. */
  558. function onMediaDevicesListChanged(devicesReceived) {
  559. availableDevices = devicesReceived.slice(0);
  560. logger.info(
  561. 'list of media devices has changed:',
  562. availableDevices);
  563. sendDeviceListToAnalytics(availableDevices);
  564. // Used by tracks to update the real device id before the consumer of lib-jitsi-meet receives the new device list.
  565. eventEmitter.emit(RTCEvents.DEVICE_LIST_WILL_CHANGE, devicesReceived);
  566. eventEmitter.emit(RTCEvents.DEVICE_LIST_CHANGED, devicesReceived);
  567. }
  568. /**
  569. * Handles the newly created Media Streams.
  570. * @param streams the new Media Streams
  571. * @param resolution the resolution of the video streams
  572. * @returns {*[]} object that describes the new streams
  573. */
  574. function handleLocalStream(streams, resolution) {
  575. let audioStream, desktopStream, videoStream;
  576. const res = [];
  577. // XXX The function obtainAudioAndVideoPermissions has examined the type of
  578. // the browser, its capabilities, etc. and has taken the decision whether to
  579. // invoke getUserMedia per device (e.g. Firefox) or once for both audio and
  580. // video (e.g. Chrome). In order to not duplicate the logic here, examine
  581. // the specified streams and figure out what we've received based on
  582. // obtainAudioAndVideoPermissions' decision.
  583. if (streams) {
  584. // As mentioned above, certian types of browser (e.g. Chrome) support
  585. // (with a result which meets our requirements expressed bellow) calling
  586. // getUserMedia once for both audio and video.
  587. const audioVideo = streams.audioVideo;
  588. if (audioVideo) {
  589. const audioTracks = audioVideo.getAudioTracks();
  590. if (audioTracks.length) {
  591. audioStream = new MediaStream();
  592. for (let i = 0; i < audioTracks.length; i++) {
  593. audioStream.addTrack(audioTracks[i]);
  594. }
  595. }
  596. const videoTracks = audioVideo.getVideoTracks();
  597. if (videoTracks.length) {
  598. videoStream = new MediaStream();
  599. for (let j = 0; j < videoTracks.length; j++) {
  600. videoStream.addTrack(videoTracks[j]);
  601. }
  602. }
  603. } else {
  604. // On other types of browser (e.g. Firefox) we choose (namely,
  605. // obtainAudioAndVideoPermissions) to call getUserMedia per device
  606. // (type).
  607. audioStream = streams.audio;
  608. videoStream = streams.video;
  609. }
  610. desktopStream = streams.desktop;
  611. }
  612. if (desktopStream) {
  613. const { stream, sourceId, sourceType } = desktopStream;
  614. res.push({
  615. stream,
  616. sourceId,
  617. sourceType,
  618. track: stream.getVideoTracks()[0],
  619. mediaType: MediaType.VIDEO,
  620. videoType: VideoType.DESKTOP
  621. });
  622. }
  623. if (audioStream) {
  624. res.push({
  625. stream: audioStream,
  626. track: audioStream.getAudioTracks()[0],
  627. mediaType: MediaType.AUDIO,
  628. videoType: null
  629. });
  630. }
  631. if (videoStream) {
  632. res.push({
  633. stream: videoStream,
  634. track: videoStream.getVideoTracks()[0],
  635. mediaType: MediaType.VIDEO,
  636. videoType: VideoType.CAMERA,
  637. resolution
  638. });
  639. }
  640. return res;
  641. }
  642. /**
  643. * Represents a default implementation of setting a <tt>MediaStream</tt> as the
  644. * source of a video element that tries to be browser-agnostic through feature
  645. * checking. Note though that it was not completely clear from the predating
  646. * browser-specific implementations what &quot;videoSrc&quot; was because one
  647. * implementation of {@link RTCUtils#getVideoSrc} would return
  648. * <tt>MediaStream</tt> (e.g. Firefox), another a <tt>string</tt> representation
  649. * of the <tt>URL</tt> of the <tt>MediaStream</tt> (e.g. Chrome) and the return
  650. * value was only used by {@link RTCUIHelper#getVideoId} which itself did not
  651. * appear to be used anywhere. Generally, the implementation will try to follow
  652. * the related standards i.e. work with the <tt>srcObject</tt> and <tt>src</tt>
  653. * properties of the specified <tt>element</tt> taking into account vender
  654. * prefixes.
  655. *
  656. * @param element the element whose video source/src is to be set to the
  657. * specified <tt>stream</tt>
  658. * @param {MediaStream} stream the <tt>MediaStream</tt> to set as the video
  659. * source/src of <tt>element</tt>
  660. */
  661. function defaultSetVideoSrc(element, stream) {
  662. // srcObject
  663. let srcObjectPropertyName = 'srcObject';
  664. if (!(srcObjectPropertyName in element)) {
  665. srcObjectPropertyName = 'mozSrcObject';
  666. if (!(srcObjectPropertyName in element)) {
  667. srcObjectPropertyName = null;
  668. }
  669. }
  670. if (srcObjectPropertyName) {
  671. element[srcObjectPropertyName] = stream;
  672. return;
  673. }
  674. // src
  675. let src;
  676. if (stream) {
  677. src = stream.jitsiObjectURL;
  678. // Save the created URL for stream so we can reuse it and not keep
  679. // creating URLs.
  680. if (!src) {
  681. stream.jitsiObjectURL = src = URL.createObjectURL(stream);
  682. }
  683. }
  684. element.src = src || '';
  685. }
  686. /**
  687. *
  688. */
  689. class RTCUtils extends Listenable {
  690. /**
  691. *
  692. */
  693. constructor() {
  694. super(eventEmitter);
  695. }
  696. /**
  697. * Depending on the browser, sets difference instance methods for
  698. * interacting with user media and adds methods to native WebRTC-related
  699. * objects. Also creates an instance variable for peer connection
  700. * constraints.
  701. *
  702. * @param {Object} options
  703. * @returns {void}
  704. */
  705. init(options = {}) {
  706. if (typeof options.disableAEC === 'boolean') {
  707. disableAEC = options.disableAEC;
  708. logger.info(`Disable AEC: ${disableAEC}`);
  709. }
  710. if (typeof options.disableNS === 'boolean') {
  711. disableNS = options.disableNS;
  712. logger.info(`Disable NS: ${disableNS}`);
  713. }
  714. if (typeof options.disableAP === 'boolean') {
  715. disableAP = options.disableAP;
  716. logger.info(`Disable AP: ${disableAP}`);
  717. }
  718. if (typeof options.disableAGC === 'boolean') {
  719. disableAGC = options.disableAGC;
  720. logger.info(`Disable AGC: ${disableAGC}`);
  721. }
  722. if (typeof options.disableHPF === 'boolean') {
  723. disableHPF = options.disableHPF;
  724. logger.info(`Disable HPF: ${disableHPF}`);
  725. }
  726. availableDevices = [];
  727. window.clearInterval(availableDevicesPollTimer);
  728. availableDevicesPollTimer = undefined;
  729. this.enumerateDevices = initEnumerateDevicesWithCallback();
  730. if (browser.usesNewGumFlow()) {
  731. this.RTCPeerConnectionType = RTCPeerConnection;
  732. this.attachMediaStream
  733. = wrapAttachMediaStream((element, stream) => {
  734. if (element) {
  735. element.srcObject = stream;
  736. }
  737. });
  738. this.getStreamID = ({ id }) => id;
  739. this.getTrackID = ({ id }) => id;
  740. } else if (browser.isChromiumBased() // this is chrome < 61
  741. || browser.isReactNative()) {
  742. this.RTCPeerConnectionType = RTCPeerConnection;
  743. this.attachMediaStream
  744. = wrapAttachMediaStream((element, stream) => {
  745. defaultSetVideoSrc(element, stream);
  746. return element;
  747. });
  748. this.getStreamID = function({ id }) {
  749. // A. MediaStreams from FF endpoints have the characters '{' and
  750. // '}' that make jQuery choke.
  751. // B. The react-native-webrtc implementation that we use at the
  752. // time of this writing returns a number for the id of
  753. // MediaStream. Let's just say that a number contains no special
  754. // characters.
  755. return (
  756. typeof id === 'number'
  757. ? id
  758. : SDPUtil.filterSpecialChars(id));
  759. };
  760. this.getTrackID = ({ id }) => id;
  761. if (!MediaStream.prototype.getVideoTracks) {
  762. MediaStream.prototype.getVideoTracks = function() {
  763. return this.videoTracks;
  764. };
  765. }
  766. if (!MediaStream.prototype.getAudioTracks) {
  767. MediaStream.prototype.getAudioTracks = function() {
  768. return this.audioTracks;
  769. };
  770. }
  771. } else {
  772. const message = 'Endpoint does not appear to be WebRTC-capable';
  773. logger.error(message);
  774. throw new Error(message);
  775. }
  776. this._initPCConstraints();
  777. screenObtainer.init(
  778. options,
  779. this.getUserMediaWithConstraints.bind(this));
  780. if (this.isDeviceListAvailable()) {
  781. this.enumerateDevices(ds => {
  782. availableDevices = ds.splice(0);
  783. logger.debug('Available devices: ', availableDevices);
  784. sendDeviceListToAnalytics(availableDevices);
  785. eventEmitter.emit(
  786. RTCEvents.DEVICE_LIST_AVAILABLE,
  787. availableDevices);
  788. // Use a shared callback to handle both the devicechange event
  789. // and the polling implementations. This prevents duplication
  790. // and works around a chrome bug (verified to occur on 68) where
  791. // devicechange fires twice in a row, which can cause async post
  792. // devicechange processing to collide.
  793. const updateKnownDevices = () => this.enumerateDevices(pds => {
  794. if (compareAvailableMediaDevices(pds)) {
  795. onMediaDevicesListChanged(pds);
  796. }
  797. });
  798. if (browser.supportsDeviceChangeEvent()) {
  799. navigator.mediaDevices.addEventListener(
  800. 'devicechange',
  801. updateKnownDevices);
  802. } else {
  803. // Periodically poll enumerateDevices() method to check if
  804. // list of media devices has changed.
  805. availableDevicesPollTimer = window.setInterval(
  806. updateKnownDevices,
  807. AVAILABLE_DEVICES_POLL_INTERVAL_TIME);
  808. }
  809. });
  810. }
  811. }
  812. /**
  813. * Creates instance objects for peer connection constraints both for p2p
  814. * and outside of p2p.
  815. */
  816. _initPCConstraints() {
  817. if (browser.isFirefox()) {
  818. this.pcConstraints = {};
  819. } else if (browser.isChromiumBased() || browser.isReactNative()) {
  820. this.pcConstraints = { optional: [
  821. { googHighStartBitrate: 0 },
  822. { googPayloadPadding: true },
  823. { googScreencastMinBitrate: 100 },
  824. { googCpuOveruseDetection: true },
  825. { googCpuOveruseEncodeUsage: true },
  826. { googCpuUnderuseThreshold: 55 },
  827. { googCpuOveruseThreshold: 85 }
  828. ] };
  829. this.p2pPcConstraints
  830. = JSON.parse(JSON.stringify(this.pcConstraints));
  831. }
  832. this.p2pPcConstraints = this.p2pPcConstraints || this.pcConstraints;
  833. }
  834. /* eslint-disable max-params */
  835. /**
  836. * @param {string[]} um required user media types
  837. * @param {Object} [options] optional parameters
  838. * @param {string} options.resolution
  839. * @param {number} options.bandwidth
  840. * @param {number} options.fps
  841. * @param {string} options.desktopStream
  842. * @param {string} options.cameraDeviceId
  843. * @param {string} options.micDeviceId
  844. * @param {Object} options.frameRate - used only for dekstop sharing.
  845. * @param {Object} options.frameRate.min - Minimum fps
  846. * @param {Object} options.frameRate.max - Maximum fps
  847. * @param {bool} options.screenShareAudio - Used by electron clients to
  848. * enable system audio screen sharing.
  849. * @returns {Promise} Returns a media stream on success or a JitsiTrackError
  850. * on failure.
  851. **/
  852. getUserMediaWithConstraints(um, options = {}) {
  853. const constraints = getConstraints(um, options);
  854. logger.info('Get media constraints', constraints);
  855. return new Promise((resolve, reject) => {
  856. navigator.mediaDevices.getUserMedia(constraints)
  857. .then(stream => {
  858. logger.log('onUserMediaSuccess');
  859. updateGrantedPermissions(um, stream);
  860. resolve(stream);
  861. })
  862. .catch(error => {
  863. logger.warn('Failed to get access to local media. '
  864. + ` ${error} ${constraints} `);
  865. updateGrantedPermissions(um, undefined);
  866. reject(new JitsiTrackError(error, constraints, um));
  867. });
  868. });
  869. }
  870. /**
  871. * Acquires a media stream via getUserMedia that
  872. * matches the given constraints
  873. *
  874. * @param {array} umDevices which devices to acquire (e.g. audio, video)
  875. * @param {Object} constraints - Stream specifications to use.
  876. * @returns {Promise}
  877. */
  878. _newGetUserMediaWithConstraints(umDevices, constraints = {}) {
  879. return new Promise((resolve, reject) => {
  880. navigator.mediaDevices.getUserMedia(constraints)
  881. .then(stream => {
  882. logger.log('onUserMediaSuccess');
  883. updateGrantedPermissions(umDevices, stream);
  884. resolve(stream);
  885. })
  886. .catch(error => {
  887. logger.warn('Failed to get access to local media. '
  888. + ` ${error} ${constraints} `);
  889. updateGrantedPermissions(umDevices, undefined);
  890. reject(new JitsiTrackError(error, constraints, umDevices));
  891. });
  892. });
  893. }
  894. /**
  895. * Acquire a display stream via the screenObtainer. This requires extra
  896. * logic compared to use screenObtainer versus normal device capture logic
  897. * in RTCUtils#_newGetUserMediaWithConstraints.
  898. *
  899. * @param {Object} options
  900. * @param {string[]} options.desktopSharingSources
  901. * @param {Object} options.desktopSharingFrameRate
  902. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  903. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  904. * @returns {Promise} A promise which will be resolved with an object which
  905. * contains the acquired display stream. If desktop sharing is not supported
  906. * then a rejected promise will be returned.
  907. */
  908. _newGetDesktopMedia(options) {
  909. if (!screenObtainer.isSupported() || !browser.supportsVideo()) {
  910. return Promise.reject(
  911. new Error('Desktop sharing is not supported!'));
  912. }
  913. return new Promise((resolve, reject) => {
  914. screenObtainer.obtainStream(
  915. this._parseDesktopSharingOptions(options),
  916. stream => {
  917. resolve(stream);
  918. },
  919. error => {
  920. reject(error);
  921. });
  922. });
  923. }
  924. /* eslint-enable max-params */
  925. /**
  926. * Creates the local MediaStreams.
  927. * @param {Object} [options] optional parameters
  928. * @param {Array} options.devices the devices that will be requested
  929. * @param {string} options.resolution resolution constraints
  930. * @param {string} options.cameraDeviceId
  931. * @param {string} options.micDeviceId
  932. * @param {Object} options.desktopSharingFrameRate
  933. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  934. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  935. * @returns {*} Promise object that will receive the new JitsiTracks
  936. */
  937. obtainAudioAndVideoPermissions(options = {}) {
  938. options.devices = options.devices || [ ...OLD_GUM_DEFAULT_DEVICES ];
  939. options.resolution = options.resolution || OLD_GUM_DEFAULT_RESOLUTION;
  940. const requestingDesktop = options.devices.includes('desktop');
  941. if (requestingDesktop && !screenObtainer.isSupported()) {
  942. return Promise.reject(
  943. new Error('Desktop sharing is not supported!'));
  944. }
  945. return this._getAudioAndVideoStreams(options).then(streams =>
  946. handleLocalStream(streams, options.resolution));
  947. }
  948. /**
  949. * Performs one call to getUserMedia for audio and/or video and another call
  950. * for desktop.
  951. *
  952. * @param {Object} options - An object describing how the gUM request should
  953. * be executed. See {@link obtainAudioAndVideoPermissions} for full options.
  954. * @returns {*} Promise object that will receive the new JitsiTracks on
  955. * success or a JitsiTrackError on failure.
  956. */
  957. _getAudioAndVideoStreams(options) {
  958. const requestingDesktop = options.devices.includes('desktop');
  959. options.devices = options.devices.filter(device =>
  960. device !== 'desktop');
  961. const gumPromise = options.devices.length
  962. ? this.getUserMediaWithConstraints(options.devices, options)
  963. : Promise.resolve(null);
  964. return gumPromise
  965. .then(avStream => {
  966. // If any requested devices are missing, call gum again in
  967. // an attempt to obtain the actual error. For example, the
  968. // requested video device is missing or permission was
  969. // denied.
  970. const missingTracks
  971. = this._getMissingTracks(options.devices, avStream);
  972. if (missingTracks.length) {
  973. this.stopMediaStream(avStream);
  974. return this.getUserMediaWithConstraints(
  975. missingTracks, options)
  976. // GUM has already failed earlier and this success
  977. // handling should not be reached.
  978. .then(() => Promise.reject(new JitsiTrackError(
  979. { name: 'UnknownError' },
  980. getConstraints(options.devices, options),
  981. missingTracks)));
  982. }
  983. return avStream;
  984. })
  985. .then(audioVideo => {
  986. if (!requestingDesktop) {
  987. return { audioVideo };
  988. }
  989. if (options.desktopSharingSourceDevice) {
  990. this.stopMediaStream(audioVideo);
  991. throw new Error('Using a camera as screenshare source is'
  992. + 'not supported on this browser.');
  993. }
  994. return new Promise((resolve, reject) => {
  995. screenObtainer.obtainStream(
  996. this._parseDesktopSharingOptions(options),
  997. desktop => resolve({
  998. audioVideo,
  999. desktop
  1000. }),
  1001. error => {
  1002. if (audioVideo) {
  1003. this.stopMediaStream(audioVideo);
  1004. }
  1005. reject(error);
  1006. });
  1007. });
  1008. });
  1009. }
  1010. /**
  1011. * Private utility for determining if the passed in MediaStream contains
  1012. * tracks of the type(s) specified in the requested devices.
  1013. *
  1014. * @param {string[]} requestedDevices - The track types that are expected to
  1015. * be includes in the stream.
  1016. * @param {MediaStream} stream - The MediaStream to check if it has the
  1017. * expected track types.
  1018. * @returns {string[]} An array of string with the missing track types. The
  1019. * array will be empty if all requestedDevices are found in the stream.
  1020. */
  1021. _getMissingTracks(requestedDevices = [], stream) {
  1022. const missingDevices = [];
  1023. const audioDeviceRequested = requestedDevices.includes('audio');
  1024. const audioTracksReceived
  1025. = stream && stream.getAudioTracks().length > 0;
  1026. if (audioDeviceRequested && !audioTracksReceived) {
  1027. missingDevices.push('audio');
  1028. }
  1029. const videoDeviceRequested = requestedDevices.includes('video');
  1030. const videoTracksReceived
  1031. = stream && stream.getVideoTracks().length > 0;
  1032. if (videoDeviceRequested && !videoTracksReceived) {
  1033. missingDevices.push('video');
  1034. }
  1035. return missingDevices;
  1036. }
  1037. /**
  1038. * Returns an object formatted for specifying desktop sharing parameters.
  1039. *
  1040. * @param {Object} options - Takes in the same options object as
  1041. * {@link obtainAudioAndVideoPermissions}.
  1042. * @returns {Object}
  1043. */
  1044. _parseDesktopSharingOptions(options) {
  1045. return {
  1046. desktopSharingSources: options.desktopSharingSources,
  1047. gumOptions: {
  1048. frameRate: options.desktopSharingFrameRate
  1049. },
  1050. trackOptions: getTrackSSConstraints(options)
  1051. };
  1052. }
  1053. /**
  1054. * Gets streams from specified device types. This function intentionally
  1055. * ignores errors for upstream to catch and handle instead.
  1056. *
  1057. * @param {Object} options - A hash describing what devices to get and
  1058. * relevant constraints.
  1059. * @param {string[]} options.devices - The types of media to capture. Valid
  1060. * values are "desktop", "audio", and "video".
  1061. * @param {Object} options.desktopSharingFrameRate
  1062. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  1063. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  1064. * @param {String} options.desktopSharingSourceDevice - The device id or
  1065. * label for a video input source that should be used for screensharing.
  1066. * @returns {Promise} The promise, when successful, will return an array of
  1067. * meta data for the requested device type, which includes the stream and
  1068. * track. If an error occurs, it will be deferred to the caller for
  1069. * handling.
  1070. */
  1071. newObtainAudioAndVideoPermissions(options) {
  1072. logger.info('Using the new gUM flow');
  1073. const mediaStreamsMetaData = [];
  1074. // Declare private functions to be used in the promise chain below.
  1075. // These functions are declared in the scope of this function because
  1076. // they are not being used anywhere else, so only this function needs to
  1077. // know about them.
  1078. /**
  1079. * Executes a request for desktop media if specified in options.
  1080. *
  1081. * @returns {Promise}
  1082. */
  1083. const maybeRequestDesktopDevice = function() {
  1084. const umDevices = options.devices || [];
  1085. const isDesktopDeviceRequested
  1086. = umDevices.indexOf('desktop') !== -1;
  1087. if (!isDesktopDeviceRequested) {
  1088. return Promise.resolve();
  1089. }
  1090. const {
  1091. desktopSharingSourceDevice,
  1092. desktopSharingSources,
  1093. desktopSharingFrameRate
  1094. } = options;
  1095. // Attempt to use a video input device as a screenshare source if
  1096. // the option is defined.
  1097. if (desktopSharingSourceDevice) {
  1098. const matchingDevice
  1099. = availableDevices && availableDevices.find(device =>
  1100. device.kind === 'videoinput'
  1101. && (device.deviceId === desktopSharingSourceDevice
  1102. || device.label === desktopSharingSourceDevice));
  1103. if (!matchingDevice) {
  1104. return Promise.reject(new JitsiTrackError(
  1105. { name: 'ConstraintNotSatisfiedError' },
  1106. {},
  1107. [ desktopSharingSourceDevice ]
  1108. ));
  1109. }
  1110. const requestedDevices = [ 'video' ];
  1111. // Leverage the helper used by {@link _newGetDesktopMedia} to
  1112. // get constraints for the desktop stream.
  1113. const { gumOptions, trackOptions }
  1114. = this._parseDesktopSharingOptions(options);
  1115. const constraints = {
  1116. video: {
  1117. ...gumOptions,
  1118. deviceId: matchingDevice.deviceId
  1119. }
  1120. };
  1121. return this._newGetUserMediaWithConstraints(
  1122. requestedDevices, constraints)
  1123. .then(stream => {
  1124. const track = stream && stream.getTracks()[0];
  1125. const applyConstrainsPromise
  1126. = track && track.applyConstraints
  1127. ? track.applyConstraints(trackOptions)
  1128. : Promise.resolve();
  1129. return applyConstrainsPromise
  1130. .then(() => {
  1131. return {
  1132. sourceType: 'device',
  1133. stream
  1134. };
  1135. });
  1136. });
  1137. }
  1138. return this._newGetDesktopMedia({
  1139. desktopSharingSources,
  1140. desktopSharingFrameRate
  1141. });
  1142. }.bind(this);
  1143. /**
  1144. * Creates a meta data object about the passed in desktopStream and
  1145. * pushes the meta data to the internal array mediaStreamsMetaData to be
  1146. * returned later.
  1147. *
  1148. * @param {MediaStreamTrack} desktopStream - A track for a desktop
  1149. * capture.
  1150. * @returns {void}
  1151. */
  1152. const maybeCreateAndAddDesktopTrack = function(desktopStream) {
  1153. if (!desktopStream) {
  1154. return;
  1155. }
  1156. const { stream, sourceId, sourceType } = desktopStream;
  1157. const desktopAudioTracks = stream.getAudioTracks();
  1158. if (desktopAudioTracks.length) {
  1159. const desktopAudioStream = new MediaStream(desktopAudioTracks);
  1160. mediaStreamsMetaData.push({
  1161. stream: desktopAudioStream,
  1162. sourceId,
  1163. sourceType,
  1164. track: desktopAudioStream.getAudioTracks()[0]
  1165. });
  1166. }
  1167. const desktopVideoTracks = stream.getVideoTracks();
  1168. if (desktopVideoTracks.length) {
  1169. const desktopVideoStream = new MediaStream(desktopVideoTracks);
  1170. mediaStreamsMetaData.push({
  1171. stream: desktopVideoStream,
  1172. sourceId,
  1173. sourceType,
  1174. track: desktopVideoStream.getVideoTracks()[0],
  1175. videoType: VideoType.DESKTOP
  1176. });
  1177. }
  1178. };
  1179. /**
  1180. * Executes a request for audio and/or video, as specified in options.
  1181. * By default both audio and video will be captured if options.devices
  1182. * is not defined.
  1183. *
  1184. * @returns {Promise}
  1185. */
  1186. const maybeRequestCaptureDevices = function() {
  1187. const umDevices = options.devices || [ 'audio', 'video' ];
  1188. const requestedCaptureDevices = umDevices.filter(device =>
  1189. device === 'audio'
  1190. || (device === 'video' && browser.supportsVideo()));
  1191. if (!requestedCaptureDevices.length) {
  1192. return Promise.resolve();
  1193. }
  1194. const constraints = newGetConstraints(
  1195. requestedCaptureDevices, options);
  1196. logger.info('Got media constraints: ', constraints);
  1197. return this._newGetUserMediaWithConstraints(
  1198. requestedCaptureDevices, constraints);
  1199. }.bind(this);
  1200. /**
  1201. * Splits the passed in media stream into separate audio and video
  1202. * streams and creates meta data objects for each and pushes them to the
  1203. * internal array mediaStreamsMetaData to be returned later.
  1204. *
  1205. * @param {MediaStreamTrack} avStream - A track for with audio and/or
  1206. * video track.
  1207. * @returns {void}
  1208. */
  1209. const maybeCreateAndAddAVTracks = function(avStream) {
  1210. if (!avStream) {
  1211. return;
  1212. }
  1213. const audioTracks = avStream.getAudioTracks();
  1214. if (audioTracks.length) {
  1215. const audioStream = new MediaStream(audioTracks);
  1216. mediaStreamsMetaData.push({
  1217. stream: audioStream,
  1218. track: audioStream.getAudioTracks()[0],
  1219. effects: options.effects
  1220. });
  1221. }
  1222. const videoTracks = avStream.getVideoTracks();
  1223. if (videoTracks.length) {
  1224. const videoStream = new MediaStream(videoTracks);
  1225. mediaStreamsMetaData.push({
  1226. stream: videoStream,
  1227. track: videoStream.getVideoTracks()[0],
  1228. videoType: VideoType.CAMERA,
  1229. effects: options.effects
  1230. });
  1231. }
  1232. };
  1233. return maybeRequestDesktopDevice()
  1234. .then(maybeCreateAndAddDesktopTrack)
  1235. .then(maybeRequestCaptureDevices)
  1236. .then(maybeCreateAndAddAVTracks)
  1237. .then(() => mediaStreamsMetaData)
  1238. .catch(error => {
  1239. mediaStreamsMetaData.forEach(({ stream }) => {
  1240. this.stopMediaStream(stream);
  1241. });
  1242. return Promise.reject(error);
  1243. });
  1244. }
  1245. /**
  1246. * Checks whether it is possible to enumerate available cameras/microphones.
  1247. *
  1248. * @returns {boolean} {@code true} if the device listing is available;
  1249. * {@code false}, otherwise.
  1250. */
  1251. isDeviceListAvailable() {
  1252. return Boolean(
  1253. navigator.mediaDevices
  1254. && navigator.mediaDevices.enumerateDevices);
  1255. }
  1256. /**
  1257. * Returns true if changing the input (camera / microphone) or output
  1258. * (audio) device is supported and false if not.
  1259. * @params {string} [deviceType] - type of device to change. Default is
  1260. * undefined or 'input', 'output' - for audio output device change.
  1261. * @returns {boolean} true if available, false otherwise.
  1262. */
  1263. isDeviceChangeAvailable(deviceType) {
  1264. return deviceType === 'output' || deviceType === 'audiooutput'
  1265. ? isAudioOutputDeviceChangeAvailable
  1266. : true;
  1267. }
  1268. /**
  1269. * A method to handle stopping of the stream.
  1270. * One point to handle the differences in various implementations.
  1271. * @param mediaStream MediaStream object to stop.
  1272. */
  1273. stopMediaStream(mediaStream) {
  1274. if (!mediaStream) {
  1275. return;
  1276. }
  1277. mediaStream.getTracks().forEach(track => {
  1278. if (track.stop) {
  1279. track.stop();
  1280. }
  1281. });
  1282. // leave stop for implementation still using it
  1283. if (mediaStream.stop) {
  1284. mediaStream.stop();
  1285. }
  1286. // The MediaStream implementation of the react-native-webrtc project has
  1287. // an explicit release method that is to be invoked in order to release
  1288. // used resources such as memory.
  1289. if (mediaStream.release) {
  1290. mediaStream.release();
  1291. }
  1292. // if we have done createObjectURL, lets clean it
  1293. const url = mediaStream.jitsiObjectURL;
  1294. if (url) {
  1295. delete mediaStream.jitsiObjectURL;
  1296. URL.revokeObjectURL(url);
  1297. }
  1298. }
  1299. /**
  1300. * Returns whether the desktop sharing is enabled or not.
  1301. * @returns {boolean}
  1302. */
  1303. isDesktopSharingEnabled() {
  1304. return screenObtainer.isSupported();
  1305. }
  1306. /**
  1307. * Sets current audio output device.
  1308. * @param {string} deviceId - id of 'audiooutput' device from
  1309. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  1310. * device
  1311. * @returns {Promise} - resolves when audio output is changed, is rejected
  1312. * otherwise
  1313. */
  1314. setAudioOutputDevice(deviceId) {
  1315. if (!this.isDeviceChangeAvailable('output')) {
  1316. return Promise.reject(
  1317. new Error('Audio output device change is not supported'));
  1318. }
  1319. return featureDetectionAudioEl.setSinkId(deviceId)
  1320. .then(() => {
  1321. audioOutputDeviceId = deviceId;
  1322. audioOutputChanged = true;
  1323. logger.log(`Audio output device set to ${deviceId}`);
  1324. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1325. deviceId);
  1326. });
  1327. }
  1328. /**
  1329. * Returns currently used audio output device id, '' stands for default
  1330. * device
  1331. * @returns {string}
  1332. */
  1333. getAudioOutputDevice() {
  1334. return audioOutputDeviceId;
  1335. }
  1336. /**
  1337. * Returns list of available media devices if its obtained, otherwise an
  1338. * empty array is returned/
  1339. * @returns {Array} list of available media devices.
  1340. */
  1341. getCurrentlyAvailableMediaDevices() {
  1342. return availableDevices;
  1343. }
  1344. /**
  1345. * Returns event data for device to be reported to stats.
  1346. * @returns {MediaDeviceInfo} device.
  1347. */
  1348. getEventDataForActiveDevice(device) {
  1349. const deviceList = [];
  1350. const deviceData = {
  1351. 'deviceId': device.deviceId,
  1352. 'kind': device.kind,
  1353. 'label': device.label,
  1354. 'groupId': device.groupId
  1355. };
  1356. deviceList.push(deviceData);
  1357. return { deviceList };
  1358. }
  1359. /**
  1360. * Configures the given PeerConnection constraints to either enable or
  1361. * disable (according to the value of the 'enable' parameter) the
  1362. * 'googSuspendBelowMinBitrate' option.
  1363. * @param constraints the constraints on which to operate.
  1364. * @param enable {boolean} whether to enable or disable the suspend video
  1365. * option.
  1366. */
  1367. setSuspendVideo(constraints, enable) {
  1368. if (!constraints.optional) {
  1369. constraints.optional = [];
  1370. }
  1371. // Get rid of all "googSuspendBelowMinBitrate" constraints (we assume
  1372. // that the elements of constraints.optional contain a single property).
  1373. constraints.optional
  1374. = constraints.optional.filter(
  1375. c => !c.hasOwnProperty('googSuspendBelowMinBitrate'));
  1376. if (enable) {
  1377. constraints.optional.push({ googSuspendBelowMinBitrate: 'true' });
  1378. }
  1379. }
  1380. }
  1381. const rtcUtils = new RTCUtils();
  1382. /**
  1383. * Wraps original attachMediaStream function to set current audio output device
  1384. * if this is supported.
  1385. * @param {Function} origAttachMediaStream
  1386. * @returns {Function}
  1387. */
  1388. function wrapAttachMediaStream(origAttachMediaStream) {
  1389. return function(element, stream) {
  1390. // eslint-disable-next-line prefer-rest-params
  1391. const res = origAttachMediaStream.apply(rtcUtils, arguments);
  1392. if (stream
  1393. && rtcUtils.isDeviceChangeAvailable('output')
  1394. && stream.getAudioTracks
  1395. && stream.getAudioTracks().length
  1396. // we skip setting audio output if there was no explicit change
  1397. && audioOutputChanged) {
  1398. element.setSinkId(rtcUtils.getAudioOutputDevice())
  1399. .catch(function(ex) {
  1400. const err
  1401. = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  1402. GlobalOnErrorHandler.callUnhandledRejectionHandler({
  1403. promise: this, // eslint-disable-line no-invalid-this
  1404. reason: err
  1405. });
  1406. logger.warn(
  1407. 'Failed to set audio output device for the element.'
  1408. + ' Default audio output device will be used'
  1409. + ' instead',
  1410. element,
  1411. err);
  1412. });
  1413. }
  1414. return res;
  1415. };
  1416. }
  1417. export default rtcUtils;