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

ScreenObtainer.js 11KB

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