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

RTCUtils.js 56KB

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