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.3KB

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