Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JitsiStreamBackgroundEffect.js 10KB

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