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

RTCUtils.js 55KB

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