webcam-loopback-manipulation-screensharing-and-stuff git · main
vcam: v4l2 loopback with overlays, filters, OpenCV and RVM matting
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.gzOpenCV 5 AND AI lol
.gitignore | 1 + INSTALL.md | 91 +++ Makefile | 126 +++- NOTICE | 47 ++ README.md | 67 ++- include/vcam.h | 13 + include/vcam_cv.h | 162 ++++++ scripts/vcam-setup | 109 ++++ scripts/vcam-tune | 31 +- src/filter.c | 48 ++ src/ipc.c | 68 +++ src/main.c | 2 + src/opencv_fx.cpp | 1651 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/opencv_stub.c | 67 +++ 14 files changed, 2472 insertions(+), 11 deletions(-) diff --git a/.gitignore b/.gitignore index efa7302..998000d 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ *.so.* vcam test_screen +.built-opencv-1 # Distribution archives *.tar.gz diff --git a/INSTALL.md b/INSTALL.md index cd86133..4a041c7 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -7,6 +7,7 @@ Wayland. - [Dependencies](#dependencies) - [Build & install](#build--install) +- [Optional: OpenCV filters](#optional-opencv-filters) - [One-time device setup (the Chromium fix)](#one-time-device-setup-the-chromium-fix) - [Verify](#verify) - [Uninstall](#uninstall) @@ -72,6 +73,96 @@ make install DESTDIR=/tmp/pkg PREFIX=/usr # staged, for packaging --- +## Optional: OpenCV filters + +vcam has seven extra filters powered by **OpenCV 5** — cartoon, +pencil-sketch, watercolor, optical-flow, background subtraction, face +effects, and person-segmentation background effects (see the OpenCV +section in [README.md](README.md)). They are **off by default**: the +normal build has no OpenCV dependency at all, and these filters simply +aren't compiled in. + +**OpenCV 5 is the recommended version** — the filters are written +OpenCV-5-first. Built against 5.x, they use the features new in that +release: + +- the **new graph-based DNN engine** (`ENGINE_AUTO`): 80%+ ONNX operator + coverage (vs ~22% in 4.x), shape inference, constant folding, and + operator fusion — the segmentation and face models load through it +- **first-class FP16** (`cv::hfloat`/`CV_16F`): the person-matte blend in + `personfx` runs at half precision, halving the memory traffic of its + heaviest per-frame step + +OpenCV 4.5–4.x also works; the same code then compiles a +classic-engine/FP32 fallback path, selected at compile time. Ask a +running vcam which path it has with `vcam-ctl opencv`. + +```bash +# OpenCV 5 dev files. If your distro still packages 4.x as +# libopencv-dev, build 5.x from source (github.com/opencv/opencv, +# branch 5.x) or use your distro's opencv5 package when available. +sudo apt install libopencv-dev + +# Build with OpenCV support +make OPENCV=1 +sudo make install # remembers the OPENCV=1 flavor automatically +``` + +**After any rebuild, restart the running vcam** — `vcam-ctl` talks to the +already-running process, which keeps serving the old binary until you +replace it: + +```bash +pkill vcam +vcam & +vcam-ctl opencv # should now report your OpenCV version + engine +``` + +The build finds OpenCV via pkg-config, probing the module names +`opencv5`, `opencv4`, and `opencv` in that order — note that an OpenCV 5 +install often still ships its pkg-config file under the `opencv4` name +for compatibility, which is fine: the version, not the module name, +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>`. + +### Model files (for `facefx` and `personfx`) + +The five classic OpenCV filters work immediately. The two DNN-based ones +need small ONNX model files, which you download once: + +```bash +vcam-setup --models # → ~/.local/share/vcam/models +# or system-wide: +sudo vcam-setup --models --system +``` + +This fetches two models, both free and permissively licensed: + +- **YuNet** face detector — ~230 KB, MIT license +- **PP-HumanSeg** person segmentation — a few MB, Apache-2.0 license +- **MobileFaceNet FER** expression recognition (for `moodfx`) — Apache-2.0 + +The `styleai` neural-style filter has its own optional pack (five +fast-neural-style networks, MIT license, ~6.5 MB each, from the ONNX +Model Zoo mirror on HuggingFace): + +```bash +vcam-setup --models-style +``` + +They're pulled from the official OpenCV model repository on HuggingFace. +If you'd rather place them yourself, drop the `.onnx` files in any of +`$VCAM_MODEL_DIR`, `~/.local/share/vcam/models`, or +`/usr/local/share/vcam/models` — vcam checks those in order. Until the +models are present, `facefx` and `personfx` pass the frame through +unchanged and print a one-time hint. + +Nothing about these filters is required: if you never build with +`OPENCV=1`, vcam is exactly the pure-C program it always was. + +--- + ## One-time device setup (the Chromium fix) Chromium-family browsers pick the first `/dev/video*` they see. If that's diff --git a/Makefile b/Makefile index bdbfe45..643feef 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,9 @@ # SPDX-License-Identifier: GPL-2.0-only # vcam — Copyright (C) 2026 the vcam authors. GPL-2.0, see LICENSE. + CC := gcc +CXX := g++ + CFLAGS := -std=c11 -O2 -Wall -Wextra -Wpedantic \ -D_POSIX_C_SOURCE=200809L \ -I include \ @@ -11,37 +14,143 @@ LDFLAGS := $(shell pkg-config --libs libavcodec libavformat libavutil libswscale $(shell pkg-config --libs libpng) \ -lpthread -lm -# Installation paths — overridable on the command line: +# ── Optional OpenCV support ───────────────────────────────────────── +# Off by default: vcam builds as a pure-C program with no OpenCV +# dependency, and the cv_* effects resolve to no-op stubs. +# +# make # no OpenCV (default) +# make OPENCV=1 # enable the OpenCV-backed filters +# +# When enabled, the OpenCV effects live in a small C++ shim +# (src/opencv_fx.cpp) that exposes a flat C ABI. The final binary is +# then linked with the C++ driver so the C++ runtime is pulled in. +# +# The filters are written OpenCV-5-first: built against 5.x they use +# the new graph-based DNN engine (ENGINE_AUTO — 80%+ ONNX operator +# coverage, shape inference, operator fusion) and first-class FP16 +# (cv::hfloat) arithmetic for the segmentation blend. Built against +# 4.5–4.x they compile the classic-engine/FP32 fallback path, chosen +# at compile time from CV_VERSION_MAJOR. Run 'vcam-ctl opencv' on a +# live vcam to see which path your build uses. +# +# The pkg-config MODULE NAME is not tied to the major version and +# varies by packaging: it may be 'opencv5', 'opencv4' (the name used +# for "4 and later" — an OpenCV 5 install often still ships +# opencv4.pc), or plain 'opencv'. We probe all three and pick the +# first that exists, then require version >= 4.5. Override with +# make OPENCV=1 OPENCV_PC=<name> +# Sticky default: if a previous build left a config stamp +# (.built-opencv-0/1), default OPENCV to that value, so +# make OPENCV=1 +# 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-*))) +ifeq ($(strip $(LAST_OPENCV)),) + OPENCV ?= 0 +else + OPENCV ?= $(LAST_OPENCV) +endif + +ifeq ($(OPENCV),1) + # Let the user force a specific pkg-config module name if they want. + ifndef OPENCV_PC + # First module in the list that pkg-config knows about wins. + OPENCV_PC := $(firstword $(foreach m,opencv5 opencv4 opencv,\ + $(shell pkg-config --exists $(m) 2>/dev/null && echo $(m)))) + endif + ifeq ($(strip $(OPENCV_PC)),) + $(error OPENCV=1 but no OpenCV pkg-config module (tried opencv5, opencv4, opencv). \ + Install OpenCV 4.5+ dev files, set OPENCV_PC=<name>, or build without OPENCV=1) + endif + # The module must actually exist (covers a hand-set OPENCV_PC typo). + ifneq ($(shell pkg-config --exists $(OPENCV_PC) && echo ok),ok) + $(error OpenCV pkg-config module '$(OPENCV_PC)' not found. \ + Check the name (try 'pkg-config --list-all | grep -i opencv'), or unset OPENCV=1) + endif + # Require a version new enough to have the APIs the filters use. + ifneq ($(shell pkg-config --atleast-version=4.5 $(OPENCV_PC) && echo ok),ok) + $(error OpenCV '$(OPENCV_PC)' is version $(shell pkg-config --modversion $(OPENCV_PC)); \ + vcam needs >= 4.5 (FaceDetectorYN + dnn). Upgrade OpenCV or unset OPENCV=1) + endif + CV_VER := $(shell pkg-config --modversion $(OPENCV_PC)) + # -isystem instead of -I: OpenCV's own headers shouldn't trip our -Wall + CV_CFLAGS := $(patsubst -I%,-isystem %,$(shell pkg-config --cflags $(OPENCV_PC))) + CV_LIBS := $(shell pkg-config --libs $(OPENCV_PC)) + CXXFLAGS := -std=c++17 -O2 -Wall -Wextra -I include $(CV_CFLAGS) + CV_OBJ := src/opencv_fx.o + LDFLAGS += $(CV_LIBS) + LINK := $(CXX) + CFLAGS += -DVCAM_HAVE_OPENCV=1 + $(info vcam: OpenCV enabled — module '$(OPENCV_PC)' version $(CV_VER)) +else + CV_OBJ := src/opencv_stub.o + LINK := $(CC) + CFLAGS += -DVCAM_HAVE_OPENCV=0 +endif + +# ── Install paths (overridable) ───────────────────────────────────── # make install (default: /usr/local) # make install PREFIX=$HOME/.local (user-local) -# make install PREFIX=/usr (system-wide) # make install DESTDIR=/tmp/stage (staged install for packaging) PREFIX ?= /usr/local BINDIR ?= $(PREFIX)/bin DOCDIR ?= $(PREFIX)/share/doc/vcam +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 -OBJS := $(SRCS:.c=.o) +OBJS := $(SRCS:.c=.o) $(CV_OBJ) BIN := vcam TEST := test_screen +# Build-config stamp: encodes the OPENCV setting the binary was linked +# with. Toggling OPENCV=0/1 changes the stamp name, which forces a +# relink — otherwise a stale vcam of the previous flavor could survive +# (both opencv_fx.o and opencv_stub.o may exist from earlier builds, +# and the binary would look up-to-date). This also makes +# '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) + .PHONY: all clean install uninstall all: $(BIN) $(TEST) -$(BIN): $(OBJS) - $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) +$(CONFIG_STAMP): + @rm -f .built-opencv-* + @touch $@ + +$(BIN): $(OBJS) $(CONFIG_STAMP) + $(LINK) -o $@ $(OBJS) $(LDFLAGS) +ifeq ($(OPENCV),1) + @echo "vcam: linked WITH OpenCV filters ($(OPENCV_PC) $(CV_VER))" +else + @echo "vcam: linked WITHOUT OpenCV filters (build with 'make OPENCV=1' to enable)" +endif $(TEST): src/test_screen.c $(CC) -std=c11 -O2 -Wall -D_POSIX_C_SOURCE=200809L -D_DEFAULT_SOURCE \ -o $@ src/test_screen.c -src/%.o: src/%.c include/vcam.h +# C objects depend on both headers so an ABI change triggers a rebuild. +src/%.o: src/%.c include/vcam.h include/vcam_cv.h $(CC) $(CFLAGS) -c -o $@ $< +# The OpenCV shim (only compiled when OPENCV=1). +src/opencv_fx.o: src/opencv_fx.cpp include/vcam_cv.h + $(CXX) $(CXXFLAGS) -c -o $@ $< + install: $(BIN) +ifeq ($(OPENCV),1) + @echo "Installing vcam WITH OpenCV filters ($(OPENCV_PC) $(CV_VER))." +else + @echo "Installing vcam WITHOUT OpenCV filters." + @echo " (If you built with 'make OPENCV=1', install with 'sudo make install OPENCV=1'" + @echo " or this step would relink and install the non-OpenCV flavor.)" +endif install -d $(DESTDIR)$(BINDIR) install -m 755 $(BIN) $(DESTDIR)$(BINDIR)/ install -m 755 scripts/vcam-ctl $(DESTDIR)$(BINDIR)/ @@ -56,6 +165,9 @@ install: $(BIN) @echo @echo "Installed to $(DESTDIR)$(BINDIR)/ (docs in $(DESTDIR)$(DOCDIR)/)" @echo "Make sure that's on your PATH." +ifeq ($(OPENCV),1) + @echo "OpenCV filters are built in. Fetch the models with: vcam-setup --models" +endif uninstall: rm -f $(DESTDIR)$(BINDIR)/$(BIN) @@ -65,4 +177,4 @@ uninstall: rm -rf $(DESTDIR)$(DOCDIR) clean: - rm -f $(OBJS) $(BIN) $(TEST) + rm -f $(SRCS:.c=.o) src/opencv_fx.o src/opencv_stub.o $(BIN) $(TEST) .built-opencv-* diff --git a/NOTICE b/NOTICE index f5c581f..3ac0a3a 100644 --- a/NOTICE +++ b/NOTICE @@ -65,6 +65,53 @@ restrictions on vcam's own source. is not part of vcam's source or binary. +Optional OpenCV components +========================== + +These are used ONLY when vcam is built with `make OPENCV=1`. The default +build does not link or depend on any of them. + + OpenCV 5 (linked when OPENCV=1) + Licensed under the Apache License 2.0. Used for the optional cv* + filters (cartoon, pencil, stylize, optical flow, background + subtraction, face and person effects). https://opencv.org + + Note on licensing: OpenCV is an optional, separately-installed system + library that vcam links against only when explicitly built with + OPENCV=1. vcam does not bundle or redistribute OpenCV. If you intend + to redistribute a binary built with OPENCV=1, be aware that Apache + 2.0 and GPL-2.0-only are considered incompatible for forming a single + combined work; the default vcam build links no Apache-2.0 code and is + unaffected. Building with OPENCV=1 for personal use is fine. + + YuNet face detection model — face_detection_yunet_2023mar.onnx + Licensed under the MIT License. Downloaded on request by + 'vcam-setup --models' from the OpenCV model repository; not bundled + with vcam. Copyright (C) Shenzhen Institute of Artificial + Intelligence and Robotics for Society. + https://github.com/ShiqiYu/libfacedetection + + PP-HumanSeg segmentation model — human_segmentation_pphumanseg_2023mar.onnx + Licensed under the Apache License 2.0. Downloaded on request by + 'vcam-setup --models'; not bundled with vcam. Originates from + PaddlePaddle/PaddleSeg. https://github.com/PaddlePaddle/PaddleSeg + + MobileFaceNet facial expression model — + facial_expression_recognition_mobilefacenet_2022july.onnx + Licensed under the Apache License 2.0. Downloaded on request by + 'vcam-setup --models'; not bundled. From the OpenCV Zoo. + + Fast neural style transfer models — mosaic-9 / candy-9 / + rain-princess-9 / udnie-9 / pointilism-9 (.onnx) + Licensed under the MIT License (ONNX Project Contributors). + Downloaded on request by 'vcam-setup --models-style' from the ONNX + Model Zoo mirror (huggingface.co/onnxmodelzoo); not bundled. + Originals from pytorch/examples fast_neural_style. + + 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. + + The fonts embedded in filter.c (the 8x8 ASCII-art glyph ramp and the VHS timecode digits) are original bitmap data created for this project and are covered by vcam's GPL-2.0 license along with the rest of the source. diff --git a/README.md b/README.md index a10da09..9309bc6 100644 --- a/README.md +++ b/README.md @@ -299,7 +299,7 @@ shown above. --- -## Filters (100 total, 11 categories) +## Filters (111 total, 12 categories) Filters run in chain order on every frame from the webcam, *before* overlays are composited. Every filter has a primary parameter; many @@ -407,7 +407,70 @@ blend), plus `emboss dither tiles zoompulse oilslick`. | `symmetry` | mode | face-symmetry mirrors — 0 left→right, 1 right→left, 2 quad kaleidoscope | | `timebubble` | delay, radius | a glowing bubble drifts around; inside it you see seconds into the past | -### mathwarp — warp *and recolor* the image with your own formulas +### OpenCV-backed set (optional — build with `make OPENCV=1`) + +These seven use OpenCV's computer-vision algorithms for effects the +hand-rolled filters can't do: real motion analysis, background +segmentation, and face detection. They're **opt-in at build time** — +the default build has no OpenCV dependency and these filters simply +aren't present. + +They're written **OpenCV-5-first**: built against OpenCV 5, the DNN +filters load their models on the **new graph-based DNN engine** +(`ENGINE_AUTO` — 80%+ ONNX operator coverage, shape inference, operator +fusion) and the person-matte blend runs in **first-class FP16** +(`cv::hfloat`), both new in 5.0. Against OpenCV 4.5+ the same code +compiles a classic-engine/FP32 fallback. Check which path your build +uses with `vcam-ctl opencv`. See +[INSTALL.md](INSTALL.md#optional-opencv-filters) to enable the filters +and fetch the (free, tiny) model files. + +| Name | Knob | Effect | Needs model | +|---|---|---|---| +| `cvcartoon` | strength | edge-preserving bilateral smoothing + adaptive ink outlines — a proper cartoon, not a posterize | no | +| `cvpencil` | color (1/0) | OpenCV's non-photorealistic pencil sketch; 1 keeps color, 0 is graphite | no | +| `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** | +| `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** | +| `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 | + +They're laptop-friendly: classic effects run on the CPU at 720p, and the +two DNN filters run inference on a downscaled frame every few frames +(the models are ~85 KB and ~6 MB, milliseconds per inference). If a model +file is missing, that filter passes the frame through untouched and prints +a one-time hint to run `vcam-setup --models`. + +```bash +vcam-ctl filter add cvcartoon 0.7 +vcam-ctl filter add opticalflow 0.7 # wave your hand, watch it flow +vcam-ctl filter add facefx 2 # googly eyes +vcam-ctl filter add personfx 0 # blur everything but you +vcam-ctl filter bgimage ~/pics/beach.jpg # then: +vcam-ctl filter add personfx 3 # you, at the beach +vcam-ctl filter add styleai 2 0.9 256 # live rain-princess painting, high quality +vcam-ctl filter add moodfx 2 # smile → confetti rains down +vcam-ctl filter add personfx 4 # invisibility cloak +vcam-ctl filter add personfx 5 # neon silhouette in a black room +vcam-ctl filter add personfx 6 # CLONE ARMY: three of you +vcam-ctl filter add facefx 3 # bighead mode +vcam-ctl filter add facefx 4 # deal-with-it sunglasses +vcam-ctl filter add moodfx 3 # you are the emoji now +vcam-ctl filter add paintflow 1.5 # smear reality by moving +vcam-ctl filter add personfx 7 # WINDOW-3D: move your head, see parallax +vcam-ctl filter add personfx 8 # your past selves follow you +vcam-ctl filter add facefx 5 # laser eyes +vcam-ctl filter add facefx 6 # bobblehead +vcam-ctl filter add facefx 7 # third eye +vcam-ctl filter add personfx 10 # hologram you +vcam-ctl filter add speedlines 1.5 # anime dodge lines +``` + + `mathwarp` has two independent expression sets. **Warp** moves pixels; **color** repaints them. Use either or both. diff --git a/include/vcam.h b/include/vcam.h index 14a74d7..5d1b5b3 100644 --- a/include/vcam.h +++ b/include/vcam.h @@ -209,6 +209,19 @@ typedef enum { FX_SYMMETRY, /* face symmetry mirrors (left/right/quad) */ FX_TIMEBUBBLE, /* drifting bubble showing N seconds into the past */ + /* ── OpenCV-backed (optional; built with OPENCV=1) ── */ + FX_CV_CARTOON, /* edge-preserving bilateral cartoon + ink outlines */ + FX_CV_PENCIL, /* non-photorealistic pencil sketch */ + FX_CV_STYLIZE, /* watercolor/poster stylization */ + FX_CV_FLOW, /* dense optical-flow motion visualization */ + FX_CV_BGSUB, /* MOG2: moving foreground vivid, static bg dimmed */ + FX_CV_FACE, /* YuNet face detection: blur / ring / googly-eyes */ + FX_CV_PERSON, /* PP-HumanSeg: blur/spotlight/gradient/your-image bg */ + FX_CV_STYLE, /* live neural style transfer (5 styles, blend, size) */ + FX_CV_MOOD, /* emotion-reactive: aura / HUD / party / emoji */ + FX_CV_PAINT, /* optical-flow paint smear: motion drags reality */ + FX_CV_SPEED, /* anime speed lines when you move fast */ + FX_UNKNOWN, } FilterType; diff --git a/include/vcam_cv.h b/include/vcam_cv.h new file mode 100644 index 0000000..c737bc7 --- /dev/null +++ b/include/vcam_cv.h @@ -0,0 +1,162 @@ +/* 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_cv.h — C ABI for the optional OpenCV-backed effects. + * + * vcam's core is C11; OpenCV 5 is a C++17 library. To keep the core + * pure C and OpenCV strictly optional, all OpenCV code lives behind + * this flat C interface, implemented either by: + * + * src/opencv_fx.cpp — the real thing (built when OPENCV=1) + * src/opencv_stub.c — no-op fallbacks (built otherwise) + * + * Every function operates on a BGR24 buffer in place (data/width/ + * height/stride matching struct Frame). All of them are safe to call + * even when OpenCV is unavailable — the stub versions simply leave the + * frame untouched, and cv_available() returns 0. + * + * Functions never throw across this boundary: the C++ side wraps every + * body in a try/catch and degrades to a no-op on error, so a bad model + * file or an unexpected frame can never crash the pipeline. + */ + +#ifndef VCAM_CV_H +#define VCAM_CV_H + +#include <stdbool.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/* True when vcam was built with OpenCV support (OPENCV=1). The stub + * build returns false. Cheap; may be called every frame. */ +bool cv_available(void); + +/* Human-readable OpenCV version string ("5.0.0"), or "none" in the + * stub build. Never NULL. */ +const char *cv_version(void); + +/* One-line description of the OpenCV generation and DNN engine in this + * build, e.g. "OpenCV 5.0.0 — new DNN graph engine (ENGINE_AUTO), FP16 + * blend" or "OpenCV 4.6.0 — classic DNN engine, FP32 blend", or + * "opencv not built in" for the stub. Never NULL. */ +const char *cv_engine_info(void); + +/* Directory the DNN filters look in for their .onnx model files. + * Defaults to, in order of preference: + * $VCAM_MODEL_DIR, then ~/.local/share/vcam/models, + * then /usr/local/share/vcam/models, then /usr/share/vcam/models. + * Returns the first that exists, or the compiled default. Never NULL. */ +const char *cv_model_dir(void); + +/* ── Classic-CV effects (no model files needed) ── + * These use only imgproc / photo / video / objdetect and run realtime + * on a laptop CPU. Each is self-contained and manages its own state. */ + +/* Edge-preserving cartoon: bilateral smoothing + adaptive-threshold + * ink outlines. strength 0..1 (0 → default). */ +void cv_fx_cartoon(unsigned char *data, int w, int h, int stride, + float strength); + +/* Non-photorealistic pencil sketch (photo::pencilSketch). + * color != 0 keeps color; 0 gives graphite gray. */ +void cv_fx_pencil(unsigned char *data, int w, int h, int stride, + int color); + +/* photo::stylization — a vivid watercolor/poster look. strength 0..1. */ +void cv_fx_stylize(unsigned char *data, int w, int h, int stride, + float strength); + +/* Dense optical-flow visualization (Farnebäck): motion direction is + * mapped to hue, magnitude to brightness, blended over the frame. + * mix 0..1 = how much flow color vs. original (0 → 0.6). */ +void cv_fx_flow(unsigned char *data, int w, int h, int stride, + float mix); + +/* MOG2 background subtraction: foreground (moving) pixels are kept in + * color, the learned static background is darkened/desaturated. + * Person walks in and "lights up" against a dim room. + * sensitivity 0..1 (0 → default). */ +void cv_fx_bgsub(unsigned char *data, int w, int h, int stride, + float sensitivity); + +/* ── DNN effects (need an .onnx model in cv_model_dir()) ── + * If the model file is missing these degrade gracefully: the frame is + * left unchanged and a one-time warning is printed. Inference runs on + * a downscaled copy and is internally rate-limited, so they stay light + * on a laptop. */ + +/* YuNet face detection. Draws a stylized effect on each detected face. + * mode selects the look: + * 0 = privacy blur (pixelate faces) + * 1 = glossy highlight ring + landmark dots + * 2 = "googly eyes" drawn at the eye landmarks + * Needs face_detection_yunet_2023mar.onnx. */ +void cv_fx_face(unsigned char *data, int w, int h, int stride, + int mode); + +/* PP-HumanSeg person segmentation → background effect. + * mode selects what happens to the background: + * 0 = blur the background (portrait mode) + * 1 = desaturate/darken the background (spotlight the person) + * 2 = replace background with a moving color gradient + * Needs human_segmentation_pphumanseg_2023mar.onnx. */ +void cv_fx_bgblur(unsigned char *data, int w, int h, int stride, + int mode); + +/* Live neural style transfer (fast-neural-style, 5 styles). + * style: 0=mosaic 1=candy 2=rain-princess 3=udnie 4=pointilism + * blend: 0..1 stylized-vs-original mix (0 -> 0.85) + * size: inference resolution 96..384, the quality<->speed knob + * (0 -> 192). Needs the style .onnx files + * ('vcam-setup --models-style'). */ +void cv_fx_style(unsigned char *data, int w, int h, int stride, + int style, float blend, float size); + +/* Emotion-reactive effects: a facial-expression model (7 emotions) + * reads your mood every few frames and the effect responds. + * mode: 0 = aura (colored vignette breathing with the emotion) + * 1 = HUD (labeled box + confidence bar) + * 2 = party (happy->confetti, sad->rain, surprised->flash, + * angry->screen shake) + * gain: sensitivity multiplier 0..2 (0 -> 1). + * Needs the YuNet face model AND the FER model ('vcam-setup --models'). */ +void cv_fx_mood(unsigned char *data, int w, int h, int stride, + int mode, float gain); + +/* Flow-advected paint canvas: dense optical flow drags a persistent + * canvas — anything that moves smears reality like wet paint. + * strength: flow multiplier 0..3 (0 -> 1) + * decay: canvas persistence 0.80..0.99 (0 -> 0.93) */ +void cv_fx_paintflow(unsigned char *data, int w, int h, int stride, + float strength, float decay); + +/* Anime speed lines: when the mean optical flow exceeds a threshold, + * white motion lines streak in from the border opposite the movement. + * sens 0..3 (0->1), density 0..1 (0->0.5). */ +void cv_fx_speedlines(unsigned char *data, int w, int h, int stride, + float sens, float density); + +/* Set/replace the user background image used by cv_fx_bgblur mode 3 + * (person keeps the camera, background becomes this image, cover- + * scaled). Returns 1 on success, 0 if the file can't be loaded. + * cv_clear_bg_image() removes it (mode 3 then shows the gradient). */ +int cv_set_bg_image(const char *path); +void cv_clear_bg_image(void); + +/* Free any lazily-created OpenCV state (detectors, nets, bg models, + * flow buffers). Called at shutdown; safe to call in the stub build. */ +void cv_shutdown(void); + +#ifdef __cplusplus +} +#endif + +#endif /* VCAM_CV_H */ diff --git a/scripts/vcam-setup b/scripts/vcam-setup index 9a54782..77fc64d 100755 --- a/scripts/vcam-setup +++ b/scripts/vcam-setup @@ -25,9 +25,118 @@ if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then echo " vcam-setup show current state and diagnosis" echo " sudo vcam-setup --install install /etc/modprobe.d/vcam.conf" 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" exit 0 fi +# ── OpenCV model download ──────────────────────────────────── +# Fetches the ONNX models the optional OpenCV DNN filters need +# (facefx, personfx). Both are small and permissively licensed +# (YuNet: MIT, PP-HumanSeg: Apache-2.0). Installs into a per-user +# data dir by default; override with VCAM_MODEL_DIR or --system. +if [ "${1:-}" = "--models" ]; 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 + + # name|url pairs (HuggingFace raw, resolve/main) + YUNET_URL="https://huggingface.co/opencv/face_detection_yunet/resolve/main/face_detection_yunet_2023mar.onnx" + SEG_URL="https://huggingface.co/opencv/human_segmentation_pphumanseg/resolve/main/human_segmentation_pphumanseg_2023mar.onnx" + FER_URL="https://huggingface.co/opencv/facial_expression_recognition/resolve/main/facial_expression_recognition_mobilefacenet_2022july.onnx" + YUNET_FILE="face_detection_yunet_2023mar.onnx" + SEG_FILE="human_segmentation_pphumanseg_2023mar.onnx" + FER_FILE="facial_expression_recognition_mobilefacenet_2022july.onnx" + + # pick a downloader + 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 to download models." >&2 + exit 1 + fi + + echo "Model directory: $MODEL_DIR" + if ! mkdir -p "$MODEL_DIR" 2>/dev/null; then + echo "Error: cannot create $MODEL_DIR (try --system with sudo, or set VCAM_MODEL_DIR)." >&2 + exit 1 + fi + + rc=0 + for pair in "$YUNET_FILE|$YUNET_URL" "$SEG_FILE|$SEG_URL" "$FER_FILE|$FER_URL"; do + f=${pair%%|*} + u=${pair#*|} + if [ -s "$MODEL_DIR/$f" ]; then + echo " already have $f — skipping" + continue + fi + echo " downloading $f ..." + # shellcheck disable=SC2086 + if $DL "$MODEL_DIR/$f.part" "$u" 2>/dev/null && [ -s "$MODEL_DIR/$f.part" ]; then + mv "$MODEL_DIR/$f.part" "$MODEL_DIR/$f" + echo " ok: $MODEL_DIR/$f" + else + rm -f "$MODEL_DIR/$f.part" + echo " FAILED to fetch $f" >&2 + rc=1 + fi + done + + if [ "$rc" -eq 0 ]; then + echo "" + echo "Models ready. The OpenCV filters (facefx, personfx, moodfx) can find them now." + echo "If you built without OpenCV, rebuild with: make OPENCV=1 && sudo make install" + fi + exit "$rc" +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 +# the ONNX Model Zoo mirror on HuggingFace. +if [ "${1:-}" = "--models-style" ]; 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 to download models." >&2 + exit 1 + fi + echo "Model directory: $MODEL_DIR" + mkdir -p "$MODEL_DIR" || { echo "Error: cannot create $MODEL_DIR" >&2; exit 1; } + rc=0 + for name in mosaic-9 candy-9 rain-princess-9 udnie-9 pointilism-9; do + f="$name.onnx" + u="https://huggingface.co/onnxmodelzoo/$name/resolve/main/$f" + if [ -s "$MODEL_DIR/$f" ]; then + echo " already have $f — skipping" + continue + fi + echo " downloading $f ..." + # shellcheck disable=SC2086 + if $DL "$MODEL_DIR/$f.part" "$u" 2>/dev/null && [ -s "$MODEL_DIR/$f.part" ]; then + mv "$MODEL_DIR/$f.part" "$MODEL_DIR/$f" + echo " ok: $MODEL_DIR/$f" + else + rm -f "$MODEL_DIR/$f.part" + echo " FAILED to fetch $f" >&2 + rc=1 + fi + done + [ "$rc" -eq 0 ] && { echo ""; echo "Styles ready. Try: vcam-ctl filter add styleai 1"; } + exit "$rc" +fi + INIT_SYSTEM="" detect_init() { if [ -d /run/systemd/system ]; then diff --git a/scripts/vcam-tune b/scripts/vcam-tune index f3b635c..0e8b6d5 100755 --- a/scripts/vcam-tune +++ b/scripts/vcam-tune @@ -84,11 +84,11 @@ n_params_for() { neon|kaleidoscope|wave) echo 4 ;; chromashift|glitch|vignette|feedback|ripples|life|plasma) echo 3 ;; swirl|pinch|bulge|shuffle|rain|lightpaint|hologram|duotone|spotlight) echo 3 ;; - predator|liquid|clones) echo 3 ;; + predator|liquid|clones|styleai) echo 3 ;; contour|fireworks|infinity|moire) echo 2 ;; cartoon|drift|slitscan|mosh|zoompulse|oilslick|ascii|sketch) echo 2 ;; shards|portal|heattrail|wormhole|magnet|nightvision|badtv|ghosts) echo 2 ;; - meltdown|rotozoom|starfield|lightning|scatter|vhs|outline|timebubble) echo 2 ;; + meltdown|rotozoom|starfield|lightning|scatter|vhs|outline|timebubble|moodfx|paintflow|speedlines) echo 2 ;; *) echo 1 ;; esac } @@ -207,6 +207,22 @@ param_label() { outline:2) echo "huespd" ;; timebubble:1) echo "delay" ;; timebubble:2) echo "radius" ;; + cvcartoon:1) echo "strength" ;; + cvpencil:1) echo "color" ;; + cvstylize:1) echo "strength" ;; + opticalflow:1) echo "mix" ;; + bgsub:1) echo "sens" ;; + facefx:1) echo "mode" ;; + personfx:1) echo "mode" ;; + styleai:1) echo "style" ;; + styleai:2) echo "blend" ;; + styleai:3) echo "size" ;; + moodfx:1) echo "mode" ;; + moodfx:2) echo "gain" ;; + speedlines:1) echo "sens" ;; + speedlines:2) echo "density" ;; + paintflow:1) echo "strength" ;; + paintflow:2) echo "decay" ;; *:1) echo "param" ;; *) echo "p$slot" ;; esac @@ -275,6 +291,10 @@ param_step() { nightvision:2) echo 5 ;; badtv:2) echo 0.5 ;; ghosts:2) echo 0.5 ;; + styleai:2) echo 0.05 ;; + styleai:3) echo 32 ;; + moodfx:2) echo 0.1 ;; + paintflow:2) echo 0.01 ;; clones:2) echo 0.5 ;; clones:3) echo 0.05 ;; meltdown:2) echo 0.05 ;; @@ -330,6 +350,8 @@ default_step() { scatter|vhs) echo 0.05 ;; outline|symmetry) echo 1 ;; timebubble) echo 0.25 ;; + cvcartoon|cvstylize|opticalflow|bgsub|paintflow|speedlines) echo 0.05 ;; + cvpencil|facefx|personfx|styleai|moodfx) echo 1 ;; *) echo 0.1 ;; esac } @@ -419,6 +441,10 @@ default_param_for() { outline) echo 2 ;; symmetry) echo 0 ;; timebubble) echo 1.5 ;; + cvcartoon|cvstylize|opticalflow) echo 0.6 ;; + bgsub) echo 0.5 ;; + cvpencil) echo 1 ;; + facefx|personfx|styleai|moodfx) echo 0 ;; *) echo 1 ;; esac } @@ -476,6 +502,7 @@ FILTER_CATEGORIES=( "Artistic:ascii duotone sketch" "AI-Craze:predator shards portal heattrail wormhole magnet liquid nightvision badtv ghosts" "Craze-2:clones meltdown rotozoom starfield lightning scatter vhs outline symmetry timebubble" + "OpenCV:cvcartoon cvpencil cvstylize opticalflow bgsub facefx personfx styleai moodfx paintflow speedlines" ) # Show an interactive picker, return chosen filter name on stdout diff --git a/src/filter.c b/src/filter.c index 3c187d5..7b5442e 100644 --- a/src/filter.c +++ b/src/filter.c @@ -15,6 +15,7 @@ */ #include "vcam.h" +#include "vcam_cv.h" #include <stdio.h> #include <stdlib.h> @@ -165,6 +166,28 @@ static const struct { const char *name; FilterType t; } NAMES[] = { {"symmetry", FX_SYMMETRY}, {"timebubble", FX_TIMEBUBBLE}, {"pastbubble", FX_TIMEBUBBLE}, + /* OpenCV-backed (optional) */ + {"cvcartoon", FX_CV_CARTOON}, + {"cvpencil", FX_CV_PENCIL}, + {"sketch2", FX_CV_PENCIL}, + {"cvstylize", FX_CV_STYLIZE}, + {"watercolor", FX_CV_STYLIZE}, + {"opticalflow", FX_CV_FLOW}, + {"cvflow", FX_CV_FLOW}, + {"bgsub", FX_CV_BGSUB}, + {"motionmask", FX_CV_BGSUB}, + {"facefx", FX_CV_FACE}, + {"face", FX_CV_FACE}, + {"personfx", FX_CV_PERSON}, + {"portrait", FX_CV_PERSON}, + {"styleai", FX_CV_STYLE}, + {"neuralstyle", FX_CV_STYLE}, + {"moodfx", FX_CV_MOOD}, + {"emotion", FX_CV_MOOD}, + {"paintflow", FX_CV_PAINT}, + {"smear", FX_CV_PAINT}, + {"speedlines", FX_CV_SPEED}, + {"anime", FX_CV_SPEED}, /* new effect additions */ {"saturate", FX_SATURATE}, {"crt", FX_CRT}, @@ -286,6 +309,18 @@ float filter_default_param(FilterType t) case FX_OUTLINE: return 2.0f; case FX_SYMMETRY: return 0.0f; case FX_TIMEBUBBLE: return 1.5f; + /* OpenCV-backed */ + case FX_CV_CARTOON: return 0.6f; + case FX_CV_PENCIL: return 1.0f; /* 1 = keep color, 0 = graphite */ + case FX_CV_STYLIZE: return 0.6f; + case FX_CV_FLOW: return 0.6f; + case FX_CV_BGSUB: return 0.5f; + case FX_CV_FACE: return 0.0f; /* mode 0 = privacy blur */ + case FX_CV_PERSON: return 0.0f; /* mode 0 = background blur */ + case FX_CV_STYLE: return 0.0f; /* style 0 = mosaic */ + case FX_CV_MOOD: return 0.0f; /* mode 0 = aura */ + case FX_CV_PAINT: return 1.0f; + case FX_CV_SPEED: return 1.0f; default: return 0.0f; } } @@ -5860,6 +5895,19 @@ void filter_chain_apply(FilterChain *fc, Frame *frame) case FX_OUTLINE: fx_outline(frame, f->param, f->param2); break; case FX_SYMMETRY: fx_symmetry(frame, f->param); break; case FX_TIMEBUBBLE: fx_timebubble(frame, f->param, f->param2); break; + /* OpenCV-backed effects operate on the whole BGR24 frame. + * In the non-OpenCV build these resolve to no-op stubs. */ + case FX_CV_CARTOON: cv_fx_cartoon(frame->data, frame->width, frame->height, frame->stride, f->param); break; + case FX_CV_PENCIL: cv_fx_pencil (frame->data, frame->width, frame->height, frame->stride, (int)f->param); break; + case FX_CV_STYLIZE: cv_fx_stylize(frame->data, frame->width, frame->height, frame->stride, f->param); break; + case FX_CV_FLOW: cv_fx_flow (frame->data, frame->width, frame->height, frame->stride, f->param); break; + case FX_CV_BGSUB: cv_fx_bgsub (frame->data, frame->width, frame->height, frame->stride, f->param); break; + case FX_CV_FACE: cv_fx_face (frame->data, frame->width, frame->height, frame->stride, (int)f->param); break; + case FX_CV_PERSON: cv_fx_bgblur (frame->data, frame->width, frame->height, frame->stride, (int)f->param); break; + case FX_CV_STYLE: cv_fx_style (frame->data, frame->width, frame->height, frame->stride, (int)f->param, f->param2, f->param3); break; + case FX_CV_MOOD: cv_fx_mood (frame->data, frame->width, frame->height, frame->stride, (int)f->param, f->param2); break; + case FX_CV_PAINT: cv_fx_paintflow(frame->data, frame->width, frame->height, frame->stride, f->param, f->param2); break; + case FX_CV_SPEED: cv_fx_speedlines(frame->data, frame->width, frame->height, frame->stride, f->param, f->param2); break; default: break; } } diff --git a/src/ipc.c b/src/ipc.c index 1670f64..ddfc4d0 100644 --- a/src/ipc.c +++ b/src/ipc.c @@ -25,6 +25,7 @@ */ #include "vcam.h" +#include "vcam_cv.h" #include <stdio.h> #include <stdlib.h> @@ -295,6 +296,34 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg) send_line(client_fd, "OK outline <thick> [<huespd>](*) marching-ants lasso traces whatever MOVES"); send_line(client_fd, "OK symmetry <mode> face symmetry: 0=left mirrored, 1=right, 2=quad"); send_line(client_fd, "OK timebubble <delay_s> [<radius>](*) a drifting bubble shows THE PAST inside it"); + send_line(client_fd, "OK"); + if (cv_available()) { + char cvline[256]; + snprintf(cvline, sizeof cvline, "OK OpenCV-backed (%s):", cv_engine_info()); + send_line(client_fd, cvline); + } else { + send_line(client_fd, "OK OpenCV-backed (NOT in this build — rebuild with 'make OPENCV=1' to enable):"); + } + send_line(client_fd, "OK cvcartoon <strength> edge-preserving cartoon with ink outlines"); + send_line(client_fd, "OK cvpencil <color> pencil sketch: 1=color, 0=graphite"); + send_line(client_fd, "OK cvstylize <strength> watercolor / poster stylization"); + send_line(client_fd, "OK opticalflow <mix> motion visualized as flowing color"); + send_line(client_fd, "OK bgsub <sensitivity> moving foreground vivid, static background dimmed"); + send_line(client_fd, "OK facefx <mode> YuNet faces: 0=blur 1=ring+dots 2=googly-eyes (needs model)"); + send_line(client_fd, "OK personfx <mode> person seg (needs model): 0=blur-bg 1=spotlight 2=gradient-bg"); + send_line(client_fd, "OK 3=YOUR-image-bg (filter bgimage <path>) 4=INVISIBILITY CLOAK 5=neon person"); + 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 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 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)"); return; } @@ -421,6 +450,33 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg) return; } + if (strcmp(sub, "bgimage") == 0) { + /* filter bgimage <path> — background image for personfx mode 3 + * filter bgimage off — remove it (mode 3 falls back to gradient) */ + char *path = strtok_r(NULL, "", &save); /* rest of line (paths may have spaces) */ + while (path && (*path == ' ' || *path == '\t')) path++; + if (!path || !*path) { + send_line(client_fd, "ERR usage: filter bgimage </abs/path/to/image.jpg | off>"); + send_line(client_fd, "ERR used by: filter add personfx 3 (person stays, background becomes your image)"); + return; + } + if (!strcmp(path, "off") || !strcmp(path, "none")) { + cv_clear_bg_image(); + send_line(client_fd, "OK background image cleared (personfx 3 shows the gradient)"); + return; + } + if (!cv_available()) { + send_line(client_fd, "ERR this build has no OpenCV (rebuild with 'make OPENCV=1')"); + return; + } + if (cv_set_bg_image(path)) { + send_line(client_fd, "OK background image loaded — add/keep 'personfx 3' to use it"); + } else { + send_line(client_fd, "ERR could not load image (check the path; PNG/JPEG supported)"); + } + return; + } + if (strcmp(sub, "set") == 0) { /* Usage: * filter set <index> <param> → primary @@ -557,6 +613,18 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg) return; /* connection will be closed after return */ } + /* ── opencv — report build info + DNN engine ── */ + if (strcmp(cmd, "opencv") == 0) { + char buf[256]; + snprintf(buf, sizeof buf, "OK %s", cv_engine_info()); + send_line(client_fd, buf); + if (cv_available()) { + snprintf(buf, sizeof buf, "OK model dir: %s", cv_model_dir()); + send_line(client_fd, buf); + } + return; + } + /* ── remove <id> ── */ if (strcmp(cmd, "remove") == 0) { char *id = strtok_r(NULL, " \t", &save); diff --git a/src/main.c b/src/main.c index 53e1d0d..384abd0 100644 --- a/src/main.c +++ b/src/main.c @@ -34,6 +34,7 @@ */ #include "vcam.h" +#include "vcam_cv.h" #include <stdio.h> #include <stdlib.h> @@ -401,5 +402,6 @@ int main(int argc, char *argv[]) if (cap) capture_close(cap); registry_destroy(&g_registry); filter_chain_destroy(&g_filters); + cv_shutdown(); /* free any OpenCV state (no-op in non-OpenCV builds) */ return 0; } diff --git a/src/opencv_fx.cpp b/src/opencv_fx.cpp new file mode 100644 index 0000000..6b1f4d2 --- /dev/null +++ b/src/opencv_fx.cpp @@ -0,0 +1,1651 @@ +/* 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. + */ + +/* + * opencv_fx.cpp — OpenCV 5 backed effects, exposed through the flat C + * ABI declared in vcam_cv.h. Built only when OPENCV=1. + * + * Design notes for the laptop case: + * - Classic effects (cartoon/pencil/stylize/flow/bgsub) use only CPU + * imgproc/photo/video and run comfortably at 720p. + * - DNN effects (face/segmentation) run inference on a DOWNSCALED + * copy and cache the result, re-inferring only every Nth frame + * (see INFER_EVERY). Between inferences the cached mask/boxes are + * reused, so per-frame cost stays low and steady. + * - Every entry point is wrapped in try/catch. Anything unexpected + * (bad frame, missing/corrupt model, OpenCV throwing) degrades to + * leaving the frame untouched. Nothing crosses the C boundary as an + * exception, so the pipeline can never crash because of OpenCV. + * - Models are loaded lazily on first use and cached. A missing model + * prints one warning and thereafter no-ops. + */ + +#include "vcam_cv.h" + +#include <opencv2/core.hpp> +#include <opencv2/imgproc.hpp> +#include <opencv2/photo.hpp> +#include <opencv2/video.hpp> +#include <opencv2/objdetect.hpp> +#include <opencv2/dnn.hpp> +#include <opencv2/imgcodecs.hpp> + +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <string> +#include <mutex> +#include <memory> +#include <sys/stat.h> + +/* ── OpenCV 5 feature gate ───────────────────────────────────── + * When built against OpenCV 5 we light up the 5.x-only features: + * + * - the NEW graph-based DNN engine (typed op graph, shape inference, + * constant folding, operator fusion; 80%+ ONNX operator coverage vs + * ~22% in 4.x). readNet() gained a 4th parameter + * `EngineType engine = ENGINE_AUTO`; we pass ENGINE_AUTO explicitly + * so 5.x tries the new engine first and falls back to the classic + * engine only if the model can't be loaded by it. + * - first-class FP16: cv::hfloat (CV_16F) became a full Mat type in + * 5.x with arithmetic available even on hardware without native + * FP16. We run the person-matte feathered blend at half precision, + * halving the memory traffic of the heaviest per-frame step. + * + * Against OpenCV 4.x the same code compiles with the classic engine and + * an FP32 blend. Everything is decided at compile time from CV_VERSION, + * and cv_engine_info() reports which path is active. */ +#if CV_VERSION_MAJOR >= 5 +# define VCAM_CV5 1 +#else +# define VCAM_CV5 0 +#endif + +namespace { + +#if VCAM_CV5 +/* Load an ONNX model on OpenCV 5's new graph engine (ENGINE_AUTO: + * new engine first, classic as automatic fallback). */ +inline cv::dnn::Net load_net(const std::string &path) +{ + return cv::dnn::readNet(path, "", "", cv::dnn::ENGINE_AUTO); +} +#else +inline cv::dnn::Net load_net(const std::string &path) +{ + return cv::dnn::readNet(path); +} +#endif + +/* Wrap the caller's BGR24 buffer as a cv::Mat WITHOUT copying. The Mat + * shares the caller's memory (respecting stride), so writes land back + * in the frame. Valid only for the duration of the call. */ +inline cv::Mat wrap_bgr(unsigned char *data, int w, int h, int stride) +{ + return cv::Mat(h, w, CV_8UC3, data, static_cast<size_t>(stride)); +} + +inline unsigned char clamp_int_u8(int v) +{ + return (unsigned char)(v < 0 ? 0 : (v > 255 ? 255 : v)); +} + +bool path_exists(const std::string &p) +{ + struct stat st; + return ::stat(p.c_str(), &st) == 0; +} + +/* ── model directory resolution ── */ +std::string resolve_model_dir() +{ + if (const char *env = std::getenv("VCAM_MODEL_DIR")) + if (path_exists(env)) return env; + + const char *home = std::getenv("HOME"); + if (home) { + std::string u = std::string(home) + "/.local/share/vcam/models"; + if (path_exists(u)) return u; + } + if (path_exists("/usr/local/share/vcam/models")) + return "/usr/local/share/vcam/models"; + if (path_exists("/usr/share/vcam/models")) + return "/usr/share/vcam/models"; + + /* Compiled default even if it doesn't exist yet — callers check for + * the specific model file and warn if absent. */ + if (home) return std::string(home) + "/.local/share/vcam/models"; + return "/usr/local/share/vcam/models"; +} + +const std::string &model_dir() +{ + static const std::string d = resolve_model_dir(); + return d; +} + +/* Print a given warning only once per process. */ +void warn_once(const char *key, const std::string &msg) +{ + static std::mutex m; + static std::string seen; + std::lock_guard<std::mutex> lock(m); + std::string tag = std::string(key) + "\n"; + if (seen.find(tag) != std::string::npos) return; + seen += tag; + std::fprintf(stderr, "[vcam/opencv] %s\n", msg.c_str()); +} + +/* A monotonically increasing per-effect frame counter, so DNN effects + * can re-infer every Nth frame. */ +inline unsigned tick(unsigned &counter) { return counter++; } + +constexpr int INFER_EVERY = 3; /* run DNN inference 1 in 3 frames */ + +/* ──────────────────────────────────────────────────────────── + * DNN model holders (lazy, cached, guarded) + * ──────────────────────────────────────────────────────────── */ + +struct FaceState { + cv::Ptr<cv::FaceDetectorYN> det; + bool tried = false; + bool ok = false; + int net_w = 0, net_h = 0; + unsigned counter = 0; + cv::Mat faces; /* cached detections between inferences */ + std::mutex mtx; +}; +FaceState g_face; + +struct SegState { + cv::dnn::Net net; + bool tried = false; + bool ok = false; + unsigned counter = 0; + cv::Mat mask; /* SOFT person alpha, CV_32F 0..1, EMA-smoothed */ + 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) */ + std::mutex mtx; +}; +SegState g_seg; + +/* User-supplied background image for personfx mode 3, set at runtime + * via 'vcam-ctl filter bgimage <path>'. Cached at the last frame size + * with cover-scaling (fill + center-crop, aspect preserved). */ +struct BgImgState { + cv::Mat orig; /* as loaded */ + cv::Mat scaled; /* cover-scaled to frame size */ + std::mutex mtx; +}; +BgImgState g_bgimg; + +/* paintflow: a persistent canvas advected by dense optical flow — + * moving objects drag the paint with them. */ +struct PaintState { + cv::Mat canvas, prev_gray, mapx, mapy; + std::mutex mtx; +}; +PaintState g_paint; + +struct ClassicState { + cv::Ptr<cv::BackgroundSubtractorMOG2> mog2; + cv::Mat prev_gray; /* for optical flow */ + std::mutex mtx; +}; +ClassicState g_classic; + +/* ── Neural style transfer state ── + * Five fast-neural-style networks (Johnson et al., instance-norm), + * MIT-licensed ONNX exports. Fully convolutional: any input size works, + * which gives us a live quality↔speed knob. Input/output: float RGB + * 0..255, NCHW. */ +static const char *STYLE_FILES[5] = { + "mosaic-9.onnx", "candy-9.onnx", "rain-princess-9.onnx", + "udnie-9.onnx", "pointilism-9.onnx", +}; +struct StyleState { + cv::dnn::Net net[5]; + bool tried[5] = {false,false,false,false,false}; + bool ok[5] = {false,false,false,false,false}; + cv::Mat ema; /* temporal smoothing of the stylized frame */ + int ema_style = -1; + std::mutex mtx; +}; +StyleState g_style; + +bool ensure_style(int s) +{ + if (g_style.tried[s]) return g_style.ok[s]; + g_style.tried[s] = true; + std::string path = model_dir() + "/" + STYLE_FILES[s]; + if (!path_exists(path)) { + warn_once((std::string("style") + STYLE_FILES[s]).c_str(), + "style model not found: " + path + + " — run 'vcam-setup --models-style' to download the styles. " + "'styleai' passes through untouched."); + return false; + } + 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); + g_style.ok[s] = true; + } catch (const std::exception &e) { + warn_once("style_load", std::string("failed to load style model: ") + e.what()); + } + return g_style.ok[s]; +} + +/* ── Emotion (FER) state ── + * MobileFaceNet expression classifier from the OpenCV Zoo (Apache-2.0), + * 112x112 input, 7 outputs. ~2ms on a laptop CPU. Reuses the YuNet face + * detector for the crop. Scores are EMA-smoothed to avoid flicker. */ +static const char *EMO_NAME[7] = + { "ANGRY", "DISGUST", "FEAR", "HAPPY", "NEUTRAL", "SAD", "SURPRISED" }; +/* BGR accent color per emotion (neutral stays colorless) */ +static const int EMO_COL[7][3] = { + {40,40,230},{60,170,60},{190,60,170},{40,200,255}, + {160,160,160},{230,140,50},{255,255,255}, +}; +struct MoodState { + cv::dnn::Net net; + bool tried = false, ok = false; + float scores[7] = {0,0,0,0,0,0,0}; /* EMA-smoothed */ + unsigned counter = 0; + /* party-mode particles: x,y,vx,vy,life,color-idx */ + float px[96], py[96], pvx[96], pvy[96], pl[96]; + int pc[96]; + std::mutex mtx; +}; +MoodState g_mood; + +bool ensure_mood() +{ + if (g_mood.tried) return g_mood.ok; + g_mood.tried = true; + std::string path = model_dir() + + "/facial_expression_recognition_mobilefacenet_2022july.onnx"; + if (!path_exists(path)) { + warn_once("fer_model", + "expression model not found: " + path + + " — run 'vcam-setup --models' to download it. " + "'moodfx' passes through untouched."); + return false; + } + 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); + g_mood.ok = true; + } catch (const std::exception &e) { + warn_once("fer_load", std::string("failed to load FER model: ") + e.what()); + } + return g_mood.ok; +} + + +/* Lazily construct the YuNet detector sized to the (downscaled) frame. + * Returns false and warns once if the model file is absent/unloadable. */ +bool ensure_face(int w, int h) +{ + if (g_face.tried && !g_face.ok) return false; + if (g_face.ok && g_face.net_w == w && g_face.net_h == h) return true; + + std::string path = model_dir() + "/face_detection_yunet_2023mar.onnx"; + if (!path_exists(path)) { + g_face.tried = true; g_face.ok = false; + warn_once("face_model", + "face model not found: " + path + + " — run 'vcam-setup --models' to download it. " + "The 'facefx' filter will pass through untouched."); + return false; + } + try { + g_face.det = cv::FaceDetectorYN::create( + path, "", cv::Size(w, h), + 0.7f, 0.3f, 5000); + g_face.net_w = w; g_face.net_h = h; + g_face.tried = true; g_face.ok = true; + return true; + } catch (const std::exception &e) { + g_face.tried = true; g_face.ok = false; + warn_once("face_load", std::string("failed to load face model: ") + e.what()); + return false; + } +} + +bool ensure_seg() +{ + if (g_seg.tried && !g_seg.ok) return false; + if (g_seg.ok) return true; + + std::string path = model_dir() + "/human_segmentation_pphumanseg_2023mar.onnx"; + if (!path_exists(path)) { + g_seg.tried = true; g_seg.ok = false; + warn_once("seg_model", + "segmentation model not found: " + path + + " — run 'vcam-setup --models' to download it. " + "The 'personfx' filter will pass through untouched."); + return false; + } + 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); + g_seg.tried = true; g_seg.ok = true; +#if VCAM_CV5 + warn_once("seg_engine", + "segmentation model loaded on the OpenCV 5 DNN graph engine"); +#endif + return true; + } catch (const std::exception &e) { + g_seg.tried = true; g_seg.ok = false; + warn_once("seg_load", std::string("failed to load seg model: ") + e.what()); + return false; + } +} + +/* PP-HumanSeg: input 192x192, two-channel softmax output (bg, person). + * 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. */ +cv::Mat seg_infer(const cv::Mat &bgr, const cv::Rect &body) +{ + /* Segment only the body ROI (from the face detector), LETTERBOXED + * into the square input instead of aspect-squished. The person now + * fills the model's view the way its selfie training data did — + * this is the difference between a mushy mask and a crisp one. */ + const int N = 192; + cv::Mat crop = bgr(body); + double s2 = (double)N / std::max(crop.cols, crop.rows); + int lw = std::max(8, (int)(crop.cols * s2)); + int lh = std::max(8, (int)(crop.rows * s2)); + cv::Mat resized(N, N, CV_8UC3, cv::Scalar(114,114,114)); + int lx = (N - lw)/2, ly = (N - lh)/2; + { + cv::Mat dst2 = resized(cv::Rect(lx, ly, lw, lh)); + cv::resize(crop, dst2, dst2.size(), 0, 0, cv::INTER_AREA); + } + cv::Mat blob = cv::dnn::blobFromImage( + resized, 1.0 / 127.5, cv::Size(N, N), + cv::Scalar(127.5, 127.5, 127.5), true, false); + + g_seg.net.setInput(blob); + 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 */ + 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. */ + cv::Mat q, q8, lbl, stats, cent; + cv::resize(full, q, cv::Size(), 0.25, 0.25, cv::INTER_LINEAR); + q8 = q > 0.22; + 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) */ + 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)) + 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); + } + + /* 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 - 0.22) * (1.0 / 0.33); + 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 */ + return full; +} + +} // namespace + +/* ════════════════════════════════════════════════════════════ + * C ABI + * ════════════════════════════════════════════════════════════ */ + +extern "C" { + +bool cv_available(void) { return true; } + +const char *cv_version(void) { return CV_VERSION; } + +const char *cv_engine_info(void) +{ +#if VCAM_CV5 + return "OpenCV " CV_VERSION " — new DNN graph engine (ENGINE_AUTO), FP16 blend"; +#else + return "OpenCV " CV_VERSION " — classic DNN engine, FP32 blend " + "(build against OpenCV 5 for the new graph engine)"; +#endif +} + +const char *cv_model_dir(void) { return model_dir().c_str(); } + +/* ── classic effects ── */ + +void cv_fx_cartoon(unsigned char *data, int w, int h, int stride, float strength) +{ + if (!data || w < 4 || h < 4) return; + if (strength <= 0.0f || strength > 1.0f) strength = 0.6f; + try { + cv::Mat img = wrap_bgr(data, w, h, stride); + cv::Mat small, smooth; + /* bilateral is expensive; run it at half-res then upscale */ + cv::resize(img, small, cv::Size(), 0.5, 0.5, cv::INTER_LINEAR); + int d = 9; + double sc = 50 + 120 * strength; + cv::bilateralFilter(small, smooth, d, sc, sc); + cv::resize(smooth, smooth, img.size(), 0, 0, cv::INTER_LINEAR); + + cv::Mat gray, edges; + cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY); + cv::medianBlur(gray, gray, 7); + cv::adaptiveThreshold(gray, edges, 255, + cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, 9, 2); + cv::cvtColor(edges, edges, cv::COLOR_GRAY2BGR); + cv::bitwise_and(smooth, edges, img); /* writes back into frame */ + } catch (const std::exception &e) { + warn_once("cartoon", std::string("cartoon failed: ") + e.what()); + } +} + +void cv_fx_pencil(unsigned char *data, int w, int h, int stride, int color) +{ + if (!data || w < 4 || h < 4) return; + try { + cv::Mat img = wrap_bgr(data, w, h, stride); + cv::Mat gray1, color1; + cv::pencilSketch(img, gray1, color1, + 60.0f, 0.07f, 0.02f); + if (color) color1.copyTo(img); + else cv::cvtColor(gray1, img, cv::COLOR_GRAY2BGR); + } catch (const std::exception &e) { + warn_once("pencil", std::string("pencil failed: ") + e.what()); + } +} + +void cv_fx_stylize(unsigned char *data, int w, int h, int stride, float strength) +{ + if (!data || w < 4 || h < 4) return; + if (strength <= 0.0f || strength > 1.0f) strength = 0.6f; + try { + cv::Mat img = wrap_bgr(data, w, h, stride); + cv::Mat out; + cv::stylization(img, out, 60.0f, 0.45f * strength + 0.1f); + out.copyTo(img); + } catch (const std::exception &e) { + warn_once("stylize", std::string("stylize failed: ") + e.what()); + } +} + +void cv_fx_flow(unsigned char *data, int w, int h, int stride, float mix) +{ + if (!data || w < 8 || h < 8) return; + if (mix <= 0.0f || mix > 1.0f) mix = 0.6f; + try { + std::lock_guard<std::mutex> lock(g_classic.mtx); + cv::Mat img = wrap_bgr(data, w, h, stride); + cv::Mat gray; + cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY); + /* flow on a downscaled gray for speed */ + cv::Mat gsmall; + double s = 0.5; + cv::resize(gray, gsmall, cv::Size(), s, s, cv::INTER_LINEAR); + + if (g_classic.prev_gray.empty() || + g_classic.prev_gray.size() != gsmall.size()) { + gsmall.copyTo(g_classic.prev_gray); + return; /* need two frames */ + } + + cv::Mat flow; + cv::calcOpticalFlowFarneback( + g_classic.prev_gray, gsmall, flow, + 0.5, 2, 13, 3, 5, 1.1, 0); + gsmall.copyTo(g_classic.prev_gray); + + /* map flow → HSV (hue=direction, val=magnitude) */ + cv::Mat parts[2]; + cv::split(flow, parts); + cv::Mat mag, ang; + cv::cartToPolar(parts[0], parts[1], mag, ang, true); + cv::normalize(mag, mag, 0, 255, cv::NORM_MINMAX); + cv::Mat hsv(gsmall.size(), CV_8UC3); + for (int y = 0; y < hsv.rows; y++) { + for (int x = 0; x < hsv.cols; x++) { + float a = ang.at<float>(y, x); + float m = mag.at<float>(y, x); + hsv.at<cv::Vec3b>(y, x) = cv::Vec3b( + static_cast<uchar>(a / 2.0f), /* H 0..180 */ + 255, + static_cast<uchar>(m)); /* V */ + } + } + cv::Mat flowbgr; + cv::cvtColor(hsv, flowbgr, cv::COLOR_HSV2BGR); + cv::resize(flowbgr, flowbgr, img.size(), 0, 0, cv::INTER_LINEAR); + cv::addWeighted(flowbgr, mix, img, 1.0 - mix, 0.0, img); + } catch (const std::exception &e) { + warn_once("flow", std::string("flow failed: ") + e.what()); + } +} + +void cv_fx_bgsub(unsigned char *data, int w, int h, int stride, float sensitivity) +{ + if (!data || w < 8 || h < 8) return; + if (sensitivity <= 0.0f || sensitivity > 1.0f) sensitivity = 0.5f; + try { + std::lock_guard<std::mutex> lock(g_classic.mtx); + cv::Mat img = wrap_bgr(data, w, h, stride); + if (!g_classic.mog2) { + g_classic.mog2 = cv::createBackgroundSubtractorMOG2( + 500, 16.0 + 40.0 * (1.0 - sensitivity), true); + } + cv::Mat fg; + g_classic.mog2->apply(img, fg, -1); + /* clean the mask */ + cv::threshold(fg, fg, 128, 255, cv::THRESH_BINARY); + cv::medianBlur(fg, fg, 5); + cv::Mat fg3; + cv::cvtColor(fg, fg3, cv::COLOR_GRAY2BGR); + + /* dim + desaturate the background, keep foreground vivid */ + cv::Mat gray, dim; + cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY); + cv::cvtColor(gray, dim, cv::COLOR_GRAY2BGR); + dim *= 0.35; + + /* out = fg ? img : dim */ + cv::Mat inv; + cv::bitwise_not(fg3, inv); + cv::Mat keep, drop; + cv::bitwise_and(img, fg3, keep); + cv::bitwise_and(dim, inv, drop); + cv::add(keep, drop, img); + } catch (const std::exception &e) { + warn_once("bgsub", std::string("bgsub failed: ") + e.what()); + } +} + +/* ── DNN effects ── */ + +void cv_fx_face(unsigned char *data, int w, int h, int stride, int mode) +{ + if (!data || w < 16 || h < 16) return; + try { + std::lock_guard<std::mutex> lock(g_face.mtx); + + /* run detection on a downscaled copy for speed, then scale + * boxes back up */ + const int TARGET_W = 320; + double s = (w > TARGET_W) ? (double)TARGET_W / w : 1.0; + int dw = std::max(16, (int)(w * s)); + int dh = std::max(16, (int)(h * s)); + + cv::Mat img = wrap_bgr(data, w, h, stride); + + if (!ensure_face(dw, dh)) return; /* model missing → no-op */ + + if (tick(g_face.counter) % INFER_EVERY == 0) { + cv::Mat small; + cv::resize(img, small, cv::Size(dw, dh)); + cv::Mat faces; + g_face.det->detect(small, faces); + faces.copyTo(g_face.faces); + } + if (g_face.faces.empty()) return; + + double inv = 1.0 / s; + for (int i = 0; i < g_face.faces.rows; i++) { + const float *f = g_face.faces.ptr<float>(i); + int x = (int)(f[0] * inv), y = (int)(f[1] * inv); + int fw = (int)(f[2] * inv), fh = (int)(f[3] * inv); + /* clamp */ + x = std::max(0, std::min(x, w - 1)); + y = std::max(0, std::min(y, h - 1)); + fw = std::max(1, std::min(fw, w - x)); + fh = std::max(1, std::min(fh, h - y)); + cv::Rect roi(x, y, fw, fh); + + if (mode == 0) { + /* privacy: pixelate the face box */ + cv::Mat face = img(roi); + int bx = std::max(1, fw / 12), by = std::max(1, fh / 12); + cv::Mat tiny; + cv::resize(face, tiny, cv::Size(bx, by), 0, 0, cv::INTER_LINEAR); + cv::resize(tiny, face, face.size(), 0, 0, cv::INTER_NEAREST); + } else if (mode == 1) { + /* glossy ring + landmark dots */ + cv::ellipse(img, cv::Point(x + fw/2, y + fh/2), + cv::Size(fw/2, fh/2), 0, 0, 360, + cv::Scalar(60, 220, 255), std::max(2, fw/40)); + /* landmarks start at index 4: re,le,nose,rmouth,lmouth */ + for (int k = 4; k + 1 < 14; k += 2) { + int lx = (int)(f[k] * inv), ly = (int)(f[k+1] * inv); + cv::circle(img, cv::Point(lx, ly), std::max(2, fw/30), + cv::Scalar(255, 255, 255), -1); + } + } else if (mode == 3 || mode == 6) { + /* BIGHEAD (3) / BOBBLEHEAD (6: scale oscillates): magnify the head in place, tracked live. + * Grab a region around the face, enlarge it, paste it + * back centered with an elliptical feather. */ + float scale = 1.45f; + if (mode == 6) + scale = 1.30f + 0.28f * std::sin((float)g_face.counter * 0.35f); + int ex = std::max(0, x - fw/3), ey = std::max(0, y - fh/2); + int ew = std::min(w - ex, fw + 2*fw/3); + int eh = std::min(h - ey, fh + fh); + if (ew > 8 && eh > 8) { + cv::Rect big(ex, ey, ew, eh); + int cw = (int)(ew / scale), ch = (int)(eh / scale); + int cx0 = ex + (ew - cw)/2, cy0 = ey + (eh - ch)/2; + cv::Mat zoom; + cv::resize(img(cv::Rect(cx0, cy0, cw, ch)), zoom, + big.size(), 0, 0, cv::INTER_LINEAR); + /* elliptical feather */ + for (int yy = 0; yy < eh; yy++) { + cv::Vec3b *dst2 = img.ptr<cv::Vec3b>(ey+yy) + ex; + const cv::Vec3b *sp2 = zoom.ptr<cv::Vec3b>(yy); + float ny = (yy - eh/2.f) / (eh/2.f); + for (int xx = 0; xx < ew; xx++) { + float nx = (xx - ew/2.f) / (ew/2.f); + float d = nx*nx + ny*ny; + if (d >= 1.0f) continue; + float a = d < 0.55f ? 1.0f : (1.0f - d) / 0.45f; + dst2[xx][0]=(uchar)(dst2[xx][0]+(sp2[xx][0]-dst2[xx][0])*a); + dst2[xx][1]=(uchar)(dst2[xx][1]+(sp2[xx][1]-dst2[xx][1])*a); + dst2[xx][2]=(uchar)(dst2[xx][2]+(sp2[xx][2]-dst2[xx][2])*a); + } + } + } + } else if (mode == 4) { + /* DEAL-WITH-IT: pixel sunglasses on the eye landmarks */ + cv::Point re((int)(f[4]*inv), (int)(f[5]*inv)); + cv::Point le((int)(f[6]*inv), (int)(f[7]*inv)); + int lw = std::max(8, fw/3); /* lens width */ + int lh = std::max(4, lw/2); + cv::Scalar black(10,10,10); + for (const cv::Point &e : {re, le}) { + cv::rectangle(img, cv::Rect(e.x-lw/2, e.y-lh/2, lw, lh), + black, cv::FILLED); + /* gloss */ + cv::rectangle(img, cv::Rect(e.x-lw/2+2, e.y-lh/2+2, + std::max(2,lw/4), std::max(1,lh/5)), + cv::Scalar(120,120,120), cv::FILLED); + } + cv::line(img, cv::Point(re.x, re.y), cv::Point(le.x, le.y), + black, std::max(2, lh/4)); /* bridge */ + cv::line(img, cv::Point(std::min(re.x,le.x)-lw/2, (re.y+le.y)/2), + cv::Point(x, y + fh/4), black, std::max(2, lh/4)); + cv::line(img, cv::Point(std::max(re.x,le.x)+lw/2, (re.y+le.y)/2), + cv::Point(x+fw, y + fh/4), black, std::max(2, lh/4)); + } else if (mode == 7) { + /* THIRD EYE: your right eye, cloned onto your forehead + * with a circular feather. Deeply unsettling. */ + cv::Point re((int)(f[4]*inv), (int)(f[5]*inv)); + int r3 = std::max(6, fw/5); + cv::Point dst3(x + fw/2, std::max(r3, y + fh/8)); + if (re.x-r3 >= 0 && re.y-r3 >= 0 && re.x+r3 < w && re.y+r3 < h && + dst3.x-r3 >= 0 && dst3.y-r3 >= 0 && dst3.x+r3 < w && dst3.y+r3 < h) { + cv::Mat patch = img(cv::Rect(re.x-r3, re.y-r3, 2*r3, 2*r3)).clone(); + for (int yy = 0; yy < 2*r3; yy++) { + cv::Vec3b *dr = img.ptr<cv::Vec3b>(dst3.y-r3+yy) + (dst3.x-r3); + const cv::Vec3b *sr = patch.ptr<cv::Vec3b>(yy); + float ny = (yy - r3) / (float)r3; + for (int xx = 0; xx < 2*r3; xx++) { + float nx = (xx - r3) / (float)r3; + float d = nx*nx + ny*ny; + if (d >= 1.0f) continue; + float a = d < 0.5f ? 1.0f : (1.0f-d)/0.5f; + dr[xx][0]=(uchar)(dr[xx][0]+(sr[xx][0]-dr[xx][0])*a); + dr[xx][1]=(uchar)(dr[xx][1]+(sr[xx][1]-dr[xx][1])*a); + dr[xx][2]=(uchar)(dr[xx][2]+(sr[xx][2]-dr[xx][2])*a); + } + } + } + } else if (mode == 8) { + /* CROWN: tracked golden crown with jewels above your head */ + int by2 = std::max(6, y - fh/6); /* band bottom */ + int bh2 = std::max(4, fh/8); + int ph = std::max(6, fh/4); /* point height */ + cv::Scalar gold(0, 190, 250), dark(0, 120, 180); + cv::rectangle(img, cv::Rect(x, by2-bh2, fw, bh2), gold, cv::FILLED); + cv::rectangle(img, cv::Rect(x, by2-bh2, fw, bh2), dark, 2); + for (int k2 = 0; k2 < 4; k2++) { + int px0 = x + (fw*k2)/4, px1 = x + (fw*(k2+1))/4; + cv::Point tri[3] = { {px0, by2-bh2}, {px1, by2-bh2}, + {(px0+px1)/2, by2-bh2-ph} }; + cv::fillConvexPoly(img, tri, 3, gold); + cv::circle(img, cv::Point((px0+px1)/2, by2-bh2-ph+3), + std::max(2, fw/40), + k2%2 ? cv::Scalar(60,60,230) : cv::Scalar(230,90,60), + cv::FILLED); + } + } else if (mode == 5) { + /* LASER EYES: beams from both eyes along the nose->eye + * axis, extended to the frame edge, with additive glow. */ + cv::Point nose((int)(f[8]*inv), (int)(f[9]*inv)); + for (int e = 0; e < 2; e++) { + cv::Point eye((int)(f[4+e*2]*inv), (int)(f[5+e*2]*inv)); + float ddx = (float)(eye.x - nose.x); + float ddy = (float)(eye.y - nose.y) - fh * 0.25f; + float L = std::sqrt(ddx*ddx + ddy*ddy); + if (L < 1) { ddx = e ? -1.f : 1.f; ddy = -0.3f; L = 1; } + cv::Point tip(eye.x + (int)(ddx/L * (w+h)), + eye.y + (int)(ddy/L * (w+h))); + cv::line(img, eye, tip, cv::Scalar(20,20,140), std::max(6, fw/8)); + cv::line(img, eye, tip, cv::Scalar(40,40,255), std::max(3, fw/16)); + cv::line(img, eye, tip, cv::Scalar(220,220,255), std::max(1, fw/40)); + cv::circle(img, eye, std::max(4, fw/10), + cv::Scalar(60,60,255), cv::FILLED); + cv::circle(img, eye, std::max(2, fw/20), + cv::Scalar(255,255,255), cv::FILLED); + } + } else { + /* googly eyes at the two eye landmarks (idx 4,5 & 6,7) */ + for (int e = 0; e < 2; e++) { + int lx = (int)(f[4 + e*2] * inv); + int ly = (int)(f[5 + e*2] * inv); + int rad = std::max(6, fw / 6); + cv::circle(img, cv::Point(lx, ly), rad, + cv::Scalar(255, 255, 255), -1); + cv::circle(img, cv::Point(lx, ly), rad, + cv::Scalar(0, 0, 0), std::max(1, rad/6)); + /* pupil offset a little for a wobble */ + int px = lx + rad/3, py = ly + rad/4; + cv::circle(img, cv::Point(px, py), + std::max(2, rad/2), cv::Scalar(0, 0, 0), -1); + } + } + } + } catch (const std::exception &e) { + warn_once("face", std::string("face fx failed: ") + e.what()); + } +} + +void cv_fx_bgblur(unsigned char *data, int w, int h, int stride, int mode) +{ + if (!data || w < 16 || h < 16) return; + try { + 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 */ + + /* 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. + * Lock order seg->face is the established unique nesting. */ + cv::Rect body(0, 0, img.cols, img.rows); + { + std::lock_guard<std::mutex> fl(g_face.mtx); + const int TW = 320; + double fs = (img.cols > TW) ? (double)TW / img.cols : 1.0; + int dw = std::max(16, (int)(img.cols * fs)); + int dh = std::max(16, (int)(img.rows * fs)); + if (ensure_face(dw, dh)) { + if (tick(g_face.counter) % INFER_EVERY == 0) { + cv::Mat sm2; cv::resize(img, sm2, cv::Size(dw, dh)); + cv::Mat fc2; g_face.det->detect(sm2, fc2); + fc2.copyTo(g_face.faces); + } + if (!g_face.faces.empty()) { + const float *ff = g_face.faces.ptr<float>(0); + double iv = 1.0 / fs; + int fx2=(int)(ff[0]*iv), fy2=(int)(ff[1]*iv); + int fw2=(int)(ff[2]*iv), fh2=(int)(ff[3]*iv); + int bx = fx2 + fw2/2 - fw2*5/2; /* 5 face-widths */ + int bw2 = fw2*5; + int by3 = fy2 - fh2; /* headroom */ + bx = std::max(0, bx); + by3 = std::max(0, by3); + bw2 = std::min(img.cols - bx, bw2); + int bh3 = img.rows - by3; /* to the floor */ + if (bw2 > 32 && bh3 > 32) + body = cv::Rect(bx, by3, bw2, bh3); + } + } + } + cv::Mat m = seg_infer(img, body); + if (!m.empty()) { + if (!g_seg.mask.empty() && g_seg.mask.size() == m.size()) + cv::addWeighted(m, 0.80, g_seg.mask, 0.20, 0.0, g_seg.mask); + else + m.copyTo(g_seg.mask); + } + } + if (g_seg.mask.empty() || g_seg.mask.size() != img.size()) return; + + /* Running background estimate: pixels the mask calls background + * feed a slow EMA — after a second or two vcam knows what the + * room looks like WITHOUT you. Powers mode 4 (invisibility). */ + if (g_seg.bg_est.empty() || g_seg.bg_est.size() != img.size()) { + img.copyTo(g_seg.bg_est); + g_seg.bg_frames = 0; + } else { + 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::Vec3b *bp = g_seg.bg_est.ptr<cv::Vec3b>(y); + for (int x = 0; x < img.cols; x++) { + if (mm[x] < 0.25f) { + bp[x][0] = (uchar)((bp[x][0]*15 + ip[x][0]) / 16); + bp[x][1] = (uchar)((bp[x][1]*15 + ip[x][1]) / 16); + bp[x][2] = (uchar)((bp[x][2]*15 + ip[x][2]) / 16); + } + } + } + if (g_seg.bg_frames < 1000) g_seg.bg_frames++; + } + + cv::Mat person3; + cv::cvtColor(g_seg.mask, person3, cv::COLOR_GRAY2BGR); + cv::Mat inv; + cv::bitwise_not(person3, inv); + + if (mode == 9) { + /* TINY YOU: you, shrunk to 45%, standing at the bottom of + * the learned room like a desk gnome. */ + cv::Mat out2; g_seg.bg_est.copyTo(out2); + int sw2 = (int)(img.cols*0.45), sh2 = (int)(img.rows*0.45); + cv::Mat si, sm; + cv::resize(img, si, cv::Size(sw2, sh2), 0, 0, cv::INTER_AREA); + cv::resize(g_seg.mask, sm, cv::Size(sw2, sh2)); + int ox2 = (img.cols - sw2)/2, oy2 = img.rows - sh2; + for (int y = 0; y < sh2; y++) { + const float *mm = sm.ptr<float>(y); + const cv::Vec3b *ip = si.ptr<cv::Vec3b>(y); + cv::Vec3b *op = out2.ptr<cv::Vec3b>(oy2+y) + ox2; + for (int x = 0; x < sw2; 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 == 10) { + /* HOLOGRAM YOU: only your body becomes a flickering cyan + * projection with scanlines; the room stays real. */ + unsigned tk = g_seg.counter; + float flick = 0.8f + 0.2f * ((float)((tk*2654435761u)>>28) / 15.0f); + for (int y = 0; y < img.rows; y++) { + const float *mm = g_seg.mask.ptr<float>(y); + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + float sl = ((y + (int)tk) % 4 == 0) ? 0.45f : 1.0f; + for (int x = 0; x < img.cols; x++) { + float a = mm[x]; if (a < 0.05f) continue; + float lum = (ip[x][0]*0.114f + ip[x][1]*0.587f + ip[x][2]*0.299f); + float b2 = std::min(255.f, (lum*1.35f + 40) * sl * flick); + float g2 = std::min(255.f, (lum*1.05f + 20) * sl * flick); + float r2 = lum * 0.35f * sl * flick; + ip[x][0]=(uchar)(ip[x][0]+(b2-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+(g2-ip[x][1])*a); + ip[x][2]=(uchar)(ip[x][2]+(r2-ip[x][2])*a); + } + } + return; + } + + if (mode == 7) { + /* WINDOW-3D (head-coupled perspective): your head position + * steers a virtual camera — the learned background shifts + * OPPOSITE your head, you shift slightly WITH it, and the + * flat screen turns into a window with real parallax. */ + float tx = 0.f, ty = 0.f; + { + /* run face detection ourselves so window3d works alone. + * Lock order seg->face is unique in the codebase (no + * path takes face->seg), so no inversion is possible. */ + std::lock_guard<std::mutex> fl(g_face.mtx); + const int TW = 320; + double s2 = (img.cols > TW) ? (double)TW / img.cols : 1.0; + int dw = std::max(16, (int)(img.cols * s2)); + int dh = std::max(16, (int)(img.rows * s2)); + if (ensure_face(dw, dh)) { + if (tick(g_face.counter) % INFER_EVERY == 0) { + cv::Mat small2; + cv::resize(img, small2, cv::Size(dw, dh)); + cv::Mat faces2; + g_face.det->detect(small2, faces2); + faces2.copyTo(g_face.faces); + } + if (!g_face.faces.empty()) { + const float *ff = g_face.faces.ptr<float>(0); + tx = (ff[0] + ff[2]*0.5f) / (float)dw - 0.5f; + ty = (ff[1] + ff[3]*0.5f) / (float)dh - 0.5f; + } + } + } + g_seg.hx = 0.85f*g_seg.hx + 0.15f*tx; + g_seg.hy = 0.85f*g_seg.hy + 0.15f*ty; + int bgdx = (int)( g_seg.hx * img.cols * 0.16f); + int bgdy = (int)( g_seg.hy * img.rows * 0.10f); + int pdx = (int)(-g_seg.hx * img.cols * 0.05f); + cv::Mat out2(img.size(), CV_8UC3); + for (int y = 0; y < img.rows; y++) { + int by = std::min(img.rows-1, std::max(0, y + bgdy)); + const cv::Vec3b *bp = g_seg.bg_est.ptr<cv::Vec3b>(by); + const float *mm = g_seg.mask.ptr<float>(y); + const cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + cv::Vec3b *op = out2.ptr<cv::Vec3b>(y); + for (int x = 0; x < img.cols; x++) { + int bx = std::min(img.cols-1, std::max(0, x + bgdx)); + op[x] = bp[bx]; + int sx = x - pdx; + if (sx < 0 || sx >= img.cols) continue; + float a = mm[sx]; + if (a < 0.05f) continue; + op[x][0]=(uchar)(op[x][0]+(ip[sx][0]-op[x][0])*a); + op[x][1]=(uchar)(op[x][1]+(ip[sx][1]-op[x][1])*a); + op[x][2]=(uchar)(op[x][2]+(ip[sx][2]-op[x][2])*a); + } + } + out2.copyTo(img); + return; + } + + if (mode == 8) { + /* CHRONO CLONES: translucent past-selves trail behind you. + * A quarter-res ring stores your matted cutout; ghosts from + * ~1.0 s and ~0.5 s ago composite behind the live you, + * tinted cyan and magenta. */ + static cv::Mat rgbR[45], aR[45]; + static int ridx = 0, rqw = 0, rqh = 0; + int QW = img.cols/4, QH = img.rows/4; + if (rqw != QW || rqh != QH) { + for (int i = 0; i < 45; i++) { rgbR[i].release(); aR[i].release(); } + rqw = QW; rqh = QH; ridx = 0; + } + cv::Mat q, qm; + cv::resize(img, q, cv::Size(QW, QH), 0, 0, cv::INTER_AREA); + cv::resize(g_seg.mask, qm, cv::Size(QW, QH)); + q.copyTo(rgbR[ridx]); qm.copyTo(aR[ridx]); + int gdel[2] = {30, 15}; + int tint[2][3] = {{255,180,40},{160,60,255}}; /* cyan-ish, magenta */ + for (int g2 = 0; g2 < 2; g2++) { + int gi = (ridx - gdel[g2] + 45) % 45; + if (rgbR[gi].empty()) continue; + cv::Mat gb, ga; + cv::resize(rgbR[gi], gb, img.size(), 0, 0, cv::INTER_LINEAR); + cv::resize(aR[gi], ga, img.size(), 0, 0, cv::INTER_LINEAR); + const int *T = tint[g2]; + for (int y = 0; y < img.rows; y++) { + const float *am = ga.ptr<float>(y); + const float *cm = g_seg.mask.ptr<float>(y); + const cv::Vec3b *gp = gb.ptr<cv::Vec3b>(y); + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + for (int x = 0; x < img.cols; x++) { + float a = am[x] * 0.55f * (1.0f - cm[x]); /* behind you */ + if (a < 0.04f) continue; + ip[x][0]=(uchar)(ip[x][0]+((gp[x][0]+T[0])/2-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+((gp[x][1]+T[1])/2-ip[x][1])*a); + ip[x][2]=(uchar)(ip[x][2]+((gp[x][2]+T[2])/2-ip[x][2])*a); + } + } + } + ridx = (ridx + 1) % 45; + return; + } + + if (mode == 6) { + /* CLONE ARMY: three of you, standing in the learned room. + * Composite the matted person at -w/3, 0, +w/3 over bg_est. */ + cv::Mat out2; + g_seg.bg_est.copyTo(out2); + int offs[3] = { -img.cols/3, 0, img.cols/3 }; + for (int k = 0; k < 3; k++) { + int dx = offs[k]; + 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::Vec3b *op = out2.ptr<cv::Vec3b>(y); + for (int x = 0; x < img.cols; x++) { + int sx = x - dx; + if (sx < 0 || sx >= img.cols) continue; + float a = mm[sx]; + if (a < 0.05f) continue; + op[x][0]=(uchar)(op[x][0]+(ip[sx][0]-op[x][0])*a); + op[x][1]=(uchar)(op[x][1]+(ip[sx][1]-op[x][1])*a); + op[x][2]=(uchar)(op[x][2]+(ip[sx][2]-op[x][2])*a); + } + } + } + out2.copyTo(img); + return; + } + + cv::Mat bg; + bool have_user_bg = false; + if (mode == 3) { + /* user-supplied background image (cover-scaled + cached) */ + std::lock_guard<std::mutex> bl(g_bgimg.mtx); + if (!g_bgimg.orig.empty()) { + if (g_bgimg.scaled.size() != img.size()) { + /* cover: scale so both dims fill, center-crop */ + double sx = (double)img.cols / g_bgimg.orig.cols; + double sy = (double)img.rows / g_bgimg.orig.rows; + double s2 = std::max(sx, sy); + cv::Mat big; + cv::resize(g_bgimg.orig, big, cv::Size(), s2, s2, + cv::INTER_AREA); + int ox = (big.cols - img.cols) / 2; + int oy = (big.rows - img.rows) / 2; + big(cv::Rect(ox, oy, img.cols, img.rows)) + .copyTo(g_bgimg.scaled); + } + g_bgimg.scaled.copyTo(bg); + have_user_bg = true; + } + /* no image set → fall through to the gradient below */ + } + if (have_user_bg) { + /* bg ready */ + } else if (mode == 0) { + /* portrait: blur the background */ + cv::GaussianBlur(img, bg, cv::Size(0, 0), 8.0); + } else if (mode == 1) { + /* spotlight: gray + dim the background */ + cv::Mat gray; + cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY); + cv::cvtColor(gray, bg, cv::COLOR_GRAY2BGR); + bg *= 0.5; + } else if (mode == 4) { + /* INVISIBILITY CLOAK: paint the person with the learned + * background. Needs ~1-2s of you moving around (or briefly + * stepping out) so the room behind you gets learned. */ + g_seg.bg_est.copyTo(bg); + } else if (mode == 5) { + /* NEON PERSON: the room goes near-black, you stay lit, and + * your silhouette gets an additive cyan edge glow. */ + bg = cv::Mat::zeros(img.size(), CV_8UC3); + cv::Mat m8, dil, ero, edge; + g_seg.mask.convertTo(m8, CV_8U, 255.0); + cv::dilate(m8, dil, cv::Mat(), cv::Point(-1,-1), 3); + cv::erode (m8, ero, cv::Mat(), cv::Point(-1,-1), 3); + edge = dil - ero; + for (int y = 0; y < img.rows; y++) { + const uchar *ep = edge.ptr<uchar>(y); + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + for (int x = 0; x < img.cols; x++) { + if (ep[x] > 40) { + ip[x][0] = clamp_int_u8(ip[x][0] + ep[x]); + ip[x][1] = clamp_int_u8(ip[x][1] + ep[x]); + ip[x][2] = clamp_int_u8(ip[x][2] + ep[x]/3); + } + } + } + } else { + /* replace with a moving diagonal color gradient */ + bg = cv::Mat(img.size(), CV_8UC3); + static unsigned t = 0; t++; + for (int y = 0; y < bg.rows; y++) { + cv::Vec3b *row = bg.ptr<cv::Vec3b>(y); + for (int x = 0; x < bg.cols; x++) { + uchar r = (uchar)(128 + 127 * std::sin((x + y + t*4) * 0.02)); + uchar g = (uchar)(128 + 127 * std::sin((x + y + t*4) * 0.02 + 2.0)); + uchar b = (uchar)(128 + 127 * std::sin((x + y + t*4) * 0.02 + 4.0)); + row[x] = cv::Vec3b(b, g, r); + } + } + } + + /* blend: person from img, elsewhere from bg, feathered by mask. + * out = img*mask + bg*(1-mask), done per-channel in floating + * point. On OpenCV 5 this runs in first-class FP16 (cv::hfloat, + * CV_16F) — half the memory traffic of FP32, with arithmetic + * guaranteed in 5.x even without native FP16 hardware. Mask is + * 0..1 and pixels 0..255, comfortably inside half range. */ +#if VCAM_CV5 + const int FDEPTH1 = CV_MAKETYPE(CV_16F, 1); + const int FDEPTH3 = CV_MAKETYPE(CV_16F, 3); +#else + const int FDEPTH1 = CV_32FC1; + const int FDEPTH3 = CV_32FC3; +#endif + cv::Mat maskf; + g_seg.mask.convertTo(maskf, FDEPTH1); /* already 0..1 */ + cv::Mat invf = cv::Scalar::all(1.0) - maskf; /* Scalar - Mat */ + + cv::Mat m3, inv3; + { + cv::Mat mc[3] = { maskf, maskf, maskf }; + cv::merge(mc, 3, m3); + cv::Mat ic[3] = { invf, invf, invf }; + cv::merge(ic, 3, inv3); + } + cv::Mat imgf, bgf, outf; + img.convertTo(imgf, FDEPTH3); + bg.convertTo(bgf, FDEPTH3); + outf = imgf.mul(m3) + bgf.mul(inv3); + outf.convertTo(img, CV_8UC3); + } catch (const std::exception &e) { + warn_once("bgblur", std::string("bg fx failed: ") + e.what()); + } +} + +void cv_fx_style(unsigned char *data, int w, int h, int stride, + int style, float blend, float size_sel) +{ + if (!data || w < 32 || h < 32) return; + if (style < 0) style = 0; + if (style > 4) style = 4; + if (blend <= 0.0f || blend > 1.0f) blend = 0.85f; + int S = (int)size_sel; + if (S < 96) S = 192; /* quality↔speed knob, default 192 */ + if (S > 384) S = 384; + try { + std::lock_guard<std::mutex> lock(g_style.mtx); + cv::Mat img = wrap_bgr(data, w, h, stride); + if (!ensure_style(style)) return; + + /* keep aspect; round dims to /8 for conv friendliness */ + double sc = (double)S / std::max(w, h); + int sw = std::max(64, ((int)(w * sc) / 8) * 8); + int sh = std::max(64, ((int)(h * sc) / 8) * 8); + cv::Mat small; + cv::resize(img, small, cv::Size(sw, sh), 0, 0, cv::INTER_AREA); + + /* fast-neural-style expects raw RGB floats 0..255 (no norm) */ + cv::Mat blob = cv::dnn::blobFromImage( + small, 1.0, cv::Size(sw, sh), cv::Scalar(), true, false); + g_style.net[style].setInput(blob); + cv::Mat out = g_style.net[style].forward(); /* [1,3,sh,sw] RGB */ + if (out.dims != 4 || out.size[1] != 3) return; + int oh = out.size[2], ow = out.size[3]; + + cv::Mat styled(oh, ow, CV_8UC3); + const float *R = out.ptr<float>(0, 0); + const float *G = out.ptr<float>(0, 1); + const float *B = out.ptr<float>(0, 2); + for (int y = 0; y < oh; y++) { + cv::Vec3b *row = styled.ptr<cv::Vec3b>(y); + for (int x = 0; x < ow; x++) { + int i = y * ow + x; + row[x] = cv::Vec3b( + cv::saturate_cast<uchar>(B[i]), + cv::saturate_cast<uchar>(G[i]), + cv::saturate_cast<uchar>(R[i])); + } + } + /* temporal EMA at small res: hides inter-frame flicker */ + if (g_style.ema_style == style && !g_style.ema.empty() && + g_style.ema.size() == styled.size()) { + cv::addWeighted(styled, 0.65, g_style.ema, 0.35, 0.0, styled); + } + styled.copyTo(g_style.ema); + g_style.ema_style = style; + + cv::Mat full; + cv::resize(styled, full, img.size(), 0, 0, cv::INTER_LINEAR); + cv::addWeighted(full, blend, img, 1.0 - blend, 0.0, img); + } catch (const std::exception &e) { + warn_once("style", std::string("styleai failed: ") + e.what()); + } +} + +void cv_fx_mood(unsigned char *data, int w, int h, int stride, + int mode, float gain) +{ + if (!data || w < 32 || h < 32) return; + if (mode < 0) mode = 0; + if (mode > 4) mode = 4; + if (gain <= 0.0f || gain > 2.0f) gain = 1.0f; + try { + cv::Mat img = wrap_bgr(data, w, h, stride); + + /* face detection (shares the YuNet state with cv_fx_face) */ + cv::Rect roi; + double eye_ang = 0.0; + { + std::lock_guard<std::mutex> lock(g_face.mtx); + const int TW = 320; + double s = (w > TW) ? (double)TW / w : 1.0; + int dw = std::max(16, (int)(w * s)); + int dh = std::max(16, (int)(h * s)); + if (!ensure_face(dw, dh)) return; + if (tick(g_face.counter) % INFER_EVERY == 0) { + cv::Mat small; + cv::resize(img, small, cv::Size(dw, dh)); + cv::Mat faces; + g_face.det->detect(small, faces); + faces.copyTo(g_face.faces); + } + if (g_face.faces.empty()) return; + const float *f = g_face.faces.ptr<float>(0); /* largest/first */ + double inv = 1.0 / s; + int x = (int)(f[0]*inv), y = (int)(f[1]*inv); + int fw = (int)(f[2]*inv), fh = (int)(f[3]*inv); + x = std::max(0, std::min(x, w-2)); + y = std::max(0, std::min(y, h-2)); + fw = std::max(2, std::min(fw, w-x)); + fh = std::max(2, std::min(fh, h-y)); + roi = cv::Rect(x, y, fw, fh); + eye_ang = std::atan2((f[7]-f[5]), (f[6]-f[4])) * 180.0 / 3.14159265; + } + + std::lock_guard<std::mutex> lock(g_mood.mtx); + if (!ensure_mood()) return; + + /* FER is ~2 ms — run it EVERY frame (the old every-3rd throttle + * plus slow EMA made reactions feel dead). */ + tick(g_mood.counter); + { + /* ALIGNED crop: the model was trained on eye-level faces. + * Rotate a padded square around the face by the eye angle, + * then crop the center — accuracy jumps massively vs the + * raw bounding box we fed it before. */ + int cx2 = roi.x + roi.width/2, cy2 = roi.y + roi.height/2; + int half = (int)(std::max(roi.width, roi.height) * 0.72); + int x0 = std::max(0, cx2-half), y0 = std::max(0, cy2-half); + int x1 = std::min(w, cx2+half), y1 = std::min(h, cy2+half); + cv::Mat pad = img(cv::Rect(x0, y0, x1-x0, y1-y0)); + /* rotation matrix by hand (getRotationMatrix2D moved into + * the new 'geometry' module in OpenCV 5 — building the 2x3 + * affine ourselves works identically on every version): + * [ c s (1-c)*cx - s*cy ] + * [ -s c s*cx + (1-c)*cy ] (positive angle = CCW) */ + double ra = eye_ang * CV_PI / 180.0; + double c = std::cos(ra), s = std::sin(ra); + double rcx = (double)(cx2 - x0), rcy = (double)(cy2 - y0); + double rbuf[6] = { c, s, (1.0 - c) * rcx - s * rcy, + -s, c, s * rcx + (1.0 - c) * rcy }; + cv::Mat rot(2, 3, CV_64F, rbuf); /* used within this scope only */ + cv::Mat level; + cv::warpAffine(pad, level, rot, pad.size(), + cv::INTER_LINEAR, cv::BORDER_REPLICATE); + int side = std::min({level.cols, level.rows, + (int)(std::max(roi.width, roi.height)*1.15)}); + int ox = std::max(0, (cx2-x0) - side/2); + int oy = std::max(0, (cy2-y0) - side/2); + ox = std::min(ox, level.cols - side); + oy = std::min(oy, level.rows - side); + cv::Mat face112; + cv::resize(level(cv::Rect(ox, oy, side, side)), face112, + cv::Size(112, 112)); + /* MobileFaceNet convention: (x/255 - 0.5)/0.5, RGB */ + cv::Mat blob = cv::dnn::blobFromImage( + face112, 1.0 / 127.5, cv::Size(112, 112), + cv::Scalar(127.5, 127.5, 127.5), true, false); + g_mood.net.setInput(blob); + cv::Mat out = g_mood.net.forward(); /* 7 scores */ + if ((int)out.total() >= 7) { + const float *o = out.ptr<float>(0); + /* softmax → EMA smoothing (kills flicker) */ + float mx = o[0]; + for (int i = 1; i < 7; i++) mx = std::max(mx, o[i]); + float ex[7], sum = 0.f; + for (int i = 0; i < 7; i++) { ex[i] = std::exp(o[i]-mx); sum += ex[i]; } + for (int i = 0; i < 7; i++) + g_mood.scores[i] = 0.6f*g_mood.scores[i] + 0.4f*(ex[i]/sum); + } + } + int emo = 0; + for (int i = 1; i < 7; i++) + if (g_mood.scores[i] > g_mood.scores[emo]) emo = i; + /* rescale: 1/7 (chance) -> 0, ~0.65 (clear expression) -> 1 */ + float raw = (g_mood.scores[emo] - 0.143f) / 0.5f; + float conf = std::min(1.0f, std::max(0.0f, raw) * gain); + const int *C = EMO_COL[emo]; + + if (mode == 0) { + /* AURA: soft colored vignette breathing with confidence. + * Neutral = no tint. */ + if (emo == 4 || conf < 0.08f) return; + float cx = w/2.f, cy = h/2.f; + float maxr = std::sqrt(cx*cx + cy*cy); + for (int y = 0; y < h; y++) { + uchar *row = data + y*stride; + float dy = y - cy; + for (int x = 0; x < w; x++) { + float dx = x - cx; + float t = std::sqrt(dx*dx + dy*dy) / maxr; /* 0..1 */ + t = t*t * conf * 0.9f; + uchar *p = row + x*3; + p[0] = (uchar)(p[0] + (C[0]-p[0])*t); + p[1] = (uchar)(p[1] + (C[1]-p[1])*t); + p[2] = (uchar)(p[2] + (C[2]-p[2])*t); + } + } + } else if (mode == 1) { + /* HUD: labeled box + confidence bar over the face */ + cv::Scalar col(C[0], C[1], C[2]); + cv::rectangle(img, roi, col, 2); + char label[48]; + snprintf(label, sizeof label, "%s %d%%", EMO_NAME[emo], + (int)(conf * 100)); + int ty = std::max(18, roi.y - 8); + cv::putText(img, label, cv::Point(roi.x, ty), + cv::FONT_HERSHEY_SIMPLEX, 0.7, cv::Scalar(0,0,0), 4); + cv::putText(img, label, cv::Point(roi.x, ty), + 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 == 4) { + /* PAINTMOOD: two neural nets chained — the FER model reads + * your emotion, which SELECTS the neural style; confidence + * drives the blend. Happy world is candy, sad world is + * rain-princess, anger turns everything to mosaic shards. + * (Lock nesting mood->style is unique; style never locks + * mood, so no inversion.) Needs the --models-style pack. */ + static const int emo2style[7] = { 0, 3, 2, 1, 3, 2, 4 }; + /* angry->mosaic disgust->udnie fear->rain happy->candy + * neutral->udnie sad->rain-princess surprised->pointilism */ + float sb = 0.30f + 0.55f * conf; + cv_fx_style(data, w, h, stride, emo2style[emo], sb, 192.0f); + } else if (mode == 3) { + /* EMOJI: your face becomes the emotion-matched emoji */ + cv::Point c(roi.x + roi.width/2, roi.y + roi.height/2); + int R2 = (int)(std::max(roi.width, roi.height) * 0.62); + cv::circle(img, c, R2, cv::Scalar(0, 200, 255), cv::FILLED); + cv::circle(img, c, R2, cv::Scalar(0, 140, 200), std::max(2, R2/24)); + int er = std::max(3, R2/7); + cv::Point el(c.x - R2/3, c.y - R2/4), er2(c.x + R2/3, c.y - R2/4); + if (emo == 6) { /* surprised: O eyes+mouth */ + cv::circle(img, el, er, cv::Scalar(30,30,30), cv::FILLED); + cv::circle(img, er2, er, cv::Scalar(30,30,30), cv::FILLED); + cv::circle(img, cv::Point(c.x, c.y + R2/3), er+2, + cv::Scalar(30,30,30), cv::FILLED); + } else { + cv::circle(img, el, er, cv::Scalar(30,30,30), cv::FILLED); + cv::circle(img, er2, er, cv::Scalar(30,30,30), cv::FILLED); + if (emo == 0) { /* angry brows */ + cv::line(img, cv::Point(el.x-er, el.y-er-4), + cv::Point(el.x+er, el.y-er+4), cv::Scalar(30,30,30), 5); + cv::line(img, cv::Point(er2.x+er, er2.y-er-4), + cv::Point(er2.x-er, er2.y-er+4), cv::Scalar(30,30,30), 5); + } + int my = c.y + R2/3; + if (emo == 3) /* happy: smile arc */ + cv::ellipse(img, cv::Point(c.x,my-6), cv::Size(R2/2,R2/3), + 0, 20, 160, cv::Scalar(30,30,30), 6); + else if (emo == 5 || emo == 2) /* sad/fear: frown */ + cv::ellipse(img, cv::Point(c.x,my+R2/4), cv::Size(R2/2,R2/4), + 0, 200, 340, cv::Scalar(30,30,30), 6); + else /* neutral-ish: flat */ + cv::line(img, cv::Point(c.x-R2/3,my), cv::Point(c.x+R2/3,my), + cv::Scalar(30,30,30), 6); + if (emo == 5) /* sad: a tear */ + cv::circle(img, cv::Point(el.x, el.y+er*2), + std::max(2,er/2), cv::Scalar(230,160,60), cv::FILLED); + } + } else { + /* PARTY: emotions trigger physical effects. + * happy → confetti; sad → falling blue rain streaks; + * surprised → white edge flash; angry → screen shake. */ + { /* live readout, bottom-right — see what the model sees */ + char lab[40]; + snprintf(lab, sizeof lab, "%s %d%%", EMO_NAME[emo], (int)(conf*100)); + cv::putText(img, lab, cv::Point(w-400, h-22), + cv::FONT_HERSHEY_SIMPLEX, 1.1, cv::Scalar(0,0,0), 6); + cv::putText(img, lab, cv::Point(w-400, h-22), + cv::FONT_HERSHEY_SIMPLEX, 1.1, + cv::Scalar(C[0],C[1],C[2]), 2); + } + if (emo == 3 && conf > 0.18f) { /* confetti */ + for (int i = 0; i < 96; i++) { + if (g_mood.pl[i] <= 0 && (rand() % 100) < (int)(conf*25)) { + g_mood.px[i] = (float)(rand() % w); + g_mood.py[i] = -(float)(rand() % 40); + g_mood.pvx[i] = ((rand()%100)-50) / 40.0f; + g_mood.pvy[i] = 2.0f + (rand()%100)/40.0f; + g_mood.pl[i] = 1.0f; + g_mood.pc[i] = rand() % 7; + } + } + } + for (int i = 0; i < 96; i++) { /* step + draw */ + if (g_mood.pl[i] <= 0) continue; + g_mood.px[i] += g_mood.pvx[i]; + g_mood.py[i] += g_mood.pvy[i]; + g_mood.pl[i] -= 0.008f; + int X = (int)g_mood.px[i], Y = (int)g_mood.py[i]; + if (X < 1 || X >= w-4 || Y < 0 || Y >= h-4) { g_mood.pl[i]=0; continue; } + const int *cc = EMO_COL[g_mood.pc[i]]; + for (int yy = 0; yy < 4; yy++) { + uchar *p = data + (Y+yy)*stride + X*3; + for (int xx = 0; xx < 4; xx++) { + p[xx*3+0]=(uchar)cc[0]; p[xx*3+1]=(uchar)cc[1]; p[xx*3+2]=(uchar)cc[2]; + } + } + } + if (emo == 5 && conf > 0.18f) { /* sad rain */ + unsigned seed = (unsigned)g_mood.counter * 2654435761u; + int n = (int)(conf * 40); + for (int i = 0; i < n; i++) { + seed = seed*1664525u + 1013904223u; + int X = (int)(seed % (unsigned)w); + int Y = (int)((seed >> 12) % (unsigned)(h - 20)); + for (int yy = 0; yy < 14; yy++) { + uchar *p = data + (Y+yy)*stride + X*3; + p[0] = clamp_int_u8(p[0] + 90); p[1] = clamp_int_u8(p[1] + 40); + } + } + } + if (emo == 6 && conf > 0.18f) { /* surprised flash edges */ + int bh = (int)(conf * 24); + for (int y = 0; y < bh; y++) { + uchar *t2 = data + y*stride; + uchar *b2 = data + (h-1-y)*stride; + for (int x = 0; x < w*3; x++) { + t2[x] = clamp_int_u8(t2[x] + 120); + b2[x] = clamp_int_u8(b2[x] + 120); + } + } + } + if (emo == 0 && conf > 0.18f) { /* angry shake */ + int off = ((int)(g_mood.counter % 4) - 2) * (int)(conf * 6); + if (off != 0) { + cv::Mat shifted; + img.copyTo(shifted); + int ax = std::abs(off); + if (ax < w) { + cv::Rect src2 = (off > 0) ? cv::Rect(0,0,w-ax,h) : cv::Rect(ax,0,w-ax,h); + cv::Rect dst2 = (off > 0) ? cv::Rect(ax,0,w-ax,h) : cv::Rect(0,0,w-ax,h); + shifted(src2).copyTo(img(dst2)); + } + } + } + } + } catch (const std::exception &e) { + warn_once("mood", std::string("moodfx failed: ") + e.what()); + } +} + +void cv_fx_paintflow(unsigned char *data, int w, int h, int stride, + float strength, float decay) +{ + if (!data || w < 16 || h < 16) return; + if (strength <= 0.0f || strength > 3.0f) strength = 1.0f; + if (decay < 0.80f || decay > 0.99f) decay = 0.93f; + try { + std::lock_guard<std::mutex> lock(g_paint.mtx); + cv::Mat img = wrap_bgr(data, w, h, stride); + cv::Mat gray, gs; + cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY); + cv::resize(gray, gs, cv::Size(), 0.5, 0.5, cv::INTER_LINEAR); + + if (g_paint.canvas.empty() || g_paint.canvas.size() != img.size() || + g_paint.prev_gray.size() != gs.size()) { + img.copyTo(g_paint.canvas); + gs.copyTo(g_paint.prev_gray); + g_paint.mapx.create(h, w, CV_32F); + g_paint.mapy.create(h, w, CV_32F); + return; + } + + cv::Mat flow; + cv::calcOpticalFlowFarneback(g_paint.prev_gray, gs, flow, + 0.5, 2, 13, 3, 5, 1.1, 0); + gs.copyTo(g_paint.prev_gray); + + /* advect the canvas: each pixel pulls paint from where the + * motion came from (flow at half res, scaled x2) */ + float k = 2.0f * strength; + for (int y = 0; y < h; y++) { + float *mx = g_paint.mapx.ptr<float>(y); + float *my = g_paint.mapy.ptr<float>(y); + const cv::Vec2f *fr = flow.ptr<cv::Vec2f>(std::min(y/2, flow.rows-1)); + for (int x = 0; x < w; x++) { + const cv::Vec2f &v = fr[std::min(x/2, flow.cols-1)]; + mx[x] = x - v[0]*k; + my[x] = y - v[1]*k; + } + } + cv::Mat moved; + cv::remap(g_paint.canvas, moved, g_paint.mapx, g_paint.mapy, + cv::INTER_LINEAR, cv::BORDER_REPLICATE); + /* refresh with a whisper of live video so stills stay sharp */ + cv::addWeighted(moved, decay, img, 1.0 - decay, 0.0, g_paint.canvas); + g_paint.canvas.copyTo(img); + } catch (const std::exception &e) { + warn_once("paintflow", std::string("paintflow failed: ") + e.what()); + } +} + +void cv_fx_speedlines(unsigned char *data, int w, int h, int stride, + float sens, float density) +{ + if (!data || w < 32 || h < 32) return; + if (sens <= 0.0f || sens > 3.0f) sens = 1.0f; + if (density <= 0.0f || density > 1.0f) density = 0.5f; + try { + std::lock_guard<std::mutex> lock(g_classic.mtx); + cv::Mat img = wrap_bgr(data, w, h, stride); + cv::Mat gray, gs; + cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY); + cv::resize(gray, gs, cv::Size(), 0.25, 0.25, cv::INTER_LINEAR); + if (g_classic.prev_gray.empty() || + g_classic.prev_gray.size() != gs.size()) { + gs.copyTo(g_classic.prev_gray); + return; + } + cv::Mat flow; + cv::calcOpticalFlowFarneback(g_classic.prev_gray, gs, flow, + 0.5, 2, 9, 2, 5, 1.1, 0); + gs.copyTo(g_classic.prev_gray); + cv::Scalar mean2 = cv::mean(flow); + float mx2 = (float)mean2[0]*4, my2 = (float)mean2[1]*4; + float mag = std::sqrt(mx2*mx2 + my2*my2) * sens; + if (mag < 3.0f) return; /* not moving enough */ + float L = std::sqrt(mx2*mx2 + my2*my2); + float dx = -mx2/L, dy = -my2/L; /* opposite motion */ + int N = (int)(10 + density * 50); + unsigned seed = (unsigned)((w+h) * 2654435761u) ^ (unsigned)(mag*97); + float inten = std::min(1.0f, mag / 30.0f); + for (int i = 0; i < N; i++) { + seed = seed*1664525u + 1013904223u; + /* start on the border the lines come FROM */ + float t = (float)(seed % 10000u) / 10000.0f; + int sx2, sy2; + if (std::fabs(dx) > std::fabs(dy)) { + sx2 = dx > 0 ? 0 : w-1; + sy2 = (int)(t * h); + } else { + sy2 = dy > 0 ? 0 : h-1; + sx2 = (int)(t * w); + } + seed = seed*1664525u + 1013904223u; + int len = (int)((0.15f + 0.20f*((seed>>20)&255)/255.0f) + * std::min(w,h) * inten) + 8; + cv::Point a2(sx2, sy2); + cv::Point b2(sx2 + (int)(dx*len), sy2 + (int)(dy*len)); + int v2 = 120 + (int)(inten * 135); + cv::line(img, a2, b2, cv::Scalar(v2,v2,v2), 1 + (int)(seed&1)); + } + } catch (const std::exception &e) { + warn_once("speedlines", std::string("speedlines failed: ") + e.what()); + } +} + +int cv_set_bg_image(const char *path) +{ + if (!path || !*path) return 0; + try { + cv::Mat m = cv::imread(path, cv::IMREAD_COLOR); + if (m.empty()) return 0; + std::lock_guard<std::mutex> l(g_bgimg.mtx); + m.copyTo(g_bgimg.orig); + g_bgimg.scaled.release(); /* re-cover on next frame */ + return 1; + } catch (const std::exception &e) { + warn_once("bgimg", std::string("bg image load failed: ") + e.what()); + return 0; + } +} + +void cv_clear_bg_image(void) +{ + try { + std::lock_guard<std::mutex> l(g_bgimg.mtx); + g_bgimg.orig.release(); + g_bgimg.scaled.release(); + } catch (...) { } +} + +void cv_shutdown(void) +{ + 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_classic.mtx); + g_classic.mog2.reset(); g_classic.prev_gray.release(); } + { std::lock_guard<std::mutex> l(g_style.mtx); + for (int i = 0; i < 5; i++) g_style.net[i] = cv::dnn::Net(); + g_style.ema.release(); } + { std::lock_guard<std::mutex> l(g_mood.mtx); + g_mood.net = cv::dnn::Net(); } + { std::lock_guard<std::mutex> l(g_paint.mtx); + g_paint.canvas.release(); g_paint.prev_gray.release(); + g_paint.mapx.release(); g_paint.mapy.release(); } + { std::lock_guard<std::mutex> l(g_bgimg.mtx); + g_bgimg.orig.release(); g_bgimg.scaled.release(); } + } catch (...) { /* shutdown must never throw */ } +} + +} // extern "C" diff --git a/src/opencv_stub.c b/src/opencv_stub.c new file mode 100644 index 0000000..8024fae --- /dev/null +++ b/src/opencv_stub.c @@ -0,0 +1,67 @@ +/* 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. + */ + +/* + * opencv_stub.c — no-op implementations of the vcam_cv.h C ABI, built + * when vcam is compiled WITHOUT OpenCV (the default). Every effect + * leaves the frame untouched; cv_available() returns false so callers + * (and the IPC layer) can tell the user OpenCV isn't compiled in. + * + * This lets filter.c call the cv_fx_* functions unconditionally — the + * linker resolves them either to the real OpenCV shim or to these. + */ + +#include "vcam_cv.h" + +bool cv_available(void) { return false; } + +const char *cv_version(void) { return "none"; } + +const char *cv_engine_info(void) { return "opencv not built in (rebuild with 'make OPENCV=1')"; } + +const char *cv_model_dir(void) { return "(opencv not built in)"; } + +/* All effects are no-ops: the BGR24 frame passes through unchanged. */ +void cv_fx_cartoon(unsigned char *d, int w, int h, int s, float x) +{ (void)d; (void)w; (void)h; (void)s; (void)x; } + +void cv_fx_pencil(unsigned char *d, int w, int h, int s, int c) +{ (void)d; (void)w; (void)h; (void)s; (void)c; } + +void cv_fx_stylize(unsigned char *d, int w, int h, int s, float x) +{ (void)d; (void)w; (void)h; (void)s; (void)x; } + +void cv_fx_flow(unsigned char *d, int w, int h, int s, float m) +{ (void)d; (void)w; (void)h; (void)s; (void)m; } + +void cv_fx_bgsub(unsigned char *d, int w, int h, int s, float x) +{ (void)d; (void)w; (void)h; (void)s; (void)x; } + +void cv_fx_face(unsigned char *d, int w, int h, int s, int m) +{ (void)d; (void)w; (void)h; (void)s; (void)m; } + +void cv_fx_bgblur(unsigned char *d, int w, int h, int s, int m) +{ (void)d; (void)w; (void)h; (void)s; (void)m; } + +void cv_fx_style(unsigned char *d, int w, int h, int s, int st, float b, float sz) +{ (void)d; (void)w; (void)h; (void)s; (void)st; (void)b; (void)sz; } + +void cv_fx_mood(unsigned char *d, int w, int h, int s, int m, float g) +{ (void)d; (void)w; (void)h; (void)s; (void)m; (void)g; } + +void cv_fx_paintflow(unsigned char *d, int w, int h, int s, float st, float dc) +{ (void)d; (void)w; (void)h; (void)s; (void)st; (void)dc; } + +void cv_fx_speedlines(unsigned char *d, int w, int h, int s, float a, float b) +{ (void)d; (void)w; (void)h; (void)s; (void)a; (void)b; } + +int cv_set_bg_image(const char *p) { (void)p; return 0; } + +void cv_clear_bg_image(void) { } + +void cv_shutdown(void) { }