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

RTCUtils.js 57KB

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