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

RTCUtils.js 58KB

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