您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RTCUtils.js 57KB

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