您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ScreenObtainer.js 17KB

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