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

RTCUtils.js 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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. screenObtainer.init(options);
  244. this.enumerateDevices(ds => {
  245. availableDevices = ds.slice(0);
  246. logger.debug('Available devices: ', availableDevices);
  247. sendDeviceListToAnalytics(availableDevices);
  248. this.eventEmitter.emit(
  249. RTCEvents.DEVICE_LIST_AVAILABLE,
  250. availableDevices);
  251. if (browser.supportsDeviceChangeEvent()) {
  252. navigator.mediaDevices.addEventListener(
  253. 'devicechange',
  254. () => this.enumerateDevices(emptyFuncton));
  255. } else {
  256. // Periodically poll enumerateDevices() method to check if
  257. // list of media devices has changed.
  258. availableDevicesPollTimer = window.setInterval(
  259. () => this.enumerateDevices(emptyFuncton),
  260. AVAILABLE_DEVICES_POLL_INTERVAL_TIME);
  261. }
  262. });
  263. }
  264. /**
  265. *
  266. * @param {Function} callback
  267. */
  268. enumerateDevices(callback) {
  269. navigator.mediaDevices.enumerateDevices()
  270. .then(devices => {
  271. this._updateKnownDevices(devices);
  272. callback(devices);
  273. })
  274. .catch(error => {
  275. logger.warn(`Failed to enumerate devices. ${error}`);
  276. this._updateKnownDevices([]);
  277. callback([]);
  278. });
  279. }
  280. /**
  281. * Acquires a media stream via getUserMedia that
  282. * matches the given constraints
  283. *
  284. * @param {array} umDevices which devices to acquire (e.g. audio, video)
  285. * @param {Object} constraints - Stream specifications to use.
  286. * @param {number} timeout - The timeout in ms for GUM.
  287. * @returns {Promise}
  288. */
  289. _getUserMedia(umDevices, constraints = {}, timeout = 0) {
  290. return new Promise((resolve, reject) => {
  291. let gumTimeout, timeoutExpired = false;
  292. if (isValidNumber(timeout) && timeout > 0) {
  293. gumTimeout = setTimeout(() => {
  294. timeoutExpired = true;
  295. gumTimeout = undefined;
  296. reject(new JitsiTrackError(JitsiTrackErrors.TIMEOUT));
  297. }, timeout);
  298. }
  299. navigator.mediaDevices.getUserMedia(constraints)
  300. .then(stream => {
  301. logger.info('onUserMediaSuccess');
  302. this._updateGrantedPermissions(umDevices, stream);
  303. if (!timeoutExpired) {
  304. if (typeof gumTimeout !== 'undefined') {
  305. clearTimeout(gumTimeout);
  306. }
  307. resolve(stream);
  308. }
  309. })
  310. .catch(error => {
  311. logger.warn(`Failed to get access to local media. ${error} ${JSON.stringify(constraints)}`);
  312. const jitsiError = new JitsiTrackError(error, constraints, umDevices);
  313. if (!timeoutExpired) {
  314. if (typeof gumTimeout !== 'undefined') {
  315. clearTimeout(gumTimeout);
  316. }
  317. reject(jitsiError);
  318. }
  319. if (jitsiError.name === JitsiTrackErrors.PERMISSION_DENIED) {
  320. this._updateGrantedPermissions(umDevices, undefined);
  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. resolution
  475. } = otherOptions;
  476. // Attempt to use a video input device as a screenshare source if
  477. // the option is defined.
  478. if (desktopSharingSourceDevice) {
  479. const matchingDevice
  480. = availableDevices && availableDevices.find(device =>
  481. device.kind === 'videoinput'
  482. && (device.deviceId === desktopSharingSourceDevice
  483. || device.label === desktopSharingSourceDevice));
  484. if (!matchingDevice) {
  485. return Promise.reject(new JitsiTrackError(
  486. { name: 'ConstraintNotSatisfiedError' },
  487. {},
  488. [ desktopSharingSourceDevice ]
  489. ));
  490. }
  491. const requestedDevices = [ 'video' ];
  492. const deviceConstraints = {
  493. video: {
  494. deviceId: matchingDevice.deviceId
  495. // frameRate is omited here on purpose since this is a device that we'll pretend is a screen.
  496. }
  497. };
  498. return this._getUserMedia(requestedDevices, deviceConstraints, timeout)
  499. .then(stream => {
  500. return {
  501. sourceType: 'device',
  502. stream
  503. };
  504. });
  505. }
  506. return this._getDesktopMedia({
  507. desktopSharingSources,
  508. resolution });
  509. }.bind(this);
  510. /**
  511. * Creates a meta data object about the passed in desktopStream and
  512. * pushes the meta data to the internal array mediaStreamsMetaData to be
  513. * returned later.
  514. *
  515. * @param {MediaStreamTrack} desktopStream - A track for a desktop
  516. * capture.
  517. * @returns {void}
  518. */
  519. const maybeCreateAndAddDesktopTrack = function(desktopStream) {
  520. if (!desktopStream) {
  521. return;
  522. }
  523. const { stream, sourceId, sourceType } = desktopStream;
  524. const desktopAudioTracks = stream.getAudioTracks();
  525. if (desktopAudioTracks.length) {
  526. const desktopAudioStream = new MediaStream(desktopAudioTracks);
  527. mediaStreamsMetaData.push({
  528. stream: desktopAudioStream,
  529. sourceId,
  530. sourceType,
  531. track: desktopAudioStream.getAudioTracks()[0]
  532. });
  533. }
  534. const desktopVideoTracks = stream.getVideoTracks();
  535. if (desktopVideoTracks.length) {
  536. const desktopVideoStream = new MediaStream(desktopVideoTracks);
  537. mediaStreamsMetaData.push({
  538. stream: desktopVideoStream,
  539. sourceId,
  540. sourceType,
  541. track: desktopVideoStream.getVideoTracks()[0],
  542. videoType: VideoType.DESKTOP
  543. });
  544. }
  545. };
  546. /**
  547. * Executes a request for audio and/or video, as specified in options.
  548. * By default both audio and video will be captured if options.devices
  549. * is not defined.
  550. *
  551. * @returns {Promise}
  552. */
  553. const maybeRequestCaptureDevices = function() {
  554. const umDevices = otherOptions.devices || [ 'audio', 'video' ];
  555. const requestedCaptureDevices = umDevices.filter(device => device === 'audio' || device === 'video');
  556. if (!requestedCaptureDevices.length) {
  557. return Promise.resolve();
  558. }
  559. constraints = getConstraints(requestedCaptureDevices, otherOptions);
  560. logger.info('Got media constraints: ', JSON.stringify(constraints));
  561. return this._getUserMedia(requestedCaptureDevices, constraints, timeout);
  562. }.bind(this);
  563. /**
  564. * Splits the passed in media stream into separate audio and video
  565. * streams and creates meta data objects for each and pushes them to the
  566. * internal array mediaStreamsMetaData to be returned later.
  567. *
  568. * @param {MediaStreamTrack} avStream - A track for with audio and/or
  569. * video track.
  570. * @returns {void}
  571. */
  572. const maybeCreateAndAddAVTracks = function(avStream) {
  573. if (!avStream) {
  574. return;
  575. }
  576. const audioTracks = avStream.getAudioTracks();
  577. if (audioTracks.length) {
  578. const audioStream = new MediaStream(audioTracks);
  579. mediaStreamsMetaData.push({
  580. constraints: constraints.audio,
  581. stream: audioStream,
  582. track: audioStream.getAudioTracks()[0],
  583. effects: otherOptions.effects
  584. });
  585. }
  586. const videoTracks = avStream.getVideoTracks();
  587. if (videoTracks.length) {
  588. const videoStream = new MediaStream(videoTracks);
  589. mediaStreamsMetaData.push({
  590. constraints: constraints.video,
  591. stream: videoStream,
  592. track: videoStream.getVideoTracks()[0],
  593. videoType: VideoType.CAMERA,
  594. effects: otherOptions.effects
  595. });
  596. }
  597. };
  598. return maybeRequestDesktopDevice()
  599. .then(maybeCreateAndAddDesktopTrack)
  600. .then(maybeRequestCaptureDevices)
  601. .then(maybeCreateAndAddAVTracks)
  602. .then(() => mediaStreamsMetaData)
  603. .catch(error => {
  604. mediaStreamsMetaData.forEach(({ stream }) => {
  605. this.stopMediaStream(stream);
  606. });
  607. return Promise.reject(error);
  608. });
  609. }
  610. /**
  611. * Returns true if changing the input (camera / microphone) or output
  612. * (audio) device is supported and false if not.
  613. * @params {string} [deviceType] - type of device to change. Default is
  614. * undefined or 'input', 'output' - for audio output device change.
  615. * @returns {boolean} true if available, false otherwise.
  616. */
  617. isDeviceChangeAvailable(deviceType) {
  618. if (deviceType === 'output' || deviceType === 'audiooutput') {
  619. return isAudioOutputDeviceChangeAvailable;
  620. }
  621. return true;
  622. }
  623. /**
  624. * A method to handle stopping of the stream.
  625. * One point to handle the differences in various implementations.
  626. * @param mediaStream MediaStream object to stop.
  627. */
  628. stopMediaStream(mediaStream) {
  629. if (!mediaStream) {
  630. return;
  631. }
  632. mediaStream.getTracks().forEach(track => {
  633. if (track.stop) {
  634. track.stop();
  635. }
  636. });
  637. // leave stop for implementation still using it
  638. if (mediaStream.stop) {
  639. mediaStream.stop();
  640. }
  641. // The MediaStream implementation of the react-native-webrtc project has
  642. // an explicit release method that is to be invoked in order to release
  643. // used resources such as memory.
  644. if (mediaStream.release) {
  645. mediaStream.release();
  646. }
  647. }
  648. /**
  649. * Returns whether the desktop sharing is enabled or not.
  650. * @returns {boolean}
  651. */
  652. isDesktopSharingEnabled() {
  653. return screenObtainer.isSupported();
  654. }
  655. /**
  656. * Sets current audio output device.
  657. * @param {string} deviceId - id of 'audiooutput' device from
  658. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  659. * device
  660. * @returns {Promise} - resolves when audio output is changed, is rejected
  661. * otherwise
  662. */
  663. setAudioOutputDevice(deviceId) {
  664. if (!this.isDeviceChangeAvailable('output')) {
  665. return Promise.reject(
  666. new Error('Audio output device change is not supported'));
  667. }
  668. return featureDetectionAudioEl.setSinkId(deviceId)
  669. .then(() => {
  670. audioOutputDeviceId = deviceId;
  671. audioOutputChanged = true;
  672. logger.debug(`Audio output device set to ${deviceId}`);
  673. this.eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  674. deviceId);
  675. });
  676. }
  677. /**
  678. * Sets the capture frame rate for desktop tracks.
  679. *
  680. * @param {number} maxFps - max fps to be used as the capture frame rate.
  681. * @returns {void}
  682. */
  683. setDesktopSharingFrameRate(maxFps) {
  684. screenObtainer.setDesktopSharingFrameRate(maxFps);
  685. }
  686. /**
  687. * Returns currently used audio output device id, '' stands for default
  688. * device
  689. * @returns {string}
  690. */
  691. getAudioOutputDevice() {
  692. return audioOutputDeviceId;
  693. }
  694. /**
  695. * Returns list of available media devices if its obtained, otherwise an
  696. * empty array is returned/
  697. * @returns {Array} list of available media devices.
  698. */
  699. getCurrentlyAvailableMediaDevices() {
  700. return availableDevices;
  701. }
  702. /**
  703. * Returns event data for device to be reported to stats.
  704. * @returns {MediaDeviceInfo} device.
  705. */
  706. getEventDataForActiveDevice(device) {
  707. const deviceList = [];
  708. const deviceData = {
  709. deviceId: device.deviceId,
  710. kind: device.kind,
  711. label: device.label,
  712. groupId: device.groupId
  713. };
  714. deviceList.push(deviceData);
  715. return { deviceList };
  716. }
  717. /**
  718. * Returns <tt>true<tt/> if a WebRTC MediaStream identified by given stream
  719. * ID is considered a valid "user" stream which means that it's not a
  720. * "receive only" stream nor a "mixed" JVB stream.
  721. *
  722. * Clients that implement Unified Plan, such as Firefox use recvonly
  723. * "streams/channels/tracks" for receiving remote stream/tracks, as opposed
  724. * to Plan B where there are only 3 channels: audio, video and data.
  725. *
  726. * @param {string} streamId The id of WebRTC MediaStream.
  727. * @returns {boolean}
  728. */
  729. isUserStreamById(streamId) {
  730. return streamId && streamId !== 'mixedmslabel' && streamId !== 'default';
  731. }
  732. }
  733. const rtcUtils = new RTCUtils();
  734. /**
  735. * Wraps original attachMediaStream function to set current audio output device
  736. * if this is supported.
  737. * @param {Function} origAttachMediaStream
  738. * @returns {Function}
  739. */
  740. function wrapAttachMediaStream(origAttachMediaStream) {
  741. return function(element, stream) {
  742. // eslint-disable-next-line prefer-rest-params
  743. origAttachMediaStream.apply(rtcUtils, arguments);
  744. if (stream
  745. && rtcUtils.isDeviceChangeAvailable('output')
  746. && stream.getAudioTracks
  747. && stream.getAudioTracks().length
  748. // we skip setting audio output if there was no explicit change
  749. && audioOutputChanged) {
  750. return element.setSinkId(rtcUtils.getAudioOutputDevice()).catch(ex => {
  751. const err
  752. = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  753. logger.warn(
  754. 'Failed to set audio output device for the element.'
  755. + ' Default audio output device will be used'
  756. + ' instead',
  757. element?.id,
  758. err);
  759. throw err;
  760. });
  761. }
  762. return Promise.resolve();
  763. };
  764. }
  765. export default rtcUtils;