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.

actions.js 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // @flow
  2. import 'image-capture';
  3. import './createImageBitmap';
  4. import { getCurrentConference } from '../base/conference';
  5. import { getLocalParticipant, getParticipantCount } from '../base/participants';
  6. import { getLocalVideoTrack } from '../base/tracks';
  7. import { getBaseUrl } from '../base/util';
  8. import {
  9. ADD_FACE_EXPRESSION,
  10. ADD_TO_FACE_EXPRESSIONS_BUFFER,
  11. CLEAR_FACE_EXPRESSIONS_BUFFER,
  12. START_FACE_LANDMARKS_DETECTION,
  13. STOP_FACE_LANDMARKS_DETECTION,
  14. UPDATE_FACE_COORDINATES
  15. } from './actionTypes';
  16. import {
  17. DETECTION_TYPES,
  18. INIT_WORKER,
  19. WEBHOOK_SEND_TIME_INTERVAL
  20. } from './constants';
  21. import {
  22. getDetectionInterval,
  23. sendDataToWorker,
  24. sendFaceBoxToParticipants,
  25. sendFaceExpressionsWebhook
  26. } from './functions';
  27. import logger from './logger';
  28. /**
  29. * Object containing a image capture of the local track.
  30. */
  31. let imageCapture;
  32. /**
  33. * Object where the face landmarks worker is stored.
  34. */
  35. let worker;
  36. /**
  37. * The last face expression received from the worker.
  38. */
  39. let lastFaceExpression;
  40. /**
  41. * The last face expression timestamp.
  42. */
  43. let lastFaceExpressionTimestamp;
  44. /**
  45. * How many duplicate consecutive expression occurred.
  46. * If a expression that is not the same as the last one it is reset to 0.
  47. */
  48. let duplicateConsecutiveExpressions = 0;
  49. /**
  50. * Variable that keeps the interval for sending expressions to webhook.
  51. */
  52. let webhookSendInterval;
  53. /**
  54. * Variable that keeps the interval for detecting faces in a frame.
  55. */
  56. let detectionInterval;
  57. /**
  58. * Loads the worker that detects the face landmarks.
  59. *
  60. * @returns {void}
  61. */
  62. export function loadWorker() {
  63. return function(dispatch: Function, getState: Function) {
  64. if (worker) {
  65. logger.info('Worker has already been initialized');
  66. return;
  67. }
  68. if (navigator.product === 'ReactNative') {
  69. logger.warn('Unsupported environment for face recognition');
  70. return;
  71. }
  72. const baseUrl = `${getBaseUrl()}libs/`;
  73. let workerUrl = `${baseUrl}face-landmarks-worker.min.js`;
  74. const workerBlob = new Blob([ `importScripts("${workerUrl}");` ], { type: 'application/javascript' });
  75. workerUrl = window.URL.createObjectURL(workerBlob);
  76. worker = new Worker(workerUrl, { name: 'Face Recognition Worker' });
  77. worker.onmessage = function(e: Object) {
  78. const { faceExpression, faceBox } = e.data;
  79. if (faceExpression) {
  80. if (faceExpression === lastFaceExpression) {
  81. duplicateConsecutiveExpressions++;
  82. } else {
  83. if (lastFaceExpression && lastFaceExpressionTimestamp) {
  84. dispatch(addFaceExpression(
  85. lastFaceExpression,
  86. duplicateConsecutiveExpressions + 1,
  87. lastFaceExpressionTimestamp
  88. ));
  89. }
  90. lastFaceExpression = faceExpression;
  91. lastFaceExpressionTimestamp = Date.now();
  92. duplicateConsecutiveExpressions = 0;
  93. }
  94. }
  95. if (faceBox) {
  96. const state = getState();
  97. const conference = getCurrentConference(state);
  98. const localParticipant = getLocalParticipant(state);
  99. if (getParticipantCount(state) > 1) {
  100. sendFaceBoxToParticipants(conference, faceBox);
  101. }
  102. dispatch({
  103. type: UPDATE_FACE_COORDINATES,
  104. faceBox,
  105. id: localParticipant.id
  106. });
  107. }
  108. };
  109. const { faceLandmarks } = getState()['features/base/config'];
  110. const detectionTypes = [
  111. faceLandmarks?.enableFaceCentering && DETECTION_TYPES.FACE_BOX,
  112. faceLandmarks?.enableFaceExpressionsDetection && DETECTION_TYPES.FACE_EXPRESSIONS
  113. ].filter(Boolean);
  114. worker.postMessage({
  115. type: INIT_WORKER,
  116. baseUrl,
  117. detectionTypes
  118. });
  119. dispatch(startFaceLandmarksDetection());
  120. };
  121. }
  122. /**
  123. * Starts the recognition and detection of face expressions.
  124. *
  125. * @param {Track | undefined} track - Track for which to start detecting faces.
  126. * @returns {Function}
  127. */
  128. export function startFaceLandmarksDetection(track) {
  129. return async function(dispatch: Function, getState: Function) {
  130. if (!worker) {
  131. return;
  132. }
  133. const state = getState();
  134. const { recognitionActive } = state['features/face-landmarks'];
  135. if (recognitionActive) {
  136. logger.log('Face recognition already active.');
  137. return;
  138. }
  139. const localVideoTrack = track || getLocalVideoTrack(state['features/base/tracks']);
  140. if (localVideoTrack === undefined) {
  141. logger.warn('Face landmarks detection is disabled due to missing local track.');
  142. return;
  143. }
  144. const stream = localVideoTrack.jitsiTrack.getOriginalStream();
  145. dispatch({ type: START_FACE_LANDMARKS_DETECTION });
  146. logger.log('Start face recognition');
  147. const firstVideoTrack = stream.getVideoTracks()[0];
  148. const { faceLandmarks } = state['features/base/config'];
  149. imageCapture = new ImageCapture(firstVideoTrack);
  150. detectionInterval = setInterval(() => {
  151. sendDataToWorker(
  152. worker,
  153. imageCapture,
  154. faceLandmarks?.faceCenteringThreshold
  155. );
  156. }, getDetectionInterval(state));
  157. if (faceLandmarks?.enableFaceExpressionsDetection) {
  158. webhookSendInterval = setInterval(async () => {
  159. const result = await sendFaceExpressionsWebhook(getState());
  160. if (result) {
  161. dispatch(clearFaceExpressionBuffer());
  162. }
  163. }, WEBHOOK_SEND_TIME_INTERVAL);
  164. }
  165. };
  166. }
  167. /**
  168. * Stops the recognition and detection of face expressions.
  169. *
  170. * @returns {void}
  171. */
  172. export function stopFaceLandmarksDetection() {
  173. return function(dispatch: Function) {
  174. if (lastFaceExpression && lastFaceExpressionTimestamp) {
  175. dispatch(
  176. addFaceExpression(
  177. lastFaceExpression,
  178. duplicateConsecutiveExpressions + 1,
  179. lastFaceExpressionTimestamp
  180. )
  181. );
  182. }
  183. clearInterval(webhookSendInterval);
  184. clearInterval(detectionInterval);
  185. duplicateConsecutiveExpressions = 0;
  186. webhookSendInterval = null;
  187. detectionInterval = null;
  188. imageCapture = null;
  189. dispatch({ type: STOP_FACE_LANDMARKS_DETECTION });
  190. logger.log('Stop face recognition');
  191. };
  192. }
  193. /**
  194. * Adds a new face expression and its duration.
  195. *
  196. * @param {string} faceExpression - Face expression to be added.
  197. * @param {number} duration - Duration in seconds of the face expression.
  198. * @param {number} timestamp - Duration in seconds of the face expression.
  199. * @returns {Object}
  200. */
  201. function addFaceExpression(faceExpression: string, duration: number, timestamp: number) {
  202. return function(dispatch: Function, getState: Function) {
  203. const finalDuration = duration * getDetectionInterval(getState()) / 1000;
  204. dispatch({
  205. type: ADD_FACE_EXPRESSION,
  206. faceExpression,
  207. duration: finalDuration,
  208. timestamp
  209. });
  210. };
  211. }
  212. /**
  213. * Adds a face expression with its timestamp to the face expression buffer.
  214. *
  215. * @param {Object} faceExpression - Object containing face expression string and its timestamp.
  216. * @returns {Object}
  217. */
  218. export function addToFaceExpressionsBuffer(faceExpression: Object) {
  219. return {
  220. type: ADD_TO_FACE_EXPRESSIONS_BUFFER,
  221. faceExpression
  222. };
  223. }
  224. /**
  225. * Clears the face expressions array in the state.
  226. *
  227. * @returns {Object}
  228. */
  229. function clearFaceExpressionBuffer() {
  230. return {
  231. type: CLEAR_FACE_EXPRESSIONS_BUFFER
  232. };
  233. }