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

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