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.

ScreenshotCaptureSummary.tsx 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import resemble from 'resemblejs';
  2. import 'image-capture';
  3. import './createImageBitmap';
  4. import { createScreensharingCaptureTakenEvent } from '../analytics/AnalyticsEvents';
  5. import { sendAnalytics } from '../analytics/functions';
  6. import { IReduxState } from '../app/types';
  7. import { getCurrentConference } from '../base/conference/functions';
  8. import { getLocalParticipant, getRemoteParticipants } from '../base/participants/functions';
  9. import { ITrack } from '../base/tracks/types';
  10. import { extractFqnFromPath } from '../dynamic-branding/functions.any';
  11. import {
  12. CLEAR_INTERVAL,
  13. INTERVAL_TIMEOUT,
  14. PERCENTAGE_LOWER_BOUND,
  15. POLL_INTERVAL,
  16. SET_INTERVAL
  17. } from './constants';
  18. // eslint-disable-next-line lines-around-comment
  19. // @ts-ignore
  20. import { processScreenshot } from './processScreenshot';
  21. import { timerWorkerScript } from './worker';
  22. declare let ImageCapture: any;
  23. /**
  24. * Effect that wraps {@code MediaStream} adding periodic screenshot captures.
  25. * Manipulates the original desktop stream and performs custom processing operations, if implemented.
  26. */
  27. export default class ScreenshotCaptureSummary {
  28. _state: IReduxState;
  29. _currentCanvas: HTMLCanvasElement;
  30. _currentCanvasContext: CanvasRenderingContext2D | null;
  31. _initializedRegion: boolean;
  32. _imageCapture: any;
  33. _streamWorker: Worker;
  34. _streamHeight: any;
  35. _streamWidth: any;
  36. _storedImageData?: ImageData;
  37. /**
  38. * Initializes a new {@code ScreenshotCaptureEffect} instance.
  39. *
  40. * @param {Object} state - The redux state.
  41. */
  42. constructor(state: IReduxState) {
  43. this._state = state;
  44. this._currentCanvas = document.createElement('canvas');
  45. this._currentCanvasContext = this._currentCanvas.getContext('2d');
  46. // Bind handlers such that they access the same instance.
  47. this._handleWorkerAction = this._handleWorkerAction.bind(this);
  48. this._initScreenshotCapture = this._initScreenshotCapture.bind(this);
  49. this._streamWorker = new Worker(timerWorkerScript, { name: 'Screenshot capture worker' });
  50. this._streamWorker.onmessage = this._handleWorkerAction;
  51. this._initializedRegion = false;
  52. }
  53. /**
  54. * Make a call to backend for region selection.
  55. *
  56. * @returns {void}
  57. */
  58. async _initRegionSelection() {
  59. const { _screenshotHistoryRegionUrl } = this._state['features/base/config'];
  60. const conference = getCurrentConference(this._state);
  61. const sessionId = conference?.getMeetingUniqueId();
  62. const { jwt } = this._state['features/base/jwt'];
  63. if (!_screenshotHistoryRegionUrl) {
  64. return;
  65. }
  66. const headers = {
  67. ...jwt && { 'Authorization': `Bearer ${jwt}` }
  68. };
  69. await fetch(`${_screenshotHistoryRegionUrl}/${sessionId}`, {
  70. method: 'POST',
  71. headers
  72. });
  73. this._initializedRegion = true;
  74. }
  75. /**
  76. * Starts the screenshot capture event on a loop.
  77. *
  78. * @param {Track} track - The track that contains the stream from which screenshots are to be sent.
  79. * @returns {Promise} - Promise that resolves once effect has started or rejects if the
  80. * videoType parameter is not desktop.
  81. */
  82. async start(track: ITrack) {
  83. const { videoType } = track;
  84. const stream = track.getOriginalStream();
  85. if (videoType !== 'desktop') {
  86. return;
  87. }
  88. const desktopTrack = stream.getVideoTracks()[0];
  89. const { height, width }
  90. = desktopTrack.getSettings() ?? desktopTrack.getConstraints();
  91. this._streamHeight = height;
  92. this._streamWidth = width;
  93. this._currentCanvas.height = parseInt(height, 10);
  94. this._currentCanvas.width = parseInt(width, 10);
  95. this._imageCapture = new ImageCapture(desktopTrack);
  96. if (!this._initializedRegion) {
  97. await this._initRegionSelection();
  98. }
  99. this._initScreenshotCapture();
  100. }
  101. /**
  102. * Stops the ongoing {@code ScreenshotCaptureEffect} by clearing the {@code Worker} interval.
  103. *
  104. * @returns {void}
  105. */
  106. stop() {
  107. this._streamWorker.postMessage({ id: CLEAR_INTERVAL });
  108. }
  109. /**
  110. * Method that is called as soon as the first frame of the video loads from stream.
  111. * The method is used to store the {@code ImageData} object from the first frames
  112. * in order to use it for future comparisons based on which we can process only certain
  113. * screenshots.
  114. *
  115. * @private
  116. * @returns {void}
  117. */
  118. async _initScreenshotCapture() {
  119. const imageBitmap = await this._imageCapture.grabFrame();
  120. this._currentCanvasContext?.drawImage(imageBitmap, 0, 0, this._streamWidth, this._streamHeight);
  121. const imageData = this._currentCanvasContext?.getImageData(0, 0, this._streamWidth, this._streamHeight);
  122. this._storedImageData = imageData;
  123. this._streamWorker.postMessage({
  124. id: SET_INTERVAL,
  125. timeMs: POLL_INTERVAL
  126. });
  127. }
  128. /**
  129. * Handler of the {@code EventHandler} message that calls the appropriate method based on the parameter's id.
  130. *
  131. * @private
  132. * @param {EventHandler} message - Message received from the Worker.
  133. * @returns {void}
  134. */
  135. _handleWorkerAction(message: { data: { id: number; }; }) {
  136. return message.data.id === INTERVAL_TIMEOUT && this._handleScreenshot();
  137. }
  138. /**
  139. * Method that processes the screenshot.
  140. *
  141. * @private
  142. * @param {ImageData} imageData - The image data of the new screenshot.
  143. * @returns {void}
  144. */
  145. _doProcessScreenshot(imageData?: ImageData) {
  146. sendAnalytics(createScreensharingCaptureTakenEvent());
  147. const conference = getCurrentConference(this._state);
  148. const sessionId = conference?.getMeetingUniqueId();
  149. const { connection } = this._state['features/base/connection'];
  150. const jid = connection?.getJid();
  151. const timestamp = Date.now();
  152. const { jwt } = this._state['features/base/jwt'];
  153. const meetingFqn = extractFqnFromPath();
  154. const remoteParticipants = getRemoteParticipants(this._state);
  155. const participants = [];
  156. participants.push(getLocalParticipant(this._state)?.id);
  157. remoteParticipants.forEach(p => participants.push(p.id));
  158. this._storedImageData = imageData;
  159. processScreenshot(this._currentCanvas, {
  160. jid,
  161. jwt,
  162. sessionId,
  163. timestamp,
  164. meetingFqn,
  165. participants
  166. });
  167. }
  168. /**
  169. * Screenshot handler.
  170. *
  171. * @private
  172. * @returns {void}
  173. */
  174. async _handleScreenshot() {
  175. const imageBitmap = await this._imageCapture.grabFrame();
  176. this._currentCanvasContext?.drawImage(imageBitmap, 0, 0, this._streamWidth, this._streamHeight);
  177. const imageData = this._currentCanvasContext?.getImageData(0, 0, this._streamWidth, this._streamHeight);
  178. resemble(imageData ?? '')
  179. .compareTo(this._storedImageData ?? '')
  180. .setReturnEarlyThreshold(PERCENTAGE_LOWER_BOUND)
  181. .onComplete(resultData => {
  182. if (resultData.rawMisMatchPercentage > PERCENTAGE_LOWER_BOUND) {
  183. this._doProcessScreenshot(imageData);
  184. }
  185. });
  186. }
  187. }