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.js 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // @flow
  2. import resemble from 'resemblejs';
  3. import 'image-capture';
  4. import './createImageBitmap';
  5. import { createScreensharingCaptureTakenEvent, sendAnalytics } from '../analytics';
  6. import { getCurrentConference } from '../base/conference';
  7. import { getRemoteParticipants } from '../base/participants';
  8. import { extractFqnFromPath } from '../dynamic-branding';
  9. import {
  10. CLEAR_INTERVAL,
  11. INTERVAL_TIMEOUT,
  12. PERCENTAGE_LOWER_BOUND,
  13. POLL_INTERVAL,
  14. SET_INTERVAL
  15. } from './constants';
  16. import { getParticipantJid } from './functions';
  17. import { processScreenshot } from './processScreenshot';
  18. import { timerWorkerScript } from './worker';
  19. declare var interfaceConfig: Object;
  20. declare var ImageCapture: any;
  21. /**
  22. * Effect that wraps {@code MediaStream} adding periodic screenshot captures.
  23. * Manipulates the original desktop stream and performs custom processing operations, if implemented.
  24. */
  25. export default class ScreenshotCaptureSummary {
  26. _state: Object;
  27. _currentCanvas: HTMLCanvasElement;
  28. _currentCanvasContext: CanvasRenderingContext2D;
  29. _handleWorkerAction: Function;
  30. _initScreenshotCapture: Function;
  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: Object) {
  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: Object) {
  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: Object) {
  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) {
  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. remoteParticipants.forEach(p => participants.push(
  157. getParticipantJid(this._state, p.id)
  158. ));
  159. this._storedImageData = imageData;
  160. processScreenshot(this._currentCanvas, {
  161. jid,
  162. jwt,
  163. sessionId,
  164. timestamp,
  165. meetingFqn,
  166. participants
  167. });
  168. }
  169. /**
  170. * Screenshot handler.
  171. *
  172. * @private
  173. * @returns {void}
  174. */
  175. async _handleScreenshot() {
  176. const imageBitmap = await this._imageCapture.grabFrame();
  177. this._currentCanvasContext.drawImage(imageBitmap, 0, 0, this._streamWidth, this._streamHeight);
  178. const imageData = this._currentCanvasContext.getImageData(0, 0, this._streamWidth, this._streamHeight);
  179. resemble(imageData)
  180. .compareTo(this._storedImageData)
  181. .setReturnEarlyThreshold(PERCENTAGE_LOWER_BOUND)
  182. .onComplete(resultData => {
  183. if (resultData.rawMisMatchPercentage > PERCENTAGE_LOWER_BOUND) {
  184. this._doProcessScreenshot(imageData);
  185. }
  186. });
  187. }
  188. }