Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

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