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

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

Live camera mode switching via API (vcam 1.1.0)

Christian Immanuel · 2026-11-12 16:21 · 6dcf8161338ad9d9f6a53426b5561032627af93d

The camera's format, resolution and fps can now be changed while vcam
runs. The loopback output keeps its startup size (consumers depend on
it); the camera picture is scaled into it, center-cropped to keep the
aspect ratio (or stretched, fit=stretch).

API (also via vcam-ctl):
- capture [get]            current mode
- capture formats [json]   every mode the camera offers
- capture set [<fmt>] [<WxH>|max] [<fps>] [fit=crop|stretch]
- capture fit crop|stretch
- status/get: capture, capture_device, capture_fmt, capture_w,
  capture_h, capture_fps, capture_fit

How: api.c validates the request against the camera's mode list
(separate fd, safe while streaming); the main loop applies it between
two frames (close, open the new mode, reopen the old one on failure)
and signals the result back. Unset fields keep their current value;
explicit ones are never changed silently.

capture.c: capture_open split into capture_start + setup_scaling;
new capture_enum_modes / capture_choose / capture_open_mode /
capture_set_fit / capture_get. --list-formats mentions the live switch.
API.md, README and vcam-ctl help updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MZiVJi7adqtP79SuimnK7v
 API.md           |  80 ++++++++++++-
 Makefile         |   3 +-
 README.md        |  49 ++------
 include/vcam.h   |  40 ++++++-
 scripts/vcam-ctl |   9 +-
 src/api.c        | 144 +++++++++++++++++++++++-
 src/capture.c    | 334 +++++++++++++++++++++++++++++++++++++++++++++++++------
 src/ipc.c        |   3 +
 src/main.c       | 107 +++++++++++++++++-
 9 files changed, 680 insertions(+), 89 deletions(-)

diff --git a/API.md b/API.md
index 7a80985..6823ee3 100644
--- a/API.md
+++ b/API.md
@@ -15,6 +15,7 @@ Through the API a program can:
 
 - start / stop a **fullscreen screen share** (the screen replaces the camera image),
 - show the **webcam as a picture-in-picture** (PiP) and move / resize it,
+- **switch the camera** format, resolution and fps live,
 - **read the state**: is sharing on, where is the cam, is the cam over the screen.
 
 vcam must already be running. The API does not start it.
@@ -64,7 +65,8 @@ command. vcam answers `#` with `OK noop`. Read lines until you see
 
 Most commands answer in about a millisecond. `share start` takes around
 0.3 s (it starts the screen capture). `share stop` can take up to about
-1 s (it waits for the capture process to end). Use a read timeout of at
+1 s (it waits for the capture process to end). `capture set` takes
+0.2 to 1 s (the camera is re-opened). Use a read timeout of at
 least **3 s**.
 
 ## Coordinates
@@ -83,9 +85,9 @@ The whole state in one line.
 
 ```
 → status
-← OK version=1.0.1 build=abc1234 input=webcam output_w=1280 output_h=720 fps=30 share=yes … recording=no
+← OK version=1.1.0 build=abc1234 input=webcam output_w=1280 output_h=720 fps=30 share=yes … recording=no
 → status json
-← {"ok":true,"version":"1.0.1","build":"abc1234","input":"webcam","output_w":1280,…,"recording":false}
+← {"ok":true,"version":"1.1.0","build":"abc1234","input":"webcam","output_w":1280,…,"recording":false}
 ```
 
 Plain form: `key=value` pairs separated by spaces, with booleans as `yes` / `no`.
@@ -94,11 +96,17 @@ Values never contain spaces.
 
 | Key | Type | Meaning |
 |---|---|---|
-| `version` | string | vcam version, e.g. `1.0.1` |
+| `version` | string | vcam version, e.g. `1.1.0` |
 | `build` | string | md5 build hash (7 chars) |
 | `input` | string | `webcam`, or `none` if vcam was started with `--no-input` |
 | `output_w`, `output_h` | int | output frame size |
 | `fps` | int | output frame rate |
+| `capture` | bool | a camera is open and delivering |
+| `capture_device` | string | camera device, e.g. `/dev/video1`; `-` with `--no-input` |
+| `capture_fmt` | string | camera format, e.g. `MJPG`; `-` when off |
+| `capture_w`, `capture_h` | int | camera resolution (0 when off) |
+| `capture_fps` | int | camera frame rate (0 when off) |
+| `capture_fit` | string | `crop` or `stretch`; `-` when off |
 | `share` | bool | a screen overlay exists |
 | `share_id` | string | its overlay id (`share` when started via the API), `-` if none |
 | `share_fullscreen` | bool | the screen overlay covers the whole output |
@@ -139,7 +147,7 @@ One value from `status`, in plain form.
 ### `version`
 
 ```
-→ version   ← OK vcam 1.0.1 (build abc1234)
+→ version   ← OK vcam 1.1.0 (build abc1234)
 ```
 
 ### `monitors`
@@ -234,10 +242,67 @@ OK cam=off
 Errors: `ERR cam is off …` (from `move`, `size` and `raise`),
 `ERR unknown position (use tl|tr|bl|br|center|full)`, `ERR cam size too small`.
 
+### `capture …`: camera format, resolution and fps
+
+Switch the camera while vcam runs. The **output size never changes**:
+it is fixed at startup (`vcam --res WxH`), because apps reading the
+virtual camera depend on it. The camera picture is scaled to it.
+
+| Command | Effect |
+|---|---|
+| `capture` / `capture get` | current mode, no change |
+| `capture formats` | every mode, one line each: `OK <fmt> <WxH> <max fps>` (use the `#` marker) |
+| `capture formats json` | the same as one line: `{"ok":true,"formats":[{"fmt":"MJPG","w":1280,"h":720,"fps":30},…]}` |
+| `capture set [<fmt>] [<WxH>\|max] [<fps>] [fit=crop\|stretch]` | switch the camera live |
+| `capture fit crop\|stretch` | change only how the picture is fitted (no camera restart) |
+
+`capture set` takes its arguments in any order, and at least one is needed:
+
+| Argument | Values |
+|---|---|
+| `<fmt>` or `fmt=` | `MJPG` `YUYV` `NV12` `YU12` `BGR3` `RGB3` (any case, `MJPEG` also works), or `auto` = best for the size and fps |
+| `<WxH>` or `res=` | an exact size from `capture formats`, or `max` = the largest size that still reaches the fps |
+| `<fps>` or `fps=` | frame rate |
+| `fit=` | `crop` (default) keeps the aspect ratio and cuts the edges; `stretch` distorts instead |
+
+Rules:
+
+- A value you leave out keeps its current value, if the camera has that combination.
+  Otherwise vcam picks the best match for the values you did give.
+  A kept fps that the camera can't reach becomes the highest fps it can.
+- A value you give is **never** changed. If it's impossible, you get an error.
+
+Reply:
+
+```
+OK capture=on device=/dev/video1 fmt=YUYV w=640 h=480 fps=30 fit=crop output=1280x720
+```
+
+Examples, for a camera that offers YUYV 1280x720 at 10 fps max:
+
+```
+→ capture set YUYV 640x480 30   ← OK capture=on … fmt=YUYV w=640 h=480 fps=30 …
+→ capture set YUYV 1280x720 30  ← ERR YUYV 1280x720 supports at most 10 fps
+→ capture set YUYV              ← OK capture=on … fmt=YUYV w=1280 h=720 fps=10 …   (size kept)
+→ capture set 15                ← OK capture=on … fps=15 …                          (fps only)
+```
+
+Errors:
+
+- `ERR camera has no mode … (see 'capture formats')`
+- `ERR … supports at most N fps`
+- `ERR unknown format '…'`
+- `ERR camera refused …`: the camera rejected the mode; the **old mode is back**
+- `ERR vcam runs with --no-input (no camera)`
+
+A switch takes about 0.2 to 1 s, and the picture pauses briefly.
+A mode smaller than the output is upscaled, so it looks softer, but it
+needs less USB bandwidth and CPU.
+
 ## Behaviour to know
 
 - **State is not saved.** After a vcam restart there is no share and no cam,
-  and the margin is back to 0.
+  the margin is back to 0, and the camera uses the startup mode again.
 - **Other clients can change things** at any time (`vcam-ctl`, hotkeys,
   other apps). Don't cache state; read `status json` before deciding.
 - **`input=none`** (vcam started with `--no-input`): there is no camera,
@@ -344,6 +409,9 @@ read `share`, `cam` and `cam_over_screen`.
 
 **Corner hotkeys.** Bind `cam pos tl` / `tr` / `bl` / `br`.
 
+**Quality picker.** Fill a menu from `capture formats json`, then call
+`capture set <fmt> <WxH> <fps>` with the user's choice.
+
 **Wait for vcam.** Retry `connect()` every 0.5 s until it succeeds.
 
 **Share a single window or area.** Get its geometry from your compositor
diff --git a/Makefile b/Makefile
index 2391ec9..14bb48b 100644
--- a/Makefile
+++ b/Makefile
@@ -1,6 +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)
+# Modified-by: Claude Opus 5.5 (api.c, build hash, PREFIX=/usr, API.md install)
 
 CC      := gcc
 CXX     := g++
@@ -238,6 +238,7 @@ endif
 	install -m 644 README.md            $(DESTDIR)$(DOCDIR)/
 	install -m 644 INSTALL.md           $(DESTDIR)$(DOCDIR)/
 	install -m 644 EXPRESSIONS.md       $(DESTDIR)$(DOCDIR)/
+	install -m 644 API.md               $(DESTDIR)$(DOCDIR)/
 	@echo
 	@echo "Installed to $(DESTDIR)$(BINDIR)/  (docs in $(DESTDIR)$(DOCDIR)/)"
 	@echo "Make sure that's on your PATH."
diff --git a/README.md b/README.md
index 37a0eb3..1ae8a17 100644
--- a/README.md
+++ b/README.md
@@ -302,55 +302,22 @@ shown above. To drive all of this from another app, see
 
 ## 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`):
+Other programs control vcam over a Unix socket (`/tmp/vcam.sock`):
+start a fullscreen share, place the webcam PiP, switch the camera mode
+live, read the state.
 
 ```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 capture set MJPG 640x480 30   # switch camera live
+vcam-ctl status --json          # whole state as one JSON line
 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.
+**Full reference: [API.md](API.md).** It covers the protocol, every
+command and status key, and a ready-to-use Python client. To get a
+program written against the API, hand that file to a new chat.
 
 ---
 
diff --git a/include/vcam.h b/include/vcam.h
index 45e0433..29e5f10 100644
--- a/include/vcam.h
+++ b/include/vcam.h
@@ -337,11 +337,11 @@ const char *ipc_sock_path(void);   /* the path actually in use */
  * on the same socket: status, get, share, cam, monitors, version.
  * [Claude Opus 5.5]
  * ────────────────────────────────────────────── */
-#define VCAM_VERSION "1.0.0"
+#define VCAM_VERSION "1.1.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)" */
+const char *api_version_string(void);   /* "vcam 1.1.0 (build abc1234)" — see API.md */
 
 /* ──────────────────────────────────────────────
  * V4L2 capture
@@ -356,6 +356,42 @@ void         capture_close(V4L2Capture *cap);
  * device supports. Returns false if the device can't be opened. */
 bool         capture_list_formats(const char *dev);
 
+/* ── live mode switching [Claude Opus 5.5] ── */
+typedef struct {
+    char fmt[8];      /* fourcc: "MJPG", "YUYV", ... */
+    int  w, h;
+    int  fps;         /* max fps when enumerated, actual fps when open */
+} CaptureMode;
+
+/* All usable modes (opens the device separately; safe while streaming).
+ * Returns the count, or -1 if the device can't be opened. */
+int          capture_enum_modes(const char *dev, CaptureMode *out, int max);
+/* Resolve a request against modes[]. Unset fields (fmt NULL/"", w/h 0,
+ * fps 0) keep *cur when possible; fmt "auto" = best, w = -1 = largest. */
+bool         capture_choose(const CaptureMode *modes, int n,
+                            const char *fmt, int w, int h, int fps,
+                            const CaptureMode *cur, int default_fps,
+                            CaptureMode *out, char *err, size_t errlen);
+/* Open in an exact mode; frames are scaled to out_w × out_h (crop keeps
+ * the aspect ratio by cutting the edges, otherwise stretch). */
+V4L2Capture *capture_open_mode(const char *dev, const CaptureMode *mode,
+                               int out_w, int out_h, bool crop);
+bool         capture_set_fit (V4L2Capture *cap, bool crop);
+void         capture_get     (const V4L2Capture *cap, CaptureMode *mode, bool *crop);
+
+/* Owned by main.c: the main loop applies requests between two frames. */
+typedef struct {
+    bool        active;    /* a camera is open */
+    CaptureMode mode;
+    bool        crop;
+} CaptureState;
+
+const char *capture_device_path(void);
+void        capture_state_get(CaptureState *st);
+/* mode NULL = keep mode (fit change only); fit -1 keep, 0 stretch, 1 crop.
+ * Blocks until applied (≤ 6 s). On failure the old mode is restored. */
+bool        capture_request(const CaptureMode *mode, int fit, char *err, size_t errlen);
+
 /* ──────────────────────────────────────────────
  * V4L2 loopback output
  * ────────────────────────────────────────────── */
diff --git a/scripts/vcam-ctl b/scripts/vcam-ctl
index 310f14b..26d4c6c 100755
--- a/scripts/vcam-ctl
+++ b/scripts/vcam-ctl
@@ -92,7 +92,14 @@
 #   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".
+#   capture [get] | formats      Current camera mode / every mode it offers.
+#   capture set [<fmt>] [<WxH>|max] [<fps>] [fit=crop|stretch]
+#                                Switch the camera live, e.g. 'capture set MJPG 640x480 30'.
+#                                The output size stays; the picture is scaled to it.
+#   capture fit crop|stretch     How a different aspect ratio is fitted (default crop).
 #   version                      vcam version + build hash.
+#   Full API reference (protocol, all keys, client examples):
+#     API.md — installed to /usr/share/doc/vcam/API.md
 #
 # Recording (capture the vcam output to a file):
 #   record start [-o <file>] [-m <alsa-dev>] [--no-audio] [--crf N]
@@ -752,7 +759,7 @@ fi
 # directly usable in scripts; exits 1 if vcam answered ERR.
 # ──────────────────────────────────────────────────────────────
 case "$1" in
-    status|get|share|cam|monitors|version)
+    status|get|share|cam|capture|monitors|version)
         require_running
         if [ "$1" = "status" ] && { [ "${2:-}" = "--json" ] || [ "${2:-}" = "json" ]; }; then
             ipc_send "status json" | head -n 1
diff --git a/src/api.c b/src/api.c
index 2103076..38583dd 100644
--- a/src/api.c
+++ b/src/api.c
@@ -5,7 +5,7 @@
  * 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)
+ * Created-by: Claude Opus 5.5 (control API, live capture switching)
  */
 
 /*
@@ -14,7 +14,7 @@
  *
  *   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)"
+ *   version                    "OK vcam 1.1.0 (build abc1234)"  — full reference: API.md
  *   monitors                   one line per monitor: "OK <n> <name> WxH+X+Y"
  *
  *   share start [<n>|<name>|<WxH+X+Y>] [fit=stretch|contain]
@@ -28,6 +28,12 @@
  *   cam size <w> [<h>]         keeps its anchor; h derived from aspect
  *   cam margin <px>            gap between cam and the output edge
  *
+ *   capture [get]              current camera mode
+ *   capture formats [json]     every mode the camera offers
+ *   capture set [<fmt>] [<WxH>|max] [<fps>] [fit=crop|stretch]
+ *                              switch the camera live (output size stays)
+ *   capture fit crop|stretch   how a different aspect ratio is fitted
+ *
  * 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.
@@ -406,7 +412,7 @@ static int cam_h_for(int w)
  * 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
+#define MAX_KV 48
 
 static int kv_add(KV *kv, int n, const char *k, char t, const char *fmt, ...)
 {
@@ -437,6 +443,15 @@ static int build_status(OverlayRegistry *reg, KV *kv)
     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);
+    CaptureState cs; memset(&cs, 0, sizeof cs);
+    if (!g_no_input) capture_state_get(&cs);
+    n = kv_add(kv, n, "capture",          'b', "%d", cs.active);
+    n = kv_add(kv, n, "capture_device",   's', "%s", g_no_input ? "-" : capture_device_path());
+    n = kv_add(kv, n, "capture_fmt",      's', "%s", cs.active ? cs.mode.fmt : "-");
+    n = kv_add(kv, n, "capture_w",        'i', "%d", cs.active ? cs.mode.w : 0);
+    n = kv_add(kv, n, "capture_h",        'i', "%d", cs.active ? cs.mode.h : 0);
+    n = kv_add(kv, n, "capture_fps",      'i', "%d", cs.active ? cs.mode.fps : 0);
+    n = kv_add(kv, n, "capture_fit",      's', "%s", cs.active ? (cs.crop ? "crop" : "stretch") : "-");
     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);
@@ -714,6 +729,128 @@ static bool share_handle(int fd, char **save, OverlayRegistry *reg)
     return true;
 }
 
+/* ══════════════════════════════════════════════════════════════
+ * capture — live camera mode (format / resolution / fps)
+ * ══════════════════════════════════════════════════════════════ */
+#define MAX_MODES 128
+
+static void capture_reply(int fd)
+{
+    CaptureState cs;
+    capture_state_get(&cs);
+    if (!cs.active) {
+        reply(fd, "OK capture=off device=%s", capture_device_path());
+        return;
+    }
+    reply(fd, "OK capture=on device=%s fmt=%s w=%d h=%d fps=%d fit=%s output=%dx%d",
+          capture_device_path(), cs.mode.fmt, cs.mode.w, cs.mode.h, cs.mode.fps,
+          cs.crop ? "crop" : "stretch", g_output_w, g_output_h);
+}
+
+static int parse_fit(const char *v)
+{
+    if (!strcmp(v, "crop"))    return 1;
+    if (!strcmp(v, "stretch")) return 0;
+    return -2;
+}
+
+static bool capture_handle(int fd, char **save)
+{
+    char *sub = strtok_r(NULL, " \t", save);
+    char err[192] = "";
+
+    if (g_no_input && sub && strcmp(sub, "get") != 0) {
+        reply(fd, "ERR vcam runs with --no-input (no camera)");
+        return true;
+    }
+    if (!sub || !strcmp(sub, "get") || !strcmp(sub, "status")) {
+        if (g_no_input) reply(fd, "OK capture=off device=-");
+        else            capture_reply(fd);
+        return true;
+    }
+
+    if (!strcmp(sub, "formats") || !strcmp(sub, "modes")) {
+        char *a = strtok_r(NULL, " \t", save);
+        bool json = a && (!strcmp(a, "json") || !strcmp(a, "--json"));
+        CaptureMode m[MAX_MODES];
+        int n = capture_enum_modes(capture_device_path(), m, MAX_MODES);
+        if (n < 0) { reply(fd, "ERR cannot open %s", capture_device_path()); return true; }
+        if (!json) {
+            if (n == 0) { reply(fd, "ERR camera reports no usable modes"); return true; }
+            for (int i = 0; i < n; i++)
+                reply(fd, "OK %s %dx%d %d", m[i].fmt, m[i].w, m[i].h, m[i].fps);
+            return true;
+        }
+        char buf[3584]; size_t off = 0;
+        off += (size_t)snprintf(buf, sizeof buf, "{\"ok\":true,\"formats\":[");
+        for (int i = 0; i < n && off < sizeof buf; i++)
+            off += (size_t)snprintf(buf + off, sizeof buf - off,
+                                    "%s{\"fmt\":\"%s\",\"w\":%d,\"h\":%d,\"fps\":%d}",
+                                    i ? "," : "", m[i].fmt, m[i].w, m[i].h, m[i].fps);
+        if (off < sizeof buf) snprintf(buf + off, sizeof buf - off, "]}");
+        reply(fd, "%s", buf);
+        return true;
+    }
+
+    if (!strcmp(sub, "fit")) {
+        char *v = strtok_r(NULL, " \t", save);
+        int fit = v ? parse_fit(v) : -2;
+        if (fit < 0) { reply(fd, "ERR usage: capture fit crop|stretch"); return true; }
+        if (!capture_request(NULL, fit, err, sizeof err)) { reply(fd, "ERR %s", err); return true; }
+        capture_reply(fd);
+        return true;
+    }
+
+    if (!strcmp(sub, "set")) {
+        const char *fmt = NULL;
+        int w = 0, h = 0, fps = 0, fit = -1;
+        char *t;
+        while ((t = strtok_r(NULL, " \t", save))) {
+            const char *v = t;
+            if      (!strncmp(t, "fmt=", 4)) { fmt = t + 4; continue; }
+            else if (!strncmp(t, "fps=", 4)) { fps = atoi(t + 4); if (fps <= 0) goto bad; continue; }
+            else if (!strncmp(t, "fit=", 4)) { fit = parse_fit(t + 4); if (fit < 0) goto bad; continue; }
+            else if (!strncmp(t, "res=", 4)) v = t + 4;
+            char tail;
+            if (!strcmp(v, "max"))                                   { w = h = -1; continue; }
+            if (sscanf(v, "%dx%d%c", &w, &h, &tail) == 2 && w > 0 && h > 0) continue;
+            if (v == t && strspn(t, "0123456789") == strlen(t))      { fps = atoi(t); if (fps <= 0) goto bad; continue; }
+            if (v == t)                                              { fmt = t; continue; }
+        bad:
+            reply(fd, "ERR bad argument '%s' (capture set [<fmt>] [<WxH>|max] [<fps>] [fit=crop|stretch])", t);
+            return true;
+        }
+        if (!fmt && !w && !fps && fit < 0) {
+            reply(fd, "ERR usage: capture set [<fmt>] [<WxH>|max] [<fps>] [fit=crop|stretch]");
+            return true;
+        }
+
+        CaptureState cs;
+        capture_state_get(&cs);
+        CaptureMode chosen;
+        if (fmt || w || fps) {
+            CaptureMode m[MAX_MODES];
+            int n = capture_enum_modes(capture_device_path(), m, MAX_MODES);
+            if (n <= 0) { reply(fd, "ERR cannot read camera modes from %s", capture_device_path()); return true; }
+            if (!capture_choose(m, n, fmt, w, h, fps, cs.active ? &cs.mode : NULL,
+                                g_output_fps, &chosen, err, sizeof err)) {
+                reply(fd, "ERR %s", err);
+                return true;
+            }
+        }
+        bool reopen = fmt || w || fps;
+        if (!capture_request(reopen ? &chosen : NULL, fit, err, sizeof err)) {
+            reply(fd, "ERR %s", err);
+            return true;
+        }
+        capture_reply(fd);
+        return true;
+    }
+
+    reply(fd, "ERR capture: unknown subcommand (get|formats|set|fit)");
+    return true;
+}
+
 /* ══════════════════════════════════════════════════════════════
  * entry point — returns true if the command was handled here
  * ══════════════════════════════════════════════════════════════ */
@@ -728,6 +865,7 @@ bool api_handle(int fd, const char *cmd, char **save, OverlayRegistry *reg)
     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, "capture")) return capture_handle(fd, save);
     if (!strcmp(cmd, "monitors")) {
         Monitor m[MAX_MON];
         int n = detect_monitors(m, MAX_MON);
diff --git a/src/capture.c b/src/capture.c
index 967b1a3..5a81bc9 100644
--- a/src/capture.c
+++ b/src/capture.c
@@ -4,6 +4,9 @@
  *
  * 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 (live mode switching: enum/choose/open_mode,
+ *              scale+crop into a fixed output size)
  */
 
 #include "vcam.h"
@@ -16,6 +19,7 @@
 #include <errno.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
+#include <strings.h>
 #include <linux/videodev2.h>
 
 #include <libavcodec/avcodec.h>
@@ -46,8 +50,20 @@ struct V4L2Capture {
     struct SwsContext *sws;
     int    sws_src_fmt;       /* AV_PIX_FMT_* */
     int    sws_src_w, sws_src_h; /* may differ from cap->width when MJPEG */
+
+    /* Output geometry: frames are scaled to out_w × out_h (the fixed
+     * loopback size). With crop, a different aspect ratio is scaled to
+     * cover (scale_w × scale_h into tmp) and the centre is cut out. */
+    int    out_w, out_h;
+    bool   crop;
+    int    scale_w, scale_h;
+    int    crop_x, crop_y;
+    Frame *tmp;               /* only when cropping is needed */
 };
 
+static bool capture_start(V4L2Capture *cap, const char *device,
+                          __u32 fmt, int w, int h, int target_fps);
+
 /* ── helpers ─────────────────────────────────── */
 static int xioctl(int fd, unsigned long req, void *arg)
 {
@@ -58,7 +74,7 @@ static int xioctl(int fd, unsigned long req, void *arg)
 
 static const char *fourcc(__u32 f)
 {
-    static char s[5];
+    static _Thread_local char s[5];   /* used from main + IPC threads */
     s[0]= f      & 0xff;
     s[1]=(f>> 8) & 0xff;
     s[2]=(f>>16) & 0xff;
@@ -161,6 +177,158 @@ static bool pick_format(int fd, int req_w, int req_h, int target_fps,
     return true;
 }
 
+/* ── formats vcam can consume, in preference order ── */
+static const __u32 g_usable[] = {
+    V4L2_PIX_FMT_MJPEG, V4L2_PIX_FMT_YUYV, V4L2_PIX_FMT_NV12,
+    V4L2_PIX_FMT_YUV420, V4L2_PIX_FMT_BGR24, V4L2_PIX_FMT_RGB24,
+};
+#define N_USABLE ((int)(sizeof g_usable / sizeof g_usable[0]))
+
+static int usable_rank(__u32 f)
+{
+    for (int i = 0; i < N_USABLE; i++) if (g_usable[i] == f) return i;
+    return -1;
+}
+
+/* Name → fourcc. Accepts the fourcc itself plus common aliases. */
+static bool fourcc_from_name(const char *n, __u32 *out)
+{
+    static const struct { const char *name; __u32 f; } names[] = {
+        { "MJPG", V4L2_PIX_FMT_MJPEG }, { "MJPEG", V4L2_PIX_FMT_MJPEG },
+        { "YUYV", V4L2_PIX_FMT_YUYV },  { "NV12",  V4L2_PIX_FMT_NV12 },
+        { "YU12", V4L2_PIX_FMT_YUV420 },{ "YUV420",V4L2_PIX_FMT_YUV420 },
+        { "I420", V4L2_PIX_FMT_YUV420 },{ "BGR3",  V4L2_PIX_FMT_BGR24 },
+        { "BGR24",V4L2_PIX_FMT_BGR24 }, { "RGB3",  V4L2_PIX_FMT_RGB24 },
+        { "RGB24",V4L2_PIX_FMT_RGB24 },
+    };
+    for (size_t i = 0; i < sizeof names / sizeof names[0]; i++)
+        if (strcasecmp(n, names[i].name) == 0) { *out = names[i].f; return true; }
+    return false;
+}
+
+/* Highest frame rate the device offers for (fmt, w, h); 0 if unknown. */
+static int max_fps_for(int fd, __u32 pixfmt, int w, int h)
+{
+    int best = 0;
+    struct v4l2_frmivalenum fi = {0};
+    fi.pixel_format = pixfmt;
+    fi.width = w; fi.height = h;
+    for (fi.index = 0; xioctl(fd, VIDIOC_ENUM_FRAMEINTERVALS, &fi) == 0; fi.index++) {
+        struct v4l2_fract *f = fi.type == V4L2_FRMIVAL_TYPE_DISCRETE
+                             ? &fi.discrete : &fi.stepwise.min;
+        int fps = f->denominator / (f->numerator ? f->numerator : 1);
+        if (fps > best) best = fps;
+        if (fi.type != V4L2_FRMIVAL_TYPE_DISCRETE) break;
+    }
+    return best;
+}
+
+static int enum_modes_fd(int fd, CaptureMode *out, int max)
+{
+    int n = 0;
+    struct v4l2_fmtdesc fd_desc = {0};
+    fd_desc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
+    for (fd_desc.index = 0; xioctl(fd, VIDIOC_ENUM_FMT, &fd_desc) == 0; fd_desc.index++) {
+        if (usable_rank(fd_desc.pixelformat) < 0) continue;
+        struct v4l2_frmsizeenum fs = {0};
+        fs.pixel_format = fd_desc.pixelformat;
+        for (fs.index = 0; xioctl(fd, VIDIOC_ENUM_FRAMESIZES, &fs) == 0 && n < max; fs.index++) {
+            if (fs.type != V4L2_FRMSIZE_TYPE_DISCRETE) continue;
+            CaptureMode *m = &out[n++];
+            snprintf(m->fmt, sizeof m->fmt, "%s", fourcc(fd_desc.pixelformat));
+            m->w   = (int)fs.discrete.width;
+            m->h   = (int)fs.discrete.height;
+            m->fps = max_fps_for(fd, fd_desc.pixelformat, m->w, m->h);
+        }
+    }
+    return n;
+}
+
+int capture_enum_modes(const char *device, CaptureMode *out, int max)
+{
+    int fd = open(device, O_RDWR | O_NONBLOCK, 0);
+    if (fd < 0) return -1;
+    int n = enum_modes_fd(fd, out, max);
+    close(fd);
+    return n;
+}
+
+/*
+ * Pick a mode. fmt / w,h / fps may each be "unset" (NULL or "", 0):
+ * unset fields keep the current mode's value when the camera allows it.
+ * fmt "auto" = best format; w,h = -1 = largest size.
+ * Explicit values are never changed silently: if they can't be met → error.
+ */
+bool capture_choose(const CaptureMode *modes, int n,
+                    const char *fmt, int w, int h, int fps,
+                    const CaptureMode *cur, int default_fps,
+                    CaptureMode *out, char *err, size_t errlen)
+{
+    char want_fmt[8] = "";
+    bool fmt_explicit = false;
+    if (fmt && *fmt && strcasecmp(fmt, "auto") != 0) {
+        __u32 f;
+        if (!fourcc_from_name(fmt, &f)) {
+            snprintf(err, errlen, "unknown format '%s' (MJPG, YUYV, NV12, YU12, BGR3, RGB3, auto)", fmt);
+            return false;
+        }
+        snprintf(want_fmt, sizeof want_fmt, "%s", fourcc(f));
+        fmt_explicit = true;
+    } else if (!fmt || !*fmt) {
+        if (cur && cur->fmt[0]) snprintf(want_fmt, sizeof want_fmt, "%s", cur->fmt);
+    }
+    bool size_explicit = w > 0 && h > 0;
+    bool size_max      = w < 0;
+    int  want_w = size_explicit ? w : (!size_max && cur ? cur->w : 0);
+    int  want_h = size_explicit ? h : (!size_max && cur ? cur->h : 0);
+    int  target = fps > 0 ? fps : (cur && cur->fps > 0 ? cur->fps : default_fps);
+    if (target <= 0) target = 30;
+
+    /* Attempts, in order: as asked → any size → any format → both.
+     * A field the caller set explicitly is never dropped. */
+    static const bool keep[4][2] = { {1,1}, {1,0}, {0,1}, {0,0} };   /* {fmt, size} */
+    for (int a = 0; a < 4; a++) {
+        if (!keep[a][0] && fmt_explicit)  continue;
+        if (!keep[a][1] && size_explicit) continue;
+        const char *ff = keep[a][0] ? want_fmt : "";
+        int fw = keep[a][1] ? want_w : 0, fh = keep[a][1] ? want_h : 0;
+
+        const CaptureMode *best = NULL;
+        int best_eff = -1; long best_area = -1; int best_rank = 99;
+        for (int i = 0; i < n; i++) {
+            const CaptureMode *m = &modes[i];
+            if (ff[0] && strcmp(m->fmt, ff) != 0) continue;
+            if (fw > 0 && (m->w != fw || m->h != fh)) continue;
+            int  eff  = m->fps <= 0 ? target : (m->fps < target ? m->fps : target);
+            long area = fw > 0 ? 0 : (long)m->w * m->h;
+            __u32 f = 0; fourcc_from_name(m->fmt, &f);
+            int  rank = usable_rank(f);
+            if (eff > best_eff ||
+                (eff == best_eff && area > best_area) ||
+                (eff == best_eff && area == best_area && rank < best_rank)) {
+                best = m; best_eff = eff; best_area = area; best_rank = rank;
+            }
+        }
+        if (!best) continue;
+        if (fps > 0 && best->fps > 0 && best->fps < fps) {
+            snprintf(err, errlen, "%s %dx%d supports at most %d fps",
+                     best->fmt, best->w, best->h, best->fps);
+            return false;
+        }
+        *out = *best;
+        out->fps = best_eff;
+        return true;
+    }
+    if (!fmt_explicit) want_fmt[0] = '\0';   /* every format was tried */
+    if (size_explicit)
+        snprintf(err, errlen, "camera has no mode %s%s%dx%d (see 'capture formats')",
+                 want_fmt, want_fmt[0] ? " " : "", w, h);
+    else
+        snprintf(err, errlen, "camera has no %s mode (see 'capture formats')",
+                 want_fmt[0] ? want_fmt : "usable");
+    return false;
+}
+
 /* ── list supported formats ───────────────────────
  * Opens the device, enumerates every (pixel format, resolution, fps)
  * combination the driver reports, and prints a human-readable table
@@ -238,6 +406,7 @@ bool capture_list_formats(const char *device)
         printf("  (no usable discrete formats reported)\n");
 
     printf("\nPick one with:  vcam --res WxH [-f FPS]\n");
+    printf("Live switch:    vcam-ctl capture set <FMT> <WxH> [FPS]   (output size stays)\n");
     close(fd);
     return true;
 }
@@ -276,6 +445,109 @@ V4L2Capture *capture_open(const char *device,
         chosen_h   = gf.fmt.pix.height;
     }
 
+    cap->crop = true;   /* only matters once out size ≠ capture size */
+    if (!capture_start(cap, device, chosen_fmt, chosen_w, chosen_h, target_fps))
+        goto err;
+
+    *out_width  = cap->width;
+    *out_height = cap->height;
+    *out_fps    = cap->fps;
+    return cap;
+
+err:
+    capture_close(cap);
+    return NULL;
+}
+
+/* Open the device in an exact mode, scaling frames to out_w × out_h. */
+V4L2Capture *capture_open_mode(const char *device, const CaptureMode *mode,
+                               int out_w, int out_h, bool crop)
+{
+    __u32 f;
+    if (!fourcc_from_name(mode->fmt, &f)) return NULL;
+    V4L2Capture *cap = calloc(1, sizeof *cap);
+    if (!cap) return NULL;
+    cap->fd = open(device, O_RDWR | O_NONBLOCK);
+    if (cap->fd < 0) {
+        perror("capture_open_mode: open");
+        free(cap);
+        return NULL;
+    }
+    cap->out_w = out_w;
+    cap->out_h = out_h;
+    cap->crop  = crop;
+    if (!capture_start(cap, device, f, mode->w, mode->h, mode->fps > 0 ? mode->fps : 30)) {
+        capture_close(cap);
+        return NULL;
+    }
+    return cap;
+}
+
+/*
+ * Scaling geometry for capture → output. Rebuilds the swscale context
+ * (MJPEG: lazily on the next decoded frame) and the crop buffer.
+ */
+static bool setup_scaling(V4L2Capture *cap)
+{
+    if (cap->out_w <= 0 || cap->out_h <= 0) {
+        cap->out_w = cap->width;
+        cap->out_h = cap->height;
+    }
+    frame_free(cap->tmp);
+    cap->tmp = NULL;
+    int sw = cap->width, sh = cap->height, ow = cap->out_w, oh = cap->out_h;
+    cap->scale_w = ow; cap->scale_h = oh;
+    cap->crop_x  = cap->crop_y = 0;
+    if (cap->crop && (long)sw * oh != (long)sh * ow) {
+        if ((long)sw * oh > (long)sh * ow) {          /* source wider: cut sides */
+            cap->scale_w = (int)(((long)sw * oh + sh - 1) / sh);
+        } else {                                      /* source taller: cut top/bottom */
+            cap->scale_h = (int)(((long)sh * ow + sw - 1) / sw);
+        }
+        cap->crop_x = (cap->scale_w - ow) / 2;
+        cap->crop_y = (cap->scale_h - oh) / 2;
+        cap->tmp = frame_alloc(cap->scale_w, cap->scale_h);
+        if (!cap->tmp) return false;
+    }
+    if (cap->sws) { sws_freeContext(cap->sws); cap->sws = NULL; }
+    if (cap->pixfmt != V4L2_PIX_FMT_MJPEG) {
+        cap->sws = sws_getContext(sw, sh, cap->sws_src_fmt,
+                                  cap->scale_w, cap->scale_h, AV_PIX_FMT_BGR24,
+                                  SWS_BILINEAR, NULL, NULL, NULL);
+        if (!cap->sws) return false;
+    }
+    return true;
+}
+
+bool capture_set_fit(V4L2Capture *cap, bool crop)
+{
+    cap->crop = crop;
+    return setup_scaling(cap);
+}
+
+void capture_get(const V4L2Capture *cap, CaptureMode *mode, bool *crop)
+{
+    snprintf(mode->fmt, sizeof mode->fmt, "%s", fourcc(cap->pixfmt));
+    mode->w   = cap->width;
+    mode->h   = cap->height;
+    mode->fps = cap->fps;
+    if (crop) *crop = cap->crop;
+}
+
+/* Copy the centre of the oversized tmp frame into out. */
+static void crop_into(const V4L2Capture *cap, Frame *out)
+{
+    const Frame *t = cap->tmp;
+    for (int y = 0; y < cap->out_h; y++)
+        memcpy(out->data + (size_t)y * out->stride,
+               t->data + (size_t)(y + cap->crop_y) * t->stride + (size_t)cap->crop_x * 3,
+               (size_t)cap->out_w * 3);
+}
+
+/* S_FMT, frame rate, buffers, STREAMON, decoder + scaler. */
+static bool capture_start(V4L2Capture *cap, const char *device,
+                          __u32 chosen_fmt, int chosen_w, int chosen_h, int target_fps)
+{
     /* ── apply the chosen format ── */
     struct v4l2_format fmt = {0};
     fmt.type                = V4L2_BUF_TYPE_VIDEO_CAPTURE;
@@ -285,7 +557,7 @@ V4L2Capture *capture_open(const char *device,
     fmt.fmt.pix.field       = V4L2_FIELD_NONE;
     if (xioctl(cap->fd, VIDIOC_S_FMT, &fmt) < 0) {
         perror("VIDIOC_S_FMT");
-        goto err;
+        return false;
     }
 
     cap->width  = fmt.fmt.pix.width;
@@ -315,7 +587,7 @@ V4L2Capture *capture_open(const char *device,
     req.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE;
     req.memory = V4L2_MEMORY_MMAP;
     if (xioctl(cap->fd, VIDIOC_REQBUFS, &req) < 0) {
-        perror("VIDIOC_REQBUFS"); goto err;
+        perror("VIDIOC_REQBUFS"); return false;
     }
     cap->nbuf = req.count;
 
@@ -325,14 +597,14 @@ V4L2Capture *capture_open(const char *device,
         buf.memory = V4L2_MEMORY_MMAP;
         buf.index  = i;
         if (xioctl(cap->fd, VIDIOC_QUERYBUF, &buf) < 0) {
-            perror("VIDIOC_QUERYBUF"); goto err;
+            perror("VIDIOC_QUERYBUF"); return false;
         }
         cap->bufs[i].length = buf.length;
         cap->bufs[i].start  = mmap(NULL, buf.length,
                                     PROT_READ | PROT_WRITE, MAP_SHARED,
                                     cap->fd, buf.m.offset);
         if (cap->bufs[i].start == MAP_FAILED) {
-            perror("mmap"); goto err;
+            perror("mmap"); return false;
         }
     }
 
@@ -342,25 +614,25 @@ V4L2Capture *capture_open(const char *device,
         buf.memory = V4L2_MEMORY_MMAP;
         buf.index  = i;
         if (xioctl(cap->fd, VIDIOC_QBUF, &buf) < 0) {
-            perror("VIDIOC_QBUF"); goto err;
+            perror("VIDIOC_QBUF"); return false;
         }
     }
 
     enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
     if (xioctl(cap->fd, VIDIOC_STREAMON, &type) < 0) {
-        perror("VIDIOC_STREAMON"); goto err;
+        perror("VIDIOC_STREAMON"); return false;
     }
 
     /* ── set up MJPEG decoder if needed ── */
     if (cap->pixfmt == V4L2_PIX_FMT_MJPEG) {
         const AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_MJPEG);
-        if (!codec) { fprintf(stderr, "[capture] no MJPEG decoder\n"); goto err; }
+        if (!codec) { fprintf(stderr, "[capture] no MJPEG decoder\n"); return false; }
         cap->mjpeg_ctx = avcodec_alloc_context3(codec);
         cap->mjpeg_ctx->width  = cap->width;
         cap->mjpeg_ctx->height = cap->height;
         if (avcodec_open2(cap->mjpeg_ctx, codec, NULL) < 0) {
             fprintf(stderr, "[capture] avcodec_open2 (MJPEG) failed\n");
-            goto err;
+            return false;
         }
         cap->mjpeg_pkt   = av_packet_alloc();
         cap->mjpeg_frame = av_frame_alloc();
@@ -378,26 +650,13 @@ V4L2Capture *capture_open(const char *device,
         case V4L2_PIX_FMT_RGB24:  avfmt = AV_PIX_FMT_RGB24;   break;
         default:
             fprintf(stderr, "[capture] unsupported format %s\n", fourcc(cap->pixfmt));
-            goto err;
+            return false;
         }
         cap->sws_src_fmt = avfmt;
         cap->sws_src_w   = cap->width;
         cap->sws_src_h   = cap->height;
-        cap->sws = sws_getContext(cap->width, cap->height, avfmt,
-                                   cap->width, cap->height, AV_PIX_FMT_BGR24,
-                                   SWS_BILINEAR, NULL, NULL, NULL);
-        if (!cap->sws) goto err;
     }
-
-    *out_width  = cap->width;
-    *out_height = cap->height;
-    *out_fps    = cap->fps;
-    return cap;
-
-err:
-    if (cap->fd >= 0) close(cap->fd);
-    free(cap);
-    return NULL;
+    return setup_scaling(cap);   /* builds the BGR24 scaler for out size */
 }
 
 /* ── read one frame ───────────────────────────── */
@@ -439,29 +698,35 @@ bool capture_read(V4L2Capture *cap, Frame *out)
                 cap->sws_src_h   != src_h) {
                 if (cap->sws) sws_freeContext(cap->sws);
                 cap->sws = sws_getContext(src_w, src_h, src_fmt,
-                                           cap->width, cap->height, AV_PIX_FMT_BGR24,
+                                           cap->scale_w, cap->scale_h, AV_PIX_FMT_BGR24,
                                            SWS_BILINEAR, NULL, NULL, NULL);
                 cap->sws_src_fmt = src_fmt;
                 cap->sws_src_w   = src_w;
                 cap->sws_src_h   = src_h;
             }
 
-            uint8_t *dst[4]  = { out->data, NULL, NULL, NULL };
-            int      dl[4]   = { out->stride, 0, 0, 0 };
-            sws_scale(cap->sws,
-                      (const uint8_t *const *)cap->mjpeg_frame->data,
-                      cap->mjpeg_frame->linesize, 0, src_h, dst, dl);
-            ok = true;
+            Frame   *target  = cap->tmp ? cap->tmp : out;
+            uint8_t *dst[4]  = { target->data, NULL, NULL, NULL };
+            int      dl[4]   = { target->stride, 0, 0, 0 };
+            if (cap->sws) {
+                sws_scale(cap->sws,
+                          (const uint8_t *const *)cap->mjpeg_frame->data,
+                          cap->mjpeg_frame->linesize, 0, src_h, dst, dl);
+                if (cap->tmp) crop_into(cap, out);
+                ok = true;
+            }
         }
     } else {
         const uint8_t *src[4]   = { cap->bufs[buf.index].start, NULL, NULL, NULL };
         int            sl[4]    = { 0 };
         av_image_fill_linesizes(sl, cap->sws_src_fmt, cap->width);
 
-        uint8_t       *dst[4]   = { out->data, NULL, NULL, NULL };
-        int            dl[4]    = { out->stride, 0, 0, 0 };
+        Frame         *target   = cap->tmp ? cap->tmp : out;
+        uint8_t       *dst[4]   = { target->data, NULL, NULL, NULL };
+        int            dl[4]    = { target->stride, 0, 0, 0 };
 
         sws_scale(cap->sws, src, sl, 0, cap->height, dst, dl);
+        if (cap->tmp) crop_into(cap, out);
         ok = true;
     }
 
@@ -483,6 +748,7 @@ void capture_close(V4L2Capture *cap)
     if (cap->mjpeg_ctx)   avcodec_free_context(&cap->mjpeg_ctx);
     if (cap->mjpeg_pkt)   av_packet_free(&cap->mjpeg_pkt);
     if (cap->mjpeg_frame) av_frame_free(&cap->mjpeg_frame);
-    close(cap->fd);
+    frame_free(cap->tmp);
+    if (cap->fd >= 0) close(cap->fd);
     free(cap);
 }
diff --git a/src/ipc.c b/src/ipc.c
index 4ead4bf..b6ae8d1 100644
--- a/src/ipc.c
+++ b/src/ipc.c
@@ -848,6 +848,9 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
         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   capture [get] | formats [json]       camera mode / modes the camera offers");
+        send_line(client_fd, "OK   capture set [<fmt>] [<WxH>|max] [<fps>] [fit=crop|stretch]   switch camera live");
+        send_line(client_fd, "OK   capture fit crop|stretch             fit a different aspect ratio");
         send_line(client_fd, "OK   version                              vcam version + build hash");
         send_line(client_fd, "OK   quit                                 close the connection");
         return;
diff --git a/src/main.c b/src/main.c
index 130ed26..9e9bdce 100644
--- a/src/main.c
+++ b/src/main.c
@@ -5,7 +5,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)
+ * Modified-by: Claude Opus 5.5 (--version, g_no_input, socket path,
+ *              live capture mode switching)
  */
 
 /*
@@ -59,6 +60,105 @@ 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) */
 
+/* ── live capture switching ───────────────────── [Claude Opus 5.5]
+ * api.c validates a request and posts it with capture_request(); the
+ * main loop applies it between two frames (close → open new mode →
+ * reopen the old one if that fails) and signals the result back.
+ */
+static const char     *g_input_dev = "/dev/video1";
+static pthread_mutex_t g_cap_lock  = PTHREAD_MUTEX_INITIALIZER;
+static pthread_cond_t  g_cap_cond  = PTHREAD_COND_INITIALIZER;
+static CaptureState    g_cap_state;            /* current; guarded by g_cap_lock */
+static CaptureMode     g_req_mode;
+static bool            g_req_reopen;
+static int             g_req_fit = -1;
+static unsigned        g_req_seq, g_done_seq;
+static bool            g_req_ok;
+static char            g_req_err[192];
+
+const char *capture_device_path(void) { return g_input_dev; }
+
+void capture_state_get(CaptureState *st)
+{
+    pthread_mutex_lock(&g_cap_lock);
+    *st = g_cap_state;
+    pthread_mutex_unlock(&g_cap_lock);
+}
+
+static void capture_state_set(V4L2Capture *cap)
+{
+    pthread_mutex_lock(&g_cap_lock);
+    memset(&g_cap_state, 0, sizeof g_cap_state);
+    if (cap) {
+        g_cap_state.active = true;
+        capture_get(cap, &g_cap_state.mode, &g_cap_state.crop);
+    }
+    pthread_mutex_unlock(&g_cap_lock);
+}
+
+bool capture_request(const CaptureMode *mode, int fit, char *err, size_t errlen)
+{
+    pthread_mutex_lock(&g_cap_lock);
+    g_req_reopen = mode != NULL;
+    if (mode) g_req_mode = *mode;
+    g_req_fit = fit;
+    unsigned seq = ++g_req_seq;
+    struct timespec dl;
+    clock_gettime(CLOCK_REALTIME, &dl);
+    dl.tv_sec += 6;
+    int rc = 0;
+    while (g_done_seq < seq && rc == 0)
+        rc = pthread_cond_timedwait(&g_cap_cond, &g_cap_lock, &dl);
+    bool done = g_done_seq >= seq;
+    bool ok   = done && g_req_ok;
+    if (!ok) snprintf(err, errlen, "%s", done ? g_req_err : "timeout (camera not responding)");
+    pthread_mutex_unlock(&g_cap_lock);
+    return ok;
+}
+
+/* Called by the main loop once per frame; cheap when nothing is pending. */
+static void capture_service(V4L2Capture **cap)
+{
+    pthread_mutex_lock(&g_cap_lock);
+    if (g_done_seq == g_req_seq) { pthread_mutex_unlock(&g_cap_lock); return; }
+    unsigned     seq    = g_req_seq;
+    CaptureMode  m      = g_req_mode;
+    bool         reopen = g_req_reopen;
+    int          fit    = g_req_fit;
+    CaptureState old    = g_cap_state;
+    pthread_mutex_unlock(&g_cap_lock);
+
+    bool crop = fit < 0 ? old.crop : fit == 1;
+    bool ok = true;
+    char err[192] = "";
+
+    if (reopen || !*cap) {
+        if (!reopen) m = old.mode;     /* fit change while camera is down: retry it */
+        if (*cap) { capture_close(*cap); *cap = NULL; }
+        *cap = capture_open_mode(g_input_dev, &m, g_output_w, g_output_h, crop);
+        if (!*cap) {
+            ok = false;
+            snprintf(err, sizeof err, "camera refused %s %dx%d@%d", m.fmt, m.w, m.h, m.fps);
+            if (old.active)
+                *cap = capture_open_mode(g_input_dev, &old.mode, g_output_w, g_output_h, old.crop);
+            if (!*cap)
+                snprintf(err + strlen(err), sizeof err - strlen(err), "; old mode failed too, no picture");
+        }
+    } else if (!capture_set_fit(*cap, crop)) {
+        ok = false;
+        snprintf(err, sizeof err, "out of memory changing fit");
+    }
+    fprintf(stderr, "[capture] switch %s → %s\n", ok ? "ok" : "FAILED", ok ? m.fmt : err);
+
+    capture_state_set(*cap);
+    pthread_mutex_lock(&g_cap_lock);
+    g_req_ok = ok;
+    snprintf(g_req_err, sizeof g_req_err, "%s", err);
+    g_done_seq = seq;
+    pthread_cond_broadcast(&g_cap_cond);
+    pthread_mutex_unlock(&g_cap_lock);
+}
+
 static void on_signal(int sig)
 {
     (void)sig;
@@ -288,6 +388,8 @@ int main(int argc, char *argv[])
     if (!no_input) {
         cap = capture_open(input_dev, &width, &height, &fps);
         if (!cap) { registry_destroy(&g_registry); filter_chain_destroy(&g_filters); return 1; }
+        g_input_dev = input_dev;
+        capture_state_set(cap);
     } else {
         if (width <= 0 || height <= 0) {
             fprintf(stderr, "[main] --no-input requires -W and -H\n");
@@ -346,6 +448,9 @@ int main(int argc, char *argv[])
         struct timespec t0;
         clock_gettime(CLOCK_MONOTONIC, &t0);
 
+        /* 0. Apply a pending live capture switch (from the API) */
+        if (!no_input) capture_service(&cap);
+
         /* 1. Capture the webcam (if open) into cam_buf */
         if (cap) {
             if (!capture_read(cap, cam_buf))