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

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

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

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

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

Add control API for screen sharing and webcam PiP (vcam 1.0.0)

Christian Immanuel · 2026-11-12 08:53 · 5eaddefd9166385906f9b3bf9e6db0b914469fa9

New high-level commands on the IPC socket, built for other apps:
- status [json] / get <key>: machine-readable state (share on/off,
  fullscreen, monitor, cam position/size, cam_over_screen, ...)
- share start|stop|toggle: fullscreen share of a monitor (by index,
  name or WxH+X+Y), with optional cam=<pos> in one call
- cam on|off|toggle|pos|move|size|margin|raise|get: webcam PiP control
- monitors: server-side detection (sway, Hyprland, wlr-randr, xrandr,
  /sys/class/drm fallback)
- version: version + md5 build hash (also vcam --version, make version)

IPC: one thread per client (commands serialised), so a long-lived
controller no longer blocks vcam-ctl. VCAM_SOCK now also works for the
daemon. vcam-ctl wraps the new commands with bare output and exit 1 on
ERR.

Also: webcam overlay aspect fix-up now rounds height like resolve_dims
(no 1px jump on first frame), Makefile defaults to PREFIX=/usr, README
gets a Control API section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MZiVJi7adqtP79SuimnK7v
 INSTALL.md         |   8 +-
 Makefile           |  22 +-
 README.md          |  67 ++++-
 commit_message.txt |  23 ++
 include/vcam.h     |  16 +-
 scripts/vcam-ctl   |  42 +++
 src/api.c          | 740 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/ipc.c          | 126 ++++++++-
 src/main.c         |  15 +-
 src/overlay.c      |   3 +
 10 files changed, 1036 insertions(+), 26 deletions(-)

diff --git a/INSTALL.md b/INSTALL.md
index c138619..d12993e 100644
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -17,7 +17,7 @@ Wayland.
 
 ## Dependencies
 
-On Debian / Ubuntu (package names differ on other distros):
+On Debian (package names differ on other distros):
 
 ```bash
 sudo apt install \
@@ -53,7 +53,7 @@ and their licenses.
 ```bash
 git clone <repo-url> vcam && cd vcam
 make
-sudo make install                          # default → /usr/local/bin
+sudo make install                          # default → /usr/bin
 ```
 
 The build is warning-clean under `-Wall -Wextra -Wpedantic`. `make`
@@ -63,7 +63,7 @@ Choose a different destination if you prefer:
 
 ```bash
 make install PREFIX=$HOME/.local             # ~/.local/bin (no sudo)
-make install PREFIX=/usr                      # system-wide
+make install PREFIX=/usr/local                # classic local prefix
 make install DESTDIR=/tmp/pkg PREFIX=/usr     # staged, for packaging
 ```
 
@@ -257,3 +257,5 @@ reload the modules (or reboot).
 
 For usage and runtime issues (filters, recording, screen capture), see
 the Troubleshooting section in [README.md](README.md).
+
+<!-- Modified-by: Claude Opus 5.5 (install prefix, distro wording) -->
diff --git a/Makefile b/Makefile
index 86fdffe..2391ec9 100644
--- a/Makefile
+++ b/Makefile
@@ -1,5 +1,6 @@
 # SPDX-License-Identifier: GPL-2.0-only
 # vcam — Copyright (C) 2026 the vcam authors. GPL-2.0, see LICENSE.
+# Modified-by: Claude Opus 5.5 (api.c, build hash, PREFIX=/usr)
 
 CC      := gcc
 CXX     := g++
@@ -141,18 +142,24 @@ else
 endif
 
 # ── Install paths (overridable) ─────────────────────────────────────
-#   make install                       (default: /usr/local)
+#   make install                       (default: /usr → binaries in /usr/bin)
+#   make install PREFIX=/usr/local     (classic local prefix)
 #   make install PREFIX=$HOME/.local   (user-local)
 #   make install DESTDIR=/tmp/stage    (staged install for packaging)
-PREFIX  ?= /usr/local
+PREFIX  ?= /usr
 BINDIR  ?= $(PREFIX)/bin
 DOCDIR  ?= $(PREFIX)/share/doc/vcam
 DATADIR ?= $(PREFIX)/share/vcam
 
 SRCS := src/main.c src/frame.c src/capture.c src/output.c \
         src/overlay.c src/registry.c src/ipc.c src/filter.c \
-        src/record.c src/ort_rvm.c
+        src/record.c src/ort_rvm.c src/api.c
 OBJS := $(SRCS:.c=.o) $(CV_OBJ)
+
+# Build hash: md5 over every source input, so 'vcam --version' and
+# 'vcam-ctl version' tell you exactly which files a binary was built from.
+HASH_INPUTS := $(SRCS) $(wildcard include/*.h src/*.cpp src/opencv_stub.c scripts/*) Makefile
+BUILD_HASH  := $(shell cat $(HASH_INPUTS) 2>/dev/null | md5sum | cut -c1-7)
 BIN  := vcam
 TEST := test_screen
 
@@ -166,10 +173,17 @@ TEST := test_screen
 # and install the stub flavor over your OpenCV build.
 CONFIG_STAMP := .built-opencv-$(OPENCV)-ort-$(ORT)
 
-.PHONY: all clean install uninstall
+.PHONY: all clean install uninstall version
 
 all: $(BIN) $(TEST)
 
+version:
+	@echo "vcam $$(sed -n 's/^#define VCAM_VERSION "\(.*\)"/\1/p' include/vcam.h) (build $(BUILD_HASH))"
+
+# api.c embeds the build hash → rebuild it whenever any input changes
+src/api.o: CFLAGS += -DVCAM_BUILD=\"$(BUILD_HASH)\"
+src/api.o: $(HASH_INPUTS)
+
 $(CONFIG_STAMP):
 	@rm -f .built-opencv-*
 ifeq ($(ORT),1)
diff --git a/README.md b/README.md
index d319595..37a0eb3 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
 # vcam — virtual webcam pipeline
 
-> 🤖 **This is 100% Vibecode by ClaudeCode.** Every line of C, every shell
+> 🤖 **This is 100% Vibecode by ClaudeCode — but tested.** Every line of C, every shell
 > script, and every word of this README was written by Claude through a
 > long iterative back-and-forth. No human authored any of it directly —
 > only the prompts that shaped it.
@@ -42,7 +42,7 @@ Full details — dependencies, build options, the one-time device setup —
 are in **[INSTALL.md](INSTALL.md)**. The short version:
 
 ```bash
-# 1. Dependencies (Debian / Ubuntu)
+# 1. Dependencies (Debian; names differ on other distros)
 sudo apt install \
     libv4l-dev libavcodec-dev libavformat-dev libavutil-dev \
     libswscale-dev libavdevice-dev libpng-dev \
@@ -295,7 +295,62 @@ vcam-ctl filter add mirror          # both corners are mirrored
 In `--no-input` mode (no cam captured) webcam overlays simply show
 black. If you want screencast + webcam corner, run vcam *without*
 `--no-input` and cover the base with a fullscreen screen overlay as
-shown above.
+shown above. To drive all of this from another app, see
+[Control API](#control-api-for-other-apps).
+
+---
+
+## Control API (for other apps)
+
+vcam listens on a Unix socket: `/tmp/vcam.sock` (override with `VCAM_SOCK`).
+One command per line, one-line replies: `OK …` or `ERR …`.
+Several apps can stay connected at the same time.
+
+| Command | What it does |
+|---|---|
+| `status` / `status json` | Whole state as `key=value` line, or one JSON line. |
+| `get <key>` | One value, e.g. `get cam_pos` → `OK br`. |
+| `share start [<n>\|<name>\|<WxH+X+Y>] [fit=stretch\|contain] [cam=<pos>\|off] [camw=N]` | Fullscreen share. Default: first monitor. |
+| `share stop` / `share toggle` | Stop / toggle sharing. |
+| `cam on [<pos>] [<w>]` / `cam off` / `cam toggle` | Webcam PiP. pos: `tl tr bl br center full`. |
+| `cam pos <pos>` / `cam move <x> <y>` / `cam size <w>` / `cam margin <px>` | Place the cam. |
+| `monitors` | `OK 1 DP-1 1920x1080+0+0` per monitor. |
+| `version` | `OK vcam 1.0.0 (build abc1234)` |
+
+Useful keys: `share`, `share_fullscreen`, `share_monitor`, `cam`,
+`cam_pos` (`tl tr bl br center full custom -`), `cam_x/y/w/h`,
+`cam_over_screen`, `input`, `recording`.
+`cam_over_screen=yes` means a cam is drawn on top of the shared screen.
+
+Shell (`vcam-ctl` strips `OK`, exits 1 on `ERR`):
+
+```bash
+vcam-ctl share start cam=br     # share monitor 1, cam bottom-right
+vcam-ctl get cam_pos            # → br
+vcam-ctl get cam_over_screen    # → yes
+vcam-ctl cam pos tl
+vcam-ctl status --json
+vcam-ctl share stop
+```
+
+Raw socket / Python:
+
+```bash
+printf 'status json\nquit\n' | ncat -U /tmp/vcam.sock
+```
+
+```python
+import socket
+s = socket.socket(socket.AF_UNIX); s.connect("/tmp/vcam.sock")
+f = s.makefile("rw")
+f.write("get cam_pos\n"); f.flush(); print(f.readline())   # OK br
+```
+
+Notes:
+
+- Run vcam *with* the webcam (no `--no-input`): the share covers the cam, the PiP sits on top.
+- Monitors are detected via sway, Hyprland, wlr-randr or xrandr (fallback: `/sys/class/drm`).
+- `fit=contain` keeps the screen's aspect ratio; the bars then show the webcam.
 
 ---
 
@@ -731,8 +786,10 @@ scripts/
 ```bash
 make              # build vcam and test_screen with -Wall -Wextra -Wpedantic -O2
 make clean
-sudo make install                       # → /usr/local/bin
+sudo make install                       # → /usr/bin
+sudo make uninstall
 make install PREFIX=$HOME/.local        # user-local, no root needed
+make version                            # version + md5 build hash
 ```
 
 To add a new source file, drop it in `src/` and append to `SRCS` in the
@@ -773,3 +830,5 @@ see the camera, missing build tools) are covered in
 | Video plays jerky/jumps back | (was) spin limit too tight | rebuild — limit raised, `vid_eof_sent` flag added |
 | `shell-init: getcwd error retrieving current directory` | Your *shell* sits in a deleted directory — **not a vcam bug** | `cd ~` in that terminal |
 | High CPU at 1080p | `blur` / `painterly` / `voronoi` are O(W·H·r²) | smaller param, drop to 720p, or pick cheaper filters |
+
+<!-- Modified-by: Claude Opus 5.5 (Control API section, install prefix, distro wording) -->
diff --git a/commit_message.txt b/commit_message.txt
new file mode 100644
index 0000000..64b327a
--- /dev/null
+++ b/commit_message.txt
@@ -0,0 +1,23 @@
+Add control API for screen sharing and webcam PiP (vcam 1.0.0)
+
+New high-level commands on the IPC socket, built for other apps:
+- status [json] / get <key>: machine-readable state (share on/off,
+  fullscreen, monitor, cam position/size, cam_over_screen, ...)
+- share start|stop|toggle: fullscreen share of a monitor (by index,
+  name or WxH+X+Y), with optional cam=<pos> in one call
+- cam on|off|toggle|pos|move|size|margin|raise|get: webcam PiP control
+- monitors: server-side detection (sway, Hyprland, wlr-randr, xrandr,
+  /sys/class/drm fallback)
+- version: version + md5 build hash (also vcam --version, make version)
+
+IPC: one thread per client (commands serialised), so a long-lived
+controller no longer blocks vcam-ctl. VCAM_SOCK now also works for the
+daemon. vcam-ctl wraps the new commands with bare output and exit 1 on
+ERR.
+
+Also: webcam overlay aspect fix-up now rounds height like resolve_dims
+(no 1px jump on first frame), Makefile defaults to PREFIX=/usr, README
+gets a Control API section.
+
+Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
+Claude-Session: https://claude.ai/code/session_01MZiVJi7adqtP79SuimnK7v
diff --git a/include/vcam.h b/include/vcam.h
index 362a7aa..45e0433 100644
--- a/include/vcam.h
+++ b/include/vcam.h
@@ -4,6 +4,8 @@
  *
  * This program is free software under the terms of the GNU General
  * Public License version 2. See the LICENSE file for the full text.
+ *
+ * Modified-by: Claude Opus 5.5 (control API declarations)
  */
 
 #pragma once
@@ -317,7 +319,7 @@ bool     registry_set_z (OverlayRegistry *r, const char *id, int target);
  *   quit
  * Responses are newline-terminated text lines.
  * ────────────────────────────────────────────── */
-#define VCAM_SOCK_PATH "/tmp/vcam.sock"
+#define VCAM_SOCK_PATH "/tmp/vcam.sock"   /* default; env VCAM_SOCK overrides */
 
 typedef struct {
     OverlayRegistry *registry;
@@ -328,6 +330,18 @@ typedef struct {
 
 bool ipc_start(IPCServer *srv, OverlayRegistry *reg);
 void ipc_stop (IPCServer *srv);
+const char *ipc_sock_path(void);   /* the path actually in use */
+
+/* ──────────────────────────────────────────────
+ * Control API (src/api.c) — high-level, script/app friendly commands
+ * on the same socket: status, get, share, cam, monitors, version.
+ * [Claude Opus 5.5]
+ * ────────────────────────────────────────────── */
+#define VCAM_VERSION "1.0.0"
+
+/* Returns true if <cmd> was an API command (reply already sent). */
+bool        api_handle(int fd, const char *cmd, char **save, OverlayRegistry *reg);
+const char *api_version_string(void);   /* "vcam 1.0.0 (build abc1234)" */
 
 /* ──────────────────────────────────────────────
  * V4L2 capture
diff --git a/scripts/vcam-ctl b/scripts/vcam-ctl
index bbd7060..310f14b 100755
--- a/scripts/vcam-ctl
+++ b/scripts/vcam-ctl
@@ -1,6 +1,7 @@
 #!/bin/sh
 # SPDX-License-Identifier: GPL-2.0-only
 # vcam — Copyright (C) 2026 the vcam authors. GPL-2.0, see LICENSE.
+# Modified-by: Claude Opus 5.5 (control API wrappers)
 #
 # vcam-ctl – complete runtime control for a running vcam process.
 #
@@ -78,6 +79,21 @@
 #                                "full" stretches it to the full output.
 #   webcam off                   Remove the "cam" overlay.
 #
+# Control API (script friendly: bare values, exit 1 on error):
+#   status [--json]              Whole state, one key=value per line (or JSON).
+#   get <key>                    One value, e.g. 'get cam_pos' → br
+#                                keys: share share_fullscreen share_monitor
+#                                cam cam_pos cam_x cam_y cam_w cam_h
+#                                cam_over_screen input recording … (see status)
+#   share start [<n>|<name>|<WxH+X+Y>] [fit=stretch|contain] [cam=<pos>|off] [camw=N]
+#                                Fullscreen share of a monitor (default: first).
+#   share stop | toggle | status
+#   cam on [<pos>] [<w>]         Webcam PiP. pos: tl tr bl br center full
+#   cam off | toggle | raise | get
+#   cam pos <pos> | move <x> <y> | size <w> [<h>] | margin <px>
+#   monitors                     List monitors as "n name WxH+X+Y".
+#   version                      vcam version + build hash.
+#
 # Recording (capture the vcam output to a file):
 #   record start [-o <file>] [-m <alsa-dev>] [--no-audio] [--crf N]
 #   record stop                  Flush + close file cleanly.
@@ -730,6 +746,32 @@ if [ "$1" = "webcam" ]; then
     exit 0
 fi
 
+# ──────────────────────────────────────────────────────────────
+# control API — status / get / share / cam / monitors / version
+# [Claude Opus 5.5] Strips the "OK " / "OK bye" noise so output is
+# directly usable in scripts; exits 1 if vcam answered ERR.
+# ──────────────────────────────────────────────────────────────
+case "$1" in
+    status|get|share|cam|monitors|version)
+        require_running
+        if [ "$1" = "status" ] && { [ "${2:-}" = "--json" ] || [ "${2:-}" = "json" ]; }; then
+            ipc_send "status json" | head -n 1
+            exit 0
+        fi
+        OUT=$(ipc_send "$*" | grep -v '^OK bye$')
+        if printf '%s\n' "$OUT" | grep -q '^ERR'; then
+            printf '%s\n' "$OUT" >&2
+            exit 1
+        fi
+        if [ "$1" = "status" ]; then
+            printf '%s\n' "${OUT#OK }" | tr ' ' '\n'
+        else
+            printf '%s\n' "$OUT" | sed 's/^OK //'
+        fi
+        exit 0
+        ;;
+esac
+
 # ──────────────────────────────────────────────────────────────
 # record subcommand — drive an ffmpeg child to capture the vcam
 # output (and optionally a microphone).
diff --git a/src/api.c b/src/api.c
new file mode 100644
index 0000000..2103076
--- /dev/null
+++ b/src/api.c
@@ -0,0 +1,740 @@
+/* SPDX-License-Identifier: GPL-2.0-only
+ * vcam — Linux virtual webcam pipeline
+ * Copyright (C) 2026 the vcam authors
+ *
+ * This program is free software under the terms of the GNU General
+ * Public License version 2. See the LICENSE file for the full text.
+ *
+ * Created-by: Claude Opus 5.5 (control API)
+ */
+
+/*
+ * High-level control API, served on the same socket as ipc.c.
+ * Built for other apps: short commands, one-line machine-readable replies.
+ *
+ *   status [json]              whole state: "OK k=v k=v ..." or one JSON line
+ *   get <key>                  one value from status, e.g. "get cam_pos" → "OK br"
+ *   version                    "OK vcam 1.0.0 (build abc1234)"
+ *   monitors                   one line per monitor: "OK <n> <name> WxH+X+Y"
+ *
+ *   share start [<n>|<name>|<WxH+X+Y>] [fit=stretch|contain]
+ *               [cam=<pos>|off] [camw=<px>]
+ *   share stop | toggle | status
+ *
+ *   cam on [<pos>] [<width>]   pos: tl tr bl br center full
+ *   cam off | toggle | raise | get
+ *   cam pos <pos>              keep size, snap to a position
+ *   cam move <x> <y>           free position (pos becomes "custom")
+ *   cam size <w> [<h>]         keeps its anchor; h derived from aspect
+ *   cam margin <px>            gap between cam and the output edge
+ *
+ * The share overlay uses id "share", the cam overlay id "cam" (same id
+ * as 'vcam-ctl webcam'). Status also recognises screen/webcam overlays
+ * added by other commands.
+ */
+
+#include "vcam.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <errno.h>
+#include <dirent.h>
+
+#ifndef VCAM_BUILD
+#define VCAM_BUILD "dev"
+#endif
+
+#define SHARE_ID "share"
+#define CAM_ID   "cam"
+
+extern FilterChain g_filters;
+extern Recorder   *g_recorder;
+extern int         g_output_w, g_output_h, g_output_fps;
+extern bool        g_no_input;
+
+/* State owned by the API. Only touched from command handlers, which
+ * ipc.c serialises with a mutex, so no extra locking is needed. */
+static char g_share_geo[64] = "";
+static char g_share_mon[64] = "";
+static int  g_cam_margin    = 0;
+
+const char *api_version_string(void)
+{
+    return "vcam " VCAM_VERSION " (build " VCAM_BUILD ")";
+}
+
+/* ── reply helper (bigger buffer than ipc.c's send_line) ───── */
+static void reply(int fd, const char *fmt, ...)
+{
+    char buf[4096];
+    va_list ap;
+    va_start(ap, fmt);
+    int n = vsnprintf(buf, sizeof buf - 1, fmt, ap);
+    va_end(ap);
+    if (n < 0) return;
+    if (n > (int)sizeof buf - 2) n = (int)sizeof buf - 2;
+    buf[n++] = '\n';
+    for (int off = 0; off < n; ) {
+        ssize_t w = write(fd, buf + off, (size_t)(n - off));
+        if (w < 0 && errno == EINTR) continue;
+        if (w <= 0) return;
+        off += (int)w;
+    }
+}
+
+/* ══════════════════════════════════════════════════════════════
+ * Monitor detection (sway, Hyprland, other wlroots, X11, DRM)
+ * Coordinates are logical (what wf-recorder -g / x11grab expect).
+ * ══════════════════════════════════════════════════════════════ */
+typedef struct { char name[32]; int w, h, x, y; } Monitor;
+#define MAX_MON 16
+
+typedef struct {
+    Monitor m;
+    double  scale;
+    bool    swap;    /* rotated 90/270 → swap w/h */
+    bool    valid;
+} Pending;
+
+static void pend_reset(Pending *p)
+{
+    memset(p, 0, sizeof *p);
+    p->scale = 1.0;
+}
+
+static void pend_commit(Pending *p, Monitor *out, int *n, int max)
+{
+    if (p->valid && p->m.w > 0 && p->m.h > 0 && *n < max) {
+        Monitor m = p->m;
+        if (p->swap) { int t = m.w; m.w = m.h; m.h = t; }
+        if (p->scale > 0.0 && p->scale != 1.0) {
+            m.w = (int)(m.w / p->scale + 0.5);
+            m.h = (int)(m.h / p->scale + 0.5);
+        }
+        out[(*n)++] = m;
+    }
+    pend_reset(p);
+}
+
+static char *skip_ws(char *s) { while (*s == ' ' || *s == '\t') s++; return s; }
+
+static bool is_rot90(const char *v)
+{
+    return strstr(v, "90") || strstr(v, "270");
+}
+
+/* swaymsg -p -t get_outputs */
+static int parse_sway(FILE *f, Monitor *out, int max)
+{
+    char line[512]; int n = 0; Pending p; pend_reset(&p);
+    while (fgets(line, sizeof line, f)) {
+        if (strncmp(line, "Output ", 7) == 0) {
+            pend_commit(&p, out, &n, max);
+            if (sscanf(line + 7, "%31s", p.m.name) == 1) p.valid = true;
+            continue;
+        }
+        char *s = skip_ws(line);
+        if      (sscanf(s, "Current mode: %dx%d", &p.m.w, &p.m.h) == 2) {}
+        else if (sscanf(s, "Position: %d,%d", &p.m.x, &p.m.y) == 2) {}
+        else if (sscanf(s, "Scale factor: %lf", &p.scale) == 1) {}
+        else if (strncmp(s, "Transform:", 10) == 0) p.swap = is_rot90(s + 10);
+    }
+    pend_commit(&p, out, &n, max);
+    return n;
+}
+
+/* hyprctl monitors */
+static int parse_hypr(FILE *f, Monitor *out, int max)
+{
+    char line[512]; int n = 0; Pending p; pend_reset(&p);
+    while (fgets(line, sizeof line, f)) {
+        if (strncmp(line, "Monitor ", 8) == 0) {
+            pend_commit(&p, out, &n, max);
+            if (sscanf(line + 8, "%31s", p.m.name) == 1) p.valid = true;
+            continue;
+        }
+        char *s = skip_ws(line);
+        int t;
+        if      (sscanf(s, "%dx%d@%*f at %dx%d", &p.m.w, &p.m.h, &p.m.x, &p.m.y) == 4) {}
+        else if (sscanf(s, "scale: %lf", &p.scale) == 1) {}
+        else if (sscanf(s, "transform: %d", &t) == 1) p.swap = (t % 2) == 1;
+    }
+    pend_commit(&p, out, &n, max);
+    return n;
+}
+
+/* wlr-randr (generic wlroots compositors) */
+static int parse_wlr(FILE *f, Monitor *out, int max)
+{
+    char line[512]; int n = 0; Pending p; pend_reset(&p);
+    while (fgets(line, sizeof line, f)) {
+        if (line[0] != ' ' && line[0] != '\t' && line[0] != '\n') {
+            pend_commit(&p, out, &n, max);
+            if (sscanf(line, "%31s", p.m.name) == 1) p.valid = true;
+            continue;
+        }
+        char *s = skip_ws(line);
+        if (strncmp(s, "Enabled: no", 11) == 0) p.valid = false;
+        else if (strstr(s, " px") && strstr(s, "current"))
+            sscanf(s, "%dx%d", &p.m.w, &p.m.h);
+        else if (sscanf(s, "Position: %d,%d", &p.m.x, &p.m.y) == 2) {}
+        else if (sscanf(s, "Scale: %lf", &p.scale) == 1) {}
+        else if (strncmp(s, "Transform:", 10) == 0) p.swap = is_rot90(s + 10);
+    }
+    pend_commit(&p, out, &n, max);
+    return n;
+}
+
+/* xrandr --query:  "DP-1 connected primary 1920x1080+0+0 (normal ..." */
+static int parse_xrandr(FILE *f, Monitor *out, int max)
+{
+    char line[512]; int n = 0;
+    while (fgets(line, sizeof line, f) && n < max) {
+        if (!strstr(line, " connected")) continue;
+        Monitor m = {0};
+        if (sscanf(line, "%31s", m.name) != 1) continue;
+        char *save = NULL;
+        for (char *t = strtok_r(line, " \t", &save); t; t = strtok_r(NULL, " \t", &save)) {
+            if (sscanf(t, "%dx%d+%d+%d", &m.w, &m.h, &m.x, &m.y) == 4) {
+                out[n++] = m;
+                break;
+            }
+        }
+    }
+    return n;
+}
+
+/* Last resort: /sys/class/drm gives resolution only (position 0,0). */
+static int detect_drm(Monitor *out, int max)
+{
+    DIR *d = opendir("/sys/class/drm");
+    if (!d) return 0;
+    int n = 0;
+    struct dirent *e;
+    while ((e = readdir(d)) && n < max) {
+        const char *dash = strchr(e->d_name, '-');
+        if (strncmp(e->d_name, "card", 4) != 0 || !dash) continue;
+        char path[512], buf[64] = "";
+        snprintf(path, sizeof path, "/sys/class/drm/%s/status", e->d_name);
+        FILE *f = fopen(path, "r");
+        if (!f) continue;
+        bool connected = fgets(buf, sizeof buf, f) && strncmp(buf, "connected", 9) == 0;
+        fclose(f);
+        if (!connected) continue;
+        snprintf(path, sizeof path, "/sys/class/drm/%s/modes", e->d_name);
+        f = fopen(path, "r");
+        if (!f) continue;
+        Monitor m = {0};
+        if (fgets(buf, sizeof buf, f) && sscanf(buf, "%dx%d", &m.w, &m.h) == 2) {
+            snprintf(m.name, sizeof m.name, "%s", dash + 1);
+            out[n++] = m;
+        }
+        fclose(f);
+    }
+    closedir(d);
+    return n;
+}
+
+static int run_parse(const char *cmd, int (*parse)(FILE *, Monitor *, int),
+                     Monitor *out, int max)
+{
+    FILE *f = popen(cmd, "r");
+    if (!f) return 0;
+    int n = parse(f, out, max);
+    pclose(f);   /* may report ECHILD if main's SIGCHLD reaped it — harmless */
+    return n;
+}
+
+static int detect_monitors(Monitor *out, int max)
+{
+    int n = 0;
+    if (getenv("WAYLAND_DISPLAY")) {
+        if (getenv("SWAYSOCK"))
+            n = run_parse("swaymsg -p -t get_outputs 2>/dev/null", parse_sway, out, max);
+        if (!n && getenv("HYPRLAND_INSTANCE_SIGNATURE"))
+            n = run_parse("hyprctl monitors 2>/dev/null", parse_hypr, out, max);
+        if (!n)
+            n = run_parse("wlr-randr 2>/dev/null", parse_wlr, out, max);
+    } else if (getenv("DISPLAY")) {
+        n = run_parse("xrandr --query 2>/dev/null", parse_xrandr, out, max);
+    }
+    if (!n) n = detect_drm(out, max);
+    return n;
+}
+
+static bool parse_geo(const char *s, int *w, int *h, int *x, int *y)
+{
+    char tail;
+    return sscanf(s, "%dx%d+%d+%d%c", w, h, x, y, &tail) == 4 && *w > 0 && *h > 0;
+}
+
+/* Resolve a selector (empty, 1-based index, name, or WxH+X+Y) to a
+ * geometry string. Returns false with *err set on failure. */
+static bool resolve_share_target(const char *sel, char *geo, size_t geolen,
+                                 char *mon, size_t monlen, const char **err)
+{
+    int w, h, x, y;
+    if (sel && parse_geo(sel, &w, &h, &x, &y)) {
+        snprintf(geo, geolen, "%dx%d+%d+%d", w, h, x, y);
+        snprintf(mon, monlen, "-");
+        return true;
+    }
+
+    Monitor m[MAX_MON];
+    int n = detect_monitors(m, MAX_MON);
+    if (n == 0) {
+        *err = "no monitor detected — pass a geometry: share start WxH+X+Y";
+        return false;
+    }
+
+    int pick = 0;   /* default: first monitor */
+    if (sel && *sel) {
+        char *ep;
+        long idx = strtol(sel, &ep, 10);
+        pick = -1;
+        if (*ep == '\0') {
+            if (idx >= 1 && idx <= n) pick = (int)idx - 1;
+        } else {
+            for (int i = 0; i < n; i++)
+                if (strcmp(m[i].name, sel) == 0) { pick = i; break; }
+        }
+        if (pick < 0) { *err = "unknown monitor (see 'monitors')"; return false; }
+    }
+    snprintf(geo, geolen, "%dx%d+%d+%d", m[pick].w, m[pick].h, m[pick].x, m[pick].y);
+    snprintf(mon, monlen, "%.31s", m[pick].name);
+    return true;
+}
+
+/* ══════════════════════════════════════════════════════════════
+ * State snapshot
+ * ══════════════════════════════════════════════════════════════ */
+typedef struct {
+    bool share;   char share_id[64]; int sx, sy, sw, sh, s_z;
+    bool cam;     char cam_id[64];   int cx, cy, cw, ch, c_z;
+    bool cam_over_screen;
+    int  overlays;
+} State;
+
+static bool rects_intersect(int ax, int ay, int aw, int ah,
+                            int bx, int by, int bw, int bh)
+{
+    return ax < bx + bw && bx < ax + aw && ay < by + bh && by < ay + ah;
+}
+
+static void collect(OverlayRegistry *reg, State *st)
+{
+    memset(st, 0, sizeof *st);
+    pthread_mutex_lock(&reg->lock);
+    st->overlays = reg->count;
+    for (int i = 0; i < reg->count; i++) {
+        OverlaySlot *s = &reg->slots[i];
+        OverlayType t = overlay_get_type(s->overlay);
+        int x, y, w, h;
+        overlay_get_rect(s->overlay, &x, &y, &w, &h);
+
+        /* Prefer our own ids ("share"/"cam") once seen; otherwise the
+         * topmost overlay of that type wins. */
+        if (t == OVERLAY_SCREEN &&
+            (!st->share || strcmp(st->share_id, SHARE_ID) != 0)) {
+            st->share = true;
+            snprintf(st->share_id, sizeof st->share_id, "%s", s->id);
+            st->sx = x; st->sy = y; st->sw = w; st->sh = h; st->s_z = i;
+        }
+        if (t == OVERLAY_WEBCAM &&
+            (!st->cam || strcmp(st->cam_id, CAM_ID) != 0)) {
+            st->cam = true;
+            snprintf(st->cam_id, sizeof st->cam_id, "%s", s->id);
+            st->cx = x; st->cy = y; st->cw = w; st->ch = h; st->c_z = i;
+        }
+
+        /* cam_over_screen: a webcam overlay drawn above a screen
+         * overlay, overlapping it, and visible inside the output. */
+        if (t == OVERLAY_WEBCAM &&
+            rects_intersect(x, y, w, h, 0, 0, g_output_w, g_output_h)) {
+            for (int j = 0; j < i; j++) {
+                if (overlay_get_type(reg->slots[j].overlay) != OVERLAY_SCREEN) continue;
+                int bx, by, bw, bh;
+                overlay_get_rect(reg->slots[j].overlay, &bx, &by, &bw, &bh);
+                if (rects_intersect(x, y, w, h, bx, by, bw, bh))
+                    st->cam_over_screen = true;
+            }
+        }
+    }
+    pthread_mutex_unlock(&reg->lock);
+}
+
+static const char *anchor_name(int x, int y, int w, int h)
+{
+    int W = g_output_w, H = g_output_h, m = g_cam_margin;
+    if (x <= 0 && y <= 0 && w >= W && h >= H) return "full";
+    int L = m, R = W - w - m, T = m, B = H - h - m;
+    if (x == L && y == T) return "tl";
+    if (x == R && y == T) return "tr";
+    if (x == L && y == B) return "bl";
+    if (x == R && y == B) return "br";
+    if (x == (W - w) / 2 && y == (H - h) / 2) return "center";
+    return "custom";
+}
+
+/* Compute x/y for a named anchor. "full" also overrides w/h. */
+static bool anchor_xy(const char *pos, int *x, int *y, int *w, int *h)
+{
+    int W = g_output_w, H = g_output_h, m = g_cam_margin;
+    if      (!strcmp(pos, "tl"))     { *x = m;            *y = m; }
+    else if (!strcmp(pos, "tr"))     { *x = W - *w - m;   *y = m; }
+    else if (!strcmp(pos, "bl"))     { *x = m;            *y = H - *h - m; }
+    else if (!strcmp(pos, "br"))     { *x = W - *w - m;   *y = H - *h - m; }
+    else if (!strcmp(pos, "center")) { *x = (W - *w) / 2; *y = (H - *h) / 2; }
+    else if (!strcmp(pos, "full"))   { *x = 0; *y = 0; *w = W; *h = H; }
+    else return false;
+    return true;
+}
+
+/* Cam height from width, using the capture aspect (cam_buf == output size).
+ * Must match overlay_tick's aspect fix-up + resolve_dims' even rounding
+ * exactly, or the first frame would shift the height and break the anchor. */
+static int cam_h_for(int w)
+{
+    int h = g_output_w > 0 ? (int)((long)w * g_output_h / g_output_w) : w * 9 / 16;
+    return (h & 1) ? h + 1 : h;
+}
+
+/* ══════════════════════════════════════════════════════════════
+ * Status: key/value list → plain, single key, or JSON
+ * ══════════════════════════════════════════════════════════════ */
+typedef struct { const char *k; char v[80]; char t; } KV;   /* t: b=bool i=int s=str */
+#define MAX_KV 40
+
+static int kv_add(KV *kv, int n, const char *k, char t, const char *fmt, ...)
+{
+    if (n >= MAX_KV) return n;
+    kv[n].k = k; kv[n].t = t;
+    va_list ap; va_start(ap, fmt);
+    vsnprintf(kv[n].v, sizeof kv[n].v, fmt, ap);
+    va_end(ap);
+    /* values must be single tokens in plain mode */
+    for (char *p = kv[n].v; *p; p++) if (*p == ' ' || *p == '"' || *p == '\\') *p = '_';
+    return n + 1;
+}
+
+static int build_status(OverlayRegistry *reg, KV *kv)
+{
+    State st; collect(reg, &st);
+    int n = 0, nf;
+    pthread_mutex_lock(&g_filters.lock);
+    nf = g_filters.count;
+    pthread_mutex_unlock(&g_filters.lock);
+    bool share_ours = st.share && !strcmp(st.share_id, SHARE_ID);
+    bool full = st.share && st.sx <= 0 && st.sy <= 0 &&
+                st.sx + st.sw >= g_output_w && st.sy + st.sh >= g_output_h;
+
+    n = kv_add(kv, n, "version",          's', "%s", VCAM_VERSION);
+    n = kv_add(kv, n, "build",            's', "%s", VCAM_BUILD);
+    n = kv_add(kv, n, "input",            's', "%s", g_no_input ? "none" : "webcam");
+    n = kv_add(kv, n, "output_w",         'i', "%d", g_output_w);
+    n = kv_add(kv, n, "output_h",         'i', "%d", g_output_h);
+    n = kv_add(kv, n, "fps",              'i', "%d", g_output_fps);
+    n = kv_add(kv, n, "share",            'b', "%d", st.share);
+    n = kv_add(kv, n, "share_id",         's', "%s", st.share ? st.share_id : "-");
+    n = kv_add(kv, n, "share_fullscreen", 'b', "%d", full);
+    n = kv_add(kv, n, "share_monitor",    's', "%s", share_ours && g_share_mon[0] ? g_share_mon : "-");
+    n = kv_add(kv, n, "share_geometry",   's', "%s", share_ours && g_share_geo[0] ? g_share_geo : "-");
+    n = kv_add(kv, n, "share_x",          'i', "%d", st.sx);
+    n = kv_add(kv, n, "share_y",          'i', "%d", st.sy);
+    n = kv_add(kv, n, "share_w",          'i', "%d", st.sw);
+    n = kv_add(kv, n, "share_h",          'i', "%d", st.sh);
+    n = kv_add(kv, n, "cam",              'b', "%d", st.cam);
+    n = kv_add(kv, n, "cam_id",           's', "%s", st.cam ? st.cam_id : "-");
+    n = kv_add(kv, n, "cam_pos",          's', "%s", st.cam ? anchor_name(st.cx, st.cy, st.cw, st.ch) : "-");
+    n = kv_add(kv, n, "cam_x",            'i', "%d", st.cx);
+    n = kv_add(kv, n, "cam_y",            'i', "%d", st.cy);
+    n = kv_add(kv, n, "cam_w",            'i', "%d", st.cw);
+    n = kv_add(kv, n, "cam_h",            'i', "%d", st.ch);
+    n = kv_add(kv, n, "cam_z",            'i', "%d", st.cam ? st.c_z : -1);
+    n = kv_add(kv, n, "cam_margin",       'i', "%d", g_cam_margin);
+    n = kv_add(kv, n, "cam_over_screen",  'b', "%d", st.cam_over_screen);
+    n = kv_add(kv, n, "overlays",         'i', "%d", st.overlays);
+    n = kv_add(kv, n, "filters",          'i', "%d", nf);
+    n = kv_add(kv, n, "recording",        'b', "%d", recorder_active(g_recorder));
+    return n;
+}
+
+static const char *kv_plain(const KV *e)
+{
+    if (e->t == 'b') return strcmp(e->v, "0") ? "yes" : "no";
+    return e->v;
+}
+
+static void cmd_status(int fd, OverlayRegistry *reg, bool json)
+{
+    KV kv[MAX_KV];
+    int n = build_status(reg, kv);
+    char buf[3072];
+    size_t off = 0;
+    off += (size_t)snprintf(buf + off, sizeof buf - off, json ? "{\"ok\":true" : "OK");
+    for (int i = 0; i < n && off < sizeof buf; i++) {
+        if (!json)
+            off += (size_t)snprintf(buf + off, sizeof buf - off, " %s=%s", kv[i].k, kv_plain(&kv[i]));
+        else if (kv[i].t == 'b')
+            off += (size_t)snprintf(buf + off, sizeof buf - off, ",\"%s\":%s", kv[i].k,
+                                    strcmp(kv[i].v, "0") ? "true" : "false");
+        else if (kv[i].t == 'i')
+            off += (size_t)snprintf(buf + off, sizeof buf - off, ",\"%s\":%s", kv[i].k, kv[i].v);
+        else
+            off += (size_t)snprintf(buf + off, sizeof buf - off, ",\"%s\":\"%s\"", kv[i].k, kv[i].v);
+    }
+    if (json && off < sizeof buf) snprintf(buf + off, sizeof buf - off, "}");
+    reply(fd, "%s", buf);
+}
+
+static void cmd_get(int fd, OverlayRegistry *reg, const char *key)
+{
+    if (!key) { reply(fd, "ERR usage: get <key>   (keys: see 'status')"); return; }
+    KV kv[MAX_KV];
+    int n = build_status(reg, kv);
+    for (int i = 0; i < n; i++)
+        if (!strcmp(kv[i].k, key)) { reply(fd, "OK %s", kv_plain(&kv[i])); return; }
+    reply(fd, "ERR unknown key '%s'", key);
+}
+
+/* ══════════════════════════════════════════════════════════════
+ * cam
+ * ══════════════════════════════════════════════════════════════ */
+static void cam_reply(int fd, OverlayRegistry *reg)
+{
+    State st; collect(reg, &st);
+    if (!st.cam) { reply(fd, "OK cam=off"); return; }
+    reply(fd, "OK cam=on id=%s pos=%s x=%d y=%d w=%d h=%d z=%d over_screen=%s",
+          st.cam_id, anchor_name(st.cx, st.cy, st.cw, st.ch),
+          st.cx, st.cy, st.cw, st.ch, st.c_z, st.cam_over_screen ? "yes" : "no");
+}
+
+/* Place (and create if needed) the cam overlay. pos may be NULL to keep
+ * the current anchor; w <= 0 keeps the current width (or 320). */
+static bool cam_place(OverlayRegistry *reg, const char *pos, int w, int h,
+                      const char **err)
+{
+    State st; collect(reg, &st);
+    const char *id = st.cam ? st.cam_id : CAM_ID;
+    const char *anchor = pos ? pos
+                       : st.cam ? anchor_name(st.cx, st.cy, st.cw, st.ch) : "tr";
+    if (w <= 0) w = st.cam ? st.cw : 320;
+    if (h <= 0) h = cam_h_for(w);
+    if (w < 16 || h < 16) { *err = "cam size too small"; return false; }
+
+    int x = st.cx, y = st.cy;
+    if (strcmp(anchor, "custom") != 0 && !anchor_xy(anchor, &x, &y, &w, &h)) {
+        *err = "unknown position (use tl|tr|bl|br|center|full)";
+        return false;
+    }
+
+    if (!st.cam) {
+        Overlay *o = overlay_create_webcam("-", x, y, w, h);
+        if (!o) { *err = "failed to create webcam overlay"; return false; }
+        if (!registry_add(reg, id, o)) {
+            overlay_free(o);
+            *err = "could not add cam overlay (registry full?)";
+            return false;
+        }
+    } else {
+        pthread_mutex_lock(&reg->lock);
+        Overlay *o = registry_find(reg, id);
+        if (o) { overlay_resize(o, w, h); overlay_move(o, x, y); }
+        pthread_mutex_unlock(&reg->lock);
+    }
+    registry_raise(reg, id);   /* cam always on top of the share */
+    return true;
+}
+
+static bool cam_handle(int fd, char **save, OverlayRegistry *reg)
+{
+    char *sub = strtok_r(NULL, " \t", save);
+    const char *err = NULL;
+    State st;
+
+    if (!sub || !strcmp(sub, "get") || !strcmp(sub, "status")) {
+        cam_reply(fd, reg); return true;
+    }
+    if (!strcmp(sub, "on") || !strcmp(sub, "pos")) {
+        char *pos = strtok_r(NULL, " \t", save);
+        char *ws  = strtok_r(NULL, " \t", save);
+        if (!strcmp(sub, "pos") && !pos) { reply(fd, "ERR usage: cam pos <tl|tr|bl|br|center|full>"); return true; }
+        if (!cam_place(reg, pos, ws ? atoi(ws) : 0, 0, &err)) { reply(fd, "ERR %s", err); return true; }
+        cam_reply(fd, reg); return true;
+    }
+    if (!strcmp(sub, "off")) {
+        collect(reg, &st);
+        if (st.cam) registry_remove(reg, st.cam_id);
+        reply(fd, "OK cam=off"); return true;
+    }
+    if (!strcmp(sub, "toggle")) {
+        collect(reg, &st);
+        if (st.cam) { registry_remove(reg, st.cam_id); reply(fd, "OK cam=off"); return true; }
+        if (!cam_place(reg, NULL, 0, 0, &err)) { reply(fd, "ERR %s", err); return true; }
+        cam_reply(fd, reg); return true;
+    }
+    if (!strcmp(sub, "move")) {
+        char *xs = strtok_r(NULL, " \t", save), *ys = strtok_r(NULL, " \t", save);
+        if (!xs || !ys) { reply(fd, "ERR usage: cam move <x> <y>"); return true; }
+        collect(reg, &st);
+        if (!st.cam) { reply(fd, "ERR cam is off (use 'cam on')"); return true; }
+        pthread_mutex_lock(&reg->lock);
+        Overlay *o = registry_find(reg, st.cam_id);
+        if (o) overlay_move(o, atoi(xs), atoi(ys));
+        pthread_mutex_unlock(&reg->lock);
+        cam_reply(fd, reg); return true;
+    }
+    if (!strcmp(sub, "size")) {
+        char *ws = strtok_r(NULL, " \t", save), *hs = strtok_r(NULL, " \t", save);
+        if (!ws) { reply(fd, "ERR usage: cam size <w> [<h>]"); return true; }
+        collect(reg, &st);
+        if (!st.cam) { reply(fd, "ERR cam is off (use 'cam on')"); return true; }
+        const char *a = anchor_name(st.cx, st.cy, st.cw, st.ch);
+        if (!strcmp(a, "full")) a = "tr";    /* resizing leaves fullscreen */
+        if (!cam_place(reg, a, atoi(ws), hs ? atoi(hs) : 0, &err)) { reply(fd, "ERR %s", err); return true; }
+        cam_reply(fd, reg); return true;
+    }
+    if (!strcmp(sub, "margin")) {
+        char *ms = strtok_r(NULL, " \t", save);
+        if (!ms) { reply(fd, "OK margin=%d", g_cam_margin); return true; }
+        collect(reg, &st);
+        const char *a = st.cam ? anchor_name(st.cx, st.cy, st.cw, st.ch) : NULL;
+        g_cam_margin = atoi(ms) < 0 ? 0 : atoi(ms);
+        if (a && strcmp(a, "custom") != 0 && strcmp(a, "full") != 0)
+            cam_place(reg, a, st.cw, st.ch, &err);
+        cam_reply(fd, reg); return true;
+    }
+    if (!strcmp(sub, "raise")) {
+        collect(reg, &st);
+        if (!st.cam) { reply(fd, "ERR cam is off"); return true; }
+        registry_raise(reg, st.cam_id);
+        cam_reply(fd, reg); return true;
+    }
+    reply(fd, "ERR cam: unknown subcommand (on|off|toggle|pos|move|size|margin|raise|get)");
+    return true;
+}
+
+/* ══════════════════════════════════════════════════════════════
+ * share
+ * ══════════════════════════════════════════════════════════════ */
+static void share_reply(int fd, OverlayRegistry *reg)
+{
+    KV kv[MAX_KV];
+    int n = build_status(reg, kv);
+    char buf[512]; size_t off = 0;
+    off += (size_t)snprintf(buf, sizeof buf, "OK");
+    for (int i = 0; i < n && off < sizeof buf; i++)
+        if (!strncmp(kv[i].k, "share", 5) || !strcmp(kv[i].k, "cam") ||
+            !strcmp(kv[i].k, "cam_pos") || !strcmp(kv[i].k, "cam_over_screen"))
+            off += (size_t)snprintf(buf + off, sizeof buf - off, " %s=%s", kv[i].k, kv_plain(&kv[i]));
+    reply(fd, "%s", buf);
+}
+
+static void share_stop(OverlayRegistry *reg)
+{
+    State st; collect(reg, &st);
+    if (st.share) registry_remove(reg, st.share_id);
+    g_share_geo[0] = g_share_mon[0] = '\0';
+}
+
+static void share_start(int fd, char **save, OverlayRegistry *reg)
+{
+    const char *sel = NULL, *campos = NULL, *err = NULL;
+    bool contain = false;
+    int camw = 0;
+    char *t;
+    while ((t = strtok_r(NULL, " \t", save))) {
+        if      (!strncmp(t, "fit=", 4))     contain = !strcmp(t + 4, "contain");
+        else if (!strncmp(t, "cam=", 4))     campos = t + 4;
+        else if (!strncmp(t, "camw=", 5))    camw = atoi(t + 5);
+        else if (!strncmp(t, "monitor=", 8)) sel = t + 8;
+        else if (!strncmp(t, "geo=", 4))     sel = t + 4;
+        else                                 sel = t;
+    }
+    if (g_output_w <= 0 || g_output_h <= 0) { reply(fd, "ERR output size unknown"); return; }
+
+    char geo[64], mon[64];
+    if (!resolve_share_target(sel, geo, sizeof geo, mon, sizeof mon, &err)) {
+        reply(fd, "ERR %s", err); return;
+    }
+    int gw, gh, gx, gy;
+    parse_geo(geo, &gw, &gh, &gx, &gy);
+
+    int dx = 0, dy = 0, dw = g_output_w, dh = g_output_h;
+    if (contain) {
+        double sx = (double)g_output_w / gw, sy = (double)g_output_h / gh;
+        double s  = sx < sy ? sx : sy;
+        dw = (int)(gw * s) & ~1; dh = (int)(gh * s) & ~1;
+        dx = (g_output_w - dw) / 2; dy = (g_output_h - dh) / 2;
+    }
+
+    share_stop(reg);   /* restart cleanly if already sharing */
+    Overlay *o = overlay_create_screen(geo, dx, dy, dw, dh);
+    if (!o) {
+        reply(fd, "ERR screen capture failed (wf-recorder on Wayland / ffmpeg x11grab on X11 — see vcam stderr)");
+        return;
+    }
+    if (!registry_add(reg, SHARE_ID, o)) {
+        overlay_free(o);
+        reply(fd, "ERR could not add share overlay (registry full?)");
+        return;
+    }
+    registry_lower(reg, SHARE_ID);   /* screen is the background layer */
+    snprintf(g_share_geo, sizeof g_share_geo, "%s", geo);
+    snprintf(g_share_mon, sizeof g_share_mon, "%s", mon);
+
+    if (campos && !strcmp(campos, "off")) {
+        State st; collect(reg, &st);
+        if (st.cam) registry_remove(reg, st.cam_id);
+    } else if (campos || camw > 0) {
+        if (!cam_place(reg, campos, camw, 0, &err)) { reply(fd, "ERR share on, but cam: %s", err); return; }
+    } else {
+        State st; collect(reg, &st);
+        if (st.cam) registry_raise(reg, st.cam_id);
+    }
+    share_reply(fd, reg);
+}
+
+static bool share_handle(int fd, char **save, OverlayRegistry *reg)
+{
+    char *sub = strtok_r(NULL, " \t", save);
+    if (!sub || !strcmp(sub, "status") || !strcmp(sub, "get")) { share_reply(fd, reg); return true; }
+    if (!strcmp(sub, "start") || !strcmp(sub, "on")) { share_start(fd, save, reg); return true; }
+    if (!strcmp(sub, "stop")  || !strcmp(sub, "off")) { share_stop(reg); share_reply(fd, reg); return true; }
+    if (!strcmp(sub, "toggle")) {
+        State st; collect(reg, &st);
+        if (st.share) { share_stop(reg); share_reply(fd, reg); }
+        else share_start(fd, save, reg);
+        return true;
+    }
+    reply(fd, "ERR share: unknown subcommand (start|stop|toggle|status)");
+    return true;
+}
+
+/* ══════════════════════════════════════════════════════════════
+ * entry point — returns true if the command was handled here
+ * ══════════════════════════════════════════════════════════════ */
+bool api_handle(int fd, const char *cmd, char **save, OverlayRegistry *reg)
+{
+    if (!strcmp(cmd, "status")) {
+        char *a = strtok_r(NULL, " \t", save);
+        cmd_status(fd, reg, a && (!strcmp(a, "json") || !strcmp(a, "--json")));
+        return true;
+    }
+    if (!strcmp(cmd, "get"))     { cmd_get(fd, reg, strtok_r(NULL, " \t", save)); return true; }
+    if (!strcmp(cmd, "version")) { reply(fd, "OK %s", api_version_string()); return true; }
+    if (!strcmp(cmd, "share"))   return share_handle(fd, save, reg);
+    if (!strcmp(cmd, "cam"))     return cam_handle(fd, save, reg);
+    if (!strcmp(cmd, "monitors")) {
+        Monitor m[MAX_MON];
+        int n = detect_monitors(m, MAX_MON);
+        if (n == 0) { reply(fd, "ERR no monitor detected"); return true; }
+        for (int i = 0; i < n; i++)
+            reply(fd, "OK %d %s %dx%d+%d+%d", i + 1, m[i].name, m[i].w, m[i].h, m[i].x, m[i].y);
+        return true;
+    }
+    return false;
+}
diff --git a/src/ipc.c b/src/ipc.c
index 66d5452..4ead4bf 100644
--- a/src/ipc.c
+++ b/src/ipc.c
@@ -4,10 +4,14 @@
  *
  * This program is free software under the terms of the GNU General
  * Public License version 2. See the LICENSE file for the full text.
+ *
+ * Modified-by: Claude Opus 5.5 (control API hook, multi-client, VCAM_SOCK)
  */
 
 /*
- * IPC server – Unix domain socket at /tmp/vcam.sock
+ * IPC server – Unix domain socket at /tmp/vcam.sock ($VCAM_SOCK overrides).
+ * Several clients may stay connected at once; commands are serialised.
+ * High-level commands (status/get/share/cam/monitors/version): api.c
  *
  * Protocol: newline-terminated UTF-8 text commands.
  *
@@ -39,6 +43,7 @@
 #include <fcntl.h>
 #include <signal.h>
 #include <pthread.h>
+#include <time.h>
 
 /* ── helpers ─────────────────────────────────── */
 static void send_line(int fd, const char *msg)
@@ -196,6 +201,10 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
         return;
     }
 
+    /* High-level control API (status, get, share, cam, monitors, version) */
+    if (api_handle(client_fd, cmd, &save, reg))
+        return;
+
     /* ── filter <subcmd> ──
      *   filter help
      *   filter add <name> [<param>]
@@ -831,6 +840,15 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
         send_line(client_fd, "OK   z      <id> <N>                      explicit z-index (0=bottom, -1=top)");
         send_line(client_fd, "OK   filter help                          list available filters");
         send_line(client_fd, "OK   filter list/add/remove/clear/set     manage filter chain");
+        send_line(client_fd, "OK control API (one-line replies, for scripts/apps):");
+        send_line(client_fd, "OK   status [json]                        whole state as k=v line or JSON");
+        send_line(client_fd, "OK   get <key>                            one status value (e.g. get cam_pos)");
+        send_line(client_fd, "OK   share start [<n>|<name>|<WxH+X+Y>] [fit=stretch|contain] [cam=<pos>|off] [camw=N]");
+        send_line(client_fd, "OK   share stop|toggle|status             fullscreen screen share");
+        send_line(client_fd, "OK   cam on [<pos>] [<w>] | off | toggle  webcam PiP; pos tl|tr|bl|br|center|full");
+        send_line(client_fd, "OK   cam pos <pos> | move <x> <y> | size <w> [<h>] | margin <px> | raise | get");
+        send_line(client_fd, "OK   monitors                             list monitors (n name WxH+X+Y)");
+        send_line(client_fd, "OK   version                              vcam version + build hash");
         send_line(client_fd, "OK   quit                                 close the connection");
         return;
     }
@@ -1258,6 +1276,57 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
     send_line(client_fd, buf);
 }
 
+/* ── clients ─────────────────────────────────────
+ * Each connection gets its own detached thread, so a long-lived
+ * controller app never blocks vcam-ctl. g_cmd_lock serialises the
+ * actual command handling (handle_command was written single-threaded).
+ */
+#define MAX_CLIENTS 16
+static pthread_mutex_t g_cmd_lock = PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t g_cli_lock = PTHREAD_MUTEX_INITIALIZER;
+static int             g_cli_fds[MAX_CLIENTS];
+static int             g_cli_n = 0;
+static char            g_sock_path[108] = VCAM_SOCK_PATH;
+
+const char *ipc_sock_path(void) { return g_sock_path; }
+
+static bool client_register(int fd)
+{
+    pthread_mutex_lock(&g_cli_lock);
+    bool ok = g_cli_n < MAX_CLIENTS;
+    if (ok) g_cli_fds[g_cli_n++] = fd;
+    pthread_mutex_unlock(&g_cli_lock);
+    return ok;
+}
+
+static void client_unregister(int fd)
+{
+    pthread_mutex_lock(&g_cli_lock);
+    for (int i = 0; i < g_cli_n; i++)
+        if (g_cli_fds[i] == fd) { g_cli_fds[i] = g_cli_fds[--g_cli_n]; break; }
+    pthread_mutex_unlock(&g_cli_lock);
+}
+
+typedef struct { IPCServer *srv; int fd; } ClientArg;
+
+static void *client_thread(void *arg)
+{
+    ClientArg ca = *(ClientArg *)arg;
+    free(arg);
+
+    char line[1024];
+    while (ca.srv->running && read_line(ca.fd, line, sizeof line) >= 0) {
+        bool should_quit = (strcmp(line, "quit") == 0);
+        pthread_mutex_lock(&g_cmd_lock);
+        if (ca.srv->running) handle_command(ca.fd, line, ca.srv->registry);
+        pthread_mutex_unlock(&g_cmd_lock);
+        if (should_quit) break;
+    }
+    client_unregister(ca.fd);
+    close(ca.fd);
+    return NULL;
+}
+
 /* ── server thread ───────────────────────────── */
 static void *ipc_thread(void *arg)
 {
@@ -1288,14 +1357,28 @@ static void *ipc_thread(void *arg)
             break;
         }
 
-        char line[1024];
-        int n;
-        while ((n = read_line(client, line, sizeof line)) >= 0) {
-            bool should_quit = (strcmp(line, "quit") == 0);
-            handle_command(client, line, srv->registry);
-            if (should_quit) break;
+        if (!client_register(client)) {
+            send_line(client, "ERR too many clients");
+            close(client);
+            continue;
         }
-        close(client);
+        ClientArg *ca = malloc(sizeof *ca);
+        pthread_t th;
+        pthread_attr_t attr;
+        pthread_attr_init(&attr);
+        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
+        bool started = false;
+        if (ca) {
+            ca->srv = srv;
+            ca->fd  = client;
+            started = pthread_create(&th, &attr, client_thread, ca) == 0;
+        }
+        if (!started) {
+            free(ca);
+            client_unregister(client);
+            close(client);
+        }
+        pthread_attr_destroy(&attr);
     }
     return NULL;
 }
@@ -1306,19 +1389,22 @@ bool ipc_start(IPCServer *srv, OverlayRegistry *reg)
     srv->registry = reg;
     srv->running  = true;
 
-    unlink(VCAM_SOCK_PATH);
+    const char *env = getenv("VCAM_SOCK");
+    if (env && *env) snprintf(g_sock_path, sizeof g_sock_path, "%s", env);
+
+    unlink(g_sock_path);
 
     srv->server_fd = socket(AF_UNIX, SOCK_STREAM, 0);
     if (srv->server_fd < 0) { perror("[ipc] socket"); return false; }
 
     struct sockaddr_un addr = {0};
     addr.sun_family = AF_UNIX;
-    strncpy(addr.sun_path, VCAM_SOCK_PATH, sizeof addr.sun_path - 1);
+    snprintf(addr.sun_path, sizeof addr.sun_path, "%s", g_sock_path);
 
     if (bind(srv->server_fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
         perror("[ipc] bind"); close(srv->server_fd); return false;
     }
-    chmod(VCAM_SOCK_PATH, 0600);
+    chmod(g_sock_path, 0600);
 
     if (listen(srv->server_fd, 4) < 0) {
         perror("[ipc] listen"); close(srv->server_fd); return false;
@@ -1328,7 +1414,7 @@ bool ipc_start(IPCServer *srv, OverlayRegistry *reg)
         perror("[ipc] pthread_create"); close(srv->server_fd); return false;
     }
 
-    fprintf(stderr, "[ipc] Listening on %s\n", VCAM_SOCK_PATH);
+    fprintf(stderr, "[ipc] Listening on %s\n", g_sock_path);
     return true;
 }
 
@@ -1338,5 +1424,19 @@ void ipc_stop(IPCServer *srv)
     shutdown(srv->server_fd, SHUT_RDWR);
     close(srv->server_fd);
     pthread_join(srv->thread, NULL);
-    unlink(VCAM_SOCK_PATH);
+
+    /* Kick connected clients out of read() and wait (max ~1s) until
+     * their threads are gone, so nothing touches the registry after. */
+    pthread_mutex_lock(&g_cli_lock);
+    for (int i = 0; i < g_cli_n; i++) shutdown(g_cli_fds[i], SHUT_RDWR);
+    pthread_mutex_unlock(&g_cli_lock);
+    for (int tries = 0; tries < 100; tries++) {
+        pthread_mutex_lock(&g_cli_lock);
+        int left = g_cli_n;
+        pthread_mutex_unlock(&g_cli_lock);
+        if (left == 0) break;
+        struct timespec ts = { 0, 10000000L };
+        nanosleep(&ts, NULL);
+    }
+    unlink(g_sock_path);
 }
diff --git a/src/main.c b/src/main.c
index 384abd0..130ed26 100644
--- a/src/main.c
+++ b/src/main.c
@@ -4,6 +4,8 @@
  *
  * This program is free software under the terms of the GNU General
  * Public License version 2. See the LICENSE file for the full text.
+ *
+ * Modified-by: Claude Opus 5.5 (--version, g_no_input, socket path)
  */
 
 /*
@@ -55,6 +57,7 @@ int                     g_output_w = 0; /* extern'd by overlay.c */
 int                     g_output_h = 0;
 int                     g_output_fps = 30; /* extern'd by ipc.c (record) */
 Recorder               *g_recorder = NULL; /* extern'd by ipc.c */
+bool                    g_no_input = false; /* extern'd by api.c (status) */
 
 static void on_signal(int sig)
 {
@@ -129,6 +132,10 @@ int main(int argc, char *argv[])
                 dev = argv[i+1];
         }
         for (int i = 1; i < argc; i++) {
+            if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-V") == 0) {
+                puts(api_version_string());
+                return 0;
+            }
             if (strcmp(argv[i], "--list-formats") == 0 ||
                 strcmp(argv[i], "--list") == 0) {
                 return capture_list_formats(dev) ? 0 : 1;
@@ -231,6 +238,7 @@ int main(int argc, char *argv[])
 "  --res WxH         Output resolution  (e.g. --res 1280x720)\n"
 "  -f <fps>          Frame rate\n"
 "  --list-formats    List the resolutions the input device supports, then exit\n"
+"  --version, -V     Print version + build hash, then exit\n"
 "  --no-input        Don't open a webcam (use screen overlays as source).\n"
 "                    Combine with --res and a fullscreen --screen overlay.\n\n"
 "Startup overlays:\n"
@@ -249,6 +257,9 @@ int main(int argc, char *argv[])
 "  vcam-ctl filter add <name> [<param>]\n"
 "  vcam-ctl filter remove <index>\n"
 "  vcam-ctl filter list / clear\n"
+"  vcam-ctl status [--json] | get <key>\n"
+"  vcam-ctl share start|stop|toggle\n"
+"  vcam-ctl cam on|off|pos|move|size\n"
             );
             registry_destroy(&g_registry);
             filter_chain_destroy(&g_filters);
@@ -259,6 +270,8 @@ int main(int argc, char *argv[])
         }
     }
 
+    g_no_input = no_input;
+
     /* ── signals ── */
     signal(SIGINT,  on_signal);
     signal(SIGTERM, on_signal);
@@ -322,7 +335,7 @@ int main(int argc, char *argv[])
     fprintf(stderr, "[main] Pipeline: %s → %s  %dx%d @ %d fps\n",
             no_input ? "(no input)" : input_dev,
             output_dev, width, height, fps);
-    fprintf(stderr, "[main] IPC socket: %s\n", VCAM_SOCK_PATH);
+    fprintf(stderr, "[main] IPC socket: %s\n", ipc_sock_path());
     fprintf(stderr, "[main] %d startup overlay(s), %d startup filter(s).\n",
             g_registry.count, g_filters.count);
 
diff --git a/src/overlay.c b/src/overlay.c
index 36a2090..4096ada 100644
--- a/src/overlay.c
+++ b/src/overlay.c
@@ -4,6 +4,8 @@
  *
  * This program is free software under the terms of the GNU General
  * Public License version 2. See the LICENSE file for the full text.
+ *
+ * Modified-by: Claude Opus 5.5 (even-height rounding in webcam aspect fix-up)
  */
 
 #include "vcam.h"
@@ -700,6 +702,7 @@ void overlay_tick(Overlay *o, const Frame *webcam_src)
                  * the user gave just width — recompute dst from real src. */
                 int new_dst_w = o->dst_w;
                 int new_dst_h = (int)((long)new_dst_w * sh / sw);
+                if (new_dst_h & 1) new_dst_h++;   /* same rounding as resolve_dims [Claude Opus 5.5] */
                 if (new_dst_h != o->dst_h) {
                     free(o->pixels);
                     o->pixels = calloc(1, (size_t)new_dst_w * new_dst_h * 3);