Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

RTCUtils.js 56KB

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