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.

JitsiStreamBackgroundEffect.js 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. // @flow
  2. import {
  3. CLEAR_TIMEOUT,
  4. TIMEOUT_TICK,
  5. SET_TIMEOUT,
  6. timerWorkerScript
  7. } from './TimerWorker';
  8. const blurValue = '25px';
  9. /**
  10. * Represents a modified MediaStream that adds effects to video background.
  11. * <tt>JitsiStreamBackgroundEffect</tt> does the processing of the original
  12. * video stream.
  13. */
  14. export default class JitsiStreamBackgroundEffect {
  15. _model: Object;
  16. _options: Object;
  17. _segmentationPixelCount: number;
  18. _inputVideoElement: HTMLVideoElement;
  19. _onMaskFrameTimer: Function;
  20. _maskFrameTimerWorker: Worker;
  21. _outputCanvasElement: HTMLCanvasElement;
  22. _outputCanvasCtx: Object;
  23. _segmentationMaskCtx: Object;
  24. _segmentationMask: Object;
  25. _segmentationMaskCanvas: Object;
  26. _renderMask: Function;
  27. _virtualImage: HTMLImageElement;
  28. isEnabled: Function;
  29. startEffect: Function;
  30. stopEffect: Function;
  31. /**
  32. * Represents a modified video MediaStream track.
  33. *
  34. * @class
  35. * @param {Object} model - Meet model.
  36. * @param {Object} options - Segmentation dimensions.
  37. */
  38. constructor(model: Object, options: Object) {
  39. this._options = options;
  40. if (this._options.virtualBackground.isVirtualBackground) {
  41. this._virtualImage = document.createElement('img');
  42. this._virtualImage.crossOrigin = 'anonymous';
  43. this._virtualImage.src = this._options.virtualBackground.virtualSource;
  44. }
  45. this._model = model;
  46. this._options = options;
  47. this._segmentationPixelCount = this._options.width * this._options.height;
  48. // Bind event handler so it is only bound once for every instance.
  49. this._onMaskFrameTimer = this._onMaskFrameTimer.bind(this);
  50. // Workaround for FF issue https://bugzilla.mozilla.org/show_bug.cgi?id=1388974
  51. this._outputCanvasElement = document.createElement('canvas');
  52. this._outputCanvasElement.getContext('2d');
  53. this._inputVideoElement = document.createElement('video');
  54. }
  55. /**
  56. * EventHandler onmessage for the maskFrameTimerWorker WebWorker.
  57. *
  58. * @private
  59. * @param {EventHandler} response - The onmessage EventHandler parameter.
  60. * @returns {void}
  61. */
  62. async _onMaskFrameTimer(response: Object) {
  63. if (response.data.id === TIMEOUT_TICK) {
  64. await this._renderMask();
  65. }
  66. }
  67. /**
  68. * Represents the run post processing.
  69. *
  70. * @returns {void}
  71. */
  72. runPostProcessing() {
  73. this._outputCanvasCtx.globalCompositeOperation = 'copy';
  74. // Draw segmentation mask.
  75. //
  76. // Smooth out the edges.
  77. if (this._options.virtualBackground.isVirtualBackground) {
  78. this._outputCanvasCtx.filter = 'blur(4px)';
  79. } else {
  80. this._outputCanvasCtx.filter = 'blur(8px)';
  81. }
  82. this._outputCanvasCtx.drawImage(
  83. this._segmentationMaskCanvas,
  84. 0,
  85. 0,
  86. this._options.width,
  87. this._options.height,
  88. 0,
  89. 0,
  90. this._inputVideoElement.width,
  91. this._inputVideoElement.height
  92. );
  93. this._outputCanvasCtx.globalCompositeOperation = 'source-in';
  94. this._outputCanvasCtx.filter = 'none';
  95. // Draw the foreground video.
  96. //
  97. this._outputCanvasCtx.drawImage(this._inputVideoElement, 0, 0);
  98. // Draw the background.
  99. //
  100. this._outputCanvasCtx.globalCompositeOperation = 'destination-over';
  101. if (this._options.virtualBackground.isVirtualBackground) {
  102. this._outputCanvasCtx.drawImage(
  103. this._virtualImage,
  104. 0,
  105. 0,
  106. this._inputVideoElement.width,
  107. this._inputVideoElement.height
  108. );
  109. } else {
  110. this._outputCanvasCtx.filter = `blur(${blurValue})`;
  111. this._outputCanvasCtx.drawImage(this._inputVideoElement, 0, 0);
  112. }
  113. }
  114. /**
  115. * Represents the run Tensorflow Interference.
  116. *
  117. * @returns {void}
  118. */
  119. runInference() {
  120. this._model._runInference();
  121. const outputMemoryOffset = this._model._getOutputMemoryOffset() / 4;
  122. for (let i = 0; i < this._segmentationPixelCount; i++) {
  123. const background = this._model.HEAPF32[outputMemoryOffset + (i * 2)];
  124. const person = this._model.HEAPF32[outputMemoryOffset + (i * 2) + 1];
  125. const shift = Math.max(background, person);
  126. const backgroundExp = Math.exp(background - shift);
  127. const personExp = Math.exp(person - shift);
  128. // Sets only the alpha component of each pixel.
  129. this._segmentationMask.data[(i * 4) + 3] = (255 * personExp) / (backgroundExp + personExp);
  130. }
  131. this._segmentationMaskCtx.putImageData(this._segmentationMask, 0, 0);
  132. }
  133. /**
  134. * Loop function to render the background mask.
  135. *
  136. * @private
  137. * @returns {void}
  138. */
  139. _renderMask() {
  140. this.resizeSource();
  141. this.runInference();
  142. this.runPostProcessing();
  143. this._maskFrameTimerWorker.postMessage({
  144. id: SET_TIMEOUT,
  145. timeMs: 1000 / 30
  146. });
  147. }
  148. /**
  149. * Represents the resize source process.
  150. *
  151. * @returns {void}
  152. */
  153. resizeSource() {
  154. this._segmentationMaskCtx.drawImage(
  155. this._inputVideoElement,
  156. 0,
  157. 0,
  158. this._inputVideoElement.width,
  159. this._inputVideoElement.height,
  160. 0,
  161. 0,
  162. this._options.width,
  163. this._options.height
  164. );
  165. const imageData = this._segmentationMaskCtx.getImageData(
  166. 0,
  167. 0,
  168. this._options.width,
  169. this._options.height
  170. );
  171. const inputMemoryOffset = this._model._getInputMemoryOffset() / 4;
  172. for (let i = 0; i < this._segmentationPixelCount; i++) {
  173. this._model.HEAPF32[inputMemoryOffset + (i * 3)] = imageData.data[i * 4] / 255;
  174. this._model.HEAPF32[inputMemoryOffset + (i * 3) + 1] = imageData.data[(i * 4) + 1] / 255;
  175. this._model.HEAPF32[inputMemoryOffset + (i * 3) + 2] = imageData.data[(i * 4) + 2] / 255;
  176. }
  177. }
  178. /**
  179. * Checks if the local track supports this effect.
  180. *
  181. * @param {JitsiLocalTrack} jitsiLocalTrack - Track to apply effect.
  182. * @returns {boolean} - Returns true if this effect can run on the specified track
  183. * false otherwise.
  184. */
  185. isEnabled(jitsiLocalTrack: Object) {
  186. return jitsiLocalTrack.isVideoTrack() && jitsiLocalTrack.videoType === 'camera';
  187. }
  188. /**
  189. * Starts loop to capture video frame and render the segmentation mask.
  190. *
  191. * @param {MediaStream} stream - Stream to be used for processing.
  192. * @returns {MediaStream} - The stream with the applied effect.
  193. */
  194. startEffect(stream: MediaStream) {
  195. this._maskFrameTimerWorker = new Worker(timerWorkerScript, { name: 'Blur effect worker' });
  196. this._maskFrameTimerWorker.onmessage = this._onMaskFrameTimer;
  197. const firstVideoTrack = stream.getVideoTracks()[0];
  198. const { height, frameRate, width }
  199. = firstVideoTrack.getSettings ? firstVideoTrack.getSettings() : firstVideoTrack.getConstraints();
  200. this._segmentationMask = new ImageData(this._options.width, this._options.height);
  201. this._segmentationMaskCanvas = document.createElement('canvas');
  202. this._segmentationMaskCanvas.width = this._options.width;
  203. this._segmentationMaskCanvas.height = this._options.height;
  204. this._segmentationMaskCtx = this._segmentationMaskCanvas.getContext('2d');
  205. this._outputCanvasElement.width = parseInt(width, 10);
  206. this._outputCanvasElement.height = parseInt(height, 10);
  207. this._outputCanvasCtx = this._outputCanvasElement.getContext('2d');
  208. this._inputVideoElement.width = parseInt(width, 10);
  209. this._inputVideoElement.height = parseInt(height, 10);
  210. this._inputVideoElement.autoplay = true;
  211. this._inputVideoElement.srcObject = stream;
  212. this._inputVideoElement.onloadeddata = () => {
  213. this._maskFrameTimerWorker.postMessage({
  214. id: SET_TIMEOUT,
  215. timeMs: 1000 / 30
  216. });
  217. };
  218. return this._outputCanvasElement.captureStream(parseInt(frameRate, 10));
  219. }
  220. /**
  221. * Stops the capture and render loop.
  222. *
  223. * @returns {void}
  224. */
  225. stopEffect() {
  226. this._maskFrameTimerWorker.postMessage({
  227. id: CLEAR_TIMEOUT
  228. });
  229. this._maskFrameTimerWorker.terminate();
  230. }
  231. }