Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

RTCUtils.js 31KB

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