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

ScreenObtainer.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. */
  113. obtainScreenOnElectron(onSuccess, onFailure) {
  114. if (window.JitsiMeetScreenObtainer && window.JitsiMeetScreenObtainer.openDesktopPicker) {
  115. const { desktopSharingFrameRate, desktopSharingSources } = this.options;
  116. window.JitsiMeetScreenObtainer.openDesktopPicker(
  117. {
  118. desktopSharingSources: desktopSharingSources || [ 'screen', 'window' ]
  119. },
  120. (streamId, streamType, screenShareAudio = false) => {
  121. if (streamId) {
  122. let audioConstraints = false;
  123. if (screenShareAudio) {
  124. audioConstraints = {};
  125. const optionalConstraints = this._getAudioConstraints();
  126. if (typeof optionalConstraints !== 'boolean') {
  127. audioConstraints = {
  128. optional: optionalConstraints
  129. };
  130. }
  131. // Audio screen sharing for electron only works for screen type devices.
  132. // i.e. when the user shares the whole desktop.
  133. // Note. The documentation specifies that chromeMediaSourceId should not be present
  134. // which, in the case a users has multiple monitors, leads to them being shared all
  135. // at once. However we tested with chromeMediaSourceId present and it seems to be
  136. // working properly.
  137. if (streamType === 'screen') {
  138. audioConstraints.mandatory = {
  139. chromeMediaSource: 'desktop'
  140. };
  141. }
  142. }
  143. const constraints = {
  144. audio: audioConstraints,
  145. video: {
  146. mandatory: {
  147. chromeMediaSource: 'desktop',
  148. chromeMediaSourceId: streamId,
  149. minFrameRate: desktopSharingFrameRate?.min ?? SS_DEFAULT_FRAME_RATE,
  150. maxFrameRate: desktopSharingFrameRate?.max ?? SS_DEFAULT_FRAME_RATE,
  151. maxWidth: window.screen.width,
  152. maxHeight: window.screen.height
  153. }
  154. }
  155. };
  156. // We have to use the old API on Electron to get a desktop stream.
  157. navigator.mediaDevices.getUserMedia(constraints)
  158. .then(stream => onSuccess({
  159. stream,
  160. sourceId: streamId,
  161. sourceType: streamType
  162. }), onFailure);
  163. } else {
  164. // As noted in Chrome Desktop Capture API:
  165. // If user didn't select any source (i.e. canceled the prompt)
  166. // then the callback is called with an empty streamId.
  167. onFailure(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_USER_CANCELED));
  168. }
  169. },
  170. err => onFailure(new JitsiTrackError(
  171. JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_ERROR,
  172. err
  173. ))
  174. );
  175. } else {
  176. onFailure(new JitsiTrackError(JitsiTrackErrors.ELECTRON_DESKTOP_PICKER_NOT_FOUND));
  177. }
  178. },
  179. /**
  180. * Obtains a screen capture stream using getDisplayMedia.
  181. *
  182. * @param callback - The success callback.
  183. * @param errorCallback - The error callback.
  184. */
  185. obtainScreenFromGetDisplayMedia(callback, errorCallback) {
  186. let getDisplayMedia;
  187. if (navigator.getDisplayMedia) {
  188. getDisplayMedia = navigator.getDisplayMedia.bind(navigator);
  189. } else {
  190. // eslint-disable-next-line max-len
  191. getDisplayMedia = navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);
  192. }
  193. const { desktopSharingFrameRate } = this.options;
  194. const video = typeof desktopSharingFrameRate === 'object' ? { frameRate: desktopSharingFrameRate } : true;
  195. const audio = this._getAudioConstraints();
  196. // At the time of this writing 'min' constraint for fps is not supported by getDisplayMedia.
  197. video.frameRate && delete video.frameRate.min;
  198. const constraints = {
  199. video,
  200. audio,
  201. cursor: 'always'
  202. };
  203. logger.info('Using getDisplayMedia for screen sharing', constraints);
  204. getDisplayMedia(constraints)
  205. .then(stream => {
  206. callback({
  207. stream,
  208. sourceId: stream.id
  209. });
  210. })
  211. .catch(error => {
  212. const errorDetails = {
  213. errorName: error && error.name,
  214. errorMsg: error && error.message,
  215. errorStack: error && error.stack
  216. };
  217. logger.error('getDisplayMedia error', constraints, errorDetails);
  218. if (errorDetails.errorMsg && errorDetails.errorMsg.indexOf('denied by system') !== -1) {
  219. // On Chrome this is the only thing different between error returned when user cancels
  220. // and when no permission was given on the OS level.
  221. errorCallback(new JitsiTrackError(JitsiTrackErrors.PERMISSION_DENIED));
  222. return;
  223. }
  224. errorCallback(new JitsiTrackError(JitsiTrackErrors.SCREENSHARING_USER_CANCELED));
  225. });
  226. },
  227. /**
  228. * Obtains a screen capture stream using getDisplayMedia.
  229. *
  230. * @param callback - The success callback.
  231. * @param errorCallback - The error callback.
  232. */
  233. obtainScreenFromGetDisplayMediaRN(callback, errorCallback) {
  234. logger.info('Using getDisplayMedia for screen sharing');
  235. navigator.mediaDevices.getDisplayMedia({ video: true })
  236. .then(stream => {
  237. callback({
  238. stream,
  239. sourceId: stream.id });
  240. })
  241. .catch(() => {
  242. errorCallback(new JitsiTrackError(JitsiTrackErrors
  243. .SCREENSHARING_USER_CANCELED));
  244. });
  245. },
  246. /**
  247. * Sets the max frame rate to be used for a desktop track capture.
  248. *
  249. * @param {number} maxFps capture frame rate to be used for desktop tracks.
  250. * @returns {void}
  251. */
  252. setDesktopSharingFrameRate(maxFps) {
  253. logger.info(`Setting the desktop capture rate to ${maxFps}`);
  254. this.options.desktopSharingFrameRate = {
  255. min: SS_DEFAULT_FRAME_RATE,
  256. max: maxFps
  257. };
  258. }
  259. };
  260. export default ScreenObtainer;