emscripten-core / emscripten-core/emscripten

JS thread blocked when calling Wasm

Open
#20,982 2 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

**Version of emscripten/emsdk:**
```
emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.51 (c0c2ca1314672a25699846b4663701bcb6f69cca)
clang version 18.0.0git (https://github.com/llvm/llvm-project f2464ca317bfeeedddb7cbdea3c2c8ec487890bb)
Target: wasm32-unknown-emscripten
Thread model: posix
InstalledDir: D:\develop\emsdk\upstream\bin
```

**link command:**
```
set_target_properties(${PROJECT_NAME} PROPERTIES LINK_FLAGS "-lembind -sALLOW_MEMORY_GROWTH -sEXPORT_ES6 -sINVOKE_RUN=0 --embind-emit-tsd silk_wasm.d.ts")
)
```

**C++ code:**
```cpp
extern "C"
{
#include
#include
}
#include
#include
using namespace std;
using namespace emscripten;

typedef struct codec_ctx
{
val cb;
} codec_ctx_t;

void codec_callback(void *userdata, unsigned char *data, int len)
{
codec_ctx_t ctx = *(codec_ctx_t *)userdata;
ctx.cb(val(typed_memory_view(len, data)));
}

int silk_encode(std::string data, int data_len, int sample_rate, val cb)
{
codec_ctx_t ctx = {cb};
unsigned char* uc = (unsigned char*) data.c_str();
int ret = silkEncode(uc, data_len, sample_rate, codec_callback, &ctx);
return ret;
}

EMSCRIPTEN_BINDINGS(module)
{
emscripten::function("silk_encode", &silk_encode);
}
```

**Typescript code:**
```ts
import Instance from './silk_wasm.js'
import { concat } from './utils'

export interface encodeResult {
data: Uint8Array
duration: number
}

export async function encode(input: Uint8Array, sampleRate: number): Promise {
const instance = await Instance()

const arr: Uint8Array[] = []
let totalLength = 0

const ret = instance.silk_encode(input, input.length, sampleRate, (chunk: Uint8Array) => {
totalLength += chunk.length
arr.push(Uint8Array.from(chunk))
})

if (ret === 0) throw new Error('silk encoding failure')

return {
data: concat(arr, totalLength).slice(0, -1),
duration: ret
}
}
```

When I run the `encode` function in the Typescript code, the JS thread is blocked. How can I solve this?

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.