Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

RTCUtils.js 56KB

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