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

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