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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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 constraintOpts = {};
  171. const {
  172. desktopSharingFrameRate,
  173. screenShareSettings
  174. } = this.options;
  175. if (typeof desktopSharingFrameRate === 'object') {
  176. video.frameRate = desktopSharingFrameRate;
  177. }
  178. // At the time of this writing 'min' constraint for fps is not supported by getDisplayMedia on any of the
  179. // browsers. getDisplayMedia will fail with an error "invalid constraints" in this case.
  180. video.frameRate && delete video.frameRate.min;
  181. if (browser.isChromiumBased()) {
  182. // Show users the current tab is the preferred capture source, default: false.
  183. browser.isEngineVersionGreaterThan(93)
  184. && (constraintOpts.preferCurrentTab = screenShareSettings?.desktopPreferCurrentTab || false);
  185. // Allow users to select system audio, default: include.
  186. browser.isEngineVersionGreaterThan(104)
  187. && (constraintOpts.systemAudio = screenShareSettings?.desktopSystemAudio || 'include');
  188. // Allow users to seamlessly switch which tab they are sharing without having to select the tab again.
  189. browser.isEngineVersionGreaterThan(106)
  190. && (constraintOpts.surfaceSwitching = screenShareSettings?.desktopSurfaceSwitching || 'include');
  191. // Allow a user to be shown a preference for what screen is to be captured, default: unset.
  192. browser.isEngineVersionGreaterThan(106) && screenShareSettings?.desktopDisplaySurface
  193. && (video.displaySurface = screenShareSettings?.desktopDisplaySurface);
  194. // Allow users to select the current tab as a capture source, default: exclude.
  195. browser.isEngineVersionGreaterThan(111)
  196. && (constraintOpts.selfBrowserSurface = screenShareSettings?.desktopSelfBrowserSurface || 'exclude');
  197. // Set bogus resolution constraints to work around
  198. // https://bugs.chromium.org/p/chromium/issues/detail?id=1056311 for low fps screenshare. Capturing SS at
  199. // very high resolutions restricts the framerate. Therefore, skip this hack when capture fps > 5 fps.
  200. if (!(desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE)) {
  201. video.height = 99999;
  202. video.width = 99999;
  203. }
  204. }
  205. // Allow a user to be shown a preference for what screen is to be captured.
  206. if (browser.isSafari() && screenShareSettings?.desktopDisplaySurface) {
  207. video.displaySurface = screenShareSettings?.desktopDisplaySurface;
  208. }
  209. if (Object.keys(video).length === 0) {
  210. video = true;
  211. }
  212. const constraints = {
  213. video,
  214. audio,
  215. ...constraintOpts,
  216. cursor: 'always'
  217. };
  218. logger.info('Using getDisplayMedia for screen sharing', constraints);
  219. getDisplayMedia(constraints)
  220. .then(stream => {
  221. this.setContentHint(stream);
  222. // Apply min fps constraints to the track so that 0Hz mode doesn't kick in.
  223. // https://bugs.chromium.org/p/webrtc/issues/detail?id=15539
  224. if (browser.isChromiumBased()) {
  225. const track = stream.getVideoTracks()[0];
  226. let minFps = SS_DEFAULT_FRAME_RATE;
  227. if (typeof desktopSharingFrameRate?.min === 'number' && desktopSharingFrameRate.min > 0) {
  228. minFps = desktopSharingFrameRate.min;
  229. }
  230. const contraints = {
  231. frameRate: {
  232. min: minFps
  233. }
  234. };
  235. try {
  236. track.applyConstraints(contraints);
  237. } catch (err) {
  238. logger.warn(`Min fps=${minFps} constraint could not be applied on the desktop track,`
  239. + `${err.message}`);
  240. }
  241. }
  242. callback({
  243. stream,
  244. sourceId: stream.id
  245. });
  246. })
  247. .catch(error => {
  248. const errorDetails = {
  249. errorName: error && error.name,
  250. errorMsg: error && error.message,
  251. errorStack: error && error.stack
  252. };
  253. logger.error('getDisplayMedia error', JSON.stringify(constraints), JSON.stringify(errorDetails));
  254. if (errorDetails.errorMsg && errorDetails.errorMsg.indexOf('denied by system') !== -1) {
  255. // On Chrome this is the only thing different between error returned when user cancels
  256. // and when no permission was given on the OS level.
  257. errorCallback(new JitsiTrackError(JitsiTrackErrors.PERMISSION_DENIED));
  258. return;
  259. }
  260. errorCallback(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_USER_CANCELED));
  261. });
  262. },
  263. /**
  264. * Obtains a screen capture stream using getDisplayMedia.
  265. *
  266. * @param callback - The success callback.
  267. * @param errorCallback - The error callback.
  268. */
  269. obtainScreenFromGetDisplayMediaRN(callback, errorCallback) {
  270. logger.info('Using getDisplayMedia for screen sharing');
  271. navigator.mediaDevices.getDisplayMedia({ video: true })
  272. .then(stream => {
  273. this.setContentHint(stream);
  274. callback({
  275. stream,
  276. sourceId: stream.id });
  277. })
  278. .catch(() => {
  279. errorCallback(new JitsiTrackError(JitsiTrackErrors
  280. .SCREENSHARING_USER_CANCELED));
  281. });
  282. },
  283. /** Sets the contentHint on the transmitted MediaStreamTrack to indicate charaterstics in the video stream, which
  284. * informs RTCPeerConnection on how to encode the track (to prefer motion or individual frame detail).
  285. *
  286. * @param {MediaStream} stream - The captured desktop stream.
  287. * @returns {void}
  288. */
  289. setContentHint(stream) {
  290. const { desktopSharingFrameRate } = this.options;
  291. const desktopTrack = stream.getVideoTracks()[0];
  292. // Set contentHint on the desktop track based on the fps requested.
  293. if ('contentHint' in desktopTrack) {
  294. desktopTrack.contentHint = desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE ? 'motion' : 'detail';
  295. } else {
  296. logger.warn('MediaStreamTrack contentHint attribute not supported');
  297. }
  298. },
  299. /**
  300. * Sets the max frame rate to be used for a desktop track capture.
  301. *
  302. * @param {number} maxFps capture frame rate to be used for desktop tracks.
  303. * @returns {void}
  304. */
  305. setDesktopSharingFrameRate(maxFps) {
  306. logger.info(`Setting the desktop capture rate to ${maxFps}`);
  307. this.options.desktopSharingFrameRate = {
  308. min: SS_DEFAULT_FRAME_RATE,
  309. max: maxFps
  310. };
  311. }
  312. };
  313. export default ScreenObtainer;