Nimbin[12]?Linux & System / webcam-loopback-manipulation-screensharing-and-stuff / commits / 778574b

webcam-loopback-manipulation-screensharing-and-stuff git · main

vcam: v4l2 loopback with overlays, filters, OpenCV and RVM matting

webcam v4l2 opencv onnx c · first commit 2026-06-29 · last commit 2026-11-12 (11 days ago) · synced 1 hour ago · upstream: github.com/nimbin2/Webcam-Filter---ScreenSharing---and-Stuff

C 51.3% C++ 40.7% Markdown 6.9% Makefile 1%
git clone https://git.christianimmanuel.de/linux-system/webcam-loopback-manipulation-screensharing-and-stuff.gitwget https://git.christianimmanuel.de/linux-system/webcam-loopback-manipulation-screensharing-and-stuff/archive/webcam-loopback-manipulation-screensharing-and-stuff.tar.gz

Better personfx Something with Onyx or so

Christian Immanuel · 2026-07-09 05:32 · 778574bec63b572a799602ccb954c11d2e3a25a0

 .built-opencv-1-ort-1 |   1 +
 .gitignore            |   1 -
 INSTALL.md            |  22 ++
 Makefile              |  63 +++++-
 NOTICE                |  16 ++
 README.md             |   6 +-
 include/vcam_ort.h    |  74 +++++++
 scripts/vcam-ctl      |  47 +++++
 scripts/vcam-setup    |  84 ++++++++
 src/ipc.c             |  17 +-
 src/opencv_fx.cpp     | 560 ++++++++++++++++++++++++++++++++++++++++++++++----
 src/ort_rvm.c         | 292 ++++++++++++++++++++++++++
 12 files changed, 1130 insertions(+), 53 deletions(-)

diff --git a/.built-opencv-1-ort-1 b/.built-opencv-1-ort-1
new file mode 100644
index 0000000..fd39866
--- /dev/null
+++ b/.built-opencv-1-ort-1
@@ -0,0 +1 @@
+/home/n76310/.local/share/vcam/onnxruntime
diff --git a/.gitignore b/.gitignore
index 998000d..efa7302 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,7 +6,6 @@
 *.so.*
 vcam
 test_screen
-.built-opencv-1
 
 # Distribution archives
 *.tar.gz
diff --git a/INSTALL.md b/INSTALL.md
index 4a041c7..c138619 100644
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -126,6 +126,28 @@ decides which code path is compiled. If nothing is found, `make
 OPENCV=1` stops with a clear message; you can force a name with
 `OPENCV_PC=<name>`.
 
+### Best matting quality: the ONNX Runtime backend
+
+OpenCV 5's new DNN engine *loads* the RVM video-matting model but
+currently **miscomputes** it (verified: empty mattes). ONNX Runtime is
+RVM's reference runtime and computes it correctly. Enabling it gives
+`personfx` its best-quality engine — temporally stable, hair-level
+mattes:
+
+```bash
+vcam-setup --ort              # fetch onnxruntime (MIT, ~60 MB, one-time)
+vcam-setup --models-rvm       # fetch the RVM model if you haven't
+make OPENCV=1 ORT=1
+sudo make install             # the build remembers ORT=1 afterwards
+pkill vcam; vcam &
+vcam-ctl opencv               # should report the ONNX Runtime backend
+```
+
+vcam picks matting engines in order: ONNX-Runtime RVM → OpenCV-DNN RVM
+(auto-disabled if it produces empty mattes) → PP-HumanSeg. Every step
+falls back automatically, so a missing library or model never breaks
+the filter. `ORT_HOME=<dir>` overrides the library location.
+
 ### Model files (for `facefx` and `personfx`)
 
 The five classic OpenCV filters work immediately. The two DNN-based ones
diff --git a/Makefile b/Makefile
index 643feef..c2edb9d 100644
--- a/Makefile
+++ b/Makefile
@@ -45,12 +45,29 @@ LDFLAGS := $(shell pkg-config --libs libavcodec libavformat libavutil libswscale
 #   sudo make install        <- installs the OpenCV flavor, as intended
 # just works. An explicit OPENCV=0/1 on the command line always wins,
 # and 'make clean' resets the memory.
-LAST_OPENCV := $(patsubst .built-opencv-%,%,$(firstword $(wildcard .built-opencv-*)))
+LAST_STAMP  := $(firstword $(wildcard .built-opencv-*))
+# stamp form: .built-opencv-<0|1>-ort-<0|1> ; split on '-' ->
+#   word1=".built" word2="opencv" word3=<0|1> word4="ort" word5=<0|1>
+LAST_OPENCV := $(word 3,$(subst -, ,$(LAST_STAMP)))
+LAST_ORT    := $(word 5,$(subst -, ,$(LAST_STAMP)))
 ifeq ($(strip $(LAST_OPENCV)),)
     OPENCV ?= 0
 else
     OPENCV ?= $(LAST_OPENCV)
 endif
+ifeq ($(strip $(LAST_ORT)),)
+    ORT ?= 0
+else
+    ORT ?= $(LAST_ORT)
+endif
+# the stamp file's CONTENT stores the ORT_HOME used, so plain
+# 'sudo make install' after 'make OPENCV=1 ORT=1 ORT_HOME=…' just works
+ifneq ($(strip $(LAST_STAMP)),)
+    LAST_ORT_HOME := $(strip $(shell cat $(LAST_STAMP) 2>/dev/null))
+    ifneq ($(strip $(LAST_ORT_HOME)),)
+        ORT_HOME ?= $(LAST_ORT_HOME)
+    endif
+endif
 
 ifeq ($(OPENCV),1)
     # Let the user force a specific pkg-config module name if they want.
@@ -89,6 +106,34 @@ else
     CFLAGS   += -DVCAM_HAVE_OPENCV=0
 endif
 
+# ── Optional ONNX Runtime backend (ORT=1) ──────────────────────────
+# Runs the RVM video-matting model CORRECTLY (OpenCV 5's young graph
+# engine loads it but miscomputes it — verified). Opt-in:
+#
+#   vcam-setup --ort            # one-time: fetch onnxruntime to
+#                               #   ~/.local/share/vcam/onnxruntime
+#   make OPENCV=1 ORT=1         # build with the backend
+#
+# ORT_HOME points at a directory containing include/onnxruntime_c_api.h
+# and lib/libonnxruntime.so; override it for a custom install:
+#   make OPENCV=1 ORT=1 ORT_HOME=/opt/onnxruntime
+ifeq ($(ORT),1)
+    ifneq ($(OPENCV),1)
+        $(error ORT=1 requires OPENCV=1 (the matting pipeline lives in the OpenCV shim))
+    endif
+    ORT_HOME ?= $(HOME)/.local/share/vcam/onnxruntime
+    ifeq ($(wildcard $(ORT_HOME)/include/onnxruntime_c_api.h),)
+        ifeq ($(filter clean uninstall,$(MAKECMDGOALS)),)
+            $(error ORT=1 but $(ORT_HOME)/include/onnxruntime_c_api.h not found. Run 'vcam-setup --ort' first, or set ORT_HOME=<dir>)
+        endif
+    endif
+    CFLAGS  += -DVCAM_HAVE_ORT=1 -isystem $(ORT_HOME)/include
+    LDFLAGS += -L$(ORT_HOME)/lib -lonnxruntime -Wl,-rpath,$(ORT_HOME)/lib
+    $(info vcam: ONNX Runtime backend enabled — $(ORT_HOME))
+else
+    CFLAGS  += -DVCAM_HAVE_ORT=0
+endif
+
 # ── Install paths (overridable) ─────────────────────────────────────
 #   make install                       (default: /usr/local)
 #   make install PREFIX=$HOME/.local   (user-local)
@@ -100,7 +145,7 @@ DATADIR ?= $(PREFIX)/share/vcam
 
 SRCS := src/main.c src/frame.c src/capture.c src/output.c \
         src/overlay.c src/registry.c src/ipc.c src/filter.c \
-        src/record.c
+        src/record.c src/ort_rvm.c
 OBJS := $(SRCS:.c=.o) $(CV_OBJ)
 BIN  := vcam
 TEST := test_screen
@@ -113,7 +158,7 @@ TEST := test_screen
 # 'make install' after 'make OPENCV=1' fail-safe: without the stamp,
 # plain 'make install' (OPENCV defaulting to 0) would silently relink
 # and install the stub flavor over your OpenCV build.
-CONFIG_STAMP := .built-opencv-$(OPENCV)
+CONFIG_STAMP := .built-opencv-$(OPENCV)-ort-$(ORT)
 
 .PHONY: all clean install uninstall
 
@@ -121,12 +166,20 @@ all: $(BIN) $(TEST)
 
 $(CONFIG_STAMP):
 	@rm -f .built-opencv-*
+ifeq ($(ORT),1)
+	@printf '%s\n' '$(ORT_HOME)' > $@
+else
 	@touch $@
+endif
 
 $(BIN): $(OBJS) $(CONFIG_STAMP)
 	$(LINK) -o $@ $(OBJS) $(LDFLAGS)
 ifeq ($(OPENCV),1)
+ifeq ($(ORT),1)
+	@echo "vcam: linked WITH OpenCV filters ($(OPENCV_PC) $(CV_VER)) + ONNX Runtime backend"
+else
 	@echo "vcam: linked WITH OpenCV filters ($(OPENCV_PC) $(CV_VER))"
+endif
 else
 	@echo "vcam: linked WITHOUT OpenCV filters (build with 'make OPENCV=1' to enable)"
 endif
@@ -145,7 +198,11 @@ src/opencv_fx.o: src/opencv_fx.cpp include/vcam_cv.h
 
 install: $(BIN)
 ifeq ($(OPENCV),1)
+ifeq ($(ORT),1)
+	@echo "Installing vcam WITH OpenCV filters ($(OPENCV_PC) $(CV_VER)) + ONNX Runtime backend."
+else
 	@echo "Installing vcam WITH OpenCV filters ($(OPENCV_PC) $(CV_VER))."
+endif
 else
 	@echo "Installing vcam WITHOUT OpenCV filters."
 	@echo "  (If you built with 'make OPENCV=1', install with 'sudo make install OPENCV=1'"
diff --git a/NOTICE b/NOTICE
index 3ac0a3a..250dc4c 100644
--- a/NOTICE
+++ b/NOTICE
@@ -65,6 +65,16 @@ restrictions on vcam's own source.
       is not part of vcam's source or binary.
 
 
+Optional ONNX Runtime backend
+=============================
+
+  ONNX Runtime (linked when built with ORT=1; default build does not)
+      Licensed under the MIT License. An optional, separately-installed
+      inference runtime ('vcam-setup --ort') used to run the RVM matting
+      model correctly. Not bundled or redistributed with vcam.
+      https://onnxruntime.ai
+
+
 Optional OpenCV components
 ==========================
 
@@ -108,6 +118,12 @@ build does not link or depend on any of them.
       Model Zoo mirror (huggingface.co/onnxmodelzoo); not bundled.
       Originals from pytorch/examples fast_neural_style.
 
+  RVM — Robust Video Matting (rvm_mobilenetv3_fp32.onnx)
+      Licensed under the GPL-3.0 license. Downloaded on request by
+      'vcam-setup --models-rvm' from the official GitHub release
+      (PeterL1n/RobustVideoMatting); not bundled with vcam. Used as an
+      optional higher-quality matting engine for the personfx filter.
+
   None of the model files above are distributed with vcam; each is fetched by the
   user from its upstream source and retains its own license above.
 
diff --git a/README.md b/README.md
index 9309bc6..cb296a3 100644
--- a/README.md
+++ b/README.md
@@ -432,10 +432,10 @@ and fetch the (free, tiny) model files.
 | `cvstylize`   | strength | watercolor / poster stylization (edge-aware) | no |
 | `opticalflow` | mix | dense Farnebäck optical flow — motion becomes flowing color (direction = hue, speed = brightness) | no |
 | `bgsub`       | sensitivity | MOG2 background subtraction: whatever moves stays vivid, the learned static background dims and desaturates | no |
-| `facefx`      | mode | YuNet face detection — 0 privacy-pixelate, 1 glossy ring + landmark dots, 2 googly eyes, 3 **bighead**, 4 **deal-with-it sunglasses**, 5 **laser eyes**, 6 **bobblehead** (rhythmically wobble-inflating head), 7 **third eye** (your own eye cloned onto your forehead), 8 **crown** (tracked golden crown with jewels) | **yes** |
-| `personfx`    | mode | PP-HumanSeg person segmentation, soft-alpha matte, per-frame + temporally smoothed — 0 = blur background, 1 = spotlight, 2 = moving gradient, 3 = **your own image** (`vcam-ctl filter bgimage /path/pic.jpg`), 4 = **invisibility cloak**, 5 = **neon person**, 6 = **clone army**, 7 = **window-3D**, 8 = **chrono clones**, 9 = **tiny you** (shrunk to 45%, standing in the learned room), 10 = **hologram you** (only your body becomes a flickering cyan scanline projection; the room stays real) | **yes** |
+| `facefx`      | mode | YuNet face detection — 0 privacy-pixelate, 1 glossy ring + landmark dots, 2 googly eyes, 3 **bighead**, 4 **deal-with-it sunglasses**, 5 **laser eyes**, 6 **bobblehead**, 7 **third eye**, 8 **crown**, 9 **mirror face**, 10 **cyclops**, 11 **heart eyes**, 12 **interrogation spotlight**, 13 **target lock** (rotating sci-fi HUD reticle) | **yes** |
+| `personfx`    | mode | person matting, best engine wins: **RVM on ONNX Runtime** (`vcam-setup --ort` + `--models-rvm`, build `ORT=1` — correct, temporally-stable, hair-level mattes) → RVM on OpenCV-DNN (auto-disabled when the engine miscomputes it) → PP-HumanSeg — 0 = blur background, 1 = spotlight, 2 = moving gradient, 3 = **your own image** (`vcam-ctl filter bgimage /path/pic.jpg`), 4 = **invisibility cloak**, 5 = **neon person**, 6 = **clone army**, 7 = **window-3D**, 8 = **chrono clones**, 9 = **tiny you**, 10 = **hologram you**, 11 = **rainbow aura** (hue-cycling glow rings around your body), 12 = **painted world** (neural style transfers the *background* while you stay photographic), 13 = **body pixelate** (privacy for everything but the room), 14 = **gravity flip**, 15 = **motion echo** (a decaying cyan comet-trail of your past poses sheds behind you as you move), 16 = **double exposure** (the classic portrait look — the learned room shows *through* your silhouette, edges inked dark) | **yes** |
 | `styleai`     | style, blend, size | **live neural style transfer** — your webcam through actual neural nets: 0 mosaic, 1 candy, 2 rain-princess, 3 udnie, 4 pointilism. `blend` mixes with the original; `size` (96–384) is the quality↔speed dial | **yes** (`--models-style`) |
-| `moodfx`      | mode, gain | **emotion-reactive**: an expression model reads your face (7 emotions, ~2 ms) and the effect responds — 0 aura, 1 HUD label, 2 party (happy→confetti, sad→rain, surprised→flash, angry→screen-shake), 3 **emoji face**, 4 **paintmood** — two neural nets chained: the emotion model *selects the neural style* live (happy→candy, sad→rain-princess, angry→mosaic, surprised→pointillism) and your confidence drives the blend; needs the `--models-style` pack | **yes** |
+| `moodfx`      | mode, gain | **emotion-reactive**: an expression model reads your face (7 emotions, ~2 ms) and the effect responds — 0 aura, 1 HUD label, 2 party (happy→confetti, sad→rain, surprised→flash, angry→screen-shake), 3 **emoji face**, 4 **paintmood**, 5 **auto-grade** (cinematic color grade steered live by your emotion), — paintmood: two neural nets chained: the emotion model *selects the neural style* live (happy→candy, sad→rain-princess, angry→mosaic, surprised→pointillism) and your confidence drives the blend; needs the `--models-style` pack | **yes** |
 | `speedlines`  | sens, density | **anime speed lines**: mean optical flow past a threshold fires white motion streaks from the border opposite your movement — dodge left, lines fly right | no |
 | `paintflow`   | strength, decay | **motion paints**: dense optical flow drags a persistent canvas — wave and you smear reality like wet paint; hold still and it sharpens back | no |
 
diff --git a/include/vcam_ort.h b/include/vcam_ort.h
new file mode 100644
index 0000000..f861b43
--- /dev/null
+++ b/include/vcam_ort.h
@@ -0,0 +1,74 @@
+/* SPDX-License-Identifier: GPL-2.0-only
+ * vcam — Linux virtual webcam pipeline
+ * Copyright (C) 2026 the vcam authors
+ *
+ * This program is free software under the terms of the GNU General
+ * Public License version 2. See the LICENSE file for the full text.
+ */
+
+/*
+ * vcam_ort.h — C ABI for the optional ONNX Runtime backend.
+ *
+ * Why this exists: OpenCV 5's new DNN graph engine LOADS the RVM video
+ * matting model but miscomputes it (empty mattes — verified on a real
+ * OpenCV 5.1 install). ONNX Runtime is the reference runtime RVM was
+ * built and tested on; through it the model computes correctly.
+ *
+ * The backend is opt-in at build time:
+ *
+ *     vcam-setup --ort                # one-time: fetch onnxruntime
+ *     make OPENCV=1 ORT=1            # build with the backend
+ *
+ * When built without ORT=1 (the default), src/ort_rvm.c compiles its
+ * stub half: ort_available() returns false and everything else no-ops,
+ * so callers can invoke these unconditionally. The OpenCV shim tries
+ * this backend first for RVM and falls back to its own paths when it
+ * isn't present or fails.
+ *
+ * Threading: calls are serialized by the caller (the segmentation lock
+ * in the OpenCV shim); an internal mutex additionally guards state so
+ * misuse degrades safely rather than corrupting memory.
+ */
+
+#ifndef VCAM_ORT_H
+#define VCAM_ORT_H
+
+#include <stdbool.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* True when vcam was built with ORT=1 and libonnxruntime loaded. */
+bool ort_available(void);
+
+/* ONNX Runtime version string ("1.27.0"), or "not built in". Never NULL. */
+const char *ort_version(void);
+
+/* Load the RVM model from the given .onnx path and prepare a session.
+ * Verifies the model exposes the RVM interface (src, r1i..r4i,
+ * downsample_ratio -> fgr, pha, r1o..r4o); anything else is rejected.
+ * Returns 1 on success, 0 on failure (a one-time reason is printed).
+ * Safe to call again after failure or with a different path. */
+int ort_rvm_init(const char *model_path);
+
+/* Run one frame of RVM.
+ *   src_chw : float32 RGB, values 0..1, planar CHW (3 * ih * iw floats)
+ *   iw, ih  : the frame's width/height (any size; /16-aligned is best)
+ *   pha_out : caller buffer for the alpha matte, ih*iw floats, 0..1
+ * The recurrent state is carried between calls internally (that's what
+ * makes RVM temporally stable) and re-initialized automatically if the
+ * frame size changes. Returns 1 on success, 0 on failure. */
+int ort_rvm_infer(const float *src_chw, int iw, int ih, float *pha_out);
+
+/* Zero the recurrent state (e.g. on a scene cut). Cheap; optional. */
+void ort_rvm_reset(void);
+
+/* Release the session and all state. Safe in every build. */
+void ort_shutdown(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* VCAM_ORT_H */
diff --git a/scripts/vcam-ctl b/scripts/vcam-ctl
index 04dbc6b..16501ce 100755
--- a/scripts/vcam-ctl
+++ b/scripts/vcam-ctl
@@ -99,6 +99,53 @@
 
 SOCK="${VCAM_SOCK:-/tmp/vcam.sock}"
 
+# ── ai "<text>": tell vcam what you want in plain words ─────
+# Deterministic keyword router (local, no cloud). Examples:
+#   vcam-ctl ai "make me invisible"     vcam-ctl ai "hologram with laser eyes"
+#   vcam-ctl ai "blur my background"    vcam-ctl ai "reset"
+if [ "${1:-}" = "ai" ]; then
+    shift
+    T=$(printf '%s' "$*" | tr '[:upper:]' '[:lower:]')
+    [ -z "$T" ] && { echo "usage: vcam-ctl ai \"what you want\""; exit 1; }
+    ADDED=0
+    say() { printf '  + %s\n' "$1"; }
+    fadd() { "$0" filter add $1 >/dev/null 2>&1 && { say "$2"; ADDED=$((ADDED+1)); }; }
+    case "$T" in *reset*|*normal*|*clear*) "$0" filter clear >/dev/null 2>&1; echo "  cleared all filters"; exit 0;; esac
+    case "$T" in *invisib*|*disappear*|*vanish*) fadd "personfx 4" "invisibility cloak";; esac
+    case "$T" in *hologram*) fadd "personfx 10" "hologram you";; esac
+    case "$T" in *laser*) fadd "facefx 5" "laser eyes";; esac
+    case "$T" in *blur*back*|*back*blur*|*portrait*) fadd "personfx 0" "background blur";; esac
+    case "$T" in *clone*|*army*) fadd "personfx 6" "clone army";; esac
+    case "$T" in *tiny*|*shrink*) fadd "personfx 9" "tiny you";; esac
+    case "$T" in *upside*|*flip*|*gravity*) fadd "personfx 14" "gravity flip";; esac
+    case "$T" in *3d*|*window*|*parallax*) fadd "personfx 7" "window-3D";; esac
+    case "$T" in *ghost*|*trail*|*echo*) fadd "personfx 15" "motion echo";; esac
+    case "$T" in *crown*|*king*|*queen*) fadd "facefx 8" "crown";; esac
+    case "$T" in *sunglass*|*shades*) fadd "facefx 4" "sunglasses";; esac
+    case "$T" in *googly*) fadd "facefx 2" "googly eyes";; esac
+    case "$T" in *bighead*|*bobble*) fadd "facefx 6" "bobblehead";; esac
+    case "$T" in *cyclop*) fadd "facefx 10" "cyclops";; esac
+    case "$T" in *heart*) fadd "facefx 11" "heart eyes";; esac
+    case "$T" in *anonym*|*privacy*) fadd "facefx 0" "face pixelate";; esac
+    case "$T" in *confetti*|*smile*|*party*) fadd "moodfx 2" "emotion party";; esac
+    case "$T" in *emoji*) fadd "moodfx 3" "emoji face";; esac
+    case "$T" in *red*|*warm*) fadd "duotone 0.8" "red-warm duotone";; esac
+    case "$T" in *paint*|*style*|*art*) fadd "styleai 1 0.85" "neural style (candy)";; esac
+    case "$T" in *mosaic*) fadd "styleai 0 0.85" "neural style (mosaic)";; esac
+    case "$T" in *smear*|*liquid*) fadd "paintflow 1.5" "paint smear";; esac
+    case "$T" in *anime*|*speed*) fadd "speedlines 1.5" "anime lines";; esac
+    case "$T" in *cartoon*) fadd "cvcartoon 0.7" "cartoon";; esac
+    case "$T" in *sketch*|*pencil*) fadd "cvpencil 1" "pencil sketch";; esac
+    if [ "$ADDED" -eq 0 ]; then
+        echo "  didn't recognize an effect. Try: invisible, hologram, laser,"
+        echo "  blur background, clones, tiny, crown, confetti, painting,"
+        echo "  cartoon, anime, red, reset"
+        exit 1
+    fi
+    exit 0
+fi
+
+
 show_help() { sed -n '/^# vcam-ctl/,/^$/p' "$0" | sed 's/^# \?//'; }
 
 # ── basic usage / help ───────────────────────────────────────
diff --git a/scripts/vcam-setup b/scripts/vcam-setup
index 77fc64d..0c3fa9c 100755
--- a/scripts/vcam-setup
+++ b/scripts/vcam-setup
@@ -27,6 +27,8 @@ if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
     echo "  sudo vcam-setup --uninstall  remove it"
     echo "  vcam-setup --models          download the OpenCV model files (face/person/emotion)"
     echo "  vcam-setup --models-style    download the 5 neural style transfer models"
+    echo "  vcam-setup --models-rvm      download RVM video matting (best personfx quality)"
+    echo "  vcam-setup --ort             download ONNX Runtime (runs RVM correctly)"
     exit 0
 fi
 
@@ -94,6 +96,88 @@ if [ "${1:-}" = "--models" ]; then
     exit "$rc"
 fi
 
+# ── ONNX Runtime: the backend that runs RVM correctly ────────
+# OpenCV 5's young DNN graph engine loads RVM but miscomputes it
+# (empty mattes). ONNX Runtime is RVM's reference runtime. This
+# fetches the official prebuilt library (MIT license, ~60 MB) into
+# ~/.local/share/vcam/onnxruntime, then vcam is rebuilt with ORT=1.
+if [ "${1:-}" = "--ort" ]; then
+    ORT_VER="${VCAM_ORT_VERSION:-1.27.0}"
+    ORT_DIR="${VCAM_ORT_DIR:-$HOME/.local/share/vcam/onnxruntime}"
+    F="onnxruntime-linux-x64-$ORT_VER.tgz"
+    U="https://github.com/microsoft/onnxruntime/releases/download/v$ORT_VER/$F"
+    if [ -e "$ORT_DIR/include/onnxruntime_c_api.h" ]; then
+        echo "already installed: $ORT_DIR"
+        echo "build with:  make OPENCV=1 ORT=1 && sudo make install"
+        exit 0
+    fi
+    if command -v curl >/dev/null 2>&1; then DL="curl -fL --retry 3 -o";
+    elif command -v wget >/dev/null 2>&1; then DL="wget -O";
+    else echo "Error: need curl or wget." >&2; exit 1; fi
+    TMP="${TMPDIR:-/tmp}/vcam-ort.$$"
+    mkdir -p "$TMP" "$ORT_DIR" || { echo "Error: cannot create dirs" >&2; exit 1; }
+    echo "downloading ONNX Runtime $ORT_VER (~60 MB) ..."
+    # shellcheck disable=SC2086
+    if $DL "$TMP/$F" "$U" && [ -s "$TMP/$F" ]; then
+        tar -xzf "$TMP/$F" -C "$ORT_DIR" --strip-components=1
+        rm -rf "$TMP"
+        if [ -e "$ORT_DIR/include/onnxruntime_c_api.h" ]; then
+            echo "ok: $ORT_DIR"
+            echo ""
+            echo "Now rebuild vcam with the backend:"
+            echo "    make OPENCV=1 ORT=1 && sudo make install"
+            echo "    pkill vcam; vcam &"
+            echo "(and make sure the RVM model is there: vcam-setup --models-rvm)"
+        else
+            echo "extraction looks wrong — check $ORT_DIR" >&2; exit 1
+        fi
+    else
+        rm -rf "$TMP"
+        echo "FAILED to download. Manual route:" >&2
+        echo "  1. fetch $U" >&2
+        echo "  2. tar -xzf $F --strip-components=1 -C $ORT_DIR" >&2
+        exit 1
+    fi
+    exit 0
+fi
+
+# ── RVM: Robust Video Matting (recommended personfx upgrade) ─
+# A recurrent video-native matting network: temporally stable, hair-
+# level alpha. GPL-3.0 licensed weights, fetched from the official
+# GitHub release; ~15 MB. vcam uses it automatically when present and
+# falls back to PP-HumanSeg when not (or if this OpenCV can't load it).
+if [ "${1:-}" = "--models-rvm" ]; then
+    if [ "${2:-}" = "--system" ]; then
+        MODEL_DIR="${VCAM_MODEL_DIR:-/usr/local/share/vcam/models}"
+    else
+        MODEL_DIR="${VCAM_MODEL_DIR:-$HOME/.local/share/vcam/models}"
+    fi
+    if command -v curl >/dev/null 2>&1; then DL="curl -fL --retry 3 -o";
+    elif command -v wget >/dev/null 2>&1; then DL="wget -O";
+    else echo "Error: need curl or wget." >&2; exit 1; fi
+    mkdir -p "$MODEL_DIR" || { echo "Error: cannot create $MODEL_DIR" >&2; exit 1; }
+    F="rvm_mobilenetv3_fp32.onnx"
+    U="https://github.com/PeterL1n/RobustVideoMatting/releases/download/v1.0.0/$F"
+    if [ -s "$MODEL_DIR/$F" ]; then
+        echo "already have $F"
+        exit 0
+    fi
+    echo "downloading $F (~15 MB) ..."
+    # shellcheck disable=SC2086
+    if $DL "$MODEL_DIR/$F.part" "$U" && [ -s "$MODEL_DIR/$F.part" ]; then
+        mv "$MODEL_DIR/$F.part" "$MODEL_DIR/$F"
+        echo "ok: $MODEL_DIR/$F"
+        echo "Restart vcam; personfx will pick it up automatically."
+        echo "(If your OpenCV can't run it, vcam prints a note and falls back.)"
+    else
+        rm -f "$MODEL_DIR/$F.part"
+        echo "FAILED — check your network, or download manually from:" >&2
+        echo "  $U" >&2
+        exit 1
+    fi
+    exit 0
+fi
+
 # ── Neural style transfer models ─────────────────────────────
 # Fetches the five fast-neural-style networks (Johnson et al.) used by
 # the 'styleai' filter. MIT-licensed ONNX exports, ~6.5 MB each, from
diff --git a/src/ipc.c b/src/ipc.c
index 19b99e4..4e0df68 100644
--- a/src/ipc.c
+++ b/src/ipc.c
@@ -26,6 +26,7 @@
 
 #include "vcam.h"
 #include "vcam_cv.h"
+#include "vcam_ort.h"
 
 #include <stdio.h>
 #include <stdlib.h>
@@ -317,12 +318,13 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
             send_line(client_fd, "OK   styleai <style> [<blend> <size>] LIVE NEURAL STYLE TRANSFER: 0=mosaic 1=candy 2=rain-princess 3=udnie 4=pointilism");
             send_line(client_fd, "OK                                    blend 0..1 mixes with original; size 96..384 = quality vs speed");
             send_line(client_fd, "OK   moodfx <mode> [<gain>]         EMOTION-REACTIVE: model reads your expression, effect responds");
-            send_line(client_fd, "OK                                    0=aura 1=HUD 2=party 3=EMOJI face 4=PAINTMOOD (emotion picks the neural style!)");
+            send_line(client_fd, "OK                                    0=aura 1=HUD 2=party 3=EMOJI 4=PAINTMOOD 5=AUTO-GRADE (cinematic grade by emotion)");
             send_line(client_fd, "OK   paintflow <strength> [<decay>] motion smears reality like wet paint (dense optical flow)");
             send_line(client_fd, "OK   facefx extra modes: 3=BIGHEAD (inflated tracked head) 4=deal-with-it sunglasses");
             send_line(client_fd, "OK   personfx extra modes: 6=CLONE ARMY 7=WINDOW-3D (head-coupled parallax) 8=CHRONO CLONES (past-selves trail)");
-            send_line(client_fd, "OK   facefx extra modes: 5=LASER EYES 6=BOBBLEHEAD 7=THIRD EYE 8=CROWN");
-            send_line(client_fd, "OK   personfx extra modes: 9=TINY YOU (desk gnome) 10=HOLOGRAM YOU (cyan flicker projection)");
+            send_line(client_fd, "OK   facefx extra modes: 5=LASERS 6=BOBBLE 7=3RD-EYE 8=CROWN 9=MIRROR 10=CYCLOPS 11=HEART-EYES 12=INTERROGATE 13=TARGET-LOCK");
+            send_line(client_fd, "OK   personfx extra modes: 9=TINY 10=HOLOGRAM 11=RAINBOW-AURA 12=PAINTED-WORLD 13=BODY-PIXELATE 14=GRAVITY-FLIP");
+            send_line(client_fd, "OK                                    15=MOTION-ECHO (comet trail of past poses) 16=DOUBLE-EXPOSURE (room shows through you)");
             send_line(client_fd, "OK   speedlines <sens> [<density>] anime motion lines streak in when you move fast");
             send_line(client_fd, "OK   filter bgimage <path|off>      set the background image for personfx mode 3");
             send_line(client_fd, "OK   (face/person models: run 'vcam-setup --models' to download)");
@@ -624,6 +626,15 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
             snprintf(buf, sizeof buf, "OK model dir: %s", cv_model_dir());
             send_line(client_fd, buf);
         }
+        if (ort_available()) {
+            snprintf(buf, sizeof buf,
+                     "OK ONNX Runtime backend: v%s (RVM matting runs here)",
+                     ort_version());
+            send_line(client_fd, buf);
+        } else {
+            send_line(client_fd, "OK ONNX Runtime backend: not built in "
+                      "(vcam-setup --ort, then make OPENCV=1 ORT=1)");
+        }
         return;
     }
 
diff --git a/src/opencv_fx.cpp b/src/opencv_fx.cpp
index 371a377..775aec2 100644
--- a/src/opencv_fx.cpp
+++ b/src/opencv_fx.cpp
@@ -26,6 +26,7 @@
  */
 
 #include "vcam_cv.h"
+#include "vcam_ort.h"
 
 #include <opencv2/core.hpp>
 #include <opencv2/imgproc.hpp>
@@ -147,6 +148,19 @@ inline unsigned tick(unsigned &counter) { return counter++; }
 
 constexpr int INFER_EVERY = 3;   /* run DNN inference 1 in 3 frames */
 
+/* Optional GPU inference: set VCAM_CV_OPENCL=1 to run DNN targets on
+ * OpenCL (AMD Radeon iGPUs work through this). Falls back to CPU
+ * automatically if the OpenCL path throws at load or first forward. */
+inline void set_net_target(cv::dnn::Net &n)
+{
+    n.setPreferableBackend(cv::dnn::DNN_BACKEND_OPENCV);
+    const char *ocl = std::getenv("VCAM_CV_OPENCL");
+    if (ocl && *ocl == '1')
+        n.setPreferableTarget(cv::dnn::DNN_TARGET_OPENCL);
+    else
+        n.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);
+}
+
 /* ────────────────────────────────────────────────────────────
  * DNN model holders (lazy, cached, guarded)
  * ──────────────────────────────────────────────────────────── */
@@ -171,6 +185,15 @@ struct SegState {
     cv::Mat bg_est;           /* running background estimate (invisibility) */
     int bg_frames = 0;        /* how much background we've learned */
     float hx = 0.0f, hy = 0.0f;   /* EMA head offset, -0.5..0.5 (window3d) */
+    int person_ch = -1;           /* which output channel is the person (-1=unlocked) */
+    int ch_vote = 0, ch_frames = 0;   /* voting to lock person_ch */
+    /* RVM (Robust Video Matting): a recurrent video-native matting net.
+     * Far better temporal stability + hair detail than PP-HumanSeg.
+     * Tried first if the model file exists; ANY failure falls back. */
+    cv::dnn::Net rvm;
+    int rvm_state = 0;            /* OpenCV-DNN RVM: 0=untried 1=ok -1=failed */
+    int ort_state = 0;            /* ONNX-Runtime RVM: 0=untried 1=ok -1=failed */
+    cv::Mat r1, r2, r3, r4;       /* recurrent states, cycled per frame */
     std::mutex mtx;
 };
 SegState g_seg;
@@ -233,8 +256,7 @@ bool ensure_style(int s)
     }
     try {
         g_style.net[s] = load_net(path);
-        g_style.net[s].setPreferableBackend(cv::dnn::DNN_BACKEND_OPENCV);
-        g_style.net[s].setPreferableTarget(cv::dnn::DNN_TARGET_CPU);
+        set_net_target(g_style.net[s]);
         g_style.ok[s] = true;
     } catch (const std::exception &e) {
         warn_once("style_load", std::string("failed to load style model: ") + e.what());
@@ -280,8 +302,7 @@ bool ensure_mood()
     }
     try {
         g_mood.net = load_net(path);
-        g_mood.net.setPreferableBackend(cv::dnn::DNN_BACKEND_OPENCV);
-        g_mood.net.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);
+        set_net_target(g_mood.net);
         g_mood.ok = true;
     } catch (const std::exception &e) {
         warn_once("fer_load", std::string("failed to load FER model: ") + e.what());
@@ -336,8 +357,7 @@ bool ensure_seg()
     }
     try {
         g_seg.net = load_net(path);   /* OpenCV 5: new graph engine (ENGINE_AUTO) */
-        g_seg.net.setPreferableBackend(cv::dnn::DNN_BACKEND_OPENCV);
-        g_seg.net.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);
+        set_net_target(g_seg.net);
         g_seg.tried = true; g_seg.ok = true;
 #if VCAM_CV5
         warn_once("seg_engine",
@@ -355,6 +375,182 @@ bool ensure_seg()
  * Returns a full-frame CV_8U mask (255 = person) or empty on failure.
  * Preprocessing: (pixel/255 - 0.5)/0.5  ==  pixel/127.5 - 1, which
  * blobFromImage produces as scalefactor=1/127.5, mean=127.5. */
+/* Try RVM once: load lazily; any exception marks it failed forever
+ * (this session) and PP-HumanSeg takes over. Returns empty on failure.
+ *
+ * Backend priority:
+ *   1. ONNX Runtime (ORT=1 builds) — the reference runtime; computes
+ *      RVM correctly. Input 512-wide for best quality.
+ *   2. OpenCV DNN — kept as a fallback; on current OpenCV 5 graph
+ *      engines it loads but MISCOMPUTES (empty matte), which the
+ *      dead-matte gate below detects, falling through to PP-HumanSeg. */
+cv::Mat rvm_infer(const cv::Mat &bgr)
+{
+    if (g_seg.rvm_state < 0) return cv::Mat();
+
+    /* ── path 1: ONNX Runtime ── */
+    if (ort_available() && g_seg.ort_state >= 0) {
+        try {
+            std::string path = model_dir() + "/rvm_mobilenetv3_fp32.onnx";
+            if (!path_exists(path)) {
+                g_seg.ort_state = -1;         /* no model; don't retry */
+            } else if (g_seg.ort_state == 0) {
+                g_seg.ort_state = ort_rvm_init(path.c_str()) ? 1 : -1;
+                if (g_seg.ort_state == 1)
+                    warn_once("rvm_ort",
+                        "personfx: RVM running on the ONNX Runtime backend "
+                        "(reference runtime — correct, temporally-stable mattes)");
+            }
+            if (g_seg.ort_state == 1) {
+                const int IW = 512;   /* ORT computes correctly; afford quality */
+                double sc = (double)IW / bgr.cols;
+                int iw = std::max(64, ((int)(bgr.cols*sc)/16)*16);
+                int ih = std::max(64, ((int)(bgr.rows*sc)/16)*16);
+                cv::Mat small2;
+                cv::resize(bgr, small2, cv::Size(iw, ih), 0, 0, cv::INTER_AREA);
+                cv::Mat src = cv::dnn::blobFromImage(small2, 1.0/255.0,
+                                  cv::Size(iw, ih), cv::Scalar(), true, false);
+                cv::Mat pha(ih, iw, CV_32F);
+                if (ort_rvm_infer((const float*)src.ptr<float>(0), iw, ih,
+                                  pha.ptr<float>(0))) {
+                    const char *dbg = std::getenv("VCAM_CV_DEBUG");
+                    if (dbg && *dbg=='1' && g_seg.counter < 6)
+                        std::fprintf(stderr, "[vcam/ort] pha mean=%.4f\n",
+                                     cv::mean(pha)[0]);
+                    cv::Mat full;
+                    cv::resize(pha, full, bgr.size(), 0, 0, cv::INTER_LINEAR);
+                    cv::min(full, 1.0, full);
+                    cv::max(full, 0.0, full);
+                    return full;
+                }
+                g_seg.ort_state = -1;         /* backend died; fall through */
+            }
+        } catch (const std::exception &e) {
+            g_seg.ort_state = -1;
+            warn_once("rvm_ort_fail",
+                std::string("ORT RVM path failed (") + e.what() +
+                ") — trying other backends");
+        }
+    }
+
+    /* ── path 2: OpenCV DNN (may miscompute on 5.x; gated below) ── */
+    try {
+        if (g_seg.rvm_state == 0) {
+            std::string path = model_dir() + "/rvm_mobilenetv3_fp32.onnx";
+            if (!path_exists(path)) { g_seg.rvm_state = -1; return cv::Mat(); }
+            g_seg.rvm = load_net(path);
+            set_net_target(g_seg.rvm);
+            g_seg.rvm_state = 1;
+            warn_once("rvm_on",
+                "personfx: RVM video matting model found — using it "
+                "(temporally-stable, hair-level mattes)");
+        }
+        /* input ~384 wide with downsample_ratio=1.0: bypasses RVM's
+         * internal dynamic-resize path entirely (prime suspect for
+         * graph-engine miscompilation -> dead matte). Smaller src keeps
+         * the compute cost similar to 512 @ ds 0.6. */
+        int IW = 384;
+        double sc = (double)IW / bgr.cols;
+        int iw = std::max(64, ((int)(bgr.cols*sc)/16)*16);
+        int ih = std::max(64, ((int)(bgr.rows*sc)/16)*16);
+        cv::Mat small2;
+        cv::resize(bgr, small2, cv::Size(iw, ih), 0, 0, cv::INTER_AREA);
+        /* src: RGB, 0..1, NCHW fp32 */
+        cv::Mat src = cv::dnn::blobFromImage(small2, 1.0/255.0, cv::Size(iw, ih),
+                                             cv::Scalar(), true, false);
+        if (g_seg.r1.empty()) {
+            int shp[4] = {1,1,1,1};
+            g_seg.r1 = cv::Mat(4, shp, CV_32F, cv::Scalar(0));
+            g_seg.r2 = g_seg.r1.clone();
+            g_seg.r3 = g_seg.r1.clone();
+            g_seg.r4 = g_seg.r1.clone();
+        }
+        float dsr[1] = {1.0f};
+        int dshp[1] = {1};
+        cv::Mat ds(1, dshp, CV_32F, dsr);
+        g_seg.rvm.setInput(src,      "src");
+        g_seg.rvm.setInput(g_seg.r1, "r1i");
+        g_seg.rvm.setInput(g_seg.r2, "r2i");
+        g_seg.rvm.setInput(g_seg.r3, "r3i");
+        g_seg.rvm.setInput(g_seg.r4, "r4i");
+        g_seg.rvm.setInput(ds,       "downsample_ratio");
+        /* OpenCV 5's graph engine requires requesting ALL 6 outputs.
+         * BUT do not trust that outs[] order matches our name order —
+         * identify tensors BY SHAPE, which is unambiguous:
+         *   pha = 4D, channels==1, spatial == input size
+         *   fgr = 4D, channels==3
+         *   recurrents = everything else (4 tensors, C>1, smaller). */
+        std::vector<cv::Mat> outs;
+        std::vector<cv::String> names = {"fgr","pha","r1o","r2o","r3o","r4o"};
+        g_seg.rvm.forward(outs, names);
+        if (outs.size() < 6) { g_seg.rvm_state = -1; return cv::Mat(); }
+        const char *dbg = std::getenv("VCAM_CV_DEBUG");
+        int pha_i = -1;
+        std::vector<int> rec_i;
+        for (int oi = 0; oi < (int)outs.size(); oi++) {
+            const cv::Mat &o = outs[oi];
+            if (o.dims != 4) continue;
+            if (dbg && *dbg=='1' && g_seg.counter < 3)
+                std::fprintf(stderr, "[vcam/rvm] out[%d] shape %dx%dx%dx%d\n",
+                    oi, o.size[0], o.size[1], o.size[2], o.size[3]);
+            if (o.size[1] == 1 && o.size[2] == ih && o.size[3] == iw)
+                pha_i = oi;
+            else if (o.size[1] != 3)
+                rec_i.push_back(oi);
+        }
+        if (pha_i < 0) { g_seg.rvm_state = -1; return cv::Mat(); }
+        if (rec_i.size() == 4) {
+            /* feed the recurrents back in the order found */
+            outs[rec_i[0]].copyTo(g_seg.r1);
+            outs[rec_i[1]].copyTo(g_seg.r2);
+            outs[rec_i[2]].copyTo(g_seg.r3);
+            outs[rec_i[3]].copyTo(g_seg.r4);
+        } else {
+            /* can't identify them safely -> run STATELESS: reset the
+             * states to zeros every frame (loses temporal memory, but
+             * the matte itself stays correct). */
+            g_seg.r1.release(); g_seg.r2.release();
+            g_seg.r3.release(); g_seg.r4.release();
+            warn_once("rvm_stateless",
+                "RVM: recurrent outputs ambiguous — running stateless");
+        }
+        int oh = outs[pha_i].size[2], ow = outs[pha_i].size[3];
+        cv::Mat pha(oh, ow, CV_32F, (float*)outs[pha_i].ptr<float>(0));
+        double pmean = cv::mean(pha)[0];
+        if (dbg && *dbg=='1' && g_seg.counter < 6)
+            std::fprintf(stderr, "[vcam/rvm] pha=out[%d] mean=%.4f\n", pha_i, pmean);
+        /* AUTO QUALITY GATE: a matte that stays essentially empty for
+         * 30 straight frames means the engine miscomputes this model.
+         * Declare RVM broken and fall back — never a black screen. */
+        static int dead = 0;
+        if (pmean < 0.005) {
+            if (++dead >= 30) {
+                g_seg.rvm_state = -1;
+                g_seg.r1.release(); g_seg.r2.release();
+                g_seg.r3.release(); g_seg.r4.release();
+                warn_once("rvm_dead",
+                    "RVM produced an empty matte for 30 frames — this "
+                    "OpenCV build miscomputes it. Falling back to "
+                    "PP-HumanSeg. (ONNX Runtime backend would fix this.)");
+                return cv::Mat();
+            }
+        } else dead = 0;
+        cv::Mat full;
+        cv::resize(pha, full, bgr.size(), 0, 0, cv::INTER_LINEAR);
+        cv::min(full, 1.0, full);
+        cv::max(full, 0.0, full);
+        return full.clone();
+    } catch (const std::exception &e) {
+        g_seg.rvm_state = -1;
+        g_seg.r1.release(); g_seg.r2.release(); g_seg.r3.release(); g_seg.r4.release();
+        warn_once("rvm_fail",
+            std::string("RVM could not run on this OpenCV build (") + e.what() +
+            ") — falling back to PP-HumanSeg. On OpenCV 5 the new graph "
+            "engine usually loads it; on 4.x it typically cannot.");
+        return cv::Mat();
+    }
+}
+
 cv::Mat seg_infer(const cv::Mat &bgr, const cv::Rect &body, float edge)
 {
     /* Segment only the body ROI (from the face detector), LETTERBOXED
@@ -380,59 +576,95 @@ cv::Mat seg_infer(const cv::Mat &bgr, const cv::Rect &body, float edge)
     cv::Mat out = g_seg.net.forward();   /* shape [1,2,192,192] */
     if (out.dims != 4 || out.size[1] < 2) return cv::Mat();
 
-    /* SOFT alpha: softmax probability of the person channel, instead of
-     * a harsh argmax. Gives smooth hair/hand edges the blend can feather. */
-    cv::Mat bg(N, N, CV_32F, out.ptr<float>(0, 0));
-    cv::Mat fg(N, N, CV_32F, out.ptr<float>(0, 1));
-    cv::Mat diff = bg - fg;               /* prob = 1/(1+exp(bg-fg)) */
-    cv::Mat e;
-    cv::exp(diff, e);
-    cv::Mat prob = 1.0 / (1.0 + e);       /* CV_32F 0..1 (per-element) */
-    /* un-letterbox → back into the body ROI → into a full-frame canvas */
+    /* Robust channel access: build a 2D header onto each channel plane
+     * from the raw data pointer (out.ptr<float>(0,c) is fragile on a 4D
+     * Mat). Plane stride is N*N floats. */
+    const int HW = N * N;
+    float *base = (float *)out.ptr<float>(0);
+    cv::Mat ch0(N, N, CV_32F, base);
+    cv::Mat ch1(N, N, CV_32F, base + HW);
+
+    /* Which channel is the PERSON? PP-HumanSeg's channel order isn't
+     * guaranteed, and getting it backwards inverts the mask (the exact
+     * "half the body is cut" symptom). The order is FIXED for a given
+     * model, so we vote over the first frames and then lock it: the
+     * person channel is hotter in the CENTER of the letterboxed crop
+     * (person is centered; background hugs the corners). */
+    auto center_minus_border = [&](const cv::Mat &c) -> float {
+        int m = N / 4;
+        cv::Scalar cen = cv::mean(c(cv::Rect(m, m, N - 2*m, N - 2*m)));
+        cv::Scalar whole = cv::mean(c);
+        return (float)(cen[0] - whole[0]);
+    };
+    cv::Mat mx = cv::max(ch0, ch1);
+    cv::Mat e0, e1;
+    cv::exp(ch0 - mx, e0);
+    cv::exp(ch1 - mx, e1);
+    cv::Mat sum = e0 + e1;
+    cv::Mat p0 = e0 / sum;
+    cv::Mat p1 = e1 / sum;
+    if (g_seg.person_ch < 0) {                 /* not locked yet: vote */
+        if (center_minus_border(p1) >= center_minus_border(p0))
+            g_seg.ch_vote++;
+        else
+            g_seg.ch_vote--;
+        if (++g_seg.ch_frames >= 8)            /* lock after 8 frames */
+            g_seg.person_ch = (g_seg.ch_vote >= 0) ? 1 : 0;
+    }
+    /* until locked, use the current best guess */
+    int pc = (g_seg.person_ch >= 0) ? g_seg.person_ch
+             : ((center_minus_border(p1) >= center_minus_border(p0)) ? 1 : 0);
+    cv::Mat prob = (pc == 1) ? p1 : p0;
+    /* un-letterbox → back into the body ROI → into a full-frame canvas.
+     * NOTE: no blur here — we sharpen the alpha FIRST (below), then apply
+     * a single narrow feather. Blurring before the opacity remap was what
+     * spread the translucent halo around the whole silhouette. */
     cv::Mat inner = prob(cv::Rect(lx, ly, lw, lh));
     cv::Mat roi_mask;
     cv::resize(inner, roi_mask, body.size(), 0, 0, cv::INTER_LINEAR);
     cv::Mat full = cv::Mat::zeros(bgr.size(), CV_32F);
     roi_mask.copyTo(full(body));
-    double sigma = std::max(2.0, bgr.cols / 240.0);
-    cv::GaussianBlur(full, full, cv::Size(0, 0), sigma);
 
-    /* connected-component cleanup at 1/4 res: keep only the biggest
-     * person blob — stray background false-positives vanish. */
+    /* connected-component cleanup at 1/4 res: keep the person blob(s),
+     * drop stray background false-positives (e.g. the leaking corner). */
     cv::Mat q, q8, lbl, stats, cent;
     cv::resize(full, q, cv::Size(), 0.25, 0.25, cv::INTER_LINEAR);
-    q8 = q > 0.22;
+    q8 = q > 0.30;
     int n2 = cv::connectedComponentsWithStats(q8, lbl, stats, cent);
     if (n2 > 1) {
         int ba = 0;
         for (int i2 = 1; i2 < n2; i2++)
             ba = std::max(ba, stats.at<int>(i2, cv::CC_STAT_AREA));
-        /* keep every component with >=10% of the largest's area — a
-         * head separated from the torso by a low-confidence neck pixel
-         * must NOT be deleted as noise (it was; hence the missing head) */
+        /* keep every component with >=15% of the largest's area (head +
+         * torso + raised arm survive; small false blobs like the leaking
+         * corner are discarded). */
         cv::Mat keep = cv::Mat::zeros(lbl.size(), CV_8U);
         for (int i2 = 1; i2 < n2; i2++) {
             int a2 = stats.at<int>(i2, cv::CC_STAT_AREA);
-            if (a2 >= std::max(24, ba / 10))
+            if (a2 >= std::max(40, ba * 15 / 100))
                 keep |= (lbl == i2);
         }
-        cv::dilate(keep, keep, cv::Mat(), cv::Point(-1,-1), 2);
-        cv::Mat keepf, keepfull;
-        keep.convertTo(keepf, CV_32F, 1.0/255.0);
-        cv::GaussianBlur(keepf, keepf, cv::Size(0,0), 2.0);
-        cv::resize(keepf, keepfull, full.size(), 0, 0, cv::INTER_LINEAR);
-        full = full.mul(keepfull);
+        cv::Mat keepfull;
+        cv::resize(keep, keepfull, full.size(), 0, 0, cv::INTER_NEAREST);
+        cv::Mat keepf; keepfull.convertTo(keepf, CV_32F, 1.0/255.0);
+        full = full.mul(keepf);
     }
 
-    /* OPACITY FIX: the model's probability inside the body hovers at
-     * 0.6-0.8, which — used directly as alpha — rendered the person
-     * translucent. Remap 0.30..0.60 -> 0..1 (smoothstep): confident
-     * regions become solid, the feather survives only at true edges. */
-    full = (full - edge) * (1.0 / 0.33);
+    /* OPACITY: remap so confident interior -> fully solid, with a NARROW
+     * transition band. 'edge' sets the midpoint (lower = more hair kept);
+     * the /0.14 makes the ramp steep, so the person is opaque and only a
+     * thin rim is soft — no more see-through halo. */
+    full = (full - edge) * (1.0 / 0.14);
     cv::min(full, 1.0, full);
     cv::max(full, 0.0, full);
     cv::Mat f2 = full.mul(full);
-    full = f2 * 3.0 - f2.mul(full) * 2.0;      /* 3t^2 - 2t^3 */
+    full = f2 * 3.0 - f2.mul(full) * 2.0;      /* smoothstep 3t^2 - 2t^3 */
+
+    /* Pull the edge inward by ~1px so the soft rim sits just INSIDE the
+     * true silhouette (prevents the 1-2px background halo from bleeding
+     * through), then a single tight feather for anti-aliasing. */
+    cv::erode(full, full, cv::Mat(), cv::Point(-1,-1), 1);
+    cv::GaussianBlur(full, full, cv::Size(0, 0), std::max(1.0, bgr.cols / 480.0));
     return full;
 }
 
@@ -780,6 +1012,65 @@ void cv_fx_face(unsigned char *data, int w, int h, int stride, int mode)
                     cv::circle(img, eye, std::max(2, fw/20),
                                cv::Scalar(255,255,255), cv::FILLED);
                 }
+            } else if (mode == 9) {
+                /* MIRROR FACE: left half of your face reflected right */
+                for (int yy = y; yy < y+fh && yy < h; yy++) {
+                    cv::Vec3b *rw2 = img.ptr<cv::Vec3b>(yy);
+                    for (int xx = 0; xx < fw/2; xx++) {
+                        int l2 = x+xx, r2 = x+fw-1-xx;
+                        if (l2>=0 && r2<w) rw2[r2] = rw2[l2];
+                    }
+                }
+            } else if (mode == 10) {
+                /* CYCLOPS: one giant eye between your two real ones */
+                int ex2=(int)((f[4]+f[6])*inv/2), ey2=(int)((f[5]+f[7])*inv/2);
+                int R4=std::max(8,fw/4);
+                cv::ellipse(img,cv::Point(ex2,ey2),cv::Size(R4,R4*2/3),0,0,360,cv::Scalar(245,245,245),cv::FILLED);
+                cv::circle(img,cv::Point(ex2,ey2),R4/2,cv::Scalar(90,40,20),cv::FILLED);
+                cv::circle(img,cv::Point(ex2,ey2),R4/4,cv::Scalar(10,10,10),cv::FILLED);
+                cv::circle(img,cv::Point(ex2-R4/6,ey2-R4/6),std::max(2,R4/8),cv::Scalar(255,255,255),cv::FILLED);
+                cv::ellipse(img,cv::Point(ex2,ey2),cv::Size(R4,R4*2/3),0,0,360,cv::Scalar(30,30,30),2);
+            } else if (mode == 11) {
+                /* HEART EYES */
+                for (int e2=0;e2<2;e2++){
+                    int hx2=(int)(f[4+e2*2]*inv), hy2=(int)(f[5+e2*2]*inv);
+                    int r5=std::max(5,fw/8);
+                    cv::Scalar red(60,40,235);
+                    cv::circle(img,cv::Point(hx2-r5/2,hy2-r5/3),r5/2+1,red,cv::FILLED);
+                    cv::circle(img,cv::Point(hx2+r5/2,hy2-r5/3),r5/2+1,red,cv::FILLED);
+                    cv::Point tri[3]={{hx2-r5,hy2-r5/6},{hx2+r5,hy2-r5/6},{hx2,hy2+r5}};
+                    cv::fillConvexPoly(img,tri,3,red);
+                }
+            } else if (mode == 12) {
+                /* INTERROGATION: darkness except an oval on your face */
+                float fcx=x+fw/2.f, fcy=y+fh/2.f, ra=fw*0.85f, rb=fh*0.95f;
+                for (int yy=0;yy<h;yy++){
+                    uchar *rw2=data+yy*stride;
+                    float ny=(yy-fcy)/rb;
+                    for (int xx=0;xx<w;xx++){
+                        float nx=(xx-fcx)/ra, d2=nx*nx+ny*ny;
+                        if (d2<1.0f) continue;
+                        float k2 = d2>2.0f?0.12f:(1.0f-(d2-1.0f)*0.88f);
+                        uchar *p2=rw2+xx*3;
+                        p2[0]=(uchar)(p2[0]*k2); p2[1]=(uchar)(p2[1]*k2); p2[2]=(uchar)(p2[2]*k2);
+                    }
+                }
+            } else if (mode == 13) {
+                /* TARGET LOCK: rotating sci-fi HUD reticle on your face */
+                cv::Point c3(x+fw/2,y+fh/2);
+                int R5=(int)(std::max(fw,fh)*0.75);
+                cv::Scalar g3(80,255,80);
+                float a3=(float)(g_face.counter%90)/90.0f*6.2832f;
+                for(int k2=0;k2<4;k2++){
+                    float aa=a3+k2*1.5708f;
+                    cv::ellipse(img,c3,cv::Size(R5,R5),aa*57.3,0,60,g3,2);
+                }
+                cv::circle(img,c3,R5*2/3,g3,1);
+                cv::line(img,cv::Point(c3.x-R5,c3.y),cv::Point(c3.x-R5/2,c3.y),g3,2);
+                cv::line(img,cv::Point(c3.x+R5/2,c3.y),cv::Point(c3.x+R5,c3.y),g3,2);
+                cv::line(img,cv::Point(c3.x,c3.y-R5),cv::Point(c3.x,c3.y-R5/2),g3,2);
+                cv::line(img,cv::Point(c3.x,c3.y+R5/2),cv::Point(c3.x,c3.y+R5),g3,2);
+                cv::putText(img,"LOCK",cv::Point(c3.x+R5/2,c3.y-R5/2),cv::FONT_HERSHEY_SIMPLEX,0.7,g3,2);
             } else {
                 /* googly eyes at the two eye landmarks (idx 4,5 & 6,7) */
                 for (int e = 0; e < 2; e++) {
@@ -816,18 +1107,28 @@ void cv_fx_bgblur(unsigned char *data, int w, int h, int stride, int mode,
         std::lock_guard<std::mutex> lock(g_seg.mtx);
         cv::Mat img = wrap_bgr(data, w, h, stride);
 
-        if (!ensure_seg()) return;   /* model missing → no-op */
+        /* PP-HumanSeg is only REQUIRED when RVM can't serve as the
+         * matting engine. With RVM available (ORT backend, or a DNN
+         * build that computes it), personfx works without the
+         * pphumanseg model file entirely. */
+        bool rvm_possible =
+            (g_seg.rvm_state >= 0 || (ort_available() && g_seg.ort_state >= 0));
+        if (!rvm_possible && !ensure_seg()) return;   /* nothing can matte */
 
         /* Inference EVERY frame: PP-HumanSeg is ~6 ms on a laptop CPU,
          * and a stale mask visibly lags moving hands (the old every-3rd
          * throttle caused exactly that). Temporal EMA keeps edges calm. */
         tick(g_seg.counter);
         {
-            /* body ROI from the face detector (the one that works!) —
-             * face box expanded to shoulders-and-torso proportions.
+            /* body ROI from the face detector — only needed for the
+             * PP-HumanSeg path (RVM mattes the full frame natively).
              * Lock order seg->face is the established unique nesting. */
             cv::Rect body(0, 0, img.cols, img.rows);
-            {
+            bool rvm_alive =
+                (ort_available() && g_seg.ort_state >= 0) || g_seg.rvm_state > 0 ||
+                (g_seg.rvm_state == 0 &&
+                 path_exists(model_dir() + "/rvm_mobilenetv3_fp32.onnx"));
+            if (!rvm_alive) {
                 std::lock_guard<std::mutex> fl(g_face.mtx);
                 const int TW = 320;
                 double fs = (img.cols > TW) ? (double)TW / img.cols : 1.0;
@@ -856,7 +1157,16 @@ void cv_fx_bgblur(unsigned char *data, int w, int h, int stride, int mode,
                     }
                 }
             }
-            cv::Mat m = seg_infer(img, body, edge);
+            cv::Mat m = rvm_infer(img);
+            if (!m.empty()) {
+                /* RVM alpha is already clean; light remap honors 'edge' */
+                m = (m - edge*0.5) * (1.0/(1.0 - edge*0.5));
+                cv::min(m, 1.0, m); cv::max(m, 0.0, m);
+            } else if (ensure_seg()) {
+                m = seg_infer(img, body, edge);
+            } else {
+                return;   /* RVM just died and pphumanseg is absent */
+            }
             if (!m.empty()) {
                 if (!g_seg.mask.empty() && g_seg.mask.size() == m.size())
                     cv::addWeighted(m, smooth, g_seg.mask, 1.0 - smooth, 0.0, g_seg.mask);
@@ -893,6 +1203,150 @@ void cv_fx_bgblur(unsigned char *data, int w, int h, int stride, int mode,
         cv::Mat inv;
         cv::bitwise_not(person3, inv);
 
+        if (mode == 11) {
+            /* RAINBOW AURA: hue-cycling glow rings around your body */
+            cv::Mat m8,d1,d2m;
+            g_seg.mask.convertTo(m8,CV_8U,255.0);
+            unsigned tk=g_seg.counter;
+            for(int ring=0;ring<3;ring++){
+                cv::dilate(m8,d1,cv::Mat(),cv::Point(-1,-1),2+ring*3);
+                cv::dilate(m8,d2m,cv::Mat(),cv::Point(-1,-1),ring*3);
+                float hue=(tk*0.06f)+ring*2.1f;
+                int cb2=(int)((std::sin(hue+4.19f)*0.5f+0.5f)*255);
+                int cg2=(int)((std::sin(hue+2.09f)*0.5f+0.5f)*255);
+                int cr2=(int)((std::sin(hue)*0.5f+0.5f)*255);
+                for(int y=0;y<img.rows;y++){
+                    const uchar *da=d1.ptr<uchar>(y),*db=d2m.ptr<uchar>(y);
+                    cv::Vec3b *ip=img.ptr<cv::Vec3b>(y);
+                    for(int x=0;x<img.cols;x++){
+                        if(da[x]>128 && db[x]<128){
+                            ip[x][0]=clamp_int_u8(ip[x][0]+cb2/2);
+                            ip[x][1]=clamp_int_u8(ip[x][1]+cg2/2);
+                            ip[x][2]=clamp_int_u8(ip[x][2]+cr2/2);
+                        }
+                    }
+                }
+            }
+            return;
+        }
+        if (mode == 12) {
+            /* PAINTED WORLD: neural style transfers the BACKGROUND
+             * while you stay photographic — two nets chained through
+             * the matte. Needs --models-style. */
+            cv::Mat styled = img.clone();
+            cv_fx_style(styled.data, img.cols, img.rows,
+                        (int)styled.step, 1 /*candy*/, 1.0f, 160.0f);
+            for(int y=0;y<img.rows;y++){
+                const float *mm=g_seg.mask.ptr<float>(y);
+                const cv::Vec3b *sp2=styled.ptr<cv::Vec3b>(y);
+                cv::Vec3b *ip=img.ptr<cv::Vec3b>(y);
+                for(int x=0;x<img.cols;x++){
+                    float a=1.0f-mm[x]; if(a<0.03f) continue;
+                    ip[x][0]=(uchar)(ip[x][0]+(sp2[x][0]-ip[x][0])*a);
+                    ip[x][1]=(uchar)(ip[x][1]+(sp2[x][1]-ip[x][1])*a);
+                    ip[x][2]=(uchar)(ip[x][2]+(sp2[x][2]-ip[x][2])*a);
+                }
+            }
+            return;
+        }
+        if (mode == 13) {
+            /* BODY PRIVACY: pixelate only the person */
+            cv::Mat tiny;
+            cv::resize(img,tiny,cv::Size(img.cols/24,img.rows/24));
+            cv::resize(tiny,tiny,img.size(),0,0,cv::INTER_NEAREST);
+            for(int y=0;y<img.rows;y++){
+                const float *mm=g_seg.mask.ptr<float>(y);
+                const cv::Vec3b *tp=tiny.ptr<cv::Vec3b>(y);
+                cv::Vec3b *ip=img.ptr<cv::Vec3b>(y);
+                for(int x=0;x<img.cols;x++){
+                    float a=mm[x]; if(a<0.05f) continue;
+                    ip[x][0]=(uchar)(ip[x][0]+(tp[x][0]-ip[x][0])*a);
+                    ip[x][1]=(uchar)(ip[x][1]+(tp[x][1]-ip[x][1])*a);
+                    ip[x][2]=(uchar)(ip[x][2]+(tp[x][2]-ip[x][2])*a);
+                }
+            }
+            return;
+        }
+        if (mode == 15) {
+            /* MOTION ECHO: translucent copies of your silhouette shed
+             * behind you as you move — a comet-trail of past poses held
+             * in a decaying accumulator, composited under the live you. */
+            static cv::Mat accum;
+            if (accum.empty() || accum.size() != img.size())
+                accum = cv::Mat::zeros(img.size(), CV_32FC3);
+            /* decay the trail */
+            accum *= 0.88;
+            /* stamp the current matted person into the accumulator */
+            for (int y = 0; y < img.rows; y++) {
+                const float *mm = g_seg.mask.ptr<float>(y);
+                const cv::Vec3b *ip = img.ptr<cv::Vec3b>(y);
+                cv::Vec3f *ap = accum.ptr<cv::Vec3f>(y);
+                for (int x = 0; x < img.cols; x++) {
+                    float a = mm[x]; if (a < 0.05f) continue;
+                    ap[x][0] = std::max(ap[x][0], ip[x][0]*a);
+                    ap[x][1] = std::max(ap[x][1], ip[x][1]*a);
+                    ap[x][2] = std::max(ap[x][2], ip[x][2]*a);
+                }
+            }
+            /* draw trail where the live person ISN'T, tinted cyan */
+            for (int y = 0; y < img.rows; y++) {
+                const float *mm = g_seg.mask.ptr<float>(y);
+                const cv::Vec3f *ap = accum.ptr<cv::Vec3f>(y);
+                cv::Vec3b *ip = img.ptr<cv::Vec3b>(y);
+                for (int x = 0; x < img.cols; x++) {
+                    float t = (1.0f - mm[x]);
+                    float lum = (ap[x][0]+ap[x][1]+ap[x][2]) / 3.0f;
+                    if (lum < 8) continue;
+                    float a = std::min(0.75f, lum/180.0f) * t;
+                    ip[x][0]=(uchar)(ip[x][0]+(std::min(255.f,ap[x][0]*1.3f)-ip[x][0])*a);
+                    ip[x][1]=(uchar)(ip[x][1]+(std::min(255.f,ap[x][1]*1.1f)-ip[x][1])*a);
+                    ip[x][2]=(uchar)(ip[x][2]+(ap[x][2]*0.6f-ip[x][2])*a);
+                }
+            }
+            return;
+        }
+        if (mode == 16) {
+            /* DOUBLE EXPOSURE: the classic portrait effect — your
+             * silhouette is filled with the room behind you (the learned
+             * background shows THROUGH your body), edges kept dark. */
+            if (g_seg.bg_est.empty()) { }
+            for (int y = 0; y < img.rows; y++) {
+                const float *mm = g_seg.mask.ptr<float>(y);
+                const cv::Vec3b *bp = g_seg.bg_est.empty() ? nullptr
+                                      : g_seg.bg_est.ptr<cv::Vec3b>(y);
+                cv::Vec3b *ip = img.ptr<cv::Vec3b>(y);
+                for (int x = 0; x < img.cols; x++) {
+                    float a = mm[x];
+                    if (a < 0.05f) { ip[x] = cv::Vec3b(20,15,15); continue; }
+                    /* inside the person: blend the body luma with the
+                     * background image for a dreamy double-exposure */
+                    float lum = (ip[x][0]*0.114f+ip[x][1]*0.587f+ip[x][2]*0.299f)/255.f;
+                    cv::Vec3b bgv = bp ? bp[x] : cv::Vec3b(60,40,80);
+                    ip[x][0]=(uchar)(bgv[0]*lum + 30*(1-lum));
+                    ip[x][1]=(uchar)(bgv[1]*lum + 20*(1-lum));
+                    ip[x][2]=(uchar)(bgv[2]*lum + 40*(1-lum));
+                }
+            }
+            return;
+        }
+        if (mode == 14) {
+            /* GRAVITY FLIP: you, upside down in the learned room */
+            cv::Mat out2; g_seg.bg_est.copyTo(out2);
+            for(int y=0;y<img.rows;y++){
+                int sy2=img.rows-1-y;
+                const float *mm=g_seg.mask.ptr<float>(sy2);
+                const cv::Vec3b *ip=img.ptr<cv::Vec3b>(sy2);
+                cv::Vec3b *op=out2.ptr<cv::Vec3b>(y);
+                for(int x=0;x<img.cols;x++){
+                    float a=mm[x]; if(a<0.05f) continue;
+                    op[x][0]=(uchar)(op[x][0]+(ip[x][0]-op[x][0])*a);
+                    op[x][1]=(uchar)(op[x][1]+(ip[x][1]-op[x][1])*a);
+                    op[x][2]=(uchar)(op[x][2]+(ip[x][2]-op[x][2])*a);
+                }
+            }
+            out2.copyTo(img);
+            return;
+        }
         if (mode == 9) {
             /* TINY YOU: you, shrunk to 45%, standing at the bottom of
              * the learned room like a desk gnome. */
@@ -1241,7 +1695,7 @@ void cv_fx_mood(unsigned char *data, int w, int h, int stride,
 {
     if (!data || w < 32 || h < 32) return;
     if (mode < 0) mode = 0;
-    if (mode > 4) mode = 4;
+    if (mode > 5) mode = 5;
     if (gain <= 0.0f || gain > 2.0f) gain = 1.0f;
     try {
         cv::Mat img = wrap_bgr(data, w, h, stride);
@@ -1373,6 +1827,25 @@ void cv_fx_mood(unsigned char *data, int w, int h, int stride,
                         cv::FONT_HERSHEY_SIMPLEX, 0.7, col, 2);
             int bw = (int)(roi.width * conf);
             cv::rectangle(img, cv::Rect(roi.x, ty + 6, bw, 5), col, cv::FILLED);
+        } else if (mode == 5) {
+            /* AUTO-GRADE: cinematic color grade steered by emotion.
+             * happy=warm lift, sad=cool desat, angry=hot contrast,
+             * surprised=bright pop, fear=purple shadows, disgust=green. */
+            static const float G[7][4] = {   /* mulB mulG mulR add */
+                {0.85f,0.90f,1.20f, 8},{0.90f,1.15f,0.90f, 0},
+                {1.15f,0.90f,1.05f,-8},{0.95f,1.05f,1.15f,12},
+                {1.f,1.f,1.f,0},{1.20f,1.00f,0.85f,-10},{1.05f,1.05f,1.05f,18}};
+            const float *g4=G[emo];
+            float k4=conf;
+            for(int y=0;y<h;y++){
+                uchar *p2=data+y*stride;
+                for(int x=0;x<w;x++){
+                    uchar *q2=p2+x*3;
+                    q2[0]=clamp_int_u8((int)(q2[0]*(1+(g4[0]-1)*k4)+g4[3]*k4));
+                    q2[1]=clamp_int_u8((int)(q2[1]*(1+(g4[1]-1)*k4)+g4[3]*k4));
+                    q2[2]=clamp_int_u8((int)(q2[2]*(1+(g4[2]-1)*k4)+g4[3]*k4));
+                }
+            }
         } else if (mode == 4) {
             /* PAINTMOOD: two neural nets chained — the FER model reads
              * your emotion, which SELECTS the neural style; confidence
@@ -1637,9 +2110,10 @@ void cv_clear_bg_image(void)
 
 void cv_shutdown(void)
 {
+    ort_shutdown();
     try {
         { std::lock_guard<std::mutex> l(g_face.mtx); g_face.det.reset(); g_face.faces.release(); }
-        { std::lock_guard<std::mutex> l(g_seg.mtx);  g_seg.net = cv::dnn::Net(); g_seg.mask.release(); g_seg.bg_est.release(); }
+        { std::lock_guard<std::mutex> l(g_seg.mtx);  g_seg.net = cv::dnn::Net(); g_seg.rvm = cv::dnn::Net(); g_seg.mask.release(); g_seg.bg_est.release(); g_seg.r1.release(); g_seg.r2.release(); g_seg.r3.release(); g_seg.r4.release(); }
         { std::lock_guard<std::mutex> l(g_classic.mtx);
           g_classic.mog2.reset(); g_classic.prev_gray.release(); }
         { std::lock_guard<std::mutex> l(g_style.mtx);
diff --git a/src/ort_rvm.c b/src/ort_rvm.c
new file mode 100644
index 0000000..cfb2c58
--- /dev/null
+++ b/src/ort_rvm.c
@@ -0,0 +1,292 @@
+/* SPDX-License-Identifier: GPL-2.0-only
+ * vcam — Linux virtual webcam pipeline
+ * Copyright (C) 2026 the vcam authors
+ *
+ * This program is free software under the terms of the GNU General
+ * Public License version 2. See the LICENSE file for the full text.
+ */
+
+/*
+ * ort_rvm.c — RVM (Robust Video Matting) on ONNX Runtime.
+ *
+ * Built with ORT=1 this is a real backend against the ORT C API;
+ * otherwise the #else half provides no-op stubs so the rest of vcam
+ * links unchanged. See include/vcam_ort.h for the interface story.
+ *
+ * Implementation notes (learned the hard way from the OpenCV attempt):
+ *   - Tensors are matched BY NAME (src, r1i.., fgr, pha, r1o..), never
+ *     by position. Model I/O order is an implementation detail.
+ *   - The four recurrent outputs are carried to the next frame by
+ *     keeping their OrtValue* alive and feeding them back as inputs —
+ *     zero copies, and exactly how RVM's own examples do it.
+ *   - Every ORT call is checked; the first failure prints one line and
+ *     the backend marks itself dead for the session. Callers fall back.
+ */
+
+#include "vcam_ort.h"
+
+#include <stdio.h>
+
+#if VCAM_HAVE_ORT
+
+#include <stdlib.h>
+#include <string.h>
+#include <pthread.h>
+#include "onnxruntime_c_api.h"
+
+static const OrtApi        *A;
+static OrtEnv              *g_env;
+static OrtSessionOptions   *g_so;
+static OrtSession          *g_sess;
+static OrtMemoryInfo       *g_mi;      /* CPU, for wrapping caller buffers */
+static OrtAllocator        *g_alloc;   /* default allocator (names, tensors) */
+
+static OrtValue *g_rec[4];             /* recurrent state r1..r4 (owned) */
+static int g_iw = 0, g_ih = 0;         /* frame size the state belongs to */
+static int g_dead = 0;                 /* backend failed; stay down */
+static pthread_mutex_t g_mtx = PTHREAD_MUTEX_INITIALIZER;
+
+/* fixed RVM interface names; init() verifies the model matches */
+static const char *IN_NAMES[6]  = {"src","r1i","r2i","r3i","r4i","downsample_ratio"};
+static const char *OUT_NAMES[6] = {"fgr","pha","r1o","r2o","r3o","r4o"};
+
+/* Check an OrtStatus; on error print once, release it, and return 0. */
+static int ok(OrtStatus *st, const char *where)
+{
+    if (!st) return 1;
+    fprintf(stderr, "[vcam/ort] %s failed: %s\n", where, A->GetErrorMessage(st));
+    A->ReleaseStatus(st);
+    return 0;
+}
+
+static void release_rec(void)
+{
+    for (int i = 0; i < 4; i++) {
+        if (g_rec[i]) { A->ReleaseValue(g_rec[i]); g_rec[i] = NULL; }
+    }
+}
+
+/* Fresh [1,1,1,1] zero tensors for the recurrent inputs (the shape RVM
+ * documents for the initial state; it broadcasts internally). */
+static int init_rec(void)
+{
+    release_rec();
+    const int64_t shp[4] = {1, 1, 1, 1};
+    for (int i = 0; i < 4; i++) {
+        if (!ok(A->CreateTensorAsOrtValue(g_alloc, shp, 4,
+                    ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &g_rec[i]),
+                "CreateTensorAsOrtValue(rec)"))
+            return 0;
+        float *p = NULL;
+        if (!ok(A->GetTensorMutableData(g_rec[i], (void **)&p),
+                "GetTensorMutableData(rec)"))
+            return 0;
+        p[0] = 0.0f;
+    }
+    return 1;
+}
+
+/* Confirm the session's inputs/outputs are exactly the RVM interface.
+ * Rejecting mismatches here means a wrong .onnx can never half-run. */
+static int verify_iface(void)
+{
+    size_t nin = 0, nout = 0;
+    if (!ok(A->SessionGetInputCount(g_sess, &nin), "SessionGetInputCount"))  return 0;
+    if (!ok(A->SessionGetOutputCount(g_sess, &nout), "SessionGetOutputCount")) return 0;
+    if (nin != 6 || nout != 6) {
+        fprintf(stderr, "[vcam/ort] model has %zu inputs / %zu outputs; RVM needs 6/6\n",
+                nin, nout);
+        return 0;
+    }
+    int seen_in = 0, seen_out = 0;
+    for (size_t i = 0; i < 6; i++) {
+        char *nm = NULL;
+        if (!ok(A->SessionGetInputName(g_sess, i, g_alloc, &nm), "SessionGetInputName"))
+            return 0;
+        for (int k = 0; k < 6; k++)
+            if (strcmp(nm, IN_NAMES[k]) == 0) { seen_in |= 1 << k; break; }
+        if (!ok(A->AllocatorFree(g_alloc, nm), "AllocatorFree")) return 0;
+        if (!ok(A->SessionGetOutputName(g_sess, i, g_alloc, &nm), "SessionGetOutputName"))
+            return 0;
+        for (int k = 0; k < 6; k++)
+            if (strcmp(nm, OUT_NAMES[k]) == 0) { seen_out |= 1 << k; break; }
+        if (!ok(A->AllocatorFree(g_alloc, nm), "AllocatorFree")) return 0;
+    }
+    if (seen_in != 0x3F || seen_out != 0x3F) {
+        fprintf(stderr, "[vcam/ort] model I/O names don't match the RVM interface "
+                        "(src,r1i..r4i,downsample_ratio -> fgr,pha,r1o..r4o)\n");
+        return 0;
+    }
+    return 1;
+}
+
+bool ort_available(void) { return true; }
+
+const char *ort_version(void)
+{
+    return OrtGetApiBase()->GetVersionString();
+}
+
+int ort_rvm_init(const char *model_path)
+{
+    if (!model_path || !*model_path) return 0;
+    pthread_mutex_lock(&g_mtx);
+    if (g_sess) { pthread_mutex_unlock(&g_mtx); return 1; }   /* already up */
+    g_dead = 0;
+
+    if (!A) A = OrtGetApiBase()->GetApi(ORT_API_VERSION);
+    if (!A) {
+        fprintf(stderr, "[vcam/ort] ORT C API version %d unavailable in this "
+                        "libonnxruntime\n", ORT_API_VERSION);
+        goto fail;
+    }
+    if (!g_env &&
+        !ok(A->CreateEnv(ORT_LOGGING_LEVEL_ERROR, "vcam", &g_env), "CreateEnv"))
+        goto fail;
+    if (!g_so) {
+        if (!ok(A->CreateSessionOptions(&g_so), "CreateSessionOptions")) goto fail;
+        if (!ok(A->SetSessionGraphOptimizationLevel(g_so, ORT_ENABLE_ALL),
+                "SetGraphOptimizationLevel")) goto fail;
+        /* leave intra-op threads at ORT's default (all cores) */
+    }
+    if (!g_mi &&
+        !ok(A->CreateCpuMemoryInfo(OrtArenaAllocator, OrtMemTypeDefault, &g_mi),
+            "CreateCpuMemoryInfo"))
+        goto fail;
+    if (!g_alloc &&
+        !ok(A->GetAllocatorWithDefaultOptions(&g_alloc), "GetAllocator"))
+        goto fail;
+
+    if (!ok(A->CreateSession(g_env, model_path, g_so, &g_sess), "CreateSession"))
+        goto fail;
+    if (!verify_iface()) {
+        A->ReleaseSession(g_sess); g_sess = NULL;
+        goto fail;
+    }
+    if (!init_rec()) {
+        A->ReleaseSession(g_sess); g_sess = NULL;
+        goto fail;
+    }
+    g_iw = g_ih = 0;
+    fprintf(stderr, "[vcam/ort] RVM ready on ONNX Runtime %s\n",
+            OrtGetApiBase()->GetVersionString());
+    pthread_mutex_unlock(&g_mtx);
+    return 1;
+fail:
+    g_dead = 1;
+    pthread_mutex_unlock(&g_mtx);
+    return 0;
+}
+
+int ort_rvm_infer(const float *src_chw, int iw, int ih, float *pha_out)
+{
+    if (!src_chw || !pha_out || iw < 16 || ih < 16) return 0;
+    pthread_mutex_lock(&g_mtx);
+    if (!g_sess || g_dead) { pthread_mutex_unlock(&g_mtx); return 0; }
+
+    /* frame size changed -> the recurrent state's spatial dims no longer
+     * match; restart it from zeros */
+    if (iw != g_iw || ih != g_ih) {
+        if (!init_rec()) goto dead;
+        g_iw = iw; g_ih = ih;
+    }
+
+    OrtValue *in_src = NULL, *in_ds = NULL;
+    OrtValue *outs[6] = {NULL, NULL, NULL, NULL, NULL, NULL};
+    static float dsr = 1.0f;               /* we pre-scale frames ourselves */
+    int ret = 0;
+
+    {
+        const int64_t sshp[4] = {1, 3, ih, iw};
+        if (!ok(A->CreateTensorWithDataAsOrtValue(g_mi, (void *)src_chw,
+                    (size_t)3 * ih * iw * sizeof(float), sshp, 4,
+                    ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &in_src),
+                "CreateTensor(src)"))
+            goto dead;
+        const int64_t dshp[1] = {1};
+        if (!ok(A->CreateTensorWithDataAsOrtValue(g_mi, &dsr, sizeof dsr,
+                    dshp, 1, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &in_ds),
+                "CreateTensor(downsample_ratio)"))
+            goto cleanup_dead;
+
+        const OrtValue *ins[6] = {in_src, g_rec[0], g_rec[1], g_rec[2], g_rec[3], in_ds};
+        if (!ok(A->Run(g_sess, NULL, IN_NAMES, ins, 6, OUT_NAMES, 6, outs), "Run"))
+            goto cleanup_dead;
+
+        /* pha = outs[1]; sanity-check its shape [1,1,ih,iw] */
+        OrtTensorTypeAndShapeInfo *ti = NULL;
+        if (!ok(A->GetTensorTypeAndShape(outs[1], &ti), "GetShape(pha)"))
+            goto cleanup_dead;
+        size_t nd = 0;
+        int64_t dims[8] = {0};
+        int shape_ok = ok(A->GetDimensionsCount(ti, &nd), "GetDimensionsCount");
+        if (shape_ok && nd <= 8)
+            shape_ok = ok(A->GetDimensions(ti, dims, nd), "GetDimensions");
+        A->ReleaseTensorTypeAndShapeInfo(ti);
+        if (!shape_ok || nd != 4 || dims[1] != 1 || dims[2] != ih || dims[3] != iw) {
+            fprintf(stderr, "[vcam/ort] unexpected pha shape\n");
+            goto cleanup_dead;
+        }
+        float *pp = NULL;
+        if (!ok(A->GetTensorMutableData(outs[1], (void **)&pp), "GetData(pha)"))
+            goto cleanup_dead;
+        memcpy(pha_out, pp, (size_t)ih * iw * sizeof(float));
+
+        /* cycle the recurrent state: steal r1o..r4o (outs[2..5]) as the
+         * next frame's inputs; release the previous generation */
+        release_rec();
+        for (int i = 0; i < 4; i++) { g_rec[i] = outs[2 + i]; outs[2 + i] = NULL; }
+        ret = 1;
+        goto cleanup;
+    }
+
+cleanup_dead:
+dead:
+    g_dead = 1;
+    fprintf(stderr, "[vcam/ort] backend disabled after error — vcam falls "
+                    "back to its other matting paths\n");
+cleanup:
+    if (in_src) A->ReleaseValue(in_src);
+    if (in_ds)  A->ReleaseValue(in_ds);
+    for (int i = 0; i < 6; i++)
+        if (outs[i]) A->ReleaseValue(outs[i]);
+    pthread_mutex_unlock(&g_mtx);
+    return ret;
+}
+
+void ort_rvm_reset(void)
+{
+    pthread_mutex_lock(&g_mtx);
+    if (g_sess && !g_dead) init_rec();
+    pthread_mutex_unlock(&g_mtx);
+}
+
+void ort_shutdown(void)
+{
+    pthread_mutex_lock(&g_mtx);
+    release_rec();
+    if (g_sess) { A->ReleaseSession(g_sess); g_sess = NULL; }
+    if (g_so)   { A->ReleaseSessionOptions(g_so); g_so = NULL; }
+    if (g_mi)   { A->ReleaseMemoryInfo(g_mi); g_mi = NULL; }
+    if (g_env)  { A->ReleaseEnv(g_env); g_env = NULL; }
+    g_alloc = NULL;   /* default allocator is not owned */
+    g_iw = g_ih = 0;
+    pthread_mutex_unlock(&g_mtx);
+}
+
+#else /* !VCAM_HAVE_ORT — stubs so everything links without ORT */
+
+bool ort_available(void) { return false; }
+
+const char *ort_version(void) { return "not built in"; }
+
+int ort_rvm_init(const char *p) { (void)p; return 0; }
+
+int ort_rvm_infer(const float *s, int w, int h, float *o)
+{ (void)s; (void)w; (void)h; (void)o; return 0; }
+
+void ort_rvm_reset(void) { }
+
+void ort_shutdown(void) { }
+
+#endif /* VCAM_HAVE_ORT */