emscripten-core / emscripten-core/emscripten

[Question] Wasm Workers and Module

Open
#19,682 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
27.6k
Forks
3.6k
Avg merge
1d 1h
Merged PRs (30d)
105

Description

I am loading media into my WebGL C code. Videos, WebCam streams and images. I use the browser to decode them and send them to my c code, where they are uploaded to the GPU. Here is the image case:
```javascript
async function load_from_url(url) {
try {
const response = await fetch(url);
const blob = await response.blob();
const bitmap = await createImageBitmap(blob);

const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
const ctx = canvas.getContext('2d');

ctx.drawImage(bitmap, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const dataPtr = Module._malloc(imageData.data.length);

Module.HEAPU8.set(imageData.data, dataPtr);
Module.ccall(
'media_setup',
'number',
['number', 'number', 'number'],
[dataPtr, canvas.width, canvas.height]
);
Module._free(dataPtr);
} catch (err) {
console.error(err);
}
};
```
The c code does essentially just:
```c
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
```
Works great!
Of course I am able to decode the blob using SDL2_Image, but once we get to webcams and hardware accelerated video decode, this approach of decoding in WASM breaks down. The overhead is quite painful, since we cannot access the browsers decode functions directly to get pixel data, but have to draw it to an invisible canvas and get those pixels copied. (Any grave misunderstandings from my side this far?)

So I want to do as much of this in a separate web worker. Simply spawning a worker is a no-go though, since `Module` isn't known by the worker. So I guess I have to use `-s WASM_WORKERS` and call `load_from_url()` from the C code? Is this logic sound? Will this even work? Reading through https://emscripten.org/docs/api_reference/wasm_workers.html I get the feeling, that I am gravely misusing the WASM API here...

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.