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

RTCUtils.js 61KB

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