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.

ScreenObtainer.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import JitsiTrackError from '../../JitsiTrackError';
  2. import * as JitsiTrackErrors from '../../JitsiTrackErrors';
  3. import browser from '../browser';
  4. const logger = require('@jitsi/logger').getLogger(__filename);
  5. /**
  6. * The default frame rate for Screen Sharing.
  7. */
  8. export const SS_DEFAULT_FRAME_RATE = 5;
  9. /**
  10. * Handles obtaining a stream from a screen capture on different browsers.
  11. */
  12. const ScreenObtainer = {
  13. /**
  14. * If not <tt>null</tt> it means that the initialization process is still in
  15. * progress. It is used to make desktop stream request wait and continue
  16. * after it's done.
  17. * {@type Promise|null}
  18. */
  19. obtainStream: null,
  20. /**
  21. * Initializes the function used to obtain a screen capture
  22. * (this.obtainStream).
  23. *
  24. * @param {object} options
  25. */
  26. init(options = {}) {
  27. this.options = options;
  28. this.obtainStream = this._createObtainStreamMethod();
  29. if (!this.obtainStream) {
  30. logger.info('Desktop sharing disabled');
  31. }
  32. },
  33. /**
  34. * Returns a method which will be used to obtain the screen sharing stream
  35. * (based on the browser type).
  36. *
  37. * @returns {Function}
  38. * @private
  39. */
  40. _createObtainStreamMethod() {
  41. if (browser.isElectron()) {
  42. return this.obtainScreenOnElectron;
  43. } else if (browser.isReactNative() && browser.supportsGetDisplayMedia()) {
  44. return this.obtainScreenFromGetDisplayMediaRN;
  45. } else if (browser.supportsGetDisplayMedia()) {
  46. return this.obtainScreenFromGetDisplayMedia;
  47. }
  48. logger.log('Screen sharing not supported on ', browser.getName());
  49. return null;
  50. },
  51. /**
  52. * Gets the appropriate constraints for audio sharing.
  53. *
  54. * @returns {Object|boolean}
  55. */
  56. _getAudioConstraints() {
  57. const { audioQuality } = this.options;
  58. const audio = audioQuality?.stereo ? {
  59. autoGainControl: false,
  60. channelCount: 2,
  61. echoCancellation: false,
  62. noiseSuppression: false
  63. } : true;
  64. return audio;
  65. },
  66. /**
  67. * Checks whether obtaining a screen capture is supported in the current
  68. * environment.
  69. * @returns {boolean}
  70. */
  71. isSupported() {
  72. return this.obtainStream !== null;
  73. },
  74. /**
  75. * Obtains a screen capture stream on Electron.
  76. *
  77. * @param onSuccess - Success callback.
  78. * @param onFailure - Failure callback.
  79. * @param {Object} options - Optional parameters.
  80. */
  81. obtainScreenOnElectron(onSuccess, onFailure, options = {}) {
  82. if (window.JitsiMeetScreenObtainer && window.JitsiMeetScreenObtainer.openDesktopPicker) {
  83. const { desktopSharingFrameRate, desktopSharingResolution, desktopSharingSources } = this.options;
  84. window.JitsiMeetScreenObtainer.openDesktopPicker(
  85. {
  86. desktopSharingSources:
  87. options.desktopSharingSources || desktopSharingSources || [ 'screen', 'window' ]
  88. },
  89. (streamId, streamType, screenShareAudio = false) => {
  90. if (streamId) {
  91. let audioConstraints = false;
  92. if (screenShareAudio) {
  93. audioConstraints = {};
  94. const optionalConstraints = this._getAudioConstraints();
  95. if (typeof optionalConstraints !== 'boolean') {
  96. audioConstraints = {
  97. optional: optionalConstraints
  98. };
  99. }
  100. // Audio screen sharing for electron only works for screen type devices.
  101. // i.e. when the user shares the whole desktop.
  102. // Note. The documentation specifies that chromeMediaSourceId should not be present
  103. // which, in the case a users has multiple monitors, leads to them being shared all
  104. // at once. However we tested with chromeMediaSourceId present and it seems to be
  105. // working properly.
  106. if (streamType === 'screen') {
  107. audioConstraints.mandatory = {
  108. chromeMediaSource: 'desktop'
  109. };
  110. }
  111. }
  112. const constraints = {
  113. audio: audioConstraints,
  114. video: {
  115. mandatory: {
  116. chromeMediaSource: 'desktop',
  117. chromeMediaSourceId: streamId,
  118. minFrameRate: desktopSharingFrameRate?.min ?? SS_DEFAULT_FRAME_RATE,
  119. maxFrameRate: desktopSharingFrameRate?.max ?? SS_DEFAULT_FRAME_RATE,
  120. minWidth: desktopSharingResolution?.width?.min,
  121. minHeight: desktopSharingResolution?.height?.min,
  122. maxWidth: desktopSharingResolution?.width?.max ?? window.screen.width,
  123. maxHeight: desktopSharingResolution?.height?.max ?? window.screen.height
  124. }
  125. }
  126. };
  127. // We have to use the old API on Electron to get a desktop stream.
  128. navigator.mediaDevices.getUserMedia(constraints)
  129. .then(stream => {
  130. this.setContentHint(stream);
  131. onSuccess({
  132. stream,
  133. sourceId: streamId,
  134. sourceType: streamType
  135. });
  136. })
  137. .catch(err => onFailure(err));
  138. } else {
  139. // As noted in Chrome Desktop Capture API:
  140. // If user didn't select any source (i.e. canceled the prompt)
  141. // then the callback is called with an empty streamId.
  142. onFailure(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_USER_CANCELED));
  143. }
  144. },
  145. err => onFailure(new JitsiTrackError(
  146. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_ERROR,
  147. err
  148. ))
  149. );
  150. } else {
  151. onFailure(new JitsiTrackError(JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_NOT_FOUND));
  152. }
  153. },
  154. /**
  155. * Obtains a screen capture stream using getDisplayMedia.
  156. *
  157. * @param callback - The success callback.
  158. * @param errorCallback - The error callback.
  159. */
  160. obtainScreenFromGetDisplayMedia(callback, errorCallback) {
  161. let getDisplayMedia;
  162. if (navigator.getDisplayMedia) {
  163. getDisplayMedia = navigator.getDisplayMedia.bind(navigator);
  164. } else {
  165. // eslint-disable-next-line max-len
  166. getDisplayMedia = navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);
  167. }
  168. const audio = this._getAudioConstraints();
  169. let video = {};
  170. const { desktopSharingFrameRate } = this.options;
  171. if (typeof desktopSharingFrameRate === 'object') {
  172. video.frameRate = desktopSharingFrameRate;
  173. }
  174. // At the time of this writing 'min' constraint for fps is not supported by getDisplayMedia on any of the
  175. // browsers. getDisplayMedia will fail with an error "invalid constraints" in this case.
  176. video.frameRate && delete video.frameRate.min;
  177. if (browser.isChromiumBased()) {
  178. // Allow users to seamlessly switch which tab they are sharing without having to select the tab again.
  179. browser.isVersionGreaterThan(106) && (video.surfaceSwitching = 'include');
  180. // Set bogus resolution constraints to work around
  181. // https://bugs.chromium.org/p/chromium/issues/detail?id=1056311 for low fps screenshare. Capturing SS at
  182. // very high resolutions restricts the framerate. Therefore, skip this hack when capture fps > 5 fps.
  183. if (!(desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE)) {
  184. video.height = 99999;
  185. video.width = 99999;
  186. }
  187. }
  188. if (Object.keys(video).length === 0) {
  189. video = true;
  190. }
  191. const constraints = {
  192. video,
  193. audio,
  194. cursor: 'always'
  195. };
  196. logger.info('Using getDisplayMedia for screen sharing', constraints);
  197. getDisplayMedia(constraints)
  198. .then(stream => {
  199. this.setContentHint(stream);
  200. callback({
  201. stream,
  202. sourceId: stream.id
  203. });
  204. })
  205. .catch(error => {
  206. const errorDetails = {
  207. errorName: error && error.name,
  208. errorMsg: error && error.message,
  209. errorStack: error && error.stack
  210. };
  211. logger.error('getDisplayMedia error', constraints, errorDetails);
  212. if (errorDetails.errorMsg && errorDetails.errorMsg.indexOf('denied by system') !== -1) {
  213. // On Chrome this is the only thing different between error returned when user cancels
  214. // and when no permission was given on the OS level.
  215. errorCallback(new JitsiTrackError(JitsiTrackErrors.PERMISSION_DENIED));
  216. return;
  217. }
  218. errorCallback(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_USER_CANCELED));
  219. });
  220. },
  221. /**
  222. * Obtains a screen capture stream using getDisplayMedia.
  223. *
  224. * @param callback - The success callback.
  225. * @param errorCallback - The error callback.
  226. */
  227. obtainScreenFromGetDisplayMediaRN(callback, errorCallback) {
  228. logger.info('Using getDisplayMedia for screen sharing');
  229. navigator.mediaDevices.getDisplayMedia({ video: true })
  230. .then(stream => {
  231. this.setContentHint(stream);
  232. callback({
  233. stream,
  234. sourceId: stream.id });
  235. })
  236. .catch(() => {
  237. errorCallback(new JitsiTrackError(JitsiTrackErrors
  238. .SCREENSHARING_USER_CANCELED));
  239. });
  240. },
  241. /** Sets the contentHint on the transmitted MediaStreamTrack to indicate charaterstics in the video stream, which
  242. * informs RTCPeerConnection on how to encode the track (to prefer motion or individual frame detail).
  243. *
  244. * @param {MediaStream} stream - The captured desktop stream.
  245. * @returns {void}
  246. */
  247. setContentHint(stream) {
  248. const { desktopSharingFrameRate } = this.options;
  249. const desktopTrack = stream.getVideoTracks()[0];
  250. // Set contentHint on the desktop track based on the fps requested.
  251. if ('contentHint' in desktopTrack) {
  252. desktopTrack.contentHint = desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE ? 'motion' : 'detail';
  253. } else {
  254. logger.warn('MediaStreamTrack contentHint attribute not supported');
  255. }
  256. },
  257. /**
  258. * Sets the max frame rate to be used for a desktop track capture.
  259. *
  260. * @param {number} maxFps capture frame rate to be used for desktop tracks.
  261. * @returns {void}
  262. */
  263. setDesktopSharingFrameRate(maxFps) {
  264. logger.info(`Setting the desktop capture rate to ${maxFps}`);
  265. this.options.desktopSharingFrameRate = {
  266. min: SS_DEFAULT_FRAME_RATE,
  267. max: maxFps
  268. };
  269. }
  270. };
  271. export default ScreenObtainer;