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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. // @flow
  2. import {
  3. CLEAR_TIMEOUT,
  4. TIMEOUT_TICK,
  5. SET_TIMEOUT,
  6. timerWorkerScript
  7. } from './TimerWorker';
  8. /**
  9. * Represents a modified MediaStream that adds effects to video background.
  10. * <tt>JitsiStreamBackgroundEffect</tt> does the processing of the original
  11. * video stream.
  12. */
  13. export default class JitsiStreamBackgroundEffect {
  14. _model: Object;
  15. _options: Object;
  16. _segmentationPixelCount: number;
  17. _inputVideoElement: HTMLVideoElement;
  18. _onMaskFrameTimer: Function;
  19. _maskFrameTimerWorker: Worker;
  20. _outputCanvasElement: HTMLCanvasElement;
  21. _outputCanvasCtx: Object;
  22. _segmentationMaskCtx: Object;
  23. _segmentationMask: Object;
  24. _segmentationMaskCanvas: Object;
  25. _renderMask: Function;
  26. _virtualImage: HTMLImageElement;
  27. isEnabled: Function;
  28. startEffect: Function;
  29. stopEffect: Function;
  30. /**
  31. * Represents a modified video MediaStream track.
  32. *
  33. * @class
  34. * @param {Object} model - Meet model.
  35. * @param {Object} options - Segmentation dimensions.
  36. */
  37. constructor(model: Object, options: Object) {
  38. this._options = options;
  39. if (this._options.virtualBackground.backgroundType === 'image') {
  40. this._virtualImage = document.createElement('img');
  41. this._virtualImage.crossOrigin = 'anonymous';
  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. _onMaskFrameTimer(response: Object) {
  62. if (response.data.id === TIMEOUT_TICK) {
  63. 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.backgroundType === 'image') {
  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.backgroundType === 'image') {
  101. this._outputCanvasCtx.drawImage(
  102. this._virtualImage,
  103. 0,
  104. 0,
  105. this._inputVideoElement.width,
  106. this._inputVideoElement.height
  107. );
  108. } else {
  109. this._outputCanvasCtx.filter = `blur(${this._options.virtualBackground.blurValue}px)`;
  110. this._outputCanvasCtx.drawImage(this._inputVideoElement, 0, 0);
  111. }
  112. }
  113. /**
  114. * Represents the run Tensorflow Interference.
  115. *
  116. * @returns {void}
  117. */
  118. runInference() {
  119. this._model._runInference();
  120. const outputMemoryOffset = this._model._getOutputMemoryOffset() / 4;
  121. for (let i = 0; i < this._segmentationPixelCount; i++) {
  122. const background = this._model.HEAPF32[outputMemoryOffset + (i * 2)];
  123. const person = this._model.HEAPF32[outputMemoryOffset + (i * 2) + 1];
  124. const shift = Math.max(background, person);
  125. const backgroundExp = Math.exp(background - shift);
  126. const personExp = Math.exp(person - shift);
  127. // Sets only the alpha component of each pixel.
  128. this._segmentationMask.data[(i * 4) + 3] = (255 * personExp) / (backgroundExp + personExp);
  129. }
  130. this._segmentationMaskCtx.putImageData(this._segmentationMask, 0, 0);
  131. }
  132. /**
  133. * Loop function to render the background mask.
  134. *
  135. * @private
  136. * @returns {void}
  137. */
  138. _renderMask() {
  139. this.resizeSource();
  140. this.runInference();
  141. this.runPostProcessing();
  142. this._maskFrameTimerWorker.postMessage({
  143. id: SET_TIMEOUT,
  144. timeMs: 1000 / 30
  145. });
  146. }
  147. /**
  148. * Represents the resize source process.
  149. *
  150. * @returns {void}
  151. */
  152. resizeSource() {
  153. this._segmentationMaskCtx.drawImage(
  154. this._inputVideoElement,
  155. 0,
  156. 0,
  157. this._inputVideoElement.width,
  158. this._inputVideoElement.height,
  159. 0,
  160. 0,
  161. this._options.width,
  162. this._options.height
  163. );
  164. const imageData = this._segmentationMaskCtx.getImageData(
  165. 0,
  166. 0,
  167. this._options.width,
  168. this._options.height
  169. );
  170. const inputMemoryOffset = this._model._getInputMemoryOffset() / 4;
  171. for (let i = 0; i < this._segmentationPixelCount; i++) {
  172. this._model.HEAPF32[inputMemoryOffset + (i * 3)] = imageData.data[i * 4] / 255;
  173. this._model.HEAPF32[inputMemoryOffset + (i * 3) + 1] = imageData.data[(i * 4) + 1] / 255;
  174. this._model.HEAPF32[inputMemoryOffset + (i * 3) + 2] = imageData.data[(i * 4) + 2] / 255;
  175. }
  176. }
  177. /**
  178. * Checks if the local track supports this effect.
  179. *
  180. * @param {JitsiLocalTrack} jitsiLocalTrack - Track to apply effect.
  181. * @returns {boolean} - Returns true if this effect can run on the specified track
  182. * false otherwise.
  183. */
  184. isEnabled(jitsiLocalTrack: Object) {
  185. return jitsiLocalTrack.isVideoTrack() && jitsiLocalTrack.videoType === 'camera';
  186. }
  187. /**
  188. * Starts loop to capture video frame and render the segmentation mask.
  189. *
  190. * @param {MediaStream} stream - Stream to be used for processing.
  191. * @returns {MediaStream} - The stream with the applied effect.
  192. */
  193. startEffect(stream: MediaStream) {
  194. this._maskFrameTimerWorker = new Worker(timerWorkerScript, { name: 'Blur effect worker' });
  195. this._maskFrameTimerWorker.onmessage = this._onMaskFrameTimer;
  196. const firstVideoTrack = stream.getVideoTracks()[0];
  197. const { height, frameRate, width }
  198. = firstVideoTrack.getSettings ? firstVideoTrack.getSettings() : firstVideoTrack.getConstraints();
  199. this._segmentationMask = new ImageData(this._options.width, this._options.height);
  200. this._segmentationMaskCanvas = document.createElement('canvas');
  201. this._segmentationMaskCanvas.width = this._options.width;
  202. this._segmentationMaskCanvas.height = this._options.height;
  203. this._segmentationMaskCtx = this._segmentationMaskCanvas.getContext('2d');
  204. this._outputCanvasElement.width = parseInt(width, 10);
  205. this._outputCanvasElement.height = parseInt(height, 10);
  206. this._outputCanvasCtx = this._outputCanvasElement.getContext('2d');
  207. this._inputVideoElement.width = parseInt(width, 10);
  208. this._inputVideoElement.height = parseInt(height, 10);
  209. this._inputVideoElement.autoplay = true;
  210. this._inputVideoElement.srcObject = stream;
  211. this._inputVideoElement.onloadeddata = () => {
  212. this._maskFrameTimerWorker.postMessage({
  213. id: SET_TIMEOUT,
  214. timeMs: 1000 / 30
  215. });
  216. };
  217. return this._outputCanvasElement.captureStream(parseInt(frameRate, 10));
  218. }
  219. /**
  220. * Stops the capture and render loop.
  221. *
  222. * @returns {void}
  223. */
  224. stopEffect() {
  225. this._maskFrameTimerWorker.postMessage({
  226. id: CLEAR_TIMEOUT
  227. });
  228. this._maskFrameTimerWorker.terminate();
  229. }
  230. }