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 56KB

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