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 9.1KB

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