modified lib-jitsi-meet dev repo
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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. /* global
  2. __filename,
  3. MediaStreamTrack,
  4. RTCIceCandidate: true,
  5. RTCPeerConnection,
  6. RTCSessionDescription: true
  7. */
  8. import EventEmitter from 'events';
  9. import { getLogger } from 'jitsi-meet-logger';
  10. import clonedeep from 'lodash.clonedeep';
  11. import JitsiTrackError from '../../JitsiTrackError';
  12. import * as JitsiTrackErrors from '../../JitsiTrackErrors';
  13. import CameraFacingMode from '../../service/RTC/CameraFacingMode';
  14. import RTCEvents from '../../service/RTC/RTCEvents';
  15. import Resolutions from '../../service/RTC/Resolutions';
  16. import VideoType from '../../service/RTC/VideoType';
  17. import { AVAILABLE_DEVICE } from '../../service/statistics/AnalyticsEvents';
  18. import browser from '../browser';
  19. import SDPUtil from '../sdp/SDPUtil';
  20. import Statistics from '../statistics/statistics';
  21. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  22. import Listenable from '../util/Listenable';
  23. import screenObtainer from './ScreenObtainer';
  24. const logger = getLogger(__filename);
  25. // Require adapter only for certain browsers. This is being done for
  26. // react-native, which has its own shims, and while browsers are being migrated
  27. // over to use adapter's shims.
  28. if (browser.usesAdapter()) {
  29. require('webrtc-adapter');
  30. }
  31. const eventEmitter = new EventEmitter();
  32. const AVAILABLE_DEVICES_POLL_INTERVAL_TIME = 3000; // ms
  33. /**
  34. * Default MediaStreamConstraints to use for calls to getUserMedia.
  35. *
  36. * @private
  37. */
  38. const DEFAULT_CONSTRAINTS = {
  39. video: {
  40. height: {
  41. ideal: 720,
  42. max: 720,
  43. min: 180
  44. },
  45. width: {
  46. ideal: 1280,
  47. max: 1280,
  48. min: 320
  49. }
  50. }
  51. };
  52. // Currently audio output device change is supported only in Chrome and
  53. // default output always has 'default' device ID
  54. let audioOutputDeviceId = 'default'; // default device
  55. // whether user has explicitly set a device to use
  56. let audioOutputChanged = false;
  57. // Disables all audio processing
  58. let disableAP = false;
  59. // Disables Acoustic Echo Cancellation
  60. let disableAEC = false;
  61. // Disables Noise Suppression
  62. let disableNS = false;
  63. // Disables Automatic Gain Control
  64. let disableAGC = false;
  65. // Enables stereo.
  66. let stereo = null;
  67. const featureDetectionAudioEl = document.createElement('audio');
  68. const isAudioOutputDeviceChangeAvailable
  69. = typeof featureDetectionAudioEl.setSinkId !== 'undefined';
  70. let availableDevices = [];
  71. let availableDevicesPollTimer;
  72. /**
  73. * An empty function.
  74. */
  75. function emptyFuncton() {
  76. // no-op
  77. }
  78. /**
  79. * Creates a constraints object to be passed into a call to getUserMedia.
  80. *
  81. * @param {Array} um - An array of user media types to get. The accepted
  82. * types are "video", "audio", and "desktop."
  83. * @param {Object} options - Various values to be added to the constraints.
  84. * @param {string} options.cameraDeviceId - The device id for the video
  85. * capture device to get video from.
  86. * @param {Object} options.constraints - Default constraints object to use
  87. * as a base for the returned constraints.
  88. * @param {Object} options.desktopStream - The desktop source id from which
  89. * to capture a desktop sharing video.
  90. * @param {string} options.facingMode - Which direction the camera is
  91. * pointing to.
  92. * @param {string} options.micDeviceId - The device id for the audio capture
  93. * device to get audio from.
  94. * @param {Object} options.frameRate - used only for dekstop sharing.
  95. * @param {Object} options.frameRate.min - Minimum fps
  96. * @param {Object} options.frameRate.max - Maximum fps
  97. * @private
  98. * @returns {Object}
  99. */
  100. function getConstraints(um = [], options = {}) {
  101. // Create a deep copy of the constraints to avoid any modification of
  102. // the passed in constraints object.
  103. const constraints = clonedeep(options.constraints || DEFAULT_CONSTRAINTS);
  104. if (um.indexOf('video') >= 0) {
  105. // The "resolution" option is a shortcut and takes precendence.
  106. if (Resolutions[options.resolution]) {
  107. const r = Resolutions[options.resolution];
  108. constraints.video = {
  109. height: { ideal: r.height },
  110. width: { ideal: r.width }
  111. };
  112. }
  113. if (!constraints.video) {
  114. constraints.video = {};
  115. }
  116. // Override the constraints on Safari because of the following webkit bug.
  117. // https://bugs.webkit.org/show_bug.cgi?id=210932
  118. // Camera doesn't start on older macOS versions if min/max constraints are specified.
  119. // TODO: remove this hack when the bug fix is available on Mojave, Sierra and High Sierra.
  120. if (browser.isWebKitBased()) {
  121. if (constraints.video.height && constraints.video.height.ideal) {
  122. constraints.video.height = { ideal: constraints.video.height.ideal };
  123. } else {
  124. logger.warn('Ideal camera height missing, camera may not start properly');
  125. }
  126. if (constraints.video.width && constraints.video.width.ideal) {
  127. constraints.video.width = { ideal: constraints.video.width.ideal };
  128. } else {
  129. logger.warn('Ideal camera width missing, camera may not start properly');
  130. }
  131. }
  132. if (options.cameraDeviceId) {
  133. constraints.video.deviceId = options.cameraDeviceId;
  134. } else {
  135. const facingMode = options.facingMode || CameraFacingMode.USER;
  136. constraints.video.facingMode = facingMode;
  137. }
  138. } else {
  139. constraints.video = false;
  140. }
  141. if (um.indexOf('audio') >= 0) {
  142. if (!constraints.audio || typeof constraints.audio === 'boolean') {
  143. constraints.audio = {};
  144. }
  145. constraints.audio = {
  146. autoGainControl: !disableAGC && !disableAP,
  147. deviceId: options.micDeviceId,
  148. echoCancellation: !disableAEC && !disableAP,
  149. noiseSuppression: !disableNS && !disableAP
  150. };
  151. if (stereo) {
  152. Object.assign(constraints.audio, { channelCount: 2 });
  153. }
  154. } else {
  155. constraints.audio = false;
  156. }
  157. return constraints;
  158. }
  159. /**
  160. * Updates the granted permissions based on the options we requested and the
  161. * streams we received.
  162. * @param um the options we requested to getUserMedia.
  163. * @param stream the stream we received from calling getUserMedia.
  164. */
  165. function updateGrantedPermissions(um, stream) {
  166. const audioTracksReceived
  167. = Boolean(stream) && stream.getAudioTracks().length > 0;
  168. const videoTracksReceived
  169. = Boolean(stream) && stream.getVideoTracks().length > 0;
  170. const grantedPermissions = {};
  171. if (um.indexOf('video') !== -1) {
  172. grantedPermissions.video = videoTracksReceived;
  173. }
  174. if (um.indexOf('audio') !== -1) {
  175. grantedPermissions.audio = audioTracksReceived;
  176. }
  177. eventEmitter.emit(RTCEvents.PERMISSIONS_CHANGED, grantedPermissions);
  178. }
  179. /**
  180. * Checks if new list of available media devices differs from previous one.
  181. * @param {MediaDeviceInfo[]} newDevices - list of new devices.
  182. * @returns {boolean} - true if list is different, false otherwise.
  183. */
  184. function compareAvailableMediaDevices(newDevices) {
  185. if (newDevices.length !== availableDevices.length) {
  186. return true;
  187. }
  188. /* eslint-disable newline-per-chained-call */
  189. return (
  190. newDevices.map(mediaDeviceInfoToJSON).sort().join('')
  191. !== availableDevices
  192. .map(mediaDeviceInfoToJSON).sort().join(''));
  193. /* eslint-enable newline-per-chained-call */
  194. /**
  195. *
  196. * @param info
  197. */
  198. function mediaDeviceInfoToJSON(info) {
  199. return JSON.stringify({
  200. kind: info.kind,
  201. deviceId: info.deviceId,
  202. groupId: info.groupId,
  203. label: info.label,
  204. facing: info.facing
  205. });
  206. }
  207. }
  208. /**
  209. * Sends analytics event with the passed device list.
  210. *
  211. * @param {Array<MediaDeviceInfo>} deviceList - List with info about the
  212. * available devices.
  213. * @returns {void}
  214. */
  215. function sendDeviceListToAnalytics(deviceList) {
  216. const audioInputDeviceCount
  217. = deviceList.filter(d => d.kind === 'audioinput').length;
  218. const audioOutputDeviceCount
  219. = deviceList.filter(d => d.kind === 'audiooutput').length;
  220. const videoInputDeviceCount
  221. = deviceList.filter(d => d.kind === 'videoinput').length;
  222. const videoOutputDeviceCount
  223. = deviceList.filter(d => d.kind === 'videooutput').length;
  224. deviceList.forEach(device => {
  225. const attributes = {
  226. 'audio_input_device_count': audioInputDeviceCount,
  227. 'audio_output_device_count': audioOutputDeviceCount,
  228. 'video_input_device_count': videoInputDeviceCount,
  229. 'video_output_device_count': videoOutputDeviceCount,
  230. 'device_id': device.deviceId,
  231. 'device_group_id': device.groupId,
  232. 'device_kind': device.kind,
  233. 'device_label': device.label
  234. };
  235. Statistics.sendAnalytics(AVAILABLE_DEVICE, attributes);
  236. });
  237. }
  238. /**
  239. * Update known devices.
  240. *
  241. * @param {Array<Object>} pds - The new devices.
  242. * @returns {void}
  243. *
  244. * NOTE: Use this function as a shared callback to handle both the devicechange event and the polling implementations.
  245. * This prevents duplication and works around a chrome bug (verified to occur on 68) where devicechange fires twice in
  246. * a row, which can cause async post devicechange processing to collide.
  247. */
  248. function updateKnownDevices(pds) {
  249. if (compareAvailableMediaDevices(pds)) {
  250. onMediaDevicesListChanged(pds);
  251. }
  252. }
  253. /**
  254. * Event handler for the 'devicechange' event.
  255. *
  256. * @param {MediaDeviceInfo[]} devices - list of media devices.
  257. * @emits RTCEvents.DEVICE_LIST_CHANGED
  258. */
  259. function onMediaDevicesListChanged(devicesReceived) {
  260. availableDevices = devicesReceived.slice(0);
  261. logger.info('list of media devices has changed:', availableDevices);
  262. sendDeviceListToAnalytics(availableDevices);
  263. // Used by tracks to update the real device id before the consumer of lib-jitsi-meet receives the new device list.
  264. eventEmitter.emit(RTCEvents.DEVICE_LIST_WILL_CHANGE, availableDevices);
  265. eventEmitter.emit(RTCEvents.DEVICE_LIST_CHANGED, availableDevices);
  266. }
  267. /**
  268. *
  269. */
  270. class RTCUtils extends Listenable {
  271. /**
  272. *
  273. */
  274. constructor() {
  275. super(eventEmitter);
  276. }
  277. /**
  278. * Depending on the browser, sets difference instance methods for
  279. * interacting with user media and adds methods to native WebRTC-related
  280. * objects. Also creates an instance variable for peer connection
  281. * constraints.
  282. *
  283. * @param {Object} options
  284. * @returns {void}
  285. */
  286. init(options = {}) {
  287. if (typeof options.disableAEC === 'boolean') {
  288. disableAEC = options.disableAEC;
  289. logger.info(`Disable AEC: ${disableAEC}`);
  290. }
  291. if (typeof options.disableNS === 'boolean') {
  292. disableNS = options.disableNS;
  293. logger.info(`Disable NS: ${disableNS}`);
  294. }
  295. if (typeof options.disableAP === 'boolean') {
  296. disableAP = options.disableAP;
  297. logger.info(`Disable AP: ${disableAP}`);
  298. }
  299. if (typeof options.disableAGC === 'boolean') {
  300. disableAGC = options.disableAGC;
  301. logger.info(`Disable AGC: ${disableAGC}`);
  302. }
  303. if (typeof options.audioQuality?.stereo === 'boolean') {
  304. stereo = options.audioQuality.stereo;
  305. logger.info(`Stereo: ${stereo}`);
  306. }
  307. window.clearInterval(availableDevicesPollTimer);
  308. availableDevicesPollTimer = undefined;
  309. if (browser.isReactNative()) {
  310. this.RTCPeerConnectionType = RTCPeerConnection;
  311. this.attachMediaStream = undefined; // Unused on React Native.
  312. this.getStreamID = function({ id }) {
  313. // The react-native-webrtc implementation that we use at the
  314. // time of this writing returns a number for the id of
  315. // MediaStream. Let's just say that a number contains no special
  316. // characters.
  317. return (
  318. typeof id === 'number'
  319. ? id
  320. : SDPUtil.filterSpecialChars(id));
  321. };
  322. this.getTrackID = ({ id }) => id;
  323. } else {
  324. this.RTCPeerConnectionType = RTCPeerConnection;
  325. this.attachMediaStream
  326. = wrapAttachMediaStream((element, stream) => {
  327. if (element) {
  328. element.srcObject = stream;
  329. }
  330. });
  331. this.getStreamID = ({ id }) => id;
  332. this.getTrackID = ({ id }) => id;
  333. }
  334. this.pcConstraints = browser.isChromiumBased() || browser.isReactNative()
  335. ? { optional: [
  336. { googScreencastMinBitrate: 100 },
  337. { googCpuOveruseDetection: true }
  338. ] }
  339. : {};
  340. screenObtainer.init(options);
  341. if (this.isDeviceListAvailable()) {
  342. this.enumerateDevices(ds => {
  343. availableDevices = ds.slice(0);
  344. logger.debug('Available devices: ', availableDevices);
  345. sendDeviceListToAnalytics(availableDevices);
  346. eventEmitter.emit(
  347. RTCEvents.DEVICE_LIST_AVAILABLE,
  348. availableDevices);
  349. if (browser.supportsDeviceChangeEvent()) {
  350. navigator.mediaDevices.addEventListener(
  351. 'devicechange',
  352. () => this.enumerateDevices(emptyFuncton));
  353. } else {
  354. // Periodically poll enumerateDevices() method to check if
  355. // list of media devices has changed.
  356. availableDevicesPollTimer = window.setInterval(
  357. () => this.enumerateDevices(emptyFuncton),
  358. AVAILABLE_DEVICES_POLL_INTERVAL_TIME);
  359. }
  360. });
  361. }
  362. }
  363. /**
  364. *
  365. * @param {Function} callback
  366. */
  367. enumerateDevices(callback) {
  368. navigator.mediaDevices.enumerateDevices()
  369. .then(devices => {
  370. updateKnownDevices(devices);
  371. callback(devices);
  372. })
  373. .catch(error => {
  374. logger.warn(`Failed to enumerate devices. ${error}`);
  375. updateKnownDevices([]);
  376. callback([]);
  377. });
  378. }
  379. /**
  380. * Acquires a media stream via getUserMedia that
  381. * matches the given constraints
  382. *
  383. * @param {array} umDevices which devices to acquire (e.g. audio, video)
  384. * @param {Object} constraints - Stream specifications to use.
  385. * @param {number} timeout - The timeout in ms for GUM.
  386. * @returns {Promise}
  387. */
  388. _getUserMedia(umDevices, constraints = {}, timeout = 0) {
  389. return new Promise((resolve, reject) => {
  390. let gumTimeout, timeoutExpired = false;
  391. if (typeof timeout === 'number' && !isNaN(timeout) && timeout > 0) {
  392. gumTimeout = setTimeout(() => {
  393. timeoutExpired = true;
  394. gumTimeout = undefined;
  395. reject(new JitsiTrackError(JitsiTrackErrors.TIMEOUT));
  396. }, timeout);
  397. }
  398. navigator.mediaDevices.getUserMedia(constraints)
  399. .then(stream => {
  400. logger.log('onUserMediaSuccess');
  401. updateGrantedPermissions(umDevices, stream);
  402. if (!timeoutExpired) {
  403. if (typeof gumTimeout !== 'undefined') {
  404. clearTimeout(gumTimeout);
  405. }
  406. resolve(stream);
  407. }
  408. })
  409. .catch(error => {
  410. logger.warn(`Failed to get access to local media. ${error} ${JSON.stringify(constraints)}`);
  411. const jitsiError = new JitsiTrackError(error, constraints, umDevices);
  412. if (!timeoutExpired) {
  413. if (typeof gumTimeout !== 'undefined') {
  414. clearTimeout(gumTimeout);
  415. }
  416. reject(error);
  417. }
  418. if (jitsiError.name === JitsiTrackErrors.PERMISSION_DENIED) {
  419. updateGrantedPermissions(umDevices, undefined);
  420. }
  421. // else {
  422. // Probably the error is not caused by the lack of permissions and we don't need to update them.
  423. // }
  424. });
  425. });
  426. }
  427. /**
  428. * Acquire a display stream via the screenObtainer. This requires extra
  429. * logic compared to use screenObtainer versus normal device capture logic
  430. * in RTCUtils#_getUserMedia.
  431. *
  432. * @returns {Promise} A promise which will be resolved with an object which
  433. * contains the acquired display stream. If desktop sharing is not supported
  434. * then a rejected promise will be returned.
  435. */
  436. _getDesktopMedia() {
  437. if (!screenObtainer.isSupported()) {
  438. return Promise.reject(new Error('Desktop sharing is not supported!'));
  439. }
  440. return new Promise((resolve, reject) => {
  441. screenObtainer.obtainStream(
  442. stream => {
  443. resolve(stream);
  444. },
  445. error => {
  446. reject(error);
  447. });
  448. });
  449. }
  450. /**
  451. * Private utility for determining if the passed in MediaStream contains
  452. * tracks of the type(s) specified in the requested devices.
  453. *
  454. * @param {string[]} requestedDevices - The track types that are expected to
  455. * be includes in the stream.
  456. * @param {MediaStream} stream - The MediaStream to check if it has the
  457. * expected track types.
  458. * @returns {string[]} An array of string with the missing track types. The
  459. * array will be empty if all requestedDevices are found in the stream.
  460. */
  461. _getMissingTracks(requestedDevices = [], stream) {
  462. const missingDevices = [];
  463. const audioDeviceRequested = requestedDevices.includes('audio');
  464. const audioTracksReceived
  465. = stream && stream.getAudioTracks().length > 0;
  466. if (audioDeviceRequested && !audioTracksReceived) {
  467. missingDevices.push('audio');
  468. }
  469. const videoDeviceRequested = requestedDevices.includes('video');
  470. const videoTracksReceived
  471. = stream && stream.getVideoTracks().length > 0;
  472. if (videoDeviceRequested && !videoTracksReceived) {
  473. missingDevices.push('video');
  474. }
  475. return missingDevices;
  476. }
  477. /**
  478. * Gets streams from specified device types. This function intentionally
  479. * ignores errors for upstream to catch and handle instead.
  480. *
  481. * @param {Object} options - A hash describing what devices to get and
  482. * relevant constraints.
  483. * @param {string[]} options.devices - The types of media to capture. Valid
  484. * values are "desktop", "audio", and "video".
  485. * @param {Object} options.desktopSharingFrameRate
  486. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  487. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  488. * @param {String} options.desktopSharingSourceDevice - The device id or
  489. * label for a video input source that should be used for screensharing.
  490. * @returns {Promise} The promise, when successful, will return an array of
  491. * meta data for the requested device type, which includes the stream and
  492. * track. If an error occurs, it will be deferred to the caller for
  493. * handling.
  494. */
  495. obtainAudioAndVideoPermissions(options) {
  496. const {
  497. timeout,
  498. ...otherOptions
  499. } = options;
  500. const mediaStreamsMetaData = [];
  501. // Declare private functions to be used in the promise chain below.
  502. // These functions are declared in the scope of this function because
  503. // they are not being used anywhere else, so only this function needs to
  504. // know about them.
  505. /**
  506. * Executes a request for desktop media if specified in options.
  507. *
  508. * @returns {Promise}
  509. */
  510. const maybeRequestDesktopDevice = function() {
  511. const umDevices = otherOptions.devices || [];
  512. const isDesktopDeviceRequested
  513. = umDevices.indexOf('desktop') !== -1;
  514. if (!isDesktopDeviceRequested) {
  515. return Promise.resolve();
  516. }
  517. const {
  518. desktopSharingSourceDevice
  519. } = otherOptions;
  520. // Attempt to use a video input device as a screenshare source if
  521. // the option is defined.
  522. if (desktopSharingSourceDevice) {
  523. const matchingDevice
  524. = availableDevices && availableDevices.find(device =>
  525. device.kind === 'videoinput'
  526. && (device.deviceId === desktopSharingSourceDevice
  527. || device.label === desktopSharingSourceDevice));
  528. if (!matchingDevice) {
  529. return Promise.reject(new JitsiTrackError(
  530. { name: 'ConstraintNotSatisfiedError' },
  531. {},
  532. [ desktopSharingSourceDevice ]
  533. ));
  534. }
  535. const requestedDevices = [ 'video' ];
  536. const constraints = {
  537. video: {
  538. deviceId: matchingDevice.deviceId
  539. // frameRate is omited here on purpose since this is a device that we'll pretend is a screen.
  540. }
  541. };
  542. return this._getUserMedia(requestedDevices, constraints, timeout)
  543. .then(stream => {
  544. return {
  545. sourceType: 'device',
  546. stream
  547. };
  548. });
  549. }
  550. return this._getDesktopMedia();
  551. }.bind(this);
  552. /**
  553. * Creates a meta data object about the passed in desktopStream and
  554. * pushes the meta data to the internal array mediaStreamsMetaData to be
  555. * returned later.
  556. *
  557. * @param {MediaStreamTrack} desktopStream - A track for a desktop
  558. * capture.
  559. * @returns {void}
  560. */
  561. const maybeCreateAndAddDesktopTrack = function(desktopStream) {
  562. if (!desktopStream) {
  563. return;
  564. }
  565. const { stream, sourceId, sourceType } = desktopStream;
  566. const desktopAudioTracks = stream.getAudioTracks();
  567. if (desktopAudioTracks.length) {
  568. const desktopAudioStream = new MediaStream(desktopAudioTracks);
  569. mediaStreamsMetaData.push({
  570. stream: desktopAudioStream,
  571. sourceId,
  572. sourceType,
  573. track: desktopAudioStream.getAudioTracks()[0]
  574. });
  575. }
  576. const desktopVideoTracks = stream.getVideoTracks();
  577. if (desktopVideoTracks.length) {
  578. const desktopVideoStream = new MediaStream(desktopVideoTracks);
  579. mediaStreamsMetaData.push({
  580. stream: desktopVideoStream,
  581. sourceId,
  582. sourceType,
  583. track: desktopVideoStream.getVideoTracks()[0],
  584. videoType: VideoType.DESKTOP
  585. });
  586. }
  587. };
  588. /**
  589. * Executes a request for audio and/or video, as specified in options.
  590. * By default both audio and video will be captured if options.devices
  591. * is not defined.
  592. *
  593. * @returns {Promise}
  594. */
  595. const maybeRequestCaptureDevices = function() {
  596. const umDevices = otherOptions.devices || [ 'audio', 'video' ];
  597. const requestedCaptureDevices = umDevices.filter(device => device === 'audio' || device === 'video');
  598. if (!requestedCaptureDevices.length) {
  599. return Promise.resolve();
  600. }
  601. const constraints = getConstraints(requestedCaptureDevices, otherOptions);
  602. logger.info('Got media constraints: ', JSON.stringify(constraints));
  603. return this._getUserMedia(requestedCaptureDevices, constraints, timeout);
  604. }.bind(this);
  605. /**
  606. * Splits the passed in media stream into separate audio and video
  607. * streams and creates meta data objects for each and pushes them to the
  608. * internal array mediaStreamsMetaData to be returned later.
  609. *
  610. * @param {MediaStreamTrack} avStream - A track for with audio and/or
  611. * video track.
  612. * @returns {void}
  613. */
  614. const maybeCreateAndAddAVTracks = function(avStream) {
  615. if (!avStream) {
  616. return;
  617. }
  618. const audioTracks = avStream.getAudioTracks();
  619. if (audioTracks.length) {
  620. const audioStream = new MediaStream(audioTracks);
  621. mediaStreamsMetaData.push({
  622. stream: audioStream,
  623. track: audioStream.getAudioTracks()[0],
  624. effects: otherOptions.effects
  625. });
  626. }
  627. const videoTracks = avStream.getVideoTracks();
  628. if (videoTracks.length) {
  629. const videoStream = new MediaStream(videoTracks);
  630. mediaStreamsMetaData.push({
  631. stream: videoStream,
  632. track: videoStream.getVideoTracks()[0],
  633. videoType: VideoType.CAMERA,
  634. effects: otherOptions.effects
  635. });
  636. }
  637. };
  638. return maybeRequestDesktopDevice()
  639. .then(maybeCreateAndAddDesktopTrack)
  640. .then(maybeRequestCaptureDevices)
  641. .then(maybeCreateAndAddAVTracks)
  642. .then(() => mediaStreamsMetaData)
  643. .catch(error => {
  644. mediaStreamsMetaData.forEach(({ stream }) => {
  645. this.stopMediaStream(stream);
  646. });
  647. return Promise.reject(error);
  648. });
  649. }
  650. /**
  651. * Checks whether it is possible to enumerate available cameras/microphones.
  652. *
  653. * @returns {boolean} {@code true} if the device listing is available;
  654. * {@code false}, otherwise.
  655. */
  656. isDeviceListAvailable() {
  657. return Boolean(
  658. navigator.mediaDevices
  659. && navigator.mediaDevices.enumerateDevices);
  660. }
  661. /**
  662. * Returns true if changing the input (camera / microphone) or output
  663. * (audio) device is supported and false if not.
  664. * @params {string} [deviceType] - type of device to change. Default is
  665. * undefined or 'input', 'output' - for audio output device change.
  666. * @returns {boolean} true if available, false otherwise.
  667. */
  668. isDeviceChangeAvailable(deviceType) {
  669. return deviceType === 'output' || deviceType === 'audiooutput'
  670. ? isAudioOutputDeviceChangeAvailable
  671. : true;
  672. }
  673. /**
  674. * A method to handle stopping of the stream.
  675. * One point to handle the differences in various implementations.
  676. * @param mediaStream MediaStream object to stop.
  677. */
  678. stopMediaStream(mediaStream) {
  679. if (!mediaStream) {
  680. return;
  681. }
  682. mediaStream.getTracks().forEach(track => {
  683. if (track.stop) {
  684. track.stop();
  685. }
  686. });
  687. // leave stop for implementation still using it
  688. if (mediaStream.stop) {
  689. mediaStream.stop();
  690. }
  691. // The MediaStream implementation of the react-native-webrtc project has
  692. // an explicit release method that is to be invoked in order to release
  693. // used resources such as memory.
  694. if (mediaStream.release) {
  695. mediaStream.release();
  696. }
  697. }
  698. /**
  699. * Returns whether the desktop sharing is enabled or not.
  700. * @returns {boolean}
  701. */
  702. isDesktopSharingEnabled() {
  703. return screenObtainer.isSupported();
  704. }
  705. /**
  706. * Sets current audio output device.
  707. * @param {string} deviceId - id of 'audiooutput' device from
  708. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  709. * device
  710. * @returns {Promise} - resolves when audio output is changed, is rejected
  711. * otherwise
  712. */
  713. setAudioOutputDevice(deviceId) {
  714. if (!this.isDeviceChangeAvailable('output')) {
  715. return Promise.reject(
  716. new Error('Audio output device change is not supported'));
  717. }
  718. return featureDetectionAudioEl.setSinkId(deviceId)
  719. .then(() => {
  720. audioOutputDeviceId = deviceId;
  721. audioOutputChanged = true;
  722. logger.log(`Audio output device set to ${deviceId}`);
  723. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  724. deviceId);
  725. });
  726. }
  727. /**
  728. * Returns currently used audio output device id, '' stands for default
  729. * device
  730. * @returns {string}
  731. */
  732. getAudioOutputDevice() {
  733. return audioOutputDeviceId;
  734. }
  735. /**
  736. * Returns list of available media devices if its obtained, otherwise an
  737. * empty array is returned/
  738. * @returns {Array} list of available media devices.
  739. */
  740. getCurrentlyAvailableMediaDevices() {
  741. return availableDevices;
  742. }
  743. /**
  744. * Returns whether available devices have permissions granted
  745. * @returns {Boolean}
  746. */
  747. arePermissionsGrantedForAvailableDevices() {
  748. return availableDevices.some(device => Boolean(device.label));
  749. }
  750. /**
  751. * Returns event data for device to be reported to stats.
  752. * @returns {MediaDeviceInfo} device.
  753. */
  754. getEventDataForActiveDevice(device) {
  755. const deviceList = [];
  756. const deviceData = {
  757. 'deviceId': device.deviceId,
  758. 'kind': device.kind,
  759. 'label': device.label,
  760. 'groupId': device.groupId
  761. };
  762. deviceList.push(deviceData);
  763. return { deviceList };
  764. }
  765. /**
  766. * Configures the given PeerConnection constraints to either enable or
  767. * disable (according to the value of the 'enable' parameter) the
  768. * 'googSuspendBelowMinBitrate' option.
  769. * @param constraints the constraints on which to operate.
  770. * @param enable {boolean} whether to enable or disable the suspend video
  771. * option.
  772. */
  773. setSuspendVideo(constraints, enable) {
  774. if (!constraints.optional) {
  775. constraints.optional = [];
  776. }
  777. // Get rid of all "googSuspendBelowMinBitrate" constraints (we assume
  778. // that the elements of constraints.optional contain a single property).
  779. constraints.optional
  780. = constraints.optional.filter(
  781. c => !c.hasOwnProperty('googSuspendBelowMinBitrate'));
  782. if (enable) {
  783. constraints.optional.push({ googSuspendBelowMinBitrate: 'true' });
  784. }
  785. }
  786. }
  787. const rtcUtils = new RTCUtils();
  788. /**
  789. * Wraps original attachMediaStream function to set current audio output device
  790. * if this is supported.
  791. * @param {Function} origAttachMediaStream
  792. * @returns {Function}
  793. */
  794. function wrapAttachMediaStream(origAttachMediaStream) {
  795. return function(element, stream) {
  796. // eslint-disable-next-line prefer-rest-params
  797. const res = origAttachMediaStream.apply(rtcUtils, arguments);
  798. if (stream
  799. && rtcUtils.isDeviceChangeAvailable('output')
  800. && stream.getAudioTracks
  801. && stream.getAudioTracks().length
  802. // we skip setting audio output if there was no explicit change
  803. && audioOutputChanged) {
  804. element.setSinkId(rtcUtils.getAudioOutputDevice())
  805. .catch(function(ex) {
  806. const err
  807. = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  808. GlobalOnErrorHandler.callUnhandledRejectionHandler({
  809. promise: this, // eslint-disable-line no-invalid-this
  810. reason: err
  811. });
  812. logger.warn(
  813. 'Failed to set audio output device for the element.'
  814. + ' Default audio output device will be used'
  815. + ' instead',
  816. element,
  817. err);
  818. });
  819. }
  820. return res;
  821. };
  822. }
  823. export default rtcUtils;