Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ScreenObtainer.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. import JitsiTrackError from '../../JitsiTrackError';
  2. import * as JitsiTrackErrors from '../../JitsiTrackErrors';
  3. import browser from '../browser';
  4. const logger = require('@jitsi/logger').getLogger('modules/RTC/ScreenObtainer');
  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.info('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. * @param {Object} options - Optional parameters.
  177. */
  178. obtainScreenFromGetDisplayMedia(callback, errorCallback, options = {}) {
  179. let getDisplayMedia;
  180. if (navigator.getDisplayMedia) {
  181. getDisplayMedia = navigator.getDisplayMedia.bind(navigator);
  182. } else {
  183. // eslint-disable-next-line max-len
  184. getDisplayMedia = navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);
  185. }
  186. const audio = this._getAudioConstraints();
  187. let video = {};
  188. const constraintOpts = {};
  189. // The options passed to this method should take precedence over the global settings.
  190. const {
  191. desktopSharingFrameRate = this.options?.desktopSharingFrameRate,
  192. resolution = this.options?.resolution,
  193. screenShareSettings = this.options?.screenShareSettings
  194. } = options;
  195. if (typeof desktopSharingFrameRate === 'object') {
  196. video.frameRate = desktopSharingFrameRate;
  197. }
  198. // At the time of this writing 'min' constraint for fps is not supported by getDisplayMedia on any of the
  199. // browsers. getDisplayMedia will fail with an error "invalid constraints" in this case.
  200. video.frameRate && delete video.frameRate.min;
  201. if (browser.isChromiumBased()) {
  202. // Show users the current tab is the preferred capture source, default: false.
  203. browser.isEngineVersionGreaterThan(93)
  204. && (constraintOpts.preferCurrentTab = screenShareSettings?.desktopPreferCurrentTab || false);
  205. // Allow users to select system audio, default: include.
  206. browser.isEngineVersionGreaterThan(104)
  207. && (constraintOpts.systemAudio = screenShareSettings?.desktopSystemAudio || 'include');
  208. // Allow users to seamlessly switch which tab they are sharing without having to select the tab again.
  209. browser.isEngineVersionGreaterThan(106)
  210. && (constraintOpts.surfaceSwitching = screenShareSettings?.desktopSurfaceSwitching || 'include');
  211. // Allow a user to be shown a preference for what screen is to be captured, default: unset.
  212. browser.isEngineVersionGreaterThan(106) && screenShareSettings?.desktopDisplaySurface
  213. && (video.displaySurface = screenShareSettings?.desktopDisplaySurface);
  214. // Allow users to select the current tab as a capture source, default: exclude.
  215. browser.isEngineVersionGreaterThan(111)
  216. && (constraintOpts.selfBrowserSurface = screenShareSettings?.desktopSelfBrowserSurface || 'exclude');
  217. // Set bogus resolution constraints to work around
  218. // https://bugs.chromium.org/p/chromium/issues/detail?id=1056311 for low fps screenshare. Capturing SS at
  219. // very high resolutions restricts the framerate. Therefore, skip this hack when capture fps > 5 fps.
  220. if (!(desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE)) {
  221. video.height = 99999;
  222. video.width = 99999;
  223. }
  224. }
  225. // Allow a user to be shown a preference for what screen is to be captured.
  226. if (browser.isSafari() && screenShareSettings?.desktopDisplaySurface) {
  227. video.displaySurface = screenShareSettings?.desktopDisplaySurface;
  228. }
  229. if (Object.keys(video).length === 0) {
  230. video = true;
  231. }
  232. const constraints = {
  233. video,
  234. audio,
  235. ...constraintOpts,
  236. cursor: 'always'
  237. };
  238. logger.info('Using getDisplayMedia for screen sharing', constraints);
  239. getDisplayMedia(constraints)
  240. .then(stream => {
  241. this.setContentHint(stream);
  242. // Apply min fps constraints to the track so that 0Hz mode doesn't kick in.
  243. // https://bugs.chromium.org/p/webrtc/issues/detail?id=15539
  244. if (browser.isChromiumBased()) {
  245. const track = stream.getVideoTracks()[0];
  246. let minFps = SS_DEFAULT_FRAME_RATE;
  247. if (typeof desktopSharingFrameRate?.min === 'number' && desktopSharingFrameRate.min > 0) {
  248. minFps = desktopSharingFrameRate.min;
  249. }
  250. const trackConstraints = {
  251. frameRate: {
  252. min: minFps
  253. }
  254. };
  255. // Set the resolution if it is specified in the options. This is currently only enabled for testing.
  256. // Note that this may result in browser crashes if the shared window is resized due to browser bugs
  257. // like https://issues.chromium.org/issues/40672396
  258. if (resolution && this.options.testing?.testMode) {
  259. trackConstraints.height = resolution;
  260. trackConstraints.width = Math.floor(resolution * 16 / 9);
  261. }
  262. try {
  263. track.applyConstraints(trackConstraints);
  264. } catch (err) {
  265. logger.warn(`Min fps=${minFps} constraint could not be applied on the desktop track,`
  266. + `${err.message}`);
  267. }
  268. }
  269. const videoTracks = stream?.getVideoTracks();
  270. const track = videoTracks?.length > 0 ? videoTracks[0] : undefined;
  271. const { deviceId } = track?.getSettings() ?? {};
  272. callback({
  273. stream,
  274. // Used by remote-control to identify the display that is currently shared.
  275. sourceId: deviceId ?? stream.id
  276. });
  277. })
  278. .catch(error => {
  279. const errorDetails = {
  280. errorCode: error.code,
  281. errorName: error.name,
  282. errorMsg: error.message,
  283. errorStack: error.stack
  284. };
  285. logger.warn('getDisplayMedia error', JSON.stringify(constraints), JSON.stringify(errorDetails));
  286. if (errorDetails.errorCode === DOMException.NOT_SUPPORTED_ERR) {
  287. // This error is thrown when an Electron client has not set a permissions handler.
  288. errorCallback(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_NOT_SUPPORTED_ERROR));
  289. } else if (errorDetails.errorMsg?.indexOf('denied by system') !== -1) {
  290. // On Chrome this is the only thing different between error returned when user cancels
  291. // and when no permission was given on the OS level.
  292. errorCallback(new JitsiTrackError(JitsiTrackErrors.PERMISSION_DENIED));
  293. } else if (errorDetails.errorMsg === 'NotReadableError') {
  294. // This can happen under some weird conditions:
  295. // - https://issues.chromium.org/issues/369103607
  296. // - https://issues.chromium.org/issues/353555347
  297. errorCallback(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_GENERIC_ERROR));
  298. } else {
  299. errorCallback(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_USER_CANCELED));
  300. }
  301. });
  302. },
  303. /**
  304. * Obtains a screen capture stream using getDisplayMedia.
  305. *
  306. * @param callback - The success callback.
  307. * @param errorCallback - The error callback.
  308. */
  309. obtainScreenFromGetDisplayMediaRN(callback, errorCallback) {
  310. logger.info('Using getDisplayMedia for screen sharing');
  311. navigator.mediaDevices.getDisplayMedia({ video: true })
  312. .then(stream => {
  313. this.setContentHint(stream);
  314. callback({
  315. stream,
  316. sourceId: stream.id });
  317. })
  318. .catch(() => {
  319. errorCallback(new JitsiTrackError(JitsiTrackErrors
  320. .SCREENSHARING_USER_CANCELED));
  321. });
  322. },
  323. /** Sets the contentHint on the transmitted MediaStreamTrack to indicate charaterstics in the video stream, which
  324. * informs RTCPeerConnection on how to encode the track (to prefer motion or individual frame detail).
  325. *
  326. * @param {MediaStream} stream - The captured desktop stream.
  327. * @returns {void}
  328. */
  329. setContentHint(stream) {
  330. const { desktopSharingFrameRate } = this.options;
  331. const desktopTrack = stream.getVideoTracks()[0];
  332. // Set contentHint on the desktop track based on the fps requested.
  333. if ('contentHint' in desktopTrack) {
  334. desktopTrack.contentHint = desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE ? 'motion' : 'detail';
  335. } else {
  336. logger.warn('MediaStreamTrack contentHint attribute not supported');
  337. }
  338. },
  339. /**
  340. * Sets the max frame rate to be used for a desktop track capture.
  341. *
  342. * @param {number} maxFps capture frame rate to be used for desktop tracks.
  343. * @returns {void}
  344. */
  345. setDesktopSharingFrameRate(maxFps) {
  346. logger.info(`Setting the desktop capture rate to ${maxFps}`);
  347. this.options.desktopSharingFrameRate = {
  348. min: SS_DEFAULT_FRAME_RATE,
  349. max: maxFps
  350. };
  351. }
  352. };
  353. export default ScreenObtainer;