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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. this._inputVideoElement.width,
  121. this._inputVideoElement.height
  122. );
  123. } else {
  124. this._outputCanvasCtx.filter = `blur(${this._options.virtualBackground.blurValue}px)`;
  125. this._outputCanvasCtx.drawImage(this._inputVideoElement, 0, 0);
  126. }
  127. }
  128. /**
  129. * Represents the run Tensorflow Interference.
  130. *
  131. * @returns {void}
  132. */
  133. runInference() {
  134. this._model._runInference();
  135. const outputMemoryOffset = this._model._getOutputMemoryOffset() / 4;
  136. for (let i = 0; i < this._segmentationPixelCount; i++) {
  137. const background = this._model.HEAPF32[outputMemoryOffset + (i * 2)];
  138. const person = this._model.HEAPF32[outputMemoryOffset + (i * 2) + 1];
  139. const shift = Math.max(background, person);
  140. const backgroundExp = Math.exp(background - shift);
  141. const personExp = Math.exp(person - shift);
  142. // Sets only the alpha component of each pixel.
  143. this._segmentationMask.data[(i * 4) + 3] = (255 * personExp) / (backgroundExp + personExp);
  144. }
  145. this._segmentationMaskCtx.putImageData(this._segmentationMask, 0, 0);
  146. }
  147. /**
  148. * Loop function to render the background mask.
  149. *
  150. * @private
  151. * @returns {void}
  152. */
  153. _renderMask() {
  154. this.resizeSource();
  155. this.runInference();
  156. this.runPostProcessing();
  157. this._maskFrameTimerWorker.postMessage({
  158. id: SET_TIMEOUT,
  159. timeMs: 1000 / 30
  160. });
  161. }
  162. /**
  163. * Represents the resize source process.
  164. *
  165. * @returns {void}
  166. */
  167. resizeSource() {
  168. this._segmentationMaskCtx.drawImage(
  169. this._inputVideoElement,
  170. 0,
  171. 0,
  172. this._inputVideoElement.width,
  173. this._inputVideoElement.height,
  174. 0,
  175. 0,
  176. this._options.width,
  177. this._options.height
  178. );
  179. const imageData = this._segmentationMaskCtx.getImageData(
  180. 0,
  181. 0,
  182. this._options.width,
  183. this._options.height
  184. );
  185. const inputMemoryOffset = this._model._getInputMemoryOffset() / 4;
  186. for (let i = 0; i < this._segmentationPixelCount; i++) {
  187. this._model.HEAPF32[inputMemoryOffset + (i * 3)] = imageData.data[i * 4] / 255;
  188. this._model.HEAPF32[inputMemoryOffset + (i * 3) + 1] = imageData.data[(i * 4) + 1] / 255;
  189. this._model.HEAPF32[inputMemoryOffset + (i * 3) + 2] = imageData.data[(i * 4) + 2] / 255;
  190. }
  191. }
  192. /**
  193. * Checks if the local track supports this effect.
  194. *
  195. * @param {JitsiLocalTrack} jitsiLocalTrack - Track to apply effect.
  196. * @returns {boolean} - Returns true if this effect can run on the specified track
  197. * false otherwise.
  198. */
  199. isEnabled(jitsiLocalTrack: Object) {
  200. return jitsiLocalTrack.isVideoTrack() && jitsiLocalTrack.videoType === 'camera';
  201. }
  202. /**
  203. * Starts loop to capture video frame and render the segmentation mask.
  204. *
  205. * @param {MediaStream} stream - Stream to be used for processing.
  206. * @returns {MediaStream} - The stream with the applied effect.
  207. */
  208. startEffect(stream: MediaStream) {
  209. this._maskFrameTimerWorker = new Worker(timerWorkerScript, { name: 'Blur effect worker' });
  210. this._maskFrameTimerWorker.onmessage = this._onMaskFrameTimer;
  211. const firstVideoTrack = stream.getVideoTracks()[0];
  212. const { height, frameRate, width }
  213. = firstVideoTrack.getSettings ? firstVideoTrack.getSettings() : firstVideoTrack.getConstraints();
  214. this._segmentationMask = new ImageData(this._options.width, this._options.height);
  215. this._segmentationMaskCanvas = document.createElement('canvas');
  216. this._segmentationMaskCanvas.width = this._options.width;
  217. this._segmentationMaskCanvas.height = this._options.height;
  218. this._segmentationMaskCtx = this._segmentationMaskCanvas.getContext('2d');
  219. this._outputCanvasElement.width = parseInt(width, 10);
  220. this._outputCanvasElement.height = parseInt(height, 10);
  221. this._outputCanvasCtx = this._outputCanvasElement.getContext('2d');
  222. this._inputVideoElement.width = parseInt(width, 10);
  223. this._inputVideoElement.height = parseInt(height, 10);
  224. this._inputVideoElement.autoplay = true;
  225. this._inputVideoElement.srcObject = stream;
  226. this._inputVideoElement.onloadeddata = () => {
  227. this._maskFrameTimerWorker.postMessage({
  228. id: SET_TIMEOUT,
  229. timeMs: 1000 / 30
  230. });
  231. };
  232. return this._outputCanvasElement.captureStream(parseInt(frameRate, 10));
  233. }
  234. /**
  235. * Stops the capture and render loop.
  236. *
  237. * @returns {void}
  238. */
  239. stopEffect() {
  240. this._maskFrameTimerWorker.postMessage({
  241. id: CLEAR_TIMEOUT
  242. });
  243. this._maskFrameTimerWorker.terminate();
  244. }
  245. }