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.gzJust some dumb AI filter stuff
README.md | 2 +- include/vcam.h | 4 + include/vcam_cv.h | 43 ++ include/vcam_ort.h | 25 + scripts/vcam-ctl | 39 ++ scripts/vcam-setup | 114 +++++ scripts/vcam-tune | 17 +- src/filter.c | 12 + src/ipc.c | 118 ++++- src/opencv_fx.cpp | 1356 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/opencv_stub.c | 24 + src/ort_rvm.c | 384 +++++++++++++++ 12 files changed, 2131 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 4e2f07c..775c0a9 100644 --- a/README.md +++ b/README.md @@ -432,7 +432,7 @@ and fetch the (free, tiny) model files. | `cvstylize` | strength | watercolor / poster stylization (edge-aware) | no | | `opticalflow` | mix | dense Farnebäck optical flow — motion becomes flowing color (direction = hue, speed = brightness) | no | | `bgsub` | sensitivity | MOG2 background subtraction: whatever moves stays vivid, the learned static background dims and desaturates | no | -| `facefx` | mode, amount, speed | YuNet face detection (`amount` scales the effect — bighead size, laser thickness, halo radius…; `speed` drives every animation) — 0 privacy-pixelate, 1 glossy ring + landmark dots, 2 googly eyes, 3 **bighead**, 4 **deal-with-it sunglasses**, 5 **laser eyes**, 6 **bobblehead**, 7 **third eye**, 8 **crown**, 9 **mirror face**, 10 **cyclops**, 11 **heart eyes**, 12 **interrogation spotlight**, 13 **target lock**, 14 **face satellites**, 15 **melting face**, 16 **sparkle eyes** (anime glints twinkling at eyes and cheeks), 17 **halo** (floating, bobbing, glowing), 18 **clown**, 20 **picasso** (your eyes, nose and mouth swap places — cubism by patch surgery; `amount` = how far they stray), 21 **time ripple**, 22 **fisheye face**, 23 **golden ratio** (the da-Vinci face-analysis meme — fibonacci spiral, phi grid, landmark ticks, and a suspiciously precise symmetry score), 19 **auto-director** (the camera dollies to keep your face centered at constant size — Center Stage for any app; amount = framing tightness, speed = follow) | **yes** | +| `facefx` | mode, amount, speed | YuNet face detection (`amount` scales the effect — bighead size, laser thickness, halo radius…; `speed` drives every animation) — 0 privacy-pixelate, 1 glossy ring + landmark dots, 2 googly eyes, 3 **bighead**, 4 **deal-with-it sunglasses**, 5 **laser eyes**, 6 **bobblehead**, 7 **third eye**, 8 **crown**, 9 **mirror face**, 10 **cyclops**, 11 **heart eyes**, 12 **interrogation spotlight**, 13 **target lock**, 14 **face satellites**, 15 **melting face**, 16 **sparkle eyes** (anime glints twinkling at eyes and cheeks), 17 **halo** (floating, bobbing, glowing), 18 **clown**, 20 **picasso** (your eyes, nose and mouth swap places — cubism by patch surgery; `amount` = how far they stray), 21 **time ripple**, 22 **fisheye face**, 23 **golden ratio**, 24 **face image** — become an animal: `vcam-ctl filter faceimage ~/pics/cat.png` then `filter add facefx 24`; any PNG with transparency tracks your head (scaled by face width, rotated with your eye angle; `amount` = overlay size). Works for animal faces, masks, helmets, meme faces, 19 **auto-director** (the camera dollies to keep your face centered at constant size — Center Stage for any app; amount = framing tightness, speed = follow) | **yes** | | `personfx` | mode, edge, smooth, size, **fx** | person matting, best engine wins (adaptive pacing keeps it realtime — inference cost is measured live and mask updates are spaced to fit your CPU; `size` 256–640 trades matte detail vs speed; **`fx` (p5, 0.2–3) is the per-mode effect-strength dial** — glitch amplitude, fire intensity, ray strength, levitation height, fog density… — adjustable **live**: `vcam-ctl filter set 0 p5 1.8`): **RVM on ONNX Runtime** (`vcam-setup --ort` + `--models-rvm`, build `ORT=1` — correct, temporally-stable, hair-level mattes) → RVM on OpenCV-DNN (auto-disabled when the engine miscomputes it) → PP-HumanSeg — 0 = blur background, 1 = spotlight, 2 = moving gradient, 3 = **your own image** (`vcam-ctl filter bgimage /path/pic.jpg`), 4 = **invisibility cloak**, 5 = **neon person**, 6 = **clone army**, 7 = **window-3D**, 8 = **chrono clones**, 9 = **tiny you**, 10 = **hologram you**, 11 = **rainbow aura** (hue-cycling glow rings around your body), 12 = **painted world** (neural style transfers the *background* while you stay photographic), 13 = **body pixelate** (privacy for everything but the room), 14 = **gravity flip**, 15 = **motion echo**, 16 = **double exposure**, 17 = **glitch body** (only you get datamoshed — band tearing + RGB split; the room stays clean), 18 = **sliced portrait** (you split into slabs sliding apart, gallery-art style), 19 = **disintegration** (you dissolve into drifting embers and re-form, on a loop), 20 = **light-paint silhouette** (your outline writes lingering hue-cycling light trails), 21 = **mirror twin** (you and your flipped double side by side — wave and it waves back with the other hand), 22 = **crystal you** (your body as a flat-shaded low-poly mesh), 23 = **X-ray scanner**, 24 = **wanted poster**, 25 = **stage spotlight** (a theater beam tracks you; dust motes drift in the light), 26 = **haunted shadow** (your wall shadow is your silhouette from one second ago — it lags you and catches up), 27 = **cosmic you** (your body is a window into an animated starfield), 28 = **paper sticker** (thick white cut-out border + drop shadow), 29 = **heat signature**, 30 = **afterimage burst**, 31 = **mandala you** (your outline contour, kaleidoscoped into six spinning neon copies while the real you sits in the center), 32 = **topo aura** (animated topographic rings radiate from your body — a living radar map via distance transform), 33 = **BALL PIT** (physics balls rain down and *bounce off your silhouette* — the matte is the collider, its gradient the surface normal; bat them with your hands), 34 = **orbit rim light** (a virtual studio light circles you; your edge catches it exactly where physics says), 35 = **mind vortex** (the room spirals into your head; you stay solid), 36 = **stained glass**, 37 = **upside-down room**, 38 = **snowfall** (snow lands on your shoulders and head — it piles up on upward-facing surfaces of your silhouette, and tumbles off when you move), 39 = **fire silhouette** (doom-fire heat sim seeded at your outline; flames rise off your body), 40 = **bubbles** (they drift up; touch one and it pops into droplets), 41 = **THOR** (lightning periodically strikes your highest point — raise a hand and the sky answers), 42 = **fireflies** (glowing agents drawn to your outline; they hover around you and scatter if you push into them), 43 = **stardust** (your moving edges shed twinkling glitter), 44 = **matrix you** (digital rain falls *inside* your silhouette), 45 = **black hole you** (the room stretches inward toward you, with an accretion glow ring), 46 = **pet moons**, 47 = **portals**, 48 = **god rays** (volumetric light streams past you — screen-space crepuscular rays, occluded by your silhouette), 49 = **tron trace** (your outline as glowing neon with a bright pulse racing around the perimeter), 50 = **shockwave** (move fast and an expanding refraction ring bursts out of you), 51 = **rapture beam** (a pillar of light takes you — you levitate inside a golden beam with rising sparks), 52 = **kaleido-body** (your matted body folded into eight mirror-wedges — a living mandala of flesh), 53 = **liquid floor** (the bottom of the frame becomes rippling water reflecting the scene), 54 = **astral soul** (a translucent cyan copy of you drifts out of your body and sinks back), 55 = **mystic fog**, and the **pro looks**: 56 = **color pop** (muted mono room, full-color you), 57 = **cinema** (2.39:1 letterbox + teal-orange split-tone + S-curve + grain), 58 = **bokeh pro** (background highlights bloom into real lens discs), 59 = **studio light** (warm key on you, cool rim, eased room + vignette — the look-better button), 60 = **night boost** (shadow lift + gentle denoise on you, room keeps its mood), 61 = **green-screen out** (you over solid chroma for OBS; fx≥1.5 = blue), 62 = **BRB privacy** (leave frame → feed auto-pixelates with a BRB card; return → instant clear), 63 = **pop-out 3D** (soft contact shadow falls from you onto the real room), 64 = **dolly zoom** (the Hitchcock shot — the room breathes scale around your head; you stay fixed), 65 = **duotone poster** (curated two-color gradient maps; fx 1–4 picks the palette) | **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, extra | **emotion-reactive**: an expression model reads your face (7 emotions, ~2 ms) and the effect responds — 0 aura, 1 HUD label, 2 party (happy→confetti, sad→rain, surprised→flash, angry→screen-shake), 3 **emoji face**, 4 **paintmood**, 5 **auto-grade**, 6 **mood ring**, 7 **emotion fountain** (particles pour from behind your head, their physics written by your mood — happy erupts golden, sad drips, angry bursts sparks, surprised rings outward; `extra` = flow), — 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** | diff --git a/include/vcam.h b/include/vcam.h index b4b63c1..362a7aa 100644 --- a/include/vcam.h +++ b/include/vcam.h @@ -221,6 +221,10 @@ typedef enum { 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_GENAI, /* generic img2img ONNX (AnimeGAN etc.) via ORT backend */ + FX_DEPTHFX, /* monocular-depth effects (MiDaS-small via ORT) */ + FX_POSEFX, /* BlazePose body-landmark effects (via ORT) */ + FX_ENHANCE, /* retinex low-light rescue (bad-lighting fixer) */ FX_UNKNOWN, } FilterType; diff --git a/include/vcam_cv.h b/include/vcam_cv.h index abc30a4..23ab5ca 100644 --- a/include/vcam_cv.h +++ b/include/vcam_cv.h @@ -144,6 +144,49 @@ void cv_fx_paintflow(unsigned char *data, int w, int h, int stride, void cv_fx_speedlines(unsigned char *data, int w, int h, int stride, float sens, float density); +/* posefx: BlazePose body landmarks (MediaPipe pose via ORT). + * Model: <models>/pose_estimation_mediapipe_2023mar.onnx + * (vcam-setup --models-pose) or 'filter posemodel <path>'. + * modes: 0 skeleton-glow, 1 neon-bones (dark room, glowing skeleton), + * 2 energy-hands (orbs in your palms; merge them!), 3 wrist-trails. + * fx = size/strength 0.2..3. */ +void cv_fx_pose(unsigned char *data, int w, int h, int stride, + int mode, float fx); +int cv_set_pose_model(const char *path); + +/* depthfx: effects driven by a monocular depth model (MiDaS v2.1 + * small interface) on the ORT backend. Model at <models>/model-small.onnx + * (vcam-setup --models-depth) or set via 'filter depthmodel <path>'. + * modes: 0 depth-blur (true depth-of-field), 1 depth-fog, + * 2 depth-view (colormapped), 3 parallax-wiggle. + * fx = effect strength 0.2..3. Adaptive pacing keeps it live. */ +void cv_fx_depth(unsigned char *data, int w, int h, int stride, + int mode, float fx); +int cv_set_depth_model(const char *path); + +/* genai: run a generic img2img ONNX model (AnimeGAN, CartoonGAN, any + * 1-in/1-out [-1,1] transformer) on the frame via the ORT backend. + * blend 0.2..1 (how much of the transformed image shows, def 1), + * size 128..512 (inference resolution, def 288). Model file is set + * with cv_set_gen_model() ('filter genmodel <path>'), defaulting to + * <models>/img2img.onnx if present. Adaptive pacing keeps it live. */ +void cv_fx_genai(unsigned char *data, int w, int h, int stride, + float blend, float size, float range01); + +/* enhance: retinex low-light rescue (no model needed). strength + * 0.2..2 def 1; denoise 0..1 = shadow noise smoothing. */ +void cv_fx_enhance(unsigned char *data, int w, int h, int stride, + float strength, float denoise); +int cv_set_gen_model(const char *path); +void cv_clear_gen_model(void); + +/* Set the face-overlay image for facefx mode 24 (any PNG; alpha + * channel respected — an animal face with transparency tracks your + * head: scaled by face width, rotated by eye angle). Returns 1 on + * success. cv_clear_face_image() removes it. */ +int cv_set_face_image(const char *path); +void cv_clear_face_image(void); + /* 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. diff --git a/include/vcam_ort.h b/include/vcam_ort.h index 835aac7..b2dde0c 100644 --- a/include/vcam_ort.h +++ b/include/vcam_ort.h @@ -65,6 +65,31 @@ int ort_rvm_init(const char *model_path); int ort_rvm_infer(const float *src_chw, int iw, int ih, float ds, float *pha_out); +/* ── generic img2img session (AnimeGAN / CartoonGAN / any 1-in 1-out + * image transformer). Values are [-1,1] floats, the GAN convention. + * Layout is auto-detected from the model at init. */ +int ort_i2i_init(const char *model_path); /* 1 ok, 0 fail */ +int ort_i2i_layout(void); /* 0 = NCHW, 1 = NHWC */ +/* in/out are w*h*3 floats in the model's own layout; same buffer + * layout for input and output. 1 ok, 0 fail. */ +int ort_i2i_infer(const float *in, int w, int h, float *out); +void ort_i2i_shutdown(void); + +/* ── BlazePose landmarks (MediaPipe pose): input RGB [0,1] NHWC at + * 256x256; landmarks195 = 39 x (x,y,z,vis,pres) in 256-crop space; + * conf1 = person-presence confidence. */ +int ort_pose_init(const char *model_path); +int ort_pose_infer(const float *rgb_nhwc_256, float *landmarks195, + float *conf1); +void ort_pose_shutdown(void); + +/* ── monocular depth (MiDaS-small interface): input RGB [0,1] planar + * CHW at exactly 256x256; output 256*256 floats of relative inverse + * depth (bigger = closer). */ +int ort_depth_init(const char *model_path); +int ort_depth_infer(const float *rgb_chw_256, float *depth_out_65536); +void ort_depth_shutdown(void); + /* Zero the recurrent state (e.g. on a scene cut). Cheap; optional. */ void ort_rvm_reset(void); diff --git a/scripts/vcam-ctl b/scripts/vcam-ctl index 35eee88..f62d50b 100755 --- a/scripts/vcam-ctl +++ b/scripts/vcam-ctl @@ -225,7 +225,46 @@ if [ "${1:-}" = "ai" ]; then case "$T" in *soul*|*astral*|*spirit*) fadd "personfx 54" "astral soul";; esac case "$T" in *fog*|*mist*|*smoke*) fadd "personfx 55" "mystic fog";; esac case "$T" in *golden*|*ratio*|*davinci*|*"da vinci"*|*phi*) fadd "facefx 23" "golden ratio scan";; esac + case "$T" in *cat*|*dog*|*animal*|*tiger*|*bear*|*"face image"*|*mask*me*) + fadd "facefx 24" "face image overlay" + echo " hint: set the image first -> vcam-ctl filter faceimage /path/animal.png";; esac case "$T" in *fountain*|*erupt*) fadd "moodfx 7" "emotion fountain";; esac + case "$T" in *retro*|*sprite*|*pixel*game*|*8bit*|*"8-bit"*) fadd "personfx 66" "retro sprite";; esac + case "$T" in *acid*|*psychedelic*|*"hue cycle"*) fadd "personfx 67" "acid you";; esac + case "$T" in *ascii*|*terminal*) fadd "personfx 68" "ascii you";; esac + case "$T" in *halftone*|*newspaper*|*print*me*) fadd "personfx 69" "halftone print";; esac + case "$T" in *chrome*|*metal*|*t1000*|*terminator*) fadd "personfx 70" "liquid metal";; esac + case "$T" in *contour*|*stripe*) fadd "personfx 71" "contour stripes";; esac + case "$T" in *static*|*"signal lost"*|*"no signal"*) fadd "personfx 72" "static you";; esac + case "$T" in *gold*|*statue*|*trophy*|*oscar*) fadd "personfx 73" "golden statue";; esac + case "$T" in *comic*|*ink*) fadd "personfx 74" "comic ink";; esac + case "$T" in *venetian*|*blind*|*shutter*) fadd "personfx 75" "venetian";; esac + case "$T" in *burn*edge*|*smolder*|*ember*edge*) fadd "personfx 76" "burning edge";; esac + case "$T" in *"glass body"*|*glass*me*|*refract*) fadd "personfx 77" "glass body";; esac + case "$T" in *enhance*|*"bad light"*|*"fix light"*|*brighten*|*"low light"*|*"improve quality"*) + fadd "enhance 1 0.4" "low-light rescue";; esac + case "$T" in *blueprint*|*technical*) fadd "personfx 78" "blueprint";; esac + case "$T" in *brick*|*lego*|*tile*) fadd "personfx 79" "brick tiles";; esac + case "$T" in *silhouette*|*witness*|*anonymous*) fadd "personfx 80" "shadow caller";; esac + case "$T" in *"glow in"*|*luminous*|*radioactive*) fadd "personfx 81" "glow in dark";; esac + case "$T" in *graphite*|*pencil*me*|*sketch*me*) fadd "personfx 82" "graphite";; esac + case "$T" in *"pop poster"*|*warhol*|*screenprint*) fadd "personfx 83" "pop poster";; esac + case "$T" in *riso*|*misregist*|*"offset print"*) fadd "personfx 84" "riso outlines";; esac + case "$T" in *haze*|*shimmer*|*mirage*) fadd "personfx 85" "heat haze";; esac + case "$T" in *security*|*cctv*|*surveil*) fadd "personfx 86" "security cam";; esac + case "$T" in *negative*|*inverted*me*) fadd "personfx 87" "negative you";; esac + case "$T" in *skeleton*|*bones*) fadd "posefx 0" "skeleton";; esac + case "$T" in *"energy hands"*|*orb*|*"power up"*|*goku*) fadd "posefx 2" "energy hands";; esac + case "$T" in *"wrist trail"*|*conduct*|*"draw in air"*) fadd "posefx 3" "wrist trails";; esac + case "$T" in *wing*|*angel*wing*) fadd "posefx 4" "light wings";; esac + case "$T" in *puppet*|*marionette*|*string*) fadd "posefx 5" "puppet strings";; esac + case "$T" in *"depth of field"*|*dof*|*"real bokeh"*) fadd "depthfx 0" "true depth-of-field";; esac + case "$T" in *"depth fog"*|*haze*|*atmosphere*) fadd "depthfx 1" "depth fog";; esac + case "$T" in *"depth view"*|*"depth map"*|*distance*) fadd "depthfx 2" "depth view";; esac + case "$T" in *parallax*|*wiggle*|*"3d effect"*) fadd "depthfx 3" "parallax wiggle";; esac + case "$T" in *anime*|*toon*|*cartoon*me*|*gan*|*"neural transform"*) + fadd "genai 1" "neural img2img" + echo " hint: needs a model -> vcam-ctl filter genmodel /path/animegan.onnx";; esac case "$T" in *"color pop"*|*colorpop*|*"black and white"*) fadd "personfx 56" "color pop";; esac case "$T" in *cinema*|*movie*|*film*) fadd "personfx 57" "cinema grade";; esac case "$T" in *bokeh*) fadd "personfx 58" "bokeh pro";; esac diff --git a/scripts/vcam-setup b/scripts/vcam-setup index 0c3fa9c..cbf56e0 100755 --- a/scripts/vcam-setup +++ b/scripts/vcam-setup @@ -29,6 +29,10 @@ if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then echo " vcam-setup --models-style download the 5 neural style transfer models" echo " vcam-setup --models-rvm download RVM video matting (best personfx quality)" echo " vcam-setup --ort download ONNX Runtime (runs RVM correctly)" + echo " vcam-setup --models-anime [ghibli|hayao|shinkai]" + echo " download an AnimeGAN img2img model for 'genai'" + echo " vcam-setup --models-depth download MiDaS v2.1 small (depthfx: every pixel gets a distance)" + echo " vcam-setup --models-pose download BlazePose landmarks (posefx: skeleton/energy-hands)" exit 0 fi @@ -96,6 +100,116 @@ if [ "${1:-}" = "--models" ]; then exit "$rc" fi +# ── BlazePose landmarks for the 'posefx' filter ────────────── +# OpenCV-zoo export, same host that serves our face/seg/FER models. +if [ "${1:-}" = "--models-pose" ]; then + MODELS_DIR="${VCAM_MODELS_DIR:-$HOME/.local/share/vcam/models}" + mkdir -p "$MODELS_DIR" || { echo "Error: cannot create $MODELS_DIR" >&2; exit 1; } + DEST="$MODELS_DIR/pose_estimation_mediapipe_2023mar.onnx" + U="https://huggingface.co/opencv/pose_estimation_mediapipe/resolve/main/pose_estimation_mediapipe_2023mar.onnx" + if [ -s "$DEST" ]; then + echo "already present: $DEST" + else + if command -v curl >/dev/null 2>&1; then DL="curl -fL --retry 3 -o"; + elif command -v wget >/dev/null 2>&1; then DL="wget -O"; else + echo "Error: need curl or wget." >&2; exit 1; fi + echo "downloading BlazePose landmarks (~5 MB) ..." + # shellcheck disable=SC2086 + if $DL "$DEST" "$U" && [ -s "$DEST" ] \ + && [ "$(wc -c < "$DEST")" -gt 1000000 ]; then + echo "ok: $DEST" + else + rm -f "$DEST"; echo "FAILED to download $U" >&2; exit 1 + fi + fi + echo "" + echo "Use it:" + echo " vcam-ctl filter add posefx 2 # energy orbs in your palms" + echo " vcam-ctl filter add posefx 0 # glowing skeleton" + exit 0 +fi + +# ── MiDaS depth model for the 'depthfx' filter ─────────────── +# Official release asset, URL taken from the MiDaS repo's own docs +# (github.com/isl-org/MiDaS, tag v2_1). ~64 MB. +if [ "${1:-}" = "--models-depth" ]; then + MODELS_DIR="${VCAM_MODELS_DIR:-$HOME/.local/share/vcam/models}" + mkdir -p "$MODELS_DIR" || { echo "Error: cannot create $MODELS_DIR" >&2; exit 1; } + DEST="$MODELS_DIR/model-small.onnx" + U="https://github.com/isl-org/MiDaS/releases/download/v2_1/model-small.onnx" + if [ -s "$DEST" ]; then + echo "already present: $DEST" + else + if command -v curl >/dev/null 2>&1; then DL="curl -fL --retry 3 -o"; + elif command -v wget >/dev/null 2>&1; then DL="wget -O"; else + echo "Error: need curl or wget." >&2; exit 1; fi + echo "downloading MiDaS v2.1 small ..." + # shellcheck disable=SC2086 + if $DL "$DEST" "$U" && [ -s "$DEST" ] \ + && [ "$(wc -c < "$DEST")" -gt 1000000 ]; then + echo "ok: $DEST" + else + rm -f "$DEST" + echo "FAILED to download $U" >&2; exit 1 + fi + fi + echo "" + echo "Use it:" + echo " vcam-ctl filter add depthfx 0 # true depth-of-field" + echo " vcam-ctl filter add depthfx 3 # 3D parallax wiggle" + exit 0 +fi + +# ── AnimeGAN img2img models for the 'genai' neural filter ──── +# Official AnimeGANv3 releases (github.com/TachibanaYoshino/AnimeGANv3). +# Their documented I/O convention (RGB, /127.5-1, sizes %8==0) is +# exactly what vcam's genai engine implements. The Ghibli asset's URL +# is taken from the project's own docs; for the others we probe a few +# plausible release tags, since assets are spread across releases. +if [ "${1:-}" = "--models-anime" ]; then + STYLE="${2:-ghibli}" + case "$STYLE" in + ghibli) ASSET="AnimeGANv3_large_Ghibli_c1_e299.onnx"; TAGS="1.0 v1.0" ;; + hayao) ASSET="AnimeGANv3_Hayao_36.onnx"; TAGS="v1.1.0 1.1.0 v1.0 1.0" ;; + shinkai) ASSET="AnimeGANv3_Shinkai_37.onnx"; TAGS="v1.1.0 1.1.0 v1.0 1.0" ;; + *) echo "Error: style must be ghibli, hayao, or shinkai" >&2; exit 1 ;; + esac + MODELS_DIR="${VCAM_MODELS_DIR:-$HOME/.local/share/vcam/models}" + mkdir -p "$MODELS_DIR" || { echo "Error: cannot create $MODELS_DIR" >&2; exit 1; } + DEST="$MODELS_DIR/$ASSET" + if [ -s "$DEST" ]; then + echo "already present: $DEST" + else + if command -v curl >/dev/null 2>&1; then DL="curl -fL --retry 2 -o"; + elif command -v wget >/dev/null 2>&1; then DL="wget -O"; + else echo "Error: need curl or wget." >&2; exit 1; fi + GOT="" + for TAG in $TAGS; do + U="https://github.com/TachibanaYoshino/AnimeGANv3/releases/download/$TAG/$ASSET" + echo "trying $U ..." + # shellcheck disable=SC2086 + if $DL "$DEST" "$U" 2>/dev/null && [ -s "$DEST" ] \ + && [ "$(wc -c < "$DEST")" -gt 1000000 ]; then + GOT=1; break + fi + rm -f "$DEST" + done + if [ -z "$GOT" ]; then + echo "FAILED — the asset may live under a different release tag." >&2 + echo "Browse https://github.com/TachibanaYoshino/AnimeGANv3/releases ," >&2 + echo "download any .onnx, then: vcam-ctl filter genmodel /path/to/it" >&2 + exit 1 + fi + echo "ok: $DEST" + fi + echo "" + echo "Use it:" + echo " vcam-ctl filter genmodel $DEST" + echo " vcam-ctl filter add genai # full anime transform" + echo " vcam-ctl filter set 0 p2 224 # smaller = faster if laggy" + exit 0 +fi + # ── ONNX Runtime: the backend that runs RVM correctly ──────── # OpenCV 5's young DNN graph engine loads RVM but miscomputes it # (empty mattes). ONNX Runtime is RVM's reference runtime. This diff --git a/scripts/vcam-tune b/scripts/vcam-tune index 753a6b4..2e3efb8 100755 --- a/scripts/vcam-tune +++ b/scripts/vcam-tune @@ -61,7 +61,7 @@ declare -A MODE_CACHE # "filtername" -> newline list "N name" # itself ('filter modes <name>' — single source of truth in ipc.c). mode_list() { local name=$1 - case "$name" in personfx|facefx|moodfx|styleai) ;; *) return 1 ;; esac + case "$name" in personfx|facefx|moodfx|styleai|depthfx|posefx) ;; *) return 1 ;; esac if [[ -z "${MODE_CACHE[$name]:-}" ]]; then MODE_CACHE[$name]=$(ipc_lines "filter modes $name" \ | sed -n 's/^OK *\([0-9][0-9]*\) \(.*\)$/\1 \2/p') @@ -109,7 +109,8 @@ n_params_for() { 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|paintflow|speedlines) echo 2 ;; + meltdown|rotozoom|starfield|lightning|scatter|vhs|outline|timebubble|paintflow|speedlines|depthfx|posefx|enhance) echo 2 ;; + genai) echo 3 ;; *) echo 1 ;; esac } @@ -247,6 +248,15 @@ param_label() { moodfx:1) echo "mode" ;; moodfx:2) echo "gain" ;; moodfx:3) echo "extra" ;; + genai:1) echo "blend" ;; + genai:2) echo "size" ;; + genai:3) echo "range01" ;; + enhance:1) echo "strength" ;; + enhance:2) echo "denoise" ;; + depthfx:1) echo "mode" ;; + depthfx:2) echo "fx" ;; + posefx:1) echo "mode" ;; + posefx:2) echo "fx" ;; speedlines:1) echo "sens" ;; speedlines:2) echo "density" ;; paintflow:1) echo "strength" ;; @@ -329,6 +339,7 @@ param_step() { moodfx:3) echo 0.1 ;; facefx:2) echo 0.1 ;; facefx:3) echo 0.1 ;; + genai:2) echo 32 ;; paintflow:2) echo 0.01 ;; clones:2) echo 0.5 ;; clones:3) echo 0.05 ;; @@ -786,7 +797,7 @@ while :; do mode_list "$name" | awk '{printf " %2s %-18s", $1, $2; if (NR % 3 == 0) printf "\n"} END {printf "\n"}' printf "mode # (enter=cancel): " - local _stty_pick; _stty_pick=$(stty -g) + _stty_pick=$(stty -g) stty echo icanon IFS= read -r pick stty "$_stty_pick" diff --git a/src/filter.c b/src/filter.c index 10c060a..5089dc3 100644 --- a/src/filter.c +++ b/src/filter.c @@ -187,6 +187,10 @@ static const struct { const char *name; FilterType t; } NAMES[] = { {"paintflow", FX_CV_PAINT}, {"smear", FX_CV_PAINT}, {"speedlines", FX_CV_SPEED}, + {"genai", FX_GENAI}, + {"depthfx", FX_DEPTHFX}, + {"posefx", FX_POSEFX}, + {"enhance", FX_ENHANCE}, {"anime", FX_CV_SPEED}, /* new effect additions */ {"saturate", FX_SATURATE}, @@ -321,6 +325,10 @@ float filter_default_param(FilterType t) case FX_CV_MOOD: return 0.0f; /* mode 0 = aura */ case FX_CV_PAINT: return 1.0f; case FX_CV_SPEED: return 1.0f; + case FX_GENAI: return 1.0f; + case FX_DEPTHFX: return 0.0f; + case FX_POSEFX: return 0.0f; + case FX_ENHANCE: return 1.0f; default: return 0.0f; } } @@ -5909,6 +5917,10 @@ void filter_chain_apply(FilterChain *fc, Frame *frame) case FX_CV_MOOD: cv_fx_mood (frame->data, frame->width, frame->height, frame->stride, (int)f->param, f->param2, f->param3); 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; + case FX_GENAI: cv_fx_genai (frame->data, frame->width, frame->height, frame->stride, f->param, f->param2, f->param3); break; + case FX_DEPTHFX: cv_fx_depth (frame->data, frame->width, frame->height, frame->stride, (int)f->param, f->param2); break; + case FX_POSEFX: cv_fx_pose (frame->data, frame->width, frame->height, frame->stride, (int)f->param, f->param2); break; + case FX_ENHANCE: cv_fx_enhance(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 9d5e5fa..8928c1b 100644 --- a/src/ipc.c +++ b/src/ipc.c @@ -151,12 +151,18 @@ static const char *PERSONFX_MODES[] = { "shockwave","rapture-beam","kaleido-body","liquid-floor","astral-soul", "mystic-fog","color-pop","cinema","bokeh-pro","studio-light","night-boost", "green-screen","brb-privacy","pop-out-3d","dolly-zoom","duotone-poster", + "retro-sprite","acid-you","ascii-you","halftone-print","liquid-metal", + "contour-stripes","static-you","golden-statue","comic-ink","venetian", + "burning-edge","glass-body","blueprint","brick-tiles","shadow-caller", + "glow-in-dark","graphite","pop-poster","riso-outlines","heat-haze", + "security-cam","negative-you", }; static const char *FACEFX_MODES[] = { "pixelate","ring-dots","googly-eyes","bighead","deal-with-it","laser-eyes", "bobblehead","third-eye","crown","mirror-face","cyclops","heart-eyes", "interrogation","target-lock","face-satellites","melting-face","sparkle-eyes", "halo","clown","auto-director","picasso","time-ripple","fisheye","golden-ratio", + "face-image", }; static const char *MOODFX_MODES[] = { "aura","hud","party","emoji","paintmood","auto-grade","mood-ring","fountain", @@ -164,6 +170,13 @@ static const char *MOODFX_MODES[] = { static const char *STYLEAI_MODES[] = { "mosaic","candy","rain-princess","udnie","pointilism", }; +static const char *DEPTHFX_MODES[] = { + "depth-blur","depth-fog","depth-view","parallax", +}; +static const char *POSEFX_MODES[] = { + "skeleton","neon-bones","energy-hands","wrist-trails","light-wings", + "puppet-strings", +}; static void handle_command(int client_fd, char *line, OverlayRegistry *reg) { @@ -358,7 +371,19 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg) send_line(client_fd, "OK facefx extra modes: 5=LASERS 6=BOBBLE 7=3RD-EYE 8=CROWN 9=MIRROR 10=CYCLOPS 11=HEART-EYES 12=INTERROGATE 13=TARGET-LOCK"); send_line(client_fd, "OK 14=FACE-SATELLITES 15=MELTING-FACE 16=SPARKLE-EYES 17=HALO 18=CLOWN"); send_line(client_fd, "OK 19=AUTO-DIRECTOR (camera follows + frames your face; amount=tightness speed=follow)"); - send_line(client_fd, "OK 20=PICASSO 21=TIME-RIPPLE 22=FISHEYE 23=GOLDEN-RATIO (da-Vinci face analysis)"); + send_line(client_fd, "OK 20=PICASSO 21=TIME-RIPPLE 22=FISHEYE 23=GOLDEN-RATIO 24=FACE-IMAGE (your PNG tracks your head)"); + send_line(client_fd, "OK filter faceimage <path|off> set the PNG for facefx 24 — ANY animal face / mask / meme with transparency"); + send_line(client_fd, "OK genai [<blend> <size>] NEURAL img2img: run ANY 1-in/1-out ONNX (AnimeGAN, CartoonGAN...) on every frame"); + send_line(client_fd, "OK via ONNX Runtime; model: filter genmodel <path> (or <models>/img2img.onnx)"); + send_line(client_fd, "OK blend 0.2..1 (def 1) size 128..512 (def 288) p3: 0=[-1,1] GAN, 1=[0,1] models"); + send_line(client_fd, "OK p3=1 fits AI low-light nets (Zero-DCE class): filter genmodel <path>, add genai 1 288 1"); + send_line(client_fd, "OK depthfx <mode> [<fx>] MONOCULAR DEPTH (MiDaS): every pixel gets a distance (vcam-setup --models-depth)"); + send_line(client_fd, "OK 0=DEPTH-BLUR (true DoF) 1=DEPTH-FOG 2=DEPTH-VIEW 3=PARALLAX-WIGGLE; fx=strength"); + send_line(client_fd, "OK enhance [<strength> <denoise>] LOW-LIGHT RESCUE: retinex shadow lift + auto white balance + shadow denoise"); + send_line(client_fd, "OK strength 0.2..2 (def 1), denoise 0..1 — fixes bad lighting, no model needed"); + send_line(client_fd, "OK posefx <mode> [<fx>] BODY LANDMARKS (BlazePose): vcam sees your skeleton (vcam-setup --models-pose)"); + send_line(client_fd, "OK 0=SKELETON 1=NEON-BONES 2=ENERGY-HANDS (merge palms!) 3=WRIST-TRAILS"); + send_line(client_fd, "OK 4=LIGHT-WINGS (beating, on your shoulders) 5=PUPPET-STRINGS"); send_line(client_fd, "OK personfx extra modes: 9=TINY 10=HOLOGRAM 11=RAINBOW-AURA 12=PAINTED-WORLD 13=BODY-PIXELATE 14=GRAVITY-FLIP"); send_line(client_fd, "OK 15=MOTION-ECHO 16=DOUBLE-EXPOSURE 17=GLITCH-BODY 18=SLICED 19=DISINTEGRATE"); send_line(client_fd, "OK 20=LIGHT-PAINT 21=MIRROR-TWIN 22=CRYSTAL 23=X-RAY-SCAN 24=WANTED-POSTER"); @@ -371,7 +396,12 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg) send_line(client_fd, "OK 48=GOD-RAYS 49=TRON-TRACE 50=SHOCKWAVE (move fast!) 51=RAPTURE-BEAM"); send_line(client_fd, "OK 52=KALEIDO-BODY 53=LIQUID-FLOOR 54=ASTRAL-SOUL 55=MYSTIC-FOG"); send_line(client_fd, "OK PRO LOOKS: 56=COLOR-POP 57=CINEMA 58=BOKEH-PRO 59=STUDIO-LIGHT 60=NIGHT-BOOST"); - send_line(client_fd, "OK 61=GREEN-SCREEN-OUT 62=BRB-PRIVACY (auto) 63=POP-OUT-3D 64=DOLLY-ZOOM 65=DUOTONE"); + send_line(client_fd, "OK 61=GREEN-SCREEN-OUT 62=BRB-PRIVACY 63=POP-OUT-3D 64=DOLLY-ZOOM 65=DUOTONE"); + send_line(client_fd, "OK 66=RETRO-SPRITE 67=ACID-YOU 68=ASCII-YOU 69=HALFTONE-PRINT 70=LIQUID-METAL"); + send_line(client_fd, "OK 71=CONTOUR-STRIPES 72=STATIC-YOU (signal lost) 73=GOLDEN-STATUE 74=COMIC-INK"); + send_line(client_fd, "OK 75=VENETIAN 76=BURNING-EDGE 77=GLASS-BODY 78=BLUEPRINT 79=BRICK-TILES"); + send_line(client_fd, "OK 80=SHADOW-CALLER 81=GLOW-IN-DARK 82=GRAPHITE 83=POP-POSTER 84=RISO-OUTLINES"); + send_line(client_fd, "OK 85=HEAT-HAZE 86=SECURITY-CAM 87=NEGATIVE-YOU"); send_line(client_fd, "OK filter modes <name> list ALL modes of personfx/facefx/moodfx/styleai BY NAME"); send_line(client_fd, "OK personfx p5 = fx per-mode effect strength 0.2..3 (glitch amp, fire, rays, lift, fog...) — tune LIVE:"); send_line(client_fd, "OK vcam-ctl filter set 0 p5 1.8"); @@ -516,8 +546,12 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg) { tbl = MOODFX_MODES; n2 = (int)(sizeof MOODFX_MODES/sizeof *MOODFX_MODES); } else if (fname && (!strcmp(fname,"styleai")||!strcmp(fname,"neuralstyle"))) { tbl = STYLEAI_MODES; n2 = (int)(sizeof STYLEAI_MODES/sizeof *STYLEAI_MODES); } + else if (fname && !strcmp(fname,"depthfx")) + { tbl = DEPTHFX_MODES; n2 = (int)(sizeof DEPTHFX_MODES/sizeof *DEPTHFX_MODES); } + else if (fname && !strcmp(fname,"posefx")) + { tbl = POSEFX_MODES; n2 = (int)(sizeof POSEFX_MODES/sizeof *POSEFX_MODES); } if (!tbl) { - send_line(client_fd, "ERR usage: filter modes <personfx|facefx|moodfx|styleai>"); + send_line(client_fd, "ERR usage: filter modes <personfx|facefx|moodfx|styleai|depthfx|posefx>"); return; } char b[96]; @@ -528,6 +562,84 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg) return; } + if (strcmp(sub, "posemodel") == 0) { + char *path = strtok_r(NULL, "", &save); + while (path && (*path == ' ' || *path == '\t')) path++; + if (!path || !*path) { + send_line(client_fd, "ERR usage: filter posemodel </abs/path/pose.onnx>"); + return; + } + if (cv_set_pose_model(path)) + send_line(client_fd, "OK pose model set — 'filter add posefx <0-3>'"); + else + send_line(client_fd, "ERR file not found"); + return; + } + + if (strcmp(sub, "depthmodel") == 0) { + char *path = strtok_r(NULL, "", &save); + while (path && (*path == ' ' || *path == '\t')) path++; + if (!path || !*path) { + send_line(client_fd, "ERR usage: filter depthmodel </abs/path/model-small.onnx>"); + return; + } + if (cv_set_depth_model(path)) + send_line(client_fd, "OK depth model set — 'filter add depthfx <0-3>'"); + else + send_line(client_fd, "ERR file not found"); + return; + } + + if (strcmp(sub, "genmodel") == 0) { + /* filter genmodel <path.onnx> — img2img model for 'genai' + * filter genmodel off — unload */ + char *path = strtok_r(NULL, "", &save); + while (path && (*path == ' ' || *path == '\t')) path++; + if (!path || !*path) { + send_line(client_fd, "ERR usage: filter genmodel </abs/path/model.onnx | off>"); + send_line(client_fd, "ERR then: filter add genai [blend 0.2-1] [size 128-512]"); + return; + } + if (!strcmp(path, "off") || !strcmp(path, "none")) { + cv_clear_gen_model(); + send_line(client_fd, "OK genai model unloaded"); + return; + } + if (cv_set_gen_model(path)) { + send_line(client_fd, "OK genai model set — 'filter add genai' transforms every frame through it"); + } else { + send_line(client_fd, "ERR file not found (absolute path to a .onnx)"); + } + return; + } + + if (strcmp(sub, "faceimage") == 0) { + /* filter faceimage <path> — overlay PNG for facefx mode 24 + * filter faceimage off — remove it */ + char *path = strtok_r(NULL, "", &save); + while (path && (*path == ' ' || *path == '\t')) path++; + if (!path || !*path) { + send_line(client_fd, "ERR usage: filter faceimage </abs/path/animal.png | off>"); + send_line(client_fd, "ERR used by: filter add facefx 24 (PNG tracks your face; alpha respected)"); + return; + } + if (!strcmp(path, "off") || !strcmp(path, "none")) { + cv_clear_face_image(); + send_line(client_fd, "OK face image cleared"); + return; + } + if (!cv_available()) { + send_line(client_fd, "ERR this build has no OpenCV (rebuild with 'make OPENCV=1')"); + return; + } + if (cv_set_face_image(path)) { + send_line(client_fd, "OK face image loaded — add/keep 'facefx 24' and it tracks your head"); + } else { + send_line(client_fd, "ERR could not load image (PNG with transparency works best)"); + } + 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) */ diff --git a/src/opencv_fx.cpp b/src/opencv_fx.cpp index 614ed2a..53da10c 100644 --- a/src/opencv_fx.cpp +++ b/src/opencv_fx.cpp @@ -217,6 +217,15 @@ struct BgImgState { }; BgImgState g_bgimg; +/* User-supplied face-overlay image (PNG with alpha) for facefx mode 24, + * set via 'vcam-ctl filter faceimage <path>'. Tracked to the face: + * scaled by face width, rotated by eye angle. */ +struct FaceImgState { + cv::Mat rgba; /* as loaded, 4-channel */ + std::mutex mtx; +}; +FaceImgState g_faceimg; + /* paintflow: a persistent canvas advected by dense optical flow — * moving objects drag the paint with them. */ struct PaintState { @@ -1034,6 +1043,100 @@ void cv_fx_face(unsigned char *data, int w, int h, int stride, int mode, cv::circle(img, eye, std::max(2, fw/20), cv::Scalar(255,255,255), cv::FILLED); } + } else if (mode == 24) { + /* FACE IMAGE: your uploaded PNG (animal face, mask, + * meme...) tracked to your face — scaled by face width, + * rotated by your eye angle, alpha-composited. + * Set it with: vcam-ctl filter faceimage <path> + * amount = overlay size. */ + std::lock_guard<std::mutex> fl2(g_faceimg.mtx); + if (!g_faceimg.rgba.empty()) { + double ang = std::atan2((double)(f[7]-f[5]), + (double)(f[6]-f[4])) * 57.2958; + /* ── AR life signs, all from YuNet's 5 landmarks ── + * jaw: nose→mouth distance vs. its running "closed" + * baseline -> mouth-open amount; yaw: nose offset + * from the eye midpoint -> head turn. */ + float emx = (f[4]+f[6])*0.5f*inv; + float nsx = f[8]*inv, nsy = f[9]*inv; + float mmx = (f[10]+f[12])*0.5f*inv, mmy2 = (f[11]+f[13])*0.5f*inv; + float nm = std::sqrt((mmx-nsx)*(mmx-nsx)+(mmy2-nsy)*(mmy2-nsy)) + / std::max(1.0f, (float)fh); + static float nm_base = -1; + if (nm_base < 0) nm_base = nm; + if (nm < nm_base) nm_base += (nm - nm_base) * 0.10f; + else nm_base += (nm - nm_base) * 0.004f; + float open2 = std::max(0.0f, std::min(1.0f, + (nm - nm_base*1.06f) / (nm_base*0.45f + 1e-4f))); + float yaw = (nsx - emx) / std::max(1.0f, (float)fw); /* ± ~0.3 */ + /* lighting match: your face region's light tints the mask */ + float lr2=0, lg2=0, lb2=0; int ln2=0; + for (int yy = y; yy < y+fh; yy += 8) + for (int xx = x; xx < x+fw; xx += 8) { + if (xx<0||yy<0||xx>=w||yy>=h) continue; + const cv::Vec3b &pv = img.at<cv::Vec3b>(yy,xx); + lb2+=pv[0]; lg2+=pv[1]; lr2+=pv[2]; ln2++; + } + float kb=1, kg=1, kr=1; + if (ln2 > 4) { + kb = std::min(1.35f, std::max(0.55f, (lb2/ln2)/150.0f)); + kg = std::min(1.35f, std::max(0.55f, (lg2/ln2)/150.0f)); + kr = std::min(1.35f, std::max(0.55f, (lr2/ln2)/150.0f)); + } + int S = std::max(24, (int)(fw * 1.9f * amount)); + int cx3 = x + fw/2 + (int)(yaw * S * 0.45f); /* turn */ + int cy3 = y + fh/2 - fh/12; + int x0 = cx3 - S/2, y0 = cy3 - S/2; + if (x0 >= 0 && y0 >= 0 && x0+S < w && y0+S < h) { + /* affine: PNG -> S x S canvas, rotated (manual + * 2x3, version-proof), transparent border */ + double sc2 = (double)S / std::max(g_faceimg.rgba.cols, + g_faceimg.rgba.rows); + double ra = -ang * 3.14159265 / 180.0; + double ca2 = std::cos(ra)*sc2, sa2 = std::sin(ra)*sc2; + double pcx = g_faceimg.rgba.cols/2.0; + double pcy = g_faceimg.rgba.rows/2.0; + double abuf[6] = { ca2, sa2, S/2.0 - ca2*pcx - sa2*pcy, + -sa2, ca2, S/2.0 + sa2*pcx - ca2*pcy }; + cv::Mat A2(2, 3, CV_64F, abuf); + cv::Mat canvas; + cv::warpAffine(g_faceimg.rgba, canvas, A2, + cv::Size(S, S), cv::INTER_LINEAR, + cv::BORDER_CONSTANT, cv::Scalar(0,0,0,0)); + /* composite with a live jaw: the bottom of the + * mask drops when YOUR mouth opens; the gap is + * a darkened mouth interior. */ + int split = (int)(S * 0.60f); + int drop = (int)(open2 * S * 0.13f); + for (int yy = 0; yy < S; yy++) { + int sy3; /* source canvas row */ + float dark = 1.0f; + if (yy < split) sy3 = yy; + else if (yy < split + drop) { sy3 = split; dark = 0.35f; } + else sy3 = yy - drop; + const cv::Vec4b *sp = canvas.ptr<cv::Vec4b>(sy3); + cv::Vec3b *dp = img.ptr<cv::Vec3b>(y0+yy) + x0; + for (int xx = 0; xx < S; xx++) { + float al = sp[xx][3] / 255.0f; + if (al < 0.02f) continue; + float b3 = sp[xx][0]*kb*dark; + float g3 = sp[xx][1]*kg*dark; + float r3 = sp[xx][2]*kr*dark; + if (b3>255)b3=255; + if (g3>255)g3=255; + if (r3>255)r3=255; + dp[xx][0]=(uchar)(dp[xx][0]+(b3-dp[xx][0])*al); + dp[xx][1]=(uchar)(dp[xx][1]+(g3-dp[xx][1])*al); + dp[xx][2]=(uchar)(dp[xx][2]+(r3-dp[xx][2])*al); + } + } + } + } else { + warn_once("faceimg_miss", + "facefx 24: no face image set — " + "vcam-ctl filter faceimage /path/animal.png " + "(PNG with transparency works best)"); + } } else if (mode == 23) { /* GOLDEN RATIO: the da-Vinci face-analysis meme — * fibonacci spiral, phi grid, rotating measurement @@ -1586,6 +1689,537 @@ mask_ready: ; } return; } + if (mode == 78) { + /* BLUEPRINT: you as a technical drawing — deep blue fill, + * white construction edges and a drafting grid; the room + * stays photographic. fx = line density. */ + cv::Mat gray, gx2, gy2; + cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY); + cv::Sobel(gray, gx2, CV_32F, 1, 0, 3); + cv::Sobel(gray, gy2, CV_32F, 0, 1, 3); + float thr = 240.0f / fx; + for (int y = 0; y < img.rows; y++) { + const float *mm = g_seg.mask.ptr<float>(y); + const float *ex = gx2.ptr<float>(y); + const float *ey = gy2.ptr<float>(y); + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + for (int x = 0; x < img.cols; x++) { + float a = mm[x]; if (a < 0.05f) continue; + float e = std::fabs(ex[x]) + std::fabs(ey[x]); + bool grid = (x % 24 == 0) || (y % 24 == 0); + cv::Vec3b c = e > thr ? cv::Vec3b(245,245,250) + : grid ? cv::Vec3b(150,105,60) + : cv::Vec3b(110,60,20); + ip[x][0]=(uchar)(ip[x][0]+(c[0]-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+(c[1]-ip[x][1])*a); + ip[x][2]=(uchar)(ip[x][2]+(c[2]-ip[x][2])*a); + } + } + return; + } + if (mode == 79) { + /* BRICK TILES: you built from beveled plastic tiles — lit + * top-left edge, shadowed bottom-right. fx = tile size. */ + int C = std::max(8, (int)(14 * fx)); + cv::Mat keep = img.clone(); + for (int y0 = 0; y0 + C <= img.rows; y0 += C) + for (int x0 = 0; x0 + C <= img.cols; x0 += C) { + if (g_seg.mask.at<float>(y0+C/2, x0+C/2) < 0.4f) continue; + cv::Vec3b c = keep.at<cv::Vec3b>(y0+C/2, x0+C/2); + c[0]=(c[0]/48)*48+24; c[1]=(c[1]/48)*48+24; c[2]=(c[2]/48)*48+24; + cv::rectangle(img, cv::Rect(x0, y0, C, C), + cv::Scalar(c[0],c[1],c[2]), cv::FILLED); + cv::line(img, {x0,y0}, {x0+C-1,y0}, + cv::Scalar(std::min(255,c[0]+55),std::min(255,c[1]+55), + std::min(255,c[2]+55)), 2); + cv::line(img, {x0,y0}, {x0,y0+C-1}, + cv::Scalar(std::min(255,c[0]+55),std::min(255,c[1]+55), + std::min(255,c[2]+55)), 2); + cv::line(img, {x0+1,y0+C-1}, {x0+C-1,y0+C-1}, + cv::Scalar(c[0]*2/3,c[1]*2/3,c[2]*2/3), 2); + cv::circle(img, {x0+C/2, y0+C/2}, C/5, + cv::Scalar(std::min(255,c[0]+30),std::min(255,c[1]+30), + std::min(255,c[2]+30)), 1); + } + return; + } + if (mode == 80) { + /* SHADOW CALLER: you become a flat black silhouette with a + * cold rim — witness-protection chic. fx = rim strength. */ + 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); + for (int x = 0; x < img.cols; x++) { + float a = mm[x]; if (a < 0.04f) continue; + float rim = (a < 0.55f) ? (0.55f-a)/0.51f : 0.0f; + int rb = (int)(rim * 150 * fx); + ip[x][0]=(uchar)(ip[x][0]*(1-a) + std::min(255, 18+rb)*a); + ip[x][1]=(uchar)(ip[x][1]*(1-a) + std::min(255, 14+rb/2)*a); + ip[x][2]=(uchar)(ip[x][2]*(1-a) + 12*a); + } + } + return; + } + if (mode == 81) { + /* GLOW IN THE DARK: lights out — you luminesce toxic green, + * brighter where you were brighter. fx = glow. */ + 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); + for (int x = 0; x < img.cols; x++) { + float a = mm[x]; + float lum = (ip[x][0]*0.114f+ip[x][1]*0.587f+ip[x][2]*0.299f)/255.f; + if (a < 0.05f) { + ip[x][0]=(uchar)(ip[x][0]*0.12f); + ip[x][1]=(uchar)(ip[x][1]*0.14f); + ip[x][2]=(uchar)(ip[x][2]*0.12f); + continue; + } + float g2 = std::min(255.f, (40 + lum*215) * fx); + ip[x][0]=(uchar)(ip[x][0]+((g2*0.35f)-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+(g2-ip[x][1])*a); + ip[x][2]=(uchar)(ip[x][2]+((g2*0.25f)-ip[x][2])*a); + } + } + return; + } + if (mode == 82) { + /* GRAPHITE: you sketched in pencil (classic dodge-blend: + * luma over its own blur), room in color. fx = contrast. */ + cv::Mat gray, blur2; + cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY); + cv::GaussianBlur(gray, blur2, cv::Size(0,0), 5.0); + for (int y = 0; y < img.rows; y++) { + const float *mm = g_seg.mask.ptr<float>(y); + const uchar *gp = gray.ptr<uchar>(y); + const uchar *bp = blur2.ptr<uchar>(y); + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + for (int x = 0; x < img.cols; x++) { + float a = mm[x]; if (a < 0.05f) continue; + float v = 255.0f * gp[x] / (256.0f - std::min(254, (int)bp[x])); + v = 255.0f - (255.0f - std::min(255.f, v)) * fx; + if (v < 0) v = 0; + uchar u2 = (uchar)v; + ip[x][0]=(uchar)(ip[x][0]+(u2-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+(u2-ip[x][1])*a); + ip[x][2]=(uchar)(ip[x][2]+(u2-ip[x][2])*a); + } + } + return; + } + if (mode == 83) { + /* POP POSTER: you in flat two-tone screen-print; the ink + * color steps to a new one every couple of seconds. + * fx = switch speed. */ + unsigned tk = g_seg.counter; + static const int INK[5][3] = { + {180,40,230},{40,180,255},{200,180,20},{60,220,90},{230,90,50}}; + int pi = (int)(tk * 0.01f * fx) % 5; + const int *I2 = INK[pi]; + 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); + 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)/255.f; + cv::Vec3b c = lum > 0.52f + ? cv::Vec3b(240, 238, 232) + : cv::Vec3b((uchar)I2[0], (uchar)I2[1], (uchar)I2[2]); + ip[x][0]=(uchar)(ip[x][0]+(c[0]-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+(c[1]-ip[x][1])*a); + ip[x][2]=(uchar)(ip[x][2]+(c[2]-ip[x][2])*a); + } + } + return; + } + if (mode == 84) { + /* RISO OUTLINES: three offset colored contours around your + * silhouette — misregistered print, on purpose. fx = offset. */ + cv::Mat m8, d1; + g_seg.mask.convertTo(m8, CV_8U, 255.0); + cv::dilate(m8, d1, cv::Mat(), cv::Point(-1,-1), 2); + int off = std::max(2, (int)(5 * fx)); + static const int OC[3][3] = {{60,60,235},{235,180,40},{200,80,200}}; + for (int y = 0; y < img.rows; y++) { + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + for (int x = 0; x < img.cols; x++) { + for (int k2 = 0; k2 < 3; k2++) { + int sx2 = x + (k2-1)*off, sy2 = y + (k2==2?off:(k2==0?-off:0)); + if (sx2<1||sy2<1||sx2>=img.cols-1||sy2>=img.rows-1) continue; + uchar c2 = d1.at<uchar>(sy2, sx2); + uchar e2 = m8.at<uchar>(sy2, sx2); + if (c2 > 128 && e2 < 128) { + ip[x][0]=clamp_int_u8(ip[x][0]/2+OC[k2][0]/2); + ip[x][1]=clamp_int_u8(ip[x][1]/2+OC[k2][1]/2); + ip[x][2]=clamp_int_u8(ip[x][2]/2+OC[k2][2]/2); + } + } + } + } + return; + } + if (mode == 85) { + /* HEAT HAZE: you shimmer like air over asphalt — small + * animated refraction inside your silhouette only. + * fx = shimmer. */ + unsigned tk = g_seg.counter; + cv::Mat keep = img.clone(); + float A2 = 3.5f * fx; + 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); + for (int x = 0; x < img.cols; x++) { + float a = mm[x]; if (a < 0.05f) continue; + int sx2 = x + (int)(std::sin(y*0.16f + tk*0.22f) * A2 * a); + int sy2 = y + (int)(std::sin(x*0.13f + tk*0.17f) * A2 * 0.6f * a); + sx2 = std::max(0, std::min(img.cols-1, sx2)); + sy2 = std::max(0, std::min(img.rows-1, sy2)); + ip[x] = keep.at<cv::Vec3b>(sy2, sx2); + } + } + return; + } + if (mode == 86) { + /* SECURITY CAM: grainy green-mono CCTV with a tracking box + * locked on you, timestamp and REC dot. fx = grain. */ + unsigned tk = g_seg.counter; + int minx=img.cols, miny=img.rows, maxx=0, maxy=0; + for (int y = 0; y < img.rows; y += 6) { + const float *mm = g_seg.mask.ptr<float>(y); + for (int x = 0; x < img.cols; x += 6) + if (mm[x] > 0.4f) { + if (x<minx)minx=x; + if (x>maxx)maxx=x; + if (y<miny)miny=y; + if (y>maxy)maxy=y; + } + } + for (int y = 0; y < img.rows; y++) { + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + for (int x = 0; x < img.cols; x++) { + float lum = ip[x][0]*0.114f+ip[x][1]*0.587f+ip[x][2]*0.299f; + int gr = (int)((uhash(x,y,tk)-0.5f)*26*fx); + ip[x][0]=clamp_int_u8((int)(lum*0.55f)+gr); + ip[x][1]=clamp_int_u8((int)(lum*0.95f)+gr+10); + ip[x][2]=clamp_int_u8((int)(lum*0.55f)+gr); + } + } + if (maxx > minx + 20) { + cv::rectangle(img, {minx-8,miny-8}, {maxx+8,maxy+8}, + cv::Scalar(120,255,120), 2); + cv::putText(img, "SUBJECT 01", {minx-8, std::max(18,miny-14)}, + cv::FONT_HERSHEY_PLAIN, 1.2, cv::Scalar(120,255,120), 1); + } + char ts[40]; + snprintf(ts, sizeof ts, "CAM 04 %02u:%02u:%02u", + (tk/108000)%24, (tk/1800)%60, (tk/30)%60); + cv::putText(img, ts, {14, img.rows-16}, + cv::FONT_HERSHEY_PLAIN, 1.3, cv::Scalar(140,255,140), 1); + if ((tk/20)%2) { + cv::circle(img, {img.cols-34, 26}, 7, cv::Scalar(60,60,255), cv::FILLED); + cv::putText(img, "REC", {img.cols-92, 32}, + cv::FONT_HERSHEY_PLAIN, 1.3, cv::Scalar(120,120,255), 1); + } + return; + } + if (mode == 87) { + /* NEGATIVE YOU: your colors inverted, film-negative style, + * with a faint hot rim; the room stays positive. */ + 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); + for (int x = 0; x < img.cols; x++) { + float a = mm[x]; if (a < 0.05f) continue; + float rim = (a < 0.5f) ? (0.5f-a)*2.0f*80*fx : 0.0f; + ip[x][0]=(uchar)(ip[x][0]+((255-ip[x][0])-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+((255-ip[x][1])-ip[x][1])*a); + ip[x][2]=clamp_int_u8((int)(ip[x][2]+((255-ip[x][2])-ip[x][2])*a+rim)); + } + } + return; + } + if (mode == 68) { + /* ASCII YOU: your body rendered as green terminal + * characters by brightness; the room stays real. + * fx = character size. */ + int C = std::max(8, (int)(10 * fx)); + static const char *RAMP[] = {".",":","+","o","X","#","@"}; + cv::Mat keep = img.clone(); + for (int y0 = 0; y0 + C <= img.rows; y0 += C) + for (int x0 = 0; x0 + C <= img.cols; x0 += C) { + if (g_seg.mask.at<float>(y0+C/2, x0+C/2) < 0.4f) continue; + cv::Vec3b c = keep.at<cv::Vec3b>(y0+C/2, x0+C/2); + float lum = (c[0]*0.114f+c[1]*0.587f+c[2]*0.299f)/255.f; + cv::rectangle(img, cv::Rect(x0, y0, C, C), + cv::Scalar(8, 14, 8), cv::FILLED); + int ri = std::min(6, (int)(lum * 7)); + cv::putText(img, RAMP[ri], {x0, y0 + C - 2}, + cv::FONT_HERSHEY_PLAIN, C/10.0, + cv::Scalar(40, 100 + (int)(lum*155), 40), 1); + } + return; + } + if (mode == 69) { + /* HALFTONE PRINT: you as a proper newspaper dot-screen — + * dot size by darkness on a print grid; the room keeps its + * color. fx = dot cell size. */ + int C = std::max(5, (int)(6 * fx)); + cv::Mat keep = img.clone(); + for (int y0 = 0; y0 + C <= img.rows; y0 += C) + for (int x0 = 0; x0 + C <= img.cols; x0 += C) { + if (g_seg.mask.at<float>(y0+C/2, x0+C/2) < 0.4f) continue; + cv::Vec3b c = keep.at<cv::Vec3b>(y0+C/2, x0+C/2); + float dark = 1.0f - (c[0]*0.114f+c[1]*0.587f+c[2]*0.299f)/255.f; + cv::rectangle(img, cv::Rect(x0, y0, C, C), + cv::Scalar(235, 232, 226), cv::FILLED); + int r2 = (int)(dark * C * 0.62f); + if (r2 > 0) + cv::circle(img, {x0 + C/2, y0 + C/2}, r2, + cv::Scalar(30, 26, 24), cv::FILLED, cv::LINE_AA); + } + return; + } + if (mode == 70) { + /* LIQUID METAL: chrome you — luminance remapped through a + * banded metallic reflection curve. T-1000 energy. + * fx = band frequency. */ + unsigned tk = g_seg.counter; + 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); + 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)/255.f; + float band = std::sin(lum * 9.0f * fx + tk * 0.02f); + float v = lum * 0.55f + 0.30f + band * 0.22f; + if (v < 0) v = 0; + if (v > 1) v = 1; + float nb = v*255*1.04f, ng = v*255*1.02f, nr = v*255*0.94f; + ip[x][0]=(uchar)(ip[x][0]+(std::min(255.f,nb)-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+(std::min(255.f,ng)-ip[x][1])*a); + ip[x][2]=(uchar)(ip[x][2]+(std::min(255.f,nr)-ip[x][2])*a); + } + } + return; + } + if (mode == 71) { + /* CONTOUR STRIPES: animated brightness-contour bands sweep + * across your body — living topography of your own light. + * fx = sweep speed. */ + unsigned tk = g_seg.counter; + 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); + 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)/255.f; + float band = std::sin(lum * 22.0f - tk * 0.12f * fx); + if (band > 0.55f) { + float hue = lum * 5.0f + tk * 0.02f; + ip[x][0]=clamp_int_u8(ip[x][0]+(int)(a*(std::sin(hue+4.19f)*.5f+.5f)*170)); + ip[x][1]=clamp_int_u8(ip[x][1]+(int)(a*(std::sin(hue+2.09f)*.5f+.5f)*170)); + ip[x][2]=clamp_int_u8(ip[x][2]+(int)(a*(std::sin(hue)*.5f+.5f)*170)); + } else { + ip[x][0]=(uchar)(ip[x][0]*(1-a*0.35f)); + ip[x][1]=(uchar)(ip[x][1]*(1-a*0.35f)); + ip[x][2]=(uchar)(ip[x][2]*(1-a*0.35f)); + } + } + } + return; + } + if (mode == 72) { + /* STATIC YOU: signal lost — your silhouette is pure TV + * white-noise while the broadcast around you is fine. + * fx = noise coarseness. */ + unsigned tk = g_seg.counter; + int C = std::max(1, (int)fx); + 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); + for (int x = 0; x < img.cols; x++) { + float a = mm[x]; if (a < 0.05f) continue; + int n = (int)(uhash(x/C, y/C, tk) * 255); + ip[x][0]=(uchar)(ip[x][0]+(n-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+(n-ip[x][1])*a); + ip[x][2]=(uchar)(ip[x][2]+(n-ip[x][2])*a); + } + } + return; + } + if (mode == 73) { + /* GOLDEN STATUE: you, cast in gold — warm metal ramp with a + * specular kick in the highlights. fx = shine. */ + 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); + 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)/255.f; + float spec = lum > 0.72f ? (lum-0.72f)/0.28f : 0.0f; + spec = spec * spec * 0.9f * fx; + float nr = std::min(255.f, (lum*200 + 55) * (1+spec*0.5f)); + float ng = std::min(255.f, (lum*160 + 30) * (1+spec*0.6f)); + float nb = std::min(255.f, (lum*60 + 8) * (1+spec*1.6f)); + ip[x][0]=(uchar)(ip[x][0]+(nb-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+(ng-ip[x][1])*a); + ip[x][2]=(uchar)(ip[x][2]+(nr-ip[x][2])*a); + } + } + return; + } + if (mode == 74) { + /* COMIC INK: you, drawn — 4-level posterized color with + * black ink where your edges are. fx = ink weight. */ + cv::Mat gray, gx2, gy2; + cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY); + cv::Sobel(gray, gx2, CV_32F, 1, 0, 3); + cv::Sobel(gray, gy2, CV_32F, 0, 1, 3); + float thr = 260.0f / fx; + for (int y = 0; y < img.rows; y++) { + const float *mm = g_seg.mask.ptr<float>(y); + const float *ex = gx2.ptr<float>(y); + const float *ey = gy2.ptr<float>(y); + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + for (int x = 0; x < img.cols; x++) { + float a = mm[x]; if (a < 0.05f) continue; + float e = std::fabs(ex[x]) + std::fabs(ey[x]); + if (e > thr) { + ip[x][0]=(uchar)(ip[x][0]*(1-a)); + ip[x][1]=(uchar)(ip[x][1]*(1-a)); + ip[x][2]=(uchar)(ip[x][2]*(1-a)); + } else { + cv::Vec3b q((ip[x][0]/64)*64+40, + (ip[x][1]/64)*64+40, + (ip[x][2]/64)*64+40); + ip[x][0]=(uchar)(ip[x][0]+(q[0]-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+(q[1]-ip[x][1])*a); + ip[x][2]=(uchar)(ip[x][2]+(q[2]-ip[x][2])*a); + } + } + } + return; + } + if (mode == 75) { + /* VENETIAN: you're seen through sliding blinds — stripes of + * you alternate with the empty room behind. fx = blind size. */ + unsigned tk = g_seg.counter; + int B = std::max(8, (int)(14 * fx)); + int off = (int)(tk * 0.8f) % (B * 2); + for (int y = 0; y < img.rows; y++) { + bool open2 = (((y + off) / B) & 1) == 0; + if (open2) continue; + const float *mm = g_seg.mask.ptr<float>(y); + const cv::Vec3b *bp = g_seg.bg_est.ptr<cv::Vec3b>(y); + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + for (int x = 0; x < img.cols; x++) { + float a = mm[x]; if (a < 0.05f) continue; + ip[x][0]=(uchar)(ip[x][0]+(bp[x][0]-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+(bp[x][1]-ip[x][1])*a); + ip[x][2]=(uchar)(ip[x][2]+(bp[x][2]-ip[x][2])*a); + } + } + return; + } + if (mode == 76) { + /* BURNING EDGE: your outline smolders like the rim of + * burning paper — white-hot line, orange glow, charred + * band inside. fx = flicker energy. */ + unsigned tk = g_seg.counter; + 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); + for (int x = 0; x < img.cols; x++) { + float a = mm[x]; + if (a < 0.04f || a > 0.97f) continue; + float fl = 0.6f + 0.4f * uhash(x/3, y/3, tk/2) * fx; + float edge2 = 1.0f - std::fabs(a - 0.5f) * 2.0f; /* peak mid */ + float hot = edge2 * edge2 * fl; + ip[x][0]=clamp_int_u8(ip[x][0]+(int)(hot*40)); + ip[x][1]=clamp_int_u8(ip[x][1]+(int)(hot*130)); + ip[x][2]=clamp_int_u8(ip[x][2]+(int)(hot*255)); + if (a > 0.75f) { /* charred inner band */ + float ch = (a - 0.75f) / 0.25f * 0.5f; + ip[x][0]=(uchar)(ip[x][0]*(1-ch)); + ip[x][1]=(uchar)(ip[x][1]*(1-ch)); + ip[x][2]=(uchar)(ip[x][2]*(1-ch)); + } + } + } + return; + } + if (mode == 77) { + /* GLASS BODY: you become refractive glass — the learned + * room shows THROUGH you, bent by your body's shape (mask + * gradient as the surface normal) with a bright rim. + * fx = refraction strength. */ + cv::Mat gx2, gy2; + cv::Sobel(g_seg.mask, gx2, CV_32F, 1, 0, 3); + cv::Sobel(g_seg.mask, gy2, CV_32F, 0, 1, 3); + float R = 34.0f * fx; + for (int y = 0; y < img.rows; y++) { + const float *mm = g_seg.mask.ptr<float>(y); + const float *px2 = gx2.ptr<float>(y); + const float *py2 = gy2.ptr<float>(y); + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + for (int x = 0; x < img.cols; x++) { + float a = mm[x]; if (a < 0.05f) continue; + int sx2 = x + (int)(px2[x] * R); + int sy2 = y + (int)(py2[x] * R); + sx2 = std::max(0, std::min(img.cols-1, sx2)); + sy2 = std::max(0, std::min(img.rows-1, sy2)); + const cv::Vec3b &bg = g_seg.bg_est.at<cv::Vec3b>(sy2, sx2); + float rim = (a > 0.04f && a < 0.6f) ? (0.6f-a)/0.56f : 0.0f; + float nb = std::min(255.f, bg[0]*1.08f + rim*110); + float ng = std::min(255.f, bg[1]*1.08f + rim*110); + float nr = std::min(255.f, bg[2]*1.05f + rim*100); + ip[x][0]=(uchar)(ip[x][0]+(nb-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+(ng-ip[x][1])*a); + ip[x][2]=(uchar)(ip[x][2]+(nr-ip[x][2])*a); + } + } + return; + } + if (mode == 66) { + /* RETRO SPRITE: you become a chunky 16-color video-game + * character; the room stays photoreal. fx = chunkiness. */ + int C = std::max(4, (int)(img.cols / 140 * fx * 2)); + for (int y0 = 0; y0 < img.rows; y0 += C) + for (int x0 = 0; x0 < img.cols; x0 += C) { + if (g_seg.mask.at<float>(std::min(img.rows-1, y0+C/2), + std::min(img.cols-1, x0+C/2)) < 0.4f) + continue; + cv::Vec3b c = img.at<cv::Vec3b>( + std::min(img.rows-1, y0+C/2), std::min(img.cols-1, x0+C/2)); + c[0] = (c[0]/64)*64+32; c[1]=(c[1]/64)*64+32; c[2]=(c[2]/64)*64+32; + cv::rectangle(img, cv::Rect(x0, y0, + std::min(C, img.cols-x0), std::min(C, img.rows-y0)), + cv::Scalar(c[0],c[1],c[2]), cv::FILLED); + } + return; + } + if (mode == 67) { + /* ACID YOU: your colors slowly cycle through the spectrum + * while the room stays sober. fx = cycle speed. */ + unsigned tk = g_seg.counter; + float ph = tk * 0.03f * fx; + float c1 = std::cos(ph), s1 = std::sin(ph); + 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); + 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 u = ip[x][2]-lum, v2 = ip[x][0]-lum; /* chroma-ish */ + float u2 = u*c1 - v2*s1, w2 = u*s1 + v2*c1; /* rotate */ + float nr = lum+u2, nb = lum+w2, ng = lum-(u2+w2)*0.4f; + ip[x][0]=(uchar)(ip[x][0]+(clamp_int_u8((int)nb)-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+(clamp_int_u8((int)ng)-ip[x][1])*a); + ip[x][2]=(uchar)(ip[x][2]+(clamp_int_u8((int)nr)-ip[x][2])*a); + } + } + return; + } if (mode == 56) { /* COLOR POP: the room falls to a cool, slightly dark * monochrome; you stay in full — slightly enriched — color. @@ -4391,6 +5025,726 @@ void cv_fx_speedlines(unsigned char *data, int w, int h, int stride, } } +/* ── enhance: retinex-style low-light rescue ──────────────────── + * out = in / blurred_illumination — recovers shadows the way the eye + * does, plus gray-world white balance and shadow denoise. */ +void cv_fx_enhance(unsigned char *data, int w, int h, int stride, + float strength, float denoise) +{ + if (!data || w < 32 || h < 32) return; + if (strength <= 0.0f) strength = 1.0f; + if (strength < 0.2f) strength = 0.2f; + if (strength > 2.0f) strength = 2.0f; + if (denoise < 0.0f) denoise = 0.0f; + if (denoise > 1.0f) denoise = 1.0f; + try { + cv::Mat img(h, w, CV_8UC3, data, stride); + /* illumination estimate: heavy blur of luma at quarter res */ + cv::Mat q, luma(h/4, w/4, CV_32F); + cv::resize(img, q, cv::Size(w/4, h/4), 0, 0, cv::INTER_AREA); + double mb = 0, mg = 0, mr = 0; + for (int y = 0; y < q.rows; y++) { + const cv::Vec3b *p2 = q.ptr<cv::Vec3b>(y); + float *lp = luma.ptr<float>(y); + for (int x = 0; x < q.cols; x++) { + lp[x] = (p2[x][0]*0.114f+p2[x][1]*0.587f+p2[x][2]*0.299f)/255.f; + mb += p2[x][0]; mg += p2[x][1]; mr += p2[x][2]; + } + } + double N = (double)q.rows * q.cols; + mb/=N; mg/=N; mr/=N; + double avg = (mb+mg+mr)/3.0 + 1e-3; + float wbB = (float)std::min(1.25, std::max(0.8, avg/(mb+1e-3))); + float wbG = (float)std::min(1.25, std::max(0.8, avg/(mg+1e-3))); + float wbR = (float)std::min(1.25, std::max(0.8, avg/(mr+1e-3))); + cv::GaussianBlur(luma, luma, cv::Size(0,0), 14.0); + cv::Mat illum; + cv::resize(luma, illum, img.size(), 0, 0, cv::INTER_LINEAR); + cv::Mat soft; + if (denoise > 0.01f) + cv::GaussianBlur(img, soft, cv::Size(0,0), 1.5); + for (int y = 0; y < h; y++) { + const float *il = illum.ptr<float>(y); + const cv::Vec3b *sp = soft.empty() ? NULL : soft.ptr<cv::Vec3b>(y); + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + for (int x = 0; x < w; x++) { + float L2 = il[x]; + /* retinex gain: dark regions lifted toward mid gray */ + float gain = (0.45f + 0.1f*strength) / (L2 + 0.06f); + gain = 1.0f + (gain - 1.0f) * strength * 0.8f; + if (gain < 1.0f) gain = 1.0f; + if (gain > 4.5f) gain = 4.5f; + float dark = 1.0f - std::min(1.0f, L2*2.2f); + for (int c2 = 0; c2 < 3; c2++) { + float v = ip[x][c2]; + if (sp) v += (sp[x][c2]-v) * denoise * dark; /* shadow DN */ + float wb2 = c2==0?wbB:(c2==1?wbG:wbR); + v = v * gain * wb2; + /* soft shoulder so highlights don't clip hard */ + if (v > 210) v = 210 + (v-210)*0.5f; + ip[x][c2] = clamp_int_u8((int)v); + } + } + } + } catch (const std::exception &e) { + warn_once("enh_fail", std::string("enhance failed: ") + e.what()); + } +} + +/* ── posefx: BlazePose body landmarks via the ORT backend ──────── */ +struct PoseState { + std::string path; + int state = 0; + float lm[33][3]; /* x,y (frame px), visibility */ + int have = 0; /* landmarks valid this session */ + int good = 0; /* consecutive confident frames */ + float trailx[2][24], traily[2][24]; /* wrist trails */ + int trail_n = 0; + double ema_ms = 0; + int skip_left = 0; + unsigned tick = 0; + std::mutex mtx; +}; +static PoseState g_pose_s; + +int cv_set_pose_model(const char *path) +{ + if (!path || !*path || !path_exists(path)) return 0; + std::lock_guard<std::mutex> l(g_pose_s.mtx); + g_pose_s.path = path; + g_pose_s.state = 0; + ort_pose_shutdown(); + g_pose_s.have = 0; + return 1; +} + +/* BlazePose-33 bone list */ +static const int POSE_BONES[][2] = { + {11,12},{11,13},{13,15},{12,14},{14,16},{11,23},{12,24},{23,24}, + {23,25},{25,27},{24,26},{26,28},{0,11},{0,12}}; + +void cv_fx_pose(unsigned char *data, int w, int h, int stride, + int mode, float fx) +{ + if (!data || w < 64 || h < 64) return; + if (mode < 0) mode = 0; + if (mode > 5) mode = 5; + if (fx <= 0.0f) fx = 1.0f; + if (fx < 0.2f) fx = 0.2f; + if (fx > 3.0f) fx = 3.0f; + if (!ort_available()) { + warn_once("pose_ort", "posefx needs the ONNX Runtime backend — " + "vcam-setup --ort, then make OPENCV=1 ORT=1"); + return; + } + try { + std::lock_guard<std::mutex> l(g_pose_s.mtx); + if (g_pose_s.state < 0) return; + if (g_pose_s.state == 0) { + std::string p = g_pose_s.path.empty() + ? model_dir() + "/pose_estimation_mediapipe_2023mar.onnx" + : g_pose_s.path; + if (!path_exists(p)) { + g_pose_s.state = -1; + warn_once("pose_model", + "posefx: no pose model — run 'vcam-setup --models-pose'"); + return; + } + if (!ort_pose_init(p.c_str())) { g_pose_s.state = -1; return; } + g_pose_s.state = 1; + warn_once("pose_on", "posefx: body landmarks live — vcam can " + "see your skeleton now"); + } + cv::Mat img(h, w, CV_8UC3, data, stride); + g_pose_s.tick++; + bool infer_now = !(g_pose_s.skip_left > 0 && g_pose_s.have); + if (infer_now) { + auto t0 = std::chrono::steady_clock::now(); + /* body crop: from the face box when we have one (the crop + * convention BlazePose expects: whole body, square) */ + int bx = 0, by = 0, bs = std::min(w, h); + { + 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 iv2 = 1.0 / fs; + int fx2 = (int)(ff[0]*iv2), fy2 = (int)(ff[1]*iv2); + int fw2 = (int)(ff[2]*iv2), fh2 = (int)(ff[3]*iv2); + /* size FIRST (clamped to what fits), THEN center on + * the face — the old order shrank the box after + * placing it, sliding you half out of the crop */ + int S = (int)(fw2 * 5.4f); + if (S < h/3) S = h/3; + bs = std::min(S, std::min(w, h)); + bx = fx2 + fw2/2 - bs/2; + by = fy2 - (int)(fh2*0.9f); + } else { + bs = std::min(w, h); + bx = (w - bs)/2; + by = 0; + } + bs = std::max(64, std::min(bs, std::min(w, h))); + bx = std::max(0, std::min(w - bs, bx)); + by = std::max(0, std::min(h - bs, by)); + } + cv::Mat crop = img(cv::Rect(bx, by, bs, bs)); + cv::Mat small2, rgb; + cv::resize(crop, small2, cv::Size(256, 256), 0, 0, cv::INTER_AREA); + cv::cvtColor(small2, rgb, cv::COLOR_BGR2RGB); + std::vector<float> in((size_t)3*256*256); + for (int i = 0; i < 256*256; i++) { /* NHWC [0,1] */ + const cv::Vec3b &p2 = rgb.at<cv::Vec3b>(i/256, i%256); + in[(size_t)i*3+0] = p2[0]/255.0f; + in[(size_t)i*3+1] = p2[1]/255.0f; + in[(size_t)i*3+2] = p2[2]/255.0f; + } + float lm195[195], conf = 0; + if (!ort_pose_infer(in.data(), lm195, &conf)) { + g_pose_s.state = -1; + return; + } + if (conf < 0.0f || conf > 1.0f) /* raw logit */ + conf = 1.0f / (1.0f + std::exp(-conf)); + if (conf >= 0.50f) { + float sx2 = (float)bs / 256.0f; + float nx2[33], ny2[33], nv2[33]; + for (int k2 = 0; k2 < 33; k2++) { + nx2[k2] = bx + lm195[k2*5+0] * sx2; + ny2[k2] = by + lm195[k2*5+1] * sx2; + nv2[k2] = 1.0f/(1.0f+std::exp(-lm195[k2*5+3])); + } + /* outlier rejection: if the whole set teleported, it's a + * bad frame — don't let it through */ + bool jumped = false; + if (g_pose_s.have) { + float acc = 0; + for (int k2 = 0; k2 < 33; k2++) + acc += std::fabs(nx2[k2]-g_pose_s.lm[k2][0]) + + std::fabs(ny2[k2]-g_pose_s.lm[k2][1]); + float allow = w * 0.10f * (1 + g_pose_s.skip_left); + if (acc / 33.0f > std::max(w*0.18f, allow)) jumped = true; + } + if (jumped) { + if (g_pose_s.good > 0) g_pose_s.good--; + } else { + for (int k2 = 0; k2 < 33; k2++) { + if (g_pose_s.have) { /* EMA smooth */ + g_pose_s.lm[k2][0] += (nx2[k2]-g_pose_s.lm[k2][0])*0.35f; + g_pose_s.lm[k2][1] += (ny2[k2]-g_pose_s.lm[k2][1])*0.35f; + g_pose_s.lm[k2][2] += (nv2[k2]-g_pose_s.lm[k2][2])*0.35f; + } else { + g_pose_s.lm[k2][0]=nx2[k2]; + g_pose_s.lm[k2][1]=ny2[k2]; + g_pose_s.lm[k2][2]=nv2[k2]; + } + } + g_pose_s.have = 1; + if (g_pose_s.good < 6) g_pose_s.good++; + } + } else { + if (g_pose_s.good > 0) g_pose_s.good--; + if (g_pose_s.good <= 0) { g_pose_s.good = 0; g_pose_s.have = 0; } + } + double ms = std::chrono::duration<double, std::milli>( + std::chrono::steady_clock::now() - t0).count(); + g_pose_s.ema_ms = g_pose_s.ema_ms <= 0 ? ms + : 0.7*g_pose_s.ema_ms + 0.3*ms; + g_pose_s.skip_left = (g_pose_s.ema_ms <= 30) ? 0 + : (g_pose_s.ema_ms <= 60) ? 1 + : (g_pose_s.ema_ms <= 110) ? 2 : 4; + } else { + g_pose_s.skip_left--; + } + if (!g_pose_s.have || g_pose_s.good < 2) return; /* debounced */ + float (*L)[3] = g_pose_s.lm; + auto P = [&](int i){ return cv::Point((int)L[i][0], (int)L[i][1]); }; + auto vis = [&](int i){ + return L[i][2] > 0.55f && + L[i][0] > -w*0.02f && L[i][0] < w*1.02f && + L[i][1] > -h*0.02f && L[i][1] < h*1.02f; /* in frame */ + }; + + if (mode == 1) img *= 0.28; /* neon bones: dark */ + if (mode == 0 || mode == 1) { + /* SKELETON: glowing bones + joints over you (0) or in the + * dark (1). fx = glow size. */ + float hue = g_pose_s.tick * 0.03f; + cv::Scalar col((std::sin(hue+4.19f)*.5f+.5f)*255, + (std::sin(hue+2.09f)*.5f+.5f)*255, + (std::sin(hue)*.5f+.5f)*255); + int th = std::max(2, (int)(4*fx)); + for (unsigned b2 = 0; b2 < sizeof POSE_BONES/sizeof *POSE_BONES; b2++) { + int a2 = POSE_BONES[b2][0], c2 = POSE_BONES[b2][1]; + if (!vis(a2) || !vis(c2)) continue; + cv::line(img, P(a2), P(c2), col*0.35, th+6, cv::LINE_AA); + cv::line(img, P(a2), P(c2), col, th, cv::LINE_AA); + } + for (int k2 = 0; k2 < 33; k2++) + if (vis(k2)) + cv::circle(img, P(k2), std::max(2,(int)(3*fx)), + cv::Scalar(255,255,255), cv::FILLED, cv::LINE_AA); + } else if (mode == 2) { + /* ENERGY HANDS: charged orbs in your actual palms — bring + * your wrists together to merge them into one big charge. */ + unsigned tk = g_pose_s.tick; + int wl2 = 15, wr2 = 16; + float dx = L[wl2][0]-L[wr2][0], dy = L[wl2][1]-L[wr2][1]; + float d = std::sqrt(dx*dx + dy*dy); + bool merged = vis(wl2) && vis(wr2) && d < w*0.09f; + for (int s2 = 0; s2 < (merged ? 1 : 2); s2++) { + int i2 = s2 ? wr2 : wl2; + if (!vis(i2) && !merged) continue; + cv::Point c2 = merged + ? cv::Point((int)((L[wl2][0]+L[wr2][0])/2), + (int)((L[wl2][1]+L[wr2][1])/2)) + : P(i2); + float R = (merged ? w*0.075f : w*0.035f) * fx + * (1.0f + 0.12f*std::sin(tk*0.25f + s2*2)); + for (int g2 = 4; g2 >= 1; g2--) + cv::circle(img, c2, (int)(R*g2/2.5f), + cv::Scalar(255,140+g2*20,40), 2, cv::LINE_AA); + cv::circle(img, c2, (int)(R*0.45f), + cv::Scalar(255,240,200), cv::FILLED, cv::LINE_AA); + for (int k2 = 0; k2 < 7; k2++) { /* crackle */ + float aa = uhash(k2, tk/2, s2)*6.283f; + float rr = R*(0.6f+0.5f*uhash(k2, tk/2, s2+9)); + cv::line(img, c2, + {c2.x+(int)(std::cos(aa)*rr), c2.y+(int)(std::sin(aa)*rr)}, + cv::Scalar(255,220,120), 1, cv::LINE_AA); + } + } + } else if (mode == 4) { + /* LIGHT WINGS: glowing wings of light unfold from your + * shoulders, slowly beating. fx = span. */ + unsigned tk = g_pose_s.tick; + if (vis(11) && vis(12)) { + float flap = 0.82f + 0.18f * std::sin(tk * 0.07f); + for (int s2 = 0; s2 < 2; s2++) { + cv::Point sh = P(s2 ? 12 : 11); + float dir = s2 ? 1.0f : -1.0f; + float span = w * 0.16f * fx * flap; + for (int fth = 0; fth < 7; fth++) { /* feather strokes */ + float t2 = fth / 6.0f; + float ang = -1.15f + t2 * 1.35f; /* fan downward */ + float len = span * (1.0f - 0.45f*t2); + cv::Point tip(sh.x + (int)(dir*std::cos(ang)*len), + sh.y + (int)(std::sin(ang)*len*0.9f)); + cv::Point mid(sh.x + (int)(dir*std::cos(ang-0.25f)*len*0.55f), + sh.y + (int)(std::sin(ang-0.25f)*len*0.5f)); + int br = (int)(200 - t2*90); + cv::line(img, sh, mid, cv::Scalar(br, br, 255), 5, cv::LINE_AA); + cv::line(img, mid, tip, cv::Scalar(br/2, br/2, 230), 3, cv::LINE_AA); + cv::line(img, sh, mid, cv::Scalar(255,255,255), 1, cv::LINE_AA); + } + } + } + } else if (mode == 5) { + /* PUPPET STRINGS: fine strings from above hold your head + * and hands — you're the marionette. */ + unsigned tk = g_pose_s.tick; + int anchors[3] = {0, 15, 16}; /* head, wrists */ + for (int a2 = 0; a2 < 3; a2++) { + int j = anchors[a2]; + if (!vis(j)) continue; + cv::Point p2 = P(j); + int topx = p2.x + (int)(std::sin(tk*0.04f + a2*2.1f) * 14); + cv::line(img, {topx, 0}, p2, cv::Scalar(220,220,225), 1, cv::LINE_AA); + cv::line(img, {topx+1, 0}, {p2.x+1, p2.y}, + cv::Scalar(120,120,125), 1, cv::LINE_AA); + /* little cross-bar at the top */ + cv::line(img, {topx-14, 6}, {topx+14, 6}, + cv::Scalar(60,80,120), 4, cv::LINE_AA); + } + } else { + /* WRIST TRAILS: your hands write comet trails through the + * air — conduct, draw, dance. fx = trail thickness. */ + int nT = 24; + if (g_pose_s.trail_n < nT) g_pose_s.trail_n++; + for (int s2 = 0; s2 < 2; s2++) { + for (int i2 = nT-1; i2 > 0; i2--) { + g_pose_s.trailx[s2][i2] = g_pose_s.trailx[s2][i2-1]; + g_pose_s.traily[s2][i2] = g_pose_s.traily[s2][i2-1]; + } + int wj = s2 ? 16 : 15; + g_pose_s.trailx[s2][0] = L[wj][0]; + g_pose_s.traily[s2][0] = L[wj][1]; + for (int i2 = 0; i2 < g_pose_s.trail_n-1; i2++) { + float k2 = 1.0f - (float)i2/nT; + cv::Scalar col = s2 ? cv::Scalar(80,160*k2,255*k2) + : cv::Scalar(255*k2,180*k2,60); + cv::line(img, + {(int)g_pose_s.trailx[s2][i2],(int)g_pose_s.traily[s2][i2]}, + {(int)g_pose_s.trailx[s2][i2+1],(int)g_pose_s.traily[s2][i2+1]}, + col, std::max(1,(int)(k2*7*fx)), cv::LINE_AA); + } + } + } + } catch (const std::exception &e) { + g_pose_s.state = -1; + warn_once("pose_fail", std::string("posefx failed: ") + e.what()); + } +} + +/* ── depthfx: monocular-depth effects via the ORT backend ──────── */ +struct DepthState { + std::string path; + int state = 0; /* 0 untried, 1 up, -1 dead */ + cv::Mat map; /* full-size CV_32F, 0=far..1=near */ + float lo = 0, hi = 1; /* EMA-smoothed normalization range */ + double ema_ms = 0; + int skip_left = 0; + unsigned tick = 0; + std::mutex mtx; +}; +static DepthState g_depth; + +int cv_set_depth_model(const char *path) +{ + if (!path || !*path || !path_exists(path)) return 0; + std::lock_guard<std::mutex> l(g_depth.mtx); + g_depth.path = path; + g_depth.state = 0; + ort_depth_shutdown(); + g_depth.map.release(); + return 1; +} + +void cv_fx_depth(unsigned char *data, int w, int h, int stride, + int mode, float fx) +{ + if (!data || w < 64 || h < 64) return; + if (mode < 0) mode = 0; + if (mode > 3) mode = 3; + if (fx <= 0.0f) fx = 1.0f; + if (fx < 0.2f) fx = 0.2f; + if (fx > 3.0f) fx = 3.0f; + if (!ort_available()) { + warn_once("depth_ort", "depthfx needs the ONNX Runtime backend — " + "vcam-setup --ort, then make OPENCV=1 ORT=1"); + return; + } + try { + std::lock_guard<std::mutex> l(g_depth.mtx); + if (g_depth.state < 0) return; + if (g_depth.state == 0) { + std::string p = g_depth.path.empty() + ? model_dir() + "/model-small.onnx" : g_depth.path; + if (!path_exists(p)) { + g_depth.state = -1; + warn_once("depth_model", + "depthfx: no depth model — run 'vcam-setup --models-depth' " + "(MiDaS v2.1 small) or 'vcam-ctl filter depthmodel <path>'"); + return; + } + if (!ort_depth_init(p.c_str())) { g_depth.state = -1; return; } + g_depth.state = 1; + warn_once("depth_on", + "depthfx: monocular depth live — every pixel now has a distance"); + } + cv::Mat img(h, w, CV_8UC3, data, stride); + g_depth.tick++; + bool infer_now = !(g_depth.skip_left > 0 && !g_depth.map.empty() + && g_depth.map.size() == img.size()); + if (infer_now) { + auto t0 = std::chrono::steady_clock::now(); + cv::Mat small2, rgb; + cv::resize(img, small2, cv::Size(256, 256), 0, 0, cv::INTER_AREA); + cv::cvtColor(small2, rgb, cv::COLOR_BGR2RGB); + std::vector<float> in((size_t)3*256*256), out((size_t)256*256); + for (int i = 0; i < 256*256; i++) { /* RGB [0,1] CHW */ + const cv::Vec3b &p2 = rgb.at<cv::Vec3b>(i/256, i%256); + in[0*65536+i] = p2[0]/255.0f; + in[1*65536+i] = p2[1]/255.0f; + in[2*65536+i] = p2[2]/255.0f; + } + if (!ort_depth_infer(in.data(), out.data())) { + g_depth.state = -1; + return; + } + /* normalize with EMA'd min/max so the scene doesn't flicker */ + float mn = out[0], mx = out[0]; + for (int i = 1; i < 65536; i++) { + if (out[i] < mn) mn = out[i]; + if (out[i] > mx) mx = out[i]; + } + if (g_depth.map.empty()) { g_depth.lo = mn; g_depth.hi = mx; } + g_depth.lo += (mn - g_depth.lo) * 0.15f; + g_depth.hi += (mx - g_depth.hi) * 0.15f; + float rng = std::max(1e-4f, g_depth.hi - g_depth.lo); + cv::Mat d256(256, 256, CV_32F); + for (int i = 0; i < 65536; i++) { + float v = (out[i] - g_depth.lo) / rng; + d256.at<float>(i/256, i%256) = + v < 0 ? 0.0f : (v > 1 ? 1.0f : v); + } + cv::resize(d256, g_depth.map, img.size(), 0, 0, cv::INTER_LINEAR); + double ms = std::chrono::duration<double, std::milli>( + std::chrono::steady_clock::now() - t0).count(); + g_depth.ema_ms = g_depth.ema_ms <= 0 ? ms + : 0.7*g_depth.ema_ms + 0.3*ms; + g_depth.skip_left = (g_depth.ema_ms <= 30) ? 0 + : (g_depth.ema_ms <= 60) ? 1 + : (g_depth.ema_ms <= 110) ? 2 : 4; + } else { + g_depth.skip_left--; + } + if (g_depth.map.empty() || g_depth.map.size() != img.size()) return; + const cv::Mat &D = g_depth.map; /* 1 = near, 0 = far */ + + if (mode == 0) { + /* DEPTH BLUR: true depth-of-field — blur grows with + * distance, continuously, no person mask needed. */ + cv::Mat b1, b2; + cv::GaussianBlur(img, b1, cv::Size(0,0), 2.0 + 1.5*fx); + cv::GaussianBlur(b1, b2, cv::Size(0,0), 3.0 + 2.5*fx); + for (int y = 0; y < h; y++) { + const float *dd = D.ptr<float>(y); + const cv::Vec3b *p1 = b1.ptr<cv::Vec3b>(y); + const cv::Vec3b *p2 = b2.ptr<cv::Vec3b>(y); + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + for (int x = 0; x < w; x++) { + float far2 = 1.0f - dd[x]; /* 0 near, 1 far */ + if (far2 < 0.25f) continue; /* near: sharp */ + float k = (far2 - 0.25f) / 0.75f; + const cv::Vec3b &src = (k > 0.55f) ? p2[x] : p1[x]; + float a = std::min(1.0f, k * 1.6f); + ip[x][0]=(uchar)(ip[x][0]+(src[0]-ip[x][0])*a); + ip[x][1]=(uchar)(ip[x][1]+(src[1]-ip[x][1])*a); + ip[x][2]=(uchar)(ip[x][2]+(src[2]-ip[x][2])*a); + } + } + } else if (mode == 1) { + /* DEPTH FOG: atmosphere thickens with distance — the room + * recedes into haze the way real air does. */ + for (int y = 0; y < h; y++) { + const float *dd = D.ptr<float>(y); + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + for (int x = 0; x < w; x++) { + float k = (1.0f - dd[x]); + k = k * k * 0.85f * std::min(1.5f, fx); + if (k < 0.02f) continue; + if (k > 0.9f) k = 0.9f; + ip[x][0]=(uchar)(ip[x][0]+(205-ip[x][0])*k); + ip[x][1]=(uchar)(ip[x][1]+(200-ip[x][1])*k); + ip[x][2]=(uchar)(ip[x][2]+(190-ip[x][2])*k); + } + } + } else if (mode == 2) { + /* DEPTH VIEW: the raw superpower, colormapped — near glows + * warm, far falls to deep blue. */ + for (int y = 0; y < h; y++) { + const float *dd = D.ptr<float>(y); + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + for (int x = 0; x < w; x++) { + float v = dd[x]; + float r2 = std::min(1.0f, v*1.8f); + float g2 = v > 0.5f ? (v-0.5f)*2.0f : v*0.6f; + float b2 = std::max(0.0f, 1.0f - v*1.6f); + ip[x][0]=(uchar)(b2*235); + ip[x][1]=(uchar)(g2*225); + ip[x][2]=(uchar)(r2*245); + } + } + } else { + /* PARALLAX WIGGLE: near pixels sway more than far ones — + * the fake-3D wiggle-gram, live. */ + float ph = std::sin(g_depth.tick * 0.06f) * 7.0f * fx; + cv::Mat keep = img.clone(); + for (int y = 0; y < h; y++) { + const float *dd = D.ptr<float>(y); + cv::Vec3b *ip = img.ptr<cv::Vec3b>(y); + for (int x = 0; x < w; x++) { + int sx2 = x + (int)(ph * (dd[x] - 0.45f)); + if (sx2 < 0) sx2 = 0; + if (sx2 >= w) sx2 = w - 1; + ip[x] = keep.at<cv::Vec3b>(y, sx2); + } + } + } + } catch (const std::exception &e) { + g_depth.state = -1; + warn_once("depth_fail", std::string("depthfx failed: ") + e.what()); + } +} + +/* ── genai: generic img2img via the ORT backend ────────────────── */ +struct GenAiState { + std::string path; /* model file; empty = use default */ + int state = 0; /* 0 untried, 1 up, -1 dead */ + cv::Mat last; /* last transformed frame (full size) */ + double ema_ms = 0; + int skip_left = 0; + std::mutex mtx; +}; +static GenAiState g_genai; + +int cv_set_gen_model(const char *path) +{ + if (!path || !*path) return 0; + if (!path_exists(path)) return 0; + std::lock_guard<std::mutex> l(g_genai.mtx); + g_genai.path = path; + g_genai.state = 0; /* (re)load lazily */ + ort_i2i_shutdown(); + g_genai.last.release(); + return 1; +} + +void cv_clear_gen_model(void) +{ + std::lock_guard<std::mutex> l(g_genai.mtx); + g_genai.path.clear(); + g_genai.state = 0; + ort_i2i_shutdown(); + g_genai.last.release(); +} + +void cv_fx_genai(unsigned char *data, int w, int h, int stride, + float blend, float size, float range01) +{ + if (!data || w < 32 || h < 32) return; + bool r01 = range01 >= 0.5f; /* p3=1: [0,1] convention (Zero-DCE etc.) */ + if (blend <= 0.0f) blend = 1.0f; + if (blend < 0.2f) blend = 0.2f; + if (blend > 1.0f) blend = 1.0f; + int iw0 = (int)size; + if (iw0 <= 0) iw0 = 288; + if (iw0 < 128) iw0 = 128; + if (iw0 > 512) iw0 = 512; + if (!ort_available()) { + warn_once("genai_ort", "genai needs the ONNX Runtime backend — " + "vcam-setup --ort, then make OPENCV=1 ORT=1"); + return; + } + try { + std::lock_guard<std::mutex> l(g_genai.mtx); + if (g_genai.state < 0) return; + if (g_genai.state == 0) { + std::string p = g_genai.path.empty() + ? model_dir() + "/img2img.onnx" : g_genai.path; + if (!path_exists(p)) { + g_genai.state = -1; + warn_once("genai_model", + "genai: no model — drop an img2img ONNX (e.g. AnimeGAN) " + "at " + p + " or set one with " + "'vcam-ctl filter genmodel <path>'"); + return; + } + if (!ort_i2i_init(p.c_str())) { g_genai.state = -1; return; } + g_genai.state = 1; + warn_once("genai_on", + "genai: img2img model live on ONNX Runtime — " + "every frame is now the network's opinion of you"); + } + cv::Mat img(h, w, CV_8UC3, data, stride); + bool infer_now = !(g_genai.skip_left > 0 && !g_genai.last.empty() + && g_genai.last.size() == img.size()); + if (infer_now) { + auto t0 = std::chrono::steady_clock::now(); + int iw = std::max(64, (iw0/8)*8); + int ih = std::max(64, ((int)((double)iw*h/w)/8)*8); + cv::Mat small2, rgb; + cv::resize(img, small2, cv::Size(iw, ih), 0, 0, cv::INTER_AREA); + cv::cvtColor(small2, rgb, cv::COLOR_BGR2RGB); + int N = iw*ih; + std::vector<float> in((size_t)3*N), out((size_t)3*N); + if (ort_i2i_layout() == 1) { /* NHWC */ + for (int i = 0; i < N; i++) { + const cv::Vec3b &p2 = rgb.at<cv::Vec3b>(i/iw, i%iw); + float d2 = r01 ? 255.0f : 127.5f, o2 = r01 ? 0.0f : 1.0f; + in[(size_t)i*3+0] = p2[0]/d2 - o2; + in[(size_t)i*3+1] = p2[1]/d2 - o2; + in[(size_t)i*3+2] = p2[2]/d2 - o2; + } + } else { /* NCHW */ + for (int i = 0; i < N; i++) { + const cv::Vec3b &p2 = rgb.at<cv::Vec3b>(i/iw, i%iw); + float d2 = r01 ? 255.0f : 127.5f, o2 = r01 ? 0.0f : 1.0f; + in[0*(size_t)N+i] = p2[0]/d2 - o2; + in[1*(size_t)N+i] = p2[1]/d2 - o2; + in[2*(size_t)N+i] = p2[2]/d2 - o2; + } + } + if (!ort_i2i_infer(in.data(), iw, ih, out.data())) { + g_genai.state = -1; + return; + } + cv::Mat res(ih, iw, CV_8UC3); + if (ort_i2i_layout() == 1) { + for (int i = 0; i < N; i++) { + cv::Vec3b &p2 = res.at<cv::Vec3b>(i/iw, i%iw); + float m2 = r01 ? 255.0f : 127.5f, a2 = r01 ? 0.0f : 1.0f; + p2[2]=clamp_int_u8((int)((out[(size_t)i*3+0]+a2)*m2)); + p2[1]=clamp_int_u8((int)((out[(size_t)i*3+1]+a2)*m2)); + p2[0]=clamp_int_u8((int)((out[(size_t)i*3+2]+a2)*m2)); + } + } else { + for (int i = 0; i < N; i++) { + cv::Vec3b &p2 = res.at<cv::Vec3b>(i/iw, i%iw); + float m2 = r01 ? 255.0f : 127.5f, a2 = r01 ? 0.0f : 1.0f; + p2[2]=clamp_int_u8((int)((out[0*(size_t)N+i]+a2)*m2)); + p2[1]=clamp_int_u8((int)((out[1*(size_t)N+i]+a2)*m2)); + p2[0]=clamp_int_u8((int)((out[2*(size_t)N+i]+a2)*m2)); + } + } + cv::resize(res, g_genai.last, img.size(), 0, 0, cv::INTER_LINEAR); + double ms = std::chrono::duration<double, std::milli>( + std::chrono::steady_clock::now() - t0).count(); + g_genai.ema_ms = g_genai.ema_ms <= 0 ? ms + : 0.7*g_genai.ema_ms + 0.3*ms; + g_genai.skip_left = (g_genai.ema_ms <= 30) ? 0 + : (g_genai.ema_ms <= 60) ? 1 + : (g_genai.ema_ms <= 110) ? 2 : 4; + } else { + g_genai.skip_left--; + } + if (!g_genai.last.empty() && g_genai.last.size() == img.size()) { + if (blend >= 0.99f) g_genai.last.copyTo(img); + else cv::addWeighted(g_genai.last, blend, img, 1.0-blend, 0, img); + } + } catch (const std::exception &e) { + g_genai.state = -1; + warn_once("genai_fail", std::string("genai failed: ") + e.what()); + } +} + +int cv_set_face_image(const char *path) +{ + if (!path || !*path) return 0; + try { + cv::Mat m = cv::imread(path, cv::IMREAD_UNCHANGED); + if (m.empty()) return 0; + if (m.channels() == 3) /* no alpha: make opaque */ + cv::cvtColor(m, m, cv::COLOR_BGR2BGRA); + if (m.channels() != 4) return 0; + std::lock_guard<std::mutex> l(g_faceimg.mtx); + m.copyTo(g_faceimg.rgba); + return 1; + } catch (const std::exception &e) { + warn_once("faceimg", std::string("face image load failed: ") + e.what()); + return 0; + } +} + +void cv_clear_face_image(void) +{ + try { + std::lock_guard<std::mutex> l(g_faceimg.mtx); + g_faceimg.rgba.release(); + } catch (...) { } +} + int cv_set_bg_image(const char *path) { if (!path || !*path) return 0; @@ -4434,6 +5788,8 @@ void cv_shutdown(void) 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(); } + { std::lock_guard<std::mutex> l(g_faceimg.mtx); + g_faceimg.rgba.release(); } } catch (...) { /* shutdown must never throw */ } } diff --git a/src/opencv_stub.c b/src/opencv_stub.c index 51331cd..67df071 100644 --- a/src/opencv_stub.c +++ b/src/opencv_stub.c @@ -60,6 +60,30 @@ void cv_fx_paintflow(unsigned char *d, int w, int h, int s, float st, float 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; } +void cv_fx_pose(unsigned char *d, int w, int h, int s, int m, float fx) +{ (void)d; (void)w; (void)h; (void)s; (void)m; (void)fx; } + +int cv_set_pose_model(const char *p) { (void)p; return 0; } + +void cv_fx_depth(unsigned char *d, int w, int h, int s, int m, float fx) +{ (void)d; (void)w; (void)h; (void)s; (void)m; (void)fx; } + +int cv_set_depth_model(const char *p) { (void)p; return 0; } + +void cv_fx_genai(unsigned char *d, int w, int h, int s, float b, float sz, float r) +{ (void)d; (void)w; (void)h; (void)s; (void)b; (void)sz; (void)r; } + +void cv_fx_enhance(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_gen_model(const char *p) { (void)p; return 0; } + +void cv_clear_gen_model(void) { } + +int cv_set_face_image(const char *p) { (void)p; return 0; } + +void cv_clear_face_image(void) { } + int cv_set_bg_image(const char *p) { (void)p; return 0; } void cv_clear_bg_image(void) { } diff --git a/src/ort_rvm.c b/src/ort_rvm.c index a63f128..23f471b 100644 --- a/src/ort_rvm.c +++ b/src/ort_rvm.c @@ -257,6 +257,367 @@ cleanup: return ret; } +/* ── BlazePose landmarks (MediaPipe pose, OpenCV-zoo export): + * input [1,256,256,3] RGB [0,1] NHWC; outputs selected by element + * count: 195 floats = 39 landmarks x (x,y,z,vis,pres), 1 float = + * person-presence confidence. ── */ +static OrtSession *g_pose; +static char g_pose_in[128]; +static char g_pose_outs[8][128]; +static size_t g_pose_nout = 0; +static int g_pose_dead = 0; + +int ort_pose_init(const char *model_path) +{ + if (!model_path || !*model_path) return 0; + pthread_mutex_lock(&g_mtx); + if (g_pose) { pthread_mutex_unlock(&g_mtx); return 1; } + g_pose_dead = 0; + if (!A) A = OrtGetApiBase()->GetApi(ORT_API_VERSION); + if (!A) goto fail; + if (!g_env && !ok(A->CreateEnv(ORT_LOGGING_LEVEL_ERROR, "vcam", &g_env), + "CreateEnv")) goto fail; + if (!g_so) { + if (!ok(A->CreateSessionOptions(&g_so), "CreateSessionOptions")) goto fail; + if (!ok(A->SetSessionGraphOptimizationLevel(g_so, ORT_ENABLE_ALL), + "SetGraphOptimizationLevel")) goto fail; + } + if (!g_mi && !ok(A->CreateCpuMemoryInfo(OrtArenaAllocator, OrtMemTypeDefault, + &g_mi), "CreateCpuMemoryInfo")) goto fail; + if (!g_alloc && !ok(A->GetAllocatorWithDefaultOptions(&g_alloc), + "GetAllocator")) goto fail; + if (!ok(A->CreateSession(g_env, model_path, g_so, &g_pose), + "CreateSession(pose)")) goto fail; + { + size_t nin = 0; + if (!ok(A->SessionGetInputCount(g_pose, &nin), "pose InCount") || + nin != 1 || + !ok(A->SessionGetOutputCount(g_pose, &g_pose_nout), "pose OutCount") || + g_pose_nout < 2 || g_pose_nout > 8) { + fprintf(stderr, "[vcam/ort] unexpected pose model interface\n"); + A->ReleaseSession(g_pose); g_pose = NULL; goto fail; + } + char *nm = NULL; + if (!ok(A->SessionGetInputName(g_pose, 0, g_alloc, &nm), "pose InName")) + { A->ReleaseSession(g_pose); g_pose = NULL; goto fail; } + snprintf(g_pose_in, sizeof g_pose_in, "%s", nm); + if (!ok(A->AllocatorFree(g_alloc, nm), "free")) { } + for (size_t i = 0; i < g_pose_nout; i++) { + if (!ok(A->SessionGetOutputName(g_pose, i, g_alloc, &nm), "pose OutName")) + { A->ReleaseSession(g_pose); g_pose = NULL; goto fail; } + snprintf(g_pose_outs[i], sizeof g_pose_outs[i], "%s", nm); + if (!ok(A->AllocatorFree(g_alloc, nm), "free")) { } + } + } + fprintf(stderr, "[vcam/ort] pose model ready (%zu outputs)\n", g_pose_nout); + pthread_mutex_unlock(&g_mtx); + return 1; +fail: + g_pose_dead = 1; + pthread_mutex_unlock(&g_mtx); + return 0; +} + +int ort_pose_infer(const float *rgb_nhwc_256, float *landmarks195, float *conf1) +{ + if (!rgb_nhwc_256 || !landmarks195 || !conf1) return 0; + pthread_mutex_lock(&g_mtx); + if (!g_pose || g_pose_dead) { pthread_mutex_unlock(&g_mtx); return 0; } + OrtValue *iv = NULL, *outs[8] = {0}; + const char *names[8]; + int ret = 0; + { + for (size_t i = 0; i < g_pose_nout; i++) names[i] = g_pose_outs[i]; + const int64_t shp[4] = {1, 256, 256, 3}; + if (!ok(A->CreateTensorWithDataAsOrtValue(g_mi, (void *)rgb_nhwc_256, + (size_t)3*256*256*sizeof(float), shp, 4, + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &iv), + "pose CreateTensor")) goto done_dead; + const OrtValue *ivs[1] = {iv}; + const char *ins[1] = {g_pose_in}; + if (!ok(A->Run(g_pose, NULL, ins, ivs, 1, names, g_pose_nout, outs), + "pose Run")) goto done_dead; + int got_lm = 0, got_cf = 0; + for (size_t i = 0; i < g_pose_nout; i++) { + OrtTensorTypeAndShapeInfo *sh = NULL; + size_t cnt = 0; + if (!ok(A->GetTensorTypeAndShape(outs[i], &sh), "pose Shape")) + goto done_dead; + int sok = ok(A->GetTensorShapeElementCount(sh, &cnt), "pose Count"); + A->ReleaseTensorTypeAndShapeInfo(sh); + if (!sok) goto done_dead; + float *p = NULL; + if (cnt == 195 && !got_lm) { + if (!ok(A->GetTensorMutableData(outs[i], (void **)&p), "pose LM")) + goto done_dead; + memcpy(landmarks195, p, 195*sizeof(float)); + got_lm = 1; + } else if (cnt == 1 && !got_cf) { + if (!ok(A->GetTensorMutableData(outs[i], (void **)&p), "pose CF")) + goto done_dead; + *conf1 = p[0]; + got_cf = 1; + } + } + if (!got_lm || !got_cf) { + fprintf(stderr, "[vcam/ort] pose outputs missing landmarks/conf\n"); + goto done_dead; + } + ret = 1; + goto done; + } +done_dead: + g_pose_dead = 1; + fprintf(stderr, "[vcam/ort] pose backend disabled after error\n"); +done: + if (iv) A->ReleaseValue(iv); + for (size_t i = 0; i < g_pose_nout; i++) + if (outs[i]) A->ReleaseValue(outs[i]); + pthread_mutex_unlock(&g_mtx); + return ret; +} + +void ort_pose_shutdown(void) +{ + pthread_mutex_lock(&g_mtx); + if (g_pose) { A->ReleaseSession(g_pose); g_pose = NULL; } + g_pose_dead = 0; + pthread_mutex_unlock(&g_mtx); +} + +/* ── monocular depth (MiDaS-small interface): fixed [1,3,256,256] + * RGB [0,1] in -> [1,256,256] (or [1,1,256,256]) inverse depth out. ── */ +static OrtSession *g_dep; +static char g_dep_in[128], g_dep_out[128]; +static int g_dep_dead = 0; + +int ort_depth_init(const char *model_path) +{ + if (!model_path || !*model_path) return 0; + pthread_mutex_lock(&g_mtx); + if (g_dep) { pthread_mutex_unlock(&g_mtx); return 1; } + g_dep_dead = 0; + if (!A) A = OrtGetApiBase()->GetApi(ORT_API_VERSION); + if (!A) goto fail; + if (!g_env && !ok(A->CreateEnv(ORT_LOGGING_LEVEL_ERROR, "vcam", &g_env), + "CreateEnv")) goto fail; + if (!g_so) { + if (!ok(A->CreateSessionOptions(&g_so), "CreateSessionOptions")) goto fail; + if (!ok(A->SetSessionGraphOptimizationLevel(g_so, ORT_ENABLE_ALL), + "SetGraphOptimizationLevel")) goto fail; + } + if (!g_mi && !ok(A->CreateCpuMemoryInfo(OrtArenaAllocator, OrtMemTypeDefault, + &g_mi), "CreateCpuMemoryInfo")) goto fail; + if (!g_alloc && !ok(A->GetAllocatorWithDefaultOptions(&g_alloc), + "GetAllocator")) goto fail; + if (!ok(A->CreateSession(g_env, model_path, g_so, &g_dep), + "CreateSession(depth)")) goto fail; + { + size_t nin = 0, nout = 0; + if (!ok(A->SessionGetInputCount(g_dep, &nin), "depth InCount") || + !ok(A->SessionGetOutputCount(g_dep, &nout), "depth OutCount") || + nin != 1 || nout != 1) { + fprintf(stderr, "[vcam/ort] depth model must be 1-in/1-out\n"); + A->ReleaseSession(g_dep); g_dep = NULL; goto fail; + } + char *nm = NULL; + if (!ok(A->SessionGetInputName(g_dep, 0, g_alloc, &nm), "depth InName")) + { A->ReleaseSession(g_dep); g_dep = NULL; goto fail; } + snprintf(g_dep_in, sizeof g_dep_in, "%s", nm); + if (!ok(A->AllocatorFree(g_alloc, nm), "free")) { } + if (!ok(A->SessionGetOutputName(g_dep, 0, g_alloc, &nm), "depth OutName")) + { A->ReleaseSession(g_dep); g_dep = NULL; goto fail; } + snprintf(g_dep_out, sizeof g_dep_out, "%s", nm); + if (!ok(A->AllocatorFree(g_alloc, nm), "free")) { } + } + fprintf(stderr, "[vcam/ort] depth model ready ('%s'->'%s')\n", + g_dep_in, g_dep_out); + pthread_mutex_unlock(&g_mtx); + return 1; +fail: + g_dep_dead = 1; + pthread_mutex_unlock(&g_mtx); + return 0; +} + +int ort_depth_infer(const float *rgb_chw_256, float *depth_out_65536) +{ + if (!rgb_chw_256 || !depth_out_65536) return 0; + pthread_mutex_lock(&g_mtx); + if (!g_dep || g_dep_dead) { pthread_mutex_unlock(&g_mtx); return 0; } + OrtValue *iv = NULL, *ov = NULL; + int ret = 0; + { + const int64_t shp[4] = {1, 3, 256, 256}; + if (!ok(A->CreateTensorWithDataAsOrtValue(g_mi, (void *)rgb_chw_256, + (size_t)3*256*256*sizeof(float), shp, 4, + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &iv), + "depth CreateTensor")) goto done_dead; + const char *ins[1] = {g_dep_in}, *outs2[1] = {g_dep_out}; + const OrtValue *ivs[1] = {iv}; + if (!ok(A->Run(g_dep, NULL, ins, ivs, 1, outs2, 1, &ov), "depth Run")) + goto done_dead; + OrtTensorTypeAndShapeInfo *sh = NULL; + size_t cnt = 0; + if (!ok(A->GetTensorTypeAndShape(ov, &sh), "depth OutShape")) + goto done_dead; + int sok = ok(A->GetTensorShapeElementCount(sh, &cnt), "depth Count"); + A->ReleaseTensorTypeAndShapeInfo(sh); + if (!sok || cnt != (size_t)256*256) { + fprintf(stderr, "[vcam/ort] depth output must be 256x256\n"); + goto done_dead; + } + float *p = NULL; + if (!ok(A->GetTensorMutableData(ov, (void **)&p), "depth OutData")) + goto done_dead; + memcpy(depth_out_65536, p, (size_t)256*256*sizeof(float)); + ret = 1; + goto done; + } +done_dead: + g_dep_dead = 1; + fprintf(stderr, "[vcam/ort] depth backend disabled after error\n"); +done: + if (iv) A->ReleaseValue(iv); + if (ov) A->ReleaseValue(ov); + pthread_mutex_unlock(&g_mtx); + return ret; +} + +void ort_depth_shutdown(void) +{ + pthread_mutex_lock(&g_mtx); + if (g_dep) { A->ReleaseSession(g_dep); g_dep = NULL; } + if (g_pose) { A->ReleaseSession(g_pose); g_pose = NULL; } + g_dep_dead = 0; + pthread_mutex_unlock(&g_mtx); +} + +/* ── generic img2img (single input, single output, dynamic H/W) ── */ +static OrtSession *g_i2i; +static char g_i2i_in[128], g_i2i_out[128]; +static int g_i2i_nhwc = 0, g_i2i_dead = 0; + +int ort_i2i_layout(void) { return g_i2i_nhwc; } + +int ort_i2i_init(const char *model_path) +{ + if (!model_path || !*model_path) return 0; + pthread_mutex_lock(&g_mtx); + if (g_i2i) { pthread_mutex_unlock(&g_mtx); return 1; } + g_i2i_dead = 0; + if (!A) A = OrtGetApiBase()->GetApi(ORT_API_VERSION); + if (!A) goto fail; + if (!g_env && !ok(A->CreateEnv(ORT_LOGGING_LEVEL_ERROR, "vcam", &g_env), + "CreateEnv")) goto fail; + if (!g_so) { + if (!ok(A->CreateSessionOptions(&g_so), "CreateSessionOptions")) goto fail; + if (!ok(A->SetSessionGraphOptimizationLevel(g_so, ORT_ENABLE_ALL), + "SetGraphOptimizationLevel")) goto fail; + } + if (!g_mi && !ok(A->CreateCpuMemoryInfo(OrtArenaAllocator, OrtMemTypeDefault, + &g_mi), "CreateCpuMemoryInfo")) goto fail; + if (!g_alloc && !ok(A->GetAllocatorWithDefaultOptions(&g_alloc), + "GetAllocator")) goto fail; + if (!ok(A->CreateSession(g_env, model_path, g_so, &g_i2i), + "CreateSession(i2i)")) goto fail; + { + size_t nin = 0, nout = 0; + if (!ok(A->SessionGetInputCount(g_i2i, &nin), "i2i InputCount") || + !ok(A->SessionGetOutputCount(g_i2i, &nout), "i2i OutputCount") || + nin != 1 || nout != 1) { + fprintf(stderr, "[vcam/ort] img2img model must have exactly " + "1 input and 1 output (has %zu/%zu)\n", nin, nout); + A->ReleaseSession(g_i2i); g_i2i = NULL; goto fail; + } + char *nm = NULL; + if (!ok(A->SessionGetInputName(g_i2i, 0, g_alloc, &nm), "i2i InName")) + { A->ReleaseSession(g_i2i); g_i2i = NULL; goto fail; } + snprintf(g_i2i_in, sizeof g_i2i_in, "%s", nm); + if (!ok(A->AllocatorFree(g_alloc, nm), "free")) { } + if (!ok(A->SessionGetOutputName(g_i2i, 0, g_alloc, &nm), "i2i OutName")) + { A->ReleaseSession(g_i2i); g_i2i = NULL; goto fail; } + snprintf(g_i2i_out, sizeof g_i2i_out, "%s", nm); + if (!ok(A->AllocatorFree(g_alloc, nm), "free")) { } + /* layout: channels dim == 3 at index 1 -> NCHW, at 3 -> NHWC */ + OrtTypeInfo *ti = NULL; + const OrtTensorTypeAndShapeInfo *sh = NULL; + int64_t dims[8] = {0}; size_t nd = 0; + if (ok(A->SessionGetInputTypeInfo(g_i2i, 0, &ti), "i2i TypeInfo") && + ok(A->CastTypeInfoToTensorInfo(ti, &sh), "i2i Cast") && + ok(A->GetDimensionsCount(sh, &nd), "i2i DimCount") && nd == 4 && + ok(A->GetDimensions(sh, dims, nd), "i2i Dims")) { + g_i2i_nhwc = (dims[3] == 3) ? 1 : 0; + } else { + g_i2i_nhwc = 0; /* dynamic everywhere: NCHW is the safer bet */ + } + if (ti) A->ReleaseTypeInfo(ti); + } + fprintf(stderr, "[vcam/ort] img2img model ready (io '%s'->'%s', %s)\n", + g_i2i_in, g_i2i_out, g_i2i_nhwc ? "NHWC" : "NCHW"); + pthread_mutex_unlock(&g_mtx); + return 1; +fail: + g_i2i_dead = 1; + pthread_mutex_unlock(&g_mtx); + return 0; +} + +int ort_i2i_infer(const float *in, int w, int h, float *out) +{ + if (!in || !out || w < 16 || h < 16) return 0; + pthread_mutex_lock(&g_mtx); + if (!g_i2i || g_i2i_dead) { pthread_mutex_unlock(&g_mtx); return 0; } + OrtValue *iv = NULL, *ov = NULL; + int ret = 0; + { + int64_t shp[4]; + if (g_i2i_nhwc) { shp[0]=1; shp[1]=h; shp[2]=w; shp[3]=3; } + else { shp[0]=1; shp[1]=3; shp[2]=h; shp[3]=w; } + if (!ok(A->CreateTensorWithDataAsOrtValue(g_mi, (void *)in, + (size_t)3*w*h*sizeof(float), shp, 4, + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &iv), + "i2i CreateTensor")) goto done_dead; + const char *ins[1] = {g_i2i_in}, *outs2[1] = {g_i2i_out}; + const OrtValue *ivs[1] = {iv}; + if (!ok(A->Run(g_i2i, NULL, ins, ivs, 1, outs2, 1, &ov), "i2i Run")) + goto done_dead; + OrtTensorTypeAndShapeInfo *sh = NULL; + size_t cnt = 0; + if (!ok(A->GetTensorTypeAndShape(ov, &sh), "i2i OutShape")) + goto done_dead; + int sok = ok(A->GetTensorShapeElementCount(sh, &cnt), "i2i Count"); + A->ReleaseTensorTypeAndShapeInfo(sh); + if (!sok || cnt != (size_t)3*w*h) { + fprintf(stderr, "[vcam/ort] img2img output size mismatch\n"); + goto done_dead; + } + float *p = NULL; + if (!ok(A->GetTensorMutableData(ov, (void **)&p), "i2i OutData")) + goto done_dead; + memcpy(out, p, (size_t)3*w*h*sizeof(float)); + ret = 1; + goto done; + } +done_dead: + g_i2i_dead = 1; + fprintf(stderr, "[vcam/ort] img2img backend disabled after error\n"); +done: + if (iv) A->ReleaseValue(iv); + if (ov) A->ReleaseValue(ov); + pthread_mutex_unlock(&g_mtx); + return ret; +} + +void ort_i2i_shutdown(void) +{ + pthread_mutex_lock(&g_mtx); + if (g_i2i) { A->ReleaseSession(g_i2i); g_i2i = NULL; } + if (g_dep) { A->ReleaseSession(g_dep); g_dep = NULL; } + g_i2i_dead = 0; + pthread_mutex_unlock(&g_mtx); +} + void ort_rvm_reset(void) { pthread_mutex_lock(&g_mtx); @@ -268,6 +629,7 @@ void ort_shutdown(void) { pthread_mutex_lock(&g_mtx); release_rec(); + if (g_i2i) { A->ReleaseSession(g_i2i); g_i2i = NULL; } if (g_sess) { A->ReleaseSession(g_sess); g_sess = NULL; } if (g_so) { A->ReleaseSessionOptions(g_so); g_so = NULL; } if (g_mi) { A->ReleaseMemoryInfo(g_mi); g_mi = NULL; } @@ -288,6 +650,28 @@ int ort_rvm_init(const char *p) { (void)p; return 0; } int ort_rvm_infer(const float *s, int w, int h, float d, float *o) { (void)s; (void)w; (void)h; (void)d; (void)o; return 0; } +int ort_i2i_init(const char *p) { (void)p; return 0; } + +int ort_i2i_layout(void) { return 0; } + +int ort_i2i_infer(const float *i, int w, int h, float *o) +{ (void)i; (void)w; (void)h; (void)o; return 0; } + +void ort_i2i_shutdown(void) { } + +int ort_depth_init(const char *p) { (void)p; return 0; } + +int ort_depth_infer(const float *i, float *o) { (void)i; (void)o; return 0; } + +void ort_depth_shutdown(void) { } + +int ort_pose_init(const char *p) { (void)p; return 0; } + +int ort_pose_infer(const float *i, float *l, float *c) +{ (void)i; (void)l; (void)c; return 0; } + +void ort_pose_shutdown(void) { } + void ort_rvm_reset(void) { } void ort_shutdown(void) { }