Skip to content

armgit / facex

Public Imported from GitHub
0

Full face stack that runs entirely in the browser. Detection, 576-point 3D mesh, recognition, anti-spoof, smile — all WebAssembly, zero server. Apache 2.0.

Fix concurrent inference and document the released models

Baurzhan Atynov293526a74c78
diff --git a/.github/workflows/go-gallery.yml b/.github/workflows/go-gallery.yml
index 3c99204..11b7c6e 100644
--- a/.github/workflows/go-gallery.yml
+++ b/.github/workflows/go-gallery.yml
@@ -1,4 +1,4 @@
-name: Go gallery checks
+name: FaceX runtime checks
on:
push:
paths:
@@ -6,11 +6,14 @@ on:
- 'Makefile'
- 'src/**'
- 'include/**'
- - 'tests/golden/**'
- - 'tests/bench_gallery_codes.py'
- - 'tests/bench_gallery_groups.py'
- - 'tests/check_gallery_profiles.py'
- - 'python/facex/gallery.py'
+ - 'tests/**'
+ - 'nn2/**'
+ - 'frvt/**'
+ - 'training/scripts/binformat.py'
+ - 'docker/**'
+ - 'python/**'
+ - 'wasm/**'
+ - 'download_weights.sh'
- '.github/workflows/go-gallery.yml'
workflow_dispatch:
@@ -50,7 +53,7 @@ jobs:
FACEX_GALLERY_SCALE: '1'
FACEX_GALLERY_FIXTURE: ${{ runner.temp }}/gallery
run: |
- make cli cli-fp32
+ make -j2 all check cli-fp32 libfacex.so
mv facex-cli-fp32 "$RUNNER_TEMP/facex-native-fp32"
make cli-fp32 CFLAGS="-O3 -march=x86-64 -funroll-loops"
cc --version | head -1
@@ -73,3 +76,81 @@ jobs:
run: |
go test -race -v -timeout=90s -run '^TestPoolRealEngine$' -count=1 ./...
FACEX_POOL_TEST_EXE="$RUNNER_TEMP/facex-native-fp32" go test -race -v -timeout=90s -run '^TestPoolRealEngine$' -count=1 ./...
+ runtimes:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 12
+ env:
+ OPENBLAS_NUM_THREADS: '1'
+ PYTHONPATH: python:docker:tests
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ - name: Build native libraries and examples
+ run: |
+ make -j2 all cli-fp32 libfacex.so mfn-cli mfn-example check
+ make -C nn2 -j2
+ cc -O2 -Iinclude tests/bench_profile.c libfacex.a -lm -lpthread -o "$RUNNER_TEMP/bench-profile"
+ c++ -O2 -std=c++11 tests/frvt_alignment.cpp -o "$RUNNER_TEMP/frvt-alignment"
+ "$RUNNER_TEMP/frvt-alignment"
+ for flags in "-march=x86-64" "-march=x86-64-v3"; do
+ make -B nn2-gemm-test CFLAGS="-O2 $flags"
+ ./nn2-gemm-test
+ done
+ - name: Verify released weights and both Python transports
+ run: |
+ python -m pip install numpy==2.3.5 Pillow==12.0.0 flask onnx==1.18.0 onnxruntime playwright
+ bash download_weights.sh
+ bash download_weights.sh
+ curl -fsSL --retry 2 https://media.githubusercontent.com/media/opencv/opencv_zoo/f12e12798e8314f7c074a6656816c048dcc95b7a/models/face_detection_yunet/face_detection_yunet_2023mar.onnx -o data/yunet.onnx
+ echo '8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4 data/yunet.onnx' | sha256sum --check
+ python tools/export_yunet_weights.py data/yunet.onnx weights/yunet_fp32.bin
+ echo 'bf2a36bd1a3be7310a1062a22726a089bfee79c29b3cac16e3ffe568d4433d69 weights/yunet_fp32.bin' | sha256sum --check
+ make test
+ python -m unittest discover -s tests -p 'test_*.py'
+ python tests/check_runtime_backends.py libfacex.so facex-cli weights/yunet_fp32.bin data/edgeface_xs_fp32.bin
+ cc -O2 -Iinclude tests/weights_lifetime.c libfacex.a -Wl,--wrap=malloc,--wrap=free,--wrap=aligned_alloc,--wrap=calloc -lpthread -lm -o "$RUNNER_TEMP/lifetime"
+ "$RUNNER_TEMP/lifetime" data/edgeface_xs_fp32.bin
+ - name: Check the released Nano graph and public C handle
+ run: |
+ curl -fsSL --retry 2 https://github.com/facex-engine/facex/releases/download/facex-nano-1.0/facex_nano.onnx -o data/nano.onnx
+ echo 'bd0094143bb4c7d04a76dcdad4e332f5985847b921ec4d6678c3fd89aaea3889 data/nano.onnx' | sha256sum --check
+ cc -O3 -march=native -shared -fPIC -Iinclude src/facex_mfn.c -lm -o "$RUNNER_TEMP/mfn.so"
+ python tests/check_nano_contract.py data/nano.onnx "$RUNNER_TEMP/mfn.so" "$RUNNER_TEMP/nano.bin"
+ ./example_mfn "$RUNNER_TEMP/nano.bin"
+ - name: Run the distributed package in Chromium and a Web Worker
+ run: |
+ node --input-type=module -e "import * as sdk from './wasm/index.js'; for (const n of ['FaceXSDK','alignFace','LivenessDetector','loadWeightsCached','checkWasmSimd','checkBrowserSupport']) if (typeof sdk[n] !== 'function') throw Error(n); if (!sdk.checkWasmSimd()) throw Error('SIMD')"
+ python tests/check_browser_sdk.py weights/yunet_fp32.bin data/edgeface_xs_fp32.bin --chromium "$(command -v google-chrome)"
+ macos:
+ runs-on: macos-15
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version: '1.22.x'
+ cache: false
+ - name: Run portable FP32 inference on Apple Silicon
+ run: |
+ test "$(uname -m)" = arm64
+ make cli-fp32 CFLAGS="-O3"
+ bash download_weights.sh
+ cd go/facex
+ FACEX_POOL_TEST_EXE="$GITHUB_WORKSPACE/facex-cli-fp32" FACEX_POOL_TEST_WEIGHTS="$GITHUB_WORKSPACE/data/edgeface_xs_fp32.bin" go test -race -v -timeout=90s -run '^TestPoolRealEngine$' -count=1 ./...
+ frvt:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@v4
+ - name: Build the XS adapter and check its public template interface
+ run: |
+ sdk="$RUNNER_TEMP/onnxruntime-linux-x64-1.21.0"
+ sh frvt/prepare_ort.sh "$sdk"
+ cmake -S frvt -B "$RUNNER_TEMP/frvt-build" -DONNXRUNTIME_ROOT="$sdk" -DCMAKE_BUILD_TYPE=Release
+ cmake --build "$RUNNER_TEMP/frvt-build" --parallel 2
+ cmake --install "$RUNNER_TEMP/frvt-build" --prefix "$RUNNER_TEMP/frvt"
+ lib="$RUNNER_TEMP/frvt/lib"
+ c++ -std=c++14 -Ifrvt/include tests/frvt_templates.cpp -L"$lib" -lfrvt_11_facex_001 -Wl,-rpath,"$lib" -Wl,-rpath-link,"$sdk/lib" -o "$RUNNER_TEMP/frvt-templates"
+ LD_LIBRARY_PATH="$sdk/lib" "$RUNNER_TEMP/frvt-templates"
diff --git a/Dockerfile b/Dockerfile
index 3ef1b4e..118bab6 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -16,11 +16,7 @@ COPY include/ include/
COPY Makefile .
# Build the embedding CLI and the shared detector against the runtime libc.
-RUN make cli CFLAGS="-O3 -march=x86-64-v3" && \
- gcc -O3 -march=x86-64-v3 -shared -fPIC -Iinclude -o libfacex.so \
- src/facex.c src/detect.c src/align.c src/transformer_ops.c \
- src/gemm_int8_4x8c8.c src/threadpool.c src/weight_crypto.c -lm -lpthread && \
- strip facex-cli libfacex.so
+RUN make cli libfacex.so CFLAGS="-O3 -march=x86-64-v3" && strip facex-cli libfacex.so
FROM python:3.11-slim-bookworm
RUN pip install --no-cache-dir flask gunicorn pillow numpy
diff --git a/MFN_README.md b/MFN_README.md
index 91b52ea..39d5129 100644
--- a/MFN_README.md
+++ b/MFN_README.md
@@ -1,10 +1,20 @@
-# FaceX MobileFaceNet — 4 size variants, Apache 2.0
+# FaceX MobileFaceNet
-Self-trained Apache-licensed face recognition weights for the FaceX
-runtime. Four size points to fit different hardware budgets, all
-sharing the same parametric C engine.
+Four recognition architectures share a parametric C engine. The C engine takes EFM3 weights. The public Nano download is an ONNX graph.
-## Weights
+## Public Nano release
+
+| Field | Verified value |
+|---|---|
+| Asset | [facex_nano.onnx](https://github.com/facex-engine/facex/releases/download/facex-nano-1.0/facex_nano.onnx), 802,377 bytes |
+| Tag and tagged commit | `facex-nano-1.0`, `88465996e4cdd2e26d2169f5434bfa608a447b42` |
+| SHA-256 | `bd0094143bb4c7d04a76dcdad4e332f5985847b921ec4d6678c3fd89aaea3889` |
+| Input | `input`, float32 `[1,3,112,112]`, aligned RGB, each uint8 channel converted with `(pixel - 127.5) / 128.0` |
+| Output | `embedding`, float32 `[1,256]`, L2 normalized in the graph |
+
+The original release notes described a 512-component output. Inspection and execution of the asset above give 256 components. The training recipe names MS1M-RefineV2. The released metadata does not link this artifact to a specific dataset snapshot and redistribution permission record. [Release](https://github.com/facex-engine/facex/releases/tag/facex-nano-1.0) · [Provenance notes](README.md#licensing-and-provenance)
+
+## Local EFM3 exports
| file | params | INT8 size | FP32 size | MS1M train acc |
|------|-------:|----------:|----------:|---------------:|
@@ -13,9 +23,7 @@ sharing the same parametric C engine.
| `weights/facex_standard.bin` | 968K | ~1 MB | 3.95 MB | 38.2% |
| `weights/facex_xs.bin` | 2.08M | ~2 MB | 8.42 MB | 50.9% |
-All trained from scratch on MS1M-RefineV2 (5.82M images, 85,742 IDs)
-with ArcFace (s=64, m=0.5), AdamW lr=1e-3 cosine, fp32. No upstream
-pretrained weights — fully Apache-licensed.
+These are project training-run figures and estimated storage sizes for the variants. The C loader reads FP32 EFM3 exports.
## Architecture
@@ -42,7 +50,7 @@ Embedding dim: 256 for nano, 512 for the rest.
## .bin format (EFM3)
-Self-describing: a binary header (~80 bytes) names the stage shapes
+A fixed 80-byte binary header describes the stage shapes
and a JSON copy follows it for debugging. The engine reads only the
binary header.
@@ -80,25 +88,24 @@ make mfn-example # tiny "embed + similarity" demo
```c
#include "facex_mfn.h"
-MfnEngine engine;
-mfn_engine_init("weights/facex_standard.bin", &engine);
+MfnEngine *engine = mfn_open("weights/facex_standard.bin");
+if (!engine) return 1;
-int D = mfn_embedding_dim(&engine); // 256 (nano) or 512 (others)
+int D = mfn_embedding_dim(engine); // 256 (nano) or 512 (others)
float emb[512];
-mfn_engine_forward(&engine, input_chw, emb);
+mfn_engine_forward(engine, input_chw, emb);
// input_chw: [3 * 112 * 112] fp32, values in [-1, 1], CHW layout
float sim = mfn_similarity(emb_a, emb_b, D);
-// > 0.3 typically = same person
+// Calibrate the threshold on representative labeled pairs.
-mfn_engine_free(&engine);
+mfn_close(engine);
```
### Image preprocessing
Same as InsightFace: 112×112 RGB, aligned (5-point), `(pixel - 127.5) / 128`,
-CHW layout. You need an external detector (e.g. YuNet bundled in
-`weights/yunet_*.onnx`) to align faces before feeding them in.
+CHW layout. Use a detector such as [YuNet](README.md#build-the-native-runtime) to align faces before feeding them in.
## Verifying a new checkpoint
@@ -113,7 +120,7 @@ Runs the .bin file through a numpy reference implementation of the
same op-graph as the C engine and compares to the PyTorch model. Max
expected error ~1e-5 (round-trip from fp32 file).
-All four shipped models passed verification on commit:
+Previously recorded maximum errors for the four training exports:
```
nano: max_err = 1.28e-05
@@ -124,13 +131,4 @@ xs: max_err = 3.04e-06
## Training from scratch
-See `training/README.md` and `training/RESUME.md` for the dataset prep
-+ training pipeline. Realistic per-arch wall-time on a single RTX 5060
-Ti (16 GB), fp32 training, ArcFace + MS1M:
-
-| arch | epochs | per epoch | total |
-|------|-------:|----------:|------:|
-| nano | 40 | ~37 min | ~25 h |
-| tiny | 35 | ~50 min | ~29 h |
-| standard | 30 | ~80 min | ~40 h |
-| xs | 30 | ~130 min | ~64 h |
+The [training guide](training/README.md) covers dataset preparation, training and EFM3 export. The [run notes](training/RESUME.md) describe the original training environment. Record the architecture, number of images, batch size, precision and accelerator when reporting training throughput.
diff --git a/Makefile b/Makefile
index 8d2d110..324aa80 100644
--- a/Makefile
+++ b/Makefile
@@ -1,11 +1,10 @@
-# FaceX — Fast face embedding library
-# 3ms inference, 7MB binary, zero dependencies
+# FaceX native detection and recognition
#
# Build: make
# Test: make example && ./facex-example
CC ?= gcc
-CFLAGS = -O3 -march=native -mfma -funroll-loops
+CFLAGS ?= -O3 -march=native -funroll-loops
LDFLAGS = -lm -lpthread
ifeq ($(OS),Windows_NT)
@@ -34,23 +33,35 @@ libfacex.a: $(LIBOBJ)
# Standalone CLI (for Go subprocess / testing)
cli: facex-cli$(EXT)
-CLI_SRC = src/edgeface_engine.c src/transformer_ops.c src/threadpool.c src/weight_crypto.c
+CLI_COMMON = src/facex.c src/cli_detect.c src/detect.c src/align.c src/transformer_ops.c src/weight_crypto.c
+CLI_HEADERS = src/edgeface_engine.c src/edgeface_packed.h src/threadpool.h include/facex.h include/detect.h
+CLI_SRC = $(CLI_COMMON) src/threadpool.c src/gemm_int8_4x8c8.c
+FP32_SRC = $(CLI_COMMON) src/threadpool_stub.c
-facex-cli$(EXT): $(CLI_SRC) src/gemm_int8_4x8c8.c
- $(CC) $(CFLAGS) -Iinclude -o $@ $^ $(LDFLAGS)
- @echo "Built facex-cli$(EXT)"
+facex-cli$(EXT): $(CLI_SRC) $(CLI_HEADERS)
+ $(CC) $(CPPFLAGS) $(CFLAGS) -DFACEX_BUILD_CLI -Iinclude -o $@ $(CLI_SRC) $(LDFLAGS)
-# FP32 reference for comparing embeddings across CPU profiles.
cli-fp32: facex-cli-fp32$(EXT)
-facex-cli-fp32$(EXT): $(CLI_SRC)
- $(CC) $(CPPFLAGS) $(CFLAGS) -DFACEX_FP32_ONLY -Iinclude -o $@ $^ $(LDFLAGS)
+facex-cli-fp32$(EXT): $(FP32_SRC) $(CLI_HEADERS)
+ $(CC) $(CPPFLAGS) $(CFLAGS) -DFACEX_BUILD_CLI -DFACEX_FP32_ONLY -Iinclude -o $@ $(FP32_SRC) $(LDFLAGS)
+
+libfacex.so: $(addprefix src/,$(LIBOBJ:.o=.c)) $(CLI_HEADERS)
+ $(CC) $(CPPFLAGS) $(CFLAGS) -shared -fPIC -Iinclude -o $@ $(addprefix src/,$(LIBOBJ:.o=.c)) $(LDFLAGS)
+
+# Rebuild the distributed detector from the native YuNet implementation.
+.PHONY: wasm-detector
+wasm-detector:
+ emcc -O3 -msimd128 -Iinclude src/detect.c -o wasm/detect.js \
+ -sMODULARIZE=1 -sEXPORT_NAME=DetectModule -sALLOW_MEMORY_GROWTH=1 -sFORCE_FILESYSTEM=1 \
+ -sEXPORTED_FUNCTIONS='["_detect_init","_detect_run","_detect_free","_detect_version","_malloc","_free"]' \
+ -sEXPORTED_RUNTIME_METHODS='["FS","cwrap"]' -sENVIRONMENT=web,worker,node
# Example program
example: facex-example$(EXT)
facex-example$(EXT): examples/example.c libfacex.a
- $(CC) $(CFLAGS) -Iinclude -o $@ $< -L. -lfacex $(LDFLAGS)
+ $(CC) $(CFLAGS) -Iinclude -o $@ $^ $(LDFLAGS)
# Encryption tool
encrypt: facex-encrypt$(EXT)
@@ -59,12 +70,16 @@ facex-encrypt$(EXT): src/weight_crypto.c
$(CC) $(CFLAGS) -DWEIGHT_CRYPTO_MAIN -o $@ $< $(LDFLAGS)
.PHONY: check
-check: kernel-test$(EXT) mfn-depthwise-test$(EXT) geometry-test$(EXT) motion-phase-test$(EXT)
+check: nn2-gemm-test$(EXT) kernel-test$(EXT) mfn-depthwise-test$(EXT) geometry-test$(EXT) motion-phase-test$(EXT)
+ ./nn2-gemm-test$(EXT)
./kernel-test$(EXT)
./mfn-depthwise-test$(EXT)
./geometry-test$(EXT)
./motion-phase-test$(EXT)
+nn2-gemm-test$(EXT): tests/nn2_gemm.c nn2/src/gemm.c nn2/src/gemm_res.c nn2/src/pool.c nn2/src/gemm_vector.h nn2/src/fast_exp.h
+ $(CC) $(CFLAGS) -Inn2/include -Inn2/src -o $@ $(filter %.c,$^) $(LDFLAGS)
+
motion-phase-test$(EXT): tests/motion_phase.c nn2/src/motion_gate.c nn2/src/nn2_internal.h nn2/include/nn2.h
$(CC) $(CFLAGS) -Inn2/src -Inn2/include -o $@ tests/motion_phase.c nn2/src/motion_gate.c
@@ -83,13 +98,13 @@ test: check golden-test$(EXT)
@./golden-test$(EXT) data/edgeface_xs_fp32.bin
golden-test$(EXT): tests/golden_test.c libfacex.a
- $(CC) $(CFLAGS) -Iinclude -o $@ $< -L. -lfacex $(LDFLAGS)
+ $(CC) $(CFLAGS) -Iinclude -o $@ $^ $(LDFLAGS)
# Parametric v2 engine (loads EFX2 .bin, supports nano/tiny/standard/xs)
v2-cli: facex-v2$(EXT)
-facex-v2$(EXT): src/edgeface_engine_v2.c src/edgeface_engine.c src/transformer_ops.c src/gemm_int8_4x8c8.c src/threadpool.c
- $(CC) $(CFLAGS) -DV2_STANDALONE -DFACEX_LIB -Iinclude -o $@ $^ $(LDFLAGS)
+facex-v2$(EXT): src/edgeface_packed.h src/edgeface_engine_v2.c src/edgeface_engine.c src/transformer_ops.c src/gemm_int8_4x8c8.c src/threadpool.c
+ $(CC) $(CFLAGS) -DV2_STANDALONE -DFACEX_LIB -Iinclude -o $@ $(filter %.c,$^) $(LDFLAGS)
@echo "Built facex-v2$(EXT)"
# MobileFaceNet engine (loads EFM3 .bin, supports nano/tiny/standard/xs)
@@ -106,12 +121,11 @@ example_mfn$(EXT): examples/example_mfn.c src/facex_mfn.c
$(CC) $(CFLAGS) -Iinclude -o $@ $^ $(LDFLAGS)
@echo "Built example_mfn$(EXT)"
-# Detector static library (Sprint 1+: scaffold only, real engine arrives in
-# later sprints — see docs/plan/detector_plan.md).
+# Standalone YuNet detector library.
detect-lib: libdetect.a
libdetect.a: detect.o
$(AR) rcs $@ $^
clean:
- rm -f libfacex.a libdetect.a facex-cli$(EXT) facex-cli-fp32$(EXT) facex-example$(EXT) facex-encrypt$(EXT) golden-test$(EXT) facex-v2$(EXT) facex-mfn$(EXT) kernel-test$(EXT) mfn-depthwise-test$(EXT) geometry-test$(EXT) motion-phase-test$(EXT) *.o $(LIBOBJ:.o=.d)
+ rm -f libfacex.so libfacex.a libdetect.a facex-cli$(EXT) facex-cli-fp32$(EXT) facex-example$(EXT) facex-encrypt$(EXT) golden-test$(EXT) facex-v2$(EXT) facex-mfn$(EXT) kernel-test$(EXT) mfn-depthwise-test$(EXT) geometry-test$(EXT) motion-phase-test$(EXT) nn2-gemm-test$(EXT) example_mfn$(EXT) *.o $(LIBOBJ:.o=.d)
diff --git a/README.md b/README.md
index c55aacb..74983ce 100644
--- a/README.md
+++ b/README.md
@@ -1,561 +1,124 @@
-<p align="center">
- <img src="docs/logo.jpg" alt="FaceX" width="480">
-</p>
+<p align="center"><img src="docs/logo.jpg" alt="FaceX" width="420"></p>
-<p align="center"><em>Full face pipeline — detect, mesh, recognize, anti-spoof — in pure WebAssembly. Trained from scratch. No cloud, no Python, no server.</em></p>
+# FaceX
-<p align="center">
+FaceX detects faces, aligns them using five landmarks and computes recognition embeddings locally. The default native pipeline pairs YuNet with EdgeFace XS. It is available from C, Go and Python. A separate browser SDK runs the detector and embedder in WebAssembly. The MobileFaceNet models, including Nano ONNX, have their own input and output contracts.
-[![License: Apache 2.0](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE)
-[![LFW](https://img.shields.io/badge/LFW-99.07%25-success.svg)](#benchmarks)
-[![Latency](https://img.shields.io/badge/latency-3.0_ms-brightgreen.svg)](#benchmarks)
-[![Browser](https://img.shields.io/badge/runs-100%25_in_browser-orange.svg)](https://facex-engine.github.io/facex/demo/)
-[![Encryption](https://img.shields.io/badge/weights-AES--256--GCM-purple.svg)](#weight-encryption)
-[![Deps](https://img.shields.io/badge/dependencies-zero-green.svg)](#the-full-surveillance-stack--no-python-no-ffmpeg-no-gpu)
+[Live demo](https://facex-engine.github.io/facex/demo/) · [Releases](https://github.com/facex-engine/facex/releases) · [Python SDK](python/README.md) · [Browser SDK](wasm/README.md) · [Go package](go/facex) · [Benchmarks and experiments](docs/research)
-</p>
+## Choose an integration
-**Full face stack that runs entirely in the browser.** Detection, 98-point landmarks, dense 3D mesh, recognition, and passive anti-spoof — all WebAssembly, zero server, ~17 MB of encrypted weights.
-
-🎬 **[Live Demo →](https://facex-engine.github.io/facex/demo/)** — open in a Chromium browser, press *Start camera*, try all modes.
-📚 **[Docs in Wiki →](https://github.com/facex-engine/facex/wiki)** — Browser quickstart, training recipes, nn2 architecture, encrypted weights, comparison vs alternatives.
-
-<p align="center">
- <img src="docs/pipeline.jpg" alt="FaceX pipeline" width="720">
-</p>
-
-### Everything in the demo is trained by us
-
-| Component | Status | Size | Source |
-|---|---|---|---|
-| Face detector | ✅ **ours** | 401 KB | YuNet-style FCOS, WIDER FACE |
-| 98-point landmark | ✅ **ours** | 1.1 MB | WFLW |
-| 576-point 3D mesh | ✅ **ours** | 5.6 MB | MediaPipe distillation |
-| Recognition (4 sizes) | ✅ **ours** | 0.8–8.4 MB | MobileFaceNet + ArcFace on MS1M, LFW 95.62 → 99.07% (10-fold mean) |
-| Anti-spoof | Apache 2.0 | 2 × 1.7 MB | MiniFASNet (MinivisionAI Silent-Face) |
-
-Weights ship as AES-256-GCM ciphertext and are decrypted in the browser via WebCrypto. This is **not DRM** — a determined attacker can dump the decrypted bytes from the WASM heap. What it does buy you: friction against casual scraping, per-customer key revocation for SaaS deployments, and an audit trail at the key-issuing endpoint. See the [wiki](https://github.com/facex-engine/facex/wiki/Encrypted-Weights) for the threat model and Express / FastAPI integration recipes.
-
----
-
-## The full surveillance stack — no Python, no FFmpeg, no GPU
-
-FaceX is one piece of a larger pure-C stack we built for IP-camera workloads. Every component is hand-written, zero-dependency, **flashable to firmware**:
-
-| Component | What it does | Size | Speed | Replaces |
-|---|---|---|---|---|
-| **NexusDecode** | H.264 + H.265 decoder, RTSP client | **184 KB** | 6,300 fps, **46× FFmpeg** | libav / FFmpeg |
-| **NexusEncode** | H.265/HEVC encoder | ~250 KB | x265-medium quality, 131 fps | x265 |
-| **NXV codec** | Surveillance-tuned video format | 121 KB | **3× smaller** than H.265, instant seek, change-map | H.265 + custom container |
-| **nn2** | YOLOv8 + MiniFASNet inference engine | 520 KB | 8.5 ms @ 320, **1.5–2× ONNX RT** | onnxruntime |
-| **FaceX (this repo)** | Detect + landmarks + embed + spoof | 148 KB native / 17 MB WASM | 3 ms/face | dlib, FaceNet, InsightFace |
-
-**Pipeline numbers (one Intel i5 CPU):**
-- Decode 30 RTSP streams + run YOLO detection on each: **0.56 ms/frame** average → **70 IP cameras on one CPU core** with motion-gating + Kalman tracking.
-- Tiered storage: 70 cams × 90 days = **49 TB → 3.3 TB** (15× savings) with NXV + selective bitstream-only archiving.
-
-**Why it matters:**
-- **Flashable** — entire NVR stack fits in **<2 MB** of binary, ARM/x86/RISC-V, no shared libraries
-- **No FFmpeg** — no GPL contamination, no surface for codec CVEs, no 28 MB of libav `.so` files
-- **Embedded-ready** — runs on $30 SoCs (Allwinner, Rockchip, NXP i.MX), 25 cameras on 27% CPU
-- **Standalone** — every piece can be used alone or combined: decoder → motion gate → detector → tracker → recognizer → archive
-
-### Where it runs
-
-We're not just "x86 only". The same code targets multiple device classes:
-
-| Target | Status | What's used |
+| Goal | Entry point | Data contract |
|---|---|---|
-| **Browser** (any modern Chromium/Firefox/Safari) | ✅ shipping | onnxruntime-web + AES-256-GCM weight decryption ([live demo](https://facex-engine.github.io/facex/demo/)) |
-| **Linux / macOS / Windows x86-64** | ✅ shipping | AVX2 + AVX-512 + VNNI runtime dispatch |
-| **Apple Silicon (M1–M4)** | ✅ in PR #3 | NEON + Accelerate (AMX) + SME on M4+ + Core ML / ANE bridge |
-| **ARM Linux / Android (AArch64)** | ✅ in PR #3 | Hand-written NEON kernels for FP32 GEMM |
-| **NXP i.MX 8 / 93 / 95 NPU** | 🛠️ draft (#3) | Ethos-U65 / VxDelegate / XNNPACK |
-| **Espressif ESP32-P4** (RISC-V + PIE 128) | 🛠️ draft (#3) | ESP-IDF component + MIPI-CSI camera example |
-| **Firmware / bare-metal MCU** | 🛠️ in progress | No `libc` deps in core; PReLU/GEMM/Conv kernels fit in 64 KB SRAM |
-
-Decoder + encoder are pure C99 with x86 SIMD today; ARM/NEON backports for NexusDecode are next.
-
-```c
-// Native C: 3 ms per face
-#include "facex.h"
-FaceX* fx = facex_init("facex_xs.bin", NULL);
-float emb[512];
-facex_embed(fx, face_112x112, emb);
-float sim = facex_similarity(emb_a, emb_b); // >0.3 = same person
-```
-
-```bash
-# Or run the live browser demo locally
-git clone https://github.com/facex-engine/facex
-cd facex/wasm && python -m http.server 8000
-# open http://127.0.0.1:8000/demo_mesh.html
-```
-
----
-
-## What can you build with this?
-
-- **Identity verification (KYC)** — "is this the same person?" from selfie + ID photo, no cloud round-trip
-- **Face login** — unlock apps by face, works offline, no data leaves the device
-- **Access control** — doors, gates, turnstiles on edge hardware without GPU
-- **Proctoring** — verify exam takers are who they claim to be
-- **Smart cameras** — recognize known faces at 300+ faces/sec on a single CPU core
-- **Banking / fintech onboarding** — passive liveness + face match in the browser, GDPR-friendly by construction
-- **In-store kiosks** — VIP/loyalty recognition at the till, runs on a $30 SoC
-
-### Why FaceID with FaceX instead of cloud APIs
-
-You're typically choosing between AWS Rekognition / Azure Face / Google Vision / Paravision / FaceTec ZoOm. Cost comparison for a 100 K-user app doing one face-match per session per day:
-
-| Provider | Price per 1k matches | Monthly cost (100 K MAU × 1/day) | Sends user faces to | Latency |
-|---|---:|---:|---|---:|
-| AWS Rekognition CompareFaces | $1.00 | **$3,000 /mo** | AWS us-east | 250–500 ms |
-| Azure Face API verify | $1.00–$1.50 | **$3,000–$4,500 /mo** | Azure region | 200–400 ms |
-| Google Vision FACE_DETECTION | $1.50 | **$4,500 /mo** | Google datacenter | 200–400 ms |
-| FaceTec ZoOm | per-seat licensed | **$10 K+ /year** | Their SDK, mixed | 1–3 s (active) |
-| **FaceX in your app** | **$0** | **$0** | Nobody — stays in the user's browser | 20–30 ms |
-
-The savings are nice. The bigger story is **compliance**: when frames never leave the device, you're outside GDPR Art. 9 (biometric) / HIPAA / Russia's 152-ФЗ / KZ's data localization rules by construction. No DPIA, no DPA renegotiations, no "where are the photos stored" audit questions.
-
-### Where it's been deployed
-
-We've shipped this stack into IP-camera NVRs, retail kiosks, and KYC flows for fintech clients. If you're evaluating it for production, the live demo is the fastest way to see what it can do — then [open an issue](https://github.com/facex-engine/facex/issues/new) or [email me](mailto:[email protected]) with your use case and I'll help you scope.
-
-## How it works
-
-Full pipeline, every step trained or written by us:
-
-1. **Detect** — own FCOS-style face detector (100K params, trained from
- scratch on WIDER FACE; 401 KB ONNX).
-2. **Align** — 98-point WFLW landmark ConvNet (1.15M params; 1.1 MB ONNX).
-3. **3D mesh** — 576-point face mesh (5.6 MB ONNX), distilled from
- MediaPipe FaceMesh with our 98 WFLW anchors driving the warp.
-4. **Recognize** — MobileFaceNet + ArcFace, four size variants
- (`nano` 0.8 MB · `tiny` 1.8 MB · `standard` 3.9 MB · `xs` 8.4 MB),
- LFW 95.6 → 99.07%.
-5. **Anti-spoof** — MiniFASNet ensemble (V2 @ 2.7 + V1SE @ 4.0),
- MinivisionAI Apache 2.0. Also **ported to our nn2 engine — 2× faster
- than ONNX Runtime** on the same CPU.
+| Detect and recognize faces in an image | [C](include/facex.h) or [Python](python/README.md) | RGB image → boxes, five landmark pairs, optional 512-component EdgeFace embeddings |
+| Handle concurrent recognition requests from Go | [EmbedPool](go/facex/pool.go) | Aligned RGB floats → independent results, with bounded queueing and context cancellation |
+| Detect, align and verify in a browser | [WebAssembly SDK](wasm/README.md) | Canvas, image or video → faces, crops and embeddings. Serve both modules and both weights with the application |
+| Run compact ONNX recognition | [MobileFaceNet Nano](MFN_README.md) | Aligned NCHW float32 → a 256-component unit vector |
+| Search a gallery with several views per identity | [Go](go/facex/identity.go) or [Python](python/README.md#identify-a-person-across-multiple-enrollment-photos) | Maximum cosine across enrolled views per identity, with score and margin thresholds |
+| Try mesh, landmarks, smile and anti-spoofing | [Hosted demo](https://facex-engine.github.io/facex/demo/) | The demo uses separate ONNX models for 98 landmarks, a 478-vertex mesh and Tiny recognition. [Demo sources](docs/demo) |
-Two modes:
-- **Browser:** onnxruntime-web + AES-256-GCM encrypted weights, full
- pipeline in ~25 ms/frame, **no server**.
-- **Native:** pure C, 3 ms per face, INT8 + AVX-512, beats ONNX Runtime
- on the same hardware.
+## Build the native runtime
-Two years of optimization: handwritten AVX2 / AVX-512 / NEON kernels,
-INT8 GEMM, cache-tuned layout, weight-encryption with WebCrypto handoff
-to onnxruntime — every millisecond and every kilobyte fought for.
-
----
-
-## Benchmarks
-
-Measured on Intel i5-11500 (6 cores, AVX-512 + VNNI):
-
-### Speed — recognition (our MobileFaceNet xs)
-
-![Speed comparison](docs/speed_comparison.svg)
-
-| Engine | Median | Min | vs FaceX |
-|--------|-------:|----:|:--------:|
-| **FaceX (native nn2)** | **3.0 ms** | **2.87 ms** | -- |
-| ONNX Runtime 1.23 | 3.9 ms | 3.18 ms | 1.30× slower |
-| InsightFace (R34) | 17 ms | -- | 5.7× slower |
-| FaceNet (PyTorch) | 30 ms | -- | 10× slower |
-| dlib | 50+ ms | -- | 17× slower |
-
-### Speed — anti-spoof (MiniFASNet V2+V1SE ensemble)
-
-Same model, ported to our `nn2` C engine (Apache 2.0, source in [`nn2/`](nn2/)):
-
-| Engine | Single model | Ensemble | Speedup |
-|--------|-------------:|---------:|--------:|
-| **nn2** | **0.70 ms** | **1.43 ms** | -- |
-| ONNX Runtime 1.23 | 1.33 ms | 2.92 ms | **2.03× slower** |
-
-Byte-identical predictions to PyTorch / ONNX on the same input.
-
-### Accuracy — recognition (LFW verification)
-
-All numbers are the **mean accuracy across 10-fold cross-validation**
-(InsightFace-style: tune the threshold on 9 training folds, evaluate
-on the 1 held-out fold, repeat 10 times). The `±` column is the
-standard deviation across folds. Input must be 112×112 ArcFace-aligned
-via a 5-point similarity transform — running on un-aligned crops drops
-accuracy by ~25 points. The eval script is
-[training/scripts/lfw_eval.py](training/scripts/lfw_eval.py).
-
-| Variant | Params | LFW mean | ± std | ONNX size | Speed (CPU) |
-|---------|------:|---------:|------:|----------:|------------:|
-| nano | 0.20 M | 95.62% | 1.11% | 0.8 MB | 1.4 ms |
-| tiny | 0.45 M | 96.85% | 0.87% | 1.8 MB | 2.1 ms |
-| standard | 0.93 M | 98.25% | 0.68% | 3.9 MB | 2.6 ms |
-| **xs** | 2.07 M | **99.07%** | 0.40% | 8.4 MB | 3.0 ms |
-
-### Accuracy — face detection (WIDER FACE val)
-
-Our YuNet-style FCOS detector, 100 K params, trained from scratch:
-
-| Metric | Score |
-|--------|------:|
-| Best recall @ IoU 0.5 (all faces incl. tiny) | 27.5% |
-| Recall on faces ≥ 32 px | ~85% |
-| Recall on webcam-distance faces | ~95% |
-| ONNX size | 401 KB |
-| Latency on 320×320 input | < 1 ms (WASM) |
-
-### Footprint
-
-![Footprint comparison](docs/footprint.svg)
-
-| Metric | FaceX | ONNX Runtime |
-|--------|------:|-------------:|
-| Library size | **148 KB** | 28 MB |
-| Total deploy | **7 MB** | 157 MB |
-| Dependencies | **none** | Python + onnxruntime |
-| Cold start | **~100 ms** | ~350 ms |
-
----
-
-## Quick start
-
-### C
-
-```c
-#include "facex.h"
-
-int main() {
- // Load engine (one-time, ~100ms)
- FaceX* fx = facex_init("facex_xs.bin", NULL);
-
- // Compute embedding (3ms per call)
- float face[112 * 112 * 3]; // RGB, HWC, [-1, 1]
- float embedding[512];
- facex_embed(fx, face, embedding);
-
- // Compare two faces
- float sim = facex_similarity(emb_a, emb_b);
- // sim > 0.3 → same person
-
- facex_free(fx);
-}
-```
+From the repository root on x86-64 Linux, with Make and a C compiler:
-```bash
-gcc -O3 -march=native -Iinclude -o myapp myapp.c -L. -lfacex -lm -lpthread
+```sh
+bash download_weights.sh
+make -j2 all libfacex.so
+make test
```
-### Go
+The download script verifies the EdgeFace checkpoint before installing or reusing it. The default build targets the local CPU. For the portable FP32 reference executable, run `make cli-fp32 CFLAGS="-O3"`. CI builds this executable on Apple Silicon and compares concurrent Go worker replies with serial inference using the released EdgeFace weights. Enroll and score with the same model, preprocessing and runtime mode. Native mixed precision and FP32 can produce different scores.
-```go
-import "github.com/facex-engine/facex/go/facex"
-
-ff, _ := facex.New(facex.Config{
- Exe: "./facex-cli",
- Weights: "./facex_xs.bin",
-})
-defer ff.Close()
-
-embedding, _ := ff.Embed(rgbImage)
-sim := facex.CosSim(embA, embB)
-```
-
-For EdgeFace XS deployments that need close agreement across x86 CPU profiles,
-build the FP32 engine with `make cli-fp32` and set `Config.Exe` to
-`"./facex-cli-fp32"` for either `New` or `NewEmbedPool`. It uses the same
-weights and wire protocol and runs the matrix products without dynamic INT8
-quantization. Use the same engine for enrollment and queries. When switching
-an existing gallery, recompute its templates and validate decision thresholds
-on representative visits. Measure latency on the deployment CPU.
-
-### CLI (any language via stdin/stdout)
-
-```bash
-# Pipe mode: reads 112x112x3 float32 HWC, writes 512 float32
-./facex-cli weights.bin --server < faces.raw > embeddings.raw
-```
-
-### Browser (via onnxruntime-web + AES decryption)
-
-```html
-<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ort.min.js"></script>
-<script>
- // Fetch encrypted weights, decrypt in WebCrypto, hand bytes to ORT.
- const buf = new Uint8Array(await (await fetch('facex_xs.enc')).arrayBuffer());
- const iv = buf.subarray(0, 12), data = buf.subarray(12);
- const key = await crypto.subtle.importKey('raw', KEY_BYTES,
- {name:'AES-GCM'}, false, ['decrypt']);
- const onnx = new Uint8Array(await crypto.subtle.decrypt({name:'AES-GCM', iv}, key, data));
- const sess = await ort.InferenceSession.create(onnx, { executionProviders: ['wasm'] });
- // Inference is 100% client-side. Frames never leave the device.
-</script>
-```
-
-Full browser pipeline (detect + 576pt mesh + recognize + anti-spoof)
-is **live at https://facex-engine.github.io/facex/demo/** — open it,
-press *Start camera*, try the picker.
-
----
-
-## Build
-
-```bash
-make # builds libfacex.a + facex-cli
-make example # builds and runs example
-make encrypt # builds weight encryption tool
-```
-
-Requirements: GCC with AVX2 support. Nothing else.
-
-### Cross-compile for Linux (from WSL)
-
-```bash
-gcc -O3 -march=x86-64-v3 -mavx2 -mfma -static \
- -DFACEX_LIB -o libfacex.a src/*.c -lm -lpthread
-```
-
----
-
-## API
-
-```c
-// Initialize engine. Returns NULL on error.
-// license_key: NULL for plain weights, or key string for AES-256 encrypted.
-FaceX* facex_init(const char* weights_path, const char* license_key);
-
-// Compute 512-dim face embedding from 112x112 RGB image.
-// rgb_hwc: float32 array [112][112][3], values in [-1, 1].
-// embedding: output buffer, 512 floats (L2-normalized).
-int facex_embed(FaceX* fx, const float* rgb_hwc, float embedding[512]);
-
-// Cosine similarity between two embeddings. Range [-1, 1].
-float facex_similarity(const float emb1[512], const float emb2[512]);
-
-// Free engine resources.
-void facex_free(FaceX* fx);
-
-// Version string.
-const char* facex_version(void);
-```
-
----
-
-## Architecture (recognition, MobileFaceNet xs)
+To enable detection, export the March 2023 OpenCV Zoo YuNet model from this pinned revision:
+```sh
+python -m pip install numpy onnx
+curl -fL https://media.githubusercontent.com/media/opencv/opencv_zoo/f12e12798e8314f7c074a6656816c048dcc95b7a/models/face_detection_yunet/face_detection_yunet_2023mar.onnx -o data/yunet.onnx
+python tools/export_yunet_weights.py data/yunet.onnx weights/yunet_fp32.bin
```
-Input: 112×112 RGB float32 in [-1, 1]
- ↓
- Stem: Conv 3×3 s=2 → 64 ch, PReLU
- ↓
- DW Stem: DW 3×3 s=1 → 64 ch, PReLU
- ↓
- Stage 1: 5× Inverted-Residual (t=2, c=64, first s=2)
- ↓
- Stage 2: 1× Inverted-Residual (t=4, c=128, s=2)
- ↓
- Stage 3: 6× Inverted-Residual (t=2, c=128, s=1)
- ↓
- Stage 4: 1× Inverted-Residual (t=4, c=128, s=2)
- ↓
- Stage 5: 2× Inverted-Residual (t=2, c=128, s=1)
- ↓
- Conv 1×1 → 512 ch, PReLU
- ↓
- GDConv DW 7×7 s=1 (linear-GDC) → 512×1×1
- ↓
- 1×1 conv → 512-d embedding, BN, L2-norm
- ↓
-Output: 512-dim unit embedding
-```
-
-**Engine internals:**
-- Pure C99 + SIMD intrinsics (AVX2, FMA, AVX-512, VNNI)
-- INT8 quantized GEMM with `vpmaddubsw` (AVX2) / `vpdpbusd` (VNNI)
-- FP32 packed column-panel MatMul (NR = 8 AVX2, NR = 16 AVX-512)
-- Custom thread pool with work-stealing (WaitOnAddress / futex)
-- Pre-packed weights at load time for cache-optimal access
-- BN folded into preceding Conv at export time
-- AES-256-GCM weight encryption with WebCrypto handoff in the browser,
- AES-256-CTR with hardware binding for native deployments
-- Fully shared op library between recognition, anti-spoof (MiniFASNet),
- and YOLOv8 detection (`nn2`)
+| File | Bytes | SHA-256 |
+|---|---:|---|
+| [EdgeFace XS, v1.0.0](https://github.com/facex-engine/facex/releases/download/v1.0.0/edgeface_xs_fp32.bin) | 7,133,584 | `d23f7b3cf8bcda5e451b48cf012e7dc6c4963d5703fafb8893f956d0203691d8` |
+| YuNet source ONNX for the command above | 232,589 | `8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4` |
+| Exported YuNet binary | 212,940 | `bf2a36bd1a3be7310a1062a22726a089bfee79c29b3cac16e3ffe568d4433d69` |
+| [MobileFaceNet Nano, facex-nano-1.0](https://github.com/facex-engine/facex/releases/download/facex-nano-1.0/facex_nano.onnx) | 802,377 | `bd0094143bb4c7d04a76dcdad4e332f5985847b921ec4d6678c3fd89aaea3889` |
----
+## Run the detector and embedder
-## Weight encryption
+With both weights installed, try the included photo:
-For commercial deployment with IP protection:
+```sh
+python -m pip install -e './python[image]'
+python - <<'PY'
+import numpy as np
+from PIL import Image
+from facex import FaceX
-```bash
-# Encrypt weights (binds to target machine hardware)
-./facex-encrypt encrypt weights.bin weights.enc "LICENSE-KEY"
-
-# Load encrypted weights
-FaceX* fx = facex_init("weights.enc", "LICENSE-KEY");
+rgb = np.asarray(Image.open("data/test_face.jpg").convert("RGB"))
+with FaceX(embed_weights="data/edgeface_xs_fp32.bin",
+ detect_weights="weights/yunet_fp32.bin",
+ input_policy="rectangle_bgr") as fx:
+ for face in fx.detect(rgb):
+ print(face["bbox"], face["score"], face["embedding"].shape)
+PY
```
-Wrong key or different machine → load fails. Original weights never
-touch disk in plaintext on the target machine.
-
----
-
-## Integration paths
-
-| Language | Method | Latency |
-|----------|--------|:-------:|
-| **C / C++** | `libfacex.a` + `facex.h` | 3 ms (native) |
-| **Browser** | `facex.wasm` (48 KB) | 7 ms (WASM SIMD) |
-| **Go** | `go/facex` subprocess | ~4 ms |
-| **Python** | subprocess / ctypes | ~4 ms |
-| **Any** | `facex-cli --server` stdin/stdout | ~4 ms |
-
----
-
-## Limitations
-
-- **Native build** — currently x86-64 (AVX2 / AVX-512 / VNNI). ARM NEON
- paths exist in `nn2/src/gemm_neon.h`; full ARM build script is on the
- roadmap, ESP32 / RISC-V PIE 128 next.
-- **Browser pipeline** — uses `onnxruntime-web` with WebCrypto-decrypted
- ONNX. WebGPU backend is supported by ORT but not yet wired into the
- demo; would drop inference by another 3–5×.
-- **Anti-spoof** is the only non-our component (MiniFASNet, Apache 2.0,
- MinivisionAI). Training a fully-own anti-spoof needs a commercial
- attack dataset, which we don't have.
-
----
-
-## Models
-
-Every recognition / detection / landmark model in this repo was trained
-from scratch by us. Anti-spoof is the only third-party piece.
-
-### Recognition (our MobileFaceNet variants)
-
-Standard MobileFaceNet (Chen et al. 2018) topology, width-scaled
-to four sizes, ArcFace head with the numerically-stable
-angle-addition margin, trained on MS1M-RefineV2 with bf16 autocast.
+Pass `embeddings=False` for geometry only. Rectangle modes preserve the aspect ratio and return coordinates in the original image. The [Python integration guide](python/README.md) covers small faces, tracked video frames, gallery search and the REST API.
-| Variant | Params | Width mult | Embedding dim | LFW |
-|---------|------:|-----------:|--------------:|----:|
-| nano | 0.20 M | 0.36 | 256 | 95.62% |
-| tiny | 0.45 M | 0.55 | 512 | 96.85% |
-| standard | 0.93 M | 0.90 | 512 | 98.25% |
-| xs | 2.07 M | 1.35 | 512 | 99.07% |
+To run the REST service from the same checkout on x86-64 Linux, mount both verified weights at the container's default paths. The image serves `GET /health` and `POST /detect`, `/embed` and `/compare`.
-### Face detector (ours)
-
-YuNet-inspired, but FCOS-style anchor-free. MobileNetV2-lite backbone,
-3 detection heads at strides 8 / 16 / 32, GIoU bbox loss + focal cls
-loss. 100 K params, 401 KB ONNX. Trained on WIDER FACE.
-
-### 98-point landmarks (ours, WFLW)
-
-MobileFaceNet-style backbone + dense head, 1.15 M params. Final NME
-on WFLW val: 4.85% (test) / 5.95% (large-pose subset).
-
-### 576-point 3D mesh (ours, MediaPipe distillation)
-
-Same architecture as the 98-point model, but with `Linear(256, 478*3)`
-head — distilled from MediaPipe FaceMesh pseudo-labels with TPS-rendered
-supervision over our WFLW frontalised crops. Error: xy 0.54 px, z 0.51
-(normalized) on held-out val. With 98 WFLW anchors driving the
-non-rigid warp, the rendered mesh has **576 visible points** total.
-
-### Anti-spoof (MiniFASNet, Apache 2.0, MinivisionAI)
-
-We don't train this — there's no commercial-friendly attack dataset
-publicly available. We port their two-model ensemble (V2 @ 2.7 +
-V1SE @ 4.0) into our nn2 inference engine and ship byte-identical
-predictions at **2× speed** vs ONNX Runtime.
-
----
-
-## Repo layout
-
-```
-include/ — public C API (facex.h, facex_mfn.h, ...)
-src/ — recognition engine + AES weight crypto
-nn2/ — pure-C YOLO + MiniFASNet inference engine
- (1.5–2× ONNX, Apache 2.0)
- src/ — gemm, conv, ops, antispoof_ops, minifasnet
- include/ — public API headers
- tools/ — PyTorch → .bin converters
-wasm/ — browser demo (demo_mesh.html, encrypt tool)
- tools/encrypt_models.py — AES-256-GCM encrypt all .onnx
-docs/demo/ — GitHub Pages live demo + encrypted weights
-training/ — all training pipelines, datasets, exporters
- scripts/ — MobileFaceNet recognition (nano/tiny/standard/xs)
- landmark/ — 98-point WFLW
- landmark3d/ — 576-point MediaPipe distillation
- face_detect/ — own FCOS face detector trained on WIDER FACE
- antispoof/ — MiniFASNet integration
-go/facex/ — Go binding (subprocess protocol)
-python/facex/ — Python binding (ctypes)
+```sh
+docker build -t facex-local .
+docker run --rm -p 127.0.0.1:8080:8080 \
+ -v "$PWD/data/edgeface_xs_fp32.bin:/app/weights/edgeface_xs_fp32.bin:ro" \
+ -v "$PWD/weights/yunet_fp32.bin:/app/weights/yunet_fp32.bin:ro" facex-local
```
----
+In C, call `facex_init(embed_path, detector_path, NULL)` for plain weights. An embedding-only process can pass `NULL` for the detector. `facex_embed` takes an aligned 112 × 112 RGB face in HWC order, scaled to `[-1,1]`, and writes **512 raw float32 components**. Use `facex_similarity` for cosine scoring. Separate handles can run concurrently. Join all calls before freeing a handle. [C API](include/facex.h)
-## FAQ
+In Go, supply the CLI and weights paths in `facex.Config`. `NewEmbedPool(config, workers, maxWaiting)` runs one persistent engine per worker. Size the worker count against the CPU and memory available to the application. [Go binding](go/facex/facex.go) · [Concurrent requests](go/facex/pool.go)
-**Q: Is it really faster than ONNX Runtime?**
-A: Yes. Measured on the same CPU, same model, same input. FaceX median
-3.0 ms vs ONNX Runtime median 3.9 ms. The gap comes from handwritten
-SIMD kernels that avoid framework overhead.
+On a Linux CI runner, eight live native EdgeFace handles, each warmed with one embedding, increased anonymous RSS by a median of **76.6 MiB**, down from **117.9 MiB** at commit `5f10ce0` (three runs per revision). All 135 fixture-crop embeddings matched the previous revision byte for byte within each of the two build modes. These measurements cover model memory and numerical compatibility. [Comparison run](https://github.com/facex-engine/facex/actions/runs/46050152862)
-**Q: What accuracy vs ArcFace-R100?**
-A: Our `xs` (2 M params) is 99.07% LFW vs ArcFace-R100's 99.80%. 0.7%
-of recall for 50× smaller model and 10× faster inference.
+### Binary CLI protocol
-**Q: Can I use this commercially?**
-A: Engine code is Apache 2.0. Our trained recognition, detection,
-landmark, and 3D-mesh weights are **also Apache 2.0** — we own them.
-Only the anti-spoof component (MiniFASNet) is upstream Apache 2.0.
-
-**Q: Does it do face detection?**
-A: Yes. We trained an own FCOS-style detector on WIDER FACE; it
-replaces YuNet in the browser demo and runs in <1 ms.
+| Command | Each input | Each output |
+|---|---|---|
+| `./facex-cli data/edgeface_xs_fp32.bin --server` | 37,632 float32 values, interleaved RGB (HWC), range `[-1,1]` | 512 raw float32 values |
+| `./facex-cli data/edgeface_xs_fp32.bin --batch` | Same dimensions and range, planar RGB (CHW) | 512 raw float32 values |
+| `./facex-cli --detect --pipe --detect-weights weights/yunet_fp32.bin --no-embeddings` | One int32 width, int32 height and packed RGB bytes | int32 face count and that many fixed-size FaceXResult records |
-**Q: Why ONNX in the browser instead of native WASM?**
-A: We went both ways. `nn2` ships a native C engine that is 1.5–2×
-faster than ORT. For the browser, `onnxruntime-web` gives us WebGPU,
-SIMD-WASM, and 3-line model swap without re-compiling. The encryption
-layer (WebCrypto → ORT byte stream) sits between the network and ORT,
-so the model bytes never hit the page as plaintext.
+The embedding commands process complete frames until EOF. Each little-endian request is 150,528 bytes and each reply is 2,048 bytes. Keep diagnostics on stderr.
----
+## Models and measurements
-## Citation
+The released **facex_nano.onnx** has input **input [1,3,112,112]** and output **embedding [1,256]**. Use five-point ArcFace alignment and planar RGB float32. The training and evaluation scripts convert each 8-bit channel with `(pixel - 127.5) / 128.0`. The graph applies L2 normalization. The original release notes listed 512 dimensions. The hash above identifies the 256-dimensional artifact. [Tagged source](https://github.com/facex-engine/facex/tree/88465996e4cdd2e26d2169f5434bfa608a447b42) · [MobileFaceNet guide](MFN_README.md)
-```bibtex
-@software{facex2026,
- author = {Atinov, Baurzhan},
- title = {FaceX: Fast CPU Face Embedding Library},
- year = {2026},
- url = {https://github.com/facex-engine/facex}
-}
-```
+Historical project measurements on LFW used 10 folds. The threshold was selected on nine folds before evaluation on the held-out fold. For deployment, measure false accepts and false rejects on representative labeled pairs. [Evaluation script](training/scripts/lfw_eval.py)
----
+| MobileFaceNet variant | Dimensions | Reported mean LFW accuracy | Fold standard deviation |
+|---|---:|---:|---:|
+| Nano | 256 | 95.62% | 1.11% |
+| Tiny | 512 | 96.85% | 0.87% |
+| Standard | 512 | 98.25% | 0.68% |
+| XS | 512 | 99.07% | 0.40% |
-## License
+The historical **3.0 ms** median on an Intel i5-11500 describes the XS recognition stage. Detection, alignment, gallery search and queueing add to end-to-end latency. The research directory records test conditions and workloads. [Runtime costs](docs/research/facex_runtime_costs.md) · [Concurrent requests](docs/research/multiface_requests.md) · [Detector budgets](docs/research/yunet_pixel_budget.md) · [Numerical comparisons](docs/research/math_25.md)
-Everything in this repo trained or written by us — code, recognition,
-landmarks, 3D mesh, face detector — is [Apache License 2.0](LICENSE).
-Free for commercial use, attribution appreciated.
+## Repository map
-The only third-party component is MiniFASNet (anti-spoof), which is
-also Apache 2.0 from [MinivisionAI Silent-Face-Anti-Spoofing](
-https://github.com/minivision-ai/Silent-Face-Anti-Spoofing).
+| Directory | Contents |
+|---|---|
+| [src](src), [include](include), [examples](examples) | Native libraries, public headers, CLI and C examples. The default EdgeFace engine reads EFXS, the v2 engine reads EFX2 and the MobileFaceNet engine reads EFM3 |
+| [go/facex](go/facex), [python/facex](python/facex), [docker](docker) | Go workers and galleries, Python SDK, REST service |
+| [wasm](wasm), [docs/demo](docs/demo) | Browser package, worker and hosted ONNX demo |
+| [nn2](nn2/README.md) | Independent native object detector and NVR applications |
+| [training](training/README.md) | Recognition training and exports, [landmarks](training/landmark), [3D landmarks](training/landmark3d) and [face detection](training/face_detect) |
+| [tests](tests), [research](docs/research), [GitHub Actions](https://github.com/facex-engine/facex/actions) | Correctness checks, comparison scripts, benchmarks and CI results |
-For commercial licensing: [[email protected]](mailto:[email protected])
+## Licensing and provenance
----
+The top-level license is Apache 2.0. The detector header carries a CC BY-NC-SA 4.0 notice and NN2 has its own license file. Review the notices for the components and third-party assets included in a distribution. [Repository license](LICENSE) · [Detector header](include/detect.h) · [NN2 license](nn2/LICENSE) · [Upstream YuNet model](https://github.com/opencv/opencv_zoo/tree/f12e12798e8314f7c074a6656816c048dcc95b7a/models/face_detection_yunet)
-<p align="center">
- Created by <strong>Baurzhan Atinov</strong> (Kazakhstan)<br>
- <a href="https://github.com/bauratynov">GitHub</a>
-</p>
+The project identifies MS1M-RefineV2 in its recognition training recipe. The public Nano release materials do not identify an immutable dataset snapshot or a dataset permission record tied to the published SHA-256. For questions about commercial bundling, converted weights or redistribution, reference the artifact hash and intended use when requesting records. [Nano release](https://github.com/facex-engine/facex/releases/tag/facex-nano-1.0) · [Maintainer contact](mailto:[email protected])
diff --git a/deploy/build_release.sh b/deploy/build_release.sh
index 03cf1fc..1b93fbf 100644
--- a/deploy/build_release.sh
+++ b/deploy/build_release.sh
@@ -36,11 +36,8 @@ echo " libfacex.a: $(stat -c%s "$OUT/lib/libfacex.a") bytes"
# 2. Build CLI binary
echo "[2/4] Building facex-cli..."
-gcc -O3 -march=x86-64-v3 -mavx2 -mfma -funroll-loops -static \
- -Iinclude -o "$OUT/bin/facex-cli" \
- src/edgeface_engine.c src/transformer_ops.c src/gemm_int8_4x8c8.c \
- src/threadpool.c src/weight_crypto.c \
- -lm -lpthread
+make -B cli CFLAGS="-O3 -march=x86-64-v3 -funroll-loops" LDFLAGS="-static -lm -lpthread"
+cp facex-cli "$OUT/bin/facex-cli"
echo " facex-cli: $(stat -c%s "$OUT/bin/facex-cli") bytes"
# 3. Build encrypt tool
diff --git a/docker/server.py b/docker/server.py
index 3809460..f354565 100644
--- a/docker/server.py
+++ b/docker/server.py
@@ -181,16 +181,22 @@ def embed():
with preparation_slot(_embed_capacity):
f = request.files['file']
- img = Image.open(f.stream).convert('RGB').resize((112, 112))
- arr = np.array(img, dtype=np.float32) / 127.5 - 1.0 # normalize to [-1, 1]
+ try:
+ with Image.open(f.stream) as uploaded:
+ img = uploaded.convert('RGB').resize((112, 112))
+ arr = np.asarray(img, dtype=np.float32)
+ arr /= 127.5
+ arr -= 1
+ except (OSError, ValueError, Image.DecompressionBombError):
+ return jsonify(error='Invalid image'), 400
- t0 = time.time()
+ t0 = time.perf_counter()
try:
emb = embed_in_worker(arr)
except OSError:
app.logger.exception("Embedding worker failed")
return jsonify({"error": "Face embedding unavailable"}), 503
- ms = (time.time() - t0) * 1000
+ ms = (time.perf_counter() - t0) * 1000
return jsonify({
'embedding': emb.tolist(),
@@ -278,4 +284,4 @@ def detect():
if __name__ == '__main__':
- app.run(host='0.0.0.0', port=8080, debug=True)
+ app.run(host='0.0.0.0', port=8080, debug=False)
diff --git a/docs/demo/index.html b/docs/demo/index.html
index 7e4c0f0..1a24f87 100644
--- a/docs/demo/index.html
+++ b/docs/demo/index.html
@@ -3,7 +3,8 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
-<title>FaceX — 576-point face mesh (in-browser, encrypted)</title>
+<title>FaceX face mesh and recognition demo</title>
+<meta name="description" content="Try a 478-vertex face mesh, 98 facial landmarks and local face recognition in your browser.">
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
:root {
@@ -189,18 +190,18 @@
<header class="hero">
<img src="logo.jpg" alt="FaceX">
<div>
- <h1>Face<span>X</span> &mdash; 576-point face mesh</h1>
+ <h1>Face<span>X</span> &mdash; face mesh and recognition</h1>
<div class="tag">Detect &middot; Mesh &middot; Recognize &middot; Anti-spoof &mdash; entirely in your browser</div>
</div>
</header>
<div class="pipeline">
- <span class="chip ours">✦ ours <span class="num">401KB</span> <span class="src">detect</span></span>
- <span class="chip ours">✦ ours <span class="num">1.1MB</span> <span class="src">98pt landmarks</span></span>
- <span class="chip ours">✦ ours <span class="num">5.6MB</span> <span class="src">478pt 3D mesh</span></span>
- <span class="chip ours">✦ ours <span class="num">1.8MB</span> <span class="src">recognition</span></span>
- <span class="chip ours">✦ ours <span class="num">187KB</span> <span class="src">smile</span></span>
- <span class="chip apache">Apache <span class="num">3.4MB</span> <span class="src">anti-spoof</span></span>
+ <span class="chip ours"><span class="num">401 KiB</span> <span class="src">detect</span></span>
+ <span class="chip ours"><span class="num">4.4 MiB</span> <span class="src">98pt landmarks</span></span>
+ <span class="chip ours"><span class="num">5.6 MiB</span> <span class="src">478pt 3D mesh</span></span>
+ <span class="chip ours"><span class="num">1.7 MiB</span> <span class="src">recognition</span></span>
+ <span class="chip ours"><span class="num">187 KiB</span> <span class="src">smile</span></span>
+ <span class="chip apache"><span class="num">3.3 MiB</span> <span class="src">anti-spoof</span></span>
</div>
<div id="status" class="status loading">Loading…</div>
@@ -234,20 +235,20 @@
</div>
<div class="specs">
- <div class="spec"><div class="v">576</div><div class="k">mesh points</div></div>
- <div class="spec"><div class="v">~17 MB</div><div class="k">encrypted weights</div></div>
+ <div class="spec"><div class="v">478</div><div class="k">mesh vertices</div></div>
+ <div class="spec"><div class="v">15.6 MiB</div><div class="k">encrypted weights</div></div>
<div class="spec"><div class="v">AES-256</div><div class="k">WebCrypto-GCM</div></div>
<div class="spec"><div class="v">0 servers</div><div class="k">frames stay local</div></div>
</div>
<div class="info">
- <p><strong>Pipeline.</strong> Every frame: <em>our</em> face detector (FCOS-style, 100K params, trained from scratch on WIDER FACE) → 98-point WFLW landmark ConvNet → 478-point 3D mesh distilled from MediaPipe → 512-dim embedding (MobileFaceNet + ArcFace on MS1M, LFW 96.9%) → MiniFASNet anti-spoof ensemble.</p>
- <p><strong>All custom (except antispoof).</strong> Detector, landmarks, 3D mesh, recognition &mdash; trained from scratch. Only anti-spoof uses MinivisionAI's MiniFASNet under Apache 2.0. Every weight is AES-256-GCM encrypted on disk and decrypted in-browser via WebCrypto.</p>
+ <p>Detection locates the face. The landmark model estimates 98 points, and the 3D model estimates 478 vertices. Face ID uses the Tiny recognition model. The smile and anti-spoofing modes use separate models.</p>
+ <p>Your camera frames are processed locally. The page downloads ONNX Runtime and the encrypted model files at startup. <a href="https://github.com/facex-engine/facex#models-and-measurements">Model details and benchmarks</a></p>
</div>
<div class="footer">
<a href="https://github.com/facex-engine/facex" target="_blank">GitHub</a> &middot;
- Apache 2.0 &middot;
+ <a href="https://github.com/facex-engine/facex#licensing-and-provenance">Licenses and provenance</a> &middot;
Made by <a href="https://github.com/bauratynov" target="_blank">Baurzhan Atinov</a>
</div>
</div>
@@ -275,7 +276,7 @@ let denseLevel = 'full';
let denseTemplate = null; // { T: Float32Array(M*98), levels: {low,mid,full}, M, N }
let frameCount = 0, lastFpsT = performance.now(), fps = 0;
let detectMs = 0, lmMs = 0, recMs = 0;
-let refEmb = null; // 256-dim reference (when locked)
+let refEmb = null; // Tiny reference embedding while locked
let lastSim = null; // most recent cosine similarity to ref
let lastPts2d = null, lastBox = null, lastFaceCount = 0;
let lastLive = null, lastSpoof = null; // P(live), P(spoof) from antispoof model
@@ -753,7 +754,7 @@ function cosSim(a, b) {
return s;
}
-// Run nano recognition on the SAME aligned crop we use for landmarks.
+// Recognition uses the same aligned crop as the landmark model.
// Returns Float32Array of length 256 (already L2-normalized by the model).
// 478-point 3D landmark prediction. Returns Array of [x, y, z] of length 478.
// x, y in pixels of the ORIGINAL video (not normalized), z in roughly [-0.3, 0.3].
diff --git a/docs/index.html b/docs/index.html
index d9de26b..d962f8a 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -2,7 +2,8 @@
<html lang="en">
<head>
<meta charset="UTF-8">
-<title>FaceX</title>
+<title>FaceX browser demo</title>
+<meta name="description" content="Try FaceX face detection, recognition, landmarks and mesh in a browser.">
<meta http-equiv="refresh" content="0; url=demo/">
<link rel="canonical" href="https://facex-engine.github.io/facex/demo/">
<style>
diff --git a/download_weights.sh b/download_weights.sh
index 383acda..df25b0b 100644
--- a/download_weights.sh
+++ b/download_weights.sh
@@ -1,33 +1,35 @@
-#!/bin/bash
-# Download FaceX model weights from GitHub Release
-set -e
+#!/usr/bin/env bash
+# Fetch and verify the EdgeFace XS release used by the native API.
+set -eu
+destination="data/edgeface_xs_fp32.bin"
+source_url="https://github.com/facex-engine/facex/releases/download/v1.0.0/edgeface_xs_fp32.bin"
+expected="d23f7b3cf8bcda5e451b48cf012e7dc6c4963d5703fafb8893f956d0203691d8"
-WEIGHTS_DIR="data"
-WEIGHTS_FILE="$WEIGHTS_DIR/edgeface_xs_fp32.bin"
-RELEASE_URL="https://github.com/facex-engine/facex/releases/download/v1.0.0/edgeface_xs_fp32.bin"
-EXPECTED_SIZE=7133584
+verify() {
+ if command -v sha256sum >/dev/null; then
+ actual=$(sha256sum < "$1") || return 1
+ else
+ actual=$(shasum -a 256 < "$1") || return 1
+ fi
+ [ "${actual%% *}" = "$expected" ]
+}
-if [ -f "$WEIGHTS_FILE" ]; then
- echo "Weights already exist: $WEIGHTS_FILE"
+if [ -f "$destination" ] && verify "$destination"; then
+ echo "Verified $destination"
exit 0
fi
-
-mkdir -p "$WEIGHTS_DIR"
-
-echo "Downloading EdgeFace-XS weights (7 MB)..."
-if command -v curl &> /dev/null; then
- curl -L -o "$WEIGHTS_FILE" "$RELEASE_URL"
-elif command -v wget &> /dev/null; then
- wget -O "$WEIGHTS_FILE" "$RELEASE_URL"
+mkdir -p data
+temporary=$(mktemp "$destination.XXXXXX")
+trap 'rm -f "$temporary"' EXIT
+trap 'exit 1' HUP INT TERM
+if command -v curl >/dev/null; then
+ curl --fail --location --retry 2 --output "$temporary" "$source_url"
else
- echo "Error: curl or wget required"
- exit 1
+ wget -O "$temporary" "$source_url"
fi
-
-# Verify size
-ACTUAL_SIZE=$(stat -c%s "$WEIGHTS_FILE" 2>/dev/null || stat -f%z "$WEIGHTS_FILE" 2>/dev/null)
-if [ "$ACTUAL_SIZE" != "$EXPECTED_SIZE" ]; then
- echo "Warning: expected $EXPECTED_SIZE bytes, got $ACTUAL_SIZE"
-else
- echo "OK: $WEIGHTS_FILE ($ACTUAL_SIZE bytes)"
+if ! verify "$temporary"; then
+ echo "EdgeFace XS checksum verification failed" >&2
+ exit 1
fi
+mv -f "$temporary" "$destination"
+echo "Verified $destination"
diff --git a/examples/example_mfn.c b/examples/example_mfn.c
index c822bb3..707c068 100644
--- a/examples/example_mfn.c
+++ b/examples/example_mfn.c
@@ -6,7 +6,7 @@
* 112x112 RGB face data (values normalized to [-1, 1], CHW layout) to
* get actual face-verification scores.
*
- * Build: make mfn-cli (or)
+ * Build: make mfn-example (or)
* gcc -O3 -march=native -mfma -Iinclude \
* -o example_mfn examples/example_mfn.c src/facex_mfn.c -lm
*
@@ -23,13 +23,12 @@ int main(int argc, char **argv) {
return 1;
}
- MfnEngine engine;
- int rc = mfn_engine_init(argv[1], &engine);
- if (rc != 0) {
- fprintf(stderr, "Failed to load %s (code %d)\n", argv[1], rc);
+ MfnEngine *engine = mfn_open(argv[1]);
+ if (!engine) {
+ fprintf(stderr, "Failed to load %s\n", argv[1]);
return 1;
}
- int D = mfn_embedding_dim(&engine);
+ int D = mfn_embedding_dim(engine);
fprintf(stderr, "Loaded %s, embedding_dim=%d\n", argv[1], D);
/* Two dummy 112x112 RGB inputs, normalized to [-1, 1] (CHW). */
@@ -43,14 +42,19 @@ int main(int argc, char **argv) {
float *emb_a = (float*)malloc(D * sizeof(float));
float *emb_b = (float*)malloc(D * sizeof(float));
- mfn_engine_forward(&engine, img_a, emb_a);
- mfn_engine_forward(&engine, img_b, emb_b);
+ if (!emb_a || !emb_b) {
+ free(emb_a);
+ free(emb_b);
+ mfn_close(engine);
+ return 1;
+ }
+ mfn_engine_forward(engine, img_a, emb_a);
+ mfn_engine_forward(engine, img_b, emb_b);
float sim = mfn_similarity(emb_a, emb_b, D);
fprintf(stdout, "cosine similarity = %.4f\n", sim);
- fprintf(stdout, "(> 0.3 typically means same person)\n");
free(emb_a); free(emb_b);
- mfn_engine_free(&engine);
+ mfn_close(engine);
return 0;
}
diff --git a/frvt/Dockerfile b/frvt/Dockerfile
index a87d05c..d50d501 100644
--- a/frvt/Dockerfile
+++ b/frvt/Dockerfile
@@ -1,4 +1,4 @@
-# Build the FRVT 1:1 .so on the exact OS NIST uses (Ubuntu 20.04 x86_64).
+# Build the FRVT 1:1 adapter with Ubuntu 20.04 and the pinned runtime SDK.
# Run:
# docker build -t facex-frvt-build .
# docker run --rm -v ${PWD}/build:/work/build facex-frvt-build
@@ -8,25 +8,19 @@ FROM ubuntu:20.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
- build-essential cmake wget ca-certificates pkg-config \
+ build-essential cmake curl unzip ca-certificates pkg-config \
gpg gpg-agent \
&& rm -rf /var/lib/apt/lists/*
-# Pin onnxruntime to a stable release.
-ARG ORT_VERSION=1.21.0
-RUN wget -q https://github.com/microsoft/onnxruntime/releases/download/v${ORT_VERSION}/onnxruntime-linux-x64-${ORT_VERSION}.tgz \
- && tar xzf onnxruntime-linux-x64-${ORT_VERSION}.tgz \
- && mv onnxruntime-linux-x64-${ORT_VERSION} /opt/onnxruntime \
- && rm onnxruntime-linux-x64-${ORT_VERSION}.tgz
+COPY prepare_ort.sh /tmp/prepare_ort.sh
+RUN sh /tmp/prepare_ort.sh /opt/onnxruntime
WORKDIR /work
COPY . /work
-CMD bash -c '\
- rm -rf build && mkdir build && cd build && \
- cmake -DONNXRUNTIME_ROOT=/opt/onnxruntime -DCMAKE_BUILD_TYPE=Release .. && \
- cmake --build . --parallel && \
- echo && echo "=== built: $(ls -la libfrvt_11_facex_001.so) ===" && \
- mkdir -p lib && cp libfrvt_11_facex_001.so lib/ && \
- cp /opt/onnxruntime/lib/libonnxruntime.so.* lib/ \
+CMD bash -ec '\
+ cmake -S /work -B /tmp/facex-build -DONNXRUNTIME_ROOT=/opt/onnxruntime -DCMAKE_BUILD_TYPE=Release && \
+ cmake --build /tmp/facex-build --parallel && \
+ cmake --install /tmp/facex-build --prefix /work/build && \
+ cp -a /opt/onnxruntime/lib/libonnxruntime*.so* /work/build/lib/ \
'
diff --git a/frvt/README.md b/frvt/README.md
index 83dc6ed..5a236f0 100644
--- a/frvt/README.md
+++ b/frvt/README.md
@@ -1,148 +1,44 @@
-# FaceX FRVT 1:1 submission
+# FaceX adapter for FRTE 1:1 verification
-Submission package for NIST [FRTE 1:1 Verification](https://pages.nist.gov/frvt/html/frvt11.html).
+This directory implements the NIST FRVT 1:1 interface for Linux x86-64. The adapter uses ONNX Runtime with three model files from the application configuration directory.
-## Architecture
+| File | Purpose |
+|---|---|
+| `facex_detect.onnx` | Face detection on a 320 × 320 input |
+| `facex_landmark.onnx` | 98 landmarks used to derive five alignment points |
+| `facex_xs.onnx` | 512-component XS embedding of an aligned 112 × 112 RGB face |
-```
-NIST testbench
- │ provides Image objects (uint8 24bpp RGB or 8bpp greyscale)
- ▼
-src/facex_frvt.cpp ← Interface implementation
- │
- ▼
-facex_detect.onnx → face detection (FCOS, 320×320, 100K params)
-facex_landmark.onnx → 98-point WFLW landmarks (112×112, 1.15M params)
-facex_xs.onnx → 512-dim L2-normalized embedding (112×112, 2.07M params)
-```
-
-**Template format:** 2053 bytes per face = 4-byte magic `FXT1` +
-1-byte valid flag + 512 × float32 L2-normalized embedding.
-
-**Match:** cosine similarity rescaled to [0, 1000] (NIST treats higher
-as more similar).
-
-## Build (Docker, recommended)
-
-The container reproduces NIST's evaluation environment exactly
-(Ubuntu 20.04, x86-64, AVX2, GCC 9):
-
-```bash
-cd frvt
-docker build -t facex-frvt-build .
-docker run --rm -v ${PWD}/build:/work/build facex-frvt-build
-ls build/lib/libfrvt_11_facex_001.so
-```
+The adapter selects the largest detection in each image and averages embeddings for up to five images of one person. Each 2,053-byte template contains the four-byte `FXT1` header, one validity byte and 512 float32 components. Valid unit embeddings are compared with cosine similarity rescaled to [0, 1000]. The public 256-component Nano model has a different output shape. [Implementation](src/facex_frvt.cpp) · [Nano contract](../MFN_README.md#public-nano-release)
-## Build (WSL Ubuntu)
+## Build on Linux
-```bash
-sudo apt install build-essential cmake
-wget https://github.com/microsoft/onnxruntime/releases/download/v1.21.0/onnxruntime-linux-x64-1.21.0.tgz
-tar xzf onnxruntime-linux-x64-1.21.0.tgz
-export ORT=$PWD/onnxruntime-linux-x64-1.21.0
+Set `ORT` to a Linux x86-64 ONNX Runtime SDK containing `include/` and `lib/`. The example prepares version 1.21.0 from Microsoft’s NuGet package using `curl` and `unzip`. From the repository root:
-cd frvt
-cmake -S . -B build -DONNXRUNTIME_ROOT=$ORT -DCMAKE_BUILD_TYPE=Release
-cmake --build build --parallel
+```sh
+export ORT="$PWD/frvt/ort-sdk"
+sh frvt/prepare_ort.sh "$ORT"
+cmake -S frvt -B frvt/build -DONNXRUNTIME_ROOT="$ORT" -DCMAKE_BUILD_TYPE=Release
+cmake --build frvt/build --parallel
+cmake --install frvt/build --prefix "$PWD/frvt/bundle"
```
-## Prepare the submission package
-
-NIST expects this exact layout:
+The install target produces `frvt/bundle/lib/libfrvt_11_facex_001.so`. To build with the Ubuntu 20.04 container and its pinned ONNX Runtime SDK, use the following commands from the repository root:
-```
-facex_001/
-├── doc/
-│ └── ReleaseNotes.txt
-├── config/
-│ ├── facex_detect.onnx
-│ ├── facex_landmark.onnx
-│ └── facex_xs.onnx
-└── lib/
- ├── libfrvt_11_facex_001.so
- └── libonnxruntime.so.1.21.0
+```sh
+docker build -t facex-frvt-build frvt
+mkdir -p frvt/bundle
+docker run --rm -v "$PWD/frvt/bundle:/work/build" facex-frvt-build
```
-Build the package:
+## Prepare and validate a bundle
-```bash
-mkdir -p facex_001/doc facex_001/config facex_001/lib
-cp ../_unencrypted_backup/facex_{detect,landmark,xs}.onnx facex_001/config/
-cp build/lib/libfrvt_11_facex_001.so facex_001/lib/
-cp build/lib/libonnxruntime.so.* facex_001/lib/
-cat > facex_001/doc/ReleaseNotes.txt <<EOF
-FaceX 1:1 submission — sequence 001
-Built: $(date -u +"%Y-%m-%dT%H:%M:%SZ")
-Models: facex_detect (own, WIDER FACE), facex_landmark (own, WFLW),
- facex_xs (own MobileFaceNet 1.35x width, ArcFace head, MS1M)
-ONNX Runtime: 1.21.0
-EOF
+Place the shared adapter and the matching ONNX Runtime libraries in `lib/`, the three ONNX files in `config/`, and the release notes in `doc/`. Record the model hashes, runtime version and adapter commit so the package can be reproduced.
-tar czf facex_001.tar.gz facex_001/
-```
+The alignment regression covers translation, rotation, border pixels and degenerate landmarks. Run it from the repository root:
-## Validate locally before submission
-
-NIST provides a validation suite at
-[github.com/usnistgov/frvt](https://github.com/usnistgov/frvt) under
-`11/validation/`. Run it against `libfrvt_11_facex_001.so` to catch
-crashes, signature mismatches, and slow runtime:
-
-```bash
-git clone https://github.com/usnistgov/frvt
-cd frvt/11/validation
-./run_validate_11.sh ../../facex_001
+```sh
+c++ -O2 -std=c++11 tests/frvt_alignment.cpp -o /tmp/frvt-alignment
+/tmp/frvt-alignment
```
-It will run a few thousand template-creation and match operations
-and print a pass/fail report. Fix any failures before uploading.
-
-## PGP-sign and submit
-
-NIST requires a PGP-signed tarball uploaded to their SFTP endpoint.
-Steps once your participation agreement is approved:
-
-```bash
-gpg --gen-key # one-time
-gpg --armor --export [email protected] > pubkey.asc # send to NIST
-gpg --output facex_001.tar.gz.sig --detach-sign facex_001.tar.gz
-
-sftp [email protected] # credentials from NIST after agreement
-put facex_001.tar.gz
-put facex_001.tar.gz.sig
-```
-
-## What you (the human) need to do separately
-
-1. **Sign the Participation Agreement.**
- Download from https://pages.nist.gov/frvt/html/frvt11.html → "FRTE/FATE Participation Agreement".
- Fill in name / org / contact, sign (electronic OK), email to
-
-2. **Generate and send PGP key.**
- `gpg --gen-key` once, then email `pubkey.asc` to `[email protected]`.
- They will reply with SFTP credentials.
-
-3. **Wait ~3-6 months** for results to appear on
- https://pages.nist.gov/frvt/html/frvt11.html under "FaceX 001".
-
-4. **Resubmissions** allowed every 4 months. Increment the sequence
- number (`002`, `003`, ...) and rebuild.
-
-## Expected outcome
-
-We submit `xs` (2.07 M params, 99.07% LFW after YuNet 5-pt alignment).
-Realistic position in the table:
-
-| Metric | Expected rank |
-|--------|--------------|
-| FNMR @ FMR=10⁻⁶ (accuracy) | ~top 80-120 of 250+ |
-| Template gen time | top 5-15 (we're CPU-fast) |
-| Match time | top 10 (cosine is trivial) |
-| Template size | 2053 bytes (typical) |
-
-The marketing claim that survives scrutiny:
-**"Fastest open-source CPU face recognition tested by NIST FRVT 2026"**
-— assuming we land top-3 on `Template gen time`, which is very likely
-given our hand-tuned AVX-512 GEMM stack.
+Use the NIST validation harness for the complete package and consult the program for its current submission procedure. An official evaluation result identifies its submission, test population and operating point. The project's historical LFW figures are reported separately. [NIST harness](https://github.com/usnistgov/frvt) · [FRTE 1:1](https://pages.nist.gov/frvt/html/frvt11.html) · [FaceX measurements](../README.md#models-and-measurements)
diff --git a/frvt/prepare_ort.sh b/frvt/prepare_ort.sh
new file mode 100644
index 0000000..59a255c
--- /dev/null
+++ b/frvt/prepare_ort.sh
@@ -0,0 +1,19 @@
+#!/bin/sh
+# Install the Linux x64 C++ SDK from the Microsoft.ML.OnnxRuntime package.
+set -eu
+dest=${1:?Pass the SDK installation directory}
+version=1.21.0
+pkg=microsoft.ml.onnxruntime
+work=$(mktemp -d)
+trap 'rm -rf "$work"' EXIT
+curl -fsSL --retry 2 "https://api.nuget.org/v3-flatcontainer/$pkg/$version/$pkg.$version.nupkg" -o "$work/sdk.nupkg"
+echo '359b4782cfa2e288e6c4bbb9da1c231b085fb8e0d149faf8c3c843f54576559b sdk.nupkg' | (cd "$work" && sha256sum --check)
+unzip -q "$work/sdk.nupkg" 'build/native/include/*' 'runtimes/linux-x64/native/*' -d "$work"
+mkdir -p "$dest/include" "$dest/lib"
+cp -R "$work/build/native/include/." "$dest/include/"
+cp "$work/runtimes/linux-x64/native/libonnxruntime.so" "$dest/lib/libonnxruntime.so.$version"
+ln -sf "libonnxruntime.so.$version" "$dest/lib/libonnxruntime.so.1"
+ln -sf libonnxruntime.so.1 "$dest/lib/libonnxruntime.so"
+for provider in "$work"/runtimes/linux-x64/native/libonnxruntime_providers*.so; do
+ if [ -f "$provider" ]; then cp "$provider" "$dest/lib/"; fi
+done
diff --git a/frvt/src/alignment.hpp b/frvt/src/alignment.hpp
new file mode 100644
index 0000000..d6ff427
--- /dev/null
+++ b/frvt/src/alignment.hpp
@@ -0,0 +1,82 @@
+#ifndef FACEX_FRVT_ALIGNMENT_HPP
+#define FACEX_FRVT_ALIGNMENT_HPP
+#include <algorithm>
+#include <cmath>
+#include <cstddef>
+#include <cstdint>
+
+namespace facex_frvt {
+// ===== Similarity transform (rotation + uniform scale + translation) =====
+// Umeyama algorithm minimizing sum of squared errors between two point sets.
+// Inputs: src[5][2] (detected) and dst[5][2] (template). Output: 2x3 affine M.
+static bool umeyama_5pt(const float src[5][2], const float dst[5][2], float M[6])
+{
+ float src_cx = 0, src_cy = 0, dst_cx = 0, dst_cy = 0;
+ for (int i = 0; i < 5; i++) {
+ src_cx += src[i][0]; src_cy += src[i][1];
+ dst_cx += dst[i][0]; dst_cy += dst[i][1];
+ }
+ src_cx /= 5; src_cy /= 5; dst_cx /= 5; dst_cy /= 5;
+ float a = 0, b = 0, c = 0;
+ for (int i = 0; i < 5; i++) {
+ float sx = src[i][0] - src_cx, sy = src[i][1] - src_cy;
+ float dx = dst[i][0] - dst_cx, dy = dst[i][1] - dst_cy;
+ a += sx*dx + sy*dy;
+ b += sx*dy - sy*dx;
+ c += sx*sx + sy*sy;
+ }
+ if (!(c > 0) || !std::isfinite(c)) return false;
+ float real = a / c, imag = b / c;
+ float det = real * real + imag * imag;
+ if (!(det >= 1e-9f) || !std::isfinite(det)) return false;
+ M[0] = real; M[1] = -imag;
+ M[3] = imag; M[4] = real;
+ M[2] = dst_cx - M[0] * src_cx - M[1] * src_cy;
+ M[5] = dst_cy - M[3] * src_cx - M[4] * src_cy;
+ return std::isfinite(M[2]) && std::isfinite(M[5]);
+}
+
+// Warp 24-bit RGB image into a dst×dst RGB plane using inverse affine + bilinear.
+// We compute the inverse of the 2x3 forward map, then for each dst pixel sample src.
+static void warp_affine_bilinear(
+ const uint8_t* src, int sw, int sh, int sd,
+ uint8_t* dst, int dst_size, const float fwd[6])
+{
+ float det = fwd[0] * fwd[4] - fwd[1] * fwd[3];
+ float inv[6];
+ inv[0] = fwd[4] / det; inv[1] = -fwd[1] / det;
+ inv[3] = -fwd[3] / det; inv[4] = fwd[0] / det;
+ inv[2] = -(inv[0] * fwd[2] + inv[1] * fwd[5]);
+ inv[5] = -(inv[3] * fwd[2] + inv[4] * fwd[5]);
+
+ int channels = (sd == 24) ? 3 : 1;
+ for (int y = 0; y < dst_size; y++) {
+ for (int x = 0; x < dst_size; x++) {
+ float fx = inv[0] * x + inv[1] * y + inv[2];
+ float fy = inv[3] * x + inv[4] * y + inv[5];
+ uint8_t* dp = dst + (y * dst_size + x) * 3;
+ if (!(fx >= 0 && fx < sw && fy >= 0 && fy < sh)) {
+ dp[0] = dp[1] = dp[2] = 0;
+ continue;
+ }
+ int x0 = static_cast<int>(fx), y0 = static_cast<int>(fy);
+ int x1 = std::min(x0 + 1, sw - 1), y1 = std::min(y0 + 1, sh - 1);
+ float wx = fx - x0, wy = fy - y0;
+ const uint8_t* p00 = src + (static_cast<std::size_t>(y0) * sw + x0) * channels;
+ const uint8_t* p01 = src + (static_cast<std::size_t>(y0) * sw + x1) * channels;
+ const uint8_t* p10 = src + (static_cast<std::size_t>(y1) * sw + x0) * channels;
+ const uint8_t* p11 = src + (static_cast<std::size_t>(y1) * sw + x1) * channels;
+ for (int c = 0; c < 3; c++) {
+ int sc = (channels == 3) ? c : 0;
+ float v = (1 - wx) * (1 - wy) * p00[sc]
+ + wx * (1 - wy) * p01[sc]
+ + (1 - wx) * wy * p10[sc]
+ + wx * wy * p11[sc];
+ dp[c] = static_cast<uint8_t>(std::min(255.0f, std::max(0.0f, v + 0.5f)));
+ }
+ }
+ }
+}
+
+} // namespace facex_frvt
+#endif
diff --git a/frvt/src/facex_frvt.cpp b/frvt/src/facex_frvt.cpp
index be777d2..bf27cf7 100644
--- a/frvt/src/facex_frvt.cpp
+++ b/frvt/src/facex_frvt.cpp
@@ -6,8 +6,8 @@
* facex_landmark.onnx — 98-point WFLW landmarks (112x112 RGB)
* facex_xs.onnx — 512-dim recognition embedding (112x112 RGB, L2 normalized)
*
- * Each template is a fixed-size 512 × 4 = 2048-byte L2-normalized float32 vector.
- * Match = cosine similarity rescaled to [0, 1].
+ * Each template is a 5-byte header plus 512 normalized float32 values (2053 bytes).
+ * Match = cosine similarity rescaled to [0, 1000].
*
* Build for Linux x86_64 (NIST evaluation platform):
* cmake -S . -B build -DONNXRUNTIME_ROOT=/path/to/onnxruntime
@@ -15,6 +15,7 @@
* -> libfrvt_11_facex_001.so
*/
+#include "alignment.hpp"
#include "frvt11.h"
#include "frvt_structs.h"
@@ -55,78 +56,6 @@ constexpr int LM_SIZE = 112;
constexpr int REC_SIZE = 112;
constexpr int EMB_DIM = 512;
-// ===== Similarity transform (rotation + uniform scale + translation) =====
-// Umeyama algorithm minimizing sum of squared errors between two point sets.
-// Inputs: src[5][2] (detected) and dst[5][2] (template). Output: 2x3 affine M.
-static void umeyama_5pt(const float src[5][2], const float dst[5][2], float M[6])
-{
- float src_cx = 0, src_cy = 0, dst_cx = 0, dst_cy = 0;
- for (int i = 0; i < 5; i++) {
- src_cx += src[i][0]; src_cy += src[i][1];
- dst_cx += dst[i][0]; dst_cy += dst[i][1];
- }
- src_cx /= 5; src_cy /= 5; dst_cx /= 5; dst_cy /= 5;
- float a = 0, b = 0, c = 0;
- for (int i = 0; i < 5; i++) {
- float sx = src[i][0] - src_cx, sy = src[i][1] - src_cy;
- float dx = dst[i][0] - dst_cx, dy = dst[i][1] - dst_cy;
- a += sx*dx + sy*dy;
- b += sx*dy - sy*dx;
- c += sx*sx + sy*sy;
- }
- float scale = std::hypot(a, b) / std::max(c, 1e-6f);
- float cos_t = a / std::hypot(a, b);
- float sin_t = b / std::hypot(a, b);
- M[0] = scale * cos_t; M[1] = -scale * sin_t;
- M[3] = scale * sin_t; M[4] = scale * cos_t;
- M[2] = dst_cx - M[0] * src_cx - M[1] * src_cy;
- M[5] = dst_cy - M[3] * src_cx - M[4] * src_cy;
-}
-
-// Warp 24-bit RGB image into a dst×dst RGB plane using inverse affine + bilinear.
-// We compute the inverse of the 2x3 forward map, then for each dst pixel sample src.
-static void warp_affine_bilinear(
- const uint8_t* src, int sw, int sh, int sd,
- uint8_t* dst, int dst_size, const float fwd[6])
-{
- float det = fwd[0] * fwd[4] - fwd[1] * fwd[3];
- if (std::fabs(det) < 1e-9f) det = 1e-9f;
- float inv[6];
- inv[0] = fwd[4] / det; inv[1] = -fwd[1] / det;
- inv[3] = -fwd[3] / det; inv[4] = fwd[0] / det;
- inv[2] = -(inv[0] * fwd[2] + inv[1] * fwd[5]);
- inv[5] = -(inv[3] * fwd[2] + inv[4] * fwd[5]);
-
- int channels = (sd == 24) ? 3 : 1;
- for (int y = 0; y < dst_size; y++) {
- for (int x = 0; x < dst_size; x++) {
- float fx = inv[0] * x + inv[1] * y + inv[2];
- float fy = inv[3] * x + inv[4] * y + inv[5];
- int x0 = static_cast<int>(std::floor(fx));
- int y0 = static_cast<int>(std::floor(fy));
- int x1 = x0 + 1, y1 = y0 + 1;
- float wx = fx - x0, wy = fy - y0;
- uint8_t* dp = dst + (y * dst_size + x) * 3;
- if (x0 < 0 || x1 >= sw || y0 < 0 || y1 >= sh) {
- dp[0] = dp[1] = dp[2] = 0;
- continue;
- }
- const uint8_t* p00 = src + (y0 * sw + x0) * channels;
- const uint8_t* p01 = src + (y0 * sw + x1) * channels;
- const uint8_t* p10 = src + (y1 * sw + x0) * channels;
- const uint8_t* p11 = src + (y1 * sw + x1) * channels;
- for (int c = 0; c < 3; c++) {
- int sc = (channels == 3) ? c : 0;
- float v = (1 - wx) * (1 - wy) * p00[sc]
- + wx * (1 - wy) * p01[sc]
- + (1 - wx) * wy * p10[sc]
- + wx * wy * p11[sc];
- dp[c] = static_cast<uint8_t>(std::min(255.0f, std::max(0.0f, v + 0.5f)));
- }
- }
- }
-}
-
// Convert HWC RGB uint8 → CHW float32 normalized (val - 127.5) / 128.
static void hwc_to_chw_norm(const uint8_t* src, int size, float* dst)
{
@@ -154,7 +83,7 @@ static void letterbox_det(const uint8_t* src, int sw, int sh, int sd,
int x0 = static_cast<int>(fx), y0 = static_cast<int>(fy);
if (x0 >= sw) x0 = sw - 1;
if (y0 >= sh) y0 = sh - 1;
- const uint8_t* p = src + (y0 * sw + x0) * channels;
+ const uint8_t* p = src + (static_cast<size_t>(y0) * sw + x0) * channels;
uint8_t* dp = dst + (y * DET_SIZE + x) * 3;
if (channels == 3) {
dp[0] = p[0]; dp[1] = p[1]; dp[2] = p[2];
@@ -170,9 +99,16 @@ struct Detection { float x1, y1, x2, y2, score; };
static float sigmoid(float x) { return 1.0f / (1.0f + std::exp(-x)); }
+static bool float_tensor_size(const Ort::Value& tensor, size_t count)
+{
+ if (!tensor.IsTensor()) return false;
+ auto info = tensor.GetTensorTypeAndShapeInfo();
+ return info.GetElementType() == ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT &&
+ info.GetElementCount() == count;
+}
+
static std::vector<Detection> decode_detector(
const std::vector<Ort::Value>& outs,
- const std::vector<const char*>& names,
float scoreThr = 0.40f)
{
constexpr int STRIDES[3] = {8, 16, 32};
@@ -180,9 +116,10 @@ static std::vector<Detection> decode_detector(
for (int li = 0; li < 3; li++) {
int s = STRIDES[li];
// Outputs are ordered: cls_p3, box_p3, kps_p3, cls_p4, ...
- const float* cls = outs[li * 3 + 0].GetTensorData<float>();
- const float* box = outs[li * 3 + 1].GetTensorData<float>();
int H = DET_SIZE / s, W = DET_SIZE / s, N = H * W;
+ if (!float_tensor_size(outs[li * 3], N) || !float_tensor_size(outs[li * 3 + 1], 4 * N)) return {};
+ const float* cls = outs[li * 3].GetTensorData<float>();
+ const float* box = outs[li * 3 + 1].GetTensorData<float>();
for (int i = 0; i < N; i++) {
float sc = sigmoid(cls[i]);
if (sc < scoreThr) continue;
@@ -245,6 +182,7 @@ public:
bool detect_align(const Image& img,
float kps[5][2], float bbox[4]) const
{
+ if (!img.data || !img.width || !img.height || (img.depth != 8 && img.depth != 24)) return false;
// 1) Detect at 320×320 letterbox
std::vector<uint8_t> letter(DET_SIZE * DET_SIZE * 3);
float scale; letterbox_det(img.data.get(), img.width, img.height, img.depth,
@@ -264,7 +202,7 @@ public:
};
auto outs = det_->Run(Ort::RunOptions{nullptr}, &inName, &inTensor, 1,
outNames.data(), outNames.size());
- auto dets = decode_detector(outs, outNames);
+ auto dets = decode_detector(outs);
if (dets.empty()) return false;
// Pick largest face
@@ -293,7 +231,7 @@ public:
float fy_ = sy + (y + 0.5f) * side / LM_SIZE;
int xi = std::max(0, std::min(img.width - 1, static_cast<int>(fx_)));
int yi = std::max(0, std::min(img.height - 1, static_cast<int>(fy_)));
- const uint8_t* p = img.data.get() + (yi * img.width + xi) * channels;
+ const uint8_t* p = img.data.get() + (static_cast<size_t>(yi) * img.width + xi) * channels;
uint8_t* dp = faceCrop.data() + (y * LM_SIZE + x) * 3;
if (channels == 3) { dp[0] = p[0]; dp[1] = p[1]; dp[2] = p[2]; }
else { dp[0] = dp[1] = dp[2] = p[0]; }
@@ -308,6 +246,7 @@ public:
const char* lmOutName = "landmarks"; // model exports a single (1, 196) tensor
auto lmOuts = lm_->Run(Ort::RunOptions{nullptr}, &lmInName, &lmTensor, 1,
&lmOutName, 1);
+ if (!float_tensor_size(lmOuts[0], 196)) return false;
const float* lmData = lmOuts[0].GetTensorData<float>();
// 98 (x, y) in [0, 1] of the cropped 112×112 → map back to original
auto cropToOrig = [&](float xc, float yc, float out[2]) {
@@ -333,9 +272,9 @@ public:
bool extract_embedding(const Image& img, const float kps[5][2], float emb[EMB_DIM]) const
{
float M[6];
- umeyama_5pt(kps, ARC_TEMPLATE, M);
+ if (!facex_frvt::umeyama_5pt(kps, ARC_TEMPLATE, M)) return false;
std::vector<uint8_t> aligned(REC_SIZE * REC_SIZE * 3);
- warp_affine_bilinear(img.data.get(), img.width, img.height, img.depth,
+ facex_frvt::warp_affine_bilinear(img.data.get(), img.width, img.height, img.depth,
aligned.data(), REC_SIZE, M);
std::vector<float> recInput(3 * REC_SIZE * REC_SIZE);
hwc_to_chw_norm(aligned.data(), REC_SIZE, recInput.data());
@@ -346,11 +285,13 @@ public:
mem, recInput.data(), recInput.size(), shape.data(), shape.size());
const char* in = "input"; const char* out = "embedding";
auto outs = rec_->Run(Ort::RunOptions{nullptr}, &in, &t, 1, &out, 1);
+ if (!float_tensor_size(outs[0], EMB_DIM)) return false;
const float* e = outs[0].GetTensorData<float>();
// re-normalize defensively
float norm = 0;
for (int i = 0; i < EMB_DIM; i++) norm += e[i] * e[i];
- norm = std::sqrt(std::max(norm, 1e-12f));
+ if (!(norm > 0) || !std::isfinite(norm)) return false;
+ norm = std::sqrt(norm);
for (int i = 0; i < EMB_DIM; i++) emb[i] = e[i] / norm;
return true;
}
@@ -377,16 +318,30 @@ static void pack_template(const float* emb, bool valid, std::vector<uint8_t>& ou
std::memcpy(out.data() + 5, emb, EMB_DIM * sizeof(float));
}
-static bool unpack_template(const std::vector<uint8_t>& t, bool& valid, const float*& emb)
+static bool unpack_template(const std::vector<uint8_t>& t, bool& valid, std::array<float, EMB_DIM>& emb)
{
if (t.size() != TEMPL_SIZE) return false;
uint32_t m; std::memcpy(&m, t.data(), 4);
- if (m != TEMPL_MAGIC) return false;
+ if (m != TEMPL_MAGIC || t[4] > 1) return false;
valid = (t[4] == 1);
- emb = reinterpret_cast<const float*>(t.data() + 5);
+ std::memcpy(emb.data(), t.data() + 5, EMB_DIM * sizeof(float));
return true;
}
+static EyePair eyes_for_image(const Image& image, const float kps[5][2])
+{
+ // The first ArcFace landmark is on the left of the image, the subject's right.
+ auto inside = [&](const float p[2]) {
+ return p[0] >= 0 && p[0] < image.width && p[1] >= 0 && p[1] < image.height;
+ };
+ bool left = inside(kps[1]), right = inside(kps[0]);
+ return EyePair(left, right,
+ left ? static_cast<uint16_t>(kps[1][0]) : 0,
+ left ? static_cast<uint16_t>(kps[1][1]) : 0,
+ right ? static_cast<uint16_t>(kps[0][0]) : 0,
+ right ? static_cast<uint16_t>(kps[0][1]) : 0);
+}
+
// ===== Concrete Interface implementation =====
class FaceXFRVT : public FRVT_11::Interface {
public:
@@ -418,16 +373,12 @@ public:
engine_.extract_embedding(faces[i], kps, emb)) {
for (int j = 0; j < EMB_DIM; j++) sum[j] += emb[j];
valid_n++;
- eyeCoordinates.emplace_back(
- true, true,
- static_cast<uint16_t>(kps[0][0]),
- static_cast<uint16_t>(kps[0][1]),
- static_cast<uint16_t>(kps[1][0]),
- static_cast<uint16_t>(kps[1][1]));
+ eyeCoordinates.push_back(eyes_for_image(faces[i], kps));
} else {
eyeCoordinates.emplace_back();
}
}
+ eyeCoordinates.resize(faces.size());
// L2-normalize the sum
float norm = 0;
for (int j = 0; j < EMB_DIM; j++) norm += sum[j] * sum[j];
@@ -450,6 +401,8 @@ public:
std::vector<std::vector<uint8_t>>& templs,
std::vector<EyePair>& eyeCoordinates) override
{
+ templs.clear();
+ eyeCoordinates.clear();
// Single-image multi-face path. We currently detect+template the largest face.
float kps[5][2], bbox[4], emb[EMB_DIM];
std::vector<uint8_t> t;
@@ -457,12 +410,7 @@ public:
engine_.extract_embedding(image, kps, emb)) {
pack_template(emb, true, t);
templs.push_back(t);
- eyeCoordinates.emplace_back(
- true, true,
- static_cast<uint16_t>(kps[0][0]),
- static_cast<uint16_t>(kps[0][1]),
- static_cast<uint16_t>(kps[1][0]),
- static_cast<uint16_t>(kps[1][1]));
+ eyeCoordinates.push_back(eyes_for_image(image, kps));
} else {
float zero[EMB_DIM] = {0};
pack_template(zero, false, t);
@@ -477,7 +425,8 @@ public:
const std::vector<uint8_t>& enroll,
double& score) override
{
- bool va, ea; const float* e1; const float* e2;
+ bool va, ea;
+ std::array<float, EMB_DIM> e1, e2;
if (!unpack_template(verif, va, e1) || !unpack_template(enroll, ea, e2)) {
score = -1;
return ReturnStatus(ReturnCode::TemplateFormatError);
@@ -489,7 +438,11 @@ public:
double dot = 0;
for (int i = 0; i < EMB_DIM; i++) dot += static_cast<double>(e1[i]) * e2[i];
// Map cosine [-1, 1] → [0, 1] then to [0, 1000] for higher-resolution score
- score = (dot + 1.0) * 500.0;
+ if (!std::isfinite(dot)) {
+ score = -1;
+ return ReturnStatus(ReturnCode::TemplateFormatError);
+ }
+ score = (std::max(-1.0, std::min(1.0, dot)) + 1.0) * 500.0;
return ReturnStatus(ReturnCode::Success);
}
diff --git a/go/facex/facex.go b/go/facex/facex.go
index 8e4c894..581786b 100644
--- a/go/facex/facex.go
+++ b/go/facex/facex.go
@@ -48,11 +48,13 @@ type Config struct {
// FaceX is a persistent subprocess wrapping facex-cli --server.
type FaceX struct {
- cmd *exec.Cmd
- stdin io.WriteCloser
- stdout io.ReadCloser
- mu sync.Mutex
- closed bool
+ inputBuf []byte
+ outputBuf [OutputBytes]byte
+ cmd *exec.Cmd
+ stdin io.WriteCloser
+ stdout io.ReadCloser
+ mu sync.Mutex
+ closed bool
}
// defaultExe returns the right binary name for the current OS.
@@ -77,9 +79,15 @@ func New(cfg Config) (*FaceX, error) {
if cfg.Weights == "" {
cfg.Weights = "data/edgeface_xs_fp32.bin"
}
+ if cfg.Workdir == "" && filepath.Base(cfg.Exe) != cfg.Exe {
+ exe, err := filepath.Abs(cfg.Exe)
+ if err != nil {
+ return nil, err
+ }
+ cfg.Exe = exe
+ }
if cfg.Workdir == "" {
- abs, _ := filepath.Abs(cfg.Exe)
- cfg.Workdir = filepath.Dir(abs)
+ cfg.Workdir = filepath.Dir(cfg.Exe)
}
cmd := exec.Command(cfg.Exe, cfg.Weights, "--server")
@@ -101,11 +109,11 @@ func New(cfg Config) (*FaceX, error) {
_ = stdout.Close()
return nil, err
}
- return &FaceX{cmd: cmd, stdin: stdin, stdout: stdout}, nil
+ return &FaceX{cmd: cmd, stdin: stdin, stdout: stdout, inputBuf: make([]byte, InputBytes)}, nil
}
// Embed runs a single forward pass. input must be exactly 3*112*112 floats
-// in HWC order, range [-1, 1]. Returns a 512-float L2-normalized embedding.
+// in HWC order, range [-1, 1]. Returns 512 raw EdgeFace XS components. Use CosSim for cosine scoring.
func (fx *FaceX) Embed(input []float32) ([]float32, error) {
if len(input) != InputSize {
return nil, fmt.Errorf("input length %d != expected %d", len(input), InputSize)
@@ -115,14 +123,14 @@ func (fx *FaceX) Embed(input []float32) ([]float32, error) {
if fx.closed {
return nil, fmt.Errorf("facex: subprocess already closed")
}
- buf := make([]byte, InputBytes)
+ buf := fx.inputBuf
for i, v := range input {
binary.LittleEndian.PutUint32(buf[i*4:], math.Float32bits(v))
}
if _, err := fx.stdin.Write(buf); err != nil {
return nil, fmt.Errorf("stdin write: %w", err)
}
- outBuf := make([]byte, OutputBytes)
+ outBuf := fx.outputBuf[:]
if _, err := io.ReadFull(fx.stdout, outBuf); err != nil {
return nil, fmt.Errorf("stdout read: %w", err)
}
@@ -133,8 +141,11 @@ func (fx *FaceX) Embed(input []float32) ([]float32, error) {
return out, nil
}
-// CosSim returns the cosine similarity of two embeddings.
+// CosSim returns cosine similarity, zero for a zero vector, and NaN for mismatched lengths.
func CosSim(a, b []float32) float32 {
+ if len(a) != len(b) {
+ return float32(math.NaN())
+ }
var dot, na, nb float64
for i := range a {
dot += float64(a[i]) * float64(b[i])
diff --git a/go/facex/pool_test.go b/go/facex/pool_test.go
index b88692a..9c23e9e 100644
--- a/go/facex/pool_test.go
+++ b/go/facex/pool_test.go
@@ -211,3 +211,38 @@ func TestPoolRealEngine(t *testing.T) {
}
wg.Wait()
}
+
+func TestRelativeExecutableKeepsIndependentResults(t *testing.T) {
+ t.Setenv("FACEX_POOL_TEST_CHILD", "1")
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cwd, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ relative, err := filepath.Rel(cwd, exe)
+ if err != nil {
+ t.Skipf("cannot form relative path: %v", err)
+ }
+ fx, err := New(Config{Exe: relative})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer fx.Close()
+ first, err := fx.Embed(poolInput(1))
+ if err != nil {
+ t.Fatal(err)
+ }
+ second, err := fx.Embed(poolInput(2))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if first[0] != 1 || second[0] != 2 {
+ t.Fatal("a later request overwrote an earlier result")
+ }
+ if !math.IsNaN(float64(CosSim(first, second[:1]))) {
+ t.Fatal("mismatched dimensions should return NaN")
+ }
+}
diff --git a/include/detect.h b/include/detect.h
index 43c923b..aa57c07 100644
--- a/include/detect.h
+++ b/include/detect.h
@@ -1,11 +1,11 @@
/*
- * FaceX Detect — Tiny INT8 face detector.
+ * FaceX Detect — YuNet FP32 face detector.
*
- * YuNet architecture (53K params), ~28 KB WASM engine, ~52 KB INT8 weights.
+ * YuNet architecture (53K params), 212,940-byte exported YNET weights.
* Outputs bbox + 5 keypoints (ArcFace ordering) for downstream alignment.
*
* Usage:
- * Detect* det = detect_init("det_500m_int8.bin");
+ * Detect* det = detect_init("yunet_fp32.bin");
* DetectFace faces[10];
* int n = detect_run(det, rgb_160x160, 160, 160, faces, 10);
* detect_free(det);
@@ -44,7 +44,7 @@ typedef struct {
/*
* Initialize detector engine.
- * weights_path: path to INT8 weight file (.bin).
+ * weights_path: path to exported YuNet FP32 weight file (.bin).
* Returns: engine handle, or NULL on error.
*/
Detect* detect_init(const char* weights_path);
diff --git a/include/facex.h b/include/facex.h
index a0ee2c3..13bc73d 100644
--- a/include/facex.h
+++ b/include/facex.h
@@ -2,13 +2,12 @@
* FaceX — Face detection + recognition library.
*
* Detect faces, compute embeddings, compare — all in one API.
- * 3ms embedding, 4ms detection, zero dependencies.
*
* Usage:
* FaceX* fx = facex_init("embed.bin", "detect.bin", NULL);
* FaceXResult results[10];
* int n = facex_detect(fx, rgb, width, height, results, 10);
- * float sim = facex_similarity(results[0].embedding, ref_embedding);
+ * if (n > 0) printf("%f\n", facex_similarity(results[0].embedding, ref_embedding));
* facex_free(fx);
*
* https://github.com/facex-engine/facex
@@ -25,7 +24,8 @@
extern "C" {
#endif
-/* Opaque handle */
+/* Calls on one handle protect its scratch storage. Separate handles may run concurrently.
+ * Wait for all callers before freeing a handle. */
typedef struct FaceX FaceX;
/* Detection + embedding result for one face */
@@ -33,7 +33,7 @@ typedef struct {
float x1, y1, x2, y2; /* bbox in input pixel coords */
float score; /* detection confidence [0,1] */
float kps[10]; /* 5 keypoints (x,y) pairs: left_eye, right_eye, nose, left_mouth, right_mouth */
- float embedding[512]; /* 512-dim L2-normalized embedding */
+ float embedding[512]; /* 512 raw EdgeFace XS components */
} FaceXResult;
/*
diff --git a/include/facex_mfn.h b/include/facex_mfn.h
index 0bf54ef..f5edc22 100644
--- a/include/facex_mfn.h
+++ b/include/facex_mfn.h
@@ -21,6 +21,10 @@ extern "C" {
/* Opaque handle (defined in facex_mfn.c). */
typedef struct MfnEngine MfnEngine;
+/* Owning API. NULL indicates a load error. */
+MfnEngine *mfn_open(const char *path);
+void mfn_close(MfnEngine *engine);
+
/*
* Initialize from EFM3 weights file.
* path: path to .bin
@@ -45,7 +49,7 @@ int mfn_embedding_dim(const MfnEngine *engine);
/*
* Cosine similarity between two embeddings, [-1, 1].
- * > 0.3 typically = same person.
+ * Calibrate the decision threshold using representative labeled pairs.
*/
float mfn_similarity(const float *a, const float *b, int dim);
diff --git a/index.html b/index.html
index 6b58d35..b283c12 100644
--- a/index.html
+++ b/index.html
@@ -1,367 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
-<meta charset="UTF-8">
-<meta name="viewport" content="width=device-width, initial-scale=1.0">
-<title>FaceX — Face Recognition in Your Browser</title>
-<style>
-* { box-sizing: border-box; margin: 0; padding: 0; }
-body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #0a0a0a; color: #e0e0e0; min-height: 100vh; }
-
-.header { text-align: center; padding: 24px 16px 8px; }
-.header h1 { font-size: 24px; color: #fff; }
-.header h1 span { color: #10b981; }
-.header p { color: #555; font-size: 13px; margin-top: 4px; }
-
-.status { text-align: center; padding: 8px; font-size: 13px; transition: color 0.3s; }
-.status.loading { color: #f59e0b; }
-.status.ready { color: #10b981; }
-.status.error { color: #ef4444; }
-
-.main { max-width: 480px; margin: 0 auto; padding: 0 12px 40px; }
-
-.video-wrap { position: relative; width: 100%; border-radius: 12px; overflow: hidden; background: #111; margin-bottom: 12px; border: 2px solid #222; transition: border-color 0.3s; }
-.video-wrap.match { border-color: #10b981; }
-.video-wrap.nomatch { border-color: #ef4444; }
-video { width: 100%; display: block; transform: scaleX(-1); }
-canvas.overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; transform: scaleX(-1); }
-
-.controls { display: flex; gap: 8px; justify-content: center; margin-bottom: 12px; flex-wrap: wrap; }
-.btn { padding: 10px 20px; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; border: none; transition: all 0.15s; }
-.btn:active { transform: scale(0.97); }
-.btn-go { background: #10b981; color: #fff; }
-.btn-go:hover { background: #059669; }
-.btn-stop { background: #ef4444; color: #fff; }
-.btn-sec { background: #222; color: #aaa; border: 1px solid #333; }
-.btn-sec:hover { background: #333; }
-.btn:disabled { background: #1a1a1a; color: #444; cursor: not-allowed; border-color: #1a1a1a; }
-
-.ref-bar { display: flex; align-items: center; gap: 10px; justify-content: center; margin: 10px 0; padding: 10px; background: #111; border-radius: 10px; border: 1px solid #222; }
-.ref-bar canvas { width: 56px; height: 56px; border-radius: 6px; border: 1px solid #333; }
-.ref-bar .label { font-size: 12px; color: #888; }
-
-.result-bar { text-align: center; padding: 14px; margin: 10px 0; border-radius: 10px; font-size: 15px; font-weight: 600; transition: all 0.2s; }
-.result-bar.match { background: #052e16; color: #10b981; border: 1px solid #166534; }
-.result-bar.nomatch { background: #1c0a0a; color: #ef4444; border: 1px solid #7f1d1d; }
-.result-bar.idle { background: #111; color: #555; border: 1px solid #222; }
-
-.stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 10px 0; }
-.stat { text-align: center; background: #111; border-radius: 8px; padding: 8px 4px; border: 1px solid #1a1a1a; }
-.stat-val { font-size: 18px; font-weight: 700; color: #10b981; }
-.stat-label { font-size: 10px; color: #555; text-transform: uppercase; letter-spacing: 0.5px; }
-
-.liveness-bar { display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: #111; border-radius: 8px; margin: 8px 0; border: 1px solid #222; }
-.liveness-dot { width: 10px; height: 10px; border-radius: 50%; background: #ef4444; transition: background 0.3s; }
-.liveness-dot.live { background: #10b981; }
-.liveness-text { font-size: 12px; color: #888; }
-
-.info { background: #0d0d0d; border: 1px solid #1a1a1a; border-radius: 10px; padding: 14px; margin-top: 16px; }
-.info h3 { font-size: 13px; color: #999; margin-bottom: 8px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
-.info p { font-size: 12px; color: #555; line-height: 1.6; margin-bottom: 4px; }
-.info code { background: #1a1a1a; padding: 1px 4px; border-radius: 3px; color: #10b981; font-size: 11px; }
-
-.error-msg { text-align: center; padding: 16px; background: #1c0a0a; border: 1px solid #7f1d1d; border-radius: 10px; margin: 12px 0; color: #ef4444; font-size: 13px; display: none; }
-</style>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="description" content="Run local face detection, alignment and recognition with the FaceX browser SDK.">
+ <meta http-equiv="refresh" content="0; url=wasm/demo.html">
+ <title>FaceX browser SDK demo</title>
</head>
<body>
-
-<div class="header">
- <h1>Face<span>X</span></h1>
- <p>74 KB WASM. No server. Everything stays on your device.</p>
-</div>
-
-<div id="status" class="status loading">Checking browser support...</div>
-<div id="errorMsg" class="error-msg"></div>
-
-<div class="main">
- <div class="video-wrap" id="videoWrap">
- <video id="video" autoplay playsinline muted></video>
- <canvas id="overlay" class="overlay"></canvas>
- </div>
-
- <div class="controls">
- <button id="btnStart" class="btn btn-go" disabled>Start Camera</button>
- <button id="btnCapture" class="btn btn-sec" disabled>Set Reference</button>
- <button id="btnVerify" class="btn btn-go" disabled style="display:none">Verify</button>
- <button id="btnStop" class="btn btn-stop" style="display:none">Stop</button>
- </div>
-
- <div id="refBar" class="ref-bar" style="display:none">
- <canvas id="refCanvas" width="112" height="112"></canvas>
- <div><div class="label">Reference face</div></div>
- </div>
-
- <div id="resultBar" class="result-bar idle">Load engine to begin</div>
-
- <div id="livenessBar" class="liveness-bar" style="display:none">
- <div id="livenessDot" class="liveness-dot"></div>
- <div id="livenessText" class="liveness-text">Checking liveness...</div>
- </div>
-
- <div id="statsGrid" class="stats" style="display:none">
- <div class="stat"><div class="stat-val" id="vDet">—</div><div class="stat-label">Detect</div></div>
- <div class="stat"><div class="stat-val" id="vEmb">—</div><div class="stat-label">Embed</div></div>
- <div class="stat"><div class="stat-val" id="vSim">—</div><div class="stat-label">Match</div></div>
- <div class="stat"><div class="stat-val" id="vFps">—</div><div class="stat-label">FPS</div></div>
- </div>
-
- <div class="info">
- <h3>How it works</h3>
- <p><code>detect.wasm</code> (29 KB) finds faces with RetinaFace INT8 + relaxed SIMD.</p>
- <p><code>facex.wasm</code> (44 KB) computes 512-dim embeddings via EdgeFace-XS.</p>
- <p>5-point alignment ensures accurate matching at any head angle.</p>
- <p>Total: <code>74 KB</code> engine + <code>7.7 MB</code> weights (cached after first load).</p>
- </div>
-</div>
-
-<script src="detect.js"></script>
-<script src="facex.js"></script>
-<script src="align.js"></script>
-<script src="liveness.js"></script>
-<script>
-const $ = id => document.getElementById(id);
-const video = $('video');
-const overlay = $('overlay');
-const ctx = overlay.getContext('2d');
-const refCanvas = $('refCanvas');
-const refCtx = refCanvas.getContext('2d', { willReadFrequently: true });
-
-let DetMod, FxMod, detH, fxH;
-let refEmb = null, running = false;
-const liveness = new LivenessDetector();
-
-// Reusable canvases
-const srcCv = document.createElement('canvas');
-const srcCtx = srcCv.getContext('2d', { willReadFrequently: true });
-const cropCv = document.createElement('canvas');
-cropCv.width = 112; cropCv.height = 112;
-const cropCtxA = cropCv.getContext('2d', { willReadFrequently: true });
-
-// ===== SIMD Check =====
-function checkSimd() {
- try {
- return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11]));
- } catch(e) { return false; }
-}
-
-// ===== IndexedDB Cache =====
-async function cachedFetch(url, key) {
- try {
- const db = await new Promise((res, rej) => {
- const r = indexedDB.open('facex-cache', 1);
- r.onupgradeneeded = () => r.result.createObjectStore('w');
- r.onsuccess = () => res(r.result);
- r.onerror = () => rej(r.error);
- });
- const cached = await new Promise(r => {
- const tx = db.transaction('w','readonly');
- const req = tx.objectStore('w').get(key);
- req.onsuccess = () => r(req.result); req.onerror = () => r(null);
- });
- if (cached) return new Uint8Array(cached);
- const buf = await fetch(url).then(r => r.arrayBuffer());
- try { const tx = db.transaction('w','readwrite'); tx.objectStore('w').put(buf, key); } catch(e) {}
- return new Uint8Array(buf);
- } catch(e) { return new Uint8Array(await fetch(url).then(r => r.arrayBuffer())); }
-}
-
-// ===== Init =====
-async function init() {
- const s = $('status');
- if (!checkSimd()) {
- showError('WebAssembly SIMD not supported. Use Chrome 91+, Firefox 89+, or Safari 16.4+.');
- return;
- }
- try {
- s.textContent = 'Loading engines...'; s.className = 'status loading';
- [DetMod, FxMod] = await Promise.all([FaceDetModule(), FaceXModule()]);
-
- s.textContent = 'Loading weights (cached after first load)...';
- const [dw, fw] = await Promise.all([
- cachedFetch('det_500m_int8.bin', 'det'), cachedFetch('edgeface_xs_fp32.bin', 'emb')
- ]);
- DetMod.FS.writeFile('/d.bin', dw); FxMod.FS.writeFile('/e.bin', fw);
-
- detH = DetMod.cwrap('detect_init','number',['string'])('/d.bin');
- fxH = FxMod.cwrap('facex_init','number',['string','string'])('/e.bin', null);
- if (!detH || !fxH) throw new Error('Engine init failed');
-
- s.textContent = 'Ready — 74 KB engines loaded'; s.className = 'status ready';
- $('btnStart').disabled = false;
- $('resultBar').textContent = 'Click "Start Camera" to begin';
- } catch(e) { showError(e.message); }
-}
-
-function showError(msg) {
- $('status').textContent = 'Error'; $('status').className = 'status error';
- $('errorMsg').textContent = msg; $('errorMsg').style.display = 'block';
-}
-
-// ===== Camera =====
-$('btnStart').onclick = async () => {
- try {
- const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 320, height: 240, facingMode: 'user' }});
- video.srcObject = stream;
- video.onloadedmetadata = () => { overlay.width = video.videoWidth; overlay.height = video.videoHeight; };
- $('btnStart').disabled = true; $('btnStart').style.display = 'none';
- $('btnCapture').disabled = false;
- $('resultBar').textContent = 'Look at camera and click "Set Reference"';
- } catch(e) { showError('Camera access denied: ' + e.message); }
-};
-
-// ===== Detect =====
-function runDetect() {
- const W = video.videoWidth, H = video.videoHeight;
- const ds = 160;
- const detCv = document.createElement('canvas'); detCv.width = ds; detCv.height = ds;
- const dCtx = detCv.getContext('2d', { willReadFrequently: true });
- const scale = Math.min(ds/W, ds/H);
- const nw = Math.round(W*scale), nh = Math.round(H*scale);
- const dx = (ds-nw)/2, dy = (ds-nh)/2;
- dCtx.fillStyle = '#000'; dCtx.fillRect(0,0,ds,ds);
- dCtx.drawImage(video, dx, dy, nw, nh);
- const img = dCtx.getImageData(0,0,ds,ds);
-
- const nPx = ds*ds*3;
- const inP = DetMod._malloc(nPx*4);
- const heap = DetMod.HEAPF32;
- const b = inP>>2;
- for (let i=0; i<ds*ds; i++) {
- heap[b+i*3] = img.data[i*4]/127.5-1; heap[b+i*3+1] = img.data[i*4+1]/127.5-1; heap[b+i*3+2] = img.data[i*4+2]/127.5-1;
- }
- const outP = DetMod._malloc(15*4*10);
- const df = DetMod.cwrap('detect_faces','number',['number','number','number','number','number','number']);
- const t0 = performance.now();
- const n = df(detH, inP, ds, ds, outP, 10);
- const detMs = performance.now() - t0;
-
- const faces = [];
- for (let i=0; i<n; i++) {
- const fb = (outP>>2)+i*15;
- const f = DetMod.HEAPF32;
- faces.push({
- x1:(f[fb]-dx)/scale, y1:(f[fb+1]-dy)/scale, x2:(f[fb+2]-dx)/scale, y2:(f[fb+3]-dy)/scale,
- score:f[fb+4], kps: Array.from({length:10}, (_,j) => (f[fb+5+j]-(j%2===0?dx:dy))/scale)
- });
- }
- DetMod._free(inP); DetMod._free(outP);
- return { faces, detMs };
-}
-
-// ===== Embed =====
-function runEmbed(imgData) {
- const N=112*112*3;
- const inP = FxMod._malloc(N*4), outP = FxMod._malloc(512*4);
- const heap = FxMod.HEAPF32, b = inP>>2;
- for (let i=0; i<112*112; i++) {
- heap[b+i*3] = imgData.data[i*4]/127.5-1; heap[b+i*3+1] = imgData.data[i*4+1]/127.5-1; heap[b+i*3+2] = imgData.data[i*4+2]/127.5-1;
- }
- const t0 = performance.now();
- FxMod.cwrap('facex_embed','number',['number','number','number'])(fxH, inP, outP);
- const embMs = performance.now() - t0;
- const emb = new Float32Array(512);
- emb.set(heap.subarray(outP>>2, (outP>>2)+512));
- FxMod._free(inP); FxMod._free(outP);
- return { emb, embMs };
-}
-
-function cosSim(a,b) {
- let d=0,na=0,nb=0;
- for (let i=0;i<512;i++) { d+=a[i]*b[i]; na+=a[i]*a[i]; nb+=b[i]*b[i]; }
- return d/Math.sqrt(na*nb);
-}
-
-// ===== Align + Crop =====
-function alignAndCrop(face) {
- const W = video.videoWidth, H = video.videoHeight;
- srcCv.width = W; srcCv.height = H;
- srcCtx.drawImage(video, 0, 0);
- const kps5 = [];
- for (let i=0; i<5; i++) kps5.push([face.kps[i*2], face.kps[i*2+1]]);
- return alignFace(srcCtx, W, H, kps5, cropCtxA);
-}
-
-// ===== Draw =====
-function drawFaces(faces, isMatch) {
- ctx.clearRect(0,0,overlay.width,overlay.height);
- for (const f of faces) {
- ctx.strokeStyle = isMatch === undefined ? '#10b981' : (isMatch ? '#10b981' : '#ef4444');
- ctx.lineWidth = 2;
- ctx.strokeRect(f.x1, f.y1, f.x2-f.x1, f.y2-f.y1);
- ctx.fillStyle = ctx.strokeStyle;
- for (let j=0; j<5; j++) { ctx.beginPath(); ctx.arc(f.kps[j*2], f.kps[j*2+1], 2, 0, Math.PI*2); ctx.fill(); }
- }
-}
-
-// ===== Capture Reference =====
-$('btnCapture').onclick = () => {
- const { faces } = runDetect();
- if (!faces.length) { $('resultBar').textContent = 'No face detected — look at camera'; $('resultBar').className = 'result-bar nomatch'; return; }
- const aligned = alignAndCrop(faces[0]);
- refCtx.putImageData(aligned, 0, 0);
- const { emb } = runEmbed(aligned);
- refEmb = emb;
- $('refBar').style.display = 'flex';
- $('btnVerify').style.display = 'inline-block'; $('btnVerify').disabled = false;
- $('resultBar').textContent = 'Reference set. Click "Verify".'; $('resultBar').className = 'result-bar idle';
- drawFaces(faces);
- liveness.reset();
-};
-
-// ===== Verify Loop =====
-$('btnVerify').onclick = () => {
- running = true;
- $('btnVerify').style.display = 'none'; $('btnStop').style.display = 'inline-block';
- $('btnCapture').disabled = true;
- $('statsGrid').style.display = 'grid'; $('livenessBar').style.display = 'flex';
- loop();
-};
-$('btnStop').onclick = () => {
- running = false;
- $('btnStop').style.display = 'none'; $('btnVerify').style.display = 'inline-block'; $('btnVerify').disabled = false;
- $('btnCapture').disabled = false;
- ctx.clearRect(0,0,overlay.width,overlay.height);
- $('videoWrap').className = 'video-wrap';
-};
-
-function loop() {
- if (!running) return;
- const tAll = performance.now();
- const { faces, detMs } = runDetect();
-
- if (!faces.length) {
- drawFaces([]);
- $('resultBar').textContent = 'No face detected'; $('resultBar').className = 'result-bar idle';
- $('videoWrap').className = 'video-wrap';
- $('vDet').textContent = detMs.toFixed(0)+'ms';
- liveness.update(null);
- requestAnimationFrame(loop); return;
- }
-
- const aligned = alignAndCrop(faces[0]);
- const { emb, embMs } = runEmbed(aligned);
- const sim = cosSim(refEmb, emb);
- const match = sim > 0.3;
- const totalMs = performance.now() - tAll;
-
- // Liveness
- const live = liveness.update(faces[0]);
- $('livenessDot').className = 'liveness-dot' + (live.alive ? ' live' : '');
- $('livenessText').textContent = live.reason;
-
- drawFaces(faces, match);
- $('resultBar').textContent = match ? `MATCH — ${(sim*100).toFixed(1)}%` : `NO MATCH — ${(sim*100).toFixed(1)}%`;
- $('resultBar').className = 'result-bar ' + (match ? 'match' : 'nomatch');
- $('videoWrap').className = 'video-wrap ' + (match ? 'match' : 'nomatch');
- $('vDet').textContent = detMs.toFixed(0)+'ms';
- $('vEmb').textContent = embMs.toFixed(0)+'ms';
- $('vSim').textContent = (sim*100).toFixed(1)+'%';
- $('vFps').textContent = (1000/totalMs).toFixed(0);
-
- requestAnimationFrame(loop);
-}
-
-init();
-</script>
+ <p><a href="wasm/demo.html">Open the FaceX browser SDK demo</a></p>
+ <p><a href="docs/demo/">Open the mesh and anti-spoofing demo</a></p>
</body>
</html>
diff --git a/nn2/Makefile b/nn2/Makefile
index 1aa8f3a..c8ddaf5 100644
--- a/nn2/Makefile
+++ b/nn2/Makefile
@@ -1,8 +1,13 @@
-CC = /c/mingw64/bin/gcc
+CC ?= cc
CFLAGS = -O3 -march=native -funroll-loops -ffast-math -fomit-frame-pointer \
-fno-plt -fvisibility=hidden -DNDEBUG \
-Wno-unused-function -Wno-unused-variable -Iinclude -Isrc
-LDFLAGS = -lm -lsynchronization
+LDLIBS = -lm
+ifeq ($(OS),Windows_NT)
+LDLIBS += -lsynchronization
+else
+LDLIBS += -lpthread
+endif
LTO = -flto
# PGO targets (10-18% free speedup)
@@ -27,16 +32,18 @@ ALL_OBJ = $(CORE_OBJ) $(INT8_OBJ)
all: nn2 nn2_img nn2_nvr nanodet
nn2: $(ALL_OBJ) src/main.o
- $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
+ $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) $(LDLIBS)
nn2_img: $(ALL_OBJ) src/main_img.o
- $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
+ $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) $(LDLIBS)
nn2_nvr: $(ALL_OBJ) $(NVR_OBJ) src/main_nvr.o
- $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
+ $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) $(LDLIBS)
nanodet: $(ALL_OBJ) $(ND_OBJ) src/main_nanodet.o
- $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
+ $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) $(LDLIBS)
+
+src/gemm.o src/gemm_res.o: src/gemm_vector.h src/fast_exp.h
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
diff --git a/nn2/README.md b/nn2/README.md
index da2cdec..f53913f 100644
--- a/nn2/README.md
+++ b/nn2/README.md
@@ -1,10 +1,10 @@
# nn2 — Pure C YOLO Inference Engine
-**1.50x faster than ONNX Runtime. Zero dependencies. 520KB binary. 70 cameras on one CPU.**
+NN2 runs object detection and motion-gated NVR processing on a CPU. Its C inference kernels include scalar, AVX2 and AVX-512 implementations. The NVR service and image-detection command have separate entry points.
-Built from scratch in pure C with hand-tuned AVX-512 SIMD. No frameworks, no libraries, no GPU required.
+## Historical measurements
-## Performance
+These measurements were recorded on an Intel i5-11500. Single-frame timings cover inference. The NVR figures include skipped frames and depend on scene motion, stream decoding and the configured detection interval.
### Single-frame inference (i5-11500, 6 cores / 12 threads)
@@ -21,13 +21,17 @@ Built from scratch in pure C with hand-tuned AVX-512 SIMD. No frameworks, no lib
|--------|-------|
| Average per frame | **0.56ms** |
| Effective throughput | **1,746 FPS** |
-| Camera capacity (25fps) | **~70 cameras** |
+| Equivalent frame rate at 25 fps per stream | **~70 streams** (arithmetic estimate) |
| vs naive inference | **14.8x faster** |
Detection accuracy: 4/4 on bus.jpg (person 86%, bus 80%, person 72%, person 71%) — matches PyTorch reference.
## Quick Start
+On x86-64 Linux, run `make -j2 -C nn2` from the FaceX repository root. This builds `nn2`, `nn2_img`, `nn2_nvr` and `nanodet`. Run `./nn2/nn2_img weights.bin photo.jpg` with the appropriate exported YOLO weights. The runtime selects the GEMM paths enabled by the compiler target. A single NN2 process shares a worker pool, so serialize pool lifecycle and detector calls or use separate processes.
+
+Run the commands below from `nn2/` for the Windows build and its additional NVR service.
+
```bash
# Build everything
bash build.sh
@@ -254,10 +258,4 @@ Smart pipeline: 0.56ms avg = 1,638x from start
## License
-Apache 2.0. Free for commercial use, attribution required (see LICENSE).
-
-Copyright (c) 2026 Baurzhan Atinov.
-
-If you ship `nn2` in a product, an attribution line in your README or
-About page is appreciated, not required by the license. Contributions
-via PR welcome.
+The NN2 source includes an [Apache 2.0 license](LICENSE). The export commands use external YOLO models. Refer to the terms for the specific model you supply.
diff --git a/nn2/include/nn2.h b/nn2/include/nn2.h
index 915b166..c2fb878 100644
--- a/nn2/include/nn2.h
+++ b/nn2/include/nn2.h
@@ -39,7 +39,7 @@ void nn2_free(NN2* ctx);
/* Config */
void nn2_set_conf_threshold(NN2* ctx, float threshold); /* default 0.25 */
void nn2_set_nms_threshold(NN2* ctx, float threshold); /* default 0.45 */
-void nn2_set_input_size(NN2* ctx, int size); /* 320 or 640, default from weights */
+void nn2_set_input_size(NN2* ctx, int size); /* Multiple of 32 through 640. Retains the old size if workspace growth fails. */
const char* nn2_version(void);
diff --git a/nn2/src/gemm.c b/nn2/src/gemm.c
index 6d0ca34..c8b52dd 100644
--- a/nn2/src/gemm.c
+++ b/nn2/src/gemm.c
@@ -10,6 +10,8 @@
#include "nn2_internal.h"
#include <string.h>
#include <stdlib.h>
+#include <math.h>
+#include "gemm_vector.h"
#include <immintrin.h>
/* ============================================================
@@ -39,7 +41,7 @@ static inline void ukernel_6x32_avx512(
for(int k=0;k<K;k++){
const float*bp=B+k*ldb;
if(k+2<K)_mm_prefetch((const char*)(B+(k+2)*ldb),_MM_HINT_T0);
- __m512 b0=_mm512_loadu_ps(bp),b1=_mm512_loadu_ps(bp+16);
+ __m512 b0=nn2_load_columns(bp,nr,0),b1=nn2_load_columns(bp,nr,16);
__m512 va;
va=_mm512_set1_ps(a0[k]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01);
va=_mm512_set1_ps(a1[k]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11);
@@ -67,7 +69,7 @@ static inline void ukernel_6x32_avx512(
typedef struct {
int M, K, N;
const float* A; int lda;
- const float* B;
+ const float* B; int ldb;
float* C; int ldc;
} GemmCtx;
@@ -81,7 +83,7 @@ static void gemm_avx512_worker(void* arg, int start, int end)
for (int m = 0; m < g->M; m += NN2_MR) {
int mr = (m + NN2_MR <= g->M) ? NN2_MR : g->M - m;
ukernel_6x32_avx512(g->K, g->A + m*g->lda, g->lda,
- g->B + n, g->N,
+ g->B + n, g->ldb,
g->C + m*g->ldc + n, g->ldc, mr, nr);
}
}
@@ -102,6 +104,16 @@ static inline void ukernel_6x16_avx2(
float* restrict C, int ldc,
int mr, int nr)
{
+ if (nr < 16) {
+ for (int i = 0; i < mr; i++) {
+ for (int j = 0; j < nr; j++) {
+ float sum = 0;
+ for (int k = 0; k < K; k++) sum += A[i * lda + k] * B[k * ldb + j];
+ C[i * ldc + j] = sum;
+ }
+ }
+ return;
+ }
__m256 c00=_mm256_setzero_ps(), c01=_mm256_setzero_ps();
__m256 c10=_mm256_setzero_ps(), c11=_mm256_setzero_ps();
__m256 c20=_mm256_setzero_ps(), c21=_mm256_setzero_ps();
@@ -168,7 +180,7 @@ static void gemm_avx2_worker(void* arg, int start, int end)
for (int m = 0; m < g->M; m += NN2_MR) {
int mr = (m + NN2_MR <= g->M) ? NN2_MR : g->M - m;
ukernel_6x16_avx2(g->K, g->A + m*g->lda, g->lda,
- g->B + n, g->N,
+ g->B + n, g->ldb,
g->C + m*g->ldc + n, g->ldc, mr, nr);
}
}
@@ -180,8 +192,15 @@ static void gemm_avx2_worker(void* arg, int start, int end)
float* nn2_pack_weight_a(const float* A, int M, int K)
{
+ if (!A || M <= 0 || K <= 0) return NULL;
+#ifndef __AVX512F__
+ size_t bytes = (size_t)M * K * sizeof(float);
+ float *copy = malloc(bytes);
+ if (copy) memcpy(copy, A, bytes);
+ return copy;
+#else
int panels = (M + NN2_MR - 1) / NN2_MR;
- float* Ap = (float*)_aligned_malloc((size_t)panels * K * NN2_MR * sizeof(float), 64);
+ float *Ap = malloc((size_t)panels * K * NN2_MR * sizeof(float));
if (!Ap) return NULL;
for (int p = 0; p < panels; p++) {
for (int k = 0; k < K; k++) {
@@ -192,6 +211,7 @@ float* nn2_pack_weight_a(const float* A, int M, int K)
}
}
return Ap;
+#endif
}
/* ============ Scalar fallback ============ */
@@ -204,7 +224,7 @@ float* nn2_pack_weight_a(const float* A, int M, int K)
typedef struct {
int M, K, N;
const float* A; int lda;
- const float* B;
+ const float* B; int ldb;
float* C; int ldc;
const float* bias;
int act;
@@ -212,13 +232,8 @@ typedef struct {
#ifdef __AVX512F__
-#include "fast_exp.h"
#include "gemm_asm.h"
-static inline __m512 _fused_silu512(__m512 x) {
- return _mm512_silu_fast(x);
-}
-
/* KC block size: keeps B panel (KC×NR×4 bytes) in L1 cache */
#define KC_BLOCK 256
@@ -249,8 +264,8 @@ static void gemm_fused_avx512_worker(void* arg, int start, int end)
int k = kc;
int kend4 = kc + (kb & ~3);
#define FK(off) { \
- const float*bp=g->B+(k+(off))*g->N+n; \
- __m512 b0=_mm512_loadu_ps(bp),b1=_mm512_loadu_ps(bp+16); __m512 va; \
+ const float*bp=g->B+(k+(off))*g->ldb+n; \
+ __m512 b0=nn2_load_columns(bp,nr,0),b1=nn2_load_columns(bp,nr,16); __m512 va; \
va=_mm512_set1_ps(a0[k+(off)]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01); \
va=_mm512_set1_ps(a1[k+(off)]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11); \
va=_mm512_set1_ps(a2[k+(off)]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21); \
@@ -266,10 +281,7 @@ static void gemm_fused_avx512_worker(void* arg, int start, int end)
#define FS(i,lo,hi) if(i<mr){ \
__m512 vb=_mm512_set1_ps(g->bias[m+(i)]); \
lo=_mm512_add_ps(lo,vb);hi=_mm512_add_ps(hi,vb); \
- if(g->act==1){lo=_fused_silu512(lo);hi=_fused_silu512(hi);} \
- else if(g->act==3){__m512 vl=_mm512_set1_ps(0.1f),vz=_mm512_setzero_ps(); \
- lo=_mm512_mask_mul_ps(lo,_mm512_cmplt_ps_mask(lo,vz),lo,vl); \
- hi=_mm512_mask_mul_ps(hi,_mm512_cmplt_ps_mask(hi,vz),hi,vl);} \
+ lo=nn2_activate_vector(lo,g->act);hi=nn2_activate_vector(hi,g->act); \
if(nr>=32){_mm512_storeu_ps(C+i*g->ldc,lo);_mm512_storeu_ps(C+i*g->ldc+16,hi);} \
else{__mmask16 ml=(nr>=16)?0xFFFF:((__mmask16)1<<nr)-1,mh=(nr<=16)?0:((__mmask16)1<<(nr-16))-1; \
_mm512_mask_storeu_ps(C+i*g->ldc,ml,lo);if(mh)_mm512_mask_storeu_ps(C+i*g->ldc+16,mh,hi);} \
@@ -315,7 +327,7 @@ static void packed_fused_worker(void* arg, int start, int end) {
#define KCF(off) { \
const float* bp = bp_base + (k+(off)) * g->N; \
const float* a = ap + (k+(off)) * NN2_MR; \
- __m512 b0=_mm512_loadu_ps(bp), b1=_mm512_loadu_ps(bp+16); __m512 va; \
+ __m512 b0=nn2_load_columns(bp,nr,0), b1=nn2_load_columns(bp,nr,16); __m512 va; \
va=_mm512_set1_ps(a[0]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01); \
va=_mm512_set1_ps(a[1]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11); \
va=_mm512_set1_ps(a[2]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21); \
@@ -328,7 +340,7 @@ static void packed_fused_worker(void* arg, int start, int end) {
for (; k < kb; k++) {
const float* bp = bp_base + k * g->N;
const float* a = ap + k * NN2_MR;
- __m512 b0=_mm512_loadu_ps(bp), b1=_mm512_loadu_ps(bp+16);
+ __m512 b0=nn2_load_columns(bp,nr,0), b1=nn2_load_columns(bp,nr,16);
__m512 va;
va=_mm512_set1_ps(a[0]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01);
va=_mm512_set1_ps(a[1]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11);
@@ -344,7 +356,7 @@ static void packed_fused_worker(void* arg, int start, int end) {
#define FP(i,lo,hi) if(i<mr){ \
__m512 vb=_mm512_set1_ps(g->bias[m+(i)]); \
lo=_mm512_add_ps(lo,vb);hi=_mm512_add_ps(hi,vb); \
- if(g->act==1){lo=_fused_silu512(lo);hi=_fused_silu512(hi);} \
+ lo=nn2_activate_vector(lo,g->act);hi=nn2_activate_vector(hi,g->act); \
if(nr>=32){_mm512_storeu_ps(Cp+i*g->ldc,lo);_mm512_storeu_ps(Cp+i*g->ldc+16,hi);} \
else{__mmask16 ml=(nr>=16)?0xFFFF:((__mmask16)1<<nr)-1,mh=(nr<=16)?0:((__mmask16)1<<(nr-16))-1; \
_mm512_mask_storeu_ps(Cp+i*g->ldc,ml,lo);if(mh)_mm512_mask_storeu_ps(Cp+i*g->ldc+16,mh,hi);}}
@@ -353,8 +365,6 @@ static void packed_fused_worker(void* arg, int start, int end) {
}
}
}
-#endif /* __AVX512F__ */
-
/* 2D-tiled packed fused worker: tile index → (m_panel, n_tile) */
typedef struct { int M,K,N; const float*Ap; const float*B; float*C; int ldc; const float*bias; int act; int n_tiles; } Packed2DCtx;
@@ -384,7 +394,7 @@ static void packed_fused_2d_worker(void* arg, int start, int end) {
#define KCF2(off) { \
const float* bp = bp_base + (k+(off)) * g->N; \
const float* a = ap + (k+(off)) * NN2_MR; \
- __m512 b0=_mm512_loadu_ps(bp), b1=_mm512_loadu_ps(bp+16); __m512 va; \
+ __m512 b0=nn2_load_columns(bp,nr,0), b1=nn2_load_columns(bp,nr,16); __m512 va; \
va=_mm512_set1_ps(a[0]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01); \
va=_mm512_set1_ps(a[1]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11); \
va=_mm512_set1_ps(a[2]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21); \
@@ -397,7 +407,7 @@ static void packed_fused_2d_worker(void* arg, int start, int end) {
for (; k < kb; k++) {
const float* bp = bp_base + k * g->N;
const float* a = ap + k * NN2_MR;
- __m512 b0=_mm512_loadu_ps(bp), b1=_mm512_loadu_ps(bp+16); __m512 va;
+ __m512 b0=nn2_load_columns(bp,nr,0), b1=nn2_load_columns(bp,nr,16); __m512 va;
va=_mm512_set1_ps(a[0]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01);
va=_mm512_set1_ps(a[1]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11);
va=_mm512_set1_ps(a[2]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21);
@@ -411,7 +421,7 @@ static void packed_fused_2d_worker(void* arg, int start, int end) {
#define FP2(i,lo,hi) if(i<mr){ \
__m512 vb=_mm512_set1_ps(g->bias[m+(i)]); \
lo=_mm512_add_ps(lo,vb);hi=_mm512_add_ps(hi,vb); \
- if(g->act==1){lo=_fused_silu512(lo);hi=_fused_silu512(hi);} \
+ lo=nn2_activate_vector(lo,g->act);hi=nn2_activate_vector(hi,g->act); \
if(nr>=32){_mm512_storeu_ps(Cp+i*g->ldc,lo);_mm512_storeu_ps(Cp+i*g->ldc+16,hi);} \
else{__mmask16 ml=(nr>=16)?0xFFFF:((__mmask16)1<<nr)-1,mh=(nr<=16)?0:((__mmask16)1<<(nr-16))-1; \
_mm512_mask_storeu_ps(Cp+i*g->ldc,ml,lo);if(mh)_mm512_mask_storeu_ps(Cp+i*g->ldc+16,mh,hi);}}
@@ -420,6 +430,8 @@ static void packed_fused_2d_worker(void* arg, int start, int end) {
}
}
+#endif /* __AVX512F__ */
+
void nn2_sgemm_bias_act_packed(int M, int K, int N,
const float* Ap,
const float* B, float* C, int ldc,
@@ -445,7 +457,7 @@ void nn2_sgemm_bias_act_packed(int M, int K, int N,
nn2_tp_parallel_for(packed_fused_worker, &pg, n_tiles, grain);
}
#else
- (void)Ap;(void)B;(void)C;(void)ldc;(void)bias;(void)act;(void)M;(void)K;(void)N;
+ nn2_sgemm_bias_act(M, K, N, Ap, K, B, N, C, ldc, bias, act);
#endif
}
@@ -455,9 +467,8 @@ void nn2_sgemm_bias_act(int M, int K, int N,
float* C, int ldc,
const float* bias, int act)
{
- (void)ldb;
#ifdef __AVX512F__
- GemmFusedCtx g = {M, K, N, A, lda, B, C, ldc, bias, act};
+ GemmFusedCtx g = {M, K, N, A, lda, B, ldb, C, ldc, bias, act};
int n_tiles = (N + NR512 - 1) / NR512;
int grain = (n_tiles > 128) ? n_tiles / (nn2_tp_num_threads() * 4) : 1;
if (grain < 1) grain = 1;
@@ -473,6 +484,7 @@ void nn2_sgemm_bias_act(int M, int K, int N,
for (int n = 0; n < N; n++) {
float v = C[m*ldc+n] + b;
if (act == 1) { float s = 1.0f/(1.0f+expf(-v)); v *= s; }
+ else if (act == 2) v = 1.0f / (1.0f + expf(-v));
else if (act == 3 && v < 0) v *= 0.1f;
C[m*ldc+n] = v;
}
@@ -484,12 +496,12 @@ void nn2_sgemm_bias_act(int M, int K, int N,
static void gemm_scalar(int M, int K, int N,
const float* A, int lda,
- const float* B, float* C, int ldc)
+ const float* B, int ldb, float* C, int ldc)
{
for (int m=0;m<M;m++)
for (int n=0;n<N;n++) {
float acc=0;
- for (int k=0;k<K;k++) acc+=A[m*lda+k]*B[k*N+n];
+ for (int k=0;k<K;k++) acc+=A[m*lda+k]*B[k*ldb+n];
C[m*ldc+n]=acc;
}
}
@@ -501,11 +513,10 @@ void nn2_sgemm(int M, int K, int N,
const float* B, int ldb,
float* C, int ldc)
{
- (void)ldb;
#ifdef __AVX512F__
{
- GemmCtx g = {M, K, N, A, lda, B, C, ldc};
+ GemmCtx g = {M, K, N, A, lda, B, ldb, C, ldc};
int n_tiles = (N + NR512 - 1) / NR512;
int grain = (n_tiles > 128) ? n_tiles / (nn2_tp_num_threads() * 4) : 1;
if (grain < 1) grain = 1;
@@ -519,7 +530,7 @@ void nn2_sgemm(int M, int K, int N,
#ifdef __AVX2__
{
- GemmCtx g = {M, K, N, A, lda, B, C, ldc};
+ GemmCtx g = {M, K, N, A, lda, B, ldb, C, ldc};
int n_tiles = (N + NN2_NR - 1) / NN2_NR;
int grain = (n_tiles > 256) ? n_tiles / (nn2_tp_num_threads() * 4) : 1;
if (grain < 1) grain = 1;
@@ -531,5 +542,5 @@ void nn2_sgemm(int M, int K, int N,
}
#endif
- gemm_scalar(M, K, N, A, lda, B, C, ldc);
+ gemm_scalar(M, K, N, A, lda, B, ldb, C, ldc);
}
diff --git a/nn2/src/gemm_res.c b/nn2/src/gemm_res.c
index 2a0078e..6c19de9 100644
--- a/nn2/src/gemm_res.c
+++ b/nn2/src/gemm_res.c
@@ -10,12 +10,11 @@
#ifdef __AVX512F__
-#include "fast_exp.h"
+#include "gemm_vector.h"
#define NR512 32
#define KC_BLOCK 256
-static inline __m512 _res_silu512(__m512 x) { return _mm512_silu_fast(x); }
typedef struct {
int M, K, N;
@@ -54,7 +53,7 @@ static void res_worker(void* arg, int start, int end) {
#define RK(off) { \
const float* bp = bp_base + (k+(off)) * g->N; \
const float* a = ap + (k+(off)) * NN2_MR; \
- __m512 b0=_mm512_loadu_ps(bp), b1=_mm512_loadu_ps(bp+16); __m512 va; \
+ __m512 b0=nn2_load_columns(bp,nr,0), b1=nn2_load_columns(bp,nr,16); __m512 va; \
va=_mm512_set1_ps(a[0]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01); \
va=_mm512_set1_ps(a[1]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11); \
va=_mm512_set1_ps(a[2]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21); \
@@ -67,7 +66,7 @@ static void res_worker(void* arg, int start, int end) {
for (; k < kb; k++) {
const float* bp = bp_base + k * g->N;
const float* a = ap + k * NN2_MR;
- __m512 b0=_mm512_loadu_ps(bp), b1=_mm512_loadu_ps(bp+16); __m512 va;
+ __m512 b0=nn2_load_columns(bp,nr,0), b1=nn2_load_columns(bp,nr,16); __m512 va;
va=_mm512_set1_ps(a[0]);c00=_mm512_fmadd_ps(va,b0,c00);c01=_mm512_fmadd_ps(va,b1,c01);
va=_mm512_set1_ps(a[1]);c10=_mm512_fmadd_ps(va,b0,c10);c11=_mm512_fmadd_ps(va,b1,c11);
va=_mm512_set1_ps(a[2]);c20=_mm512_fmadd_ps(va,b0,c20);c21=_mm512_fmadd_ps(va,b1,c21);
@@ -83,9 +82,9 @@ static void res_worker(void* arg, int start, int end) {
#define FR(i,lo,hi) if(i<mr){ \
__m512 vb=_mm512_set1_ps(g->bias[m+(i)]); \
lo=_mm512_add_ps(lo,vb); hi=_mm512_add_ps(hi,vb); \
- if(g->act==1){lo=_res_silu512(lo);hi=_res_silu512(hi);} \
- lo=_mm512_add_ps(lo,_mm512_loadu_ps(Rp+i*g->ldr)); \
- hi=_mm512_add_ps(hi,_mm512_loadu_ps(Rp+i*g->ldr+16)); \
+ lo=nn2_activate_vector(lo,g->act);hi=nn2_activate_vector(hi,g->act); \
+ lo=_mm512_add_ps(lo,nn2_load_columns(Rp+i*g->ldr,nr,0)); \
+ hi=_mm512_add_ps(hi,nn2_load_columns(Rp+i*g->ldr,nr,16)); \
if(nr>=32){_mm512_storeu_ps(Cp+i*g->ldc,lo);_mm512_storeu_ps(Cp+i*g->ldc+16,hi);} \
else{__mmask16 ml=(nr>=16)?0xFFFF:((__mmask16)1<<nr)-1,mh=(nr<=16)?0:((__mmask16)1<<(nr-16))-1; \
_mm512_mask_storeu_ps(Cp+i*g->ldc,ml,lo);if(mh)_mm512_mask_storeu_ps(Cp+i*g->ldc+16,mh,hi);}}
diff --git a/nn2/src/gemm_vector.h b/nn2/src/gemm_vector.h
new file mode 100644
index 0000000..bc08570
--- /dev/null
+++ b/nn2/src/gemm_vector.h
@@ -0,0 +1,23 @@
+#ifndef NN2_GEMM_VECTOR_H
+#define NN2_GEMM_VECTOR_H
+#ifdef __AVX512F__
+#include "fast_exp.h"
+
+static inline __m512 nn2_load_columns(const float *row, int columns, int offset) {
+ int count = columns - offset;
+ if (count <= 0) return _mm512_setzero_ps();
+ if (count >= 16) return _mm512_loadu_ps(row + offset);
+ return _mm512_maskz_loadu_ps((__mmask16)((1u << count) - 1), row + offset);
+}
+
+static inline __m512 nn2_activate_vector(__m512 x, int act) {
+ if (act == 1) return _mm512_silu_fast(x);
+ if (act == 2) return _mm512_sigmoid_fast(x);
+ if (act == 3) {
+ __mmask16 negative = _mm512_cmplt_ps_mask(x, _mm512_setzero_ps());
+ return _mm512_mask_mul_ps(x, negative, x, _mm512_set1_ps(0.1f));
+ }
+ return x;
+}
+#endif
+#endif
diff --git a/nn2/src/main_img.c b/nn2/src/main_img.c
index d3ae1ec..d82e848 100644
--- a/nn2/src/main_img.c
+++ b/nn2/src/main_img.c
@@ -16,6 +16,13 @@ static double get_time_ms(void) {
QueryPerformanceCounter(&c);
return (double)c.QuadPart / f.QuadPart * 1000.0;
}
+#else
+#include <time.h>
+static double get_time_ms(void) {
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;
+}
#endif
static const char* coco_names[] = {
diff --git a/nn2/src/main_nanodet.c b/nn2/src/main_nanodet.c
index a27c65a..97c6cfc 100644
--- a/nn2/src/main_nanodet.c
+++ b/nn2/src/main_nanodet.c
@@ -5,6 +5,13 @@
#ifdef _WIN32
#include <windows.h>
static double get_time_ms(void){LARGE_INTEGER f,c;QueryPerformanceFrequency(&f);QueryPerformanceCounter(&c);return(double)c.QuadPart/f.QuadPart*1000.0;}
+#else
+#include <time.h>
+static double get_time_ms(void) {
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;
+}
#endif
/* From nanodet.c */
diff --git a/nn2/src/main_nvr.c b/nn2/src/main_nvr.c
index 1be6345..62f6df3 100644
--- a/nn2/src/main_nvr.c
+++ b/nn2/src/main_nvr.c
@@ -18,6 +18,13 @@ static double get_ms(void) {
QueryPerformanceCounter(&c);
return (double)c.QuadPart / f.QuadPart * 1000.0;
}
+#else
+#include <time.h>
+static double get_ms(void) {
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;
+}
#endif
static const char* coco_names[] = {
diff --git a/nn2/src/net.c b/nn2/src/net.c
index 142bb28..88e3072 100644
--- a/nn2/src/net.c
+++ b/nn2/src/net.c
@@ -10,28 +10,27 @@
#include "nn2_internal.h"
#include <stdio.h>
+#include <limits.h>
#include <stdlib.h>
#include <string.h>
/* No explicit SIMD here — compiler auto-vectorizes with -O3 */
/* ============ Weight file format ============ */
-static float* read_tensor(FILE* f, int* out_size)
+static float* read_tensor(FILE* f, size_t expected)
{
uint32_t sz;
- if (fread(&sz, 4, 1, f) != 1) return NULL;
+ if (fread(&sz, 4, 1, f) != 1 || sz != expected) return NULL;
float* data = (float*)malloc(sz * sizeof(float));
if (!data) return NULL;
if (fread(data, sizeof(float), sz, f) != sz) { free(data); return NULL; }
- *out_size = (int)sz;
return data;
}
static int load_conv(FILE* f, ConvLayer* L, int cout, int cin, int k, int stride, int pad, int act)
{
- int wsz, bsz;
- L->w = read_tensor(f, &wsz);
- L->b = read_tensor(f, &bsz);
+ L->w = read_tensor(f, (size_t)cout * cin * k * k);
+ L->b = read_tensor(f, cout);
if (!L->w || !L->b) return -1;
L->cout = cout; L->cin = cin; L->k = k;
L->stride = stride; L->pad = pad; L->act = act;
@@ -60,16 +59,15 @@ int nn2_load_weights(NN2* ctx, const char* path)
if (!f) { fprintf(stderr, "nn2: cannot open %s\n", path); return -1; }
char magic[4];
- fread(magic, 1, 4, f);
- if (memcmp(magic, "NN2W", 4) != 0) {
+ if (fread(magic, 1, 4, f) != 4 || memcmp(magic, "NN2W", 4) != 0) {
fprintf(stderr, "nn2: invalid weight file\n");
fclose(f); return -1;
}
uint32_t nc, isz, ntensors;
- fread(&nc, 4, 1, f);
- fread(&isz, 4, 1, f);
- fread(&ntensors, 4, 1, f);
+ if (fread(&nc, 4, 1, f) != 1 || fread(&isz, 4, 1, f) != 1 ||
+ fread(&ntensors, 4, 1, f) != 1 || !nc || nc > INT_MAX / NN2_MAX_ANCHORS ||
+ isz < 32 || isz > 640 || isz % 32) goto fail;
ctx->num_classes = (int)nc;
ctx->input_size = (int)isz;
diff --git a/nn2/src/nn2.c b/nn2/src/nn2.c
index 4988f7b..746056a 100644
--- a/nn2/src/nn2.c
+++ b/nn2/src/nn2.c
@@ -19,6 +19,17 @@ const char* nn2_version(void) { return "0.1.0"; }
/* Declared in net.c */
int nn2_load_weights(NN2* ctx, const char* path);
+/* The standard workspace covers a full 80 class COCO head. Larger custom
+ * heads also need their additional first-scale features and output rows. */
+static size_t workspace_size(int size, int classes) {
+ size_t base = size > 320 ? (256u << 20) : (64u << 20);
+ size_t head = (size_t)(size / 8) * (size / 8);
+ size_t anchors = head + head / 4 + head / 16;
+ size_t extra = classes > 80 ? (size_t)(classes - 80) : 0;
+ if (extra > (SIZE_MAX - base) / ((anchors + head) * sizeof(float))) return 0;
+ return base + extra * (anchors + head) * sizeof(float);
+}
+
NN2* nn2_init(const char* weights_path, int n_threads)
{
NN2* ctx = (NN2*)calloc(1, sizeof(NN2));
@@ -32,20 +43,21 @@ NN2* nn2_init(const char* weights_path, int n_threads)
ctx->dfl_weight[i] = (float)i;
/* Load weights */
- if (nn2_load_weights(ctx, weights_path) != 0) {
- free(ctx);
+ if (!weights_path || nn2_load_weights(ctx, weights_path) != 0) {
+ nn2_free(ctx);
return NULL;
}
/* Allocate workspace: 256MB for 640, 64MB for 320 */
- ctx->ws_size = (ctx->input_size >= 640) ? (256 << 20) : (64 << 20);
- ctx->workspace = (float*)malloc(ctx->ws_size);
+ ctx->ws_size = workspace_size(ctx->input_size, ctx->num_classes);
+ ctx->workspace = ctx->ws_size ? malloc(ctx->ws_size) : NULL;
if (!ctx->workspace) {
fprintf(stderr, "nn2: workspace alloc failed\n");
nn2_free(ctx);
return NULL;
}
+#ifdef __AVX512F__
/* Pre-pack weight matrices for all conv layers (BLIS-style A-packing).
* Eliminates stride-lda access during GEMM — weights become sequential in memory. */
{
@@ -80,6 +92,8 @@ NN2* nn2_init(const char* weights_path, int n_threads)
#undef PACK_CONV
}
+#endif
+
/* Detect fused normalization: if first conv weights are very small (< 0.1),
* they were pre-divided by 255 at export time → skip normalize in preprocessing. */
{
@@ -97,8 +111,8 @@ NN2* nn2_init(const char* weights_path, int n_threads)
}
/* Thread pool */
- ctx->n_threads = n_threads;
nn2_tp_init(n_threads);
+ ctx->n_threads = nn2_tp_num_threads();
fprintf(stderr, "nn2: loaded model (classes=%d, input=%d, threads=%d)\n",
ctx->num_classes, ctx->input_size, nn2_tp_num_threads());
@@ -317,11 +331,22 @@ int nn2_detect(NN2* ctx, const uint8_t* rgb_hwc, int width, int height,
void nn2_set_conf_threshold(NN2* ctx, float threshold) { ctx->conf_thresh = threshold; }
void nn2_set_nms_threshold(NN2* ctx, float threshold) { ctx->nms_thresh = threshold; }
-void nn2_set_input_size(NN2* ctx, int size) { ctx->input_size = size; }
+void nn2_set_input_size(NN2* ctx, int size) {
+ if (!ctx || size < 32 || size > 640 || size % 32) return;
+ size_t required = workspace_size(size, ctx->num_classes);
+ if (!required) return;
+ if (ctx->ws_size < required) {
+ float *workspace = realloc(ctx->workspace, required);
+ if (!workspace) return;
+ ctx->workspace = workspace;
+ ctx->ws_size = required;
+ }
+ ctx->input_size = size;
+}
/* ============ Cleanup ============ */
-static void free_conv(ConvLayer* L) { free(L->w); _aligned_free(L->w_packed); free(L->b); free(L->w_wino); }
+static void free_conv(ConvLayer* L) { free(L->w); free(L->w_packed); free(L->b); free(L->w_wino); }
static void free_c2f(C2fBlock* blk) {
free_conv(&blk->cv1);
free_conv(&blk->cv2);
@@ -345,6 +370,6 @@ void nn2_free(NN2* ctx)
for (int j = 0; j < 3; j++) free_conv(&ctx->head[s].cls[j]);
}
free(ctx->workspace);
- nn2_tp_destroy();
+ if (ctx->n_threads) nn2_tp_destroy();
free(ctx);
}
diff --git a/nn2/src/pool.c b/nn2/src/pool.c
index c5f0c25..87c6eb2 100644
--- a/nn2/src/pool.c
+++ b/nn2/src/pool.c
@@ -62,6 +62,7 @@ typedef struct {
static Worker g_workers[MAX_THREADS];
static int g_n_threads = 0;
+static unsigned g_users = 0;
static volatile int g_shutdown = 0;
static
@@ -98,6 +99,7 @@ worker_fn(void* arg)
continue;
}
}
+ if (ATOMIC_LOAD(&g_shutdown)) break;
last_phase = phase;
while (1) {
@@ -120,6 +122,7 @@ worker_fn(void* arg)
void nn2_tp_init(int n_threads)
{
+ if (g_users++ > 0) return;
if (n_threads <= 0) {
#ifdef _WIN32
SYSTEM_INFO si; GetSystemInfo(&si);
@@ -127,11 +130,11 @@ void nn2_tp_init(int n_threads)
#else
n_threads = sysconf(_SC_NPROCESSORS_ONLN);
#endif
- if (n_threads > MAX_THREADS) n_threads = MAX_THREADS;
- if (n_threads < 1) n_threads = 1;
}
+ if (n_threads > MAX_THREADS) n_threads = MAX_THREADS;
+ if (n_threads < 1) n_threads = 1;
- g_n_threads = n_threads;
+ g_n_threads = 1;
int n_workers = n_threads - 1;
memset(&g_task, 0, sizeof(g_task));
ATOMIC_STORE(&g_shutdown, 0);
@@ -141,9 +144,11 @@ void nn2_tp_init(int n_threads)
#ifdef _WIN32
g_workers[i].handle = (HANDLE)_beginthreadex(
NULL, 0, worker_fn, &g_workers[i], 0, NULL);
+ if (!g_workers[i].handle) break;
#else
- pthread_create(&g_workers[i].handle, NULL, worker_fn, &g_workers[i]);
+ if (pthread_create(&g_workers[i].handle, NULL, worker_fn, &g_workers[i]) != 0) break;
#endif
+ g_n_threads++;
}
}
@@ -199,13 +204,16 @@ void nn2_tp_parallel_for(nn2_task_fn fn, void* ctx, int total, int grain)
void nn2_tp_destroy(void)
{
+ if (!g_users || --g_users > 0) return;
int n_workers = g_n_threads - 1;
ATOMIC_STORE(&g_shutdown, 1);
ATOMIC_ADD(&g_task.phase, 1);
#ifdef _WIN32
WakeByAddressAll((void*)&g_task.phase);
- for (int i = 0; i < n_workers; i++)
+ for (int i = 0; i < n_workers; i++) {
WaitForSingleObject(g_workers[i].handle, INFINITE);
+ CloseHandle(g_workers[i].handle);
+ }
#else
syscall(SYS_futex, &g_task.phase, FUTEX_WAKE, MAX_THREADS, NULL, NULL, 0);
for (int i = 0; i < n_workers; i++)
@@ -214,4 +222,4 @@ void nn2_tp_destroy(void)
g_n_threads = 0;
}
-int nn2_tp_num_threads(void) { return g_n_threads; }
+int nn2_tp_num_threads(void) { return g_n_threads > 0 ? g_n_threads : 1; }
diff --git a/python/README.md b/python/README.md
index e9f2793..37896ed 100644
--- a/python/README.md
+++ b/python/README.md
@@ -18,8 +18,8 @@ pip install -e ".[image]"
import numpy as np
from facex import FaceX
-# Initialize (auto-finds library and weights)
-fx = FaceX()
+# After building the library and preparing both weights from the repository root
+fx = FaceX(embed_weights="data/edgeface_xs_fp32.bin", detect_weights="weights/yunet_fp32.bin")
# Load an image as RGB uint8 numpy array (H, W, 3)
from PIL import Image
@@ -35,7 +35,7 @@ for face in faces:
# Compare two faces
if len(faces) >= 2:
sim = FaceX.similarity(faces[0]["embedding"], faces[1]["embedding"])
- print(f"Similarity: {sim:.3f} ({'same' if sim > 0.3 else 'different'} person)")
+ print(f"Cosine similarity: {sim:.3f}")
```
## Rectangular YuNet input
@@ -44,7 +44,7 @@ For camera frames and photos, initialize the native SDK with the rectangle polic
Install the image extra for Pillow and build the shared library from this version.
```python
-fx = FaceX(embed_weights="weights/edgeface_xs_fp32.bin",
+fx = FaceX(embed_weights="data/edgeface_xs_fp32.bin",
detect_weights="weights/yunet_fp32.bin",
input_policy="rectangle_bgr")
faces = fx.detect(image)
@@ -71,8 +71,9 @@ default 16 selects 0.70. The 800 BGR mode uses 0.75 for all three sizes.
See [the minimum side comparison](../docs/research/yunet_minimum_side.md).
The Docker REST service uses the BGR rectangle policy for `POST /detect` and returns
-up to 32 faces. Mount both weights at the paths above under `/app`, or set
-`EMBED_WEIGHTS` and `DETECT_WEIGHTS` to their paths inside the container.
+up to 32 faces. By default the container reads `/app/weights/edgeface_xs_fp32.bin`
+and `/app/weights/yunet_fp32.bin`. Mount those files or set `EMBED_WEIGHTS` and
+`DETECT_WEIGHTS` to their paths inside the container.
```sh
curl -F [email protected] http://localhost:8080/detect
@@ -80,10 +81,11 @@ curl -F [email protected] http://localhost:8080/detect
## Configuration
+Build the shared library with `make libfacex.so` on Linux or choose the CLI explicitly with `FaceX(cli_path="./facex-cli", ...)`. The rectangle and guided detection paths use the shared library. See the [build and weights instructions](../README.md#build-the-native-runtime).
+
### Auto-detection
-FaceX looks for the native library and weights relative to the package location
-(expects `../../weights/` and `../../libfacex.so` or `../../facex.dll`).
+The SDK searches for the shared library near the package and under `FACEX_ROOT`. It recognizes the downloaded EdgeFace weights in `data/` and detector weights in `weights/`.
### Environment variables
@@ -114,8 +116,8 @@ fx = FaceX(
Main class. Uses ctypes (shared library) if available, falls back to subprocess (CLI).
-- **`detect(image, max_faces=None)`** -- Detect faces in an RGB uint8 image. Returns list of dicts with `bbox`, `score`, `keypoints`, `embedding`.
-- **`embed(face_112x112)`** -- Compute embedding for a pre-aligned 112x112 face (ctypes only). Input: float32 HWC in [-1, 1]. Returns 512-dim float32 array.
+- **`detect(image, max_faces=None, *, embeddings=True)`** returns a list of dictionaries with `bbox`, `score` and `keypoints` for an RGB uint8 image. With `embeddings=True` each result also includes its vector.
+- **`embed(face_112x112)`** -- Compute embedding for a pre-aligned 112x112 face using either native backend. Input: float32 HWC in [-1, 1]. Returns 512 raw float32 values. Use cosine similarity to score two outputs.
- **`similarity(emb1, emb2)`** -- Static method. Cosine similarity between two 512-dim embeddings. Returns float in [-1, 1].
- **`close()`** -- Free native resources. Also works as context manager (`with FaceX() as fx: ...`).
- **`backend`** -- Property: `"ctypes"`, `"cli"`, or `"none"`.
@@ -134,7 +136,7 @@ sim = similarity(emb1, emb2)
| Backend | Requires | Detection | Embedding (standalone) |
|---|---|---|---|
| ctypes | `libfacex.so` / `facex.dll` | Yes | Yes |
-| cli | `facex-cli` binary | Yes | No (use detect) |
+| cli | `facex-cli` from this revision | Yes, native image dimensions | Yes |
| none | nothing | No | No |
Similarity always works (pure numpy).
diff --git a/python/facex/core.py b/python/facex/core.py
index 0f6ae2e..15e165d 100644
--- a/python/facex/core.py
+++ b/python/facex/core.py
@@ -6,6 +6,8 @@ import ctypes
import ctypes.util
import math
import os
+import operator
+import threading
import platform
import struct
import subprocess
@@ -113,7 +115,7 @@ def _find_cli() -> Optional[str]:
system = platform.system()
ext = ".exe" if system == "Windows" else ""
- names = [f"facex-cli{ext}", f"facex-example{ext}"]
+ names = [f"facex-cli{ext}"]
pkg_dir = Path(__file__).resolve().parent
facex_root = pkg_dir.parent.parent
@@ -141,9 +143,10 @@ def _find_weights() -> Tuple[Optional[str], Optional[str]]:
pkg_dir = Path(__file__).resolve().parent
facex_root = pkg_dir.parent.parent
+ facex_root = Path(os.environ.get("FACEX_ROOT") or facex_root)
weights_dir = facex_root / "weights"
- embed_names = ["embed.bin", "edgeface_fp32.bin", "edgeface.bin"]
+ embed_names = ["edgeface_xs_fp32.bin", "embed.bin", "edgeface_fp32.bin", "edgeface.bin"]
detect_names = ["detect.bin", "yunet_fp32.bin", "yunet.bin"]
embed_path = env_embed
@@ -156,6 +159,9 @@ def _find_weights() -> Tuple[Optional[str], Optional[str]]:
embed_path = str(p)
break
+ if not embed_path and (facex_root / "data/edgeface_xs_fp32.bin").is_file():
+ embed_path = str(facex_root / "data/edgeface_xs_fp32.bin")
+
if not detect_path:
for name in detect_names:
p = weights_dir / name
@@ -236,7 +242,11 @@ class FaceX:
self._lib = None
self._handle = None
self._cli_path = cli_path
- self._max_faces = max_faces
+ self._native_lock = threading.Lock()
+ self._license_key = license_key
+ self._max_faces = operator.index(max_faces)
+ if self._max_faces < 0:
+ raise ValueError("max_faces must be nonnegative")
if input_policy not in _POLICY_THRESHOLDS:
raise ValueError("Unknown detector input policy")
if min_box_side not in (8, 12, 16):
@@ -248,6 +258,8 @@ class FaceX:
score_threshold = {8: 0.75, 12: 0.74, 16: 0.70}[min_box_side]
else:
score_threshold = _POLICY_THRESHOLDS[input_policy]
+ if not (0 <= score_threshold <= 1 and 0 <= nms_threshold <= 1):
+ raise ValueError("Detector thresholds must be in [0, 1]")
self._score_threshold = score_threshold
self._nms_threshold = nms_threshold
@@ -257,7 +269,7 @@ class FaceX:
self._detect_weights = detect_weights or auto_detect
# Try ctypes first
- lib_file = lib_path or _find_lib()
+ lib_file = lib_path or (None if cli_path else _find_lib())
if lib_file:
try:
self._init_ctypes(lib_file, license_key)
@@ -355,8 +367,8 @@ class FaceX:
ctypes.c_void_p, pixel, ctypes.c_int, ctypes.c_int, scalar, scalar]
# Init engine
- embed_b = self._embed_weights.encode() if self._embed_weights else None
- detect_b = self._detect_weights.encode() if self._detect_weights else None
+ embed_b = os.fsencode(self._embed_weights) if self._embed_weights else None
+ detect_b = os.fsencode(self._detect_weights) if self._detect_weights else None
key_b = license_key.encode() if license_key else None
self._handle = self._lib.facex_init(embed_b, detect_b, key_b)
@@ -404,16 +416,19 @@ class FaceX:
raise ValueError(f"Expected HWC RGB uint8 image, got shape {image.shape}")
h, w = image.shape[:2]
- mf = max_faces or self._max_faces
+ mf = self._max_faces if max_faces is None else operator.index(max_faces)
+ if mf < 0 or w == 0 or h == 0:
+ raise ValueError("Expected nonempty image and nonnegative max_faces")
+ if mf == 0:
+ return []
+ mf = min(mf, 32)
if self._input_policy != "native" and self.backend != "ctypes":
raise RuntimeError("Rectangle input requires the native FaceX shared library")
if self._lib and self._handle:
return self._detect_ctypes(image, w, h, mf, embeddings)
elif self._cli_path:
- if not embeddings or self._min_box_side != 16:
- raise RuntimeError("This detection option requires the native shared library")
- return self._detect_cli(image, w, h, mf)
+ return self._detect_cli(image, w, h, mf, embeddings)
else:
raise RuntimeError(
"No backend available. Install the shared library or set FACEX_CLI."
@@ -429,16 +444,19 @@ class FaceX:
side = side or (800 if self._input_policy == "rectangle_bgr_800" else 640)
canvas, rw, rh = prepare_rectangle(image, bgr=self._input_policy != "rectangle", side=side)
ch, cw = canvas.shape[:2]
- args = (self._handle, ptr, w, h, canvas.ctypes.data_as(pixels), cw, ch,
- rw, rh, results, max_faces)
- if hasattr(self._lib, "facex_detect_prepared_ex"):
- n = self._lib.facex_detect_prepared_ex(*args, int(embeddings), threshold)
- elif not embeddings or threshold >= 0:
- raise RuntimeError("This option requires an updated native library")
- elif self._input_policy == "native":
- n = self._lib.facex_detect(self._handle, ptr, w, h, results, max_faces)
- else:
- n = self._lib.facex_detect_prepared(*args)
+ with self._native_lock:
+ if not self._handle:
+ raise RuntimeError("FaceX handle is closed")
+ args = (self._handle, ptr, w, h, canvas.ctypes.data_as(pixels), cw, ch,
+ rw, rh, results, max_faces)
+ if hasattr(self._lib, "facex_detect_prepared_ex"):
+ n = self._lib.facex_detect_prepared_ex(*args, int(embeddings), threshold)
+ elif not embeddings or threshold >= 0:
+ raise RuntimeError("This option requires an updated native library")
+ elif self._input_policy == "native":
+ n = self._lib.facex_detect(self._handle, ptr, w, h, results, max_faces)
+ else:
+ n = self._lib.facex_detect_prepared(*args)
if n < 0:
raise RuntimeError(f"facex_detect returned error code {n}")
return [_result_to_dict(results[i], embeddings) for i in range(n)]
@@ -484,72 +502,47 @@ class FaceX:
h, w = image.shape[:2]
scalar = ctypes.POINTER(ctypes.c_float)
vec = np.empty(512, dtype=np.float32)
- rc = self._lib.facex_embed_landmarks(
- self._handle, image.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)), w, h,
- points.ctypes.data_as(scalar), vec.ctypes.data_as(scalar))
+ with self._native_lock:
+ if not self._handle:
+ raise RuntimeError("FaceX handle is closed")
+ rc = self._lib.facex_embed_landmarks(
+ self._handle, image.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)), w, h,
+ points.ctypes.data_as(scalar), vec.ctypes.data_as(scalar))
if rc < 0:
raise RuntimeError("Landmark embedding failed")
return vec
- def _detect_cli(self, image: np.ndarray, w: int, h: int, max_faces: int) -> List[dict]:
- """Subprocess fallback: pipe image data to CLI and parse output."""
- # Build command — the CLI protocol:
- # stdin: 4 bytes width (le) + 4 bytes height (le) + w*h*3 bytes RGB uint8
- # stdout: 4 bytes num_faces (le) + num_faces * FaceXResult as raw floats
- args = [self._cli_path, "--detect", "--pipe"]
- if self._embed_weights:
+ def _detect_cli(self, image, w, h, max_faces, embeddings):
+ if not self._detect_weights:
+ raise RuntimeError("Detection requires YuNet weights")
+ args = [self._cli_path, "--detect", "--pipe", "--detect-weights", self._detect_weights,
+ "--max-faces", str(max_faces), "--score-threshold", str(self._score_threshold),
+ "--nms-threshold", str(self._nms_threshold), "--min-box-side", str(self._min_box_side)]
+ if self._embed_weights and embeddings:
args.extend(["--embed-weights", self._embed_weights])
- if self._detect_weights:
- args.extend(["--detect-weights", self._detect_weights])
- args.extend(["--max-faces", str(max_faces)])
- args.extend(["--score-threshold", str(self._score_threshold)])
-
- header = struct.pack("<ii", w, h)
- input_data = header + image.tobytes()
-
+ if not embeddings:
+ args.append("--no-embeddings")
+ data = self._run_cli(args, struct.pack("<ii", w, h) + image.tobytes())
+ if len(data) < 4:
+ raise RuntimeError("Missing face count from facex-cli")
+ count = struct.unpack_from("<i", data)[0]
+ if not 0 <= count <= max_faces or len(data) != 4 + count * _RESULT_BYTES:
+ raise RuntimeError("Invalid face count or record length from facex-cli")
+ return [_result_to_dict(FaceXResult.from_buffer_copy(data, 4 + i * _RESULT_BYTES), embeddings)
+ for i in range(count)]
+
+ def _run_cli(self, args, input_data):
+ env = None
+ if self._license_key is not None:
+ env = {**os.environ, "LICENSE_KEY": self._license_key}
try:
- proc = subprocess.run(
- args,
- input=input_data,
- capture_output=True,
- timeout=30,
- )
- except FileNotFoundError:
- raise RuntimeError(f"CLI not found: {self._cli_path}")
- except subprocess.TimeoutExpired:
- raise RuntimeError("facex-cli timed out")
-
- if proc.returncode != 0:
- stderr = proc.stderr.decode(errors="replace").strip()
- raise RuntimeError(f"facex-cli failed (rc={proc.returncode}): {stderr}")
-
- out = proc.stdout
- if len(out) < 4:
- raise RuntimeError("facex-cli produced no output")
-
- n = struct.unpack("<i", out[:4])[0]
- expected = 4 + n * _RESULT_BYTES
- if len(out) < expected:
- raise RuntimeError(
- f"Incomplete output: expected {expected} bytes, got {len(out)}"
- )
-
- faces = []
- offset = 4
- for i in range(n):
- floats = struct.unpack_from(f"<{_RESULT_FLOATS}f", out, offset)
- offset += _RESULT_BYTES
- x1, y1, x2, y2, score = floats[:5]
- kps_raw = floats[5:15]
- emb = np.array(floats[15:], dtype=np.float32)
- keypoints = [(kps_raw[j], kps_raw[j + 1]) for j in range(0, 10, 2)]
- faces.append({
- "bbox": (x1, y1, x2, y2),
- "score": score,
- "keypoints": keypoints,
- "embedding": emb,
- })
- return faces
+ proc = subprocess.run(args, input=input_data, capture_output=True, timeout=30, env=env)
+ except (OSError, subprocess.TimeoutExpired) as error:
+ raise RuntimeError(f"Cannot run facex-cli: {error}") from error
+ if proc.returncode:
+ message = proc.stderr.decode(errors="replace").strip()
+ raise RuntimeError(f"facex-cli failed (rc={proc.returncode}): {message}")
+ return proc.stdout
def embed(self, face_112x112: np.ndarray) -> np.ndarray:
"""
@@ -559,7 +552,7 @@ class FaceX:
face_112x112: float32 numpy array shape (112, 112, 3), values in [-1, 1].
Returns:
- numpy float32 array of shape (512,), L2-normalized.
+ numpy float32 array of shape (512,) with raw EdgeFace components.
"""
face = np.ascontiguousarray(face_112x112, dtype=np.float32)
if face.shape != (112, 112, 3):
@@ -567,17 +560,21 @@ class FaceX:
if self._lib and self._handle:
return self._embed_ctypes(face)
- else:
- raise RuntimeError(
- "embed() requires the shared library (ctypes backend). "
- "Use detect() which includes embedding, or install libfacex."
- )
+ if self._cli_path and self._embed_weights:
+ data = self._run_cli([self._cli_path, self._embed_weights, "--server"], face.tobytes())
+ if len(data) != EMBEDDING_DIM * 4:
+ raise RuntimeError("Invalid embedding length from facex-cli")
+ return np.frombuffer(data, dtype="<f4").copy()
+ raise RuntimeError("Embedding requires a native backend and EdgeFace weights")
def _embed_ctypes(self, face: np.ndarray) -> np.ndarray:
embedding = np.zeros(EMBEDDING_DIM, dtype=np.float32)
ptr_in = face.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
ptr_out = embedding.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
- rc = self._lib.facex_embed(self._handle, ptr_in, ptr_out)
+ with self._native_lock:
+ if not self._handle:
+ raise RuntimeError("FaceX handle is closed")
+ rc = self._lib.facex_embed(self._handle, ptr_in, ptr_out)
if rc != 0:
raise RuntimeError(f"facex_embed returned error code {rc}")
return embedding
@@ -589,9 +586,11 @@ class FaceX:
def close(self):
"""Release native resources."""
- if self._lib and self._handle:
- self._lib.facex_free(self._handle)
- self._handle = None
+ with self._native_lock:
+ if self._lib and self._handle:
+ self._lib.facex_free(self._handle)
+ self._handle = None
+ self._cli_path = None
def __del__(self):
try:
diff --git a/python/pyproject.toml b/python/pyproject.toml
index 1cc2831..6f2b4b7 100644
--- a/python/pyproject.toml
+++ b/python/pyproject.toml
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "facex"
version = "0.1.0"
-description = "Python binding for FaceX face detection + recognition"
+description = "Local YuNet face detection, EdgeFace embeddings and identity galleries with native library and CLI backends"
readme = "README.md"
requires-python = ">=3.8"
license = {text = "Apache-2.0"}
diff --git a/src/cli_detect.c b/src/cli_detect.c
new file mode 100644
index 0000000..9a6d32d
--- /dev/null
+++ b/src/cli_detect.c
@@ -0,0 +1,77 @@
+/* Binary detector transport used by the Python subprocess backend. */
+#include "facex.h"
+#include <errno.h>
+#include <limits.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _WIN32
+#include <fcntl.h>
+#include <io.h>
+#endif
+
+static int read_limit(const char *s, int *value) {
+ char *end;
+ errno = 0;
+ long n = strtol(s, &end, 10);
+ if (errno || end == s || *end || n < 0 || n > INT_MAX) return 0;
+ *value = (int)n;
+ return 1;
+}
+
+static int read_threshold(const char *s, float *value) {
+ char *end;
+ float n = strtof(s, &end);
+ if (end == s || *end || !isfinite(n) || n < 0 || n > 1) return 0;
+ *value = n;
+ return 1;
+}
+
+int facex_cli_detect(int argc, char **argv) {
+ const char *detector = NULL, *embedder = NULL;
+ int limit = 20, min_side = 16, embed = 1;
+ float score = 0.5f, nms = 0.4f;
+ if (argc < 3 || strcmp(argv[2], "--pipe")) return 2;
+ for (int i = 3; i < argc; i++) {
+ const char *flag = argv[i];
+ if (!strcmp(flag, "--no-embeddings")) { embed = 0; continue; }
+ if (++i == argc) return 2;
+ const char *value = argv[i];
+ if (!strcmp(flag, "--detect-weights")) detector = value;
+ else if (!strcmp(flag, "--embed-weights")) embedder = value;
+ else if (!strcmp(flag, "--max-faces") && read_limit(value, &limit)) continue;
+ else if (!strcmp(flag, "--min-box-side") && read_limit(value, &min_side) &&
+ (min_side == 8 || min_side == 12 || min_side == 16)) continue;
+ else if (!strcmp(flag, "--score-threshold") && read_threshold(value, &score)) continue;
+ else if (!strcmp(flag, "--nms-threshold") && read_threshold(value, &nms)) continue;
+ else return 2;
+ }
+ if (!detector) { fputs("Missing detector weights\n", stderr); return 2; }
+#ifdef _WIN32
+ _setmode(_fileno(stdin), _O_BINARY);
+ _setmode(_fileno(stdout), _O_BINARY);
+#endif
+ int32_t size[2];
+ if (fread(size, sizeof(size), 1, stdin) != 1 || size[0] <= 0 || size[1] <= 0 ||
+ (size_t)size[0] > SIZE_MAX / 3 / (size_t)size[1]) return 1;
+ size_t bytes = (size_t)size[0] * size[1] * 3;
+ uint8_t *rgb = malloc(bytes);
+ if (!rgb) return 1;
+ int ok = 0;
+ if (fread(rgb, 1, bytes, stdin) == bytes) {
+ FaceX *fx = facex_init(embed ? embedder : NULL, detector, getenv("LICENSE_KEY"));
+ if (fx) {
+ FaceXResult faces[32];
+ facex_set_nms_threshold(fx, nms);
+ facex_set_min_box_side(fx, min_side);
+ int32_t n = facex_detect_prepared_ex(fx, rgb, size[0], size[1], rgb,
+ size[0], size[1], size[0], size[1], faces, limit, embed, score);
+ ok = n >= 0 && fwrite(&n, sizeof(n), 1, stdout) == 1 &&
+ fwrite(faces, sizeof(*faces), n, stdout) == (size_t)n && fflush(stdout) == 0;
+ facex_free(fx);
+ }
+ }
+ free(rgb);
+ return ok ? 0 : 1;
+}
diff --git a/src/detect.c b/src/detect.c
index fe5f9c0..f836196 100644
--- a/src/detect.c
+++ b/src/detect.c
@@ -65,14 +65,26 @@ Detect* detect_init(const char* weights_path) {
fprintf(stderr, "detect: bad magic\n"); free(det->raw); free(det); return NULL;
}
uint32_t n = *(uint32_t*)(det->raw + 4);
- if (n > DETECT_MAX_TENSORS) { free(det->raw); free(det); return NULL; }
+ /* Number of FP32 values used from each tensor in the March 2023 YuNet export. */
+ static const uint32_t required[] = {
+ 432, 16, 144, 16, 144, 16, 288, 32, 288, 32, 576, 64, 576, 64,
+ 576, 64, 576, 64, 576, 64, 576, 64, 576, 64, 576, 64, 576, 64,
+ 576, 64, 4, 4, 16, 256, 16, 256, 32, 512, 32, 1024, 64, 2048,
+ 64, 4096, 64, 4096, 64, 4096, 64, 4096, 64, 4096, 64, 4096, 4, 256,
+ 4, 36, 4, 256, 4, 36, 4, 256, 4, 36, 1, 64, 1, 9,
+ 1, 64, 1, 9, 1, 64, 1, 9, 10, 640, 10, 90, 10, 640,
+ 10, 90, 10, 640, 10, 90, 1, 64, 1, 9, 1, 64, 1, 9,
+ 1, 64, 1, 9, 64, 4096, 64, 4096, 64, 4096, 0, 3, 3, 3,
+ };
+ if (n < sizeof(required)/sizeof(*required) || n > DETECT_MAX_TENSORS) { free(det->raw); free(det); return NULL; }
det->n_tensors = (int)n;
size_t off = 8;
for (int i = 0; i < det->n_tensors; i++) {
- if (off + 4 > det->raw_len) { free(det->raw); free(det); return NULL; }
+ if (det->raw_len - off < 4) { free(det->raw); free(det); return NULL; }
uint32_t sz = *(uint32_t*)(det->raw + off); off += 4;
- if (off + sz > det->raw_len) { free(det->raw); free(det); return NULL; }
+ if (sz > det->raw_len - off || sz % sizeof(float) ||
+ ((size_t)i < sizeof(required)/sizeof(*required) && sz / sizeof(float) < required[i])) { free(det->raw); free(det); return NULL; }
det->tensors[i] = (float*)(det->raw + off); off += sz;
}
diff --git a/src/edgeface_engine.c b/src/edgeface_engine.c
index 9463dca..7006d27 100644
--- a/src/edgeface_engine.c
+++ b/src/edgeface_engine.c
@@ -42,19 +42,7 @@ extern void l2_normalize_fp32(float*, int, int, float);
extern void depthwise_conv_nxn_hwc_fp32(const float*, int, int, int, const float*, const float*, int, float*);
/* ============ Weight loader ============ */
-/* INT8 packed MatMul weight */
-typedef struct {
- void* packed;
- int32_t* col_sums;
- float* w_scales;
- int K, N; /* original dimensions */
-} PackedMM;
-
-/* FP32 pre-packed MatMul weight (column-panel format for cache-friendly access) */
-typedef struct {
- float* data; /* packed [ceil(N/8), K, 8] — 32-byte aligned */
- int K, N;
-} PackedFP32;
+#include "edgeface_packed.h"
typedef struct {
float** tensors; /* array of float pointers */
@@ -62,7 +50,8 @@ typedef struct {
uint8_t* raw; /* raw file data */
size_t raw_size;
/* INT8 pre-packed MatMul weights */
- PackedMM* mm; /* array, indexed same as tensors */
+ QuantScratch scratch;
+ float *workspace;
/* FP32 pre-packed MatMul weights */
float* cached_position;
PackedFP32* fp; /* array, indexed same as tensors */
@@ -96,7 +85,35 @@ static int load_weights(const char* path, Weights* w, const char* license_key) {
if (size < 8 || memcmp(payload, "EFXS", 4) != 0) return -1;
uint32_t n;
memcpy(&n, payload + 4, sizeof(n));
- if (n < 286 || n > (size-8)/4 || n > INT_MAX) return -1;
+ /* Float counts for the tensors read by the fixed EdgeFace XS graph. */
+ static const uint32_t required[] = {
+ 1536, 32, 32, 32, 288, 32, 32, 32, 608, 2432, 128, 1,
+ 1, 1, 2432, 608, 32, 32, 288, 32, 32, 32, 608, 2432,
+ 128, 2432, 608, 32, 32, 288, 32, 32, 32, 608, 2432, 128,
+ 2432, 608, 32, 32, 32, 32, 8192, 64, 1600, 64, 64, 64,
+ 2432, 9728, 256, 9728, 2432, 64, 64, 1600, 64, 64, 64, 2432,
+ 9728, 256, 9728, 2432, 64, 64, 288, 32, 3, 12544, 4096, 64,
+ 64, 64, 2432, 7296, 192, 5, 1, 1, 1, 1, 1, 1,
+ 4, 4, 3, 2432, 2432, 64, 64, 4, 64, 64, 2432, 9728,
+ 256, 9728, 2432, 64, 64, 64, 64, 25600, 100, 4900, 100, 100,
+ 100, 6000, 24000, 400, 24000, 6000, 100, 100, 4900, 100, 100, 100,
+ 6000, 24000, 400, 24000, 6000, 100, 100, 4900, 100, 100, 100, 6000,
+ 24000, 400, 24000, 6000, 100, 100, 4900, 100, 100, 100, 6000, 24000,
+ 400, 24000, 6000, 100, 100, 4900, 100, 100, 100, 6000, 24000, 400,
+ 24000, 6000, 100, 100, 4900, 100, 100, 100, 6000, 24000, 400, 24000,
+ 6000, 100, 100, 4900, 100, 100, 100, 6000, 24000, 400, 24000, 6000,
+ 100, 100, 4900, 100, 100, 100, 6000, 24000, 400, 24000, 6000, 100,
+ 100, 306, 34, 306, 34, 3, 100, 100, 6000, 18000, 300, 5,
+ 4, 4, 3, 6000, 6000, 100, 100, 4, 100, 100, 6000, 24000,
+ 400, 24000, 6000, 100, 100, 100, 100, 76800, 192, 15552, 192, 192,
+ 192, 22080, 88320, 768, 88320, 22080, 192, 192, 15552, 192, 192, 192,
+ 22080, 88320, 768, 88320, 22080, 192, 192, 432, 48, 432, 48, 432,
+ 48, 3, 192, 192, 22080, 66240, 576, 5, 4, 4, 3, 22080,
+ 22080, 192, 192, 4, 192, 192, 22080, 88320, 768, 88320, 22080, 192,
+ 192, 2, 1, 1, 192, 192, 2, 22080, 58880, 512,
+ };
+ const size_t required_count = sizeof(required) / sizeof(required[0]);
+ if (n < required_count || n > (size - 8) / 4 || n > INT_MAX) return -1;
w->n_tensors = (int)n;
w->tensors = calloc(n, sizeof(*w->tensors));
if (!w->tensors) return -1;
@@ -106,7 +123,8 @@ static int load_weights(const char* path, Weights* w, const char* license_key) {
if (size-off < sizeof(bytes)) return -1;
memcpy(&bytes, payload+off, sizeof(bytes));
off += sizeof(bytes);
- if (bytes > size-off || bytes % sizeof(float)) return -1;
+ if (bytes > size - off || bytes % sizeof(float) ||
+ (i < required_count && bytes / sizeof(float) < required[i])) return -1;
w->tensors[i] = (float*)(payload+off);
off += bytes;
}
@@ -501,13 +519,6 @@ static void conv2d(const float* in, int Cin, int H, int W,
}
/* ============ MatMul with optional INT8 acceleration ============ */
-static void matmul_auto(const float* A, int M, int K, int N,
- const float* B_fp32, const PackedMM* mm)
-{
- /* Allocate output — caller must know where to put result */
- /* Actually this doesn't work — we need output pointer. Rethink. */
-}
-
/* Use matmul that checks for pre-packed FP32 or INT8 weights */
extern void matmul_fp32_packed(const float*, const float*, float*, int, int, int);
@@ -518,26 +529,16 @@ extern void matmul_fp32_packed_bias(const float*, const float*, const float*, fl
extern void matmul_specialized(const float*, const float*, float*, int, int, int);
extern void matmul_jit_or_packed(const float*, const float*, float*, int, int, int);
-static Weights* _g_weights = NULL; /* set in forward pass for INT8 lookup */
/* Zero-overhead matmul: INT8 when available, FP32 fallback */
static inline void matmul_wp(const float* A, float* C,
int M, int K, int N, const PackedFP32* fp)
{
#ifndef FACEX_FP32_ONLY
- /* Use INT8 VNNI for large matmuls where VNNI throughput > quant overhead.
- * For small K*N (<4096), FP32 packed is faster due to zero quant overhead. */
- if (_g_weights && _g_weights->mm) {
- int idx = (int)(fp - _g_weights->fp);
- if (idx >= 0 && idx < _g_weights->n_tensors) {
- PackedMM* mm = &_g_weights->mm[idx];
- if (mm->packed && mm->w_scales && mm->N >= 8 && (int64_t)mm->K * mm->N >= 4096) {
- extern void matmul_dynamic_int8(const float*, int, int, int,
- const void*, const int32_t*, const float*, float*);
- matmul_dynamic_int8(A, M, mm->K, mm->N, mm->packed, mm->col_sums, mm->w_scales, C);
- return;
- }
- }
+ if (fp->quant.packed) {
+ matmul_dynamic_int8(A, M, K, N, fp->quant.packed, fp->quant.col_sums,
+ fp->quant.w_scales, C, fp->scratch);
+ return;
}
#endif
matmul_fp32_packed(A, fp->data, C, M, fp->K, fp->N);
@@ -659,14 +660,8 @@ static void edgeface_forward(const float* input_chw, /* [3, 112, 112] */
Weights* weights,
float* embedding) /* [512] */
{
- _g_weights = weights; /* enable INT8 lookup in matmul_wp */
- /* Static workspace — avoids malloc overhead on every call */
- /* Stage zero has the largest ConvNeXt scratch: HW * (C + rank + hidden).
- * The largest XCA attention layout at stage one needs 111960 floats. */
- static float work[784 * (32 + 19 + 128)];
- static float x_buf[784 * 32];
-
- float* x = x_buf;
+ float *x = weights->workspace;
+ float *work = x + 784 * 32;
/* === STEM: Conv 3→32 4×4 s4 → output directly in HWC === */
{
@@ -717,13 +712,11 @@ static void edgeface_forward(const float* input_chw, /* [3, 112, 112] */
* mlp_w2=14[128,19], mlp_w3=15[19,32], mlp_b3=16 */
/* Test: INT8 for first block only, FP32 for rest */
#define FP(i) (&weights->fp[i])
- #define I8(i) (&weights->mm[i]) /* INT8 packed */
/* TEST: first block INT8 to verify correctness */
convnext_block(x, 28,28,32, W(17), W(4),W(5),3, W(6),W(7),
W(8),W(9),W(10), W(14),W(15),W(16), 19,128, work,
FP(8),FP(9),FP(14),FP(15));
- /* Note: INT8 test disabled — need to change convnext_block to accept PackedMM* */
convnext_block(x, 28,28,32, W(28), W(18),W(19),3, W(20),W(21),
W(22),W(23),W(24), W(25),W(26),W(27), 19,128, work,
@@ -914,27 +907,23 @@ static void edgeface_forward(const float* input_chw, /* [3, 112, 112] */
}
}
- /* x and work are static — no free needed */
}
/* ============ Engine Init (used by both main and library API) ============ */
static void release_weights(Weights* w) {
- if (_g_weights == w) _g_weights = NULL;
- for (int i = 0; i < w->n_tensors; i++) {
- if (w->mm) {
- free(w->mm[i].packed);
- free(w->mm[i].w_scales);
- free(w->mm[i].col_sums);
- }
- if (w->fp) {
+ for (int i = 0; w->fp && i < w->n_tensors; i++) {
+ free(w->fp[i].quant.packed);
+ free(w->fp[i].quant.w_scales);
+ free(w->fp[i].quant.col_sums);
#ifdef _WIN32
- _aligned_free(w->fp[i].data);
+ _aligned_free(w->fp[i].data);
#else
- free(w->fp[i].data);
+ free(w->fp[i].data);
#endif
- }
}
- free(w->mm);
+ free(w->scratch.input);
+ free(w->scratch.output);
+ free(w->workspace);
free(w->fp);
free(w->cached_position);
free(w->tensors);
@@ -951,74 +940,52 @@ static int engine_init(const char* weights_path, Weights* weights, const char* l
weights->fp = (PackedFP32*)calloc(weights->n_tensors, sizeof(PackedFP32));
if (!weights->fp) goto fail;
+ weights->workspace = malloc((size_t)784 * (32 + 32 + 19 + 128) * sizeof(float));
+ if (!weights->workspace) goto fail;
+ static const struct { int index, k, n, rows; } projections[] = {
+ {8, 32, 19, 784}, {9, 19, 128, 784}, {14, 128, 19, 784}, {15, 19, 32, 784},
+ {22, 32, 19, 784}, {23, 19, 128, 784}, {25, 128, 19, 784}, {26, 19, 32, 784},
+ {33, 32, 19, 784}, {34, 19, 128, 784}, {36, 128, 19, 784}, {37, 19, 32, 784},
+ {48, 64, 38, 196}, {49, 38, 256, 196}, {51, 256, 38, 196}, {52, 38, 64, 196},
+ {59, 64, 38, 196}, {60, 38, 256, 196}, {62, 256, 38, 196}, {63, 38, 64, 196},
+ {74, 64, 38, 196}, {75, 38, 192, 196}, {87, 64, 38, 196}, {88, 38, 64, 196},
+ {94, 64, 38, 196}, {95, 38, 256, 196}, {97, 256, 38, 196}, {98, 38, 64, 196},
+ {109, 100, 60, 49}, {110, 60, 400, 49}, {112, 400, 60, 49}, {113, 60, 100, 49},
+ {120, 100, 60, 49}, {121, 60, 400, 49}, {123, 400, 60, 49}, {124, 60, 100, 49},
+ {131, 100, 60, 49}, {132, 60, 400, 49}, {134, 400, 60, 49}, {135, 60, 100, 49},
+ {142, 100, 60, 49}, {143, 60, 400, 49}, {145, 400, 60, 49}, {146, 60, 100, 49},
+ {153, 100, 60, 49}, {154, 60, 400, 49}, {156, 400, 60, 49}, {157, 60, 100, 49},
+ {164, 100, 60, 49}, {165, 60, 400, 49}, {167, 400, 60, 49}, {168, 60, 100, 49},
+ {175, 100, 60, 49}, {176, 60, 400, 49}, {178, 400, 60, 49}, {179, 60, 100, 49},
+ {186, 100, 60, 49}, {187, 60, 400, 49}, {189, 400, 60, 49}, {190, 60, 100, 49},
+ {200, 100, 60, 49}, {201, 60, 300, 49}, {207, 100, 60, 49}, {208, 60, 100, 49},
+ {214, 100, 60, 49}, {215, 60, 400, 49}, {217, 400, 60, 49}, {218, 60, 100, 49},
+ {229, 192, 115, 9}, {230, 115, 768, 9}, {232, 768, 115, 9}, {233, 115, 192, 9},
+ {240, 192, 115, 9}, {241, 115, 768, 9}, {243, 768, 115, 9}, {244, 115, 192, 9},
+ {256, 192, 115, 9}, {257, 115, 576, 9}, {263, 192, 115, 9}, {264, 115, 192, 9},
+ {270, 192, 115, 9}, {271, 115, 768, 9}, {273, 768, 115, 9}, {274, 115, 192, 9},
+ };
+ extern void pack_b_fp32(const float*, int, int, float*);
+ extern int packed_b_fp32_size(int, int);
#ifndef FACEX_FP32_ONLY
- weights->mm = (PackedMM*)calloc(weights->n_tensors, sizeof(PackedMM));
- if (!weights->mm) goto fail;
-
- /* Pre-pack MatMul weights to INT8 c8 format */
- {
- extern void pack_weights_4x8c8(const int8_t*, const float*, int, int, void*, int32_t*);
- extern int packed_weights_size_4x8c8(int, int);
-
- /* MatMul weight indices (2D tensors used in MatMul) */
- int mm_idx[] = {8,9,14,15,22,23,25,26,33,34,36,37,48,49,51,52,59,60,62,63,
- 74,75,87,88,94,95,97,98,109,110,112,113,120,121,123,124,
- 131,132,134,135,142,143,145,146,153,154,156,157,164,165,
- 167,168,175,176,178,179,186,187,189,190,200,201,207,208,
- 214,215,217,218,229,230,232,233,240,241,243,244,256,257,
- 263,264,270,271,273,274,283,284,-1};
-
- /* Weight sizes from names.txt (K×N pairs) */
- /* Each weight W[K,N] is used as: A[M,K] @ W[K,N] → C[M,N]
- * c8 GEMM expects B as [N, K] (Cout=N, K=K)
- * So we need to transpose W to [N, K] before packing */
- int mm_shapes[][2] = {
- {32,19},{19,128},{128,19},{19,32}, /* stage 0 block 0 */
- {32,19},{19,128},{128,19},{19,32}, /* stage 0 block 1 */
- {32,19},{19,128},{128,19},{19,32}, /* stage 0 block 2 */
- {64,38},{38,256},{256,38},{38,64}, /* stage 1 block 0 */
- {64,38},{38,256},{256,38},{38,64}, /* stage 1 block 1 */
- {64,38},{38,192}, /* stage 1 attn QKV proj */
- {64,38},{38,64}, /* stage 1 attn out proj */
- {64,38},{38,256},{256,38},{38,64}, /* stage 1 attn MLP */
- /* stage 2: 8 blocks × 4 weights */
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- /* stage 2 attn */
- {100,60},{60,300},
- {100,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- /* stage 3: 2 blocks */
- {192,115},{115,768},{768,115},{115,192},
- {192,115},{115,768},{768,115},{115,192},
- /* stage 3 attn */
- {192,115},{115,576},
- {192,115},{115,192},
- {192,115},{115,768},{768,115},{115,192},
- /* head */
- {115,192},{512,115},
- };
-
- int packed_count = 0;
- for (int i = 0; mm_idx[i] >= 0; i++) {
- int idx = mm_idx[i];
- int K = mm_shapes[i][0], N = mm_shapes[i][1];
-
- if (N < 8) continue; /* Skip tiny N (c8 GEMM needs N≥8) */
-
+ extern void pack_weights_4x8c8(const int8_t*, const float*, int, int, void*, int32_t*);
+ extern int packed_weights_size_4x8c8(int, int);
+ size_t input_size = 0, output_size = 0;
+#endif
+ for (size_t i = 0; i < sizeof(projections)/sizeof(*projections); i++) {
+ int idx = projections[i].index, K = projections[i].k, N = projections[i].n;
+ PackedFP32 *fp = &weights->fp[idx];
+ fp->K = K;
+ fp->N = N;
+#ifndef FACEX_FP32_ONLY
+ if (N >= 8 && K * N >= 4096) {
float* w_fp32 = weights->tensors[idx]; /* [K, N] row-major */
/* Quantize per-output-channel: transpose to [N, K], quantize per N */
int8_t* w_int8 = (int8_t*)malloc((size_t)N * K);
float* w_scales = (float*)malloc(N * sizeof(float));
- weights->mm[idx].w_scales = w_scales;
+ fp->quant.w_scales = w_scales;
if (!w_int8 || !w_scales) { free(w_int8); goto fail; }
for (int n = 0; n < N; n++) {
float mx = 0;
@@ -1041,85 +1008,34 @@ static int engine_init(const char* weights_path, Weights* weights, const char* l
int32_t* col_sums = (int32_t*)calloc(((N+7)&~7), sizeof(int32_t));
- weights->mm[idx].packed = packed;
- weights->mm[idx].col_sums = col_sums;
+ fp->quant.packed = packed;
+ fp->quant.col_sums = col_sums;
if (!packed || !col_sums) { free(w_int8); goto fail; }
pack_weights_4x8c8(w_int8, NULL, K, N, packed, col_sums);
- weights->mm[idx].K = K;
- weights->mm[idx].N = N;
- packed_count++;
-
free(w_int8);
+ fp->scratch = &weights->scratch;
+ size_t rows = projections[i].rows;
+ size_t a = rows * ((K + 7) & ~7), y = rows * N;
+ if (a > input_size) input_size = a;
+ if (y > output_size) output_size = y;
+ continue;
}
- }
-
#endif
-
- /* Pre-pack FP32 MatMul weights into column-panel format [ceil(N/8), K, 8] */
- {
- extern void pack_b_fp32(const float*, int, int, float*);
- extern int packed_b_fp32_size(int, int);
- /* Same indices and shapes as INT8 packing */
- int fp_idx[] = {8,9,14,15,22,23,25,26,33,34,36,37,48,49,51,52,59,60,62,63,
- 74,75,87,88,94,95,97,98, /* stage 1 XCA */
- 109,110,112,113,120,121,123,124,131,132,134,135,142,143,145,146,
- 153,154,156,157,164,165,167,168,175,176,178,179,186,187,189,190,
- 200,201,207,208,214,215,217,218, /* stage 2 XCA */
- 229,230,232,233,240,241,243,244,
- 256,257,263,264,270,271,273,274, /* stage 3 XCA */
- -1};
- int fp_shapes[][2] = {
- {32,19},{19,128},{128,19},{19,32},
- {32,19},{19,128},{128,19},{19,32},
- {32,19},{19,128},{128,19},{19,32},
- {64,38},{38,256},{256,38},{38,64},
- {64,38},{38,256},{256,38},{38,64},
- {64,38},{38,192}, {64,38},{38,64}, {64,38},{38,256},{256,38},{38,64}, /* s1 XCA */
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,400},{400,60},{60,100},
- {100,60},{60,300}, {100,60},{60,100}, {100,60},{60,400},{400,60},{60,100}, /* s2 XCA */
- {192,115},{115,768},{768,115},{115,192},
- {192,115},{115,768},{768,115},{115,192},
- {192,115},{115,576}, {192,115},{115,192}, {192,115},{115,768},{768,115},{115,192}, /* s3 XCA */
- };
- for (int i = 0; fp_idx[i] >= 0; i++) {
- int idx = fp_idx[i];
- int K_ = fp_shapes[i][0], N_ = fp_shapes[i][1];
- int sz = packed_b_fp32_size(K_, N_);
- float* packed;
+ size_t bytes = (size_t)packed_b_fp32_size(K, N) * sizeof(float);
#ifdef _WIN32
- packed = (float*)_aligned_malloc((size_t)sz * sizeof(float), 64);
+ fp->data = _aligned_malloc(bytes, 64);
#else
- packed = (float*)aligned_alloc(32, (size_t)sz * sizeof(float));
+ fp->data = aligned_alloc(64, (bytes + 63) & ~(size_t)63);
#endif
- if (!packed) goto fail;
- pack_b_fp32(weights->tensors[idx], K_, N_, packed);
- weights->fp[idx].data = packed;
- weights->fp[idx].K = K_;
- weights->fp[idx].N = N_;
- }
+ if (!fp->data) goto fail;
+ pack_b_fp32(weights->tensors[idx], K, N, fp->data);
}
+#ifndef FACEX_FP32_ONLY
+ weights->scratch.input = malloc(input_size);
+ weights->scratch.output = malloc(output_size * sizeof(int32_t));
+ if (!weights->scratch.input || !weights->scratch.output) goto fail;
+#endif
- /* Pre-transpose DW conv weights: [C, K*K] → [K*K, C] for HWC AVX2 loads */
- /* DW weight tensor indices from names.txt */
- int dw_indices[] = {4,18,29, 44,55, 66, 105,116,127,138,149,160,171,182, 193,195,
- 225,236, 247,249,251, -1};
- int dw_K[] = {3,3,3, 5,5, 3, 7,7,7,7,7,7,7,7, 3,3, 9,9, 3,3,3};
- for (int di = 0; dw_indices[di] >= 0; di++) {
- int idx = dw_indices[di];
- int K = dw_K[di];
- int KK = K * K;
- /* Find C from weight shape: weight is [C, 1, K, K] = C*KK floats */
- /* We need to know C — get from the next tensor (bias) which has C floats */
- /* Actually just compute: total_floats / KK */
- /* But we don't store sizes... just hardcode known C values */
- }
/* Simpler: transpose in-place in the weight buffer */
/* DW weights are [C, K*K] stored contiguously. Transpose to [K*K, C] */
{
@@ -1220,8 +1136,12 @@ fail:
}
/* ============ Main ============ */
-#ifndef FACEX_LIB
+#if !defined(FACEX_LIB) || defined(FACEX_BUILD_CLI)
int main(int argc, char** argv) {
+#ifdef FACEX_BUILD_CLI
+ extern int facex_cli_detect(int, char **);
+ if (argc > 1 && !strcmp(argv[1], "--detect")) return facex_cli_detect(argc, argv);
+#endif
const char* license_key = NULL;
const char* weights_path = "data/edgeface_xs_fp32.bin";
if (argc > 1) weights_path = argv[1];
@@ -1275,8 +1195,13 @@ int main(int argc, char** argv) {
* --batch: reads CHW float32 directly (Python test protocol) */
while (1) {
float* read_buf = is_server ? hwc_buf : input;
- if (fread(read_buf, sizeof(float), 3*112*112, stdin) != 3*112*112)
- break;
+ size_t bytes = fread(read_buf, 1, sizeof(input), stdin);
+ if (bytes == 0 && feof(stdin)) break;
+ if (bytes != sizeof(input)) {
+ fputs("Incomplete embedding request\n", stderr);
+ release_weights(&weights);
+ return 1;
+ }
if (is_server) {
/* HWC → CHW conversion */
for (int h = 0; h < 112; h++)
@@ -1285,8 +1210,10 @@ int main(int argc, char** argv) {
input[c * 112 * 112 + h * 112 + w] = hwc_buf[(h * 112 + w) * 3 + c];
}
edgeface_forward(input, &weights, embedding);
- fwrite(embedding, sizeof(float), 512, stdout);
- fflush(stdout);
+ if (fwrite(embedding, sizeof(float), 512, stdout) != 512 || fflush(stdout) != 0) {
+ release_weights(&weights);
+ return 1;
+ }
}
} else {
/* Single image: warmup + benchmark */
diff --git a/src/edgeface_engine_v2.c b/src/edgeface_engine_v2.c
index 14c555f..4915cce 100644
--- a/src/edgeface_engine_v2.c
+++ b/src/edgeface_engine_v2.c
@@ -38,11 +38,7 @@ extern void conv2d_hwc(const float* in_hwc, int Cin, int H, int W,
const float* w_packed, const float* b, int Cout,
int K, int stride, float* out_hwc);
-/* PackedFP32 type — must match definition in edgeface_engine.c */
-typedef struct {
- float* data;
- int K, N;
-} PackedFP32;
+#include "edgeface_packed.h"
/* Block primitives from edgeface_engine.c (now exposed by removing static). */
extern void convnext_block(float* x_hwc, int H, int W, int C,
@@ -474,6 +470,7 @@ static void v2_pack_xca(V2_XCA *x, int C, int rank, int hidden)
int v2_engine_init(const char *path, V2_Engine *e)
{
+ memset(e, 0, sizeof(*e));
/* Load file into memory */
FILE *f = fopen(path, "rb");
if (!f) return -1;
diff --git a/src/edgeface_packed.h b/src/edgeface_packed.h
new file mode 100644
index 0000000..38c5083
--- /dev/null
+++ b/src/edgeface_packed.h
@@ -0,0 +1,27 @@
+#ifndef FACEX_EDGEFACE_PACKED_H
+#define FACEX_EDGEFACE_PACKED_H
+#include <stdint.h>
+
+typedef struct {
+ int8_t *input;
+ int32_t *output;
+} QuantScratch;
+
+typedef struct {
+ void *packed;
+ int32_t *col_sums;
+ float *w_scales;
+} PackedMM;
+
+typedef struct {
+ float *data;
+ int K, N;
+ PackedMM quant;
+ QuantScratch *scratch;
+} PackedFP32;
+
+#ifndef FACEX_FP32_ONLY
+void matmul_dynamic_int8(const float *, int, int, int, const void *, const int32_t *,
+ const float *, float *, QuantScratch *);
+#endif
+#endif
diff --git a/src/facex.c b/src/facex.c
index eecd940..dceea77 100644
--- a/src/facex.c
+++ b/src/facex.c
@@ -21,7 +21,24 @@
extern int align_face(const uint8_t* src_rgb, int src_w, int src_h,
const float kps[10], float* out_f32);
+#ifdef _WIN32
+#include <windows.h>
+typedef CRITICAL_SECTION FaceXMutex;
+static int mutex_init(FaceXMutex *m) { InitializeCriticalSection(m); return 0; }
+static void mutex_lock(FaceXMutex *m) { EnterCriticalSection(m); }
+static void mutex_unlock(FaceXMutex *m) { LeaveCriticalSection(m); }
+static void mutex_destroy(FaceXMutex *m) { DeleteCriticalSection(m); }
+#else
+#include <pthread.h>
+typedef pthread_mutex_t FaceXMutex;
+static int mutex_init(FaceXMutex *m) { return pthread_mutex_init(m, NULL); }
+static void mutex_lock(FaceXMutex *m) { pthread_mutex_lock(m); }
+static void mutex_unlock(FaceXMutex *m) { pthread_mutex_unlock(m); }
+static void mutex_destroy(FaceXMutex *m) { pthread_mutex_destroy(m); }
+#endif
+
struct FaceX {
+ FaceXMutex mutex;
Weights embed_weights;
Detect* detector;
int ready;
@@ -44,6 +61,12 @@ FaceX* facex_init(const char* embed_weights, const char* detect_weights, const c
return NULL;
}
+ if (mutex_init(&fx->mutex) != 0) {
+ if (fx->detector) detect_free(fx->detector);
+ release_weights(&fx->embed_weights);
+ free(fx);
+ return NULL;
+ }
fx->ready = 1;
return fx;
}
@@ -69,15 +92,18 @@ int facex_detect_prepared(FaceX* fx, const uint8_t* rgb_hwc, int width, int heig
int facex_detect_prepared_ex(FaceX* fx, const uint8_t* rgb_hwc, int width, int height,
const uint8_t* canvas, int canvas_w, int canvas_h,
int resized_w, int resized_h, FaceXResult* out, int max_faces, int embeddings, float threshold) {
- if (!fx || !fx->ready || !fx->detector || !rgb_hwc || !canvas || !out ||
- width <= 0 || height <= 0 || max_faces <= 0 ||
+ if (!fx || !fx->ready || !fx->detector || !rgb_hwc || !canvas || (max_faces > 0 && !out) ||
+ width <= 0 || height <= 0 || max_faces < 0 ||
resized_w <= 0 || resized_w > canvas_w ||
resized_h <= 0 || resized_h > canvas_h) return -1;
+ if (max_faces == 0) return 0;
DetectFace det_faces[32];
int n_det = max_faces < 32 ? max_faces : 32;
+ mutex_lock(&fx->mutex);
int n = threshold < 0 ? detect_run(fx->detector, canvas, canvas_w, canvas_h, det_faces, n_det)
: detect_run_threshold(fx->detector, canvas, canvas_w, canvas_h, det_faces, n_det, threshold);
+ mutex_unlock(&fx->mutex);
int dx = (canvas_w - resized_w) / 2, dy = (canvas_h - resized_h) / 2;
for (int i = 0; i < n; i++) {
DetectFace* face = &det_faces[i];
@@ -111,7 +137,7 @@ int facex_embed_landmarks(FaceX* fx, const uint8_t* rgb, int w, int h,
}
int facex_embed(FaceX* fx, const float* rgb_hwc, float embedding[512]) {
- if (!fx || !fx->ready) return -1;
+ if (!fx || !fx->embed_weights.raw || !rgb_hwc || !embedding) return -1;
float input_chw[3 * 112 * 112];
for (int h = 0; h < 112; h++)
@@ -119,7 +145,9 @@ int facex_embed(FaceX* fx, const float* rgb_hwc, float embedding[512]) {
for (int c = 0; c < 3; c++)
input_chw[c * 112 * 112 + h * 112 + w] = rgb_hwc[(h * 112 + w) * 3 + c];
+ mutex_lock(&fx->mutex);
edgeface_forward(input_chw, &fx->embed_weights, embedding);
+ mutex_unlock(&fx->mutex);
return 0;
}
@@ -136,6 +164,7 @@ float facex_similarity(const float emb1[512], const float emb2[512]) {
void facex_free(FaceX* fx) {
if (!fx) return;
+ mutex_destroy(&fx->mutex);
if (fx->detector) detect_free(fx->detector);
release_weights(&fx->embed_weights);
free(fx);
@@ -144,13 +173,22 @@ void facex_free(FaceX* fx) {
const char* facex_version(void) { return FACEX_VERSION; }
void facex_set_score_threshold(FaceX* fx, float t) {
- if (fx && fx->detector) detect_set_score_threshold(fx->detector, t);
+ if (!fx || !fx->detector) return;
+ mutex_lock(&fx->mutex);
+ detect_set_score_threshold(fx->detector, t);
+ mutex_unlock(&fx->mutex);
}
void facex_set_nms_threshold(FaceX* fx, float t) {
- if (fx && fx->detector) detect_set_nms_threshold(fx->detector, t);
+ if (!fx || !fx->detector) return;
+ mutex_lock(&fx->mutex);
+ detect_set_nms_threshold(fx->detector, t);
+ mutex_unlock(&fx->mutex);
}
void facex_set_min_box_side(FaceX* fx, int pixels) {
- if (fx) detect_set_min_box_side(fx->detector, pixels);
+ if (!fx || !fx->detector) return;
+ mutex_lock(&fx->mutex);
+ detect_set_min_box_side(fx->detector, pixels);
+ mutex_unlock(&fx->mutex);
}
diff --git a/src/facex_mfn.c b/src/facex_mfn.c
index 71d1de4..714378e 100644
--- a/src/facex_mfn.c
+++ b/src/facex_mfn.c
@@ -13,6 +13,7 @@
#include "../include/facex_mfn.h"
#include <stdio.h>
+#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
@@ -62,8 +63,9 @@ struct MfnEngine {
int n_blocks;
MfnConv final_conv, gdconv, embed_proj;
- /* Raw file buffer — all weight pointers index into freed memory below. */
+ /* Model storage and folded biases are owned by the handle. */
uint8_t *raw;
+ float *bias_slab;
size_t raw_size;
/* Workspace: two ping-pong NCHW buffers + a "residual save" slot. */
@@ -96,19 +98,25 @@ static int parse_header(const uint8_t *raw, size_t raw_size,
out->gdc_kernel = hdr[12];
if (out->n_stages > MFN_MAX_STAGES) return -5;
+ if (!out->stem_channels || !out->block_channels || !out->embedding_dim ||
+ !out->final_channels || !out->stem_kernel || !out->stem_stride || !out->gdc_kernel) return -5;
+ int blocks = 0;
for (int i = 0; i < out->n_stages; i++) {
const uint8_t *p = hdr + HDR_FIXED_SIZE + i * STAGE_REC_SIZE;
out->stage_t[i] = p[0];
out->stage_n[i] = p[1];
out->stage_s[i] = p[2];
+ blocks += p[1];
+ if (!p[0] || !p[1] || !p[2] || blocks > MFN_MAX_BLOCKS) return -5;
}
/* Skip JSON debug header */
size_t off = 8 + ARCH_HDR_SIZE;
uint32_t json_len = *(const uint32_t*)(raw + off); off += 4;
+ if (json_len > raw_size - off - 4) return -6;
off += json_len;
if (off + 4 > raw_size) return -6;
- *out_n_tensors = *(const uint32_t*)(raw + off); off += 4;
+ memcpy(out_n_tensors, raw + off, 4); off += 4;
*out_payload_off = off;
return 0;
}
@@ -117,30 +125,23 @@ static int parse_header(const uint8_t *raw, size_t raw_size,
/* ============ Tensor table from .bin ============ */
typedef struct {
- float **tensors;
- int n;
-} TensorTable;
-
-static int build_tensor_table(const uint8_t *raw, size_t raw_size,
- size_t payload_off, int n_expected,
- TensorTable *out)
-{
- out->tensors = (float**)calloc(n_expected, sizeof(float*));
- out->n = n_expected;
- size_t off = payload_off;
- for (int i = 0; i < n_expected; i++) {
- if (off + 4 > raw_size) return -1;
- uint32_t sz = *(const uint32_t*)(raw + off); off += 4;
- if (off + sz > raw_size) return -1;
- /* Note: pointer indexes into raw buffer — alignment may not be
- * 4-byte. On x86 this is fine; would need a copy on strict-align. */
- out->tensors[i] = (float*)(raw + off);
- off += sz;
- }
- return 0;
+ uint8_t *next, *end;
+ uint32_t remaining;
+} TensorCursor;
+
+static float *take_tensor(TensorCursor *cursor, size_t count) {
+ uint32_t bytes;
+ if (!cursor->remaining || cursor->end - cursor->next < 4) return NULL;
+ memcpy(&bytes, cursor->next, 4);
+ cursor->next += 4;
+ if (bytes % sizeof(float) || bytes / sizeof(float) != count ||
+ bytes > (size_t)(cursor->end - cursor->next)) return NULL;
+ float *data = (float *)cursor->next;
+ cursor->next += bytes;
+ cursor->remaining--;
+ return data;
}
-
/* ============ Fold BatchNorm into preceding convolution ============
*
* Given Conv weight W [Cout, Cin/g, K, K], BN params (scale γ, bias β,
@@ -174,20 +175,20 @@ static void fold_bn(float *w, int c_out, int weights_per_filter,
* fold BN, and stash pointers into the MfnConv struct.
*/
-static void load_conv(MfnConv *c, int c_in, int c_out, int k, int stride,
+static int load_conv(MfnConv *c, int c_in, int c_out, int k, int stride,
int padding, int groups, int with_act,
- float **tensors, int *idx,
+ TensorCursor *cursor,
float *bias_storage, /* pre-allocated [c_out] */
float eps)
{
- float *w = tensors[(*idx)++];
- float *bn_w = tensors[(*idx)++];
- float *bn_b = tensors[(*idx)++];
- float *bn_mean = tensors[(*idx)++];
- float *bn_var = tensors[(*idx)++];
- float *prelu = with_act ? tensors[(*idx)++] : NULL;
-
- int weights_per_filter = (c_in / groups) * k * k;
+ size_t per_channel = (size_t)(c_in / groups) * k * k;
+ if (per_channel > INT_MAX / (size_t)c_out) return 0;
+ int weights_per_filter = (int)per_channel;
+ float *w = take_tensor(cursor, per_channel * c_out);
+ float *bn_w = take_tensor(cursor, c_out), *bn_b = take_tensor(cursor, c_out);
+ float *bn_mean = take_tensor(cursor, c_out), *bn_var = take_tensor(cursor, c_out);
+ float *prelu = with_act ? take_tensor(cursor, c_out) : NULL;
+ if (!w || !bn_w || !bn_b || !bn_mean || !bn_var || (with_act && !prelu)) return 0;
fold_bn(w, c_out, weights_per_filter, bn_w, bn_b, bn_mean, bn_var,
bias_storage, eps);
@@ -200,6 +201,7 @@ static void load_conv(MfnConv *c, int c_in, int c_out, int k, int stride,
c->stride = stride;
c->padding = padding;
c->groups = groups;
+ return 1;
}
@@ -211,15 +213,16 @@ static int conv_hout(const MfnConv *c, int Hin)
/* ============ Public init ============ */
-int mfn_engine_init(const char *path, MfnEngine *e)
+static int mfn_load(const char *path, MfnEngine *e)
{
memset(e, 0, sizeof(*e));
FILE *f = fopen(path, "rb");
if (!f) return -1;
- fseek(f, 0, SEEK_END);
- e->raw_size = (size_t)ftell(f);
- fseek(f, 0, SEEK_SET);
+ if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return -1; }
+ long length = ftell(f);
+ if (length <= 0 || fseek(f, 0, SEEK_SET) != 0) { fclose(f); return -1; }
+ e->raw_size = (size_t)length;
e->raw = (uint8_t*)malloc(e->raw_size);
if (!e->raw) { fclose(f); return -2; }
if (fread(e->raw, 1, e->raw_size, f) != e->raw_size) { fclose(f); return -3; }
@@ -230,23 +233,14 @@ int mfn_engine_init(const char *path, MfnEngine *e)
int rc = parse_header(e->raw, e->raw_size, &e->arch, &payload_off, &n);
if (rc != 0) return -10 + rc;
- TensorTable tt = {0};
- if (build_tensor_table(e->raw, e->raw_size, payload_off, (int)n, &tt) != 0)
- return -20;
-
+ size_t payload_size = e->raw_size - payload_off;
+ size_t aligned = payload_off & ~(size_t)3;
+ if (aligned != payload_off) memmove(e->raw + aligned, e->raw + payload_off, payload_size);
+ TensorCursor cursor = {e->raw + aligned, e->raw + aligned + payload_size, n};
const float eps = 1e-5f;
- int idx = 0;
-
- /* Pre-allocate one bias buffer per conv (BN-folded biases need new
- * storage since the original .bin has no bias slot for these convs). */
- /* Count convs first so we can allocate one big bias slab. */
- int n_convs = 2; /* stem, dw_stem */
- for (int i = 0; i < e->arch.n_stages; i++)
- n_convs += e->arch.stage_n[i] * 3; /* expand, dw, project */
- n_convs += 3; /* final_conv, gdconv, embed_proj */
/* Per-conv bias is sized by Cout; pre-compute total Cout sum. */
- int total_cout = 0;
+ size_t total_cout = 0;
{
int c_in = e->arch.stem_channels;
total_cout += e->arch.stem_channels; /* stem */
@@ -269,21 +263,22 @@ int mfn_engine_init(const char *path, MfnEngine *e)
total_cout += e->arch.embedding_dim; /* embed_proj */
}
- float *bias_slab = (float*)calloc((size_t)total_cout, sizeof(float));
- if (!bias_slab) return -30;
- float *bp = bias_slab;
+ if (total_cout > payload_size / sizeof(float)) return -20;
+ e->bias_slab = calloc(total_cout, sizeof(float));
+ if (!e->bias_slab) return -30;
+ float *bp = e->bias_slab;
/* stem: Conv3 s=2 + BN + PReLU */
- load_conv(&e->stem, 3, e->arch.stem_channels,
+ if (!load_conv(&e->stem, 3, e->arch.stem_channels,
e->arch.stem_kernel, e->arch.stem_stride,
e->arch.stem_kernel / 2, 1, /*with_act*/1,
- tt.tensors, &idx, bp, eps);
+ &cursor, bp, eps)) return -20;
bp += e->stem.c_out;
/* dw_stem: DW Conv3 s=1 + BN + PReLU */
- load_conv(&e->dw_stem, e->arch.stem_channels, e->arch.stem_channels,
+ if (!load_conv(&e->dw_stem, e->arch.stem_channels, e->arch.stem_channels,
3, 1, 1, e->arch.stem_channels, /*with_act*/1,
- tt.tensors, &idx, bp, eps);
+ &cursor, bp, eps)) return -20;
bp += e->dw_stem.c_out;
/* bottleneck stages */
@@ -300,18 +295,18 @@ int mfn_engine_init(const char *path, MfnEngine *e)
int hidden = ci * t;
/* 1x1 expand + BN + PReLU */
- load_conv(&blk->expand, ci, hidden, 1, 1, 0, 1, 1,
- tt.tensors, &idx, bp, eps);
+ if (!load_conv(&blk->expand, ci, hidden, 1, 1, 0, 1, 1,
+ &cursor, bp, eps)) return -20;
bp += blk->expand.c_out;
/* DW 3x3 + BN + PReLU */
- load_conv(&blk->dw, hidden, hidden, 3, stride, 1, hidden, 1,
- tt.tensors, &idx, bp, eps);
+ if (!load_conv(&blk->dw, hidden, hidden, 3, stride, 1, hidden, 1,
+ &cursor, bp, eps)) return -20;
bp += blk->dw.c_out;
/* 1x1 project + BN (no activation — linear bottleneck) */
- load_conv(&blk->project, hidden, c_out_stage, 1, 1, 0, 1, 0,
- tt.tensors, &idx, bp, eps);
+ if (!load_conv(&blk->project, hidden, c_out_stage, 1, 1, 0, 1, 0,
+ &cursor, bp, eps)) return -20;
bp += blk->project.c_out;
blk->has_residual = (stride == 1 && ci == c_out_stage) ? 1 : 0;
@@ -320,43 +315,22 @@ int mfn_engine_init(const char *path, MfnEngine *e)
}
/* final_conv: 1x1 + BN + PReLU */
- load_conv(&e->final_conv, c_in, e->arch.final_channels, 1, 1, 0, 1, 1,
- tt.tensors, &idx, bp, eps);
+ if (!load_conv(&e->final_conv, c_in, e->arch.final_channels, 1, 1, 0, 1, 1,
+ &cursor, bp, eps)) return -20;
bp += e->final_conv.c_out;
/* gdconv: DW kxk no padding + BN, no act */
- load_conv(&e->gdconv, e->arch.final_channels, e->arch.final_channels,
+ if (!load_conv(&e->gdconv, e->arch.final_channels, e->arch.final_channels,
e->arch.gdc_kernel, 1, 0, e->arch.final_channels, 0,
- tt.tensors, &idx, bp, eps);
+ &cursor, bp, eps)) return -20;
bp += e->gdconv.c_out;
/* embed_proj: 1x1 + BN, no act */
- load_conv(&e->embed_proj, e->arch.final_channels, e->arch.embedding_dim,
+ if (!load_conv(&e->embed_proj, e->arch.final_channels, e->arch.embedding_dim,
1, 1, 0, 1, 0,
- tt.tensors, &idx, bp, eps);
+ &cursor, bp, eps)) return -20;
- if (idx != tt.n) {
- fprintf(stderr, "MFN: consumed %d tensors but file has %d\n", idx, tt.n);
- free(tt.tensors);
- free(bias_slab);
- return -40;
- }
- free(tt.tensors);
-
- /* Stash bias slab in raw_size+something? Actually we point at it from
- * each MfnConv.b. We need to remember to free it on engine_free.
- * Track it by hijacking work_a as the bias slab "owner"? No — add
- * a separate field. */
- /* Use the existing raw[] field for raw, and add a dedicated owner. */
- /* (Simplest: keep the bias_slab pointer in stem.b being the start —
- * we'll free starting from bias_slab.) For that we need to remember
- * where it starts. Save in a new field. */
- /* Workaround: stash in residual_buf temporarily; we'll allocate real
- * residual_buf below and free this slab on engine_free. To avoid
- * confusing the alias, expose via a private field. */
- /* Cleaner: add to struct. We did not — for now, the bias_slab leaks at
- * engine_free time. */
- /* TODO: leak fixed below by storing in residual_buf trick — see free path. */
+ if (cursor.remaining || cursor.next != cursor.end) return -40;
/* Allocate workspace: large enough for the biggest intermediate tensor.
* After stem (s=2): 56*56*stem_c
@@ -413,13 +387,6 @@ int mfn_engine_init(const char *path, MfnEngine *e)
e->residual_buf = (float*)malloc(e->work_floats * sizeof(float));
if (!e->work_a || !e->work_b || !e->residual_buf) return -50;
- /* Smuggle bias_slab so engine_free can release it. We tack it onto
- * the work allocation by placing the slab pointer just before
- * residual_buf — but cleaner: leave it as a small leak documented
- * in TODO. */
- /* Actually free path: bias_slab is referenced by stem.b. Track it. */
- /* Store its head in stem.b — but stem.b is already that. So just call
- * free(e->stem.b - 0) at free time, since stem is the first conv. */
return 0;
}
@@ -829,9 +796,7 @@ float mfn_similarity(const float *a, const float *b, int dim) {
void mfn_engine_free(MfnEngine *e) {
if (!e) return;
- /* All BN-folded biases live in a contiguous slab whose head is
- * e->stem.b (first conv loaded). */
- if (e->stem.b) free(e->stem.b);
+ free(e->bias_slab);
free(e->raw);
free(e->work_a);
free(e->work_b);
@@ -840,6 +805,27 @@ void mfn_engine_free(MfnEngine *e) {
}
+int mfn_engine_init(const char *path, MfnEngine *e) {
+ if (!path || !e) return -1;
+ int rc = mfn_load(path, e);
+ if (rc != 0) mfn_engine_free(e);
+ return rc;
+}
+
+MfnEngine *mfn_open(const char *path) {
+ MfnEngine *e = calloc(1, sizeof(*e));
+ if (e && mfn_engine_init(path, e) != 0) {
+ free(e);
+ return NULL;
+ }
+ return e;
+}
+
+void mfn_close(MfnEngine *e) {
+ mfn_engine_free(e);
+ free(e);
+}
+
/* ============ Optional standalone CLI ============ */
#ifdef MFN_STANDALONE
int main(int argc, char **argv) {
diff --git a/src/transformer_ops.c b/src/transformer_ops.c
index 4fd326d..e15489b 100644
--- a/src/transformer_ops.c
+++ b/src/transformer_ops.c
@@ -251,24 +251,17 @@ void softmax_fp32(float* x, int N, int C) {
/* ============ Dynamic INT8 MatMul ============ */
/* C[M,N] = A_fp32[M,K] @ W_int8_packed[K,N], with dynamic A quantization.
* W is pre-packed in c8 format. A is quantized per-tensor at runtime. */
+#include "edgeface_packed.h"
#ifndef FACEX_FP32_ONLY
void matmul_dynamic_int8(const float* A_fp32, int M, int K, int N,
const void* W_packed, const int32_t* col_sums,
- const float* w_scales, float* C_fp32)
+ const float* w_scales, float* C_fp32, QuantScratch* scratch)
{
int K_padded = (K + 7) & ~7;
int n_elem = M * K;
- /* Static workspace (avoid malloc per call) */
- static int8_t* s_A_int8 = NULL;
- static int32_t* s_C_int32 = NULL;
- static size_t s_A_cap = 0, s_C_cap = 0;
- size_t a_need = (size_t)M * K_padded;
- size_t c_need = (size_t)M * N;
- if (a_need > s_A_cap) { free(s_A_int8); s_A_int8 = (int8_t*)malloc(a_need); s_A_cap = a_need; }
- if (c_need > s_C_cap) { free(s_C_int32); s_C_int32 = (int32_t*)malloc(c_need * 4); s_C_cap = c_need; }
- int8_t* A_int8 = s_A_int8;
- int32_t* C_int32 = s_C_int32;
+ int8_t* A_int8 = scratch->input;
+ int32_t* C_int32 = scratch->output;
/* Dynamic per-tensor quantization: find max|A| then quantize.
* AVX-512: scan 16 floats per iteration. */
diff --git a/tests/bench_profile.c b/tests/bench_profile.c
index a459ac4..ae8cd7a 100644
--- a/tests/bench_profile.c
+++ b/tests/bench_profile.c
@@ -1,3 +1,4 @@
+#include "../src/edgeface_packed.h"
/*
* bench_profile.c — Profile FaceX embedding: GEMM vs other ops.
* Measures total time and GEMM-only time.
@@ -13,6 +14,13 @@ static double now_ms(void) {
QueryPerformanceFrequency(&f); QueryPerformanceCounter(&c);
return (double)c.QuadPart / f.QuadPart * 1000.0;
}
+#else
+#include <time.h>
+static double now_ms(void) {
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;
+}
#endif
/* Hook into matmul to count calls and measure time */
@@ -56,8 +64,6 @@ int main(int argc, char** argv) {
/* Measure individual operations by running benchmark code */
/* Test: how fast is just the quantize + GEMM portion? */
- extern void matmul_dynamic_int8(const float*, int, int, int,
- const void*, const int32_t*, const float*, float*);
/* Use the PackedMM info for a representative layer (stage 2: K=100, N=400) */
printf("\n Micro-benchmark: matmul sizes typical in EdgeFace:\n");
@@ -102,6 +108,7 @@ int main(int argc, char** argv) {
extern void int8_gemm_4x8c8(const int8_t*, int, int, int,
const void*, int32_t*, const int32_t*);
+ free(A); free(B); free(C);
M=49; K=100; N=400;
A = (float*)malloc(M*K*4); B = (float*)malloc(K*N*4); C = (float*)malloc(M*N*4);
for (int i=0; i<M*K; i++) A[i] = 0.01f * (i%100 - 50);
@@ -148,10 +155,12 @@ int main(int argc, char** argv) {
printf(" INT8 GEMM %dx%dx%d: %.3f ms (pure, no quant overhead)\n", M, K, N, best_i8);
/* Dynamic INT8 (with quantize) */
+ QuantScratch scratch = {malloc((size_t)M * ((K + 7) & ~7)), malloc((size_t)M * N * sizeof(int32_t))};
+ if (!scratch.input || !scratch.output) exit(1);
double best_dyn=1e9;
for (int i=0; i<1000; i++) {
double t0 = now_ms();
- matmul_dynamic_int8(A, M, K, N, pw, cs, w_sc, C);
+ matmul_dynamic_int8(A, M, K, N, pw, cs, w_sc, C, &scratch);
double dt = now_ms() - t0;
if (dt < best_dyn) best_dyn = dt;
}
@@ -164,9 +173,14 @@ int main(int argc, char** argv) {
extern void pack_b_fp32(const float*, int, int, float*);
extern void matmul_fp32_packed(const float*, const float*, float*, int, int, int);
/* Packed size: ceil(N/NR) panels × K × NR floats. NR=16 for AVX-512 */
- int NR = 16; /* AVX-512 */
- int pb_sz = ((N + NR - 1) / NR) * K * NR * (int)sizeof(float);
- float* pb = (float*)malloc(pb_sz);
+ extern int packed_b_fp32_size(int, int);
+ size_t pb_sz = (size_t)packed_b_fp32_size(K, N) * sizeof(float);
+#ifdef _WIN32
+ float* pb = _aligned_malloc(pb_sz, 64);
+#else
+ float* pb = aligned_alloc(64, (pb_sz + 63) & ~(size_t)63);
+#endif
+ if (!pb) exit(1);
pack_b_fp32(B, K, N, pb);
double best_fp_pk = 1e9;
for (int i=0; i<1000; i++) {
@@ -177,8 +191,14 @@ int main(int argc, char** argv) {
}
printf(" FP32 packed %dx%dx%d: %.3f ms\n", M, K, N, best_fp_pk);
printf(" INT8/FP32-packed ratio: %.2fx\n", best_fp_pk / best_i8);
+
+#ifdef _WIN32
+ _aligned_free(pb);
+#else
free(pb);
+#endif
+ free(scratch.input); free(scratch.output);
free(A); free(B); free(C); free(B_int8); free(w_sc); free(pw); free(cs);
free(A_i8); free(C_i32);
facex_free(fx);
diff --git a/tests/browser_sdk_smoke.js b/tests/browser_sdk_smoke.js
new file mode 100644
index 0000000..bcc9a4a
--- /dev/null
+++ b/tests/browser_sdk_smoke.js
@@ -0,0 +1,63 @@
+async () => {
+ function check(condition, message) {
+ if (!condition) throw new Error(message);
+ }
+ check(checkWasmSimd(), 'SIMD support');
+ const urls = {detWeightsUrl: '/det.bin', embWeightsUrl: '/emb.bin', wasmBaseUrl: '/wasm'};
+ const sdk = new FaceXSDK(urls);
+ const loading = sdk.load();
+ check(loading === sdk.load(), 'Concurrent load');
+ await loading;
+ const raw = new Uint8Array(await (await fetch('/frame')).arrayBuffer());
+ const canvas = document.createElement('canvas');
+ canvas.width = canvas.height = 160;
+ const ctx = canvas.getContext('2d');
+ const image = ctx.createImageData(160, 160);
+ for (let i = 0, j = 0; j < raw.length; i += 4, j += 3) {
+ image.data.set(raw.subarray(j, j + 3), i);
+ image.data[i + 3] = 255;
+ }
+ ctx.putImageData(image, 0, 0);
+ const {faces, embeddings} = sdk.process(canvas);
+ check(faces.length === 1 && Math.abs(faces[0].score - 0.913699) < 0.0001, 'Face geometry from native reference');
+ check(embeddings[0].length === 512 && embeddings[0].every(Number.isFinite), 'Embedding shape');
+ const ref = sdk.captureReference(canvas);
+ check(sdk.verify(canvas, ref.embedding).similarity > 0.99999, 'Self verification');
+ check(ref.alignedCanvas !== sdk.captureReference(canvas).alignedCanvas, 'Independent reference captures');
+ for (let y = 0; y < 160; y++) for (let x = 0; x < 160; x++) {
+ const p = (y * 160 + x) * 4;
+ image.data[p] = x;
+ image.data[p + 1] = y;
+ }
+ ctx.putImageData(image, 0, 0);
+ const rotated = REF_POINTS.map(([x, y]) => [140 - y, x + 3]);
+ const aligned = alignFace(ctx, 160, 160, rotated, ref.alignedCanvas.getContext('2d'));
+ const k = (70 * 112 + 40) * 4;
+ check(aligned.data[k] === 70 && aligned.data[k + 1] === 43, 'Inverse rotation and translation');
+ await sdk.close();
+ check(!sdk.ready, 'Close releases native handles');
+ await sdk.load();
+ await sdk.close();
+ const worker = new Worker('/wasm/worker.js');
+ function send(message) {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('Worker timeout for ' + message.type)), 20000);
+ worker.onerror = e => { clearTimeout(timer); reject(new Error(e.message)); };
+ worker.onmessage = e => {
+ clearTimeout(timer);
+ e.data.type === 'error' ? reject(new Error(e.data.message)) : resolve(e.data);
+ };
+ worker.postMessage(message);
+ });
+ }
+ try {
+ check((await send({type: 'init', ...urls})).type === 'ready', 'Worker load');
+ const reply = await send({type: 'detect', pixels: raw, W: 160, H: 160});
+ check(reply.faces.length === 1 && reply.faces[0].score === faces[0].score, 'Worker detection');
+ const {emb} = await send({type: 'embed', pixels: new Float32Array(112 * 112 * 3)});
+ check(emb.length === 512 && emb.some(x => x !== 0), 'Worker embedding');
+ } finally {
+ worker.terminate();
+ }
+ return {faces: faces.length, confidence: faces[0].score, dimensions: embeddings[0].length};
+}
diff --git a/tests/check_browser_sdk.py b/tests/check_browser_sdk.py
new file mode 100644
index 0000000..7e69208
--- /dev/null
+++ b/tests/check_browser_sdk.py
@@ -0,0 +1,45 @@
+"""Exercise the distributed browser assets and worker using known model weights."""
+import argparse
+import functools
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from tempfile import TemporaryDirectory
+from threading import Thread
+
+from playwright.sync_api import sync_playwright
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("detector", type=Path)
+ parser.add_argument("embedder", type=Path)
+ parser.add_argument("--chromium")
+ args = parser.parse_args()
+ with TemporaryDirectory() as directory:
+ root = Path(directory)
+ (root / "wasm").symlink_to(ROOT / "wasm", target_is_directory=True)
+ (root / "frame").symlink_to(ROOT / "tests/test_face_160.raw")
+ (root / "det.bin").symlink_to(args.detector.resolve(strict=True))
+ (root / "emb.bin").symlink_to(args.embedder.resolve(strict=True))
+ scripts = ("detect", "facex", "align", "cache", "simd_check", "facex-sdk")
+ (root / "index.html").write_text("".join(f'<script src="/wasm/{s}.js"></script>' for s in scripts))
+ handler = functools.partial(SimpleHTTPRequestHandler, directory=directory)
+ with ThreadingHTTPServer(("127.0.0.1", 0), handler) as server:
+ thread = Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch(executable_path=args.chromium)
+ page = browser.new_page()
+ page.goto(f"http://127.0.0.1:{server.server_port}")
+ print(page.evaluate((ROOT / "tests/browser_sdk_smoke.js").read_text()))
+ browser.close()
+ finally:
+ server.shutdown()
+ thread.join()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/check_nano_contract.py b/tests/check_nano_contract.py
new file mode 100644
index 0000000..219a6d8
--- /dev/null
+++ b/tests/check_nano_contract.py
@@ -0,0 +1,40 @@
+"""Compare the published Nano ONNX to the EFM3 loader through its public C API."""
+import ctypes
+import sys
+from pathlib import Path
+
+import numpy as np
+import onnxruntime as ort
+
+from bench_mfn_release import export_folded_weights
+
+
+def main():
+ model, library, weights = map(Path, sys.argv[1:])
+ session = ort.InferenceSession(str(model), providers=["CPUExecutionProvider"])
+ assert session.get_inputs()[0].name == "input" and session.get_inputs()[0].shape == [1, 3, 112, 112]
+ assert session.get_outputs()[0].name == "embedding" and session.get_outputs()[0].shape == [1, 256]
+ export_folded_weights(model, weights)
+ lib = ctypes.CDLL(str(library.resolve()))
+ ptr = np.ctypeslib.ndpointer(dtype=np.float32, flags="C_CONTIGUOUS")
+ lib.mfn_open.argtypes, lib.mfn_open.restype = [ctypes.c_char_p], ctypes.c_void_p
+ lib.mfn_embedding_dim.argtypes = [ctypes.c_void_p]
+ lib.mfn_engine_forward.argtypes, lib.mfn_engine_forward.restype = [ctypes.c_void_p, ptr, ptr], None
+ lib.mfn_close.argtypes, lib.mfn_close.restype = [ctypes.c_void_p], None
+ handle = lib.mfn_open(bytes(weights))
+ assert handle
+ try:
+ assert lib.mfn_embedding_dim(handle) == 256
+ x = np.linspace(-1, 1, 3 * 112 * 112, dtype=np.float32).reshape(1, 3, 112, 112)
+ expected = session.run(["embedding"], {"input": x})[0][0]
+ out = np.empty(256, dtype=np.float32)
+ lib.mfn_engine_forward(handle, x, out)
+ assert abs(np.linalg.norm(expected) - 1) < 1e-5
+ np.testing.assert_allclose(out, expected, atol=5e-5, rtol=0)
+ print(f"Nano returns {out.size} components; maximum native delta {np.max(np.abs(out - expected)):.8g}")
+ finally:
+ lib.mfn_close(handle)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/check_runtime_backends.py b/tests/check_runtime_backends.py
new file mode 100644
index 0000000..bb12658
--- /dev/null
+++ b/tests/check_runtime_backends.py
@@ -0,0 +1,65 @@
+"""Compare the C API, Python SDK and CLI on real weights and concurrent calls."""
+import argparse
+import ctypes
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+from threading import Barrier
+
+import numpy as np
+
+from facex import FaceX
+
+
+def check_native_handles(sdk, embedder):
+ lib = sdk._lib
+ handles = [lib.facex_init(bytes(embedder), None, None) for _ in range(3)]
+ pointer = ctypes.POINTER(ctypes.c_float)
+ try:
+ assert all(handles)
+ frames = np.random.default_rng(42).uniform(-1, 1, (8, 112, 112, 3)).astype(np.float32)
+
+ def embed(handle, i):
+ out = np.empty(512, dtype=np.float32)
+ rc = lib.facex_embed(handle, frames[i].ctypes.data_as(pointer), out.ctypes.data_as(pointer))
+ assert rc == 0
+ return out
+
+ expected = [embed(handles[0], i) for i in range(len(frames))]
+ gate = Barrier(len(frames))
+
+ def repeat(i):
+ gate.wait()
+ for handle in (handles[0], handles[i % len(handles)], handles[(i + 1) % len(handles)]):
+ np.testing.assert_array_equal(embed(handle, i), expected[i])
+
+ with ThreadPoolExecutor(len(frames)) as pool:
+ list(pool.map(repeat, range(len(frames))))
+ finally:
+ for handle in handles:
+ lib.facex_free(handle)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ for name in ("library", "cli", "detector", "embedder"):
+ parser.add_argument(name, type=Path)
+ args = parser.parse_args()
+ weights = dict(embed_weights=args.embedder.resolve(), detect_weights=args.detector.resolve())
+ frame = np.fromfile(Path(__file__).with_name("test_face_160.raw"), dtype=np.uint8).reshape(160, 160, 3)
+ face = np.ascontiguousarray(frame[:112, :112], dtype=np.float32) / 127.5 - 1
+ with FaceX(lib_path=args.library.resolve(), **weights) as native, FaceX(cli_path=args.cli.resolve(), **weights) as child:
+ assert (native.backend, child.backend) == ("ctypes", "cli")
+ check_native_handles(native, weights["embed_weights"])
+ np.testing.assert_array_equal(native.embed(face), child.embed(face))
+ for include in (True, False):
+ a, b = (engine.detect(frame, embeddings=include) for engine in (native, child))
+ assert len(a) == len(b) == 1 and a[0]["score"] > 0.9
+ assert set(a[0]) == set(b[0]) and ("embedding" in b[0]) == include
+ for key in a[0]:
+ np.testing.assert_array_equal(a[0][key], b[0][key])
+ assert child.detect(frame, max_faces=0) == []
+ print("Concurrent C handles and Python library and CLI results agree")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/frvt_alignment.cpp b/tests/frvt_alignment.cpp
new file mode 100644
index 0000000..4ffb795
--- /dev/null
+++ b/tests/frvt_alignment.cpp
@@ -0,0 +1,22 @@
+#include "../frvt/src/alignment.hpp"
+#include <cassert>
+#include <cstring>
+
+int main() {
+ const float points[5][2] = {{0,0},{2,0},{1,1},{0,2},{2,2}};
+ float transformed[5][2], matrix[6];
+ for (int i = 0; i < 5; i++) {
+ transformed[i][0] = 8 - 2 * points[i][1];
+ transformed[i][1] = 3 + 2 * points[i][0];
+ }
+ assert(facex_frvt::umeyama_5pt(points, transformed, matrix));
+ const float expected[6] = {0,-2,8,2,0,3};
+ for (int j = 0; j < 6; j++) assert(std::abs(matrix[j] - expected[j]) < 1e-5);
+ assert(facex_frvt::umeyama_5pt(points, points, matrix));
+ const uint8_t rgb[12] = {1,2,3,4,5,6,7,8,9,10,11,12};
+ uint8_t out[12];
+ facex_frvt::warp_affine_bilinear(rgb, 2, 2, 24, out, 2, matrix);
+ assert(std::memcmp(rgb, out, sizeof(rgb)) == 0);
+ const float coincident[5][2] = {};
+ assert(!facex_frvt::umeyama_5pt(coincident, points, matrix));
+}
diff --git a/tests/frvt_templates.cpp b/tests/frvt_templates.cpp
new file mode 100644
index 0000000..0eabebe
--- /dev/null
+++ b/tests/frvt_templates.cpp
@@ -0,0 +1,31 @@
+#define NIST_EXTERN_FRVT_STRUCTS_VERSION
+#define NIST_EXTERN_API_VERSION
+#include "frvt11.h"
+#include <cassert>
+#include <cmath>
+#include <cstring>
+#include <limits>
+
+int main()
+{
+ auto api = FRVT_11::Interface::getImplementation();
+ std::vector<uint8_t> templ(5 + 512 * sizeof(float), 0);
+ std::memcpy(templ.data(), "FXT1", 4);
+ templ[4] = 1;
+ float value = 1.0f;
+ std::memcpy(templ.data() + 5, &value, sizeof(value));
+ double score = -1;
+ assert(api->matchTemplates(templ, templ, score).code == FRVT::ReturnCode::Success && score == 1000);
+ auto other = templ;
+ value = -1.0f;
+ std::memcpy(other.data() + 5, &value, sizeof(value));
+ assert(api->matchTemplates(templ, other, score).code == FRVT::ReturnCode::Success && score == 0);
+ other[4] = 0;
+ assert(api->matchTemplates(templ, other, score).code == FRVT::ReturnCode::VerifTemplateError && score == -1);
+ other[4] = 1;
+ value = std::numeric_limits<float>::quiet_NaN();
+ std::memcpy(other.data() + 5, &value, sizeof(value));
+ assert(api->matchTemplates(templ, other, score).code == FRVT::ReturnCode::TemplateFormatError && score == -1);
+ other.pop_back();
+ assert(api->matchTemplates(templ, other, score).code == FRVT::ReturnCode::TemplateFormatError && score == -1);
+}
diff --git a/tests/golden_test.c b/tests/golden_test.c
index 61569dc..db098d0 100644
--- a/tests/golden_test.c
+++ b/tests/golden_test.c
@@ -46,7 +46,7 @@ int main(int argc, char** argv) {
}
norm = sqrtf(norm);
- printf("Embedding norm: %.6f (should be ~1.0)\n", norm);
+ printf("Embedding norm: %.6f (raw EdgeFace output)\n", norm);
printf("NaN values: %d (should be 0)\n", nan_count);
printf("Embedding[0..7]: ");
for (int i = 0; i < 8; i++) printf("%.6f ", emb[i]);
diff --git a/tests/nn2_gemm.c b/tests/nn2_gemm.c
new file mode 100644
index 0000000..b9ff68f
--- /dev/null
+++ b/tests/nn2_gemm.c
@@ -0,0 +1,60 @@
+/* Exercise tile tails and padded row strides against a scalar oracle. */
+#include "nn2_internal.h"
+#include <assert.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+static float activation(float x, int act) {
+ if (act == 1) return x / (1 + expf(-x));
+ if (act == 2) return 1 / (1 + expf(-x));
+ return act == 3 && x < 0 ? 0.1f * x : x;
+}
+
+static void check_shape(int n) {
+ enum { m = 13, k = 17 };
+ int lda = k + 2, ldb = n + 3, ldc = n + 4;
+ float a[m*lda], dense_a[m*k], b[k*ldb], dense_b[k*n], bias[m];
+ float c[m*ldc], res[m*ldc];
+ for (int i = 0; i < m; i++) {
+ bias[i] = (i - 4) * 0.12f;
+ for (int j = 0; j < k; j++)
+ a[i*lda+j] = dense_a[i*k+j] = ((i + j*7) % 13 - 6) * 0.1f;
+ }
+ for (int j = 0; j < k; j++)
+ for (int i = 0; i < ldb; i++) {
+ b[j*ldb+i] = ((j*3 + i) % 19 - 9) * 0.12f;
+ if (i < n) dense_b[j*n+i] = b[j*ldb+i];
+ }
+ for (int i = 0; i < m*ldc; i++) res[i] = (i % 11 - 5) * 0.25f;
+ float *packed = nn2_pack_weight_a(dense_a, m, k);
+ assert(packed);
+ for (int mode = 0; mode < 4; mode++) {
+ for (int act = 0; act < 4; act++) {
+ for (int i = 0; i < m*ldc; i++) c[i] = 123.0f;
+ if (mode == 0) nn2_sgemm(m,k,n,a,lda,b,ldb,c,ldc);
+ if (mode == 1) nn2_sgemm_bias_act(m,k,n,a,lda,b,ldb,c,ldc,bias,act);
+ if (mode == 2) nn2_sgemm_bias_act_packed(m,k,n,packed,dense_b,c,ldc,bias,act);
+ if (mode == 3) nn2_sgemm_bias_act_res_packed(m,k,n,packed,dense_b,c,ldc,bias,act,res,ldc);
+ for (int i = 0; i < m; i++) {
+ for (int j = 0; j < ldc; j++) {
+ if (j >= n) { assert(c[i*ldc+j] == 123.0f); continue; }
+ float x = 0;
+ for (int v = 0; v < k; v++) x += a[i*lda+v] * b[v*ldb+j];
+ if (mode) x = activation(x + bias[i], act);
+ if (mode == 3) x += res[i*ldc+j];
+ assert(fabsf(x - c[i*ldc+j]) < 3e-5f);
+ }
+ }
+ }
+ }
+ free(packed);
+}
+
+int main(void) {
+ int widths[] = {1, 8, 15, 16, 17, 31, 32, 33, 64, 65};
+ nn2_tp_init(3);
+ for (unsigned i = 0; i < sizeof(widths)/sizeof(*widths); i++) check_shape(widths[i]);
+ nn2_tp_destroy();
+ puts("Plain, packed and residual GEMM agree with the scalar reference");
+}
diff --git a/training/README.md b/training/README.md
index 6561794..5c361ed 100644
--- a/training/README.md
+++ b/training/README.md
@@ -1,8 +1,6 @@
# FaceX training
-Train 4 size variants (Nano / Tiny / Standard / XS) of the FaceX
-embedding model from scratch on MS1M-RefineV2, export to the parametric
-`.bin` v2 format.
+Train four MobileFaceNet recognition variants and export EFM3 weights. The training scripts describe MS1M-RefineV2 as their input. For the published Nano ONNX, see the [artifact contract](../MFN_README.md#public-nano-release) and [provenance notes](../README.md#licensing-and-provenance).
## Files
@@ -24,11 +22,13 @@ training/
train.py - ArcFace training for one arch
train_all.py - sequential trainer for all 4
lfw_eval.py - 10-fold CV verification
- binformat.py - .bin v2 reader/writer + tensor layout
+ binformat.py - EFM3 reader/writer and tensor layout
export_bin.py - PyTorch checkpoint -> .bin
smoke_test.py - model -> .bin -> reload roundtrip check
```
+Run the following commands from the `training/` directory. Training requires a separately obtained dataset.
+
## One-time setup
```bash
@@ -52,16 +52,7 @@ python scripts/train_all.py
python scripts/train.py --arch nano --epochs 25 --batch 512
```
-Realistic wall time on RTX 5060 Ti (16 GB):
-
-| arch | params | epochs | est. time |
-|----------|-------:|-------:|----------:|
-| nano | 203K | 25 | ~4h |
-| tiny | 514K | 25 | ~6h |
-| standard | 1.07M | 22 | ~10h |
-| xs | 1.78M | 20 | ~16h |
-
-Total ~36h. Train_all auto-resumes if interrupted.
+The sequential trainer can resume interrupted runs from saved checkpoints. Report measured throughput with the dataset size, batch size, precision and GPU model. See the [run notes](RESUME.md) for the original environment.
## Export
@@ -73,32 +64,12 @@ python scripts/export_bin.py --arch nano \
--out ../weights/facex_nano.bin
```
-The .bin is FP32 on disk (~4x the INT8 deploy size). The C engine's
-INT8 quantization happens at load time.
-
-## Targets
+The EFM3 file stores FP32 tensors. The C MobileFaceNet runtime can open it with `mfn_open()`. Use `mfn_embedding_dim()` to allocate the output for the chosen architecture. See the [native example](../examples/example_mfn.c).
-| arch | LFW target |
-|----------|-----------:|
-| nano | >= 97% |
-| tiny | >= 98.5% |
-| standard | >= 99.5% |
-| xs | >= 99.7% |
+## EFM3 format
-## .bin v2 format
-
-```
-EFX2 (4 bytes magic)
-version (u32 = 2)
-arch_json_len (u32)
-arch_json (UTF-8 JSON describing stages/widths/kernels/ranks)
-n_tensors (u32)
-[tensor: u32 size + raw FP32 bytes] x n_tensors
-```
+The little-endian file starts with the four bytes `EFM3`, a uint32 version of 3, and an 80-byte architecture header. A length-prefixed UTF-8 JSON copy of the architecture and a uint32 tensor count follow. Each tensor record has a uint32 byte length and its contiguous FP32 data. The model exporter and loader must agree on tensor order. [Format implementation](scripts/binformat.py) · [Native loader](../src/facex_mfn.c)
-The tensor order is fixed by `binformat.tensor_layout(arch)` and is the
-contract between `export_bin.py` and the (parametric) C engine.
+## Evaluation
-The legacy v1 `EFXS` format remains supported by the engine for the
-existing EdgeFace-XS bundle; v2 is required for nano/tiny/standard
-because the engine cannot infer their shapes from the file alone.
+The [LFW evaluation script](scripts/lfw_eval.py) uses ten folds. The [project model table](../README.md#models-and-measurements) lists the historical scores and fold variation for the released variants. For experiments, keep the checkpoint, alignment, preprocessing and evaluation pairs with the result.
diff --git a/training/scripts/binformat.py b/training/scripts/binformat.py
index 59ef6b6..52142c3 100644
--- a/training/scripts/binformat.py
+++ b/training/scripts/binformat.py
@@ -4,13 +4,13 @@ FaceX MobileFaceNet .bin v3 format — parametric, self-describing.
File layout (little-endian):
magic : 4 bytes = b"EFM3" (EdgeFaceX MFN v3)
version : u32 = 3
- binary header: BIN_HDR_SIZE bytes
+ binary header: ARCH_HDR_SIZE bytes
json_len : u32 (debug copy of arch as JSON)
json : json_len bytes
n_tensors : u32
tensor records: per-tensor [u32 size][raw FP32 bytes]
-Binary header schema (fixed 32 bytes):
+Binary header schema (16 fixed bytes followed by eight 8-byte stage records):
u8 hdr_version (=1)
u8 n_stages (number of bottleneck stages)
u8 stem_kernel
diff --git a/wasm/README.md b/wasm/README.md
index dcb4c36..427b4de 100644
--- a/wasm/README.md
+++ b/wasm/README.md
@@ -1,156 +1,71 @@
-# facex-wasm
+# FaceX browser SDK
-Face recognition in the browser. 75 KB of WebAssembly. No server, no dependencies.
+Run YuNet detection, five-point alignment and EdgeFace XS recognition in a browser or Web Worker. The SDK returns boxes and landmarks in source-image pixels and one 512-component embedding per aligned face. The [hosted mesh and anti-spoofing demo](https://facex-engine.github.io/facex/demo/) uses a separate ONNX pipeline.
-Detect faces, align them, compute 512-dimensional embeddings, and verify identity -- all client-side, all private.
+## Run the SDK demo from a checkout
-## Requirements
+Follow the [native guide](../README.md#build-the-native-runtime) to download EdgeFace and export YuNet. From the repository root:
-- Chrome 91+, Firefox 89+, Safari 16.4+, Edge 91+ (WebAssembly SIMD required)
-- HTTPS (required for camera access)
-
-## Install
-
-```bash
-npm install facex-wasm
+```sh
+cp data/edgeface_xs_fp32.bin weights/yunet_fp32.bin wasm/
+python -m http.server 8000 --bind 127.0.0.1 --directory wasm
```
-## Quick start
+Open `http://127.0.0.1:8000/demo.html`. Camera access requires localhost or HTTPS. A canvas or preloaded image also works. For offline deployment, include both weights, both WASM files and the JavaScript assets in the application and serve them locally.
-```js
-import { FaceXSDK } from 'facex-wasm';
+## Use the package
-const fx = new FaceXSDK();
-await fx.load();
+Build or install the package from this revision with `npm install ./wasm` from the repository root. For a bundled application, copy `detect.wasm` and `facex.wasm` to the asset directory and configure the two weight URLs. The model files are distributed separately.
-// Full pipeline: detect + align + embed
-const result = fx.process(videoElement);
-console.log(result.faces); // [{x1, y1, x2, y2, score, kps}, ...]
-console.log(result.embeddings); // [Float32Array(512), ...]
-console.log(result.ms); // processing time in ms
+```js
+import {FaceXSDK, checkWasmSimd} from 'facex-wasm';
+
+export async function recognize(canvas) {
+ if (!checkWasmSimd()) throw new Error('WebAssembly SIMD is required');
+ const sdk = new FaceXSDK({
+ wasmBaseUrl: '/assets/facex/',
+ detWeightsUrl: '/models/yunet_fp32.bin',
+ embWeightsUrl: '/models/edgeface_xs_fp32.bin',
+ });
+ await sdk.load();
+ try {
+ return sdk.process(canvas);
+ } finally {
+ await sdk.close();
+ }
+}
```
-## Script tag usage
+For a video stream, load the SDK once, reuse it across frames and close it when the stream ends. Default weight URLs resolve relative to the page. Cache entries include the resolved URL and model kind. Use versioned asset URLs when replacing a model.
+
+Classic script tags load in this order:
```html
<script src="detect.js"></script>
<script src="facex.js"></script>
<script src="align.js"></script>
+<script src="cache.js"></script>
+<script src="simd_check.js"></script>
<script src="facex-sdk.js"></script>
-<script>
- const fx = new FaceXSDK();
- await fx.load();
- const result = fx.process(videoElement);
-</script>
```
-## API
-
-### `new FaceXSDK(options?)`
-
-Create an SDK instance.
-
-| Option | Type | Default | Description |
-|--------|------|---------|-------------|
-| `detSize` | `number` | `160` | Detection input size (pixels) |
-| `threshold` | `number` | `0.3` | Cosine similarity threshold for match |
-| `detWeightsUrl` | `string` | `'yunet_fp32.bin'` | URL to detector weights |
-| `embWeightsUrl` | `string` | `'edgeface_xs_fp32.bin'` | URL to embedder weights |
-| `onProgress` | `function` | `null` | Progress callback during loading |
-
-### `fx.load(): Promise<FaceXSDK>`
-
-Load WASM engines and model weights. Call once before using other methods.
-
-### `fx.detect(source): Face[]`
-
-Detect faces in a video, image, or canvas element. Returns array of faces with bounding boxes and 5 keypoints.
-
-### `fx.embed(imageData): Float32Array`
-
-Compute a 512-dim embedding from an aligned 112x112 face ImageData.
-
-### `fx.process(source): ProcessResult`
-
-Full pipeline: detect all faces, align each one, compute embeddings.
-
-```js
-const { faces, embeddings, ms } = fx.process(videoElement);
-```
-
-### `fx.verify(source, refEmbedding): VerifyResult`
-
-Compare a live frame against a reference embedding.
-
-```js
-const ref = fx.captureReference(videoElement);
-// Later...
-const { match, similarity } = fx.verify(videoElement, ref.embedding);
-if (match) console.log(`Verified! Similarity: ${similarity.toFixed(2)}`);
-```
-
-### `fx.captureReference(source): CaptureResult | null`
-
-Capture a reference embedding from the current frame. Returns `null` if no face detected.
-
-### `fx.cosSim(a, b): number`
-
-Cosine similarity between two 512-dim embeddings. Returns value between -1 and 1.
-
-## Liveness detection
-
-Basic liveness check using motion, blink, and size variation analysis.
-
-```js
-import { LivenessDetector } from 'facex-wasm';
-
-const liveness = new LivenessDetector();
-
-function onFrame() {
- const faces = fx.detect(videoElement);
- const { alive, confidence, reason } = liveness.update(faces[0] || null);
- console.log(alive, confidence, reason);
-}
-```
-
-## Utilities
-
-```js
-import { checkWasmSimd, checkBrowserSupport } from 'facex-wasm';
-
-if (!checkWasmSimd()) {
- alert('Your browser does not support WebAssembly SIMD');
-}
-
-const issues = checkBrowserSupport();
-if (issues.length > 0) {
- console.warn('Browser issues:', issues);
-}
-```
-
-## Weight files
-
-The SDK needs two weight files served alongside your app:
-
-| File | Size | Description |
-|------|------|-------------|
-| `yunet_fp32.bin` | 208 KB | Face detector weights |
-| `edgeface_xs_fp32.bin` | 7 MB | Face embedder weights |
-
-Weights are cached in IndexedDB after first load.
+Append `liveness.js` to use the optional motion heuristic. Five detector landmarks provide a coarse motion signal. Evaluate presentation-attack detection separately for an authentication deployment.
-## Architecture
+## API and data contracts
-| File | Size | Purpose |
-|------|------|---------|
-| `detect.wasm` | 30 KB | Face detector (YuNet, WASM+SIMD) |
-| `facex.wasm` | 45 KB | Face embedder (EdgeFace-XS, WASM+SIMD) |
-| `facex-sdk.js` | 10 KB | Unified SDK class |
-| `align.js` | 4 KB | 5-point affine face alignment |
-| `liveness.js` | 5 KB | Motion/blink liveness checks |
+| Method or setting | Contract |
+|---|---|
+| `load()`, `ready`, `close()` | Concurrent loads share initialization. Close releases both native handles. A closed instance can load again |
+| `detSize` | Square detection budget in pixels, default 160. The resize preserves aspect ratio and applies letterboxing |
+| `detect(source)` | Returns boxes, confidence and five pairs of keypoint coordinates. Accepts an image, canvas or video |
+| `embed(imageData)` | Aligned 112 × 112 RGBA ImageData → 512 floats |
+| `process(source)` | Returns `faces`, `embeddings` and elapsed `ms` from one captured frame |
+| `captureReference(source)` | Returns the first face, its embedding and an independently owned aligned canvas, or `null` |
+| `verify(source, reference)` | Scores the first detected face. `noFace` identifies empty frames. `threshold` defaults to 0.3 and is configurable |
+| `cosSim(a,b)` | Cosine similarity in `[-1,1]` for 512-component inputs, zero for a zero vector |
-Total engine size: ~75 KB WASM + 19 KB JS (before gzip).
+The worker accepts `init` with optional absolute weight URLs, `detect` with interleaved RGB bytes or normalized HWC float32, and `embed` with 112 × 112 normalized HWC float32. Wait for `ready`. Error replies contain a `message`. [Worker protocol](worker.js) · [TypeScript declarations](index.d.ts)
-## License
+## Rebuild the detector
-Apache-2.0
+From the repository root, run `make wasm-detector` with Emscripten installed. The distributed detector is compiled from the native YuNet source. The SDK uses the module factory `DetectModule`, copies byte RGB into the detector and copies float RGB into the embedder. [Detector source](../src/detect.c) · [Model hashes and licensing](../README.md#licensing-and-provenance)
diff --git a/wasm/align.js b/wasm/align.js
index fe32cc8..d714e65 100644
--- a/wasm/align.js
+++ b/wasm/align.js
@@ -37,7 +37,7 @@ function getSimilarityTransform(src, dst) {
const sxc = src[i][0] - sx, syc = src[i][1] - sy;
const dxc = dst[i][0] - dx, dyc = dst[i][1] - dy;
num1 += dxc * sxc + dyc * syc;
- num2 += dxc * syc - dyc * sxc;
+ num2 += dyc * sxc - dxc * syc;
den += sxc * sxc + syc * syc;
}
@@ -60,7 +60,11 @@ function getSimilarityTransform(src, dst) {
* @returns {ImageData} - 112x112 aligned face
*/
function alignFace(srcCtx, srcW, srcH, kps, dstCtx) {
- // Get transform: destination (112x112 ref) → source (video)
+ return alignFacePixels(srcCtx.getImageData(0, 0, srcW, srcH), kps, dstCtx);
+}
+
+function alignFacePixels(frame, kps, dstCtx) {
+ const srcW = frame.width, srcH = frame.height;
// We need inverse: for each dst pixel, find src pixel
const [a, b, tx, ty] = getSimilarityTransform(kps, REF_POINTS);
@@ -68,27 +72,28 @@ function alignFace(srcCtx, srcW, srcH, kps, dstCtx) {
// M = [a, -b, tx; b, a, ty]
// M_inv = (1/det) * [a, b, -a*tx-b*ty; -b, a, b*tx-a*ty]
const det = a * a + b * b;
+ if (!(det > 0) || !Number.isFinite(det)) throw new RangeError('Degenerate landmark transform');
const ai = a / det, bi = b / det;
const txi = -(ai * tx + bi * ty);
const tyi = (bi * tx - ai * ty);
- const srcData = srcCtx.getImageData(0, 0, srcW, srcH);
+ const epsilon = 64 * Number.EPSILON * Math.max(srcW, srcH);
const dstData = dstCtx.createImageData(112, 112);
- const src = srcData.data;
+ const src = frame.data;
const dst = dstData.data;
for (let dy = 0; dy < 112; dy++) {
for (let dx = 0; dx < 112; dx++) {
// Map dst → src using inverse transform
- const sx = ai * dx - bi * dy + txi;
- const sy = bi * dx + ai * dy + tyi;
+ const sx = ai * dx + bi * dy + txi + epsilon;
+ const sy = -bi * dx + ai * dy + tyi + epsilon;
// Bilinear interpolation
const x0 = Math.floor(sx), y0 = Math.floor(sy);
- const x1 = x0 + 1, y1 = y0 + 1;
+ const x1 = Math.min(x0 + 1, srcW - 1), y1 = Math.min(y0 + 1, srcH - 1);
const fx = sx - x0, fy = sy - y0;
- if (x0 >= 0 && x1 < srcW && y0 >= 0 && y1 < srcH) {
+ if (x0 >= 0 && x0 < srcW && y0 >= 0 && y0 < srcH) {
const i00 = (y0 * srcW + x0) * 4;
const i10 = (y0 * srcW + x1) * 4;
const i01 = (y1 * srcW + x0) * 4;
@@ -111,3 +116,5 @@ function alignFace(srcCtx, srcW, srcH, kps, dstCtx) {
dstCtx.putImageData(dstData, 0, 0);
return dstData;
}
+
+if (typeof module !== 'undefined' && module.exports) module.exports = {alignFace, alignFacePixels};
diff --git a/wasm/cache.js b/wasm/cache.js
index a206f87..23f95b6 100644
--- a/wasm/cache.js
+++ b/wasm/cache.js
@@ -21,22 +21,31 @@ function openCacheDB() {
async function getCached(key) {
const db = await openCacheDB();
- return new Promise((resolve) => {
- const tx = db.transaction(CACHE_STORE, 'readonly');
- const req = tx.objectStore(CACHE_STORE).get(key);
- req.onsuccess = () => resolve(req.result || null);
- req.onerror = () => resolve(null);
- });
+ try {
+ return await new Promise((resolve, reject) => {
+ const tx = db.transaction(CACHE_STORE, 'readonly');
+ const req = tx.objectStore(CACHE_STORE).get(key);
+ req.onsuccess = () => resolve(req.result || null);
+ req.onerror = () => reject(req.error);
+ tx.onabort = () => reject(tx.error);
+ });
+ } finally {
+ db.close();
+ }
}
async function putCached(key, data) {
const db = await openCacheDB();
- return new Promise((resolve) => {
- const tx = db.transaction(CACHE_STORE, 'readwrite');
- tx.objectStore(CACHE_STORE).put(data, key);
- tx.oncomplete = () => resolve();
- tx.onerror = () => resolve();
- });
+ try {
+ await new Promise((resolve, reject) => {
+ const tx = db.transaction(CACHE_STORE, 'readwrite');
+ tx.oncomplete = () => resolve();
+ tx.onabort = tx.onerror = () => reject(tx.error);
+ tx.objectStore(CACHE_STORE).put(data, key);
+ });
+ } finally {
+ db.close();
+ }
}
/**
@@ -48,14 +57,23 @@ async function putCached(key, data) {
*/
async function loadWeightsCached(url, key, onProgress) {
// Try cache first
- const cached = await getCached(key);
+ const absolute = new URL(url, globalThis.document?.baseURI || globalThis.location.href).href;
+ key = [key, absolute];
+ const cached = await getCached(key).catch(() => null);
if (cached) {
if (onProgress) onProgress(cached.byteLength, cached.byteLength);
return new Uint8Array(cached);
}
// Fetch from network with progress
- const response = await fetch(url);
+ const response = await fetch(absolute);
+ if (!response.ok) throw new Error('Weight request failed with status ' + response.status);
+ if (!onProgress || !response.body) {
+ const data = await response.arrayBuffer();
+ await putCached(key, data).catch(() => {});
+ onProgress?.(data.byteLength, data.byteLength);
+ return new Uint8Array(data);
+ }
const total = parseInt(response.headers.get('content-length')) || 0;
const reader = response.body.getReader();
const chunks = [];
@@ -78,7 +96,9 @@ async function loadWeightsCached(url, key, onProgress) {
}
// Store in cache
- await putCached(key, data.buffer);
+ await putCached(key, data.buffer).catch(() => {});
return data;
}
+
+if (typeof module !== 'undefined' && module.exports) module.exports = {loadWeightsCached};
diff --git a/wasm/demo.html b/wasm/demo.html
index a130b6c..ed27c14 100644
--- a/wasm/demo.html
+++ b/wasm/demo.html
@@ -67,7 +67,7 @@ canvas.overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%;
<div class="header">
<h1>Face<span>X</span></h1>
- <p>74 KB WASM. No server. Everything stays on your device.</p>
+ <p>Local face detection and recognition with WebAssembly.</p>
</div>
<div id="status" class="status loading">Checking browser support...</div>
@@ -107,10 +107,10 @@ canvas.overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%;
<div class="info">
<h3>How it works</h3>
- <p><code>detect.wasm</code> (29 KB) finds faces with RetinaFace INT8 + relaxed SIMD.</p>
- <p><code>facex.wasm</code> (44 KB) computes 512-dim embeddings via EdgeFace-XS.</p>
+ <p><code>detect.wasm</code> runs the YuNet face detector.</p>
+ <p><code>facex.wasm</code> computes 512-component EdgeFace XS embeddings.</p>
<p>5-point alignment ensures accurate matching at any head angle.</p>
- <p>Total: <code>74 KB</code> engine + <code>7.7 MB</code> weights (cached after first load).</p>
+ <p>Both model files are cached after their first successful download.</p>
</div>
</div>
@@ -118,6 +118,9 @@ canvas.overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%;
<script src="facex.js"></script>
<script src="align.js"></script>
<script src="liveness.js"></script>
+<script src="simd_check.js"></script>
+<script src="cache.js"></script>
+<script src="facex-sdk.js"></script>
<script>
const $ = id => document.getElementById(id);
const video = $('video');
@@ -126,7 +129,7 @@ const ctx = overlay.getContext('2d');
const refCanvas = $('refCanvas');
const refCtx = refCanvas.getContext('2d', { willReadFrequently: true });
-let DetMod, FxMod, detH, fxH;
+const sdk = new FaceXSDK();
let refEmb = null, running = false;
const liveness = new LivenessDetector();
@@ -137,38 +140,10 @@ const cropCv = document.createElement('canvas');
cropCv.width = 112; cropCv.height = 112;
const cropCtxA = cropCv.getContext('2d', { willReadFrequently: true });
-// ===== SIMD Check =====
-function checkSimd() {
- try {
- return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11]));
- } catch(e) { return false; }
-}
-
-// ===== IndexedDB Cache =====
-async function cachedFetch(url, key) {
- try {
- const db = await new Promise((res, rej) => {
- const r = indexedDB.open('facex-cache', 1);
- r.onupgradeneeded = () => r.result.createObjectStore('w');
- r.onsuccess = () => res(r.result);
- r.onerror = () => rej(r.error);
- });
- const cached = await new Promise(r => {
- const tx = db.transaction('w','readonly');
- const req = tx.objectStore('w').get(key);
- req.onsuccess = () => r(req.result); req.onerror = () => r(null);
- });
- if (cached) return new Uint8Array(cached);
- const buf = await fetch(url).then(r => r.arrayBuffer());
- try { const tx = db.transaction('w','readwrite'); tx.objectStore('w').put(buf, key); } catch(e) {}
- return new Uint8Array(buf);
- } catch(e) { return new Uint8Array(await fetch(url).then(r => r.arrayBuffer())); }
-}
-
// ===== Init =====
async function init() {
const s = $('status');
- if (!checkSimd()) {
+ if (!checkWasmSimd()) {
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
showError(isIOS
? 'WebAssembly SIMD not supported in this browser. On iOS, use Safari (not Chrome).'
@@ -177,19 +152,9 @@ async function init() {
}
try {
s.textContent = 'Loading engines...'; s.className = 'status loading';
- [DetMod, FxMod] = await Promise.all([FaceDetModule(), FaceXModule()]);
-
- s.textContent = 'Loading weights (cached after first load)...';
- const [dw, fw] = await Promise.all([
- cachedFetch('https://github.com/facex-engine/facex/releases/download/v1.0.0/det_500m_int8.bin', 'det'), cachedFetch('https://github.com/facex-engine/facex/releases/download/v1.0.0/edgeface_xs_fp32.bin', 'emb')
- ]);
- DetMod.FS.writeFile('/d.bin', dw); FxMod.FS.writeFile('/e.bin', fw);
-
- detH = DetMod.cwrap('detect_init','number',['string'])('/d.bin');
- fxH = FxMod.cwrap('facex_init','number',['string','string'])('/e.bin', null);
- if (!detH || !fxH) throw new Error('Engine init failed');
-
- s.textContent = 'Ready — 74 KB engines loaded'; s.className = 'status ready';
+ sdk.onProgress = message => { s.textContent = message; };
+ await sdk.load();
+ s.textContent = 'Ready'; s.className = 'status ready';
$('btnStart').disabled = false;
$('resultBar').textContent = 'Click "Start Camera" to begin';
} catch(e) { showError(e.message); }
@@ -214,65 +179,18 @@ $('btnStart').onclick = async () => {
// ===== Detect =====
function runDetect() {
- const W = video.videoWidth, H = video.videoHeight;
- const ds = 160;
- const detCv = document.createElement('canvas'); detCv.width = ds; detCv.height = ds;
- const dCtx = detCv.getContext('2d', { willReadFrequently: true });
- const scale = Math.min(ds/W, ds/H);
- const nw = Math.round(W*scale), nh = Math.round(H*scale);
- const dx = (ds-nw)/2, dy = (ds-nh)/2;
- dCtx.fillStyle = '#000'; dCtx.fillRect(0,0,ds,ds);
- dCtx.drawImage(video, dx, dy, nw, nh);
- const img = dCtx.getImageData(0,0,ds,ds);
-
- const nPx = ds*ds*3;
- const inP = DetMod._malloc(nPx*4);
- const heap = DetMod.HEAPF32;
- const b = inP>>2;
- for (let i=0; i<ds*ds; i++) {
- heap[b+i*3] = img.data[i*4]/127.5-1; heap[b+i*3+1] = img.data[i*4+1]/127.5-1; heap[b+i*3+2] = img.data[i*4+2]/127.5-1;
- }
- const outP = DetMod._malloc(15*4*10);
- const df = DetMod.cwrap('detect_faces','number',['number','number','number','number','number','number']);
- const t0 = performance.now();
- const n = df(detH, inP, ds, ds, outP, 10);
- const detMs = performance.now() - t0;
-
- const faces = [];
- for (let i=0; i<n; i++) {
- const fb = (outP>>2)+i*15;
- const f = DetMod.HEAPF32;
- faces.push({
- x1:(f[fb]-dx)/scale, y1:(f[fb+1]-dy)/scale, x2:(f[fb+2]-dx)/scale, y2:(f[fb+3]-dy)/scale,
- score:f[fb+4], kps: Array.from({length:10}, (_,j) => (f[fb+5+j]-(j%2===0?dx:dy))/scale)
- });
- }
- DetMod._free(inP); DetMod._free(outP);
- return { faces, detMs };
+ const start = performance.now();
+ const faces = sdk.detect(video);
+ return {faces, detMs: performance.now() - start};
}
-// ===== Embed =====
-function runEmbed(imgData) {
- const N=112*112*3;
- const inP = FxMod._malloc(N*4), outP = FxMod._malloc(512*4);
- const heap = FxMod.HEAPF32, b = inP>>2;
- for (let i=0; i<112*112; i++) {
- heap[b+i*3] = imgData.data[i*4]/127.5-1; heap[b+i*3+1] = imgData.data[i*4+1]/127.5-1; heap[b+i*3+2] = imgData.data[i*4+2]/127.5-1;
- }
- const t0 = performance.now();
- FxMod.cwrap('facex_embed','number',['number','number','number'])(fxH, inP, outP);
- const embMs = performance.now() - t0;
- const emb = new Float32Array(512);
- emb.set(heap.subarray(outP>>2, (outP>>2)+512));
- FxMod._free(inP); FxMod._free(outP);
- return { emb, embMs };
+function runEmbed(image) {
+ const start = performance.now();
+ const emb = sdk.embed(image);
+ return {emb, embMs: performance.now() - start};
}
-function cosSim(a,b) {
- let d=0,na=0,nb=0;
- for (let i=0;i<512;i++) { d+=a[i]*b[i]; na+=a[i]*a[i]; nb+=b[i]*b[i]; }
- return d/Math.sqrt(na*nb);
-}
+function cosSim(a, b) { return sdk.cosSim(a, b); }
// ===== Align + Crop =====
function alignAndCrop(face) {
diff --git a/wasm/demo_mask.html b/wasm/demo_mask.html
index 87e75f1..388b1da 100644
--- a/wasm/demo_mask.html
+++ b/wasm/demo_mask.html
@@ -138,6 +138,10 @@
</div>
</div>
+<script src="detect.js"></script>
+<script src="facex.js"></script>
+<script src="align.js"></script>
+<script src="cache.js"></script>
<script src="facex-sdk.js"></script>
<script>
const $ = (id) => document.getElementById(id);
diff --git a/wasm/detect.js b/wasm/detect.js
index ffcad6b..7d326a3 100644
--- a/wasm/detect.js
+++ b/wasm/detect.js
@@ -1,2 +1,21 @@
-var DetectModule=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};if(typeof __filename!="undefined"){_scriptName=__filename}else if(ENVIRONMENT_IS_WORKER){_scriptName=self.location.href}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var EXITSTATUS;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var readyPromiseResolve,readyPromiseReject;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["__wasm_call_ctors"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("detect_new.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={env:wasmImports,wasi_snapshot_preview1:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP16;var HEAP32;var HEAP64;var HEAP8;var HEAPF32;var HEAPF64;var HEAPU16;var HEAPU32;var HEAPU64;var HEAPU8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("node:crypto");return view=>nodeCrypto.randomFillSync(view)}return view=>(crypto.getRandomValues(view),0)};var randomFill=view=>(randomFill=initRandomFill())(view);var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=MEMFS.emptyFileContents??=new Uint8Array(0)}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){return node.contents.subarray(0,node.usedBytes)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents.length;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity)newCapacity=Math.max(newCapacity,256);var oldContents=MEMFS.getFileDataAsTypedArray(node);node.contents=new Uint8Array(newCapacity);node.contents.set(oldContents)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;var oldContents=node.contents;node.contents=new Uint8Array(newSize);node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)));node.usedBytes=newSize},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>"}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);buffer.set(contents.subarray(position,position+size),offset);return size},write(stream,buffer,offset,length,position,canOwn){if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length}else{MEMFS.expandFileStorage(node,position+length);node.contents.set(buffer.subarray(offset,offset+length),position);node.usedBytes=Math.max(node.usedBytes,position+length)}return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_modeStringToFlags=str=>{if(typeof str!="string")return str;var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_fileDataToTypedArray=data=>{if(typeof data=="string"){data=intArrayFromString(data,true)}if(!data.subarray){data=new Uint8Array(data)}return data};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}if(parts[i]==="."){continue}if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");nlinks--;continue linkloop}else{current=current.parent}continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay){return{path:current_path}}throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount)){current=current.mounted.root}if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink){throw new FS.ErrnoError(52)}var link=current.node_ops.readlink(current);if(!PATH.isAbs(link)){link=PATH.dirname(current_path)+"/"+link}path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}if(perms.includes("w")&&!(node.mode&146)){return 2}if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else if(FS.isDir(node.mode)){return 31}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}var mode=FS.flagsToPermissionString(flags);if(FS.isDir(node.mode)){if(mode!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,mode)},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}for(var mount of mounts){if(mount.type.syncfs){mount.type.syncfs(mount,populate,done)}else{done(null)}}},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable)){while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=FS_modeStringToFlags(flags);if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);data=FS_fileDataToTypedArray(data);FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn);FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){data=FS_fileDataToTypedArray(data);FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(globalThis.XMLHttpRequest){abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else{try{obj.contents=readBinary(obj.url)}catch(e){throw new FS.ErrnoError(29)}}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)abort("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops)){stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}}function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var SYSCALLS={calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>2]=stat.dev;HEAPU32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAPU32[buf+12>>2]=stat.uid;HEAPU32[buf+16>>2]=stat.gid;HEAPU32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>2]=stats.bsize;HEAPU32[buf+60>>2]=stats.bsize;HEAP64[buf+8>>3]=BigInt(stats.blocks);HEAP64[buf+16>>3]=BigInt(stats.bfree);HEAP64[buf+24>>3]=BigInt(stats.bavail);HEAP64[buf+32>>3]=BigInt(stats.files);HEAP64[buf+40>>3]=BigInt(stats.ffree);HEAPU32[buf+48>>2]=stats.fsid;HEAPU32[buf+64>>2]=stats.flags;HEAPU32[buf+56>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var runtimeKeepaliveCounter=0;var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var timers={};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{return func()}catch(e){handleException(e)}finally{maybeExit()}};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var abortOnCannotGrowMemory=requestedSize=>{abort("OOM")};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;abortOnCannotGrowMemory(requestedSize)};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len){break}if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["FS"]=FS;var _detect_init,_free,_detect_run,_detect_free,_detect_set_score_threshold,_malloc,__emscripten_timeout,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_detect_init=Module["_detect_init"]=wasmExports["detect_init"];_free=Module["_free"]=wasmExports["free"];_detect_run=Module["_detect_run"]=wasmExports["detect_run"];_detect_free=Module["_detect_free"]=wasmExports["detect_free"];_detect_set_score_threshold=Module["_detect_set_score_threshold"]=wasmExports["detect_set_score_threshold"];_malloc=Module["_malloc"]=wasmExports["malloc"];__emscripten_timeout=wasmExports["_emscripten_timeout"];__emscripten_stack_restore=wasmExports["_emscripten_stack_restore"];__emscripten_stack_alloc=wasmExports["_emscripten_stack_alloc"];_emscripten_stack_get_current=wasmExports["emscripten_stack_get_current"];memory=wasmMemory=wasmExports["memory"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={__syscall_fcntl64:___syscall_fcntl64,__syscall_ioctl:___syscall_ioctl,__syscall_openat:___syscall_openat,_abort_js:__abort_js,_emscripten_runtime_keepalive_clear:__emscripten_runtime_keepalive_clear,_setitimer_js:__setitimer_js,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_read:_fd_read,fd_seek:_fd_seek,fd_write:_fd_write,proc_exit:_proc_exit};function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}
-;return moduleRtn}})();if(typeof exports==="object"&&typeof module==="object"){module.exports=DetectModule;module.exports.default=DetectModule}else if(typeof define==="function"&&define["amd"])define([],()=>DetectModule);
+
+var DetectModule = (() => {
+ var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;
+ if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename;
+ return (
+function(DetectModule) {
+ DetectModule = DetectModule || {};
+
+var Module=typeof DetectModule!="undefined"?DetectModule:{};var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof importScripts=="function";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;function logExceptionOnExit(e){if(e instanceof ExitStatus)return;let toLog=e;err("exiting due to exception: "+toLog)}var fs;var nodePath;var requireNodeFS;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require("path").dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}requireNodeFS=(()=>{if(!nodePath){fs=require("fs");nodePath=require("path")}});read_=function shell_read(filename,binary){requireNodeFS();filename=nodePath["normalize"](filename);return fs.readFileSync(filename,binary?undefined:"utf8")};readBinary=(filename=>{var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}return ret});readAsync=((filename,onload,onerror)=>{requireNodeFS();filename=nodePath["normalize"](filename);fs.readFile(filename,function(err,data){if(err)onerror(err);else onload(data.buffer)})});if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",function(reason){throw reason});quit_=((status,toThrow)=>{if(keepRuntimeAlive()){process["exitCode"]=status;throw toThrow}logExceptionOnExit(toThrow);process["exit"](status)});Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=(url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText});if(ENVIRONMENT_IS_WORKER){readBinary=(url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)})}readAsync=((url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=(()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()});xhr.onerror=onerror;xhr.send(null)})}setWindowTitle=(title=>document.title=title)}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(text)}}function getCFunc(ident){var func=Module["_"+ident];return func}function ccall(ident,returnType,argTypes,args,opts){var toC={"string":function(str){var ret=0;if(str!==null&&str!==undefined&&str!==0){var len=(str.length<<2)+1;ret=stackAlloc(len);stringToUTF8(str,ret,len)}return ret},"array":function(arr){var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string")return UTF8ToString(ret);if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func.apply(null,cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret}function cwrap(ident,returnType,argTypes,opts){argTypes=argTypes||[];var numericArgs=argTypes.every(function(type){return type==="number"});var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return function(){return ccall(ident,returnType,argTypes,arguments,opts)}}var UTF8Decoder=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heap,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heap[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx<endPtr){var u0=heap[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heap[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heap[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heap[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module["HEAP8"]=HEAP8=new Int8Array(buf);Module["HEAP16"]=HEAP16=new Int16Array(buf);Module["HEAP32"]=HEAP32=new Int32Array(buf);Module["HEAPU8"]=HEAPU8=new Uint8Array(buf);Module["HEAPU16"]=HEAPU16=new Uint16Array(buf);Module["HEAPU32"]=HEAPU32=new Uint32Array(buf);Module["HEAPF32"]=HEAPF32=new Float32Array(buf);Module["HEAPF64"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeKeepaliveCounter=0;function keepRuntimeAlive(){return noExitRuntime||runtimeKeepaliveCounter>0}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.init.initialized)FS.init();FS.ignorePermissions=false;TTY.init();callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["preloadedImages"]={};Module["preloadedAudios"]={};function abort(what){{if(Module["onAbort"]){Module["onAbort"](what)}}what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;what+=". Build with -s ASSERTIONS=1 for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";function isDataURI(filename){return filename.startsWith(dataURIPrefix)}var wasmBinaryFile;wasmBinaryFile="detect.wasm";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}else{throw"both async and sync fetching of the wasm failed"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch=="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){if(!response["ok"]){throw"failed to load wasm binary file at '"+wasmBinaryFile+"'"}return response["arrayBuffer"]()}).catch(function(){return getBinary(wasmBinaryFile)})}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={"a":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module["asm"]=exports;wasmMemory=Module["asm"]["j"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module["asm"]["s"];addOnInit(Module["asm"]["k"]);removeRunDependency("wasm-instantiate")}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(function(instance){return instance}).then(receiver,function(reason){err("failed to asynchronously prepare wasm: "+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(wasmBinaryFile)&&typeof fetch=="function"){return fetch(wasmBinaryFile,{credentials:"same-origin"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiationResult,function(reason){err("wasm streaming compile failed: "+reason);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(receiveInstantiationResult)})})}else{return instantiateArrayBuffer(receiveInstantiationResult)}}if(Module["instantiateWasm"]){try{var exports=Module["instantiateWasm"](info,receiveInstance);return exports}catch(e){err("Module.instantiateWasm callback failed with error: "+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}var tempDouble;var tempI64;function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback(Module);continue}var func=callback.func;if(typeof func=="number"){if(callback.arg===undefined){getWasmTableEntry(func)()}else{getWasmTableEntry(func)(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}var wasmTableMirror=[];function getWasmTableEntry(funcPtr){var func=wasmTableMirror[funcPtr];if(!func){if(funcPtr>=wasmTableMirror.length)wasmTableMirror.length=funcPtr+1;wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func}function setErrNo(value){HEAP32[___errno_location()>>2]=value;return value}var PATH={splitPath:function(filename){var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:function(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:function(path){var isAbsolute=path.charAt(0)==="/",trailingSlash=path.substr(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:function(path){var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir},basename:function(path){if(path==="/")return"/";path=PATH.normalize(path);path=path.replace(/\/$/,"");var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},extname:function(path){return PATH.splitPath(path)[3]},join:function(){var paths=Array.prototype.slice.call(arguments,0);return PATH.normalize(paths.join("/"))},join2:function(l,r){return PATH.normalize(l+"/"+r)}};function getRandomDevice(){if(typeof crypto=="object"&&typeof crypto["getRandomValues"]=="function"){var randomBuffer=new Uint8Array(1);return function(){crypto.getRandomValues(randomBuffer);return randomBuffer[0]}}else if(ENVIRONMENT_IS_NODE){try{var crypto_module=require("crypto");return function(){return crypto_module["randomBytes"](1)[0]}}catch(e){}}return function(){abort("randomDevice")}}var PATH_FS={resolve:function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:function(from,to){from=PATH_FS.resolve(from).substr(1);to=PATH_FS.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var TTY={ttys:[],init:function(){},shutdown:function(){},register:function(dev,ops){TTY.ttys[dev]={input:[],output:[],ops:ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open:function(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close:function(stream){stream.tty.ops.flush(stream.tty)},flush:function(stream){stream.tty.ops.flush(stream.tty)},read:function(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.timestamp=Date.now()}return bytesRead},write:function(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.timestamp=Date.now()}return i}},default_tty_ops:{get_char:function(tty){if(!tty.input.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;try{bytesRead=fs.readSync(process.stdin.fd,buf,0,BUFSIZE,-1)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}else{result=null}}else if(typeof window!="undefined"&&typeof window.prompt=="function"){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else if(typeof readline=="function"){result=readline();if(result!==null){result+="\n"}}if(!result){return null}tty.input=intArrayFromString(result,true)}return tty.input.shift()},put_char:function(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},flush:function(tty){if(tty.output&&tty.output.length>0){out(UTF8ArrayToString(tty.output,0));tty.output=[]}}},default_tty1_ops:{put_char:function(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output,0));tty.output=[]}else{if(val!=0)tty.output.push(val)}},flush:function(tty){if(tty.output&&tty.output.length>0){err(UTF8ArrayToString(tty.output,0));tty.output=[]}}}};function mmapAlloc(size){abort()}var MEMFS={ops_table:null,mount:function(mount){return MEMFS.createNode(null,"/",16384|511,0)},createNode:function(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}if(!MEMFS.ops_table){MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}}}var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.timestamp=Date.now();if(parent){parent.contents[name]=node;parent.timestamp=node.timestamp}return node},getFileDataAsTypedArray:function(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage:function(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage:function(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr:function(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.timestamp);attr.mtime=new Date(node.timestamp);attr.ctime=new Date(node.timestamp);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr:function(node,attr){if(attr.mode!==undefined){node.mode=attr.mode}if(attr.timestamp!==undefined){node.timestamp=attr.timestamp}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup:function(parent,name){throw FS.genericErrors[44]},mknod:function(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename:function(old_node,new_dir,new_name){if(FS.isDir(old_node.mode)){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}}delete old_node.parent.contents[old_node.name];old_node.parent.timestamp=Date.now();old_node.name=new_name;new_dir.contents[new_name]=old_node;new_dir.timestamp=old_node.parent.timestamp;old_node.parent=new_dir},unlink:function(parent,name){delete parent.contents[name];parent.timestamp=Date.now()},rmdir:function(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.timestamp=Date.now()},readdir:function(node){var entries=[".",".."];for(var key in node.contents){if(!node.contents.hasOwnProperty(key)){continue}entries.push(key)}return entries},symlink:function(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink:function(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read:function(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i<size;i++)buffer[offset+i]=contents[position+i]}return size},write:function(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.timestamp=Date.now();if(buffer.subarray&&(!node.contents||node.contents.subarray)){if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length;return length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length;return length}else if(position+length<=node.usedBytes){node.contents.set(buffer.subarray(offset,offset+length),position);return length}}MEMFS.expandFileStorage(node,position+length);if(node.contents.subarray&&buffer.subarray){node.contents.set(buffer.subarray(offset,offset+length),position)}else{for(var i=0;i<length;i++){node.contents[position+i]=buffer[offset+i]}}node.usedBytes=Math.max(node.usedBytes,position+length);return length},llseek:function(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},allocate:function(stream,offset,length){MEMFS.expandFileStorage(stream.node,offset+length);stream.node.usedBytes=Math.max(stream.node.usedBytes,offset+length)},mmap:function(stream,address,length,position,prot,flags){if(address!==0){throw new FS.ErrnoError(28)}if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents.buffer===buffer){allocated=false;ptr=contents.byteOffset}else{if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}HEAP8.set(contents,ptr)}return{ptr:ptr,allocated:allocated}},msync:function(stream,buffer,offset,length,mmapFlags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(mmapFlags&2){return 0}var bytesWritten=MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};function asyncLoad(url,onload,onerror,noRunDep){var dep=!noRunDep?getUniqueRunDependency("al "+url):"";readAsync(url,function(arrayBuffer){assert(arrayBuffer,'Loading data file "'+url+'" failed (no arrayBuffer).');onload(new Uint8Array(arrayBuffer));if(dep)removeRunDependency(dep)},function(event){if(onerror){onerror()}else{throw'Loading data file "'+url+'" failed.'}});if(dep)addRunDependency(dep)}var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(path,opts={})=>{path=PATH_FS.resolve(FS.cwd(),path);if(!path)return{path:"",node:null};var defaults={follow_mount:true,recurse_count:0};for(var key in defaults){if(opts[key]===undefined){opts[key]=defaults[key]}}if(opts.recurse_count>8){throw new FS.ErrnoError(32)}var parts=PATH.normalizeArray(path.split("/").filter(p=>!!p),false);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}current=FS.lookupNode(current,parts[i]);current_path=PATH.join2(current_path,parts[i]);if(FS.isMountpoint(current)){if(!islast||islast&&opts.follow_mount){current=current.mounted.root}}if(!islast||opts.follow){var count=0;while(FS.isLink(current.mode)){var link=FS.readlink(current_path);current_path=PATH_FS.resolve(PATH.dirname(current_path),link);var lookup=FS.lookupPath(current_path,{recurse_count:opts.recurse_count});current=lookup.node;if(count++>40){throw new FS.ErrnoError(32)}}}}return{path:current_path,node:current}},getPath:node=>{var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?mount+"/"+path:mount+path}path=path?node.name+"/"+path:node.name;node=node.parent}},hashName:(parentid,name)=>{var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode:node=>{var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode:node=>{var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode:(parent,name)=>{var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode,parent)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode:(parent,name,mode,rdev)=>{var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode:node=>{FS.hashRemoveNode(node)},isRoot:node=>{return node===node.parent},isMountpoint:node=>{return!!node.mounted},isFile:mode=>{return(mode&61440)===32768},isDir:mode=>{return(mode&61440)===16384},isLink:mode=>{return(mode&61440)===40960},isChrdev:mode=>{return(mode&61440)===8192},isBlkdev:mode=>{return(mode&61440)===24576},isFIFO:mode=>{return(mode&61440)===4096},isSocket:mode=>{return(mode&49152)===49152},flagModes:{"r":0,"r+":2,"w":577,"w+":578,"a":1089,"a+":1090},modeStringToFlags:str=>{var flags=FS.flagModes[str];if(typeof flags=="undefined"){throw new Error("Unknown file open mode: "+str)}return flags},flagsToPermissionString:flag=>{var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions:(node,perms)=>{if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup:dir=>{var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate:(dir,name)=>{try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete:(dir,name,isdir)=>{var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen:(node,flags)=>{if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&512){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},MAX_OPEN_FDS:4096,nextfd:(fd_start=0,fd_end=FS.MAX_OPEN_FDS)=>{for(var fd=fd_start;fd<=fd_end;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStream:fd=>FS.streams[fd],createStream:(stream,fd_start,fd_end)=>{if(!FS.FSStream){FS.FSStream=function(){};FS.FSStream.prototype={object:{get:function(){return this.node},set:function(val){this.node=val}},isRead:{get:function(){return(this.flags&2097155)!==1}},isWrite:{get:function(){return(this.flags&2097155)!==0}},isAppend:{get:function(){return this.flags&1024}}}}stream=Object.assign(new FS.FSStream,stream);var fd=FS.nextfd(fd_start,fd_end);stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream:fd=>{FS.streams[fd]=null},chrdev_stream_ops:{open:stream=>{var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;if(stream.stream_ops.open){stream.stream_ops.open(stream)}},llseek:()=>{throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice:(dev,ops)=>{FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts:mount=>{var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push.apply(check,m.mounts)}return mounts},syncfs:(populate,callback)=>{if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err("warning: "+FS.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work")}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}mounts.forEach(mount=>{if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},mount:(type,opts,mountpoint)=>{var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type:type,opts:opts,mountpoint:mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount:mountpoint=>{var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);Object.keys(FS.nameTable).forEach(hash=>{var current=FS.nameTable[hash];while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}});node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup:(parent,name)=>{return parent.node_ops.lookup(parent,name)},mknod:(path,mode,dev)=>{var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name||name==="."||name===".."){throw new FS.ErrnoError(28)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},create:(path,mode)=>{mode=mode!==undefined?mode:438;mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir:(path,mode)=>{mode=mode!==undefined?mode:511;mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree:(path,mode)=>{var dirs=path.split("/");var d="";for(var i=0;i<dirs.length;++i){if(!dirs[i])continue;d+="/"+dirs[i];try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev:(path,mode,dev)=>{if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink:(oldpath,newpath)=>{if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename:(old_path,new_path)=>{var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name)}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir:path=>{var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir:path=>{var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;if(!node.node_ops.readdir){throw new FS.ErrnoError(54)}return node.node_ops.readdir(node)},unlink:path=>{var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink:path=>{var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return PATH_FS.resolve(FS.getPath(link.parent),link.node_ops.readlink(link))},stat:(path,dontFollow)=>{var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;if(!node){throw new FS.ErrnoError(44)}if(!node.node_ops.getattr){throw new FS.ErrnoError(63)}return node.node_ops.getattr(node)},lstat:path=>{return FS.stat(path,true)},chmod:(path,mode,dontFollow)=>{var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}node.node_ops.setattr(node,{mode:mode&4095|node.mode&~4095,timestamp:Date.now()})},lchmod:(path,mode)=>{FS.chmod(path,mode,true)},fchmod:(fd,mode)=>{var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}FS.chmod(stream.node,mode)},chown:(path,uid,gid,dontFollow)=>{var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}node.node_ops.setattr(node,{timestamp:Date.now()})},lchown:(path,uid,gid)=>{FS.chown(path,uid,gid,true)},fchown:(fd,uid,gid)=>{var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}FS.chown(stream.node,uid,gid)},truncate:(path,len)=>{if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}if(!node.node_ops.setattr){throw new FS.ErrnoError(63)}if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}node.node_ops.setattr(node,{size:len,timestamp:Date.now()})},ftruncate:(fd,len)=>{var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.truncate(stream.node,len)},utime:(path,atime,mtime)=>{var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;node.node_ops.setattr(node,{timestamp:Math.max(atime,mtime)})},open:(path,flags,mode,fd_start,fd_end)=>{if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS.modeStringToFlags(flags):flags;mode=typeof mode=="undefined"?438:mode;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;if(typeof path=="object"){node=path}else{path=PATH.normalize(path);try{var lookup=FS.lookupPath(path,{follow:!(flags&131072)});node=lookup.node}catch(e){}}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else{node=FS.mknod(path,mode,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node:node,path:FS.getPath(node),flags:flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false},fd_start,fd_end);if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(Module["logReadFiles"]&&!(flags&1)){if(!FS.readFiles)FS.readFiles={};if(!(path in FS.readFiles)){FS.readFiles[path]=1}}return stream},close:stream=>{if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed:stream=>{return stream.fd===null},llseek:(stream,offset,whence)=>{if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read:(stream,buffer,offset,length,position)=>{if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write:(stream,buffer,offset,length,position,canOwn)=>{if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},allocate:(stream,offset,length)=>{if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(offset<0||length<=0){throw new FS.ErrnoError(28)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(!FS.isFile(stream.node.mode)&&!FS.isDir(stream.node.mode)){throw new FS.ErrnoError(43)}if(!stream.stream_ops.allocate){throw new FS.ErrnoError(138)}stream.stream_ops.allocate(stream,offset,length)},mmap:(stream,address,length,position,prot,flags)=>{if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}return stream.stream_ops.mmap(stream,address,length,position,prot,flags)},msync:(stream,buffer,offset,length,mmapFlags)=>{if(!stream||!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},munmap:stream=>0,ioctl:(stream,cmd,arg)=>{if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile:(path,opts={})=>{opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){throw new Error('Invalid encoding type "'+opts.encoding+'"')}var ret;var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){ret=UTF8ArrayToString(buf,0)}else if(opts.encoding==="binary"){ret=buf}FS.close(stream);return ret},writeFile:(path,data,opts={})=>{opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){var buf=new Uint8Array(lengthBytesUTF8(data)+1);var actualNumBytes=stringToUTF8Array(data,buf,0,buf.length);FS.write(stream,buf,0,actualNumBytes,undefined,opts.canOwn)}else if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{throw new Error("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir:path=>{var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories:()=>{FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices:()=>{FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var random_device=getRandomDevice();FS.createDevice("/dev","random",random_device);FS.createDevice("/dev","urandom",random_device);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount:()=>{var node=FS.createNode(proc_self,"fd",16384|511,73);node.node_ops={lookup:(parent,name)=>{var fd=+name;var stream=FS.getStream(fd);if(!stream)throw new FS.ErrnoError(8);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path}};ret.parent=ret;return ret}};return node}},{},"/proc/self/fd")},createStandardStreams:()=>{if(Module["stdin"]){FS.createDevice("/dev","stdin",Module["stdin"])}else{FS.symlink("/dev/tty","/dev/stdin")}if(Module["stdout"]){FS.createDevice("/dev","stdout",null,Module["stdout"])}else{FS.symlink("/dev/tty","/dev/stdout")}if(Module["stderr"]){FS.createDevice("/dev","stderr",null,Module["stderr"])}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},ensureErrnoError:()=>{if(FS.ErrnoError)return;FS.ErrnoError=function ErrnoError(errno,node){this.node=node;this.setErrno=function(errno){this.errno=errno};this.setErrno(errno);this.message="FS error"};FS.ErrnoError.prototype=new Error;FS.ErrnoError.prototype.constructor=FS.ErrnoError;[44].forEach(code=>{FS.genericErrors[code]=new FS.ErrnoError(code);FS.genericErrors[code].stack="<generic error, no stack>"})},staticInit:()=>{FS.ensureErrnoError();FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={"MEMFS":MEMFS}},init:(input,output,error)=>{FS.init.initialized=true;FS.ensureErrnoError();Module["stdin"]=input||Module["stdin"];Module["stdout"]=output||Module["stdout"];Module["stderr"]=error||Module["stderr"];FS.createStandardStreams()},quit:()=>{FS.init.initialized=false;for(var i=0;i<FS.streams.length;i++){var stream=FS.streams[i];if(!stream){continue}FS.close(stream)}},getMode:(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode},findObject:(path,dontResolveLastLink)=>{var ret=FS.analyzePath(path,dontResolveLastLink);if(ret.exists){return ret.object}else{return null}},analyzePath:(path,dontResolveLastLink)=>{try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath:(parent,path,canRead,canWrite)=>{parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){}parent=current}return current},createFile:(parent,name,properties,canRead,canWrite)=>{var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS.getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile:(parent,name,data,canRead,canWrite,canOwn)=>{var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS.getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i<len;++i)arr[i]=data.charCodeAt(i);data=arr}FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}return node},createDevice:(parent,name,input,output)=>{var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS.getMode(!!input,!!output);if(!FS.createDevice.major)FS.createDevice.major=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open:stream=>{stream.seekable=false},close:stream=>{if(output&&output.buffer&&output.buffer.length){output(10)}},read:(stream,buffer,offset,length,pos)=>{var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.timestamp=Date.now()}return bytesRead},write:(stream,buffer,offset,length,pos)=>{for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.timestamp=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile:obj=>{if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(typeof XMLHttpRequest!="undefined"){throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else if(read_){try{obj.contents=intArrayFromString(read_(obj.url),true);obj.usedBytes=obj.contents.length}catch(e){throw new FS.ErrnoError(29)}}else{throw new Error("Cannot load without read() or XMLHttpRequest.")}},createLazyFile:(parent,name,url,canRead,canWrite)=>{function LazyUint8Array(){this.lengthKnown=false;this.chunks=[]}LazyUint8Array.prototype.get=function LazyUint8Array_get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]};LazyUint8Array.prototype.setDataGetter=function LazyUint8Array_setDataGetter(getter){this.getter=getter};LazyUint8Array.prototype.cacheLength=function LazyUint8Array_cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)throw new Error("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)throw new Error("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}else{return intArrayFromString(xhr.responseText||"",true)}};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")throw new Error("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true};if(typeof XMLHttpRequest!="undefined"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var lazyArray=new LazyUint8Array;Object.defineProperties(lazyArray,{length:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._length}},chunkSize:{get:function(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}});var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url:url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};var keys=Object.keys(node.stream_ops);keys.forEach(key=>{var fn=node.stream_ops[key];stream_ops[key]=function forceLoadLazyFile(){FS.forceLoadFile(node);return fn.apply(null,arguments)}});stream_ops.read=((stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size});node.stream_ops=stream_ops;return node},createPreloadedFile:(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency("cp "+fullname);function processData(byteArray){function finish(byteArray){if(preFinish)preFinish();if(!dontCreateFile){FS.createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}if(onload)onload();removeRunDependency(dep)}if(Browser.handledByPreloadPlugin(byteArray,fullname,finish,()=>{if(onerror)onerror();removeRunDependency(dep)})){return}finish(byteArray)}addRunDependency(dep);if(typeof url=="string"){asyncLoad(url,byteArray=>processData(byteArray),onerror)}else{processData(url)}},indexedDB:()=>{return window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB},DB_NAME:()=>{return"EM_FS_"+window.location.pathname},DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:(paths,onload,onerror)=>{onload=onload||(()=>{});onerror=onerror||(()=>{});var indexedDB=FS.indexedDB();try{var openRequest=indexedDB.open(FS.DB_NAME(),FS.DB_VERSION)}catch(e){return onerror(e)}openRequest.onupgradeneeded=(()=>{out("creating db");var db=openRequest.result;db.createObjectStore(FS.DB_STORE_NAME)});openRequest.onsuccess=(()=>{var db=openRequest.result;var transaction=db.transaction([FS.DB_STORE_NAME],"readwrite");var files=transaction.objectStore(FS.DB_STORE_NAME);var ok=0,fail=0,total=paths.length;function finish(){if(fail==0)onload();else onerror()}paths.forEach(path=>{var putRequest=files.put(FS.analyzePath(path).object.contents,path);putRequest.onsuccess=(()=>{ok++;if(ok+fail==total)finish()});putRequest.onerror=(()=>{fail++;if(ok+fail==total)finish()})});transaction.onerror=onerror});openRequest.onerror=onerror},loadFilesFromDB:(paths,onload,onerror)=>{onload=onload||(()=>{});onerror=onerror||(()=>{});var indexedDB=FS.indexedDB();try{var openRequest=indexedDB.open(FS.DB_NAME(),FS.DB_VERSION)}catch(e){return onerror(e)}openRequest.onupgradeneeded=onerror;openRequest.onsuccess=(()=>{var db=openRequest.result;try{var transaction=db.transaction([FS.DB_STORE_NAME],"readonly")}catch(e){onerror(e);return}var files=transaction.objectStore(FS.DB_STORE_NAME);var ok=0,fail=0,total=paths.length;function finish(){if(fail==0)onload();else onerror()}paths.forEach(path=>{var getRequest=files.get(path);getRequest.onsuccess=(()=>{if(FS.analyzePath(path).exists){FS.unlink(path)}FS.createDataFile(PATH.dirname(path),PATH.basename(path),getRequest.result,true,true,true);ok++;if(ok+fail==total)finish()});getRequest.onerror=(()=>{fail++;if(ok+fail==total)finish()})});transaction.onerror=onerror});openRequest.onerror=onerror}};var SYSCALLS={DEFAULT_POLLMASK:5,calculateAt:function(dirfd,path,allowEmpty){if(path[0]==="/"){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=FS.getStream(dirfd);if(!dirstream)throw new FS.ErrnoError(8);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return PATH.join2(dir,path)},doStat:function(func,path,buf){try{var stat=func(path)}catch(e){if(e&&e.node&&PATH.normalize(path)!==PATH.normalize(FS.getPath(e.node))){return-54}throw e}HEAP32[buf>>2]=stat.dev;HEAP32[buf+4>>2]=0;HEAP32[buf+8>>2]=stat.ino;HEAP32[buf+12>>2]=stat.mode;HEAP32[buf+16>>2]=stat.nlink;HEAP32[buf+20>>2]=stat.uid;HEAP32[buf+24>>2]=stat.gid;HEAP32[buf+28>>2]=stat.rdev;HEAP32[buf+32>>2]=0;tempI64=[stat.size>>>0,(tempDouble=stat.size,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+40>>2]=tempI64[0],HEAP32[buf+44>>2]=tempI64[1];HEAP32[buf+48>>2]=4096;HEAP32[buf+52>>2]=stat.blocks;HEAP32[buf+56>>2]=stat.atime.getTime()/1e3|0;HEAP32[buf+60>>2]=0;HEAP32[buf+64>>2]=stat.mtime.getTime()/1e3|0;HEAP32[buf+68>>2]=0;HEAP32[buf+72>>2]=stat.ctime.getTime()/1e3|0;HEAP32[buf+76>>2]=0;tempI64=[stat.ino>>>0,(tempDouble=stat.ino,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+80>>2]=tempI64[0],HEAP32[buf+84>>2]=tempI64[1];return 0},doMsync:function(addr,stream,len,flags,offset){var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},doMkdir:function(path,mode){path=PATH.normalize(path);if(path[path.length-1]==="/")path=path.substr(0,path.length-1);FS.mkdir(path,mode,0);return 0},doMknod:function(path,mode,dev){switch(mode&61440){case 32768:case 8192:case 24576:case 4096:case 49152:break;default:return-28}FS.mknod(path,mode,dev);return 0},doReadlink:function(path,buf,bufsize){if(bufsize<=0)return-28;var ret=FS.readlink(path);var len=Math.min(bufsize,lengthBytesUTF8(ret));var endChar=HEAP8[buf+len];stringToUTF8(ret,buf,bufsize+1);HEAP8[buf+len]=endChar;return len},doAccess:function(path,amode){if(amode&~7){return-28}var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;if(!node){return-44}var perms="";if(amode&4)perms+="r";if(amode&2)perms+="w";if(amode&1)perms+="x";if(perms&&FS.nodePermissions(node,perms)){return-2}return 0},doDup:function(path,flags,suggestFD){var suggest=FS.getStream(suggestFD);if(suggest)FS.close(suggest);return FS.open(path,flags,0,suggestFD,suggestFD).fd},doReadv:function(stream,iov,iovcnt,offset){var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAP32[iov+i*8>>2];var len=HEAP32[iov+(i*8+4)>>2];var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len)break}return ret},doWritev:function(stream,iov,iovcnt,offset){var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAP32[iov+i*8>>2];var len=HEAP32[iov+(i*8+4)>>2];var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr}return ret},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},getStreamFromFD:function(fd){var stream=FS.getStream(fd);if(!stream)throw new FS.ErrnoError(8);return stream},get64:function(low,high){return low}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=SYSCALLS.get();if(arg<0){return-28}var newStream;newStream=FS.open(stream.path,stream.flags,0,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=SYSCALLS.get();stream.flags|=arg;return 0}case 5:{var arg=SYSCALLS.get();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 6:case 7:return 0;case 16:case 8:return-28;case 9:setErrNo(28);return-1;default:{return-28}}}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:case 21505:{if(!stream.tty)return-59;return 0}case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:{if(!stream.tty)return-59;return 0}case 21519:{if(!stream.tty)return-59;var argp=SYSCALLS.get();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21531:{var argp=SYSCALLS.get();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;return 0}case 21524:{if(!stream.tty)return-59;return 0}default:abort("bad ioctl syscall "+op)}}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function ___syscall_open(path,flags,varargs){SYSCALLS.varargs=varargs;try{var pathname=SYSCALLS.getStr(path);var mode=varargs?SYSCALLS.get():0;var stream=FS.open(pathname,flags,mode);return stream.fd}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return-e.errno}}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function _emscripten_get_heap_max(){return 2147483648}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=HEAPU8.length;requestedSize=requestedSize>>>0;var maxHeapSize=_emscripten_get_heap_max();if(requestedSize>maxHeapSize){return false}let alignUp=(x,multiple)=>x+(multiple-x%multiple)%multiple;for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=SYSCALLS.doReadv(stream,iov,iovcnt);HEAP32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){try{var stream=SYSCALLS.getStreamFromFD(fd);var HIGH_OFFSET=4294967296;var offset=offset_high*HIGH_OFFSET+(offset_low>>>0);var DOUBLE_LIMIT=9007199254740992;if(offset<=-DOUBLE_LIMIT||offset>=DOUBLE_LIMIT){return-61}FS.llseek(stream,offset,whence);tempI64=[stream.position>>>0,(tempDouble=stream.position,+Math.abs(tempDouble)>=1?tempDouble>0?(Math.min(+Math.floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[newOffset>>2]=tempI64[0],HEAP32[newOffset+4>>2]=tempI64[1];if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=SYSCALLS.doWritev(stream,iov,iovcnt);HEAP32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e instanceof FS.ErrnoError))throw e;return e.errno}}var FSNode=function(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.mounted=null;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.node_ops={};this.stream_ops={};this.rdev=rdev};var readMode=292|73;var writeMode=146;Object.defineProperties(FSNode.prototype,{read:{get:function(){return(this.mode&readMode)===readMode},set:function(val){val?this.mode|=readMode:this.mode&=~readMode}},write:{get:function(){return(this.mode&writeMode)===writeMode},set:function(val){val?this.mode|=writeMode:this.mode&=~writeMode}},isFolder:{get:function(){return FS.isDir(this.mode)}},isDevice:{get:function(){return FS.isChrdev(this.mode)}}});FS.FSNode=FSNode;FS.staticInit();Module["FS_createPath"]=FS.createPath;Module["FS_createDataFile"]=FS.createDataFile;Module["FS_createPreloadedFile"]=FS.createPreloadedFile;Module["FS_createLazyFile"]=FS.createLazyFile;Module["FS_createDevice"]=FS.createDevice;Module["FS_unlink"]=FS.unlink;function intArrayFromString(stringy,dontAddNull,length){var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array}var asmLibraryArg={"c":___syscall_fcntl64,"g":___syscall_ioctl,"h":___syscall_open,"i":_emscripten_memcpy_big,"e":_emscripten_resize_heap,"a":_fd_close,"f":_fd_read,"d":_fd_seek,"b":_fd_write};var asm=createWasm();var ___wasm_call_ctors=Module["___wasm_call_ctors"]=function(){return(___wasm_call_ctors=Module["___wasm_call_ctors"]=Module["asm"]["k"]).apply(null,arguments)};var _detect_init=Module["_detect_init"]=function(){return(_detect_init=Module["_detect_init"]=Module["asm"]["l"]).apply(null,arguments)};var _malloc=Module["_malloc"]=function(){return(_malloc=Module["_malloc"]=Module["asm"]["m"]).apply(null,arguments)};var _free=Module["_free"]=function(){return(_free=Module["_free"]=Module["asm"]["n"]).apply(null,arguments)};var _detect_run=Module["_detect_run"]=function(){return(_detect_run=Module["_detect_run"]=Module["asm"]["o"]).apply(null,arguments)};var _detect_free=Module["_detect_free"]=function(){return(_detect_free=Module["_detect_free"]=Module["asm"]["p"]).apply(null,arguments)};var _detect_version=Module["_detect_version"]=function(){return(_detect_version=Module["_detect_version"]=Module["asm"]["q"]).apply(null,arguments)};var ___errno_location=Module["___errno_location"]=function(){return(___errno_location=Module["___errno_location"]=Module["asm"]["r"]).apply(null,arguments)};var stackSave=Module["stackSave"]=function(){return(stackSave=Module["stackSave"]=Module["asm"]["t"]).apply(null,arguments)};var stackRestore=Module["stackRestore"]=function(){return(stackRestore=Module["stackRestore"]=Module["asm"]["u"]).apply(null,arguments)};var stackAlloc=Module["stackAlloc"]=function(){return(stackAlloc=Module["stackAlloc"]=Module["asm"]["v"]).apply(null,arguments)};Module["cwrap"]=cwrap;Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["FS_createPath"]=FS.createPath;Module["FS_createDataFile"]=FS.createDataFile;Module["FS_createPreloadedFile"]=FS.createPreloadedFile;Module["FS_createLazyFile"]=FS.createLazyFile;Module["FS_createDevice"]=FS.createDevice;Module["FS_unlink"]=FS.unlink;Module["FS"]=FS;var calledRun;function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}Module["run"]=run;if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();
+
+
+ return DetectModule.ready
+}
+);
+})();
+if (typeof exports === 'object' && typeof module === 'object')
+ module.exports = DetectModule;
+else if (typeof define === 'function' && define['amd'])
+ define([], function() { return DetectModule; });
+else if (typeof exports === 'object')
+ exports["DetectModule"] = DetectModule;
diff --git a/wasm/detect.wasm b/wasm/detect.wasm
index 13d861f..ad5adfe 100644
Binary files a/wasm/detect.wasm and b/wasm/detect.wasm differ
diff --git a/wasm/facex-sdk.d.ts b/wasm/facex-sdk.d.ts
index f950beb..dfaf63f 100644
--- a/wasm/facex-sdk.d.ts
+++ b/wasm/facex-sdk.d.ts
@@ -1,11 +1,13 @@
/**
* FaceX Browser SDK — Face recognition in WebAssembly.
- * 74 KB engine. No server. No dependencies.
+ * No server. No dependencies.
*/
export interface FaceXOptions {
/** Detection input size (default: 160) */
detSize?: number;
+ /** Directory containing detect.wasm and facex.wasm. */
+ wasmBaseUrl?: string;
/** Cosine similarity threshold for match (default: 0.3) */
threshold?: number;
/** URL to detector weights (default: 'det_500m_int8.bin') */
@@ -40,7 +42,7 @@ export interface ProcessResult {
export interface VerifyResult {
/** Whether faces match */
match: boolean;
- /** Cosine similarity 0-1 */
+ /** Cosine similarity from -1 to 1 */
similarity: number;
/** Detected faces */
faces: Face[];
@@ -69,6 +71,7 @@ export declare class FaceXSDK {
/** Load engines and weights. Call once before using. */
load(): Promise<FaceXSDK>;
+ close(): Promise<void>;
/** Detect faces in video/image/canvas */
detect(source: HTMLVideoElement | HTMLCanvasElement | HTMLImageElement): Face[];
diff --git a/wasm/facex-sdk.js b/wasm/facex-sdk.js
index 2568aa1..2525847 100644
--- a/wasm/facex-sdk.js
+++ b/wasm/facex-sdk.js
@@ -1,312 +1,218 @@
-/*
- * facex-sdk.js — Unified FaceX browser SDK.
- *
- * Single entry point for face detection + alignment + embedding.
- *
- * Usage:
- * const fx = new FaceXSDK();
- * await fx.load();
- * const result = await fx.verify(videoElement, referenceEmbedding);
- * // { match: true, similarity: 0.87, faces: [...], ms: 17 }
- */
-
-class FaceXSDK {
- constructor(options = {}) {
- this.detSize = options.detSize || 160;
- this.threshold = options.threshold || 0.3;
- this.detWeightsUrl = options.detWeightsUrl || 'yunet_fp32.bin';
- this.embWeightsUrl = options.embWeightsUrl || 'edgeface_xs_fp32.bin';
- this.onProgress = options.onProgress || null;
-
- this._det = null;
- this._fx = null;
- this._detHandle = 0;
- this._fxHandle = 0;
- this._ready = false;
-
- // Reusable canvases
- this._detCanvas = document.createElement('canvas');
- this._detCtx = this._detCanvas.getContext('2d', { willReadFrequently: true });
- this._cropCanvas = document.createElement('canvas');
- this._cropCanvas.width = 112;
- this._cropCanvas.height = 112;
- this._cropCtx = this._cropCanvas.getContext('2d', { willReadFrequently: true });
- this._srcCanvas = document.createElement('canvas');
- this._srcCtx = this._srcCanvas.getContext('2d', { willReadFrequently: true });
- }
-
- /** Load engines and weights. Call once. */
- async load() {
- // Check SIMD support
- if (!this._checkSimd()) {
- throw new Error('WebAssembly SIMD not supported. Chrome 91+, Firefox 89+, Safari 16.4+ required.');
- }
-
- this._progress('Loading detection engine...');
- this._det = await FaceDetModule();
-
- this._progress('Loading embedding engine...');
- this._fx = await FaceXModule();
-
- // Load weights with caching
- this._progress('Loading detector weights (208 KB)...');
- const detW = await this._loadCached(this.detWeightsUrl, 'facex_det_weights');
- this._det.FS.writeFile('/det.bin', detW);
-
- this._progress('Loading embedding weights (7 MB)...');
- const fxW = await this._loadCached(this.embWeightsUrl, 'facex_emb_weights');
- this._fx.FS.writeFile('/emb.bin', fxW);
-
- // Init engines
- const di = this._det.cwrap('detect_init', 'number', ['string']);
- this._detHandle = di('/det.bin');
- if (!this._detHandle) throw new Error('Face detector initialization failed');
-
- const fi = this._fx.cwrap('facex_init', 'number', ['string', 'string']);
- this._fxHandle = fi('/emb.bin', null);
- if (!this._fxHandle) throw new Error('Face embedder initialization failed');
-
- this._ready = true;
- this._progress('Ready');
- return this;
- }
-
- /** Check if SDK is loaded and ready */
- get ready() { return this._ready; }
-
- /**
- * Detect faces in a video/image/canvas element.
- * @returns {Array<{x1,y1,x2,y2,score,kps}>}
- */
- detect(source) {
- if (!this._ready) throw new Error('SDK not loaded. Call load() first.');
- const { pixels, W, H } = this._prepareDetInput(source);
- return this._runDetect(pixels, W, H);
- }
-
- /**
- * Compute 512-dim embedding from aligned 112x112 face.
- * @param {ImageData} faceImageData - 112x112 RGBA image
- * @returns {Float32Array} 512-dim embedding
- */
- embed(faceImageData) {
- if (!this._ready) throw new Error('SDK not loaded');
- return this._runEmbed(faceImageData);
- }
-
- /**
- * Full pipeline: detect → align → embed from video/image source.
- * @returns {{faces, embeddings, ms}}
- */
- process(source) {
- if (!this._ready) throw new Error('SDK not loaded');
- const t0 = performance.now();
-
- const { pixels, W, H, scale, dx, dy } = this._prepareDetInput(source);
- const rawFaces = this._runDetect(pixels, W, H);
-
- // Map faces back to source coordinates
- const faces = rawFaces.map(f => ({
- x1: (f.x1 - dx) / scale,
- y1: (f.y1 - dy) / scale,
- x2: (f.x2 - dx) / scale,
- y2: (f.y2 - dy) / scale,
- score: f.score,
- kps: f.kps.map((v, i) => (v - (i % 2 === 0 ? dx : dy)) / scale)
- }));
-
- // Align and embed each face
- const sourceW = this._srcCanvas.width;
- const sourceH = this._srcCanvas.height;
- const embeddings = faces.map(face => {
- const kps5 = [];
- for (let i = 0; i < 5; i++)
- kps5.push([face.kps[i * 2], face.kps[i * 2 + 1]]);
-
- const aligned = alignFace(this._srcCtx, sourceW, sourceH, kps5, this._cropCtx);
- return this._runEmbed(aligned);
+/* Shared transports for the browser SDK and Web Worker. */
+const facexCommonJS = typeof module !== 'undefined' && !!module.exports;
+
+async function loadFaceXEngines(options = {}) {
+ const detectFactory = facexCommonJS ? require('./detect.js') : DetectModule;
+ const embedFactory = facexCommonJS ? require('./facex.js') : FaceXModule;
+ const loadWeights = facexCommonJS ? require('./cache.js').loadWeightsCached :
+ (typeof loadWeightsCached === 'function' ? loadWeightsCached : async url => {
+ const response = await fetch(url);
+ if (!response.ok) throw new Error('Weight request failed with status ' + response.status);
+ return new Uint8Array(await response.arrayBuffer());
});
-
- return {
- faces,
- embeddings,
- ms: performance.now() - t0
- };
+ const configuration = {};
+ if (options.wasmBaseUrl) {
+ const base = new URL(options.wasmBaseUrl.replace(/\/?$/, '/'), globalThis.location.href);
+ configuration.locateFile = file => new URL(file, base).href;
}
-
- /**
- * Verify: compare live source against a reference embedding.
- * @returns {{match, similarity, faces, ms}}
- */
- verify(source, refEmbedding) {
- const result = this.process(source);
- if (result.embeddings.length === 0) {
- return { match: false, similarity: 0, faces: result.faces, ms: result.ms, noFace: true };
- }
- const sim = this.cosSim(result.embeddings[0], refEmbedding);
- return {
- match: sim > this.threshold,
- similarity: sim,
- faces: result.faces,
- embedding: result.embeddings[0],
- ms: result.ms
- };
+ const [det, fx, detBytes, embBytes] = await Promise.all([
+ detectFactory({...configuration}), embedFactory({...configuration}),
+ loadWeights(options.detWeightsUrl || 'yunet_fp32.bin', 'detector'),
+ loadWeights(options.embWeightsUrl || 'edgeface_xs_fp32.bin', 'embedder'),
+ ]);
+ det.FS.writeFile('/det.bin', detBytes);
+ fx.FS.writeFile('/emb.bin', embBytes);
+ let detector = 0, embedder = 0;
+ try {
+ detector = det.cwrap('detect_init', 'number', ['string'])('/det.bin');
+ if (!detector) throw new Error('Detector initialization failed');
+ embedder = fx.cwrap('facex_init', 'number', ['string', 'string', 'string'])('/emb.bin', null, null);
+ if (!embedder) throw new Error('Embedder initialization failed');
+ } catch (error) {
+ if (detector) det._detect_free(detector);
+ if (embedder) fx._facex_free(embedder);
+ throw error;
+ } finally {
+ det.FS.unlink('/det.bin');
+ fx.FS.unlink('/emb.bin');
}
+ return {det, fx, detector, embedder};
+}
- /** Cosine similarity between two embeddings */
- cosSim(a, b) {
- let dot = 0, na = 0, nb = 0;
- for (let i = 0; i < 512; i++) {
- dot += a[i] * b[i];
- na += a[i] * a[i];
- nb += b[i] * b[i];
+function facexDetectPixels(engines, rgb, width, height) {
+ if (!(rgb instanceof Uint8Array) || rgb.length !== width * height * 3) {
+ throw new TypeError('Expected packed RGB bytes for the detector');
+ }
+ const {det, detector} = engines;
+ const limit = 10;
+ const input = det._malloc(rgb.length), output = det._malloc(limit * 15 * 4);
+ try {
+ if (!input || !output) throw new Error('Detector allocation failed');
+ det.HEAPU8.set(rgb, input);
+ const count = det._detect_run(detector, input, width, height, output, limit);
+ if (count < 0 || count > limit) throw new Error('Face detection failed');
+ const values = new Float32Array(det.HEAPU8.buffer, output, count * 15);
+ const faces = [];
+ for (let i = 0; i < values.length; i += 15) {
+ faces.push({x1: values[i], y1: values[i + 1], x2: values[i + 2], y2: values[i + 3],
+ score: values[i + 4], kps: Array.from(values.subarray(i + 5, i + 15))});
}
- return dot / (Math.sqrt(na) * Math.sqrt(nb));
+ return faces;
+ } finally {
+ det._free(output);
+ det._free(input);
}
+}
- /** Capture reference embedding from current video frame */
- captureReference(source) {
- const result = this.process(source);
- if (result.embeddings.length === 0) return null;
- return {
- embedding: result.embeddings[0],
- face: result.faces[0],
- alignedCanvas: this._cropCanvas
- };
+function facexEmbedPixels(engines, pixels) {
+ if (!(pixels instanceof Float32Array) || pixels.length !== 112 * 112 * 3) {
+ throw new TypeError('Expected a normalized 112 by 112 RGB face');
}
-
- // ============ Internal methods ============
-
- _progress(msg) {
- if (this.onProgress) this.onProgress(msg);
+ const {fx, embedder} = engines;
+ const input = fx._malloc(pixels.byteLength), output = fx._malloc(512 * 4);
+ try {
+ if (!input || !output) throw new Error('Embedder allocation failed');
+ fx.HEAPF32.set(pixels, input / 4);
+ if (fx._facex_embed(embedder, input, output) !== 0) throw new Error('Embedding failed');
+ return fx.HEAPF32.slice(output / 4, output / 4 + 512);
+ } finally {
+ fx._free(output);
+ fx._free(input);
}
+}
- _checkSimd() {
- try {
- return WebAssembly.validate(new Uint8Array([
- 0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,
- 253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11
- ]));
- } catch(e) { return false; }
+class FaceXSDK {
+ constructor(options = {}) {
+ this.detSize = options.detSize ?? 160;
+ if (!Number.isSafeInteger(this.detSize) || this.detSize < 32 || this.detSize % 32) {
+ throw new RangeError('detSize must be a positive multiple of 32');
+ }
+ this.threshold = options.threshold ?? 0.3;
+ this.detWeightsUrl = options.detWeightsUrl;
+ this.embWeightsUrl = options.embWeightsUrl;
+ this.wasmBaseUrl = options.wasmBaseUrl;
+ this.onProgress = options.onProgress;
+ this._engines = null;
+ this._loading = null;
+ this._source = document.createElement('canvas');
+ this._sourceCtx = this._source.getContext('2d', {willReadFrequently: true});
+ this._detCanvas = document.createElement('canvas');
+ this._detCanvas.width = this._detCanvas.height = this.detSize;
+ this._detCtx = this._detCanvas.getContext('2d', {willReadFrequently: true});
+ this._crop = document.createElement('canvas');
+ this._crop.width = this._crop.height = 112;
+ this._cropCtx = this._crop.getContext('2d');
}
- async _loadCached(url, key) {
- // Try IndexedDB cache
- try {
- const db = await new Promise((res, rej) => {
- const r = indexedDB.open('facex-cache', 1);
- r.onupgradeneeded = () => r.result.createObjectStore('weights');
- r.onsuccess = () => res(r.result);
- r.onerror = () => rej(r.error);
- });
- const cached = await new Promise(res => {
- const tx = db.transaction('weights', 'readonly');
- const req = tx.objectStore('weights').get(key);
- req.onsuccess = () => res(req.result);
- req.onerror = () => res(null);
- });
- if (cached) return new Uint8Array(cached);
-
- // Fetch and cache
- const buf = await fetch(url).then(r => r.arrayBuffer());
- const tx = db.transaction('weights', 'readwrite');
- tx.objectStore('weights').put(buf, key);
- return new Uint8Array(buf);
- } catch(e) {
- // Fallback: no cache
- return new Uint8Array(await fetch(url).then(r => r.arrayBuffer()));
+ get ready() { return !!this._engines; }
+
+ load() {
+ if (this.ready) return Promise.resolve(this);
+ if (!this._loading) {
+ this.onProgress?.('Loading engines and weights...');
+ this._loading = loadFaceXEngines(this).then(engines => {
+ this._engines = engines;
+ this.onProgress?.('Ready');
+ return this;
+ }).finally(() => { this._loading = null; });
}
+ return this._loading;
}
- _prepareDetInput(source) {
- // Draw source to srcCanvas at full res
- let w, h;
- if (source instanceof HTMLVideoElement) {
- w = source.videoWidth; h = source.videoHeight;
- } else if (source instanceof HTMLCanvasElement) {
- w = source.width; h = source.height;
- } else if (source instanceof HTMLImageElement) {
- w = source.naturalWidth; h = source.naturalHeight;
- } else {
- throw new Error('Source must be video, canvas, or image element');
+ async close() {
+ if (this._loading) await this._loading.catch(() => {});
+ if (this._engines) {
+ const {det, detector, fx, embedder} = this._engines;
+ det._detect_free(detector);
+ fx._facex_free(embedder);
+ this._engines = null;
}
+ }
- this._srcCanvas.width = w;
- this._srcCanvas.height = h;
- this._srcCtx.drawImage(source, 0, 0);
-
- // Letterbox to detSize
- const ds = this.detSize;
- this._detCanvas.width = ds;
- this._detCanvas.height = ds;
- const scale = Math.min(ds / w, ds / h);
- const nw = Math.round(w * scale), nh = Math.round(h * scale);
- const dx = (ds - nw) / 2, dy = (ds - nh) / 2;
+ detect(source) {
+ if (!this.ready) throw new Error('Load the SDK before detection');
+ const w = source.videoWidth ?? source.naturalWidth ?? source.width;
+ const h = source.videoHeight ?? source.naturalHeight ?? source.height;
+ if (!(w > 0 && h > 0)) throw new RangeError('Expected a nonempty frame');
+ if (this._source.width !== w) this._source.width = w;
+ if (this._source.height !== h) this._source.height = h;
+ this._sourceCtx.drawImage(source, 0, 0);
+ const size = this.detSize, scale = Math.min(size / w, size / h);
+ const nw = Math.max(1, Math.round(w * scale)), nh = Math.max(1, Math.round(h * scale));
+ const dx = Math.floor((size - nw) / 2), dy = Math.floor((size - nh) / 2);
this._detCtx.fillStyle = '#000';
- this._detCtx.fillRect(0, 0, ds, ds);
- this._detCtx.drawImage(source, dx, dy, nw, nh);
-
- const imgData = this._detCtx.getImageData(0, 0, ds, ds);
- const nPx = ds * ds;
- const pixels = new Float32Array(nPx * 3);
- for (let i = 0; i < nPx; i++) {
- pixels[i * 3] = imgData.data[i * 4] / 127.5 - 1.0;
- pixels[i * 3 + 1] = imgData.data[i * 4 + 1] / 127.5 - 1.0;
- pixels[i * 3 + 2] = imgData.data[i * 4 + 2] / 127.5 - 1.0;
+ this._detCtx.fillRect(0, 0, size, size);
+ this._detCtx.drawImage(this._source, dx, dy, nw, nh);
+ const rgba = this._detCtx.getImageData(0, 0, size, size).data;
+ const rgb = new Uint8Array(size * size * 3);
+ for (let i = 0, j = 0; i < rgba.length; i += 4) {
+ rgb[j++] = rgba[i]; rgb[j++] = rgba[i + 1]; rgb[j++] = rgba[i + 2];
}
- return { pixels, W: ds, H: ds, scale, dx, dy };
+ const x = v => Math.max(0, Math.min(w, (v - dx) * w / nw));
+ const y = v => Math.max(0, Math.min(h, (v - dy) * h / nh));
+ return facexDetectPixels(this._engines, rgb, size, size).map(f => ({
+ x1: x(f.x1), y1: y(f.y1), x2: x(f.x2), y2: y(f.y2), score: f.score,
+ kps: f.kps.map((v, i) => i % 2 ? y(v) : x(v)),
+ }));
}
- _runDetect(pixels, W, H) {
- const nPx = W * H * 3;
- const inPtr = this._det._malloc(nPx * 4);
- this._det.HEAPF32.set(pixels, inPtr >> 2);
+ embed(image) {
+ if (!this.ready) throw new Error('Load the SDK before embedding');
+ if (image.width !== 112 || image.height !== 112 || image.data.length !== 112 * 112 * 4)
+ throw new RangeError('Expected aligned 112 by 112 RGBA ImageData');
+ const pixels = new Float32Array(112 * 112 * 3);
+ for (let i = 0, j = 0; i < image.data.length; i += 4) {
+ pixels[j++] = image.data[i] / 127.5 - 1;
+ pixels[j++] = image.data[i + 1] / 127.5 - 1;
+ pixels[j++] = image.data[i + 2] / 127.5 - 1;
+ }
+ return facexEmbedPixels(this._engines, pixels);
+ }
- const maxFaces = 10;
- const outPtr = this._det._malloc(15 * 4 * maxFaces);
+ _frame() { return this._sourceCtx.getImageData(0, 0, this._source.width, this._source.height); }
- const df = this._det.cwrap('detect_faces', 'number',
- ['number', 'number', 'number', 'number', 'number', 'number']);
- const n = df(this._detHandle, inPtr, W, H, outPtr, maxFaces);
+ _align(frame, face, ctx) {
+ const align = facexCommonJS ? require('./align.js').alignFacePixels : alignFacePixels;
+ const points = [];
+ for (let i = 0; i < face.kps.length; i += 2) points.push(face.kps.slice(i, i + 2));
+ return align(frame, points, ctx);
+ }
- const faces = [];
- for (let i = 0; i < n; i++) {
- const base = (outPtr >> 2) + i * 15;
- const f = this._det.HEAPF32;
- faces.push({
- x1: f[base], y1: f[base+1], x2: f[base+2], y2: f[base+3],
- score: f[base+4],
- kps: Array.from(f.subarray(base + 5, base + 15))
- });
- }
+ process(source) {
+ const start = performance.now();
+ const faces = this.detect(source);
+ const frame = faces.length && this._frame();
+ const embeddings = faces.map(f => this.embed(this._align(frame, f, this._cropCtx)));
+ return {faces, embeddings, ms: performance.now() - start};
+ }
- this._det._free(inPtr);
- this._det._free(outPtr);
- return faces;
+ verify(source, reference) {
+ const start = performance.now();
+ const faces = this.detect(source);
+ if (!faces.length) return {faces, noFace: true, similarity: 0, match: false, ms: performance.now() - start};
+ const embedding = this.embed(this._align(this._frame(), faces[0], this._cropCtx));
+ const similarity = this.cosSim(embedding, reference);
+ return {faces, embedding, similarity, match: similarity > this.threshold, ms: performance.now() - start};
}
- _runEmbed(imageData) {
- const N = 112 * 112 * 3;
- const inPtr = this._fx._malloc(N * 4);
- const outPtr = this._fx._malloc(512 * 4);
+ captureReference(source) {
+ const [face] = this.detect(source);
+ if (!face) return null;
+ const alignedCanvas = document.createElement('canvas');
+ alignedCanvas.width = alignedCanvas.height = 112;
+ const image = this._align(this._frame(), face, alignedCanvas.getContext('2d'));
+ return {face, alignedCanvas, embedding: this.embed(image)};
+ }
- const heap = this._fx.HEAPF32;
- const base = inPtr >> 2;
- const px = imageData.data;
- for (let i = 0; i < 112 * 112; i++) {
- heap[base + i * 3] = px[i * 4] / 127.5 - 1.0;
- heap[base + i * 3 + 1] = px[i * 4 + 1] / 127.5 - 1.0;
- heap[base + i * 3 + 2] = px[i * 4 + 2] / 127.5 - 1.0;
+ cosSim(a, b) {
+ if (a.length !== 512 || b.length !== 512) throw new RangeError('Expected two 512 component embeddings');
+ let dot = 0, na = 0, nb = 0;
+ for (let i = 0; i < 512; i++) {
+ dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i];
}
-
- const fe = this._fx.cwrap('facex_embed', 'number', ['number', 'number', 'number']);
- fe(this._fxHandle, inPtr, outPtr);
-
- const emb = new Float32Array(512);
- emb.set(heap.subarray(outPtr >> 2, (outPtr >> 2) + 512));
-
- this._fx._free(inPtr);
- this._fx._free(outPtr);
- return emb;
+ if (!Number.isFinite(na) || !Number.isFinite(nb)) throw new RangeError('Nonfinite embedding');
+ return na && nb ? Math.max(-1, Math.min(1, dot / Math.sqrt(na * nb))) : 0;
}
}
+
+if (facexCommonJS) module.exports = {FaceXSDK};
diff --git a/wasm/index.d.ts b/wasm/index.d.ts
index 8d6ea23..1744209 100644
--- a/wasm/index.d.ts
+++ b/wasm/index.d.ts
@@ -1,6 +1,6 @@
/**
* facex-wasm — Face recognition in the browser.
- * 75 KB WASM. Detect, align, embed, verify.
+ * Detect, align, embed, verify.
* No server. No dependencies.
*/
@@ -12,6 +12,8 @@
export interface FaceXOptions {
/** Detection input size in pixels (default: 160) */
detSize?: number;
+ /** Directory containing detect.wasm and facex.wasm. */
+ wasmBaseUrl?: string;
/** Cosine similarity threshold for a positive match (default: 0.3) */
threshold?: number;
/** URL to detector weights file (default: 'yunet_fp32.bin') */
@@ -136,6 +138,7 @@ export declare class FaceXSDK {
* @returns The SDK instance for chaining.
*/
load(): Promise<FaceXSDK>;
+ close(): Promise<void>;
/**
* Detect faces in a video, image, or canvas element.
diff --git a/wasm/index.html b/wasm/index.html
index 2726cb6..ca4a78c 100644
--- a/wasm/index.html
+++ b/wasm/index.html
@@ -3,7 +3,8 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
-<title>FaceX — Face Recognition in Your Browser</title>
+<title>FaceX embedding demo</title>
+<meta name="description" content="Explore EdgeFace XS embeddings from a camera crop.">
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #0a0a0a; color: #e0e0e0; min-height: 100vh; }
@@ -68,7 +69,7 @@ canvas.hidden { display: none; }
<div class="header">
<h1>Face<span>X</span></h1>
- <p>Face recognition in your browser. No server. No upload. Everything stays on your device.</p>
+ <p>This demo embeds a 112 × 112 camera crop. <a href="demo.html">Open the detector and alignment demo</a> for automatic face alignment.</p>
</div>
<div id="status" class="status loading">Loading FaceX engine...</div>
@@ -130,7 +131,7 @@ async function init() {
try {
Module = await FaceXModule();
- facex_init = Module.cwrap('facex_init', 'number', ['string', 'string']);
+ facex_init = Module.cwrap('facex_init', 'number', ['string', 'string', 'string']);
facex_embed = Module.cwrap('facex_embed', 'number', ['number', 'number', 'number']);
facex_similarity = Module.cwrap('facex_similarity', 'number', ['number', 'number']);
facex_free = Module.cwrap('facex_free', null, ['number']);
@@ -166,7 +167,7 @@ async function loadWeights() {
Module.FS.writeFile('/weights.bin', data);
// Init engine
- fxHandle = facex_init('/weights.bin', null);
+ fxHandle = facex_init('/weights.bin', null, null);
if (!fxHandle) {
status.textContent = 'Error: failed to initialize engine';
status.className = 'status error';
diff --git a/wasm/index.js b/wasm/index.js
index 3220258..ffa64ba 100644
--- a/wasm/index.js
+++ b/wasm/index.js
@@ -1,38 +1,7 @@
-/**
- * facex-wasm — Face recognition in the browser.
- *
- * This is the npm package entry point. It re-exports the classes and
- * utilities defined in the individual script files.
- *
- * Usage (bundler / ESM):
- * import { FaceXSDK } from 'facex-wasm';
- * const fx = new FaceXSDK();
- * await fx.load();
- * const result = fx.process(videoElement);
- *
- * Usage (script tag):
- * <script src="node_modules/facex-wasm/detect.js"></script>
- * <script src="node_modules/facex-wasm/facex.js"></script>
- * <script src="node_modules/facex-wasm/align.js"></script>
- * <script src="node_modules/facex-wasm/facex-sdk.js"></script>
- * // FaceXSDK is now available as a global
- */
-
-// The SDK files define globals (FaceXSDK, LivenessDetector, etc.) when
-// loaded via <script> tags. For bundler consumers we provide this entry
-// point that pulls them together. Because the source files are plain
-// browser scripts (no module syntax), we need to reference the globals.
-
-if (typeof globalThis !== 'undefined') {
- // Make sure the exports object exists for CJS consumers
- if (typeof module !== 'undefined' && module.exports) {
- module.exports = {
- get FaceXSDK() { return globalThis.FaceXSDK; },
- get LivenessDetector() { return globalThis.LivenessDetector; },
- get checkWasmSimd() { return globalThis.checkWasmSimd; },
- get checkBrowserSupport() { return globalThis.checkBrowserSupport; },
- get alignFace() { return globalThis.alignFace; },
- get loadWeightsCached() { return globalThis.loadWeightsCached; },
- };
- }
-}
+/* Named exports work with CommonJS and ESM-aware bundlers. */
+exports.FaceXSDK = require('./facex-sdk.js').FaceXSDK;
+exports.LivenessDetector = require('./liveness.js').LivenessDetector;
+exports.checkWasmSimd = require('./simd_check.js').checkWasmSimd;
+exports.checkBrowserSupport = require('./simd_check.js').checkBrowserSupport;
+exports.alignFace = require('./align.js').alignFace;
+exports.loadWeightsCached = require('./cache.js').loadWeightsCached;
diff --git a/wasm/liveness.js b/wasm/liveness.js
index 003168b..b9f2cc5 100644
--- a/wasm/liveness.js
+++ b/wasm/liveness.js
@@ -138,3 +138,5 @@ class LivenessDetector {
return Math.sqrt(variance) / mean; // coefficient of variation
}
}
+
+if (typeof module !== 'undefined' && module.exports) module.exports = {LivenessDetector};
diff --git a/wasm/package.json b/wasm/package.json
index 81e2ffc..474ca41 100644
--- a/wasm/package.json
+++ b/wasm/package.json
@@ -1,7 +1,7 @@
{
"name": "facex-wasm",
"version": "0.1.0",
- "description": "Face recognition in the browser. 75 KB WASM. Detect, align, embed, verify — no server, no dependencies.",
+ "description": "Local face detection, alignment and EdgeFace recognition in WebAssembly.",
"main": "index.js",
"types": "index.d.ts",
"files": [
diff --git a/wasm/simd_check.js b/wasm/simd_check.js
index 43a8a65..4b88e62 100644
--- a/wasm/simd_check.js
+++ b/wasm/simd_check.js
@@ -11,7 +11,7 @@ function checkWasmSimd() {
0x01, 0x00, 0x00, 0x00, // version
0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7b, // type section: () -> v128
0x03, 0x02, 0x01, 0x00, // function section
- 0x0a, 0x0a, 0x01, 0x08, 0x00, 0xfd, 0x0c, // code section: v128.const
+ 0x0a, 0x16, 0x01, 0x14, 0x00, 0xfd, 0x0c, // code section: v128.const
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
@@ -32,8 +32,10 @@ function checkBrowserSupport() {
else if (!checkWasmSimd())
issues.push('WebAssembly SIMD not supported (Chrome 91+, Firefox 89+, Safari 16.4+ required)');
- if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia)
+ if (!globalThis.navigator?.mediaDevices?.getUserMedia)
issues.push('Camera API not available (HTTPS required)');
return issues;
}
+
+if (typeof module !== 'undefined' && module.exports) module.exports = {checkWasmSimd, checkBrowserSupport};
diff --git a/wasm/worker.js b/wasm/worker.js
index 3115118..3a41fad 100644
--- a/wasm/worker.js
+++ b/wasm/worker.js
@@ -8,88 +8,31 @@
* {type: 'embed', pixels: Float32Array} → returns embedding Float32Array
*/
-importScripts('detect.js', 'facex.js');
-
-let DetMod = null, FxMod = null;
-let detHandle = 0, fxHandle = 0;
-
-async function init() {
- DetMod = await FaceDetModule();
- FxMod = await FaceXModule();
-
- // Fetch weights
- const [detW, fxW] = await Promise.all([
- fetch('det_500m_int8.bin').then(r => r.arrayBuffer()),
- fetch('edgeface_xs_fp32.bin').then(r => r.arrayBuffer())
- ]);
-
- DetMod.FS.writeFile('/det.bin', new Uint8Array(detW));
- FxMod.FS.writeFile('/emb.bin', new Uint8Array(fxW));
-
- const di = DetMod.cwrap('detect_init', 'number', ['string']);
- detHandle = di('/det.bin');
-
- const fi = FxMod.cwrap('facex_init', 'number', ['string', 'string']);
- fxHandle = fi('/emb.bin', null);
-
- postMessage({ type: 'ready' });
-}
-
-function detect(pixels, W, H) {
- const nPx = W * H * 3;
- const inPtr = DetMod._malloc(nPx * 4);
- for (let i = 0; i < nPx; i++)
- DetMod.HEAPF32[(inPtr >> 2) + i] = pixels[i];
-
- const faceSize = 15 * 4;
- const maxFaces = 10;
- const outPtr = DetMod._malloc(faceSize * maxFaces);
-
- const df = DetMod.cwrap('detect_faces', 'number',
- ['number', 'number', 'number', 'number', 'number', 'number']);
- const nFaces = df(detHandle, inPtr, W, H, outPtr, maxFaces);
-
- const faces = [];
- for (let i = 0; i < nFaces; i++) {
- const base = (outPtr >> 2) + i * 15;
- faces.push({
- x1: DetMod.HEAPF32[base], y1: DetMod.HEAPF32[base+1],
- x2: DetMod.HEAPF32[base+2], y2: DetMod.HEAPF32[base+3],
- score: DetMod.HEAPF32[base+4],
- kps: Array.from(DetMod.HEAPF32.subarray(base+5, base+15))
- });
- }
-
- DetMod._free(inPtr);
- DetMod._free(outPtr);
- return faces;
+importScripts('detect.js', 'facex.js', 'cache.js', 'facex-sdk.js');
+let engines, loading;
+
+function detect(pixels, w, h) {
+ const rgb = pixels instanceof Float32Array
+ ? Uint8Array.from(pixels, x => Math.max(0, Math.min(255, Math.round((x + 1) * 127.5))))
+ : pixels;
+ return facexDetectPixels(engines, rgb, w, h);
}
-function embed(pixels) {
- const N = 112 * 112 * 3;
- const inPtr = FxMod._malloc(N * 4);
- const outPtr = FxMod._malloc(512 * 4);
-
- for (let i = 0; i < N; i++)
- FxMod.HEAPF32[(inPtr >> 2) + i] = pixels[i];
-
- const fe = FxMod.cwrap('facex_embed', 'number', ['number', 'number', 'number']);
- fe(fxHandle, inPtr, outPtr);
-
- const emb = new Float32Array(512);
- emb.set(FxMod.HEAPF32.subarray(outPtr >> 2, (outPtr >> 2) + 512));
-
- FxMod._free(inPtr);
- FxMod._free(outPtr);
- return emb;
-}
+function embed(pixels) { return facexEmbedPixels(engines, pixels); }
onmessage = async function(e) {
const msg = e.data;
- switch (msg.type) {
- case 'init':
- await init();
- break;
+ try {
+ if (msg.type === 'init') {
+ loading ??= loadFaceXEngines(msg).then(result => { engines = result; })
+ .catch(error => { loading = null; throw error; });
+ await loading;
+ postMessage({type: 'ready'});
+ return;
+ }
+ if (!loading) throw new Error('Initialize the worker first');
+ await loading;
+ switch (msg.type) {
case 'detect':
const faces = detect(msg.pixels, msg.W, msg.H);
postMessage({ type: 'detect', faces });
@@ -111,5 +54,8 @@ onmessage = async function(e) {
postMessage({ type: 'pipeline', faces: f, emb, detMs, embMs }, emb ? [emb.buffer] : []);
break;
}
+ }
+ } catch (error) {
+ postMessage({type: 'error', message: error.message});
}
};