test.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import YUVSurfaceShader from "./YUVSurfaceShader";
  2. import Texture from "./Texture";
  3. let canvas = null;
  4. let yuvSurfaceShader = null;
  5. let yTexture = null;
  6. let uTexture = null;
  7. let vTexture = null;
  8. function initWebGLCanvas() {
  9. canvas = document.createElement("canvas");
  10. canvas.id = "test_canvas";
  11. canvas.style = `position: fixed;top:0;left: 0;z-index: 100;`;
  12. const gl = canvas.getContext("webgl");
  13. yuvSurfaceShader = YUVSurfaceShader.create(gl);
  14. yTexture = Texture.create(gl, gl.LUMINANCE);
  15. uTexture = Texture.create(gl, gl.LUMINANCE);
  16. vTexture = Texture.create(gl, gl.LUMINANCE);
  17. document.body.append(canvas);
  18. }
  19. function draw(buffer, width, height) {
  20. canvas.width = width;
  21. canvas.height = height;
  22. // the width & height returned are actually padded, so we have to use the frame size to get the real image dimension
  23. // when uploading to texture
  24. const stride = width; // stride
  25. // height is padded with filler rows
  26. // if we knew the size of the video before encoding, we could cut out the black filler pixels. We don't, so just set
  27. // it to the size after encoding
  28. const sourceWidth = width;
  29. const sourceHeight = height;
  30. const maxXTexCoord = sourceWidth / stride;
  31. const maxYTexCoord = sourceHeight / height;
  32. const lumaSize = stride * height;
  33. const chromaSize = lumaSize >> 2;
  34. const yBuffer = buffer.subarray(0, lumaSize);
  35. const uBuffer = buffer.subarray(lumaSize, lumaSize + chromaSize);
  36. const vBuffer = buffer.subarray(
  37. lumaSize + chromaSize,
  38. lumaSize + 2 * chromaSize
  39. );
  40. // console.log("yBuffer", 1);
  41. window.updateTexture(yBuffer);
  42. const chromaHeight = height >> 1;
  43. const chromaStride = stride >> 1;
  44. // we upload the entire image, including stride padding & filler rows. The actual visible image will be mapped
  45. // from texture coordinates as to crop out stride padding & filler rows using maxXTexCoord and maxYTexCoord.
  46. yTexture.image2dBuffer(yBuffer, stride, height);
  47. uTexture.image2dBuffer(uBuffer, chromaStride, chromaHeight);
  48. vTexture.image2dBuffer(vBuffer, chromaStride, chromaHeight);
  49. yuvSurfaceShader.setTexture(yTexture, uTexture, vTexture);
  50. yuvSurfaceShader.updateShaderData(
  51. { w: width, h: height },
  52. { maxXTexCoord, maxYTexCoord }
  53. );
  54. // debugger
  55. // data = window.changeTexture(data);
  56. // window.updateTexture( data );
  57. yuvSurfaceShader.draw();
  58. }
  59. export { canvas, initWebGLCanvas, draw };