Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

RTCUtils.js 55KB

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