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

ScreenObtainer.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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 { desktopSharingFrameRate } = this.options;
  196. const setScreenSharingResolutionConstraints = browser.isChromiumBased()
  197. && this.options?.testing?.setScreenSharingResolutionConstraints;
  198. let video = {};
  199. // Allow users to seamlessly switch which tab they are sharing without having to select the tab again.
  200. if (browser.isChromiumBased() && browser.isVersionGreaterThan(106)) {
  201. video.surfaceSwitching = 'include';
  202. }
  203. if (typeof desktopSharingFrameRate === 'object') {
  204. video.frameRate = desktopSharingFrameRate;
  205. }
  206. // Capturing the screenshare at very high resolutions restricts the framerate. Therefore, skip this hack when
  207. // the capture framerate is > 5 fps.
  208. if (setScreenSharingResolutionConstraints && !(desktopSharingFrameRate?.max > SS_DEFAULT_FRAME_RATE)) {
  209. // Set bogus resolution constraints to work around
  210. // https://bugs.chromium.org/p/chromium/issues/detail?id=1056311
  211. video.height = 99999;
  212. video.width = 99999;
  213. }
  214. const audio = this._getAudioConstraints();
  215. // At the time of this writing 'min' constraint for fps is not supported by getDisplayMedia.
  216. video.frameRate && delete video.frameRate.min;
  217. if (Object.keys(video).length === 0) {
  218. video = true;
  219. }
  220. const constraints = {
  221. video,
  222. audio,
  223. cursor: 'always'
  224. };
  225. logger.info('Using getDisplayMedia for screen sharing', constraints);
  226. getDisplayMedia(constraints)
  227. .then(stream => {
  228. callback({
  229. stream,
  230. sourceId: stream.id
  231. });
  232. })
  233. .catch(error => {
  234. const errorDetails = {
  235. errorName: error && error.name,
  236. errorMsg: error && error.message,
  237. errorStack: error && error.stack
  238. };
  239. logger.error('getDisplayMedia error', constraints, errorDetails);
  240. if (errorDetails.errorMsg && errorDetails.errorMsg.indexOf('denied by system') !== -1) {
  241. // On Chrome this is the only thing different between error returned when user cancels
  242. // and when no permission was given on the OS level.
  243. errorCallback(new JitsiTrackError(JitsiTrackErrors.PERMISSION_DENIED));
  244. return;
  245. }
  246. errorCallback(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_USER_CANCELED));
  247. });
  248. },
  249. /**
  250. * Obtains a screen capture stream using getDisplayMedia.
  251. *
  252. * @param callback - The success callback.
  253. * @param errorCallback - The error callback.
  254. */
  255. obtainScreenFromGetDisplayMediaRN(callback, errorCallback) {
  256. logger.info('Using getDisplayMedia for screen sharing');
  257. navigator.mediaDevices.getDisplayMedia({ video: true })
  258. .then(stream => {
  259. callback({
  260. stream,
  261. sourceId: stream.id });
  262. })
  263. .catch(() => {
  264. errorCallback(new JitsiTrackError(JitsiTrackErrors
  265. .SCREENSHARING_USER_CANCELED));
  266. });
  267. },
  268. /**
  269. * Sets the max frame rate to be used for a desktop track capture.
  270. *
  271. * @param {number} maxFps capture frame rate to be used for desktop tracks.
  272. * @returns {void}
  273. */
  274. setDesktopSharingFrameRate(maxFps) {
  275. logger.info(`Setting the desktop capture rate to ${maxFps}`);
  276. this.options.desktopSharingFrameRate = {
  277. min: SS_DEFAULT_FRAME_RATE,
  278. max: maxFps
  279. };
  280. }
  281. };
  282. export default ScreenObtainer;