Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

RTCUtils.js 54KB

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