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

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