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

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