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

RTCUtils.js 56KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620
  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 ortcRTCPeerConnection from './ortc/RTCPeerConnection';
  20. import screenObtainer from './ScreenObtainer';
  21. import SDPUtil from '../xmpp/SDPUtil';
  22. import Statistics from '../statistics/statistics';
  23. import VideoType from '../../service/RTC/VideoType';
  24. const logger = getLogger(__filename);
  25. // Require adapter only for certain browsers. This is being done for
  26. // react-native, which has its own shims, and while browsers are being migrated
  27. // over to use adapter's shims.
  28. if (browser.usesAdapter()) {
  29. require('webrtc-adapter');
  30. }
  31. const eventEmitter = new EventEmitter();
  32. const AVAILABLE_DEVICES_POLL_INTERVAL_TIME = 3000; // ms
  33. /**
  34. * Default resolution to obtain for video tracks if no resolution is specified.
  35. * This default is used for old gum flow only, as new gum flow uses
  36. * {@link DEFAULT_CONSTRAINTS}.
  37. */
  38. const OLD_GUM_DEFAULT_RESOLUTION = 720;
  39. /**
  40. * Default devices to obtain when no specific devices are specified. This
  41. * default is used for old gum flow only.
  42. */
  43. const OLD_GUM_DEFAULT_DEVICES = [ 'audio', 'video' ];
  44. /**
  45. * Default MediaStreamConstraints to use for calls to getUserMedia.
  46. *
  47. * @private
  48. */
  49. const DEFAULT_CONSTRAINTS = {
  50. video: {
  51. aspectRatio: 16 / 9,
  52. height: {
  53. ideal: 720,
  54. max: 720,
  55. min: 240
  56. }
  57. }
  58. };
  59. /**
  60. * The default frame rate for Screen Sharing.
  61. */
  62. const SS_DEFAULT_FRAME_RATE = 5;
  63. // Currently audio output device change is supported only in Chrome and
  64. // default output always has 'default' device ID
  65. let audioOutputDeviceId = 'default'; // default device
  66. // whether user has explicitly set a device to use
  67. let audioOutputChanged = false;
  68. // Disables all audio processing
  69. let disableAP = false;
  70. // Disables Acoustic Echo Cancellation
  71. let disableAEC = false;
  72. // Disables Noise Suppression
  73. let disableNS = false;
  74. // Disables Automatic Gain Control
  75. let disableAGC = false;
  76. // Disables Highpass Filter
  77. let disableHPF = false;
  78. const featureDetectionAudioEl = document.createElement('audio');
  79. const isAudioOutputDeviceChangeAvailable
  80. = typeof featureDetectionAudioEl.setSinkId !== 'undefined';
  81. let availableDevices;
  82. let availableDevicesPollTimer;
  83. /**
  84. * Initialize wrapper function for enumerating devices.
  85. * TODO: remove this, it should no longer be needed.
  86. *
  87. * @returns {?Function}
  88. */
  89. function initEnumerateDevicesWithCallback() {
  90. if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
  91. return callback => {
  92. navigator.mediaDevices.enumerateDevices()
  93. .then(callback, () => callback([]));
  94. };
  95. }
  96. }
  97. /**
  98. *
  99. * @param constraints
  100. * @param isNewStyleConstraintsSupported
  101. * @param resolution
  102. */
  103. function setResolutionConstraints(
  104. constraints,
  105. isNewStyleConstraintsSupported,
  106. resolution) {
  107. if (Resolutions[resolution]) {
  108. if (isNewStyleConstraintsSupported) {
  109. constraints.video.width = {
  110. ideal: Resolutions[resolution].width
  111. };
  112. constraints.video.height = {
  113. ideal: Resolutions[resolution].height
  114. };
  115. }
  116. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  117. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  118. }
  119. if (constraints.video.mandatory.minWidth) {
  120. constraints.video.mandatory.maxWidth
  121. = constraints.video.mandatory.minWidth;
  122. }
  123. if (constraints.video.mandatory.minHeight) {
  124. constraints.video.mandatory.maxHeight
  125. = constraints.video.mandatory.minHeight;
  126. }
  127. }
  128. /**
  129. * @param {string[]} um required user media types
  130. *
  131. * @param {Object} [options={}] optional parameters
  132. * @param {string} options.resolution
  133. * @param {number} options.bandwidth
  134. * @param {number} options.fps
  135. * @param {string} options.desktopStream
  136. * @param {string} options.cameraDeviceId
  137. * @param {string} options.micDeviceId
  138. * @param {CameraFacingMode} options.facingMode
  139. * @param {bool} firefox_fake_device
  140. * @param {Object} options.frameRate - used only for dekstop sharing.
  141. * @param {Object} options.frameRate.min - Minimum fps
  142. * @param {Object} options.frameRate.max - Maximum fps
  143. */
  144. function getConstraints(um, options = {}) {
  145. const constraints = {
  146. audio: false,
  147. video: false
  148. };
  149. // Don't mix new and old style settings for Chromium as this leads
  150. // to TypeError in new Chromium versions. @see
  151. // https://bugs.chromium.org/p/chromium/issues/detail?id=614716
  152. // This is a temporary solution, in future we will fully split old and
  153. // new style constraints when new versions of Chromium and Firefox will
  154. // have stable support of new constraints format. For more information
  155. // @see https://github.com/jitsi/lib-jitsi-meet/pull/136
  156. const isNewStyleConstraintsSupported
  157. = browser.isFirefox()
  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 = stream && stream.getAudioTracks().length > 0;
  440. const videoTracksReceived = stream && stream.getVideoTracks().length > 0;
  441. const grantedPermissions = {};
  442. if (um.indexOf('video') !== -1) {
  443. grantedPermissions.video = videoTracksReceived;
  444. }
  445. if (um.indexOf('audio') !== -1) {
  446. grantedPermissions.audio = audioTracksReceived;
  447. }
  448. eventEmitter.emit(RTCEvents.GRANTED_PERMISSIONS, grantedPermissions);
  449. }
  450. /**
  451. * Checks if new list of available media devices differs from previous one.
  452. * @param {MediaDeviceInfo[]} newDevices - list of new devices.
  453. * @returns {boolean} - true if list is different, false otherwise.
  454. */
  455. function compareAvailableMediaDevices(newDevices) {
  456. if (newDevices.length !== availableDevices.length) {
  457. return true;
  458. }
  459. /* eslint-disable newline-per-chained-call */
  460. return (
  461. newDevices.map(mediaDeviceInfoToJSON).sort().join('')
  462. !== availableDevices
  463. .map(mediaDeviceInfoToJSON).sort().join(''));
  464. /* eslint-enable newline-per-chained-call */
  465. /**
  466. *
  467. * @param info
  468. */
  469. function mediaDeviceInfoToJSON(info) {
  470. return JSON.stringify({
  471. kind: info.kind,
  472. deviceId: info.deviceId,
  473. groupId: info.groupId,
  474. label: info.label,
  475. facing: info.facing
  476. });
  477. }
  478. }
  479. /**
  480. * Sends analytics event with the passed device list.
  481. *
  482. * @param {Array<MediaDeviceInfo>} deviceList - List with info about the
  483. * available devices.
  484. * @returns {void}
  485. */
  486. function sendDeviceListToAnalytics(deviceList) {
  487. const audioInputDeviceCount
  488. = deviceList.filter(d => d.kind === 'audioinput').length;
  489. const audioOutputDeviceCount
  490. = deviceList.filter(d => d.kind === 'audiooutput').length;
  491. const videoInputDeviceCount
  492. = deviceList.filter(d => d.kind === 'videoinput').length;
  493. const videoOutputDeviceCount
  494. = deviceList.filter(d => d.kind === 'videooutput').length;
  495. deviceList.forEach(device => {
  496. const attributes = {
  497. 'audio_input_device_count': audioInputDeviceCount,
  498. 'audio_output_device_count': audioOutputDeviceCount,
  499. 'video_input_device_count': videoInputDeviceCount,
  500. 'video_output_device_count': videoOutputDeviceCount,
  501. 'device_id': device.deviceId,
  502. 'device_group_id': device.groupId,
  503. 'device_kind': device.kind,
  504. 'device_label': device.label
  505. };
  506. Statistics.sendAnalytics(AVAILABLE_DEVICE, attributes);
  507. });
  508. }
  509. /**
  510. * Event handler for the 'devicechange' event.
  511. *
  512. * @param {MediaDeviceInfo[]} devices - list of media devices.
  513. * @emits RTCEvents.DEVICE_LIST_CHANGED
  514. */
  515. function onMediaDevicesListChanged(devicesReceived) {
  516. availableDevices = devicesReceived.slice(0);
  517. logger.info(
  518. 'list of media devices has changed:',
  519. availableDevices);
  520. sendDeviceListToAnalytics(availableDevices);
  521. eventEmitter.emit(RTCEvents.DEVICE_LIST_CHANGED, devicesReceived);
  522. }
  523. /**
  524. * Handles the newly created Media Streams.
  525. * @param streams the new Media Streams
  526. * @param resolution the resolution of the video streams
  527. * @returns {*[]} object that describes the new streams
  528. */
  529. function handleLocalStream(streams, resolution) {
  530. let audioStream, desktopStream, videoStream;
  531. const res = [];
  532. // XXX The function obtainAudioAndVideoPermissions has examined the type of
  533. // the browser, its capabilities, etc. and has taken the decision whether to
  534. // invoke getUserMedia per device (e.g. Firefox) or once for both audio and
  535. // video (e.g. Chrome). In order to not duplicate the logic here, examine
  536. // the specified streams and figure out what we've received based on
  537. // obtainAudioAndVideoPermissions' decision.
  538. if (streams) {
  539. // As mentioned above, certian types of browser (e.g. Chrome) support
  540. // (with a result which meets our requirements expressed bellow) calling
  541. // getUserMedia once for both audio and video.
  542. const audioVideo = streams.audioVideo;
  543. if (audioVideo) {
  544. const audioTracks = audioVideo.getAudioTracks();
  545. if (audioTracks.length) {
  546. audioStream = new MediaStream();
  547. for (let i = 0; i < audioTracks.length; i++) {
  548. audioStream.addTrack(audioTracks[i]);
  549. }
  550. }
  551. const videoTracks = audioVideo.getVideoTracks();
  552. if (videoTracks.length) {
  553. videoStream = new MediaStream();
  554. for (let j = 0; j < videoTracks.length; j++) {
  555. videoStream.addTrack(videoTracks[j]);
  556. }
  557. }
  558. } else {
  559. // On other types of browser (e.g. Firefox) we choose (namely,
  560. // obtainAudioAndVideoPermissions) to call getUserMedia per device
  561. // (type).
  562. audioStream = streams.audio;
  563. videoStream = streams.video;
  564. }
  565. desktopStream = streams.desktop;
  566. }
  567. if (desktopStream) {
  568. const { stream, sourceId, sourceType } = desktopStream;
  569. res.push({
  570. stream,
  571. sourceId,
  572. sourceType,
  573. track: stream.getVideoTracks()[0],
  574. mediaType: MediaType.VIDEO,
  575. videoType: VideoType.DESKTOP
  576. });
  577. }
  578. if (audioStream) {
  579. res.push({
  580. stream: audioStream,
  581. track: audioStream.getAudioTracks()[0],
  582. mediaType: MediaType.AUDIO,
  583. videoType: null
  584. });
  585. }
  586. if (videoStream) {
  587. res.push({
  588. stream: videoStream,
  589. track: videoStream.getVideoTracks()[0],
  590. mediaType: MediaType.VIDEO,
  591. videoType: VideoType.CAMERA,
  592. resolution
  593. });
  594. }
  595. return res;
  596. }
  597. /**
  598. * Represents a default implementation of setting a <tt>MediaStream</tt> as the
  599. * source of a video element that tries to be browser-agnostic through feature
  600. * checking. Note though that it was not completely clear from the predating
  601. * browser-specific implementations what &quot;videoSrc&quot; was because one
  602. * implementation of {@link RTCUtils#getVideoSrc} would return
  603. * <tt>MediaStream</tt> (e.g. Firefox), another a <tt>string</tt> representation
  604. * of the <tt>URL</tt> of the <tt>MediaStream</tt> (e.g. Chrome) and the return
  605. * value was only used by {@link RTCUIHelper#getVideoId} which itself did not
  606. * appear to be used anywhere. Generally, the implementation will try to follow
  607. * the related standards i.e. work with the <tt>srcObject</tt> and <tt>src</tt>
  608. * properties of the specified <tt>element</tt> taking into account vender
  609. * prefixes.
  610. *
  611. * @param element the element whose video source/src is to be set to the
  612. * specified <tt>stream</tt>
  613. * @param {MediaStream} stream the <tt>MediaStream</tt> to set as the video
  614. * source/src of <tt>element</tt>
  615. */
  616. function defaultSetVideoSrc(element, stream) {
  617. // srcObject
  618. let srcObjectPropertyName = 'srcObject';
  619. if (!(srcObjectPropertyName in element)) {
  620. srcObjectPropertyName = 'mozSrcObject';
  621. if (!(srcObjectPropertyName in element)) {
  622. srcObjectPropertyName = null;
  623. }
  624. }
  625. if (srcObjectPropertyName) {
  626. element[srcObjectPropertyName] = stream;
  627. return;
  628. }
  629. // src
  630. let src;
  631. if (stream) {
  632. src = stream.jitsiObjectURL;
  633. // Save the created URL for stream so we can reuse it and not keep
  634. // creating URLs.
  635. if (!src) {
  636. stream.jitsiObjectURL = src = URL.createObjectURL(stream);
  637. }
  638. }
  639. element.src = src || '';
  640. }
  641. /**
  642. *
  643. */
  644. class RTCUtils extends Listenable {
  645. /**
  646. *
  647. */
  648. constructor() {
  649. super(eventEmitter);
  650. }
  651. /**
  652. * Depending on the browser, sets difference instance methods for
  653. * interacting with user media and adds methods to native WebRTC-related
  654. * objects. Also creates an instance variable for peer connection
  655. * constraints.
  656. *
  657. * @param {Object} options
  658. * @returns {void}
  659. */
  660. init(options = {}) {
  661. if (typeof options.disableAEC === 'boolean') {
  662. disableAEC = options.disableAEC;
  663. logger.info(`Disable AEC: ${disableAEC}`);
  664. }
  665. if (typeof options.disableNS === 'boolean') {
  666. disableNS = options.disableNS;
  667. logger.info(`Disable NS: ${disableNS}`);
  668. }
  669. if (typeof options.disableAP === 'boolean') {
  670. disableAP = options.disableAP;
  671. logger.info(`Disable AP: ${disableAP}`);
  672. }
  673. if (typeof options.disableAGC === 'boolean') {
  674. disableAGC = options.disableAGC;
  675. logger.info(`Disable AGC: ${disableAGC}`);
  676. }
  677. if (typeof options.disableHPF === 'boolean') {
  678. disableHPF = options.disableHPF;
  679. logger.info(`Disable HPF: ${disableHPF}`);
  680. }
  681. availableDevices = undefined;
  682. window.clearInterval(availableDevicesPollTimer);
  683. availableDevicesPollTimer = undefined;
  684. this.enumerateDevices = initEnumerateDevicesWithCallback();
  685. if (browser.usesNewGumFlow()) {
  686. this.RTCPeerConnectionType = RTCPeerConnection;
  687. this.attachMediaStream
  688. = wrapAttachMediaStream((element, stream) => {
  689. if (element) {
  690. element.srcObject = stream;
  691. }
  692. });
  693. this.getStreamID = ({ id }) => id;
  694. this.getTrackID = ({ id }) => id;
  695. } else if (browser.isChromiumBased() // this is chrome < 61
  696. || browser.isReactNative()) {
  697. this.RTCPeerConnectionType = RTCPeerConnection;
  698. this.attachMediaStream
  699. = wrapAttachMediaStream((element, stream) => {
  700. defaultSetVideoSrc(element, stream);
  701. return element;
  702. });
  703. this.getStreamID = function({ id }) {
  704. // A. MediaStreams from FF endpoints have the characters '{' and
  705. // '}' that make jQuery choke.
  706. // B. The react-native-webrtc implementation that we use at the
  707. // time of this writing returns a number for the id of
  708. // MediaStream. Let's just say that a number contains no special
  709. // characters.
  710. return (
  711. typeof id === 'number'
  712. ? id
  713. : SDPUtil.filterSpecialChars(id));
  714. };
  715. this.getTrackID = ({ id }) => id;
  716. if (!MediaStream.prototype.getVideoTracks) {
  717. MediaStream.prototype.getVideoTracks = function() {
  718. return this.videoTracks;
  719. };
  720. }
  721. if (!MediaStream.prototype.getAudioTracks) {
  722. MediaStream.prototype.getAudioTracks = function() {
  723. return this.audioTracks;
  724. };
  725. }
  726. } else if (browser.isEdge()) {
  727. this.RTCPeerConnectionType = ortcRTCPeerConnection;
  728. this.attachMediaStream
  729. = wrapAttachMediaStream((element, stream) => {
  730. defaultSetVideoSrc(element, stream);
  731. });
  732. // ORTC does not generate remote MediaStreams so those are
  733. // manually created by the ORTC shim. This means that their
  734. // id (internally generated) does not match the stream id
  735. // signaled into the remote SDP. Therefore, the shim adds a
  736. // custom jitsiRemoteId property with the original stream id.
  737. this.getStreamID = function(stream) {
  738. const id = stream.jitsiRemoteId || stream.id;
  739. return SDPUtil.filterSpecialChars(id);
  740. };
  741. // Remote MediaStreamTracks generated by ORTC (within a
  742. // RTCRtpReceiver) have an internally/random id which does not match
  743. // the track id signaled in the remote SDP. The shim adds a custom
  744. // jitsi-id property with the original track id.
  745. this.getTrackID = track => track.jitsiRemoteId || track.id;
  746. } else {
  747. const message = 'Endpoint does not appear to be WebRTC-capable';
  748. logger.error(message);
  749. throw new Error(message);
  750. }
  751. this._initPCConstraints(options);
  752. screenObtainer.init(
  753. options,
  754. this.getUserMediaWithConstraints.bind(this));
  755. if (this.isDeviceListAvailable()) {
  756. this.enumerateDevices(ds => {
  757. availableDevices = ds.splice(0);
  758. logger.debug('Available devices: ', availableDevices);
  759. sendDeviceListToAnalytics(availableDevices);
  760. eventEmitter.emit(
  761. RTCEvents.DEVICE_LIST_AVAILABLE,
  762. availableDevices);
  763. // Use a shared callback to handle both the devicechange event
  764. // and the polling implementations. This prevents duplication
  765. // and works around a chrome bug (verified to occur on 68) where
  766. // devicechange fires twice in a row, which can cause async post
  767. // devicechange processing to collide.
  768. const updateKnownDevices = () => this.enumerateDevices(pds => {
  769. if (compareAvailableMediaDevices(pds)) {
  770. onMediaDevicesListChanged(pds);
  771. }
  772. });
  773. if (browser.supportsDeviceChangeEvent()) {
  774. navigator.mediaDevices.addEventListener(
  775. 'devicechange',
  776. updateKnownDevices);
  777. } else {
  778. // Periodically poll enumerateDevices() method to check if
  779. // list of media devices has changed.
  780. availableDevicesPollTimer = window.setInterval(
  781. updateKnownDevices,
  782. AVAILABLE_DEVICES_POLL_INTERVAL_TIME);
  783. }
  784. });
  785. }
  786. }
  787. /**
  788. * Creates instance objects for peer connection constraints both for p2p
  789. * and outside of p2p.
  790. *
  791. * @params {Object} options - Configuration for setting RTCUtil's instance
  792. * objects for peer connection constraints.
  793. * @params {boolean} options.useIPv6 - Set to true if IPv6 should be used.
  794. * @params {boolean} options.disableSuspendVideo - Whether or not video
  795. * should become suspended if bandwidth estimation becomes low.
  796. * @params {Object} options.testing - Additional configuration for work in
  797. * development.
  798. * @params {Object} options.testing.forceP2PSuspendVideoRatio - True if
  799. * video should become suspended if bandwidth estimation becomes low while
  800. * in peer to peer connection mode.
  801. */
  802. _initPCConstraints(options) {
  803. if (browser.isFirefox()) {
  804. this.pcConstraints = {};
  805. } else if (browser.isChromiumBased() || browser.isReactNative()) {
  806. this.pcConstraints = { optional: [
  807. { googHighStartBitrate: 0 },
  808. { googPayloadPadding: true },
  809. { googScreencastMinBitrate: 400 },
  810. { googCpuOveruseDetection: true },
  811. { googCpuOveruseEncodeUsage: true },
  812. { googCpuUnderuseThreshold: 55 },
  813. { googCpuOveruseThreshold: 85 }
  814. ] };
  815. if (options.useIPv6) {
  816. // https://code.google.com/p/webrtc/issues/detail?id=2828
  817. this.pcConstraints.optional.push({ googIPv6: true });
  818. }
  819. this.p2pPcConstraints
  820. = JSON.parse(JSON.stringify(this.pcConstraints));
  821. // Allows sending of video to be suspended if the bandwidth
  822. // estimation is too low.
  823. if (!options.disableSuspendVideo) {
  824. this.pcConstraints.optional.push(
  825. { googSuspendBelowMinBitrate: true });
  826. }
  827. // There's no reason not to use this for p2p
  828. this.p2pPcConstraints.optional.push({
  829. googSuspendBelowMinBitrate: true
  830. });
  831. }
  832. this.p2pPcConstraints = this.p2pPcConstraints || this.pcConstraints;
  833. }
  834. /* eslint-disable max-params */
  835. /**
  836. * @param {string[]} um required user media types
  837. * @param {Object} [options] optional parameters
  838. * @param {string} options.resolution
  839. * @param {number} options.bandwidth
  840. * @param {number} options.fps
  841. * @param {string} options.desktopStream
  842. * @param {string} options.cameraDeviceId
  843. * @param {string} options.micDeviceId
  844. * @param {Object} options.frameRate - used only for dekstop sharing.
  845. * @param {Object} options.frameRate.min - Minimum fps
  846. * @param {Object} options.frameRate.max - Maximum fps
  847. * @returns {Promise} Returns a media stream on success or a JitsiTrackError
  848. * on failure.
  849. **/
  850. getUserMediaWithConstraints(um, options = {}) {
  851. const constraints = getConstraints(um, options);
  852. logger.info('Get media constraints', constraints);
  853. return new Promise((resolve, reject) => {
  854. navigator.mediaDevices.getUserMedia(constraints)
  855. .then(stream => {
  856. logger.log('onUserMediaSuccess');
  857. updateGrantedPermissions(um, stream);
  858. resolve(stream);
  859. })
  860. .catch(error => {
  861. logger.warn('Failed to get access to local media. '
  862. + ` ${error} ${constraints} `);
  863. updateGrantedPermissions(um, undefined);
  864. reject(new JitsiTrackError(error, constraints, um));
  865. });
  866. });
  867. }
  868. /**
  869. * Acquires a media stream via getUserMedia that
  870. * matches the given constraints
  871. *
  872. * @param {array} umDevices which devices to acquire (e.g. audio, video)
  873. * @param {Object} constraints - Stream specifications to use.
  874. * @returns {Promise}
  875. */
  876. _newGetUserMediaWithConstraints(umDevices, constraints = {}) {
  877. return new Promise((resolve, reject) => {
  878. navigator.mediaDevices.getUserMedia(constraints)
  879. .then(stream => {
  880. logger.log('onUserMediaSuccess');
  881. updateGrantedPermissions(umDevices, stream);
  882. resolve(stream);
  883. })
  884. .catch(error => {
  885. logger.warn('Failed to get access to local media. '
  886. + ` ${error} ${constraints} `);
  887. updateGrantedPermissions(umDevices, undefined);
  888. reject(new JitsiTrackError(error, constraints, umDevices));
  889. });
  890. });
  891. }
  892. /**
  893. * Acquire a display stream via the screenObtainer. This requires extra
  894. * logic compared to use screenObtainer versus normal device capture logic
  895. * in RTCUtils#_newGetUserMediaWithConstraints.
  896. *
  897. * @param {Object} options
  898. * @param {Object} options.desktopSharingExtensionExternalInstallation
  899. * @param {string[]} options.desktopSharingSources
  900. * @param {Object} options.gumOptions.frameRate
  901. * @param {Object} options.gumOptions.frameRate.min - Minimum fps
  902. * @param {Object} options.gumOptions.frameRate.max - Maximum fps
  903. * @returns {Promise} A promise which will be resolved with an object whic
  904. * contains the acquired display stream. If desktop sharing is not supported
  905. * then a rejected promise will be returned.
  906. */
  907. _newGetDesktopMedia(options) {
  908. if (!screenObtainer.isSupported() || !browser.supportsVideo()) {
  909. return Promise.reject(
  910. new Error('Desktop sharing is not supported!'));
  911. }
  912. const {
  913. desktopSharingExtensionExternalInstallation,
  914. desktopSharingSources,
  915. gumOptions
  916. } = options;
  917. return new Promise((resolve, reject) => {
  918. screenObtainer.obtainStream(
  919. {
  920. ...desktopSharingExtensionExternalInstallation,
  921. desktopSharingSources,
  922. gumOptions,
  923. trackOptions: getTrackSSConstraints(options)
  924. },
  925. stream => {
  926. resolve(stream);
  927. },
  928. error => {
  929. reject(error);
  930. });
  931. });
  932. }
  933. /* eslint-enable max-params */
  934. /**
  935. * Creates the local MediaStreams.
  936. * @param {Object} [options] optional parameters
  937. * @param {Array} options.devices the devices that will be requested
  938. * @param {string} options.resolution resolution constraints
  939. * @param {string} options.cameraDeviceId
  940. * @param {string} options.micDeviceId
  941. * @param {Object} options.desktopSharingFrameRate
  942. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  943. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  944. * @returns {*} Promise object that will receive the new JitsiTracks
  945. */
  946. obtainAudioAndVideoPermissions(options = {}) {
  947. options.devices = options.devices || [ ...OLD_GUM_DEFAULT_DEVICES ];
  948. options.resolution = options.resolution || OLD_GUM_DEFAULT_RESOLUTION;
  949. const requestingDesktop = options.devices.includes('desktop');
  950. if (requestingDesktop && !screenObtainer.isSupported()) {
  951. return Promise.reject(
  952. new Error('Desktop sharing is not supported!'));
  953. }
  954. let gumPromise;
  955. if (browser.supportsMediaStreamConstructor()) {
  956. gumPromise = this._getAudioAndVideoStreams(options);
  957. } else {
  958. // If the MediaStream constructor is not supported, then get tracks
  959. // in separate GUM calls in order to keep different tracks separate.
  960. gumPromise = this._getAudioAndVideoStreamsSeparately(options);
  961. }
  962. return gumPromise.then(streams =>
  963. handleLocalStream(streams, options.resolution));
  964. }
  965. /**
  966. * Performs one call to getUserMedia for audio and/or video and another call
  967. * for desktop.
  968. *
  969. * @param {Object} options - An object describing how the gUM request should
  970. * be executed. See {@link obtainAudioAndVideoPermissions} for full options.
  971. * @returns {*} Promise object that will receive the new JitsiTracks on
  972. * success or a JitsiTrackError on failure.
  973. */
  974. _getAudioAndVideoStreams(options) {
  975. const requestingDesktop = options.devices.includes('desktop');
  976. options.devices = options.devices.filter(device =>
  977. device !== 'desktop');
  978. const gumPromise = options.devices.length
  979. ? this.getUserMediaWithConstraints(options.devices, options)
  980. : Promise.resolve(null);
  981. return gumPromise
  982. .then(avStream => {
  983. // If any requested devices are missing, call gum again in
  984. // an attempt to obtain the actual error. For example, the
  985. // requested video device is missing or permission was
  986. // denied.
  987. const missingTracks
  988. = this._getMissingTracks(options.devices, avStream);
  989. if (missingTracks.length) {
  990. this.stopMediaStream(avStream);
  991. return this.getUserMediaWithConstraints(
  992. missingTracks, options)
  993. // GUM has already failed earlier and this success
  994. // handling should not be reached.
  995. .then(() => Promise.reject(new JitsiTrackError(
  996. { name: 'UnknownError' },
  997. getConstraints(options.devices, options),
  998. missingTracks)));
  999. }
  1000. return avStream;
  1001. })
  1002. .then(audioVideo => {
  1003. if (!requestingDesktop) {
  1004. return { audioVideo };
  1005. }
  1006. return new Promise((resolve, reject) => {
  1007. screenObtainer.obtainStream(
  1008. this._parseDesktopSharingOptions(options),
  1009. desktop => resolve({
  1010. audioVideo,
  1011. desktop
  1012. }),
  1013. error => {
  1014. if (audioVideo) {
  1015. this.stopMediaStream(audioVideo);
  1016. }
  1017. reject(error);
  1018. });
  1019. });
  1020. });
  1021. }
  1022. /**
  1023. * Private utility for determining if the passed in MediaStream contains
  1024. * tracks of the type(s) specified in the requested devices.
  1025. *
  1026. * @param {string[]} requestedDevices - The track types that are expected to
  1027. * be includes in the stream.
  1028. * @param {MediaStream} stream - The MediaStream to check if it has the
  1029. * expected track types.
  1030. * @returns {string[]} An array of string with the missing track types. The
  1031. * array will be empty if all requestedDevices are found in the stream.
  1032. */
  1033. _getMissingTracks(requestedDevices = [], stream) {
  1034. const missingDevices = [];
  1035. const audioDeviceRequested = requestedDevices.includes('audio');
  1036. const audioTracksReceived
  1037. = stream && stream.getAudioTracks().length > 0;
  1038. if (audioDeviceRequested && !audioTracksReceived) {
  1039. missingDevices.push('audio');
  1040. }
  1041. const videoDeviceRequested = requestedDevices.includes('video');
  1042. const videoTracksReceived
  1043. = stream && stream.getVideoTracks().length > 0;
  1044. if (videoDeviceRequested && !videoTracksReceived) {
  1045. missingDevices.push('video');
  1046. }
  1047. return missingDevices;
  1048. }
  1049. /**
  1050. * Performs separate getUserMedia calls for audio and video instead of in
  1051. * one call. Will also request desktop if specified.
  1052. *
  1053. * @param {Object} options - An object describing how the gUM request should
  1054. * be executed. See {@link obtainAudioAndVideoPermissions} for full options.
  1055. * @returns {*} Promise object that will receive the new JitsiTracks on
  1056. * success or a JitsiTrackError on failure.
  1057. */
  1058. _getAudioAndVideoStreamsSeparately(options) {
  1059. return new Promise((resolve, reject) => {
  1060. const deviceGUM = {
  1061. audio: (...args) =>
  1062. this.getUserMediaWithConstraints([ 'audio' ], ...args),
  1063. video: (...args) =>
  1064. this.getUserMediaWithConstraints([ 'video' ], ...args),
  1065. desktop: (...args) =>
  1066. screenObtainer.obtainStream(
  1067. this._parseDesktopSharingOptions(options), ...args)
  1068. };
  1069. obtainDevices({
  1070. options,
  1071. devices: options.devices,
  1072. streams: {},
  1073. successCallback: resolve,
  1074. errorCallback: reject,
  1075. deviceGUM
  1076. });
  1077. });
  1078. }
  1079. /**
  1080. * Returns an object formatted for specifying desktop sharing parameters.
  1081. *
  1082. * @param {Object} options - Takes in the same options object as
  1083. * {@link obtainAudioAndVideoPermissions}.
  1084. * @returns {Object}
  1085. */
  1086. _parseDesktopSharingOptions(options) {
  1087. return {
  1088. ...options.desktopSharingExtensionExternalInstallation,
  1089. desktopSharingSources: options.desktopSharingSources,
  1090. gumOptions: {
  1091. frameRate: options.desktopSharingFrameRate
  1092. },
  1093. trackOptions: getTrackSSConstraints(options)
  1094. };
  1095. }
  1096. /**
  1097. * Gets streams from specified device types. This function intentionally
  1098. * ignores errors for upstream to catch and handle instead.
  1099. *
  1100. * @param {Object} options - A hash describing what devices to get and
  1101. * relevant constraints.
  1102. * @param {string[]} options.devices - The types of media to capture. Valid
  1103. * values are "desktop", "audio", and "video".
  1104. * @param {Object} options.desktopSharingFrameRate
  1105. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  1106. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  1107. * @returns {Promise} The promise, when successful, will return an array of
  1108. * meta data for the requested device type, which includes the stream and
  1109. * track. If an error occurs, it will be deferred to the caller for
  1110. * handling.
  1111. */
  1112. newObtainAudioAndVideoPermissions(options) {
  1113. logger.info('Using the new gUM flow');
  1114. const mediaStreamsMetaData = [];
  1115. // Declare private functions to be used in the promise chain below.
  1116. // These functions are declared in the scope of this function because
  1117. // they are not being used anywhere else, so only this function needs to
  1118. // know about them.
  1119. /**
  1120. * Executes a request for desktop media if specified in options.
  1121. *
  1122. * @returns {Promise}
  1123. */
  1124. const maybeRequestDesktopDevice = function() {
  1125. const umDevices = options.devices || [];
  1126. const isDesktopDeviceRequsted = umDevices.indexOf('desktop') !== -1;
  1127. const {
  1128. desktopSharingExtensionExternalInstallation,
  1129. desktopSharingSources,
  1130. desktopSharingFrameRate
  1131. } = options;
  1132. return isDesktopDeviceRequsted
  1133. ? this._newGetDesktopMedia(
  1134. {
  1135. desktopSharingExtensionExternalInstallation,
  1136. desktopSharingSources,
  1137. gumOptions: {
  1138. frameRate: desktopSharingFrameRate
  1139. }
  1140. })
  1141. : Promise.resolve();
  1142. }.bind(this);
  1143. /**
  1144. * Creates a meta data object about the passed in desktopStream and
  1145. * pushes the meta data to the internal array mediaStreamsMetaData to be
  1146. * returned later.
  1147. *
  1148. * @param {MediaStreamTrack} desktopStream - A track for a desktop
  1149. * capture.
  1150. * @returns {void}
  1151. */
  1152. const maybeCreateAndAddDesktopTrack = function(desktopStream) {
  1153. if (!desktopStream) {
  1154. return;
  1155. }
  1156. const { stream, sourceId, sourceType } = desktopStream;
  1157. mediaStreamsMetaData.push({
  1158. stream,
  1159. sourceId,
  1160. sourceType,
  1161. track: stream.getVideoTracks()[0],
  1162. videoType: VideoType.DESKTOP
  1163. });
  1164. };
  1165. /**
  1166. * Executes a request for audio and/or video, as specified in options.
  1167. * By default both audio and video will be captured if options.devices
  1168. * is not defined.
  1169. *
  1170. * @returns {Promise}
  1171. */
  1172. const maybeRequestCaptureDevices = function() {
  1173. const umDevices = options.devices || [ 'audio', 'video' ];
  1174. const requestedCaptureDevices = umDevices.filter(device =>
  1175. device === 'audio'
  1176. || (device === 'video' && browser.supportsVideo()));
  1177. if (!requestedCaptureDevices.length) {
  1178. return Promise.resolve();
  1179. }
  1180. const constraints = newGetConstraints(
  1181. requestedCaptureDevices, options);
  1182. logger.info('Got media constraints: ', constraints);
  1183. return this._newGetUserMediaWithConstraints(
  1184. requestedCaptureDevices, constraints);
  1185. }.bind(this);
  1186. /**
  1187. * Splits the passed in media stream into separate audio and video
  1188. * streams and creates meta data objects for each and pushes them to the
  1189. * internal array mediaStreamsMetaData to be returned later.
  1190. *
  1191. * @param {MediaStreamTrack} avStream - A track for with audio and/or
  1192. * video track.
  1193. * @returns {void}
  1194. */
  1195. const maybeCreateAndAddAVTracks = function(avStream) {
  1196. if (!avStream) {
  1197. return;
  1198. }
  1199. const audioTracks = avStream.getAudioTracks();
  1200. if (audioTracks.length) {
  1201. const audioStream = new MediaStream(audioTracks);
  1202. mediaStreamsMetaData.push({
  1203. stream: audioStream,
  1204. track: audioStream.getAudioTracks()[0]
  1205. });
  1206. }
  1207. const videoTracks = avStream.getVideoTracks();
  1208. if (videoTracks.length) {
  1209. const videoStream = new MediaStream(videoTracks);
  1210. mediaStreamsMetaData.push({
  1211. stream: videoStream,
  1212. track: videoStream.getVideoTracks()[0],
  1213. videoType: VideoType.CAMERA
  1214. });
  1215. }
  1216. };
  1217. return maybeRequestDesktopDevice()
  1218. .then(maybeCreateAndAddDesktopTrack)
  1219. .then(maybeRequestCaptureDevices)
  1220. .then(maybeCreateAndAddAVTracks)
  1221. .then(() => mediaStreamsMetaData);
  1222. }
  1223. /**
  1224. * Checks whether it is possible to enumerate available cameras/microphones.
  1225. *
  1226. * @returns {boolean} {@code true} if the device listing is available;
  1227. * {@code false}, otherwise.
  1228. */
  1229. isDeviceListAvailable() {
  1230. return Boolean(
  1231. navigator.mediaDevices
  1232. && navigator.mediaDevices.enumerateDevices);
  1233. }
  1234. /**
  1235. * Returns true if changing the input (camera / microphone) or output
  1236. * (audio) device is supported and false if not.
  1237. * @params {string} [deviceType] - type of device to change. Default is
  1238. * undefined or 'input', 'output' - for audio output device change.
  1239. * @returns {boolean} true if available, false otherwise.
  1240. */
  1241. isDeviceChangeAvailable(deviceType) {
  1242. return deviceType === 'output' || deviceType === 'audiooutput'
  1243. ? isAudioOutputDeviceChangeAvailable
  1244. : browser.isChromiumBased()
  1245. || browser.isFirefox() || browser.isEdge();
  1246. }
  1247. /**
  1248. * A method to handle stopping of the stream.
  1249. * One point to handle the differences in various implementations.
  1250. * @param mediaStream MediaStream object to stop.
  1251. */
  1252. stopMediaStream(mediaStream) {
  1253. mediaStream.getTracks().forEach(track => {
  1254. if (track.stop) {
  1255. track.stop();
  1256. }
  1257. });
  1258. // leave stop for implementation still using it
  1259. if (mediaStream.stop) {
  1260. mediaStream.stop();
  1261. }
  1262. // The MediaStream implementation of the react-native-webrtc project has
  1263. // an explicit release method that is to be invoked in order to release
  1264. // used resources such as memory.
  1265. if (mediaStream.release) {
  1266. mediaStream.release();
  1267. }
  1268. // if we have done createObjectURL, lets clean it
  1269. const url = mediaStream.jitsiObjectURL;
  1270. if (url) {
  1271. delete mediaStream.jitsiObjectURL;
  1272. URL.revokeObjectURL(url);
  1273. }
  1274. }
  1275. /**
  1276. * Returns whether the desktop sharing is enabled or not.
  1277. * @returns {boolean}
  1278. */
  1279. isDesktopSharingEnabled() {
  1280. return screenObtainer.isSupported();
  1281. }
  1282. /**
  1283. * Sets current audio output device.
  1284. * @param {string} deviceId - id of 'audiooutput' device from
  1285. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  1286. * device
  1287. * @returns {Promise} - resolves when audio output is changed, is rejected
  1288. * otherwise
  1289. */
  1290. setAudioOutputDevice(deviceId) {
  1291. if (!this.isDeviceChangeAvailable('output')) {
  1292. return Promise.reject(
  1293. new Error('Audio output device change is not supported'));
  1294. }
  1295. return featureDetectionAudioEl.setSinkId(deviceId)
  1296. .then(() => {
  1297. audioOutputDeviceId = deviceId;
  1298. audioOutputChanged = true;
  1299. logger.log(`Audio output device set to ${deviceId}`);
  1300. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1301. deviceId);
  1302. });
  1303. }
  1304. /**
  1305. * Returns currently used audio output device id, '' stands for default
  1306. * device
  1307. * @returns {string}
  1308. */
  1309. getAudioOutputDevice() {
  1310. return audioOutputDeviceId;
  1311. }
  1312. /**
  1313. * Returns list of available media devices if its obtained, otherwise an
  1314. * empty array is returned/
  1315. * @returns {Array} list of available media devices.
  1316. */
  1317. getCurrentlyAvailableMediaDevices() {
  1318. return availableDevices;
  1319. }
  1320. /**
  1321. * Returns event data for device to be reported to stats.
  1322. * @returns {MediaDeviceInfo} device.
  1323. */
  1324. getEventDataForActiveDevice(device) {
  1325. const deviceList = [];
  1326. const deviceData = {
  1327. 'deviceId': device.deviceId,
  1328. 'kind': device.kind,
  1329. 'label': device.label,
  1330. 'groupId': device.groupId
  1331. };
  1332. deviceList.push(deviceData);
  1333. return { deviceList };
  1334. }
  1335. /**
  1336. * Configures the given PeerConnection constraints to either enable or
  1337. * disable (according to the value of the 'enable' parameter) the
  1338. * 'googSuspendBelowMinBitrate' option.
  1339. * @param constraints the constraints on which to operate.
  1340. * @param enable {boolean} whether to enable or disable the suspend video
  1341. * option.
  1342. */
  1343. setSuspendVideo(constraints, enable) {
  1344. if (!constraints.optional) {
  1345. constraints.optional = [];
  1346. }
  1347. // Get rid of all "googSuspendBelowMinBitrate" constraints (we assume
  1348. // that the elements of constraints.optional contain a single property).
  1349. constraints.optional
  1350. = constraints.optional.filter(
  1351. c => !c.hasOwnProperty('googSuspendBelowMinBitrate'));
  1352. if (enable) {
  1353. constraints.optional.push({ googSuspendBelowMinBitrate: 'true' });
  1354. }
  1355. }
  1356. }
  1357. const rtcUtils = new RTCUtils();
  1358. /**
  1359. *
  1360. * @param context Execution context, containing options and callbacks
  1361. */
  1362. function obtainDevices(context) {
  1363. if (!context.devices || context.devices.length === 0) {
  1364. return context.successCallback(context.streams || {});
  1365. }
  1366. const device = context.devices.splice(0, 1);
  1367. context.deviceGUM[device](context.options)
  1368. .then(stream => {
  1369. context.streams = context.streams || {};
  1370. context.streams[device] = stream;
  1371. obtainDevices(context);
  1372. }, error => {
  1373. Object.keys(context.streams).forEach(
  1374. d => rtcUtils.stopMediaStream(context.streams[d]));
  1375. logger.error(
  1376. `failed to obtain ${device} stream - stop`, error);
  1377. context.errorCallback(error);
  1378. });
  1379. }
  1380. /**
  1381. * Wraps original attachMediaStream function to set current audio output device
  1382. * if this is supported.
  1383. * @param {Function} origAttachMediaStream
  1384. * @returns {Function}
  1385. */
  1386. function wrapAttachMediaStream(origAttachMediaStream) {
  1387. return function(element, stream) {
  1388. // eslint-disable-next-line prefer-rest-params
  1389. const res = origAttachMediaStream.apply(rtcUtils, arguments);
  1390. if (stream
  1391. && rtcUtils.isDeviceChangeAvailable('output')
  1392. && stream.getAudioTracks
  1393. && stream.getAudioTracks().length
  1394. // we skip setting audio output if there was no explicit change
  1395. && audioOutputChanged) {
  1396. element.setSinkId(rtcUtils.getAudioOutputDevice())
  1397. .catch(function(ex) {
  1398. const err
  1399. = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  1400. GlobalOnErrorHandler.callUnhandledRejectionHandler({
  1401. promise: this, // eslint-disable-line no-invalid-this
  1402. reason: err
  1403. });
  1404. logger.warn(
  1405. 'Failed to set audio output device for the element.'
  1406. + ' Default audio output device will be used'
  1407. + ' instead',
  1408. element,
  1409. err);
  1410. });
  1411. }
  1412. return res;
  1413. };
  1414. }
  1415. export default rtcUtils;