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.

JitsiStreamBlurEffect.js 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. // @flow
  2. import * as StackBlur from 'stackblur-canvas';
  3. import {
  4. CLEAR_TIMEOUT,
  5. TIMEOUT_TICK,
  6. SET_TIMEOUT,
  7. timerWorkerScript
  8. } from './TimerWorker';
  9. /**
  10. * Represents a modified MediaStream that adds blur to video background.
  11. * <tt>JitsiStreamBlurEffect</tt> does the processing of the original
  12. * video stream.
  13. */
  14. export default class JitsiStreamBlurEffect {
  15. _bpModel: Object;
  16. _inputVideoElement: HTMLVideoElement;
  17. _inputVideoCanvasElement: HTMLCanvasElement;
  18. _onMaskFrameTimer: Function;
  19. _maskFrameTimerWorker: Worker;
  20. _maskInProgress: boolean;
  21. _outputCanvasElement: HTMLCanvasElement;
  22. _renderMask: Function;
  23. _segmentationData: Object;
  24. isEnabled: Function;
  25. startEffect: Function;
  26. stopEffect: Function;
  27. /**
  28. * Represents a modified video MediaStream track.
  29. *
  30. * @class
  31. * @param {BodyPix} bpModel - BodyPix model.
  32. */
  33. constructor(bpModel: Object) {
  34. this._bpModel = bpModel;
  35. // Bind event handler so it is only bound once for every instance.
  36. this._onMaskFrameTimer = this._onMaskFrameTimer.bind(this);
  37. // Workaround for FF issue https://bugzilla.mozilla.org/show_bug.cgi?id=1388974
  38. this._outputCanvasElement = document.createElement('canvas');
  39. this._outputCanvasElement.getContext('2d');
  40. this._inputVideoElement = document.createElement('video');
  41. this._inputVideoCanvasElement = document.createElement('canvas');
  42. }
  43. /**
  44. * EventHandler onmessage for the maskFrameTimerWorker WebWorker.
  45. *
  46. * @private
  47. * @param {EventHandler} response - The onmessage EventHandler parameter.
  48. * @returns {void}
  49. */
  50. async _onMaskFrameTimer(response: Object) {
  51. if (response.data.id === TIMEOUT_TICK) {
  52. await this._renderMask();
  53. }
  54. }
  55. /**
  56. * Loop function to render the background mask.
  57. *
  58. * @private
  59. * @returns {void}
  60. */
  61. async _renderMask() {
  62. if (!this._maskInProgress) {
  63. this._maskInProgress = true;
  64. this._bpModel.segmentPerson(this._inputVideoElement, {
  65. internalResolution: 'low', // resized to 0.5 times of the original resolution before inference
  66. maxDetections: 1, // max. number of person poses to detect per image
  67. segmentationThreshold: 0.7, // represents probability that a pixel belongs to a person
  68. flipHorizontal: false,
  69. scoreThreshold: 0.2
  70. }).then(data => {
  71. this._segmentationData = data;
  72. this._maskInProgress = false;
  73. });
  74. }
  75. const inputCanvasCtx = this._inputVideoCanvasElement.getContext('2d');
  76. inputCanvasCtx.drawImage(this._inputVideoElement, 0, 0);
  77. const currentFrame = inputCanvasCtx.getImageData(
  78. 0,
  79. 0,
  80. this._inputVideoCanvasElement.width,
  81. this._inputVideoCanvasElement.height
  82. );
  83. if (this._segmentationData) {
  84. const blurData = new ImageData(currentFrame.data.slice(), currentFrame.width, currentFrame.height);
  85. StackBlur.imageDataRGB(blurData, 0, 0, currentFrame.width, currentFrame.height, 12);
  86. for (let x = 0; x < this._outputCanvasElement.width; x++) {
  87. for (let y = 0; y < this._outputCanvasElement.height; y++) {
  88. const n = (y * this._outputCanvasElement.width) + x;
  89. if (this._segmentationData.data[n] === 0) {
  90. currentFrame.data[n * 4] = blurData.data[n * 4];
  91. currentFrame.data[(n * 4) + 1] = blurData.data[(n * 4) + 1];
  92. currentFrame.data[(n * 4) + 2] = blurData.data[(n * 4) + 2];
  93. currentFrame.data[(n * 4) + 3] = blurData.data[(n * 4) + 3];
  94. }
  95. }
  96. }
  97. }
  98. this._outputCanvasElement.getContext('2d').putImageData(currentFrame, 0, 0);
  99. this._maskFrameTimerWorker.postMessage({
  100. id: SET_TIMEOUT,
  101. timeMs: 1000 / 30
  102. });
  103. }
  104. /**
  105. * Checks if the local track supports this effect.
  106. *
  107. * @param {JitsiLocalTrack} jitsiLocalTrack - Track to apply effect.
  108. * @returns {boolean} - Returns true if this effect can run on the specified track
  109. * false otherwise.
  110. */
  111. isEnabled(jitsiLocalTrack: Object) {
  112. return jitsiLocalTrack.isVideoTrack() && jitsiLocalTrack.videoType === 'camera';
  113. }
  114. /**
  115. * Starts loop to capture video frame and render the segmentation mask.
  116. *
  117. * @param {MediaStream} stream - Stream to be used for processing.
  118. * @returns {MediaStream} - The stream with the applied effect.
  119. */
  120. startEffect(stream: MediaStream) {
  121. this._maskFrameTimerWorker = new Worker(timerWorkerScript, { name: 'Blur effect worker' });
  122. this._maskFrameTimerWorker.onmessage = this._onMaskFrameTimer;
  123. const firstVideoTrack = stream.getVideoTracks()[0];
  124. const { height, frameRate, width }
  125. = firstVideoTrack.getSettings ? firstVideoTrack.getSettings() : firstVideoTrack.getConstraints();
  126. this._outputCanvasElement.width = parseInt(width, 10);
  127. this._outputCanvasElement.height = parseInt(height, 10);
  128. this._inputVideoCanvasElement.width = parseInt(width, 10);
  129. this._inputVideoCanvasElement.height = parseInt(height, 10);
  130. this._inputVideoElement.width = parseInt(width, 10);
  131. this._inputVideoElement.height = parseInt(height, 10);
  132. this._inputVideoElement.autoplay = true;
  133. this._inputVideoElement.srcObject = stream;
  134. this._inputVideoElement.onloadeddata = () => {
  135. this._maskFrameTimerWorker.postMessage({
  136. id: SET_TIMEOUT,
  137. timeMs: 1000 / 30
  138. });
  139. };
  140. return this._outputCanvasElement.captureStream(parseInt(frameRate, 10));
  141. }
  142. /**
  143. * Stops the capture and render loop.
  144. *
  145. * @returns {void}
  146. */
  147. stopEffect() {
  148. this._maskFrameTimerWorker.postMessage({
  149. id: CLEAR_TIMEOUT
  150. });
  151. this._maskFrameTimerWorker.terminate();
  152. }
  153. }