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

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