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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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.isNWJS()) {
  42. return (onSuccess, onFailure) => {
  43. window.JitsiMeetNW.obtainDesktopStream(
  44. onSuccess,
  45. (error, constraints) => {
  46. let jitsiError;
  47. // FIXME:
  48. // This is very very dirty fix for recognising that the
  49. // user have clicked the cancel button from the Desktop
  50. // sharing pick window. The proper solution would be to
  51. // detect this in the NWJS application by checking the
  52. // streamId === "". Even better solution would be to
  53. // stop calling GUM from the NWJS app and just pass the
  54. // streamId to lib-jitsi-meet. This way the desktop
  55. // sharing implementation for NWJS and chrome extension
  56. // will be the same and lib-jitsi-meet will be able to
  57. // control the constraints, check the streamId, etc.
  58. //
  59. // I cannot find documentation about "InvalidStateError"
  60. // but this is what we are receiving from GUM when the
  61. // streamId for the desktop sharing is "".
  62. if (error && error.name === 'InvalidStateError') {
  63. jitsiError = new JitsiTrackError(
  64. JitsiTrackErrors.SCREENSHARING_USER_CANCELED
  65. );
  66. } else {
  67. jitsiError = new JitsiTrackError(
  68. error, constraints, [ 'desktop' ]);
  69. }
  70. (typeof onFailure === 'function')
  71. && onFailure(jitsiError);
  72. });
  73. };
  74. } else if (browser.isElectron()) {
  75. return this.obtainScreenOnElectron;
  76. } else if (browser.isReactNative() && browser.supportsGetDisplayMedia()) {
  77. return this.obtainScreenFromGetDisplayMediaRN;
  78. } else if (browser.supportsGetDisplayMedia()) {
  79. return this.obtainScreenFromGetDisplayMedia;
  80. }
  81. logger.log('Screen sharing not supported on ', browser.getName());
  82. return null;
  83. },
  84. /**
  85. * Gets the appropriate constraints for audio sharing.
  86. *
  87. * @returns {Object|boolean}
  88. */
  89. _getAudioConstraints() {
  90. const { audioQuality } = this.options;
  91. const audio = audioQuality?.stereo ? {
  92. autoGainControl: false,
  93. channelCount: 2,
  94. echoCancellation: false,
  95. noiseSuppression: false
  96. } : true;
  97. return audio;
  98. },
  99. /**
  100. * Checks whether obtaining a screen capture is supported in the current
  101. * environment.
  102. * @returns {boolean}
  103. */
  104. isSupported() {
  105. return this.obtainStream !== null;
  106. },
  107. /**
  108. * Obtains a screen capture stream on Electron.
  109. *
  110. * @param onSuccess - Success callback.
  111. * @param onFailure - Failure callback.
  112. * @param {Object} options - Optional parameters.
  113. */
  114. obtainScreenOnElectron(onSuccess, onFailure, options = {}) {
  115. if (window.JitsiMeetScreenObtainer && window.JitsiMeetScreenObtainer.openDesktopPicker) {
  116. const { desktopSharingFrameRate, desktopSharingResolution, desktopSharingSources } = this.options;
  117. window.JitsiMeetScreenObtainer.openDesktopPicker(
  118. {
  119. desktopSharingSources:
  120. options.desktopSharingSources || desktopSharingSources || [ 'screen', 'window' ]
  121. },
  122. (streamId, streamType, screenShareAudio = false) => {
  123. if (streamId) {
  124. let audioConstraints = false;
  125. if (screenShareAudio) {
  126. audioConstraints = {};
  127. const optionalConstraints = this._getAudioConstraints();
  128. if (typeof optionalConstraints !== 'boolean') {
  129. audioConstraints = {
  130. optional: optionalConstraints
  131. };
  132. }
  133. // Audio screen sharing for electron only works for screen type devices.
  134. // i.e. when the user shares the whole desktop.
  135. // Note. The documentation specifies that chromeMediaSourceId should not be present
  136. // which, in the case a users has multiple monitors, leads to them being shared all
  137. // at once. However we tested with chromeMediaSourceId present and it seems to be
  138. // working properly.
  139. if (streamType === 'screen') {
  140. audioConstraints.mandatory = {
  141. chromeMediaSource: 'desktop'
  142. };
  143. }
  144. }
  145. const constraints = {
  146. audio: audioConstraints,
  147. video: {
  148. mandatory: {
  149. chromeMediaSource: 'desktop',
  150. chromeMediaSourceId: streamId,
  151. minFrameRate: desktopSharingFrameRate?.min ?? SS_DEFAULT_FRAME_RATE,
  152. maxFrameRate: desktopSharingFrameRate?.max ?? SS_DEFAULT_FRAME_RATE,
  153. minWidth: desktopSharingResolution?.width?.min,
  154. minHeight: desktopSharingResolution?.height?.min,
  155. maxWidth: desktopSharingResolution?.width?.max ?? window.screen.width,
  156. maxHeight: desktopSharingResolution?.height?.max ?? window.screen.height
  157. }
  158. }
  159. };
  160. // We have to use the old API on Electron to get a desktop stream.
  161. navigator.mediaDevices.getUserMedia(constraints)
  162. .then(stream => {
  163. this.setContentHint(stream);
  164. onSuccess({
  165. stream,
  166. sourceId: streamId,
  167. sourceType: streamType
  168. });
  169. })
  170. .catch(err => onFailure(err));
  171. } else {
  172. // As noted in Chrome Desktop Capture API:
  173. // If user didn't select any source (i.e. canceled the prompt)
  174. // then the callback is called with an empty streamId.
  175. onFailure(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_USER_CANCELED));
  176. }
  177. },
  178. err => onFailure(new JitsiTrackError(
  179. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_ERROR,
  180. err
  181. ))
  182. );
  183. } else {
  184. onFailure(new JitsiTrackError(JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_NOT_FOUND));
  185. }
  186. },
  187. /**
  188. * Obtains a screen capture stream using getDisplayMedia.
  189. *
  190. * @param callback - The success callback.
  191. * @param errorCallback - The error callback.
  192. */
  193. obtainScreenFromGetDisplayMedia(callback, errorCallback) {
  194. let getDisplayMedia;
  195. if (navigator.getDisplayMedia) {
  196. getDisplayMedia = navigator.getDisplayMedia.bind(navigator);
  197. } else {
  198. // eslint-disable-next-line max-len
  199. getDisplayMedia = navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);
  200. }
  201. const audio = this._getAudioConstraints();
  202. let video = {};
  203. const { desktopSharingFrameRate } = this.options;
  204. if (typeof desktopSharingFrameRate === 'object') {
  205. video.frameRate = desktopSharingFrameRate;
  206. }
  207. // At the time of this writing 'min' constraint for fps is not supported by getDisplayMedia on any of the
  208. // browsers. getDisplayMedia will fail with an error "invalid constraints" in this case.
  209. video.frameRate && delete video.frameRate.min;
  210. if (browser.isChromiumBased()) {
  211. // Allow users to seamlessly switch which tab they are sharing without having to select the tab again.
  212. browser.isVersionGreaterThan(106) && (video.surfaceSwitching = 'include');
  213. // Set bogus resolution constraints to work around
  214. // https://bugs.chromium.org/p/chromium/issues/detail?id=1056311 for low fps screenshare. Capturing SS at
  215. // very high resolutions restricts the framerate. Therefore, skip this hack when capture fps > 5 fps.
  216. if (!(desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE)) {
  217. video.height = 99999;
  218. video.width = 99999;
  219. }
  220. }
  221. if (Object.keys(video).length === 0) {
  222. video = true;
  223. }
  224. const constraints = {
  225. video,
  226. audio,
  227. cursor: 'always'
  228. };
  229. logger.info('Using getDisplayMedia for screen sharing', constraints);
  230. getDisplayMedia(constraints)
  231. .then(stream => {
  232. this.setContentHint(stream);
  233. callback({
  234. stream,
  235. sourceId: stream.id
  236. });
  237. })
  238. .catch(error => {
  239. const errorDetails = {
  240. errorName: error && error.name,
  241. errorMsg: error && error.message,
  242. errorStack: error && error.stack
  243. };
  244. logger.error('getDisplayMedia error', constraints, errorDetails);
  245. if (errorDetails.errorMsg && errorDetails.errorMsg.indexOf('denied by system') !== -1) {
  246. // On Chrome this is the only thing different between error returned when user cancels
  247. // and when no permission was given on the OS level.
  248. errorCallback(new JitsiTrackError(JitsiTrackErrors.PERMISSION_DENIED));
  249. return;
  250. }
  251. errorCallback(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_USER_CANCELED));
  252. });
  253. },
  254. /**
  255. * Obtains a screen capture stream using getDisplayMedia.
  256. *
  257. * @param callback - The success callback.
  258. * @param errorCallback - The error callback.
  259. */
  260. obtainScreenFromGetDisplayMediaRN(callback, errorCallback) {
  261. logger.info('Using getDisplayMedia for screen sharing');
  262. navigator.mediaDevices.getDisplayMedia({ video: true })
  263. .then(stream => {
  264. this.setContentHint(stream);
  265. callback({
  266. stream,
  267. sourceId: stream.id });
  268. })
  269. .catch(() => {
  270. errorCallback(new JitsiTrackError(JitsiTrackErrors
  271. .SCREENSHARING_USER_CANCELED));
  272. });
  273. },
  274. /** Sets the contentHint on the transmitted MediaStreamTrack to indicate charaterstics in the video stream, which
  275. * informs RTCPeerConnection on how to encode the track (to prefer motion or individual frame detail).
  276. *
  277. * @param {MediaStream} stream - The captured desktop stream.
  278. * @returns {void}
  279. */
  280. setContentHint(stream) {
  281. const { desktopSharingFrameRate } = this.options;
  282. const desktopTrack = stream.getVideoTracks()[0];
  283. // Set contentHint on the desktop track based on the fps requested.
  284. if ('contentHint' in desktopTrack) {
  285. desktopTrack.contentHint = desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE ? 'motion' : 'detail';
  286. } else {
  287. logger.warn('MediaStreamTrack contentHint attribute not supported');
  288. }
  289. },
  290. /**
  291. * Sets the max frame rate to be used for a desktop track capture.
  292. *
  293. * @param {number} maxFps capture frame rate to be used for desktop tracks.
  294. * @returns {void}
  295. */
  296. setDesktopSharingFrameRate(maxFps) {
  297. logger.info(`Setting the desktop capture rate to ${maxFps}`);
  298. this.options.desktopSharingFrameRate = {
  299. min: SS_DEFAULT_FRAME_RATE,
  300. max: maxFps
  301. };
  302. }
  303. };
  304. export default ScreenObtainer;