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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. this._electronSkipDisplayMedia = false;
  33. },
  34. /**
  35. * Returns a method which will be used to obtain the screen sharing stream
  36. * (based on the browser type).
  37. *
  38. * @returns {Function}
  39. * @private
  40. */
  41. _createObtainStreamMethod() {
  42. const supportsGetDisplayMedia = browser.supportsGetDisplayMedia();
  43. if (browser.isElectron()) {
  44. return this.obtainScreenOnElectron;
  45. } else if (browser.isReactNative() && supportsGetDisplayMedia) {
  46. return this.obtainScreenFromGetDisplayMediaRN;
  47. } else if (supportsGetDisplayMedia) {
  48. return this.obtainScreenFromGetDisplayMedia;
  49. }
  50. logger.log('Screen sharing not supported on ', browser.getName());
  51. return null;
  52. },
  53. /**
  54. * Gets the appropriate constraints for audio sharing.
  55. *
  56. * @returns {Object|boolean}
  57. */
  58. _getAudioConstraints() {
  59. const { audioQuality } = this.options;
  60. const audio = audioQuality?.stereo ? {
  61. autoGainControl: false,
  62. channelCount: 2,
  63. echoCancellation: false,
  64. noiseSuppression: false
  65. } : true;
  66. return audio;
  67. },
  68. /**
  69. * Checks whether obtaining a screen capture is supported in the current
  70. * environment.
  71. * @returns {boolean}
  72. */
  73. isSupported() {
  74. return this.obtainStream !== null;
  75. },
  76. /**
  77. * Obtains a screen capture stream on Electron.
  78. *
  79. * @param onSuccess - Success callback.
  80. * @param onFailure - Failure callback.
  81. * @param {Object} options - Optional parameters.
  82. */
  83. obtainScreenOnElectron(onSuccess, onFailure, options = {}) {
  84. if (!this._electronSkipDisplayMedia) {
  85. // Fall-back to the old API in case of not supported error. This can happen if
  86. // an old Electron SDK is used with a new Jitsi Meet + lib-jitsi-meet version.
  87. this.obtainScreenFromGetDisplayMedia(onSuccess, err => {
  88. if (err.name === JitsiTrackErrors.SCREENSHARING_NOT_SUPPORTED_ERROR) {
  89. // Make sure we don't recurse infinitely.
  90. this._electronSkipDisplayMedia = true;
  91. this.obtainScreenOnElectron(onSuccess, onFailure);
  92. } else {
  93. onFailure(err);
  94. }
  95. });
  96. return;
  97. }
  98. // TODO: legacy flow, remove after the Electron SDK supporting gDM has been out for a while.
  99. if (typeof window.JitsiMeetScreenObtainer?.openDesktopPicker === 'function') {
  100. const { desktopSharingFrameRate, desktopSharingResolution, desktopSharingSources } = this.options;
  101. window.JitsiMeetScreenObtainer.openDesktopPicker(
  102. {
  103. desktopSharingSources:
  104. options.desktopSharingSources || desktopSharingSources || [ 'screen', 'window' ]
  105. },
  106. (streamId, streamType, screenShareAudio = false) => {
  107. if (streamId) {
  108. let audioConstraints = false;
  109. if (screenShareAudio) {
  110. audioConstraints = {};
  111. const optionalConstraints = this._getAudioConstraints();
  112. if (typeof optionalConstraints !== 'boolean') {
  113. audioConstraints = {
  114. optional: optionalConstraints
  115. };
  116. }
  117. // Audio screen sharing for electron only works for screen type devices.
  118. // i.e. when the user shares the whole desktop.
  119. // Note. The documentation specifies that chromeMediaSourceId should not be present
  120. // which, in the case a users has multiple monitors, leads to them being shared all
  121. // at once. However we tested with chromeMediaSourceId present and it seems to be
  122. // working properly.
  123. if (streamType === 'screen') {
  124. audioConstraints.mandatory = {
  125. chromeMediaSource: 'desktop'
  126. };
  127. }
  128. }
  129. const constraints = {
  130. audio: audioConstraints,
  131. video: {
  132. mandatory: {
  133. chromeMediaSource: 'desktop',
  134. chromeMediaSourceId: streamId,
  135. minFrameRate: desktopSharingFrameRate?.min ?? SS_DEFAULT_FRAME_RATE,
  136. maxFrameRate: desktopSharingFrameRate?.max ?? SS_DEFAULT_FRAME_RATE,
  137. minWidth: desktopSharingResolution?.width?.min,
  138. minHeight: desktopSharingResolution?.height?.min,
  139. maxWidth: desktopSharingResolution?.width?.max ?? window.screen.width,
  140. maxHeight: desktopSharingResolution?.height?.max ?? window.screen.height
  141. }
  142. }
  143. };
  144. // We have to use the old API on Electron to get a desktop stream.
  145. navigator.mediaDevices.getUserMedia(constraints)
  146. .then(stream => {
  147. this.setContentHint(stream);
  148. onSuccess({
  149. stream,
  150. sourceId: streamId,
  151. sourceType: streamType
  152. });
  153. })
  154. .catch(err => onFailure(err));
  155. } else {
  156. // As noted in Chrome Desktop Capture API:
  157. // If user didn't select any source (i.e. canceled the prompt)
  158. // then the callback is called with an empty streamId.
  159. onFailure(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_USER_CANCELED));
  160. }
  161. },
  162. err => onFailure(new JitsiTrackError(
  163. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_ERROR,
  164. err
  165. ))
  166. );
  167. } else {
  168. onFailure(new JitsiTrackError(JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_NOT_FOUND));
  169. }
  170. },
  171. /**
  172. * Obtains a screen capture stream using getDisplayMedia.
  173. *
  174. * @param callback - The success callback.
  175. * @param errorCallback - The error callback.
  176. */
  177. obtainScreenFromGetDisplayMedia(callback, errorCallback) {
  178. let getDisplayMedia;
  179. if (navigator.getDisplayMedia) {
  180. getDisplayMedia = navigator.getDisplayMedia.bind(navigator);
  181. } else {
  182. // eslint-disable-next-line max-len
  183. getDisplayMedia = navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);
  184. }
  185. const audio = this._getAudioConstraints();
  186. let video = {};
  187. const constraintOpts = {};
  188. const {
  189. desktopSharingFrameRate,
  190. screenShareSettings
  191. } = this.options;
  192. if (typeof desktopSharingFrameRate === 'object') {
  193. video.frameRate = desktopSharingFrameRate;
  194. }
  195. // At the time of this writing 'min' constraint for fps is not supported by getDisplayMedia on any of the
  196. // browsers. getDisplayMedia will fail with an error "invalid constraints" in this case.
  197. video.frameRate && delete video.frameRate.min;
  198. if (browser.isChromiumBased()) {
  199. // Show users the current tab is the preferred capture source, default: false.
  200. browser.isEngineVersionGreaterThan(93)
  201. && (constraintOpts.preferCurrentTab = screenShareSettings?.desktopPreferCurrentTab || false);
  202. // Allow users to select system audio, default: include.
  203. browser.isEngineVersionGreaterThan(104)
  204. && (constraintOpts.systemAudio = screenShareSettings?.desktopSystemAudio || 'include');
  205. // Allow users to seamlessly switch which tab they are sharing without having to select the tab again.
  206. browser.isEngineVersionGreaterThan(106)
  207. && (constraintOpts.surfaceSwitching = screenShareSettings?.desktopSurfaceSwitching || 'include');
  208. // Allow a user to be shown a preference for what screen is to be captured, default: unset.
  209. browser.isEngineVersionGreaterThan(106) && screenShareSettings?.desktopDisplaySurface
  210. && (video.displaySurface = screenShareSettings?.desktopDisplaySurface);
  211. // Allow users to select the current tab as a capture source, default: exclude.
  212. browser.isEngineVersionGreaterThan(111)
  213. && (constraintOpts.selfBrowserSurface = screenShareSettings?.desktopSelfBrowserSurface || 'exclude');
  214. // Set bogus resolution constraints to work around
  215. // https://bugs.chromium.org/p/chromium/issues/detail?id=1056311 for low fps screenshare. Capturing SS at
  216. // very high resolutions restricts the framerate. Therefore, skip this hack when capture fps > 5 fps.
  217. if (!(desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE)) {
  218. video.height = 99999;
  219. video.width = 99999;
  220. }
  221. }
  222. // Allow a user to be shown a preference for what screen is to be captured.
  223. if (browser.isSafari() && screenShareSettings?.desktopDisplaySurface) {
  224. video.displaySurface = screenShareSettings?.desktopDisplaySurface;
  225. }
  226. if (Object.keys(video).length === 0) {
  227. video = true;
  228. }
  229. const constraints = {
  230. video,
  231. audio,
  232. ...constraintOpts,
  233. cursor: 'always'
  234. };
  235. logger.info('Using getDisplayMedia for screen sharing', constraints);
  236. getDisplayMedia(constraints)
  237. .then(stream => {
  238. this.setContentHint(stream);
  239. // Apply min fps constraints to the track so that 0Hz mode doesn't kick in.
  240. // https://bugs.chromium.org/p/webrtc/issues/detail?id=15539
  241. if (browser.isChromiumBased()) {
  242. const track = stream.getVideoTracks()[0];
  243. let minFps = SS_DEFAULT_FRAME_RATE;
  244. if (typeof desktopSharingFrameRate?.min === 'number' && desktopSharingFrameRate.min > 0) {
  245. minFps = desktopSharingFrameRate.min;
  246. }
  247. const contraints = {
  248. frameRate: {
  249. min: minFps
  250. }
  251. };
  252. try {
  253. track.applyConstraints(contraints);
  254. } catch (err) {
  255. logger.warn(`Min fps=${minFps} constraint could not be applied on the desktop track,`
  256. + `${err.message}`);
  257. }
  258. }
  259. callback({
  260. stream,
  261. sourceId: stream.id
  262. });
  263. })
  264. .catch(error => {
  265. const errorDetails = {
  266. errorCode: error.code,
  267. errorName: error.name,
  268. errorMsg: error.message,
  269. errorStack: error.stack
  270. };
  271. logger.warn('getDisplayMedia error', JSON.stringify(constraints), JSON.stringify(errorDetails));
  272. if (errorDetails.code === DOMException.NOT_SUPPORTED_ERR) {
  273. // This error is thrown when an Electron client has not set a permissions handler.
  274. errorCallback(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_NOT_SUPPORTED_ERROR));
  275. } else if (errorDetails.errorMsg?.indexOf('denied by system') !== -1) {
  276. // On Chrome this is the only thing different between error returned when user cancels
  277. // and when no permission was given on the OS level.
  278. errorCallback(new JitsiTrackError(JitsiTrackErrors.PERMISSION_DENIED));
  279. } else if (errorDetails.errorMsg === 'NotReadableError') {
  280. // This can happen under some weird conditions:
  281. // - https://issues.chromium.org/issues/369103607
  282. // - https://issues.chromium.org/issues/353555347
  283. errorCallback(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_GENERIC_ERROR));
  284. } else {
  285. errorCallback(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_USER_CANCELED));
  286. }
  287. });
  288. },
  289. /**
  290. * Obtains a screen capture stream using getDisplayMedia.
  291. *
  292. * @param callback - The success callback.
  293. * @param errorCallback - The error callback.
  294. */
  295. obtainScreenFromGetDisplayMediaRN(callback, errorCallback) {
  296. logger.info('Using getDisplayMedia for screen sharing');
  297. navigator.mediaDevices.getDisplayMedia({ video: true })
  298. .then(stream => {
  299. this.setContentHint(stream);
  300. callback({
  301. stream,
  302. sourceId: stream.id });
  303. })
  304. .catch(() => {
  305. errorCallback(new JitsiTrackError(JitsiTrackErrors
  306. .SCREENSHARING_USER_CANCELED));
  307. });
  308. },
  309. /** Sets the contentHint on the transmitted MediaStreamTrack to indicate charaterstics in the video stream, which
  310. * informs RTCPeerConnection on how to encode the track (to prefer motion or individual frame detail).
  311. *
  312. * @param {MediaStream} stream - The captured desktop stream.
  313. * @returns {void}
  314. */
  315. setContentHint(stream) {
  316. const { desktopSharingFrameRate } = this.options;
  317. const desktopTrack = stream.getVideoTracks()[0];
  318. // Set contentHint on the desktop track based on the fps requested.
  319. if ('contentHint' in desktopTrack) {
  320. desktopTrack.contentHint = desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE ? 'motion' : 'detail';
  321. } else {
  322. logger.warn('MediaStreamTrack contentHint attribute not supported');
  323. }
  324. },
  325. /**
  326. * Sets the max frame rate to be used for a desktop track capture.
  327. *
  328. * @param {number} maxFps capture frame rate to be used for desktop tracks.
  329. * @returns {void}
  330. */
  331. setDesktopSharingFrameRate(maxFps) {
  332. logger.info(`Setting the desktop capture rate to ${maxFps}`);
  333. this.options.desktopSharingFrameRate = {
  334. min: SS_DEFAULT_FRAME_RATE,
  335. max: maxFps
  336. };
  337. }
  338. };
  339. export default ScreenObtainer;