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.

JitsiStreamBlurEffect.js 7.4KB

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