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 57KB

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