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

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