You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RTCUtils.js 54KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  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. // Enables stereo.
  79. let stereo = 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. constraints.audio = {
  369. autoGainControl: !disableAGC && !disableAP,
  370. deviceId: options.micDeviceId,
  371. echoCancellation: !disableAEC && !disableAP,
  372. noiseSuppression: !disableNS && !disableAP
  373. };
  374. if (stereo) {
  375. Object.assign(constraints.audio, { channelCount: 2 });
  376. }
  377. } else {
  378. constraints.audio = false;
  379. }
  380. if (um.indexOf('desktop') >= 0) {
  381. if (!constraints.video || typeof constraints.video === 'boolean') {
  382. constraints.video = {};
  383. }
  384. constraints.video = {
  385. mandatory: getSSConstraints({
  386. ...options,
  387. source: 'desktop'
  388. })
  389. };
  390. }
  391. return constraints;
  392. }
  393. /**
  394. * Generates GUM constraints for screen sharing.
  395. *
  396. * @param {Object} options - The options passed to
  397. * <tt>obtainAudioAndVideoPermissions</tt>.
  398. * @returns {Object} - GUM constraints.
  399. *
  400. * TODO: Currently only the new GUM flow and Chrome is using the method. We
  401. * should make it work for all use cases.
  402. */
  403. function getSSConstraints(options = {}) {
  404. const {
  405. desktopStream,
  406. frameRate = {
  407. min: SS_DEFAULT_FRAME_RATE,
  408. max: SS_DEFAULT_FRAME_RATE
  409. }
  410. } = options;
  411. const { max, min } = frameRate;
  412. const constraints = {
  413. chromeMediaSource: options.source,
  414. maxWidth: window.screen.width,
  415. maxHeight: window.screen.height
  416. };
  417. if (typeof min === 'number') {
  418. constraints.minFrameRate = min;
  419. }
  420. if (typeof max === 'number') {
  421. constraints.maxFrameRate = max;
  422. }
  423. if (typeof desktopStream !== 'undefined') {
  424. constraints.chromeMediaSourceId = desktopStream;
  425. }
  426. return constraints;
  427. }
  428. /**
  429. * Generates constraints for screen sharing when using getDisplayMedia.
  430. * The constraints(MediaTrackConstraints) are applied to the resulting track.
  431. *
  432. * @returns {Object} - MediaTrackConstraints constraints.
  433. */
  434. function getTrackSSConstraints(options = {}) {
  435. // we used to set height and width in the constraints, but this can lead
  436. // to inconsistencies if the browser is on a lower resolution screen
  437. // and we share a screen with bigger resolution, so they are now not set
  438. const constraints = {
  439. frameRate: SS_DEFAULT_FRAME_RATE
  440. };
  441. const { desktopSharingFrameRate } = options;
  442. if (desktopSharingFrameRate && desktopSharingFrameRate.max) {
  443. constraints.frameRate = desktopSharingFrameRate.max;
  444. }
  445. return constraints;
  446. }
  447. /**
  448. * Updates the granted permissions based on the options we requested and the
  449. * streams we received.
  450. * @param um the options we requested to getUserMedia.
  451. * @param stream the stream we received from calling getUserMedia.
  452. */
  453. function updateGrantedPermissions(um, stream) {
  454. const audioTracksReceived
  455. = Boolean(stream) && stream.getAudioTracks().length > 0;
  456. const videoTracksReceived
  457. = Boolean(stream) && stream.getVideoTracks().length > 0;
  458. const grantedPermissions = {};
  459. if (um.indexOf('video') !== -1) {
  460. grantedPermissions.video = videoTracksReceived;
  461. }
  462. if (um.indexOf('audio') !== -1) {
  463. grantedPermissions.audio = audioTracksReceived;
  464. }
  465. eventEmitter.emit(RTCEvents.PERMISSIONS_CHANGED, grantedPermissions);
  466. }
  467. /**
  468. * Checks if new list of available media devices differs from previous one.
  469. * @param {MediaDeviceInfo[]} newDevices - list of new devices.
  470. * @returns {boolean} - true if list is different, false otherwise.
  471. */
  472. function compareAvailableMediaDevices(newDevices) {
  473. if (newDevices.length !== availableDevices.length) {
  474. return true;
  475. }
  476. /* eslint-disable newline-per-chained-call */
  477. return (
  478. newDevices.map(mediaDeviceInfoToJSON).sort().join('')
  479. !== availableDevices
  480. .map(mediaDeviceInfoToJSON).sort().join(''));
  481. /* eslint-enable newline-per-chained-call */
  482. /**
  483. *
  484. * @param info
  485. */
  486. function mediaDeviceInfoToJSON(info) {
  487. return JSON.stringify({
  488. kind: info.kind,
  489. deviceId: info.deviceId,
  490. groupId: info.groupId,
  491. label: info.label,
  492. facing: info.facing
  493. });
  494. }
  495. }
  496. /**
  497. * Sends analytics event with the passed device list.
  498. *
  499. * @param {Array<MediaDeviceInfo>} deviceList - List with info about the
  500. * available devices.
  501. * @returns {void}
  502. */
  503. function sendDeviceListToAnalytics(deviceList) {
  504. const audioInputDeviceCount
  505. = deviceList.filter(d => d.kind === 'audioinput').length;
  506. const audioOutputDeviceCount
  507. = deviceList.filter(d => d.kind === 'audiooutput').length;
  508. const videoInputDeviceCount
  509. = deviceList.filter(d => d.kind === 'videoinput').length;
  510. const videoOutputDeviceCount
  511. = deviceList.filter(d => d.kind === 'videooutput').length;
  512. deviceList.forEach(device => {
  513. const attributes = {
  514. 'audio_input_device_count': audioInputDeviceCount,
  515. 'audio_output_device_count': audioOutputDeviceCount,
  516. 'video_input_device_count': videoInputDeviceCount,
  517. 'video_output_device_count': videoOutputDeviceCount,
  518. 'device_id': device.deviceId,
  519. 'device_group_id': device.groupId,
  520. 'device_kind': device.kind,
  521. 'device_label': device.label
  522. };
  523. Statistics.sendAnalytics(AVAILABLE_DEVICE, attributes);
  524. });
  525. }
  526. /**
  527. * Update known devices.
  528. *
  529. * @param {Array<Object>} pds - The new devices.
  530. * @returns {void}
  531. *
  532. * NOTE: Use this function as a shared callback to handle both the devicechange event and the polling implementations.
  533. * This prevents duplication and works around a chrome bug (verified to occur on 68) where devicechange fires twice in
  534. * a row, which can cause async post devicechange processing to collide.
  535. */
  536. function updateKnownDevices(pds) {
  537. if (compareAvailableMediaDevices(pds)) {
  538. onMediaDevicesListChanged(pds);
  539. }
  540. }
  541. /**
  542. * Event handler for the 'devicechange' event.
  543. *
  544. * @param {MediaDeviceInfo[]} devices - list of media devices.
  545. * @emits RTCEvents.DEVICE_LIST_CHANGED
  546. */
  547. function onMediaDevicesListChanged(devicesReceived) {
  548. availableDevices = devicesReceived.slice(0);
  549. logger.info('list of media devices has changed:', availableDevices);
  550. sendDeviceListToAnalytics(availableDevices);
  551. // Used by tracks to update the real device id before the consumer of lib-jitsi-meet receives the new device list.
  552. eventEmitter.emit(RTCEvents.DEVICE_LIST_WILL_CHANGE, availableDevices);
  553. eventEmitter.emit(RTCEvents.DEVICE_LIST_CHANGED, availableDevices);
  554. }
  555. /**
  556. * Handles the newly created Media Streams.
  557. * @param streams the new Media Streams
  558. * @param resolution the resolution of the video streams
  559. * @returns {*[]} object that describes the new streams
  560. */
  561. function handleLocalStream(streams, resolution) {
  562. let audioStream, desktopStream, videoStream;
  563. const res = [];
  564. // XXX The function obtainAudioAndVideoPermissions has examined the type of
  565. // the browser, its capabilities, etc. and has taken the decision whether to
  566. // invoke getUserMedia per device (e.g. Firefox) or once for both audio and
  567. // video (e.g. Chrome). In order to not duplicate the logic here, examine
  568. // the specified streams and figure out what we've received based on
  569. // obtainAudioAndVideoPermissions' decision.
  570. if (streams) {
  571. // As mentioned above, certian types of browser (e.g. Chrome) support
  572. // (with a result which meets our requirements expressed bellow) calling
  573. // getUserMedia once for both audio and video.
  574. const audioVideo = streams.audioVideo;
  575. if (audioVideo) {
  576. const audioTracks = audioVideo.getAudioTracks();
  577. if (audioTracks.length) {
  578. audioStream = new MediaStream();
  579. for (let i = 0; i < audioTracks.length; i++) {
  580. audioStream.addTrack(audioTracks[i]);
  581. }
  582. }
  583. const videoTracks = audioVideo.getVideoTracks();
  584. if (videoTracks.length) {
  585. videoStream = new MediaStream();
  586. for (let j = 0; j < videoTracks.length; j++) {
  587. videoStream.addTrack(videoTracks[j]);
  588. }
  589. }
  590. audioVideo.release && audioVideo.release(false);
  591. } else {
  592. // On other types of browser (e.g. Firefox) we choose (namely,
  593. // obtainAudioAndVideoPermissions) to call getUserMedia per device
  594. // (type).
  595. audioStream = streams.audio;
  596. videoStream = streams.video;
  597. }
  598. desktopStream = streams.desktop;
  599. }
  600. if (desktopStream) {
  601. const { stream, sourceId, sourceType } = desktopStream;
  602. res.push({
  603. stream,
  604. sourceId,
  605. sourceType,
  606. track: stream.getVideoTracks()[0],
  607. mediaType: MediaType.VIDEO,
  608. videoType: VideoType.DESKTOP
  609. });
  610. }
  611. if (audioStream) {
  612. res.push({
  613. stream: audioStream,
  614. track: audioStream.getAudioTracks()[0],
  615. mediaType: MediaType.AUDIO,
  616. videoType: null
  617. });
  618. }
  619. if (videoStream) {
  620. res.push({
  621. stream: videoStream,
  622. track: videoStream.getVideoTracks()[0],
  623. mediaType: MediaType.VIDEO,
  624. videoType: VideoType.CAMERA,
  625. resolution
  626. });
  627. }
  628. return res;
  629. }
  630. /**
  631. *
  632. */
  633. class RTCUtils extends Listenable {
  634. /**
  635. *
  636. */
  637. constructor() {
  638. super(eventEmitter);
  639. }
  640. /**
  641. * Depending on the browser, sets difference instance methods for
  642. * interacting with user media and adds methods to native WebRTC-related
  643. * objects. Also creates an instance variable for peer connection
  644. * constraints.
  645. *
  646. * @param {Object} options
  647. * @returns {void}
  648. */
  649. init(options = {}) {
  650. if (typeof options.disableAEC === 'boolean') {
  651. disableAEC = options.disableAEC;
  652. logger.info(`Disable AEC: ${disableAEC}`);
  653. }
  654. if (typeof options.disableNS === 'boolean') {
  655. disableNS = options.disableNS;
  656. logger.info(`Disable NS: ${disableNS}`);
  657. }
  658. if (typeof options.disableAP === 'boolean') {
  659. disableAP = options.disableAP;
  660. logger.info(`Disable AP: ${disableAP}`);
  661. }
  662. if (typeof options.disableAGC === 'boolean') {
  663. disableAGC = options.disableAGC;
  664. logger.info(`Disable AGC: ${disableAGC}`);
  665. }
  666. if (typeof options.disableHPF === 'boolean') {
  667. disableHPF = options.disableHPF;
  668. logger.info(`Disable HPF: ${disableHPF}`);
  669. }
  670. if (typeof options.audioQuality?.stereo === 'boolean') {
  671. stereo = options.audioQuality.stereo;
  672. logger.info(`Stereo: ${stereo}`);
  673. }
  674. window.clearInterval(availableDevicesPollTimer);
  675. availableDevicesPollTimer = undefined;
  676. if (browser.usesNewGumFlow()) {
  677. this.RTCPeerConnectionType = RTCPeerConnection;
  678. this.attachMediaStream
  679. = wrapAttachMediaStream((element, stream) => {
  680. if (element) {
  681. element.srcObject = stream;
  682. }
  683. });
  684. this.getStreamID = ({ id }) => id;
  685. this.getTrackID = ({ id }) => id;
  686. } else if (browser.isReactNative()) {
  687. this.RTCPeerConnectionType = RTCPeerConnection;
  688. this.attachMediaStream = undefined; // Unused on React Native.
  689. this.getStreamID = function({ id }) {
  690. // The react-native-webrtc implementation that we use at the
  691. // time of this writing returns a number for the id of
  692. // MediaStream. Let's just say that a number contains no special
  693. // characters.
  694. return (
  695. typeof id === 'number'
  696. ? id
  697. : SDPUtil.filterSpecialChars(id));
  698. };
  699. this.getTrackID = ({ id }) => id;
  700. } else {
  701. const message = 'Endpoint does not appear to be WebRTC-capable';
  702. logger.error(message);
  703. throw new Error(message);
  704. }
  705. this.pcConstraints = browser.isChromiumBased() || browser.isReactNative()
  706. ? { optional: [
  707. { googScreencastMinBitrate: 100 },
  708. { googCpuOveruseDetection: true }
  709. ] }
  710. : {};
  711. screenObtainer.init(
  712. options,
  713. this.getUserMediaWithConstraints.bind(this));
  714. if (this.isDeviceListAvailable()) {
  715. this.enumerateDevices(ds => {
  716. availableDevices = ds.slice(0);
  717. logger.debug('Available devices: ', availableDevices);
  718. sendDeviceListToAnalytics(availableDevices);
  719. eventEmitter.emit(
  720. RTCEvents.DEVICE_LIST_AVAILABLE,
  721. availableDevices);
  722. if (browser.supportsDeviceChangeEvent()) {
  723. navigator.mediaDevices.addEventListener(
  724. 'devicechange',
  725. () => this.enumerateDevices(emptyFuncton));
  726. } else {
  727. // Periodically poll enumerateDevices() method to check if
  728. // list of media devices has changed.
  729. availableDevicesPollTimer = window.setInterval(
  730. () => this.enumerateDevices(emptyFuncton),
  731. AVAILABLE_DEVICES_POLL_INTERVAL_TIME);
  732. }
  733. });
  734. }
  735. }
  736. /**
  737. *
  738. * @param {Function} callback
  739. */
  740. enumerateDevices(callback) {
  741. navigator.mediaDevices.enumerateDevices()
  742. .then(devices => {
  743. updateKnownDevices(devices);
  744. callback(devices);
  745. })
  746. .catch(error => {
  747. logger.warn(`Failed to enumerate devices. ${error}`);
  748. updateKnownDevices([]);
  749. callback([]);
  750. });
  751. }
  752. /* eslint-disable max-params */
  753. /**
  754. * @param {string[]} um required user media types
  755. * @param {Object} [options] optional parameters
  756. * @param {string} options.resolution
  757. * @param {number} options.bandwidth
  758. * @param {number} options.fps
  759. * @param {string} options.desktopStream
  760. * @param {string} options.cameraDeviceId
  761. * @param {string} options.micDeviceId
  762. * @param {Object} options.frameRate - used only for dekstop sharing.
  763. * @param {Object} options.frameRate.min - Minimum fps
  764. * @param {Object} options.frameRate.max - Maximum fps
  765. * @param {bool} options.screenShareAudio - Used by electron clients to
  766. * enable system audio screen sharing.
  767. * @param {number} options.timeout - The timeout in ms for GUM.
  768. * @returns {Promise} Returns a media stream on success or a JitsiTrackError
  769. * on failure.
  770. **/
  771. getUserMediaWithConstraints(um, options = {}) {
  772. const {
  773. timeout,
  774. ...otherOptions
  775. } = options;
  776. const constraints = getConstraints(um, otherOptions);
  777. logger.info('Get media constraints', JSON.stringify(constraints));
  778. return this._getUserMedia(um, constraints, timeout);
  779. }
  780. /**
  781. * Acquires a media stream via getUserMedia that
  782. * matches the given constraints
  783. *
  784. * @param {array} umDevices which devices to acquire (e.g. audio, video)
  785. * @param {Object} constraints - Stream specifications to use.
  786. * @param {number} timeout - The timeout in ms for GUM.
  787. * @returns {Promise}
  788. */
  789. _getUserMedia(umDevices, constraints = {}, timeout = 0) {
  790. return new Promise((resolve, reject) => {
  791. let gumTimeout, timeoutExpired = false;
  792. if (typeof timeout === 'number' && !isNaN(timeout) && timeout > 0) {
  793. gumTimeout = setTimeout(() => {
  794. timeoutExpired = true;
  795. gumTimeout = undefined;
  796. reject(new JitsiTrackError(JitsiTrackErrors.TIMEOUT));
  797. }, timeout);
  798. }
  799. navigator.mediaDevices.getUserMedia(constraints)
  800. .then(stream => {
  801. logger.log('onUserMediaSuccess');
  802. updateGrantedPermissions(umDevices, stream);
  803. if (!timeoutExpired) {
  804. if (typeof gumTimeout !== 'undefined') {
  805. clearTimeout(gumTimeout);
  806. }
  807. resolve(stream);
  808. }
  809. })
  810. .catch(error => {
  811. logger.warn(`Failed to get access to local media. ${error} ${JSON.stringify(constraints)}`);
  812. const jitsiError = new JitsiTrackError(error, constraints, umDevices);
  813. if (!timeoutExpired) {
  814. if (typeof gumTimeout !== 'undefined') {
  815. clearTimeout(gumTimeout);
  816. }
  817. reject(error);
  818. }
  819. if (jitsiError.name === JitsiTrackErrors.PERMISSION_DENIED) {
  820. updateGrantedPermissions(umDevices, undefined);
  821. }
  822. // else {
  823. // Probably the error is not caused by the lack of permissions and we don't need to update them.
  824. // }
  825. });
  826. });
  827. }
  828. /**
  829. * Acquire a display stream via the screenObtainer. This requires extra
  830. * logic compared to use screenObtainer versus normal device capture logic
  831. * in RTCUtils#_getUserMedia.
  832. *
  833. * @param {Object} options
  834. * @param {string[]} options.desktopSharingSources
  835. * @param {Object} options.desktopSharingFrameRate
  836. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  837. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  838. * @returns {Promise} A promise which will be resolved with an object which
  839. * contains the acquired display stream. If desktop sharing is not supported
  840. * then a rejected promise will be returned.
  841. */
  842. _newGetDesktopMedia(options) {
  843. if (!screenObtainer.isSupported()) {
  844. return Promise.reject(new Error('Desktop sharing is not supported!'));
  845. }
  846. return new Promise((resolve, reject) => {
  847. screenObtainer.obtainStream(
  848. this._parseDesktopSharingOptions(options),
  849. stream => {
  850. resolve(stream);
  851. },
  852. error => {
  853. reject(error);
  854. });
  855. });
  856. }
  857. /* eslint-enable max-params */
  858. /**
  859. * Creates the local MediaStreams.
  860. * @param {Object} [options] optional parameters
  861. * @param {Array} options.devices the devices that will be requested
  862. * @param {string} options.resolution resolution constraints
  863. * @param {string} options.cameraDeviceId
  864. * @param {string} options.micDeviceId
  865. * @param {Object} options.desktopSharingFrameRate
  866. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  867. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  868. * @returns {*} Promise object that will receive the new JitsiTracks
  869. */
  870. obtainAudioAndVideoPermissions(options = {}) {
  871. options.devices = options.devices || [ ...OLD_GUM_DEFAULT_DEVICES ];
  872. options.resolution = options.resolution || OLD_GUM_DEFAULT_RESOLUTION;
  873. const requestingDesktop = options.devices.includes('desktop');
  874. if (requestingDesktop && !screenObtainer.isSupported()) {
  875. return Promise.reject(
  876. new Error('Desktop sharing is not supported!'));
  877. }
  878. return this._getAudioAndVideoStreams(options).then(streams =>
  879. handleLocalStream(streams, options.resolution));
  880. }
  881. /**
  882. * Performs one call to getUserMedia for audio and/or video and another call
  883. * for desktop.
  884. *
  885. * @param {Object} options - An object describing how the gUM request should
  886. * be executed. See {@link obtainAudioAndVideoPermissions} for full options.
  887. * @returns {*} Promise object that will receive the new JitsiTracks on
  888. * success or a JitsiTrackError on failure.
  889. */
  890. _getAudioAndVideoStreams(options) {
  891. const requestingDesktop = options.devices.includes('desktop');
  892. options.devices = options.devices.filter(device =>
  893. device !== 'desktop');
  894. const gumPromise = options.devices.length
  895. ? this.getUserMediaWithConstraints(options.devices, options)
  896. : Promise.resolve(null);
  897. return gumPromise
  898. .then(avStream => {
  899. // If any requested devices are missing, call gum again in
  900. // an attempt to obtain the actual error. For example, the
  901. // requested video device is missing or permission was
  902. // denied.
  903. const missingTracks
  904. = this._getMissingTracks(options.devices, avStream);
  905. if (missingTracks.length) {
  906. this.stopMediaStream(avStream);
  907. return this.getUserMediaWithConstraints(
  908. missingTracks, options)
  909. // GUM has already failed earlier and this success
  910. // handling should not be reached.
  911. .then(() => Promise.reject(new JitsiTrackError(
  912. { name: 'UnknownError' },
  913. getConstraints(options.devices, options),
  914. missingTracks)));
  915. }
  916. return avStream;
  917. })
  918. .then(audioVideo => {
  919. if (!requestingDesktop) {
  920. return { audioVideo };
  921. }
  922. if (options.desktopSharingSourceDevice) {
  923. this.stopMediaStream(audioVideo);
  924. throw new Error('Using a camera as screenshare source is'
  925. + 'not supported on this browser.');
  926. }
  927. return new Promise((resolve, reject) => {
  928. screenObtainer.obtainStream(
  929. this._parseDesktopSharingOptions(options),
  930. desktop => resolve({
  931. audioVideo,
  932. desktop
  933. }),
  934. error => {
  935. if (audioVideo) {
  936. this.stopMediaStream(audioVideo);
  937. }
  938. reject(error);
  939. });
  940. });
  941. });
  942. }
  943. /**
  944. * Private utility for determining if the passed in MediaStream contains
  945. * tracks of the type(s) specified in the requested devices.
  946. *
  947. * @param {string[]} requestedDevices - The track types that are expected to
  948. * be includes in the stream.
  949. * @param {MediaStream} stream - The MediaStream to check if it has the
  950. * expected track types.
  951. * @returns {string[]} An array of string with the missing track types. The
  952. * array will be empty if all requestedDevices are found in the stream.
  953. */
  954. _getMissingTracks(requestedDevices = [], stream) {
  955. const missingDevices = [];
  956. const audioDeviceRequested = requestedDevices.includes('audio');
  957. const audioTracksReceived
  958. = stream && stream.getAudioTracks().length > 0;
  959. if (audioDeviceRequested && !audioTracksReceived) {
  960. missingDevices.push('audio');
  961. }
  962. const videoDeviceRequested = requestedDevices.includes('video');
  963. const videoTracksReceived
  964. = stream && stream.getVideoTracks().length > 0;
  965. if (videoDeviceRequested && !videoTracksReceived) {
  966. missingDevices.push('video');
  967. }
  968. return missingDevices;
  969. }
  970. /**
  971. * Returns an object formatted for specifying desktop sharing parameters.
  972. *
  973. * @param {Object} options - Takes in the same options object as
  974. * {@link obtainAudioAndVideoPermissions}.
  975. * @returns {Object}
  976. */
  977. _parseDesktopSharingOptions(options) {
  978. return {
  979. desktopSharingSources: options.desktopSharingSources,
  980. gumOptions: {
  981. frameRate: options.desktopSharingFrameRate
  982. },
  983. trackOptions: getTrackSSConstraints(options)
  984. };
  985. }
  986. /**
  987. * Gets streams from specified device types. This function intentionally
  988. * ignores errors for upstream to catch and handle instead.
  989. *
  990. * @param {Object} options - A hash describing what devices to get and
  991. * relevant constraints.
  992. * @param {string[]} options.devices - The types of media to capture. Valid
  993. * values are "desktop", "audio", and "video".
  994. * @param {Object} options.desktopSharingFrameRate
  995. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  996. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  997. * @param {String} options.desktopSharingSourceDevice - The device id or
  998. * label for a video input source that should be used for screensharing.
  999. * @returns {Promise} The promise, when successful, will return an array of
  1000. * meta data for the requested device type, which includes the stream and
  1001. * track. If an error occurs, it will be deferred to the caller for
  1002. * handling.
  1003. */
  1004. newObtainAudioAndVideoPermissions(options) {
  1005. logger.info('Using the new gUM flow');
  1006. const {
  1007. timeout,
  1008. ...otherOptions
  1009. } = options;
  1010. const mediaStreamsMetaData = [];
  1011. // Declare private functions to be used in the promise chain below.
  1012. // These functions are declared in the scope of this function because
  1013. // they are not being used anywhere else, so only this function needs to
  1014. // know about them.
  1015. /**
  1016. * Executes a request for desktop media if specified in options.
  1017. *
  1018. * @returns {Promise}
  1019. */
  1020. const maybeRequestDesktopDevice = function() {
  1021. const umDevices = otherOptions.devices || [];
  1022. const isDesktopDeviceRequested
  1023. = umDevices.indexOf('desktop') !== -1;
  1024. if (!isDesktopDeviceRequested) {
  1025. return Promise.resolve();
  1026. }
  1027. const {
  1028. desktopSharingSourceDevice,
  1029. desktopSharingSources,
  1030. desktopSharingFrameRate
  1031. } = otherOptions;
  1032. // Attempt to use a video input device as a screenshare source if
  1033. // the option is defined.
  1034. if (desktopSharingSourceDevice) {
  1035. const matchingDevice
  1036. = availableDevices && availableDevices.find(device =>
  1037. device.kind === 'videoinput'
  1038. && (device.deviceId === desktopSharingSourceDevice
  1039. || device.label === desktopSharingSourceDevice));
  1040. if (!matchingDevice) {
  1041. return Promise.reject(new JitsiTrackError(
  1042. { name: 'ConstraintNotSatisfiedError' },
  1043. {},
  1044. [ desktopSharingSourceDevice ]
  1045. ));
  1046. }
  1047. const requestedDevices = [ 'video' ];
  1048. // Leverage the helper used by {@link _newGetDesktopMedia} to
  1049. // get constraints for the desktop stream.
  1050. const { gumOptions, trackOptions }
  1051. = this._parseDesktopSharingOptions(otherOptions);
  1052. const constraints = {
  1053. video: {
  1054. ...gumOptions,
  1055. deviceId: matchingDevice.deviceId
  1056. }
  1057. };
  1058. return this._getUserMedia(requestedDevices, constraints, timeout)
  1059. .then(stream => {
  1060. const track = stream && stream.getTracks()[0];
  1061. const applyConstrainsPromise
  1062. = track && track.applyConstraints
  1063. ? track.applyConstraints(trackOptions)
  1064. : Promise.resolve();
  1065. return applyConstrainsPromise
  1066. .then(() => {
  1067. return {
  1068. sourceType: 'device',
  1069. stream
  1070. };
  1071. });
  1072. });
  1073. }
  1074. return this._newGetDesktopMedia({
  1075. desktopSharingSources,
  1076. desktopSharingFrameRate
  1077. });
  1078. }.bind(this);
  1079. /**
  1080. * Creates a meta data object about the passed in desktopStream and
  1081. * pushes the meta data to the internal array mediaStreamsMetaData to be
  1082. * returned later.
  1083. *
  1084. * @param {MediaStreamTrack} desktopStream - A track for a desktop
  1085. * capture.
  1086. * @returns {void}
  1087. */
  1088. const maybeCreateAndAddDesktopTrack = function(desktopStream) {
  1089. if (!desktopStream) {
  1090. return;
  1091. }
  1092. const { stream, sourceId, sourceType } = desktopStream;
  1093. const desktopAudioTracks = stream.getAudioTracks();
  1094. if (desktopAudioTracks.length) {
  1095. const desktopAudioStream = new MediaStream(desktopAudioTracks);
  1096. mediaStreamsMetaData.push({
  1097. stream: desktopAudioStream,
  1098. sourceId,
  1099. sourceType,
  1100. track: desktopAudioStream.getAudioTracks()[0]
  1101. });
  1102. }
  1103. const desktopVideoTracks = stream.getVideoTracks();
  1104. if (desktopVideoTracks.length) {
  1105. const desktopVideoStream = new MediaStream(desktopVideoTracks);
  1106. mediaStreamsMetaData.push({
  1107. stream: desktopVideoStream,
  1108. sourceId,
  1109. sourceType,
  1110. track: desktopVideoStream.getVideoTracks()[0],
  1111. videoType: VideoType.DESKTOP
  1112. });
  1113. }
  1114. };
  1115. /**
  1116. * Executes a request for audio and/or video, as specified in options.
  1117. * By default both audio and video will be captured if options.devices
  1118. * is not defined.
  1119. *
  1120. * @returns {Promise}
  1121. */
  1122. const maybeRequestCaptureDevices = function() {
  1123. const umDevices = otherOptions.devices || [ 'audio', 'video' ];
  1124. const requestedCaptureDevices = umDevices.filter(device => device === 'audio' || device === 'video');
  1125. if (!requestedCaptureDevices.length) {
  1126. return Promise.resolve();
  1127. }
  1128. const constraints = newGetConstraints(
  1129. requestedCaptureDevices, otherOptions);
  1130. logger.info('Got media constraints: ', JSON.stringify(constraints));
  1131. return this._getUserMedia(requestedCaptureDevices, constraints, timeout);
  1132. }.bind(this);
  1133. /**
  1134. * Splits the passed in media stream into separate audio and video
  1135. * streams and creates meta data objects for each and pushes them to the
  1136. * internal array mediaStreamsMetaData to be returned later.
  1137. *
  1138. * @param {MediaStreamTrack} avStream - A track for with audio and/or
  1139. * video track.
  1140. * @returns {void}
  1141. */
  1142. const maybeCreateAndAddAVTracks = function(avStream) {
  1143. if (!avStream) {
  1144. return;
  1145. }
  1146. const audioTracks = avStream.getAudioTracks();
  1147. if (audioTracks.length) {
  1148. const audioStream = new MediaStream(audioTracks);
  1149. mediaStreamsMetaData.push({
  1150. stream: audioStream,
  1151. track: audioStream.getAudioTracks()[0],
  1152. effects: otherOptions.effects
  1153. });
  1154. }
  1155. const videoTracks = avStream.getVideoTracks();
  1156. if (videoTracks.length) {
  1157. const videoStream = new MediaStream(videoTracks);
  1158. mediaStreamsMetaData.push({
  1159. stream: videoStream,
  1160. track: videoStream.getVideoTracks()[0],
  1161. videoType: VideoType.CAMERA,
  1162. effects: otherOptions.effects
  1163. });
  1164. }
  1165. };
  1166. return maybeRequestDesktopDevice()
  1167. .then(maybeCreateAndAddDesktopTrack)
  1168. .then(maybeRequestCaptureDevices)
  1169. .then(maybeCreateAndAddAVTracks)
  1170. .then(() => mediaStreamsMetaData)
  1171. .catch(error => {
  1172. mediaStreamsMetaData.forEach(({ stream }) => {
  1173. this.stopMediaStream(stream);
  1174. });
  1175. return Promise.reject(error);
  1176. });
  1177. }
  1178. /**
  1179. * Checks whether it is possible to enumerate available cameras/microphones.
  1180. *
  1181. * @returns {boolean} {@code true} if the device listing is available;
  1182. * {@code false}, otherwise.
  1183. */
  1184. isDeviceListAvailable() {
  1185. return Boolean(
  1186. navigator.mediaDevices
  1187. && navigator.mediaDevices.enumerateDevices);
  1188. }
  1189. /**
  1190. * Returns true if changing the input (camera / microphone) or output
  1191. * (audio) device is supported and false if not.
  1192. * @params {string} [deviceType] - type of device to change. Default is
  1193. * undefined or 'input', 'output' - for audio output device change.
  1194. * @returns {boolean} true if available, false otherwise.
  1195. */
  1196. isDeviceChangeAvailable(deviceType) {
  1197. return deviceType === 'output' || deviceType === 'audiooutput'
  1198. ? isAudioOutputDeviceChangeAvailable
  1199. : true;
  1200. }
  1201. /**
  1202. * A method to handle stopping of the stream.
  1203. * One point to handle the differences in various implementations.
  1204. * @param mediaStream MediaStream object to stop.
  1205. */
  1206. stopMediaStream(mediaStream) {
  1207. if (!mediaStream) {
  1208. return;
  1209. }
  1210. mediaStream.getTracks().forEach(track => {
  1211. if (track.stop) {
  1212. track.stop();
  1213. }
  1214. });
  1215. // leave stop for implementation still using it
  1216. if (mediaStream.stop) {
  1217. mediaStream.stop();
  1218. }
  1219. // The MediaStream implementation of the react-native-webrtc project has
  1220. // an explicit release method that is to be invoked in order to release
  1221. // used resources such as memory.
  1222. if (mediaStream.release) {
  1223. mediaStream.release();
  1224. }
  1225. }
  1226. /**
  1227. * Returns whether the desktop sharing is enabled or not.
  1228. * @returns {boolean}
  1229. */
  1230. isDesktopSharingEnabled() {
  1231. return screenObtainer.isSupported();
  1232. }
  1233. /**
  1234. * Sets current audio output device.
  1235. * @param {string} deviceId - id of 'audiooutput' device from
  1236. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  1237. * device
  1238. * @returns {Promise} - resolves when audio output is changed, is rejected
  1239. * otherwise
  1240. */
  1241. setAudioOutputDevice(deviceId) {
  1242. if (!this.isDeviceChangeAvailable('output')) {
  1243. return Promise.reject(
  1244. new Error('Audio output device change is not supported'));
  1245. }
  1246. return featureDetectionAudioEl.setSinkId(deviceId)
  1247. .then(() => {
  1248. audioOutputDeviceId = deviceId;
  1249. audioOutputChanged = true;
  1250. logger.log(`Audio output device set to ${deviceId}`);
  1251. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1252. deviceId);
  1253. });
  1254. }
  1255. /**
  1256. * Returns currently used audio output device id, '' stands for default
  1257. * device
  1258. * @returns {string}
  1259. */
  1260. getAudioOutputDevice() {
  1261. return audioOutputDeviceId;
  1262. }
  1263. /**
  1264. * Returns list of available media devices if its obtained, otherwise an
  1265. * empty array is returned/
  1266. * @returns {Array} list of available media devices.
  1267. */
  1268. getCurrentlyAvailableMediaDevices() {
  1269. return availableDevices;
  1270. }
  1271. /**
  1272. * Returns whether available devices have permissions granted
  1273. * @returns {Boolean}
  1274. */
  1275. arePermissionsGrantedForAvailableDevices() {
  1276. return availableDevices.some(device => Boolean(device.label));
  1277. }
  1278. /**
  1279. * Returns event data for device to be reported to stats.
  1280. * @returns {MediaDeviceInfo} device.
  1281. */
  1282. getEventDataForActiveDevice(device) {
  1283. const deviceList = [];
  1284. const deviceData = {
  1285. 'deviceId': device.deviceId,
  1286. 'kind': device.kind,
  1287. 'label': device.label,
  1288. 'groupId': device.groupId
  1289. };
  1290. deviceList.push(deviceData);
  1291. return { deviceList };
  1292. }
  1293. /**
  1294. * Configures the given PeerConnection constraints to either enable or
  1295. * disable (according to the value of the 'enable' parameter) the
  1296. * 'googSuspendBelowMinBitrate' option.
  1297. * @param constraints the constraints on which to operate.
  1298. * @param enable {boolean} whether to enable or disable the suspend video
  1299. * option.
  1300. */
  1301. setSuspendVideo(constraints, enable) {
  1302. if (!constraints.optional) {
  1303. constraints.optional = [];
  1304. }
  1305. // Get rid of all "googSuspendBelowMinBitrate" constraints (we assume
  1306. // that the elements of constraints.optional contain a single property).
  1307. constraints.optional
  1308. = constraints.optional.filter(
  1309. c => !c.hasOwnProperty('googSuspendBelowMinBitrate'));
  1310. if (enable) {
  1311. constraints.optional.push({ googSuspendBelowMinBitrate: 'true' });
  1312. }
  1313. }
  1314. }
  1315. const rtcUtils = new RTCUtils();
  1316. /**
  1317. * Wraps original attachMediaStream function to set current audio output device
  1318. * if this is supported.
  1319. * @param {Function} origAttachMediaStream
  1320. * @returns {Function}
  1321. */
  1322. function wrapAttachMediaStream(origAttachMediaStream) {
  1323. return function(element, stream) {
  1324. // eslint-disable-next-line prefer-rest-params
  1325. const res = origAttachMediaStream.apply(rtcUtils, arguments);
  1326. if (stream
  1327. && rtcUtils.isDeviceChangeAvailable('output')
  1328. && stream.getAudioTracks
  1329. && stream.getAudioTracks().length
  1330. // we skip setting audio output if there was no explicit change
  1331. && audioOutputChanged) {
  1332. element.setSinkId(rtcUtils.getAudioOutputDevice())
  1333. .catch(function(ex) {
  1334. const err
  1335. = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  1336. GlobalOnErrorHandler.callUnhandledRejectionHandler({
  1337. promise: this, // eslint-disable-line no-invalid-this
  1338. reason: err
  1339. });
  1340. logger.warn(
  1341. 'Failed to set audio output device for the element.'
  1342. + ' Default audio output device will be used'
  1343. + ' instead',
  1344. element,
  1345. err);
  1346. });
  1347. }
  1348. return res;
  1349. };
  1350. }
  1351. export default rtcUtils;