modified lib-jitsi-meet dev repo
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

RTCUtils.js 55KB

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