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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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, 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. maxWidth: window.screen.width,
  154. maxHeight: window.screen.height
  155. }
  156. }
  157. };
  158. // We have to use the old API on Electron to get a desktop stream.
  159. navigator.mediaDevices.getUserMedia(constraints)
  160. .then(stream => onSuccess({
  161. stream,
  162. sourceId: streamId,
  163. sourceType: streamType
  164. }), onFailure);
  165. } else {
  166. // As noted in Chrome Desktop Capture API:
  167. // If user didn't select any source (i.e. canceled the prompt)
  168. // then the callback is called with an empty streamId.
  169. onFailure(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_USER_CANCELED));
  170. }
  171. },
  172. err => onFailure(new JitsiTrackError(
  173. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_ERROR,
  174. err
  175. ))
  176. );
  177. } else {
  178. onFailure(new JitsiTrackError(JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_NOT_FOUND));
  179. }
  180. },
  181. /**
  182. * Obtains a screen capture stream using getDisplayMedia.
  183. *
  184. * @param callback - The success callback.
  185. * @param errorCallback - The error callback.
  186. */
  187. obtainScreenFromGetDisplayMedia(callback, errorCallback) {
  188. let getDisplayMedia;
  189. if (navigator.getDisplayMedia) {
  190. getDisplayMedia = navigator.getDisplayMedia.bind(navigator);
  191. } else {
  192. // eslint-disable-next-line max-len
  193. getDisplayMedia = navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);
  194. }
  195. const audio = this._getAudioConstraints();
  196. let video = {};
  197. const { desktopSharingFrameRate } = this.options;
  198. if (typeof desktopSharingFrameRate === 'object') {
  199. video.frameRate = desktopSharingFrameRate;
  200. }
  201. // At the time of this writing 'min' constraint for fps is not supported by getDisplayMedia on any of the
  202. // browsers. getDisplayMedia will fail with an error "invalid constraints" in this case.
  203. video.frameRate && delete video.frameRate.min;
  204. if (browser.isChromiumBased()) {
  205. // Allow users to seamlessly switch which tab they are sharing without having to select the tab again.
  206. browser.isVersionGreaterThan(106) && (video.surfaceSwitching = 'include');
  207. // Set bogus resolution constraints to work around
  208. // https://bugs.chromium.org/p/chromium/issues/detail?id=1056311 for low fps screenshare. Capturing SS at
  209. // very high resolutions restricts the framerate. Therefore, skip this hack when capture fps > 5 fps.
  210. if (desktopSharingFrameRate?.max <= SS_DEFAULT_FRAME_RATE) {
  211. video.height = 99999;
  212. video.width = 99999;
  213. }
  214. }
  215. if (Object.keys(video).length === 0) {
  216. video = true;
  217. }
  218. const constraints = {
  219. video,
  220. audio,
  221. cursor: 'always'
  222. };
  223. logger.info('Using getDisplayMedia for screen sharing', constraints);
  224. getDisplayMedia(constraints)
  225. .then(stream => {
  226. callback({
  227. stream,
  228. sourceId: stream.id
  229. });
  230. })
  231. .catch(error => {
  232. const errorDetails = {
  233. errorName: error && error.name,
  234. errorMsg: error && error.message,
  235. errorStack: error && error.stack
  236. };
  237. logger.error('getDisplayMedia error', constraints, errorDetails);
  238. if (errorDetails.errorMsg && errorDetails.errorMsg.indexOf('denied by system') !== -1) {
  239. // On Chrome this is the only thing different between error returned when user cancels
  240. // and when no permission was given on the OS level.
  241. errorCallback(new JitsiTrackError(JitsiTrackErrors.PERMISSION_DENIED));
  242. return;
  243. }
  244. errorCallback(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_USER_CANCELED));
  245. });
  246. },
  247. /**
  248. * Obtains a screen capture stream using getDisplayMedia.
  249. *
  250. * @param callback - The success callback.
  251. * @param errorCallback - The error callback.
  252. */
  253. obtainScreenFromGetDisplayMediaRN(callback, errorCallback) {
  254. logger.info('Using getDisplayMedia for screen sharing');
  255. navigator.mediaDevices.getDisplayMedia({ video: true })
  256. .then(stream => {
  257. callback({
  258. stream,
  259. sourceId: stream.id });
  260. })
  261. .catch(() => {
  262. errorCallback(new JitsiTrackError(JitsiTrackErrors
  263. .SCREENSHARING_USER_CANCELED));
  264. });
  265. },
  266. /**
  267. * Sets the max frame rate to be used for a desktop track capture.
  268. *
  269. * @param {number} maxFps capture frame rate to be used for desktop tracks.
  270. * @returns {void}
  271. */
  272. setDesktopSharingFrameRate(maxFps) {
  273. logger.info(`Setting the desktop capture rate to ${maxFps}`);
  274. this.options.desktopSharingFrameRate = {
  275. min: SS_DEFAULT_FRAME_RATE,
  276. max: maxFps
  277. };
  278. }
  279. };
  280. export default ScreenObtainer;