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

RTCUtils.js 54KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562
  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, availableDevices);
  591. eventEmitter.emit(RTCEvents.DEVICE_LIST_CHANGED, availableDevices);
  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. *
  670. */
  671. class RTCUtils extends Listenable {
  672. /**
  673. *
  674. */
  675. constructor() {
  676. super(eventEmitter);
  677. }
  678. /**
  679. * Depending on the browser, sets difference instance methods for
  680. * interacting with user media and adds methods to native WebRTC-related
  681. * objects. Also creates an instance variable for peer connection
  682. * constraints.
  683. *
  684. * @param {Object} options
  685. * @returns {void}
  686. */
  687. init(options = {}) {
  688. if (typeof options.disableAEC === 'boolean') {
  689. disableAEC = options.disableAEC;
  690. logger.info(`Disable AEC: ${disableAEC}`);
  691. }
  692. if (typeof options.disableNS === 'boolean') {
  693. disableNS = options.disableNS;
  694. logger.info(`Disable NS: ${disableNS}`);
  695. }
  696. if (typeof options.disableAP === 'boolean') {
  697. disableAP = options.disableAP;
  698. logger.info(`Disable AP: ${disableAP}`);
  699. }
  700. if (typeof options.disableAGC === 'boolean') {
  701. disableAGC = options.disableAGC;
  702. logger.info(`Disable AGC: ${disableAGC}`);
  703. }
  704. if (typeof options.disableHPF === 'boolean') {
  705. disableHPF = options.disableHPF;
  706. logger.info(`Disable HPF: ${disableHPF}`);
  707. }
  708. availableDevices = [];
  709. window.clearInterval(availableDevicesPollTimer);
  710. availableDevicesPollTimer = undefined;
  711. this.enumerateDevices = initEnumerateDevicesWithCallback();
  712. if (browser.usesNewGumFlow()) {
  713. this.RTCPeerConnectionType = RTCPeerConnection;
  714. this.attachMediaStream
  715. = wrapAttachMediaStream((element, stream) => {
  716. if (element) {
  717. element.srcObject = stream;
  718. }
  719. });
  720. this.getStreamID = ({ id }) => id;
  721. this.getTrackID = ({ id }) => id;
  722. } else if (browser.isReactNative()) {
  723. this.RTCPeerConnectionType = RTCPeerConnection;
  724. this.attachMediaStream = undefined; // Unused on React Native.
  725. this.getStreamID = function({ id }) {
  726. // The react-native-webrtc implementation that we use at the
  727. // time of this writing returns a number for the id of
  728. // MediaStream. Let's just say that a number contains no special
  729. // characters.
  730. return (
  731. typeof id === 'number'
  732. ? id
  733. : SDPUtil.filterSpecialChars(id));
  734. };
  735. this.getTrackID = ({ id }) => id;
  736. } else {
  737. const message = 'Endpoint does not appear to be WebRTC-capable';
  738. logger.error(message);
  739. throw new Error(message);
  740. }
  741. this._initPCConstraints();
  742. screenObtainer.init(
  743. options,
  744. this.getUserMediaWithConstraints.bind(this));
  745. if (this.isDeviceListAvailable()) {
  746. this.enumerateDevices(ds => {
  747. availableDevices = ds.slice(0);
  748. logger.debug('Available devices: ', availableDevices);
  749. sendDeviceListToAnalytics(availableDevices);
  750. eventEmitter.emit(
  751. RTCEvents.DEVICE_LIST_AVAILABLE,
  752. availableDevices);
  753. if (browser.supportsDeviceChangeEvent()) {
  754. navigator.mediaDevices.addEventListener(
  755. 'devicechange',
  756. () => this.enumerateDevices(emptyFuncton));
  757. } else {
  758. // Periodically poll enumerateDevices() method to check if
  759. // list of media devices has changed.
  760. availableDevicesPollTimer = window.setInterval(
  761. () => this.enumerateDevices(emptyFuncton),
  762. AVAILABLE_DEVICES_POLL_INTERVAL_TIME);
  763. }
  764. });
  765. }
  766. }
  767. /**
  768. * Creates instance objects for peer connection constraints both for p2p
  769. * and outside of p2p.
  770. */
  771. _initPCConstraints() {
  772. if (browser.isFirefox()) {
  773. this.pcConstraints = {};
  774. } else if (browser.isChromiumBased() || browser.isReactNative()) {
  775. this.pcConstraints = { optional: [
  776. { googHighStartBitrate: 0 },
  777. { googPayloadPadding: true },
  778. { googScreencastMinBitrate: 100 },
  779. { googCpuOveruseDetection: true },
  780. { googCpuOveruseEncodeUsage: true },
  781. { googCpuUnderuseThreshold: 55 },
  782. { googCpuOveruseThreshold: 85 }
  783. ] };
  784. this.p2pPcConstraints
  785. = JSON.parse(JSON.stringify(this.pcConstraints));
  786. }
  787. this.p2pPcConstraints = this.p2pPcConstraints || this.pcConstraints;
  788. }
  789. /* eslint-disable max-params */
  790. /**
  791. * @param {string[]} um required user media types
  792. * @param {Object} [options] optional parameters
  793. * @param {string} options.resolution
  794. * @param {number} options.bandwidth
  795. * @param {number} options.fps
  796. * @param {string} options.desktopStream
  797. * @param {string} options.cameraDeviceId
  798. * @param {string} options.micDeviceId
  799. * @param {Object} options.frameRate - used only for dekstop sharing.
  800. * @param {Object} options.frameRate.min - Minimum fps
  801. * @param {Object} options.frameRate.max - Maximum fps
  802. * @param {bool} options.screenShareAudio - Used by electron clients to
  803. * enable system audio screen sharing.
  804. * @returns {Promise} Returns a media stream on success or a JitsiTrackError
  805. * on failure.
  806. **/
  807. getUserMediaWithConstraints(um, options = {}) {
  808. const constraints = getConstraints(um, options);
  809. logger.info('Get media constraints', JSON.stringify(constraints));
  810. return new Promise((resolve, reject) => {
  811. navigator.mediaDevices.getUserMedia(constraints)
  812. .then(stream => {
  813. logger.log('onUserMediaSuccess');
  814. updateGrantedPermissions(um, stream);
  815. resolve(stream);
  816. })
  817. .catch(error => {
  818. logger.warn(`Failed to get access to local media. ${error} ${JSON.stringify(constraints)}`);
  819. updateGrantedPermissions(um, undefined);
  820. reject(new JitsiTrackError(error, constraints, um));
  821. });
  822. });
  823. }
  824. /**
  825. * Acquires a media stream via getUserMedia that
  826. * matches the given constraints
  827. *
  828. * @param {array} umDevices which devices to acquire (e.g. audio, video)
  829. * @param {Object} constraints - Stream specifications to use.
  830. * @returns {Promise}
  831. */
  832. _newGetUserMediaWithConstraints(umDevices, constraints = {}) {
  833. return new Promise((resolve, reject) => {
  834. navigator.mediaDevices.getUserMedia(constraints)
  835. .then(stream => {
  836. logger.log('onUserMediaSuccess');
  837. updateGrantedPermissions(umDevices, stream);
  838. resolve(stream);
  839. })
  840. .catch(error => {
  841. logger.warn(`Failed to get access to local media. ${error} ${JSON.stringify(constraints)}`);
  842. updateGrantedPermissions(umDevices, undefined);
  843. reject(new JitsiTrackError(error, constraints, umDevices));
  844. });
  845. });
  846. }
  847. /**
  848. * Acquire a display stream via the screenObtainer. This requires extra
  849. * logic compared to use screenObtainer versus normal device capture logic
  850. * in RTCUtils#_newGetUserMediaWithConstraints.
  851. *
  852. * @param {Object} options
  853. * @param {string[]} options.desktopSharingSources
  854. * @param {Object} options.desktopSharingFrameRate
  855. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  856. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  857. * @returns {Promise} A promise which will be resolved with an object which
  858. * contains the acquired display stream. If desktop sharing is not supported
  859. * then a rejected promise will be returned.
  860. */
  861. _newGetDesktopMedia(options) {
  862. if (!screenObtainer.isSupported()) {
  863. return Promise.reject(new Error('Desktop sharing is not supported!'));
  864. }
  865. return new Promise((resolve, reject) => {
  866. screenObtainer.obtainStream(
  867. this._parseDesktopSharingOptions(options),
  868. stream => {
  869. resolve(stream);
  870. },
  871. error => {
  872. reject(error);
  873. });
  874. });
  875. }
  876. /* eslint-enable max-params */
  877. /**
  878. * Creates the local MediaStreams.
  879. * @param {Object} [options] optional parameters
  880. * @param {Array} options.devices the devices that will be requested
  881. * @param {string} options.resolution resolution constraints
  882. * @param {string} options.cameraDeviceId
  883. * @param {string} options.micDeviceId
  884. * @param {Object} options.desktopSharingFrameRate
  885. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  886. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  887. * @returns {*} Promise object that will receive the new JitsiTracks
  888. */
  889. obtainAudioAndVideoPermissions(options = {}) {
  890. options.devices = options.devices || [ ...OLD_GUM_DEFAULT_DEVICES ];
  891. options.resolution = options.resolution || OLD_GUM_DEFAULT_RESOLUTION;
  892. const requestingDesktop = options.devices.includes('desktop');
  893. if (requestingDesktop && !screenObtainer.isSupported()) {
  894. return Promise.reject(
  895. new Error('Desktop sharing is not supported!'));
  896. }
  897. return this._getAudioAndVideoStreams(options).then(streams =>
  898. handleLocalStream(streams, options.resolution));
  899. }
  900. /**
  901. * Performs one call to getUserMedia for audio and/or video and another call
  902. * for desktop.
  903. *
  904. * @param {Object} options - An object describing how the gUM request should
  905. * be executed. See {@link obtainAudioAndVideoPermissions} for full options.
  906. * @returns {*} Promise object that will receive the new JitsiTracks on
  907. * success or a JitsiTrackError on failure.
  908. */
  909. _getAudioAndVideoStreams(options) {
  910. const requestingDesktop = options.devices.includes('desktop');
  911. options.devices = options.devices.filter(device =>
  912. device !== 'desktop');
  913. const gumPromise = options.devices.length
  914. ? this.getUserMediaWithConstraints(options.devices, options)
  915. : Promise.resolve(null);
  916. return gumPromise
  917. .then(avStream => {
  918. // If any requested devices are missing, call gum again in
  919. // an attempt to obtain the actual error. For example, the
  920. // requested video device is missing or permission was
  921. // denied.
  922. const missingTracks
  923. = this._getMissingTracks(options.devices, avStream);
  924. if (missingTracks.length) {
  925. this.stopMediaStream(avStream);
  926. return this.getUserMediaWithConstraints(
  927. missingTracks, options)
  928. // GUM has already failed earlier and this success
  929. // handling should not be reached.
  930. .then(() => Promise.reject(new JitsiTrackError(
  931. { name: 'UnknownError' },
  932. getConstraints(options.devices, options),
  933. missingTracks)));
  934. }
  935. return avStream;
  936. })
  937. .then(audioVideo => {
  938. if (!requestingDesktop) {
  939. return { audioVideo };
  940. }
  941. if (options.desktopSharingSourceDevice) {
  942. this.stopMediaStream(audioVideo);
  943. throw new Error('Using a camera as screenshare source is'
  944. + 'not supported on this browser.');
  945. }
  946. return new Promise((resolve, reject) => {
  947. screenObtainer.obtainStream(
  948. this._parseDesktopSharingOptions(options),
  949. desktop => resolve({
  950. audioVideo,
  951. desktop
  952. }),
  953. error => {
  954. if (audioVideo) {
  955. this.stopMediaStream(audioVideo);
  956. }
  957. reject(error);
  958. });
  959. });
  960. });
  961. }
  962. /**
  963. * Private utility for determining if the passed in MediaStream contains
  964. * tracks of the type(s) specified in the requested devices.
  965. *
  966. * @param {string[]} requestedDevices - The track types that are expected to
  967. * be includes in the stream.
  968. * @param {MediaStream} stream - The MediaStream to check if it has the
  969. * expected track types.
  970. * @returns {string[]} An array of string with the missing track types. The
  971. * array will be empty if all requestedDevices are found in the stream.
  972. */
  973. _getMissingTracks(requestedDevices = [], stream) {
  974. const missingDevices = [];
  975. const audioDeviceRequested = requestedDevices.includes('audio');
  976. const audioTracksReceived
  977. = stream && stream.getAudioTracks().length > 0;
  978. if (audioDeviceRequested && !audioTracksReceived) {
  979. missingDevices.push('audio');
  980. }
  981. const videoDeviceRequested = requestedDevices.includes('video');
  982. const videoTracksReceived
  983. = stream && stream.getVideoTracks().length > 0;
  984. if (videoDeviceRequested && !videoTracksReceived) {
  985. missingDevices.push('video');
  986. }
  987. return missingDevices;
  988. }
  989. /**
  990. * Returns an object formatted for specifying desktop sharing parameters.
  991. *
  992. * @param {Object} options - Takes in the same options object as
  993. * {@link obtainAudioAndVideoPermissions}.
  994. * @returns {Object}
  995. */
  996. _parseDesktopSharingOptions(options) {
  997. return {
  998. desktopSharingSources: options.desktopSharingSources,
  999. gumOptions: {
  1000. frameRate: options.desktopSharingFrameRate
  1001. },
  1002. trackOptions: getTrackSSConstraints(options)
  1003. };
  1004. }
  1005. /**
  1006. * Gets streams from specified device types. This function intentionally
  1007. * ignores errors for upstream to catch and handle instead.
  1008. *
  1009. * @param {Object} options - A hash describing what devices to get and
  1010. * relevant constraints.
  1011. * @param {string[]} options.devices - The types of media to capture. Valid
  1012. * values are "desktop", "audio", and "video".
  1013. * @param {Object} options.desktopSharingFrameRate
  1014. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  1015. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  1016. * @param {String} options.desktopSharingSourceDevice - The device id or
  1017. * label for a video input source that should be used for screensharing.
  1018. * @returns {Promise} The promise, when successful, will return an array of
  1019. * meta data for the requested device type, which includes the stream and
  1020. * track. If an error occurs, it will be deferred to the caller for
  1021. * handling.
  1022. */
  1023. newObtainAudioAndVideoPermissions(options) {
  1024. logger.info('Using the new gUM flow');
  1025. const mediaStreamsMetaData = [];
  1026. // Declare private functions to be used in the promise chain below.
  1027. // These functions are declared in the scope of this function because
  1028. // they are not being used anywhere else, so only this function needs to
  1029. // know about them.
  1030. /**
  1031. * Executes a request for desktop media if specified in options.
  1032. *
  1033. * @returns {Promise}
  1034. */
  1035. const maybeRequestDesktopDevice = function() {
  1036. const umDevices = options.devices || [];
  1037. const isDesktopDeviceRequested
  1038. = umDevices.indexOf('desktop') !== -1;
  1039. if (!isDesktopDeviceRequested) {
  1040. return Promise.resolve();
  1041. }
  1042. const {
  1043. desktopSharingSourceDevice,
  1044. desktopSharingSources,
  1045. desktopSharingFrameRate
  1046. } = options;
  1047. // Attempt to use a video input device as a screenshare source if
  1048. // the option is defined.
  1049. if (desktopSharingSourceDevice) {
  1050. const matchingDevice
  1051. = availableDevices && availableDevices.find(device =>
  1052. device.kind === 'videoinput'
  1053. && (device.deviceId === desktopSharingSourceDevice
  1054. || device.label === desktopSharingSourceDevice));
  1055. if (!matchingDevice) {
  1056. return Promise.reject(new JitsiTrackError(
  1057. { name: 'ConstraintNotSatisfiedError' },
  1058. {},
  1059. [ desktopSharingSourceDevice ]
  1060. ));
  1061. }
  1062. const requestedDevices = [ 'video' ];
  1063. // Leverage the helper used by {@link _newGetDesktopMedia} to
  1064. // get constraints for the desktop stream.
  1065. const { gumOptions, trackOptions }
  1066. = this._parseDesktopSharingOptions(options);
  1067. const constraints = {
  1068. video: {
  1069. ...gumOptions,
  1070. deviceId: matchingDevice.deviceId
  1071. }
  1072. };
  1073. return this._newGetUserMediaWithConstraints(
  1074. requestedDevices, constraints)
  1075. .then(stream => {
  1076. const track = stream && stream.getTracks()[0];
  1077. const applyConstrainsPromise
  1078. = track && track.applyConstraints
  1079. ? track.applyConstraints(trackOptions)
  1080. : Promise.resolve();
  1081. return applyConstrainsPromise
  1082. .then(() => {
  1083. return {
  1084. sourceType: 'device',
  1085. stream
  1086. };
  1087. });
  1088. });
  1089. }
  1090. return this._newGetDesktopMedia({
  1091. desktopSharingSources,
  1092. desktopSharingFrameRate
  1093. });
  1094. }.bind(this);
  1095. /**
  1096. * Creates a meta data object about the passed in desktopStream and
  1097. * pushes the meta data to the internal array mediaStreamsMetaData to be
  1098. * returned later.
  1099. *
  1100. * @param {MediaStreamTrack} desktopStream - A track for a desktop
  1101. * capture.
  1102. * @returns {void}
  1103. */
  1104. const maybeCreateAndAddDesktopTrack = function(desktopStream) {
  1105. if (!desktopStream) {
  1106. return;
  1107. }
  1108. const { stream, sourceId, sourceType } = desktopStream;
  1109. const desktopAudioTracks = stream.getAudioTracks();
  1110. if (desktopAudioTracks.length) {
  1111. const desktopAudioStream = new MediaStream(desktopAudioTracks);
  1112. mediaStreamsMetaData.push({
  1113. stream: desktopAudioStream,
  1114. sourceId,
  1115. sourceType,
  1116. track: desktopAudioStream.getAudioTracks()[0]
  1117. });
  1118. }
  1119. const desktopVideoTracks = stream.getVideoTracks();
  1120. if (desktopVideoTracks.length) {
  1121. const desktopVideoStream = new MediaStream(desktopVideoTracks);
  1122. mediaStreamsMetaData.push({
  1123. stream: desktopVideoStream,
  1124. sourceId,
  1125. sourceType,
  1126. track: desktopVideoStream.getVideoTracks()[0],
  1127. videoType: VideoType.DESKTOP
  1128. });
  1129. }
  1130. };
  1131. /**
  1132. * Executes a request for audio and/or video, as specified in options.
  1133. * By default both audio and video will be captured if options.devices
  1134. * is not defined.
  1135. *
  1136. * @returns {Promise}
  1137. */
  1138. const maybeRequestCaptureDevices = function() {
  1139. const umDevices = options.devices || [ 'audio', 'video' ];
  1140. const requestedCaptureDevices = umDevices.filter(device => device === 'audio' || device === 'video');
  1141. if (!requestedCaptureDevices.length) {
  1142. return Promise.resolve();
  1143. }
  1144. const constraints = newGetConstraints(
  1145. requestedCaptureDevices, options);
  1146. logger.info('Got media constraints: ', JSON.stringify(constraints));
  1147. return this._newGetUserMediaWithConstraints(
  1148. requestedCaptureDevices, constraints);
  1149. }.bind(this);
  1150. /**
  1151. * Splits the passed in media stream into separate audio and video
  1152. * streams and creates meta data objects for each and pushes them to the
  1153. * internal array mediaStreamsMetaData to be returned later.
  1154. *
  1155. * @param {MediaStreamTrack} avStream - A track for with audio and/or
  1156. * video track.
  1157. * @returns {void}
  1158. */
  1159. const maybeCreateAndAddAVTracks = function(avStream) {
  1160. if (!avStream) {
  1161. return;
  1162. }
  1163. const audioTracks = avStream.getAudioTracks();
  1164. if (audioTracks.length) {
  1165. const audioStream = new MediaStream(audioTracks);
  1166. mediaStreamsMetaData.push({
  1167. stream: audioStream,
  1168. track: audioStream.getAudioTracks()[0],
  1169. effects: options.effects
  1170. });
  1171. }
  1172. const videoTracks = avStream.getVideoTracks();
  1173. if (videoTracks.length) {
  1174. const videoStream = new MediaStream(videoTracks);
  1175. mediaStreamsMetaData.push({
  1176. stream: videoStream,
  1177. track: videoStream.getVideoTracks()[0],
  1178. videoType: VideoType.CAMERA,
  1179. effects: options.effects
  1180. });
  1181. }
  1182. };
  1183. return maybeRequestDesktopDevice()
  1184. .then(maybeCreateAndAddDesktopTrack)
  1185. .then(maybeRequestCaptureDevices)
  1186. .then(maybeCreateAndAddAVTracks)
  1187. .then(() => mediaStreamsMetaData)
  1188. .catch(error => {
  1189. mediaStreamsMetaData.forEach(({ stream }) => {
  1190. this.stopMediaStream(stream);
  1191. });
  1192. return Promise.reject(error);
  1193. });
  1194. }
  1195. /**
  1196. * Checks whether it is possible to enumerate available cameras/microphones.
  1197. *
  1198. * @returns {boolean} {@code true} if the device listing is available;
  1199. * {@code false}, otherwise.
  1200. */
  1201. isDeviceListAvailable() {
  1202. return Boolean(
  1203. navigator.mediaDevices
  1204. && navigator.mediaDevices.enumerateDevices);
  1205. }
  1206. /**
  1207. * Returns true if changing the input (camera / microphone) or output
  1208. * (audio) device is supported and false if not.
  1209. * @params {string} [deviceType] - type of device to change. Default is
  1210. * undefined or 'input', 'output' - for audio output device change.
  1211. * @returns {boolean} true if available, false otherwise.
  1212. */
  1213. isDeviceChangeAvailable(deviceType) {
  1214. return deviceType === 'output' || deviceType === 'audiooutput'
  1215. ? isAudioOutputDeviceChangeAvailable
  1216. : true;
  1217. }
  1218. /**
  1219. * A method to handle stopping of the stream.
  1220. * One point to handle the differences in various implementations.
  1221. * @param mediaStream MediaStream object to stop.
  1222. */
  1223. stopMediaStream(mediaStream) {
  1224. if (!mediaStream) {
  1225. return;
  1226. }
  1227. mediaStream.getTracks().forEach(track => {
  1228. if (track.stop) {
  1229. track.stop();
  1230. }
  1231. });
  1232. // leave stop for implementation still using it
  1233. if (mediaStream.stop) {
  1234. mediaStream.stop();
  1235. }
  1236. // The MediaStream implementation of the react-native-webrtc project has
  1237. // an explicit release method that is to be invoked in order to release
  1238. // used resources such as memory.
  1239. if (mediaStream.release) {
  1240. mediaStream.release();
  1241. }
  1242. }
  1243. /**
  1244. * Returns whether the desktop sharing is enabled or not.
  1245. * @returns {boolean}
  1246. */
  1247. isDesktopSharingEnabled() {
  1248. return screenObtainer.isSupported();
  1249. }
  1250. /**
  1251. * Sets current audio output device.
  1252. * @param {string} deviceId - id of 'audiooutput' device from
  1253. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  1254. * device
  1255. * @returns {Promise} - resolves when audio output is changed, is rejected
  1256. * otherwise
  1257. */
  1258. setAudioOutputDevice(deviceId) {
  1259. if (!this.isDeviceChangeAvailable('output')) {
  1260. return Promise.reject(
  1261. new Error('Audio output device change is not supported'));
  1262. }
  1263. return featureDetectionAudioEl.setSinkId(deviceId)
  1264. .then(() => {
  1265. audioOutputDeviceId = deviceId;
  1266. audioOutputChanged = true;
  1267. logger.log(`Audio output device set to ${deviceId}`);
  1268. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1269. deviceId);
  1270. });
  1271. }
  1272. /**
  1273. * Returns currently used audio output device id, '' stands for default
  1274. * device
  1275. * @returns {string}
  1276. */
  1277. getAudioOutputDevice() {
  1278. return audioOutputDeviceId;
  1279. }
  1280. /**
  1281. * Returns list of available media devices if its obtained, otherwise an
  1282. * empty array is returned/
  1283. * @returns {Array} list of available media devices.
  1284. */
  1285. getCurrentlyAvailableMediaDevices() {
  1286. return availableDevices;
  1287. }
  1288. /**
  1289. * Returns event data for device to be reported to stats.
  1290. * @returns {MediaDeviceInfo} device.
  1291. */
  1292. getEventDataForActiveDevice(device) {
  1293. const deviceList = [];
  1294. const deviceData = {
  1295. 'deviceId': device.deviceId,
  1296. 'kind': device.kind,
  1297. 'label': device.label,
  1298. 'groupId': device.groupId
  1299. };
  1300. deviceList.push(deviceData);
  1301. return { deviceList };
  1302. }
  1303. /**
  1304. * Configures the given PeerConnection constraints to either enable or
  1305. * disable (according to the value of the 'enable' parameter) the
  1306. * 'googSuspendBelowMinBitrate' option.
  1307. * @param constraints the constraints on which to operate.
  1308. * @param enable {boolean} whether to enable or disable the suspend video
  1309. * option.
  1310. */
  1311. setSuspendVideo(constraints, enable) {
  1312. if (!constraints.optional) {
  1313. constraints.optional = [];
  1314. }
  1315. // Get rid of all "googSuspendBelowMinBitrate" constraints (we assume
  1316. // that the elements of constraints.optional contain a single property).
  1317. constraints.optional
  1318. = constraints.optional.filter(
  1319. c => !c.hasOwnProperty('googSuspendBelowMinBitrate'));
  1320. if (enable) {
  1321. constraints.optional.push({ googSuspendBelowMinBitrate: 'true' });
  1322. }
  1323. }
  1324. }
  1325. const rtcUtils = new RTCUtils();
  1326. /**
  1327. * Wraps original attachMediaStream function to set current audio output device
  1328. * if this is supported.
  1329. * @param {Function} origAttachMediaStream
  1330. * @returns {Function}
  1331. */
  1332. function wrapAttachMediaStream(origAttachMediaStream) {
  1333. return function(element, stream) {
  1334. // eslint-disable-next-line prefer-rest-params
  1335. const res = origAttachMediaStream.apply(rtcUtils, arguments);
  1336. if (stream
  1337. && rtcUtils.isDeviceChangeAvailable('output')
  1338. && stream.getAudioTracks
  1339. && stream.getAudioTracks().length
  1340. // we skip setting audio output if there was no explicit change
  1341. && audioOutputChanged) {
  1342. element.setSinkId(rtcUtils.getAudioOutputDevice())
  1343. .catch(function(ex) {
  1344. const err
  1345. = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  1346. GlobalOnErrorHandler.callUnhandledRejectionHandler({
  1347. promise: this, // eslint-disable-line no-invalid-this
  1348. reason: err
  1349. });
  1350. logger.warn(
  1351. 'Failed to set audio output device for the element.'
  1352. + ' Default audio output device will be used'
  1353. + ' instead',
  1354. element,
  1355. err);
  1356. });
  1357. }
  1358. return res;
  1359. };
  1360. }
  1361. export default rtcUtils;