yuv.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. var wasmExports;
  2. fetch('yuv.wasm').then(function (res) { return res.arrayBuffer(); })
  3. .then(function (file) { return WebAssembly.instantiate(file); })
  4. .then(function (wasm) {
  5. wasmExports = wasm.instance.exports;
  6. console.log('yuv ready');
  7. });
  8. var yPtr, yPtrLen, uPtr, uPtrLen, vPtr, vPtrLen, outPtr, outPtrLen;
  9. let testSpeed = [0, 0];
  10. function I420ToARGB(yb) {
  11. if (!wasmExports) return;
  12. var tm0 = new Date().getTime();
  13. var { malloc, free, memory } = wasmExports;
  14. var HEAPU8 = new Uint8Array(memory.buffer);
  15. let n = yb.y.bytes.length;
  16. if (yPtrLen != n) {
  17. if (yPtr) free(yPtr);
  18. yPtrLen = n;
  19. yPtr = malloc(n);
  20. }
  21. HEAPU8.set(yb.y.bytes, yPtr);
  22. n = yb.u.bytes.length;
  23. if (uPtrLen != n) {
  24. if (uPtr) free(uPtr);
  25. uPtrLen = n;
  26. uPtr = malloc(n);
  27. }
  28. HEAPU8.set(yb.u.bytes, uPtr);
  29. n = yb.v.bytes.length;
  30. if (vPtrLen != n) {
  31. if (vPtr) free(vPtr);
  32. vPtrLen = n;
  33. vPtr = malloc(n);
  34. }
  35. HEAPU8.set(yb.v.bytes, vPtr);
  36. var w = yb.format.displayWidth;
  37. var h = yb.format.displayHeight;
  38. n = w * h * 4;
  39. if (outPtrLen != n) {
  40. if (outPtr) free(outPtr);
  41. outPtrLen = n;
  42. outPtr = malloc(n);
  43. HEAPU8.fill(255, outPtr, outPtr + n);
  44. }
  45. // var res = wasmExports.I420ToARGB(yPtr, yb.y.stride, uPtr, yb.u.stride, vPtr, yb.v.stride, outPtr, w * 4, w, h);
  46. // var res = wasmExports.AVX_YUV_to_ARGB(outPtr, yPtr, yb.y.stride, uPtr, yb.u.stride, vPtr, yb.v.stride, w, h);
  47. var res = wasmExports.yuv420_rgb24_std(w, h, yPtr, uPtr, vPtr, yb.y.stride, yb.v.stride, outPtr, w * 4, 1);
  48. var out = HEAPU8.slice(outPtr, outPtr + n);
  49. testSpeed[1] += new Date().getTime() - tm0;
  50. testSpeed[0] += 1;
  51. if (testSpeed[0] > 30) {
  52. console.log('yuv: ' + parseInt('' + testSpeed[1] / testSpeed[0]));
  53. testSpeed = [0, 0];
  54. }
  55. return out;
  56. }
  57. var currentFrame;
  58. self.addEventListener('message', (e) => {
  59. currentFrame = e.data;
  60. });
  61. function run() {
  62. if (currentFrame) {
  63. self.postMessage(I420ToARGB(currentFrame));
  64. currentFrame = undefined;
  65. }
  66. setTimeout(run, 1);
  67. }
  68. run();