Repository: opencv
Issue: built OpenCV.js fails to load wasm in node.js
Labels: category: javascript (js),category: 3rdparty

##### System information (version)
<!-- Example
- OpenCV => 4.2
- Operating System / Platform => Windows 64 Bit
- Compiler => Visual Studio 2017
-->

- OpenCV => 4.5.1 & master
- Operating System / Platform => node 8/10/14 (built on ubuntu 20)
- Compiler => emscripten

##### Detailed description

**Expected behavior**:

1. Running opencv.js via **node** built using the documented instructions correctly loads, passes all tests and runs `test_async.js` (see further). 
    * build instructions https://docs.opencv.org/master/d4/da1/tutorial_js_setup.html
2. Pre-built opencv.js passes all tests and `test_async.js`
    * distributed opencv.js https://docs.opencv.org/master/opencv.js

Note that running the `tests.html` via browser works correctly, the failures are specific to running via node.js.

**Actual behavior**: 

1. Self-built opencv.js
    * `node tests.js` fails to even fail properly and instead just reports `0 failed, 0 passed`
    * `node test_async.js` fails to load wasm due to needing experimental wasm threads & shared memory
        * `RuntimeError: abort(RuntimeError: abort(CompileError: WebAssembly.instantiate(): Compiling function #73 failed: Invalid opcode (enable with --experimental-wasm-threads) @+39429)`
        * (with threads enabled) `RuntimeError: abort(RuntimeError: abort(CompileError: WebAssembly.instantiate(): Compiling function #73 failed: Atomic opcodes used without shared memory @+39428)`
2. Pre-built opencv.js
    * `node tests.js` fails most tests (34 failed, 10 passed), due to improper loading
    * `node test_async.js` works as expected (and generally using the pre-built library works as expected when loaded properly)
**

Running `node tests.js` simply outputs:

```
Testing  /home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js ... 
0 failed, 0 passed
```


If I modify `tests.js` and only allow a single file (e.g. `tests: [ 'test_mat.js']`) I instead get the following error:

```
You are getting _malloc on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js
RuntimeError: abort(You are getting _malloc on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js) at Error
    at jsStackTrace (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7381549)
    at stackTrace (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7381725)
    at abort (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:33457)
    at Promise.get (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7202)
    at Object.<anonymous> (/home/ubuntu/prog/docker-opencv/js_wasm/bin/test_mat.js:756:26)
    at runTest (/home/ubuntu/prog/docker-opencv/js_wasm/bin/node_modules/node-qunit/node_modules/qunit/qunit/qunit.js:3044:32)
    at Test.run (/home/ubuntu/prog/docker-opencv/js_wasm/bin/node_modules/node-qunit/node_modules/qunit/qunit/qunit.js:3032:8)
    at /home/ubuntu/prog/docker-opencv/js_wasm/bin/node_modules/node-qunit/node_modules/qunit/qunit/qunit.js:3255:15
    at processTaskQueue (/home/ubuntu/prog/docker-opencv/js_wasm/bin/node_modules/node-qunit/node_modules/qunit/qunit/qunit.js:2640:26)
    at /home/ubuntu/prog/docker-opencv/js_wasm/bin/node_modules/node-qunit/node_modules/qunit/qunit/qunit.js:2644:12
0 failed, 0 passed
```

This is presumably due to the tests not loading the library correctly.

**

Running `node test_async.js` (code see further) produces the following error:


Node 8/Node 10 -- generic decoding error:

```
failed to asynchronously prepare wasm: CompileError: WasmCompile: Wasm decoding failed: unexpected section: Code @+37433
CompileError: WasmCompile: Wasm decoding failed: unexpected section: Code @+37433
RuntimeError: abort(CompileError: WasmCompile: Wasm decoding failed: unexpected section: Code @+37433) at Error
    at jsStackTrace (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7381549)
    at stackTrace (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7381725)
    at abort (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:33457)
    at /home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7358365
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7)
    at Function.Module.runMain (module.js:696:11)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3

```

Node 14 -- invalid threads opcode

```
RuntimeError: abort(RuntimeError: abort(CompileError: WebAssembly.instantiate(): Compiling function #73 failed: Invalid opcode (enable with --experimental-wasm-threads) @+39429) at Error
    at jsStackTrace (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7381549)
    at stackTrace (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7381725)
    at abort (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:33457)
    at /home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7358365) at Error
    at jsStackTrace (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7381549)
    at stackTrace (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7381725)
    at process.abort (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:33457)
    at process.emit (events.js:315:20)
    at processPromiseRejections (internal/process/promises.js:245:33)
    at processTicksAndRejections (internal/process/task_queues.js:94:32)
    at process.abort (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:33488)
    at process.emit (events.js:315:20)
    at processPromiseRejections (internal/process/promises.js:245:33)
    at processTicksAndRejections (internal/process/task_queues.js:94:32)
```

Rerunning with `--experimental-wasm-threads` produces invalid shared memory opcode instead

```
RuntimeError: abort(RuntimeError: abort(CompileError: WebAssembly.instantiate(): Compiling function #73 failed: Atomic opcodes used without shared memory @+39428) at Error
    at jsStackTrace (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7381549)
    at stackTrace (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7381725)
    at abort (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:33457)
    at /home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7358365) at Error
    at jsStackTrace (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7381549)
    at stackTrace (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:7381725)
    at process.abort (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:33457)
    at process.emit (events.js:315:20)
    at processPromiseRejections (internal/process/promises.js:245:33)
    at processTicksAndRejections (internal/process/task_queues.js:94:32)
    at process.abort (/home/ubuntu/prog/docker-opencv/js_wasm/bin/opencv.js:31:33488)
    at process.emit (events.js:315:20)
    at processPromiseRejections (internal/process/promises.js:245:33)
    at processTicksAndRejections (internal/process/task_queues.js:94:32)
```

<!-- your description -->

##### Steps to reproduce

1. Follow instructions here except for extra flags (see 2) https://docs.opencv.org/4.5.1/d4/da1/tutorial_js_setup.html
  * using emsdk or docker didn't make any difference, nor the latest emsdk vs 2.0.10
  * using `--build_wasm` or not also doesn't seem to matter (it always produces wasm)
2. Build with `--build_test` and `--build_flags '-s ASSERTIONS=1'`
```
sudo docker run --rm -v $(pwd):/src -u 1000:1000 emscripten/emsdk:2.0.10 emcmake python3 ./opencv/platforms/js/build_js.py js_assertions --build_test --build_flags '-s ASSERTIONS=1'
```
3. install node dependencies & run tests
4. change `tests.js` to run only for a single file (`tests: [ 'test_mat.js' ]`) & run tests
5. run `node test_async.js`
```js
let cv

function loadOpenCv() {
    return new Promise(resolve => {
        global.Module = {
            onRuntimeInitialized: () => {
                console.log('opencv ready')
                resolve()
            }
        }
        cv = require('./opencv.js')
    })
}

loadOpenCv().then(() => {
    const mat = new cv.Mat(10, 20, cv.CV_8UC3)
    console.log(mat.cols)
    mat.delete()
})
```


##### Issue submission checklist

 - [x] I report the issue, it's not a question
   <!--
   OpenCV team works with answers.opencv.org, Stack Overflow and other communities
   to discuss problems. Tickets with question without real issue statement will be
   closed.
   -->
 - [x] I checked the problem with documentation, FAQ, open issues,
       answers.opencv.org, Stack Overflow, etc and have not found solution
   <!--
   Places to check:
   * OpenCV documentation: https://docs.opencv.org
   * FAQ page: https://github.com/opencv/opencv/wiki/FAQ
   * OpenCV forum: https://answers.opencv.org
   * OpenCV issue tracker: https://github.com/opencv/opencv/issues?q=is%3Aissue
   * Stack Overflow branch: https://stackoverflow.com/questions/tagged/opencv
   -->
 - [x] I updated to latest OpenCV version and the issue is still there
   <!--
   master branch for OpenCV 4.x and 3.4 branch for OpenCV 3.x releases.
   OpenCV team supports only latest release for each branch.
   The ticket is closed, if the problem is not reproduced with modern version.
   -->
 - [ ] There is reproducer code and related data files: videos, images, onnx, etc
   <!--
   The best reproducer -- test case for OpenCV that we can add to the library.
   Recommendations for media files and binary files:
   * Try to reproduce the issue with images and videos in opencv_extra repository
     to reduce attachment size
   * Use PNG for images, if you report some CV related bug, but not image reader
     issue
   * Attach the image as archive to the ticket, if you report some reader issue.
     Image hosting services compress images and it breaks the repro code.
   * Provide ONNX file for some public model or ONNX file with with random weights,
     if you report ONNX parsing or handling issue. Architecture details diagram
     from netron tool can be very useful too. See https://lutzroeder.github.io/netron/
   -->