modified lib-jitsi-meet dev repo
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 52KB

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