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

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