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

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