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

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