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

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

init

Christian Immanuel · 2026-06-29 23:32 · 59ace161f8a6bb12189cdf67a357e37df08f3d7e

 Makefile           |   39 ++
 README.md          |  528 ++++++++++++++++++++
 include/vcam.h     |  226 +++++++++
 scripts/vcam-ctl   |  423 ++++++++++++++++
 scripts/vcam-setup |  221 +++++++++
 scripts/vcam-tune  |  303 ++++++++++++
 src/capture.c      |  399 +++++++++++++++
 src/filter.c       | 1387 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/frame.c        |   22 +
 src/ipc.c          |  702 ++++++++++++++++++++++++++
 src/main.c         |  335 +++++++++++++
 src/output.c       |  256 ++++++++++
 src/overlay.c      |  949 +++++++++++++++++++++++++++++++++++
 src/registry.c     |  143 ++++++
 src/test_screen.c  |  300 ++++++++++++
 15 files changed, 6233 insertions(+)

diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..d806385
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,39 @@
+CC      := gcc
+CFLAGS  := -std=c11 -O2 -Wall -Wextra -Wpedantic \
+            -D_POSIX_C_SOURCE=200809L \
+            -I include \
+            $(shell pkg-config --cflags libavcodec libavformat libavutil libswscale) \
+            $(shell pkg-config --cflags libpng)
+
+LDFLAGS := $(shell pkg-config --libs libavcodec libavformat libavutil libswscale libavdevice) \
+            $(shell pkg-config --libs libpng) \
+            -lpthread -lm
+
+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
+OBJS := $(SRCS:.c=.o)
+BIN  := vcam
+TEST := test_screen
+
+.PHONY: all clean install
+
+all: $(BIN) $(TEST)
+
+$(BIN): $(OBJS)
+	$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
+
+$(TEST): src/test_screen.c
+	$(CC) -std=c11 -O2 -Wall -D_POSIX_C_SOURCE=200809L -D_DEFAULT_SOURCE \
+	    -o $@ src/test_screen.c
+
+src/%.o: src/%.c include/vcam.h
+	$(CC) $(CFLAGS) -c -o $@ $<
+
+install: $(BIN)
+	install -m 755 $(BIN) /usr/local/bin/
+	install -m 755 scripts/vcam-ctl /usr/local/bin/
+	install -m 755 scripts/vcam-setup /usr/local/bin/
+	install -m 755 scripts/vcam-tune /usr/local/bin/
+
+clean:
+	rm -f $(OBJS) $(BIN) $(TEST)
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..997dbc9
--- /dev/null
+++ b/README.md
@@ -0,0 +1,528 @@
+# vcam — virtual webcam pipeline
+
+100% vibe coded by ClaudeCode  
+
+Loopback your webcam so you can add filters, screensharing, images, super laggy videos nad such things
+
+Real-time virtual webcam written in C. Reads from a physical webcam, runs
+your frames through a chain of pixel effects, composites images / looping
+videos / live screen regions on top, and writes the result to a
+v4l2loopback device that browsers and video-call apps see as a normal
+camera.
+
+```
+/dev/video1 ──► [capture] ──► [filters] ──► [composite] ──► /dev/video0
+   (real cam)                                ▲              (loopback)
+                            PNG/JPEG · looping video · live screen region
+                                runtime add/remove via vcam-ctl
+```
+
+Works in Firefox, Chrome/Chromium, qutebrowser, Brave, Discord, OBS,
+Zoom — anything that consumes a V4L2 capture device.
+
+---
+
+## Tools at a glance
+
+| Command | What it does |
+|---|---|
+| `vcam`        | Main process — runs the capture → filter → composite → output pipeline. |
+| `vcam-ctl`    | Send commands to a running vcam (overlays, filters, screen capture). |
+| `vcam-setup`  | One-time install of `/etc/modprobe.d/vcam.conf` for browser compatibility. |
+| `vcam-tune`   | Interactively dial filter parameters with arrow keys. |
+
+Every tool has `--help`. Run any of them with no arguments or `-h` for full usage.
+
+---
+
+## Quick start
+
+```bash
+# 1. Dependencies (Debian / Ubuntu — package names differ on other distros)
+sudo apt install \
+    libv4l-dev libavcodec-dev libavformat-dev libavutil-dev \
+    libswscale-dev libavdevice-dev libpng-dev \
+    v4l2loopback-dkms pkg-config build-essential \
+    wf-recorder slurp ncat
+
+# 2. Build & install
+git clone <repo-url> vcam && cd vcam
+make
+sudo make install      # vcam, vcam-ctl, vcam-setup, vcam-tune
+
+# 3. ONE-TIME: make v4l2loopback land at /dev/video0 (Chromium needs this)
+sudo vcam-setup --install
+
+# Then reboot, or do the manual module reload it prints:
+sudo modprobe -r uvcvideo
+sudo modprobe -r v4l2loopback
+sudo modprobe v4l2loopback
+sudo modprobe uvcvideo
+
+# 4. Verify
+vcam-setup
+# → "OK — loopback at /dev/video0 comes before real cam at /dev/video1"
+
+# 5. Start it (defaults: input /dev/video1, output /dev/video0)
+vcam
+
+# 6. Test the output
+ffplay /dev/video0
+```
+
+In your video-call app, pick "vcam" as the camera.
+
+---
+
+## Why two device numbers? (the Chromium fix)
+
+Chromium-family browsers pick the first `/dev/video*` they see. If that's
+your real webcam and vcam is already streaming from it, the browser gets
+`EBUSY` → `NotReadableError` and the page errors out before the user can
+even pick a different device. Firefox doesn't have this problem.
+
+`vcam-setup --install` writes `/etc/modprobe.d/vcam.conf` so the
+v4l2loopback module claims `/dev/video0` *before* USB cameras enumerate.
+Your real cam then sits at `/dev/video1+` and the loopback is what
+Chromium auto-picks. The `exclusive_caps=1` parameter it sets is also
+mandatory for Firefox.
+
+---
+
+## vcam — main process
+
+Just run `./vcam` if you did everything above to run the video loopback modification software
+
+```
+vcam [OPTIONS]
+
+Pipeline:
+  -i <device>     Input webcam        (default /dev/video1)
+  -o <device>     Output loopback     (default /dev/video0)
+  -W <px>         Output width        (default: camera native)
+  -H <px>         Output height       (default: camera native)
+  -f <fps>        Frame rate
+  --no-input      Skip the webcam (screen overlay becomes the source).
+                  Requires -W and -H.
+
+Startup overlays:
+  --img      <id> <x> <y> [<w> [<h>]] <file>       PNG or JPEG
+  --vid      <id> <x> <y> [<w> [<h>]] <file>       video, loops
+  --vid-once <id> <x> <y> [<w> [<h>]] <file>       video, plays once
+  --screen   <id> <x> <y> [<w> [<h>]] <WxH+X+Y>    live screen region
+
+Startup filters (chain order = listed order):
+  --filter <name> [<param>]
+```
+
+If you pass only `<w>`, height is computed from the source aspect ratio;
+same for `<h>` alone (use `0 <h>` to skip width).
+
+### Examples
+
+```bash
+vcam                                                    # plain forward
+vcam -W 1280 -H 720 -f 30                               # force 720p30
+vcam --img logo 1100 10 160 /assets/logo.png            # top-right logo
+vcam --vid intro 50 50 320 180 /clips/intro.mp4
+vcam --filter modern 0.8 --filter vignette 0.6          # cinematic
+vcam --no-input -W 1920 -H 1080 \
+     --screen scr 0 0 1920 1080 1920x1080+0+0           # pure screencast
+```
+
+---
+
+## vcam-ctl — runtime control
+
+```bash
+vcam-ctl --help                                # script help
+vcam-ctl help                                  # all IPC commands
+
+vcam-ctl list                                  # active overlays (draw order)
+vcam-ctl add img      <id> <x> <y> [<w> [<h>]] <file>
+vcam-ctl add vid      <id> <x> <y> [<w> [<h>]] <file>      # loops
+vcam-ctl add vid-once <id> <x> <y> [<w> [<h>]] <file>      # plays once
+vcam-ctl add screen   <id> <x> <y> [<w> [<h>]] <WxH+X+Y>
+vcam-ctl add webcam   <id> <x> <y> [<w> [<h>]] <device>    # /dev/video1, …
+vcam-ctl remove <id>                           # one overlay
+vcam-ctl remove all                            # every overlay
+vcam-ctl move   <id> [x=N|N] [y=N|N]           # positional or keyed
+                                               # value can be a number, "keep", or "-"
+                                               # missing = keep
+vcam-ctl resize <id> [w=N|N] [h=N|N]           # positional or keyed
+                                               # value can be a number, "keep", "auto" or "-"
+                                               # missing = auto (derive from aspect)
+vcam-ctl raise  <id>                           # bring to top
+vcam-ctl lower  <id>                           # send to bottom
+vcam-ctl z      <id> <N>                       # explicit z-index
+                                               # 0 = bottom, -1 = top, -2 = second-from-top
+
+vcam-ctl webcam tr             # quick: webcam PiP at top-right
+vcam-ctl webcam br 480         # bigger, bottom-right
+vcam-ctl webcam center         # centered
+vcam-ctl webcam full           # fullscreen webcam overlay
+vcam-ctl webcam tl 200 cam2    # second webcam overlay (different id)
+vcam-ctl webcam off            # remove the default 'cam'
+
+vcam-ctl filter help                           # full filter list
+vcam-ctl filter list
+vcam-ctl filter add <name> [<param>]
+vcam-ctl filter set <index> <param>            # update parameter live
+vcam-ctl filter remove <index>
+vcam-ctl filter clear
+```
+
+The socket lives at `/tmp/vcam.sock`. Override with `VCAM_SOCK=...` if you
+ever need to.
+
+---
+
+## vcam-ctl screen — live screen capture
+
+(This used to be a separate `vcam-screen` script; it's now a subcommand
+of `vcam-ctl` so everything lives in one tool.)
+
+```
+vcam-ctl screen [OPTIONS]
+
+  -i <id>          Overlay ID (default: auto — picks screen, screen2, …)
+  -x <px>          Destination X on output           (default: 0)
+  -y <px>          Destination Y on output           (default: 0)
+  -w <px>          Destination width  (only -w preserves source aspect)
+  -h <px>          Destination height
+  --full           Capture the whole monitor. If multiple monitors are
+                   connected and --monitor wasn't passed, asks which to use.
+  --monitor <N>    For --full: pick monitor by connector name (DP-1,
+                   HDMI-A-1, …) or 1-based index. Suppresses the prompt.
+  --monitors       List connected monitors and exit.
+  -r, --replace    Remove existing overlay with the same ID first
+  --list           List active screen overlays
+  --remove [id]    Remove a screen overlay (default id "screen")
+  --remove-all     Remove every active screen overlay
+```
+
+Multiple captures are first-class: calling `vcam-ctl screen` repeatedly
+without `-i` creates `screen`, `screen2`, `screen3`, … so they don't
+collide.
+
+Examples:
+
+```bash
+vcam-ctl screen                          # auto-ID, draw a region with slurp/slop
+vcam-ctl screen                          # second call → ID "screen2"
+vcam-ctl screen --full                   # whole monitor (picker if multiple)
+vcam-ctl screen --full -w 1280           # whole monitor, scaled to 1280 wide
+vcam-ctl screen --full --monitor DP-1    # specific monitor, no prompt
+vcam-ctl screen --full --monitor 2       # 2nd monitor in --monitors list
+vcam-ctl screen --monitors               # list connected monitors
+vcam-ctl screen -i clip -x 100 -y 100 -w 320
+vcam-ctl screen --list
+vcam-ctl screen --remove screen2
+vcam-ctl screen --remove-all
+
+# move/resize examples — keep / auto syntax
+vcam-ctl move   logo 500              # x=500, keep current y
+vcam-ctl move   logo - 300            # keep current x, y=300
+vcam-ctl resize logo 400              # w=400, h derived from source aspect
+vcam-ctl resize logo - 300            # h=300, w derived from source aspect
+```
+
+### How screen capture works internally
+
+On Wayland we spawn `wf-recorder` (uses the `wlr-screencopy` protocol —
+no root, no `CAP_SYS_ADMIN` needed). On X11 we use `ffmpeg -f x11grab`.
+Each screen overlay gets its own reader thread that drains the capture
+pipe at full speed; the main loop just snapshots the latest frame, so
+capture latency is minimal regardless of output framerate.
+
+Region dimensions are snapped down to multiples of 16 (width) and 2
+(height) to match compositor stride alignment — otherwise the captured
+image appears to scroll diagonally because frame N starts a few bytes
+into frame N+1's data.
+
+A historic bug worth knowing: `wf-recorder` prompts "Overwrite?" when its
+output file exists. We pre-load `y\n` into its stdin so the prompt is
+auto-answered, otherwise the whole pipeline hangs silently and you'd see
+a black overlay forever.
+
+`--full` detects connected monitors by reading `/sys/class/drm/card*-*/status`
+and `modes` directly from the kernel — no external tools required. If
+`swaymsg` is available (i.e. you're running sway) it's used in addition
+for accurate per-monitor X/Y positions on multi-monitor setups; without
+it we report `0,0` for all monitors, which is correct for single-monitor
+setups but may be wrong for non-primary monitors on multi-monitor.
+
+---
+
+## vcam-setup — boot-time configuration
+
+```bash
+vcam-setup                  # diagnose current /dev/video* layout
+sudo vcam-setup --install   # write /etc/modprobe.d/vcam.conf
+sudo vcam-setup --uninstall # revert
+vcam-setup --help
+```
+
+The script detects systemd / OpenRC / runit / manual init and prints
+init-system-specific instructions for activating the new module load
+order without a reboot.
+
+---
+
+## Webcam as an overlay
+
+The webcam is captured once by the main pipeline. Any number of webcam
+overlays can sample from that single shared capture, so you can have
+the cam fullscreen, in a corner, several times at different sizes, etc.
+— V4L2's one-streamer-per-device rule doesn't apply because we never
+open the device more than once.
+
+Filters apply to the captured cam stream before any compositing, so a
+cam-in-corner picture-in-picture shows whatever filters are active.
+
+Typical screencast-with-webcam-corner workflow:
+
+```bash
+vcam                                # captures cam, uses it as base
+vcam-ctl screen --full              # screen covers the cam base
+vcam-ctl webcam br 400              # cam reappears in bottom-right
+vcam-ctl raise cam                  # make sure it stays on top
+vcam-ctl filter add modern 0.8      # cinema look on the cam image
+```
+
+Multiple corners are fine — pass distinct IDs:
+
+```bash
+vcam-ctl webcam tl 200 cam_tl
+vcam-ctl webcam br 200 cam_br
+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.
+
+---
+
+## Filters (43 total, 6 categories)
+
+Filters run in chain order on every frame from the webcam, *before*
+overlays are composited.
+
+### Basic
+
+| Name | Param | Description |
+|---|---|---|
+| `grayscale`  | —             | Rec.601 luma |
+| `sepia`      | —             | warm brown tone |
+| `invert`     | —             | negative colours |
+| `mirror`     | —             | horizontal flip |
+| `flip`       | —             | vertical flip |
+| `pixelate`   | block px (8)  | average colour per block |
+| `blur`       | radius 1–6 (2)| two-pass box blur |
+| `vignette`   | 0–1 (0.6)     | darken edges radially |
+| `brightness` | mult (1.2)    | clamped multiply |
+| `contrast`   | mult (1.4)    | contrast around mid-grey |
+| `posterize`  | levels (4)    | reduce colour levels per channel |
+| `edges`      | —             | Sobel edge detection |
+
+### Fancy
+
+| Name | Param | Description |
+|---|---|---|
+| `chromashift`  | offset px (5)       | VHS-style RGB channel separation |
+| `glitch`       | intensity 0–1 (0.3) | animated slice displacement |
+| `kaleidoscope` | segments (6)        | radial mirror |
+| `swirl`        | strength (1.0)      | radial twist |
+| `thermal`      | —                   | luma → heatmap palette |
+| `oldfilm`      | —                   | sepia + grain + scratches + vignette |
+| `wave`         | amplitude px (10)   | animated sin-wave x-shift per row |
+| `cartoon`      | edge thresh (50)    | posterize + dark edges |
+| `solarize`     | threshold (128)     | invert pixels above value |
+| `rainbow`      | speed (1.0)         | animated additive hue rotation |
+
+### Soft & dreamy
+
+| Name | Param | Description |
+|---|---|---|
+| `dream`     | 0–1 (0.5) | hazy soft glow |
+| `bloom`     | 0–1 (0.6) | highlight bloom |
+| `glow`      | 0–1 (0.4) | gentle gaussian glow |
+| `pinch`     | 0–1 (0.5) | radial inward pull |
+| `bulge`     | 0–1 (0.5) | fisheye-like outward push |
+| `painterly` | 1–5 (3)   | oil-painting effect |
+
+### Themed looks
+
+| Name | Param | Description |
+|---|---|---|
+| `modern`    | 0–1 (0.7)         | teal-orange cinematic grade |
+| `cyberpunk` | 0–1 (0.7)         | neon contrast + chromashift |
+| `romantic`  | 0–1 (0.7)         | soft warm haze + blur + vignette |
+| `vangogh`   | radius 1–5 (3)    | heavy painterly + saturation |
+| `picasso`   | segments 4–16 (8) | cubist: kaleidoscope + posterize + edges |
+
+### Mathematical patterns
+
+| Name | Param | Description |
+|---|---|---|
+| `sine`    | amplitude (15)    | animated sin-wave x/y distortion |
+| `xor`     | 0–1 (0.5)         | `(x ^ y)` bitwise overlay |
+| `modulo`  | divisor 2–128 (64)| colour mod N |
+| `polar`   | 0–1 (0.7)         | polar-coordinate warp |
+| `voronoi` | cells 4–64 (20)   | voronoi-cell mosaic |
+
+### Pixel-crazy / animated
+
+| Name | Param | Description |
+|---|---|---|
+| `bitcrush` | bits 1–8 (3)   | quantize each channel to N bits — chunky banding |
+| `melt`     | 0–1 (0.5)      | columns drip downward, animated over time |
+| `popart`   | 0–1 (1.0)      | Warhol 2×2 quadrants with rotating colour tints |
+| `displace` | 0–1 (0.5)      | bright pixels shift right, dark pixels left |
+| `ripple`   | 0–1 (0.5)      | animated water ripple radiating from the center |
+
+### Combinations to try
+
+```bash
+vcam-ctl filter add modern 0.8                                  # cinema look
+vcam-ctl filter add cyberpunk 0.9                               # neon
+vcam-ctl filter add romantic 0.7                                # soft skin
+vcam-ctl filter add vangogh 3                                   # painting
+vcam-ctl filter add picasso 8                                   # cubism
+vcam-ctl filter add thermal                                     # heatvision
+vcam-ctl filter add cartoon                                     # animated
+vcam-ctl filter add glitch 0.4 && vcam-ctl filter add chromashift 6
+vcam-ctl filter add voronoi 30 && vcam-ctl filter add xor 0.4   # math art
+```
+
+---
+
+## vcam-tune — interactive parameter dial
+
+Walk mode (no args) navigates every active filter; the highlighted one is
+the one whose parameter the arrows are tweaking. Single-filter mode adds
+(or selects) one filter and dials just it.
+
+```
+vcam-tune                  walk mode — navigate all active filters
+vcam-tune <name> [<step>]  add the filter and dial it
+vcam-tune <index> [<step>] dial an existing filter at <index>
+vcam-tune --help
+```
+
+| Key | Action |
+|---|---|
+| `↑` / `k` | increase parameter |
+| `↓` / `j` | decrease parameter |
+| `r`       | reset to default |
+| `x`       | remove and quit |
+| `q` / Esc | quit |
+| `→` / `l` / Tab | next filter (walk mode) |
+| `←` / `h`       | previous filter (walk mode) |
+
+Examples:
+
+```bash
+vcam-tune modern         # add modern, then arrows to dial strength
+vcam-tune pinch 0.02     # smaller step for finer control
+vcam-tune                # walk everything you already added
+vcam-tune 2              # dial existing filter at index 2
+```
+
+---
+
+## Architecture
+
+```
+src/
+  main.c       – CLI parsing, signal handling, main compositing loop
+  capture.c    – V4L2 mmap capture (auto-picks YUYV/MJPG/NV12 at best
+                 resolution), MJPG decoded via libavcodec, converted to BGR24
+  output.c     – V4L2 streaming I/O to loopback with mmap output buffers,
+                 BGR24 → YUYV422 conversion, BT.709 (HD) / BT.601 (SD)
+                 colourspace tags
+  frame.c      – BGR24 frame allocation
+  overlay.c    – Image (PNG/JPEG), looping/once video, live screen overlays
+                 (one reader thread per screen)
+  registry.c   – Mutex-protected overlay list (thread-safe runtime mutation)
+  ipc.c        – Unix-domain-socket server (separate thread)
+  filter.c     – 38-effect filter chain; mutex-protected
+  test_screen.c – Standalone diagnostic for the screen-capture path
+include/
+  vcam.h       – Public API
+scripts/
+  vcam-ctl     – Complete runtime control: overlays, filters, and the
+                 'screen' subcommand (slurp/slop region picker, --full
+                 monitor capture via /sys/class/drm, list/remove screens)
+  vcam-setup   – v4l2loopback boot configuration
+  vcam-tune    – Interactive parameter dial
+```
+
+**Threading model**
+
+| Thread | Job |
+|---|---|
+| main | capture → filter chain → composite → output, paced at fps |
+| IPC  | accepts UDS connections, mutates registry + filter chain under their locks |
+| 1 per screen overlay | drains FIFO/pipe as fast as data arrives, keeps `latest_frame` mutex-protected |
+
+**Pixel format**
+
+- Internal: BGR24, packed, row-major.
+- Capture: V4L2 native → swscale → BGR24 (lazy: built from the first
+  received frame's actual `pix_fmt`, not the pre-decode guess — this is
+  what fixed the historic "green block" bug).
+- Output: swscale BGR24 → YUYV422 directly into mmap'd output buffers,
+  with proper `V4L2_COLORSPACE_*` / `ycbcr_enc` tags so browsers don't
+  reject the device.
+
+---
+
+## Working on the source
+
+```bash
+make              # build vcam and test_screen with -Wall -Wextra -Wpedantic -O2
+make clean
+sudo make install # all four scripts + vcam to /usr/local/bin
+```
+
+To add a new source file, drop it in `src/` and append to `SRCS` in the
+Makefile. No autotools, no generated headers.
+
+### test_screen
+
+Standalone diagnostic for screen capture. Prints every step (env vars,
+exact wf-recorder command, child status, byte-by-byte arrival progress),
+saves a raw frame, and tells you how to view it as PNG:
+
+```bash
+./test_screen 1280x720+0+0 /tmp/frame.raw
+ffmpeg -f rawvideo -pix_fmt bgr0 -video_size 1280x720 -i /tmp/frame.raw \
+       -frames:v 1 -update 1 -y /tmp/frame.png
+xdg-open /tmp/frame.png
+```
+
+If `test_screen` produces a good PNG but vcam itself still shows black,
+the bug is in the compositing path, not capture. If `test_screen` itself
+times out, your compositor probably doesn't support `wlr-screencopy`
+(GNOME/Plasma don't; Sway/Hyprland/river/niri/wayfire do).
+
+---
+
+## Troubleshooting
+
+| Symptom | Likely cause | Fix |
+|---|---|---|
+| `Cannot open /dev/video0` | v4l2loopback not loaded | `sudo vcam-setup --install`, then reboot or manual reload |
+| `NotReadableError` in Chromium | Loopback isn't at /dev/video0 | `sudo vcam-setup --install` |
+| Firefox shows no camera | v4l2loopback without `exclusive_caps=1` | vcam-setup writes it correctly |
+| Screen overlay is black | (was) wf-recorder hung on Overwrite prompt | rebuild — pre-loaded `y\n` is in stdin now |
+| Screen overlay still black | Compositor doesn't support wlr-screencopy | Use Sway, Hyprland, river, niri, wayfire |
+| Screen image scrolls diagonally | (was) stride misalignment | rebuild — dims snap to 16/2 now |
+| Video overlay is a green block | (was) pre-decode `pix_fmt` was NONE | rebuild — sws is lazy now |
+| Video plays jerky/jumps back | (was) spin limit too tight | rebuild — limit raised, `vid_eof_sent` flag added |
+| `vcam-ctl: ncat: command not found` | ncat not installed | `sudo apt install ncat` |
+| `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 |
diff --git a/include/vcam.h b/include/vcam.h
new file mode 100644
index 0000000..30817c2
--- /dev/null
+++ b/include/vcam.h
@@ -0,0 +1,226 @@
+#pragma once
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <pthread.h>
+
+/* ──────────────────────────────────────────────
+ * Frame  (internal BGR24)
+ * ────────────────────────────────────────────── */
+typedef struct {
+    uint8_t *data;
+    int      width, height, stride;
+} Frame;
+
+Frame *frame_alloc(int width, int height);
+void   frame_free(Frame *f);
+
+/* ──────────────────────────────────────────────
+ * Overlay
+ * ────────────────────────────────────────────── */
+typedef enum {
+    OVERLAY_IMAGE,   /* static PNG/JPEG             */
+    OVERLAY_VIDEO,   /* looping video file          */
+    OVERLAY_SCREEN,  /* live screen-region capture  */
+    OVERLAY_WEBCAM,  /* live webcam capture (own V4L2 device) */
+} OverlayType;
+
+typedef struct Overlay Overlay;
+
+Overlay *overlay_create_image (const char *path,
+                                int dst_x, int dst_y, int dst_w, int dst_h);
+Overlay *overlay_create_video (const char *path,
+                                int dst_x, int dst_y, int dst_w, int dst_h,
+                                bool loop);  /* loop=true: restart on EOF */
+
+/*
+ * screen_geometry: "WxH+X+Y"  (as output by slurp / wf-recorder -g)
+ * dst_*: placement on the output frame (0 = use capture native size)
+ */
+Overlay *overlay_create_screen(const char *screen_geometry,
+                                int dst_x, int dst_y, int dst_w, int dst_h);
+
+/*
+ * device: V4L2 path (e.g. "/dev/video1"). Will fail with EBUSY if the
+ * main vcam process is already capturing from the same device — webcam
+ * overlays are intended for use in --no-input mode where the main
+ * pipeline doesn't own the camera.
+ */
+Overlay *overlay_create_webcam(const char *device,
+                                int dst_x, int dst_y, int dst_w, int dst_h);
+
+void overlay_free (Overlay *o);
+void overlay_blit (Overlay *o, Frame *dst);
+
+/* Advance one frame.
+ * webcam_src: the latest captured webcam frame (after filters), used by
+ * OVERLAY_WEBCAM overlays as their source. Pass NULL if no webcam is
+ * being captured — webcam overlays will then show black.
+ * Other overlay types ignore this argument. */
+void overlay_tick (Overlay *o, const Frame *webcam_src);
+
+/* Runtime geometry update */
+void overlay_move  (Overlay *o, int x, int y);
+void overlay_resize(Overlay *o, int w, int h);
+
+/* Inspect overlay state (for IPC list command) */
+OverlayType overlay_get_type(const Overlay *o);
+void        overlay_get_rect(const Overlay *o, int *x, int *y, int *w, int *h);
+void        overlay_get_src (const Overlay *o, int *w, int *h);
+
+/* ──────────────────────────────────────────────
+ * Filter chain — per-pixel effects applied to the
+ * webcam frame before overlays are composited.
+ * ────────────────────────────────────────────── */
+typedef enum {
+    FX_GRAYSCALE,
+    FX_SEPIA,
+    FX_INVERT,
+    FX_MIRROR,      /* horizontal flip */
+    FX_FLIP,        /* vertical flip   */
+    FX_PIXELATE,    /* param = block size (px), default 8  */
+    FX_BLUR,        /* param = radius (px), default 2      */
+    FX_VIGNETTE,    /* param = strength 0..1, default 0.6  */
+    FX_BRIGHTNESS,  /* param = multiplier, default 1.2     */
+    FX_CONTRAST,    /* param = multiplier, default 1.4     */
+    FX_POSTERIZE,   /* param = levels per channel, def 4   */
+    FX_EDGES,       /* sobel edge detect                    */
+
+    /* ── fancier effects ── */
+    FX_CHROMASHIFT, /* param = offset px, default 5 (VHS-style RGB split) */
+    FX_GLITCH,      /* param = intensity 0..1, default 0.3 (animated)     */
+    FX_KALEIDOSCOPE,/* param = segments, default 6                        */
+    FX_SWIRL,       /* param = strength, default 1.0                      */
+    FX_THERMAL,     /* heatmap palette mapped from luma                   */
+    FX_OLDFILM,     /* sepia + grain + scratches + vignette               */
+    FX_WAVE,        /* param = amplitude px, default 10 (sinusoidal)      */
+    FX_CARTOON,     /* posterize + edge enhancement                       */
+    FX_SOLARIZE,    /* param = threshold 0..255, default 128              */
+    FX_RAINBOW,     /* animated hue rotation, param = speed (default 1.0) */
+
+    /* ── soft / dreamy / painterly ── */
+    FX_DREAM,       /* blur + brightness boost (soft hazy glow)           */
+    FX_BLOOM,       /* highlight-bloom glow on bright areas               */
+    FX_GLOW,        /* gentle gaussian glow over everything               */
+    FX_PINCH,       /* radial inward pull toward center                   */
+    FX_BULGE,       /* radial outward push from center (fisheye-ish)      */
+    FX_PAINTERLY,   /* oil-painting: dominant color in neighborhood       */
+
+    /* ── themed / styled looks ── */
+    FX_MODERN,      /* clean teal-orange grade, default 0.7 strength      */
+    FX_CYBERPUNK,   /* chromashift + neon contrast, default 0.7 intensity */
+    FX_ROMANTIC,    /* soft warm haze, default 0.7 strength               */
+    FX_VANGOGH,     /* heavy painterly + saturation boost                 */
+    FX_PICASSO,     /* kaleidoscope + posterize + cartoon edges           */
+
+    /* ── mathematical patterns ── */
+    FX_SINE,        /* sinusoidal x/y distortion, default 15px            */
+    FX_XOR,         /* x^y bitwise overlay, 0..1                          */
+    FX_MODULO,      /* color modulo, default 64                           */
+    FX_POLAR,       /* polar-coordinate warp, 0..1                        */
+    FX_VORONOI,     /* voronoi cell mosaic, default 20 cells              */
+
+    /* ── pixel-crazy / animated ── */
+    FX_BITCRUSH,    /* quantize bits per channel, 1..8, default 3         */
+    FX_MELT,        /* animated drip downward, 0..1, default 0.5          */
+    FX_POPART,      /* warhol-style 2x2 quadrants, strength 0..1          */
+    FX_DISPLACE,    /* luma-based horizontal displacement, default 0.5    */
+    FX_RIPPLE,      /* animated water ripple from center, default 0.5     */
+
+    FX_UNKNOWN,
+} FilterType;
+
+typedef struct {
+    FilterType type;
+    float      param;
+} Filter;
+
+#define MAX_FILTERS 16
+
+typedef struct {
+    Filter          filters[MAX_FILTERS];
+    int             count;
+    pthread_mutex_t lock;
+} FilterChain;
+
+void        filter_chain_init   (FilterChain *fc);
+void        filter_chain_destroy(FilterChain *fc);
+bool        filter_chain_add    (FilterChain *fc, FilterType t, float param);
+bool        filter_chain_remove (FilterChain *fc, int index);
+void        filter_chain_clear  (FilterChain *fc);
+void        filter_chain_apply  (FilterChain *fc, Frame *f); /* takes lock */
+
+FilterType  filter_type_from_name(const char *name);
+const char *filter_type_to_name  (FilterType t);
+float       filter_default_param (FilterType t);
+
+/* ──────────────────────────────────────────────
+ * Overlay registry  (mutex-protected list)
+ * ────────────────────────────────────────────── */
+#define MAX_OVERLAYS 64
+
+typedef struct {
+    Overlay    *overlay;
+    char        id[64];      /* user-supplied name */
+} OverlaySlot;
+
+typedef struct {
+    OverlaySlot  slots[MAX_OVERLAYS];
+    int          count;
+    pthread_mutex_t lock;
+} OverlayRegistry;
+
+void     registry_init  (OverlayRegistry *r);
+void     registry_destroy(OverlayRegistry *r);
+bool     registry_add   (OverlayRegistry *r, const char *id, Overlay *o);
+bool     registry_remove(OverlayRegistry *r, const char *id);
+Overlay *registry_find  (OverlayRegistry *r, const char *id);  /* caller must hold lock */
+bool     registry_raise (OverlayRegistry *r, const char *id);  /* draw last  (on top) */
+bool     registry_lower (OverlayRegistry *r, const char *id);  /* draw first (at bottom) */
+bool     registry_set_z (OverlayRegistry *r, const char *id, int target);
+/*  target >= 0    : absolute position (0 = bottom)
+ *  target <  0    : count from top (-1 = top, -2 = second-from-top, …)
+ *  Out-of-range values are clamped.  Returns false only if id not found. */
+
+/* ──────────────────────────────────────────────
+ * IPC control server
+ * Commands (newline-terminated text):
+ *   add img   <id> <x> <y> [<w> <h>] <file>
+ *   add vid   <id> <x> <y> [<w> <h>] <file>
+ *   add screen <id> <x> <y> [<w> <h>] <geometry>
+ *   remove <id>
+ *   move   <id> <x> <y>
+ *   resize <id> <w> <h>
+ *   list
+ *   quit
+ * Responses are newline-terminated text lines.
+ * ────────────────────────────────────────────── */
+#define VCAM_SOCK_PATH "/tmp/vcam.sock"
+
+typedef struct {
+    OverlayRegistry *registry;
+    int              server_fd;
+    pthread_t        thread;
+    volatile bool    running;
+} IPCServer;
+
+bool ipc_start(IPCServer *srv, OverlayRegistry *reg);
+void ipc_stop (IPCServer *srv);
+
+/* ──────────────────────────────────────────────
+ * V4L2 capture
+ * ────────────────────────────────────────────── */
+typedef struct V4L2Capture V4L2Capture;
+
+V4L2Capture *capture_open (const char *dev, int *w, int *h, int *fps);
+bool         capture_read (V4L2Capture *cap, Frame *out);
+void         capture_close(V4L2Capture *cap);
+
+/* ──────────────────────────────────────────────
+ * V4L2 loopback output
+ * ────────────────────────────────────────────── */
+typedef struct V4L2Output V4L2Output;
+
+V4L2Output *output_open (const char *dev, int w, int h, int fps);
+bool        output_write(V4L2Output *out, const Frame *frame);
+void        output_close(V4L2Output *out);
diff --git a/scripts/vcam-ctl b/scripts/vcam-ctl
new file mode 100755
index 0000000..cf87330
--- /dev/null
+++ b/scripts/vcam-ctl
@@ -0,0 +1,423 @@
+#!/usr/bin/env bash
+#
+# vcam-ctl – complete runtime control for a running vcam process.
+#
+# Usage:
+#   vcam-ctl <command> [args...]
+#
+# Overlay commands:
+#   list                                                  show active overlays
+#                                                         (draw order: first = bottom,
+#                                                          last = on top)
+#   add img      <id> <x> <y> [<w> [<h>]] <file>          image (PNG/JPEG)
+#   add vid      <id> <x> <y> [<w> [<h>]] <file>          video (loops)
+#   add vid-once <id> <x> <y> [<w> [<h>]] <file>          video (plays once)
+#   add screen   <id> <x> <y> [<w> [<h>]] <WxH+X+Y>       live screen region
+#   add webcam   <id> <x> <y> [<w> [<h>]] [-]            same webcam as the main
+#                                                         pipeline, shown at <x,y>
+#                                                         scaled to <w x h>. Path arg
+#                                                         is unused — pass "-" or
+#                                                         anything. Multiple webcam
+#                                                         overlays are fine; they
+#                                                         all share one capture.
+#   remove <id>                                           remove one overlay
+#   remove all                                            remove every overlay
+#   move   <id> [x=N|N] [y=N|N]    Positional or x=/y=. Each value may
+#                                  be a number, "keep", or "-" (= keep).
+#                                  Missing = keep current. Default action
+#                                  for positions is "keep".
+#   resize <id> [w=N|N] [h=N|N]    Positional or w=/h=. Each value may
+#                                  be a number, "keep", or "auto" / "-"
+#                                  (derive from source aspect ratio).
+#                                  Missing = auto. Default action for
+#                                  resize is "auto".
+#   raise  <id>                    bring overlay to the top (drawn last)
+#   lower  <id>                    send overlay to the bottom (drawn first)
+#   z      <id> <N>                explicit z-index: 0 = bottom, -1 = top,
+#                                  -2 = second-from-top, etc.
+#
+# Filter commands:
+#   filter help                                           list available filters
+#   filter list                                           show active chain
+#   filter add <name> [<param>]
+#   filter set <index> <param>                            update parameter live
+#   filter remove <index>
+#   filter clear
+#
+# Screen commands (formerly the vcam-screen script):
+#   screen                       Pick a region with slurp/slop and add it.
+#                                Auto-picks a free ID (screen, screen2, …).
+#   screen --full                Capture the whole monitor. If multiple
+#                                monitors are connected and you didn't pass
+#                                --monitor, an interactive picker appears.
+#   screen --monitor <name|N>    Pick a specific monitor for --full, by
+#                                connector name (e.g. DP-1, HDMI-A-1) or
+#                                1-based index. Suppresses the picker.
+#   screen --monitors            List connected monitors and exit.
+#   screen --list                List active screen overlays.
+#   screen --remove [id]         Remove a screen overlay (default id: "screen").
+#   screen --remove-all          Remove all active screen overlays.
+#
+#   Screen options accepted with or without --full:
+#     -i <id>      Overlay ID                  (default: auto)
+#     -x <px>      Destination X               (default: 0)
+#     -y <px>      Destination Y               (default: 0)
+#     -w <px>      Destination width           (only -w preserves aspect)
+#     -h <px>      Destination height
+#     -r           Replace existing overlay with the same ID first
+#
+# Webcam-as-overlay quick command (great for screencasting):
+#   webcam <tl|tr|bl|br|center|full> [width] [id]
+#                                Add a webcam overlay that shares the
+#                                main pipeline's V4L2 capture. Multiple
+#                                instances are fine — pass a different
+#                                <id> to avoid replacing. Default id is
+#                                "cam", default width 320, position tr.
+#                                "full" stretches it to the full output.
+#   webcam off                   Remove the "cam" overlay.
+#
+# Other:
+#   help                                                  IPC command list
+#   --help, -h                                            this message
+#
+# Notes:
+#   - Passing only <w> (no <h>) preserves source aspect ratio for overlays.
+#   - Default socket path is /tmp/vcam.sock. Override with VCAM_SOCK.
+#   - See also: vcam-tune (interactive filter dial), vcam-setup (boot config).
+
+SOCK="${VCAM_SOCK:-/tmp/vcam.sock}"
+
+show_help() { sed -n '/^# vcam-ctl/,/^$/p' "$0" | sed 's/^# \?//'; }
+
+# ── basic usage / help ───────────────────────────────────────
+if [[ $# -eq 0 || "$1" == "-h" || "$1" == "--help" ]]; then
+    show_help
+    exit 0
+fi
+
+# ── check vcam is alive ──────────────────────────────────────
+require_running() {
+    if [[ ! -S "$SOCK" ]]; then
+        echo "Error: vcam is not running (socket $SOCK not found)" >&2
+        exit 1
+    fi
+}
+
+# ── send an IPC command and print the reply ──────────────────
+ipc_send() {
+    require_running
+    printf '%s\nquit\n' "$*" | ncat -U "$SOCK"
+}
+
+# ── bare-metal monitor detection ─────────────────────────────
+# Lists connected monitors as one line each: "NAME WxH X Y"
+# Uses /sys/class/drm for resolution (works everywhere). For accurate
+# X/Y positions on multi-monitor setups, falls back to swaymsg if
+# present — without it we report 0,0 for all monitors (correct for
+# single-monitor; possibly wrong offset for non-primary on multi).
+detect_monitors() {
+    # Try sway first — it gives us real positions, not just resolutions.
+    if command -v swaymsg >/dev/null 2>&1 \
+       && swaymsg -t get_outputs --pretty 2>/dev/null | grep -q "^Output "; then
+        swaymsg -t get_outputs --pretty 2>/dev/null | awk '
+            /^Output / { name=$2 }
+            /Current mode: / { mode=$3 }
+            /Position: / {
+                gsub(",", " ", $2)
+                if (name && mode) {
+                    split($2, p, " ")
+                    print name, mode, p[1], p[2]
+                    name=""; mode=""
+                }
+            }
+        '
+        return 0
+    fi
+    # Bare-metal fallback: /sys/class/drm — only gives resolution.
+    for status_file in /sys/class/drm/card*/status; do
+        [[ -r "$status_file" ]] || continue
+        [[ "$status_file" =~ /card[0-9]+-[^/]+/status$ ]] || continue
+        if [[ "$(cat "$status_file")" == "connected" ]]; then
+            local dir="${status_file%/status}"
+            local name mode
+            name=$(basename "$dir" | sed 's/^card[0-9]*-//')
+            mode=$(head -1 "$dir/modes" 2>/dev/null)
+            if [[ -n "$mode" && "$mode" =~ ^[0-9]+x[0-9]+$ ]]; then
+                echo "$name $mode 0 0"
+            fi
+        fi
+    done
+}
+
+# Resolves a monitor selector (name or 1-based index) to a "NAME WxH X Y"
+# line. Empty selector + single monitor → that monitor. Empty selector +
+# multiple monitors → interactive prompt.
+resolve_monitor() {
+    local selector="$1"
+    local lines
+    lines=$(detect_monitors)
+    [[ -z "$lines" ]] && { return 1; }
+
+    local count
+    count=$(echo "$lines" | wc -l)
+
+    # Specific selector
+    if [[ -n "$selector" ]]; then
+        if [[ "$selector" =~ ^[0-9]+$ ]]; then
+            echo "$lines" | sed -n "${selector}p"
+        else
+            echo "$lines" | awk -v n="$selector" '$1 == n { print; exit }'
+        fi
+        return 0
+    fi
+
+    # Single monitor: just use it
+    if [[ $count -eq 1 ]]; then
+        echo "$lines"
+        return 0
+    fi
+
+    # Multiple monitors: interactive prompt
+    # Only require stdin to be a TTY — stdout is captured by $(...) so
+    # -t 1 would always fail when called via command substitution.
+    if [[ ! -t 0 ]]; then
+        echo "$lines" | head -1
+        return 0
+    fi
+
+    echo "Multiple monitors connected:" >&2
+    local i=0
+    while IFS= read -r line; do
+        i=$((i+1))
+        read -r name mode x y <<< "$line"
+        printf "  %d) %-12s %s  at (%d,%d)\n" "$i" "$name" "$mode" "$x" "$y" >&2
+    done <<< "$lines"
+    printf "Select monitor (1-%d, default 1): " "$count" >&2
+    local choice
+    read -r choice
+    [[ -z "$choice" ]] && choice=1
+    if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > count )); then
+        echo "Invalid selection" >&2; return 1
+    fi
+    echo "$lines" | sed -n "${choice}p"
+}
+
+# ──────────────────────────────────────────────────────────────
+# screen subcommand — fully merged from old vcam-screen
+# ──────────────────────────────────────────────────────────────
+if [[ "$1" == "screen" ]]; then
+    shift
+    require_running
+
+    ID=""
+    DST_X=0; DST_Y=0; DST_W=0; DST_H=0
+    REPLACE=0
+    FULL=0
+    MONITOR=""
+    ACTION="add"   # add | list | remove | remove-all | monitors
+
+    while [[ $# -gt 0 ]]; do
+        case "$1" in
+            --help) show_help; exit 0 ;;
+            -i) ID="$2"; shift 2 ;;
+            -x) DST_X="$2"; shift 2 ;;
+            -y) DST_Y="$2"; shift 2 ;;
+            -w) DST_W="$2"; shift 2 ;;
+            -h) DST_H="$2"; shift 2 ;;
+            --full) FULL=1; shift ;;
+            --monitor) MONITOR="$2"; shift 2 ;;
+            --monitors) ACTION="monitors"; shift ;;
+            -r|--replace) REPLACE=1; shift ;;
+            --list) ACTION="list"; shift ;;
+            --remove)
+                ACTION="remove"
+                if [[ $# -ge 2 && "$2" != -* ]]; then ID="$2"; shift 2
+                else ID="screen"; shift; fi ;;
+            --remove-all) ACTION="remove-all"; shift ;;
+            *) echo "Unknown screen option: $1  (try --help)" >&2; exit 1 ;;
+        esac
+    done
+
+    # ── list / remove / monitors paths ──
+    if [[ "$ACTION" == "monitors" ]]; then
+        lines=$(detect_monitors)
+        if [[ -z "$lines" ]]; then
+            echo "No monitors detected." >&2; exit 1
+        fi
+        i=0
+        while IFS= read -r line; do
+            i=$((i+1))
+            read -r name mode x y <<< "$line"
+            printf "  %d) %-12s %s  at (%d,%d)\n" "$i" "$name" "$mode" "$x" "$y"
+        done <<< "$lines"
+        exit 0
+    fi
+
+    if [[ "$ACTION" == "list" ]]; then
+        ipc_send list | grep '\[screen\]' || echo "no screen overlays"
+        exit 0
+    fi
+    if [[ "$ACTION" == "remove" ]]; then
+        ipc_send "remove $ID"
+        exit 0
+    fi
+    if [[ "$ACTION" == "remove-all" ]]; then
+        ipc_send list | grep -oE '\[screen\] id=[^ ]+' | \
+            awk -F= '{print $2}' | while read -r oid; do
+                [[ -n "$oid" ]] && { echo "removing $oid"; ipc_send "remove $oid"; }
+            done
+        exit 0
+    fi
+
+    # ── add path ──
+    # Auto-pick a free ID if user didn't provide one
+    if [[ -z "$ID" ]]; then
+        EXISTING=$(ipc_send list 2>/dev/null | grep -oE 'id=[^ ]+' | awk -F= '{print $2}')
+        if ! echo "$EXISTING" | grep -qx "screen"; then
+            ID="screen"
+        else
+            i=2
+            while echo "$EXISTING" | grep -qx "screen$i"; do i=$((i+1)); done
+            ID="screen$i"
+        fi
+    fi
+
+    # Detect display server
+    if [[ -n "${WAYLAND_DISPLAY:-}" ]]; then DS="wayland"
+    elif [[ -n "${DISPLAY:-}" ]]; then       DS="x11"
+    else
+        echo "Error: neither WAYLAND_DISPLAY nor DISPLAY is set" >&2; exit 1
+    fi
+
+    # Obtain geometry
+    GEOMETRY=""
+    if [[ $FULL -eq 1 ]]; then
+        SEL=$(resolve_monitor "$MONITOR")
+        if [[ -z "$SEL" ]]; then
+            echo "Could not resolve monitor selection." >&2
+            echo "Run 'vcam-ctl screen --monitors' to list connected monitors." >&2
+            exit 1
+        fi
+        read -r MNAME MMODE MX MY <<< "$SEL"
+        GEOMETRY="${MMODE}+${MX}+${MY}"
+        echo "Full screen on $MNAME: $GEOMETRY"
+    else
+        echo "Select a screen region..." >&2
+        if [[ "$DS" == "wayland" ]]; then
+            command -v slurp >/dev/null || { echo "slurp not installed" >&2; exit 1; }
+            SLURP_RAW=$(slurp 2>/dev/null) || { echo "Cancelled." >&2; exit 1; }
+            SX=$(echo "$SLURP_RAW" | cut -d',' -f1)
+            SY=$(echo "$SLURP_RAW" | cut -d',' -f2 | cut -d' ' -f1)
+            SW=$(echo "$SLURP_RAW" | cut -d' ' -f2 | cut -d'x' -f1)
+            SH=$(echo "$SLURP_RAW" | cut -d' ' -f2 | cut -d'x' -f2)
+            GEOMETRY="${SW}x${SH}+${SX}+${SY}"
+        else
+            if command -v slop >/dev/null; then
+                GEOMETRY=$(slop -f "%wx%h+%x+%y" 2>/dev/null) || { echo "Cancelled." >&2; exit 1; }
+            else
+                echo "slop not installed. Enter geometry manually (WxH+X+Y):" >&2
+                read -r GEOMETRY
+            fi
+        fi
+        echo "Selected: $GEOMETRY" >&2
+    fi
+
+    if [[ $REPLACE -eq 1 ]]; then
+        echo "Removing existing overlay '$ID'..." >&2
+        ipc_send "remove $ID" >/dev/null || true
+    fi
+
+    ARGS="add screen $ID $DST_X $DST_Y"
+    if   [[ $DST_W -gt 0 && $DST_H -gt 0 ]]; then ARGS="$ARGS $DST_W $DST_H"
+    elif [[ $DST_W -gt 0 ]];                    then ARGS="$ARGS $DST_W"
+    elif [[ $DST_H -gt 0 ]];                    then ARGS="$ARGS 0 $DST_H"
+    fi
+    ARGS="$ARGS $GEOMETRY"
+
+    echo "Adding screen overlay '$ID'..." >&2
+    ipc_send $ARGS
+    echo "" >&2
+    echo "Screen overlay '$ID' is live." >&2
+    echo "  Remove:  vcam-ctl screen --remove $ID" >&2
+    echo "  Move:    vcam-ctl move   $ID <x|-> [<y|->]" >&2
+    echo "  Resize:  vcam-ctl resize $ID <w|-> [<h|->]" >&2
+    exit 0
+fi
+
+# ──────────────────────────────────────────────────────────────
+# webcam subcommand — add the webcam as a movable overlay
+# ──────────────────────────────────────────────────────────────
+# Useful in --no-input mode (or with a second camera) to show yourself
+# in the corner while screensharing. Internally the webcam is an
+# overlay just like images/videos, so move/resize/raise/lower work on
+# it identically.
+#
+# Usage:
+#   vcam-ctl webcam <position>     [width] [device]
+#   vcam-ctl webcam off
+#
+#   position: tl|tr|bl|br|center   (top/bottom × left/right, or center)
+#   width:    overlay width in px  (default 320; height auto from aspect)
+#   device:   /dev/video<N>         (default /dev/video1)
+#
+# Examples:
+#   vcam-ctl webcam tr             # 320-wide PiP in the top-right
+#   vcam-ctl webcam br 480         # bigger, bottom-right
+#   vcam-ctl webcam center         # centered on screen
+#   vcam-ctl webcam off            # remove the webcam overlay
+#
+# Default ID is "cam". To run multiple webcam overlays, add them with
+# the lower-level: vcam-ctl add webcam myid <x> <y> [<w>] <device>
+if [[ "$1" == "webcam" ]]; then
+    shift
+    require_running
+    POS="${1:-tr}"; WIDTH="${2:-320}"; ID="${3:-cam}"
+
+    if [[ "$POS" == "off" || "$POS" == "remove" ]]; then
+        ipc_send "remove $ID"
+        exit 0
+    fi
+
+    # Output frame size — needed to compute corner positions.
+    OUT="${VCAM_OUTPUT:-/dev/video0}"
+    OUT_SIZE=""
+    if command -v v4l2-ctl >/dev/null 2>&1; then
+        OUT_SIZE=$(v4l2-ctl -d "$OUT" --get-fmt-video 2>/dev/null \
+                   | awk -F'/' '/Width\/Height/{print $2}' | tr -d ' ')
+    fi
+    [[ "$OUT_SIZE" =~ ^[0-9]+x[0-9]+$ ]] || OUT_SIZE="1280x720"
+    OUT_W="${OUT_SIZE%x*}"; OUT_H="${OUT_SIZE#*x}"
+
+    # Webcam is 16:9 (height computed from width)
+    HEIGHT=$(( WIDTH * 9 / 16 ))
+    PAD=10
+    case "$POS" in
+        tl)     X=$PAD;                       Y=$PAD ;;
+        tr)     X=$(( OUT_W - WIDTH - PAD )); Y=$PAD ;;
+        bl)     X=$PAD;                       Y=$(( OUT_H - HEIGHT - PAD )) ;;
+        br)     X=$(( OUT_W - WIDTH - PAD )); Y=$(( OUT_H - HEIGHT - PAD )) ;;
+        center) X=$(( (OUT_W - WIDTH) / 2 )); Y=$(( (OUT_H - HEIGHT) / 2 )) ;;
+        full)   X=0; Y=0; WIDTH=$OUT_W; HEIGHT=$OUT_H ;;
+        *) echo "Unknown position '$POS' (use tl|tr|bl|br|center|full|off)" >&2; exit 1 ;;
+    esac
+
+    # Replace any existing overlay with this ID
+    ipc_send "remove $ID" >/dev/null 2>&1 || true
+    echo "Adding webcam overlay '$ID' at $POS (${X},${Y}) width=$WIDTH"
+    # The webcam overlay shares the main pipeline's capture; pass "-" as
+    # the path argument since the type doesn't need one.
+    ipc_send "add webcam $ID $X $Y $WIDTH -"
+
+    echo ""
+    echo "Webcam overlay '$ID' is live. Tweak with:"
+    echo "  vcam-ctl move   $ID x=N y=N"
+    echo "  vcam-ctl resize $ID w=N"
+    echo "  vcam-ctl raise  $ID         # bring to top"
+    echo "  vcam-ctl lower  $ID         # send to bottom"
+    echo "  vcam-ctl z      $ID <N>     # explicit z-index"
+    echo "  vcam-ctl webcam off          # remove (if id was 'cam')"
+    exit 0
+fi
+
+# ── default: pass everything else straight to the IPC server ─
+ipc_send "$*"
diff --git a/scripts/vcam-setup b/scripts/vcam-setup
new file mode 100755
index 0000000..6a4be81
--- /dev/null
+++ b/scripts/vcam-setup
@@ -0,0 +1,221 @@
+#!/usr/bin/env bash
+# vcam-setup – diagnose and configure v4l2loopback for Chromium compatibility
+#
+# Chromium-based browsers pick the FIRST /dev/video* node by default.
+# If that's your real camera and vcam is using it, you get NotReadableError.
+# The fix is to make the v4l2loopback device sit at a LOWER video_nr than
+# the real camera.
+#
+# This script:
+#   - lists current video devices and analyses ordering
+#   - writes /etc/modprobe.d/vcam.conf with video_nr=0 + correct params
+#   - detects whether the system uses systemd, OpenRC, runit, or none of
+#     those, and gives you concrete next steps for YOUR init system
+#
+# Run with sudo to install.
+
+set -eu
+
+# ── help ─────────────────────────────────────────────────────
+if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
+    sed -n '/^# vcam-setup/,/^$/p' "$0" | sed 's/^# \?//'
+    echo "Usage:"
+    echo "  vcam-setup              show current state and diagnosis"
+    echo "  sudo vcam-setup --install    install /etc/modprobe.d/vcam.conf"
+    echo "  sudo vcam-setup --uninstall  remove it"
+    exit 0
+fi
+
+INIT_SYSTEM=""
+detect_init() {
+    if [[ -d /run/systemd/system ]]; then
+        INIT_SYSTEM="systemd"
+    elif command -v rc-status &>/dev/null && rc-status &>/dev/null; then
+        INIT_SYSTEM="openrc"
+    elif command -v sv &>/dev/null && [[ -d /etc/service || -d /var/service ]]; then
+        INIT_SYSTEM="runit"
+    elif [[ -d /etc/rc.d || -d /etc/init.d ]]; then
+        INIT_SYSTEM="sysv-or-bsd"
+    else
+        INIT_SYSTEM="unknown"
+    fi
+}
+
+list_devices() {
+    echo "── Current /dev/video* devices ─────────────────────────"
+    for dev in /dev/video*; do
+        [[ -e $dev ]] || continue
+        local name="" driver=""
+        if command -v v4l2-ctl &>/dev/null; then
+            name=$(v4l2-ctl -d "$dev" --info 2>/dev/null | \
+                   awk -F': ' '/Card type/ {print $2; exit}')
+            driver=$(v4l2-ctl -d "$dev" --info 2>/dev/null | \
+                     awk -F': ' '/Driver name/ {print $2; exit}')
+        fi
+        printf "  %-15s  %-25s  (driver: %s)\n" "$dev" "${name:-?}" "${driver:-?}"
+    done
+    echo ""
+}
+
+# ── show current state ───────────────────────────────────────
+list_devices
+detect_init
+
+LOOPBACK_DEV=""
+REAL_CAMS=()
+for dev in /dev/video*; do
+    [[ -e $dev ]] || continue
+    if command -v v4l2-ctl &>/dev/null; then
+        driver=$(v4l2-ctl -d "$dev" --info 2>/dev/null | \
+                 awk -F': ' '/Driver name/ {print $2; exit}')
+        if [[ "$driver" == "v4l2 loopback" ]]; then
+            LOOPBACK_DEV="$dev"
+        elif [[ -n "$driver" ]]; then
+            REAL_CAMS+=("$dev")
+        fi
+    fi
+done
+
+# ── analysis ─────────────────────────────────────────────────
+echo "── Analysis ────────────────────────────────────────────"
+echo "  Init system : $INIT_SYSTEM"
+if [[ -z "$LOOPBACK_DEV" ]]; then
+    echo "  Loopback    : NOT FOUND"
+else
+    echo "  Loopback    : $LOOPBACK_DEV"
+fi
+if [[ ${#REAL_CAMS[@]} -eq 0 ]]; then
+    echo "  Real cam    : NOT FOUND"
+else
+    echo "  Real cam(s) : ${REAL_CAMS[*]}"
+fi
+echo ""
+
+if [[ -n "$LOOPBACK_DEV" && ${#REAL_CAMS[@]} -gt 0 ]]; then
+    loopback_nr=${LOOPBACK_DEV#/dev/video}
+    # Find the lowest-numbered real cam
+    lowest_real=999
+    for rc in "${REAL_CAMS[@]}"; do
+        n=${rc#/dev/video}
+        (( n < lowest_real )) && lowest_real=$n
+    done
+    echo "── Chromium compatibility ──────────────────────────────"
+    if (( loopback_nr < lowest_real )); then
+        echo "  OK — loopback at $LOOPBACK_DEV comes before real cam at /dev/video$lowest_real"
+        echo "  Chromium should pick the loopback by default."
+    else
+        echo "  PROBLEM — loopback ($LOOPBACK_DEV) is AFTER real cam (/dev/video$lowest_real)"
+        echo "  Chromium will try /dev/video$lowest_real first → NotReadableError."
+        echo ""
+        echo "  To fix:  sudo $0 --install"
+    fi
+    echo ""
+fi
+
+# ── install ──────────────────────────────────────────────────
+if [[ "${1:-}" == "--install" ]]; then
+    if [[ $EUID -ne 0 ]]; then
+        echo "Error: --install requires root." >&2
+        exit 1
+    fi
+
+    # /etc/modprobe.d/ works regardless of init system — it's read by
+    # modprobe itself, not by an init system.
+    mkdir -p /etc/modprobe.d
+    cat > /etc/modprobe.d/vcam.conf <<MODPROBE
+# vcam virtual camera (v4l2loopback)
+# video_nr=0       claim /dev/video0 so Chromium picks it by default
+# card_label       human-readable name in browser camera lists
+# exclusive_caps=1 advertise only V4L2_CAP_VIDEO_CAPTURE — required for Firefox/Chromium
+# max_buffers=2    real-camera-like buffer count
+options v4l2loopback video_nr=0 card_label="vcam" exclusive_caps=1 max_buffers=2
+MODPROBE
+    echo "Wrote /etc/modprobe.d/vcam.conf"
+
+    # Also write systemd's modules-load.d if the directory exists, since
+    # it's harmless on other systems and helpful where systemd is present.
+    if [[ -d /etc/modules-load.d ]]; then
+        echo "v4l2loopback" > /etc/modules-load.d/vcam.conf
+        echo "Wrote /etc/modules-load.d/vcam.conf (systemd-style autoload)"
+    fi
+
+    echo ""
+    echo "── Init-system-specific next steps ─────────────────────"
+    case "$INIT_SYSTEM" in
+      systemd)
+        cat <<MSG
+  systemd: /etc/modules-load.d/vcam.conf already written above.
+  systemd will auto-load v4l2loopback at boot before USB devices.
+  To activate now without rebooting:
+      sudo modprobe -r uvcvideo
+      sudo modprobe -r v4l2loopback
+      sudo modprobe v4l2loopback
+      sudo modprobe uvcvideo
+MSG
+        ;;
+      openrc)
+        cat <<MSG
+  OpenRC: append the module name to the modules autoload list:
+      echo "v4l2loopback" | sudo tee -a /etc/conf.d/modules
+  Then to activate immediately:
+      sudo modprobe -r uvcvideo
+      sudo modprobe -r v4l2loopback
+      sudo modprobe v4l2loopback
+      sudo modprobe uvcvideo
+MSG
+        ;;
+      runit)
+        cat <<MSG
+  runit (e.g. Void Linux): add v4l2loopback to the kernel module loader:
+      echo "v4l2loopback" | sudo tee -a /etc/modules.d/vcam.conf
+  Some distros instead use /etc/modules — try both.
+  Activate immediately:
+      sudo modprobe -r uvcvideo
+      sudo modprobe -r v4l2loopback
+      sudo modprobe v4l2loopback
+      sudo modprobe uvcvideo
+MSG
+        ;;
+      *)
+        cat <<MSG
+  Manual / unknown init: load v4l2loopback at boot via whatever
+  mechanism you normally use (rc.local, /etc/modules, an init script,
+  etc.). The key requirement is that v4l2loopback is loaded BEFORE
+  the uvcvideo module / before USB cameras enumerate.
+
+  Activate immediately:
+      sudo modprobe -r uvcvideo
+      sudo modprobe -r v4l2loopback
+      sudo modprobe v4l2loopback
+      sudo modprobe uvcvideo
+
+  Or for a permanent setup on a manual init system, add this to your
+  boot script (e.g. /etc/rc.local) before any device setup:
+      modprobe v4l2loopback
+MSG
+        ;;
+    esac
+
+    echo ""
+    echo "After reloading the modules, run this script again to verify."
+    echo "Then start vcam with the new device numbers, e.g.:"
+    echo "    vcam -i /dev/video1 -o /dev/video0"
+    exit 0
+fi
+
+if [[ "${1:-}" == "--uninstall" ]]; then
+    if [[ $EUID -ne 0 ]]; then
+        echo "Error: --uninstall requires root." >&2
+        exit 1
+    fi
+    rm -f /etc/modprobe.d/vcam.conf
+    rm -f /etc/modules-load.d/vcam.conf 2>/dev/null || true
+    echo "Removed /etc/modprobe.d/vcam.conf"
+    echo "Reload modules or reboot to fully revert."
+    exit 0
+fi
+
+echo "Usage:"
+echo "  $0              show current state and diagnosis"
+echo "  sudo $0 --install    install /etc/modprobe.d/vcam.conf"
+echo "  sudo $0 --uninstall  remove it"
diff --git a/scripts/vcam-tune b/scripts/vcam-tune
new file mode 100755
index 0000000..54a6967
--- /dev/null
+++ b/scripts/vcam-tune
@@ -0,0 +1,303 @@
+#!/usr/bin/env bash
+#
+# vcam-tune – interactively adjust filter parameters with the keyboard.
+#
+# Three modes:
+#
+#   vcam-tune                  WALK MODE — navigate all active filters,
+#                              adjust each, remove or reset as you go.
+#
+#   vcam-tune <name> [<step>]  Add the named filter (with its default
+#                              parameter) and immediately dial it.
+#
+#   vcam-tune <index> [<step>] Dial an existing filter at the given
+#                              index (see 'vcam-ctl filter list').
+#
+# Keys (single-filter and walk mode):
+#   ↑ / k        increase current filter's parameter
+#   ↓ / j        decrease current filter's parameter
+#   r            reset current filter to its default value
+#   x            remove current filter and exit
+#   q / Esc      quit (filter stays at its current value)
+#
+# Walk-mode-only keys:
+#   → / l / Tab  next filter
+#   ← / h        previous filter
+
+set -eu
+
+SOCK="${VCAM_SOCK:-/tmp/vcam.sock}"
+
+# ── help ─────────────────────────────────────────────────────
+if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
+    sed -n '/^# vcam-tune/,/^$/p' "$0" | sed 's/^# \?//'
+    exit 0
+fi
+
+if [[ ! -S "$SOCK" ]]; then
+    echo "Error: vcam is not running (socket $SOCK not found)" >&2
+    exit 1
+fi
+
+# ── IPC helpers ──────────────────────────────────────────────
+ipc() {
+    printf '%s\nquit\n' "$*" | ncat -U "$SOCK" 2>/dev/null | head -1
+}
+ipc_lines() {
+    printf '%s\nquit\n' "$*" | ncat -U "$SOCK" 2>/dev/null
+}
+
+# Read current filter list as parallel arrays: NAMES[], PARAMS[]
+declare -a NAMES PARAMS DEFAULTS
+read_filters() {
+    NAMES=(); PARAMS=(); DEFAULTS=()
+    local lines name param
+    while IFS= read -r line; do
+        if [[ "$line" =~ ^OK\ ([0-9]+):\ ([a-z]+)\ param=([0-9.\-]+) ]]; then
+            local idx="${BASH_REMATCH[1]}"
+            name="${BASH_REMATCH[2]}"
+            param="${BASH_REMATCH[3]}"
+            NAMES[idx]="$name"
+            PARAMS[idx]="$param"
+        fi
+    done < <(ipc_lines "filter list")
+}
+
+# Sensible default step per filter type
+default_step() {
+    case "$1" in
+        blur|pixelate|posterize|chromashift|wave|painterly|vangogh) echo 1 ;;
+        kaleidoscope|picasso|voronoi|sine|modulo) echo 1 ;;
+        bitcrush) echo 1 ;;
+        cartoon|solarize) echo 5 ;;
+        brightness|contrast|swirl|rainbow) echo 0.1 ;;
+        vignette|glitch|dream|bloom|glow|pinch|bulge|modern|cyberpunk|romantic|xor|polar) echo 0.05 ;;
+        melt|popart|displace|ripple) echo 0.05 ;;
+        *) echo 0.1 ;;
+    esac
+}
+
+# Get the default parameter for a filter type by querying vcam.
+# We add a temp filter just to learn its default, then remove it.
+default_param_for() {
+    case "$1" in
+        pixelate) echo 8 ;;
+        blur) echo 2 ;;
+        vignette) echo 0.6 ;;
+        brightness) echo 1.2 ;;
+        contrast) echo 1.4 ;;
+        posterize) echo 4 ;;
+        chromashift) echo 5 ;;
+        glitch) echo 0.3 ;;
+        kaleidoscope) echo 6 ;;
+        swirl) echo 1 ;;
+        wave) echo 10 ;;
+        cartoon) echo 50 ;;
+        solarize) echo 128 ;;
+        rainbow) echo 1 ;;
+        dream|bloom|glow|pinch|bulge|modern|cyberpunk|romantic|polar) echo 0.5 ;;
+        painterly|vangogh) echo 3 ;;
+        picasso) echo 8 ;;
+        sine) echo 15 ;;
+        xor) echo 0.5 ;;
+        modulo) echo 64 ;;
+        voronoi) echo 20 ;;
+        bitcrush) echo 3 ;;
+        melt|displace|ripple) echo 0.5 ;;
+        popart) echo 1 ;;
+        *) echo 1 ;;
+    esac
+}
+
+# Portable float arithmetic
+calc() { awk "BEGIN { printf \"%g\", $1 }"; }
+
+# ── set a single parameter ───────────────────────────────────
+set_param() {
+    local index=$1 value=$2
+    local resp
+    resp=$(ipc "filter set $index $value")
+    if [[ "$resp" =~ ^OK ]]; then
+        PARAMS[index]="$value"
+        return 0
+    fi
+    return 1
+}
+
+# ── single-filter mode ───────────────────────────────────────
+if [[ $# -ge 1 ]]; then
+    ARG="$1"
+    STEP="${2:-}"
+
+    if [[ "$ARG" =~ ^[0-9]+$ ]]; then
+        # Dial existing filter at index
+        read_filters
+        INDEX="$ARG"
+        if [[ -z "${NAMES[INDEX]:-}" ]]; then
+            echo "No filter at index $INDEX" >&2; exit 1
+        fi
+        NAME="${NAMES[INDEX]}"
+        DEFAULT=$(default_param_for "$NAME")
+    else
+        # Add the filter, then dial it
+        NAME="$ARG"
+        RESP=$(ipc "filter add $NAME")
+        if [[ "$RESP" =~ ^ERR ]]; then
+            echo "$RESP" >&2; exit 1
+        fi
+        read_filters
+        INDEX=$((${#NAMES[@]} - 1))
+        DEFAULT=$(default_param_for "$NAME")
+    fi
+
+    [[ -z "$STEP" ]] && STEP=$(default_step "$NAME")
+    CURRENT="${PARAMS[INDEX]}"
+    REMOVE_ON_EXIT=0
+
+    stty_orig=$(stty -g)
+    trap 'stty "$stty_orig"; echo' EXIT
+    stty -echo -icanon time 0 min 1
+
+    echo "vcam-tune  '$NAME' (index $INDEX)   step=$STEP"
+    echo "  ↑/k=up  ↓/j=down  r=reset to $DEFAULT  q=quit  x=remove+quit"
+    echo ""
+
+    draw() { printf '\r\033[K  %s = %s  ' "$NAME" "$CURRENT"; }
+    draw
+
+    while :; do
+        IFS= read -rsn1 c
+        if [[ "$c" == $'\x1b' ]]; then
+            IFS= read -rsn1 -t 0.05 c2 || c2=""
+            [[ -z "$c2" ]] && break
+            if [[ "$c2" == "[" ]]; then
+                IFS= read -rsn1 c3
+                case "$c3" in
+                    A) set_param "$INDEX" "$(calc "$CURRENT + $STEP")" && CURRENT="${PARAMS[INDEX]}" ;;
+                    B) set_param "$INDEX" "$(calc "$CURRENT - $STEP")" && CURRENT="${PARAMS[INDEX]}" ;;
+                esac
+            fi
+        else
+            case "$c" in
+                k|K) set_param "$INDEX" "$(calc "$CURRENT + $STEP")" && CURRENT="${PARAMS[INDEX]}" ;;
+                j|J) set_param "$INDEX" "$(calc "$CURRENT - $STEP")" && CURRENT="${PARAMS[INDEX]}" ;;
+                r|R) set_param "$INDEX" "$DEFAULT" && CURRENT="${PARAMS[INDEX]}" ;;
+                q|Q) break ;;
+                x|X) REMOVE_ON_EXIT=1; break ;;
+            esac
+        fi
+        draw
+    done
+
+    stty "$stty_orig"
+    echo ""
+    if [[ "$REMOVE_ON_EXIT" == "1" ]]; then
+        ipc "filter remove $INDEX" >/dev/null
+        echo "Removed."
+    else
+        echo "Final value: $NAME = $CURRENT  (active at index $INDEX)"
+    fi
+    exit 0
+fi
+
+# ── walk mode ────────────────────────────────────────────────
+read_filters
+if [[ ${#NAMES[@]} -eq 0 ]]; then
+    echo "No filters active. Add some with 'vcam-ctl filter add <name>'." >&2
+    echo "Or pass a filter name to this tool: 'vcam-tune <name>'." >&2
+    exit 1
+fi
+
+CURRENT_IDX=0
+NUM_FILTERS=${#NAMES[@]}
+
+stty_orig=$(stty -g)
+trap 'stty "$stty_orig"; echo' EXIT
+stty -echo -icanon time 0 min 1
+
+echo "vcam-tune walk mode  —  $NUM_FILTERS active filter(s)"
+echo "  ↑/k=up  ↓/j=down  →/l/Tab=next  ←/h=prev  r=reset  x=remove  q=quit"
+echo ""
+
+draw() {
+    local idx=$CURRENT_IDX
+    printf '\r\033[K'
+    printf '[%d/%d]  ' $((idx + 1)) "$NUM_FILTERS"
+    for i in "${!NAMES[@]}"; do
+        if [[ $i -eq $idx ]]; then
+            printf '\033[1;36m▶ %s=%s \033[0m' "${NAMES[i]}" "${PARAMS[i]}"
+        else
+            printf '  %s=%s ' "${NAMES[i]}" "${PARAMS[i]}"
+        fi
+    done
+}
+draw
+
+while :; do
+    IFS= read -rsn1 c
+    if [[ "$c" == $'\x1b' ]]; then
+        IFS= read -rsn1 -t 0.05 c2 || c2=""
+        [[ -z "$c2" ]] && break  # plain Esc
+        if [[ "$c2" == "[" ]]; then
+            IFS= read -rsn1 c3
+            case "$c3" in
+                A) # up
+                    name="${NAMES[CURRENT_IDX]}"
+                    step=$(default_step "$name")
+                    set_param "$CURRENT_IDX" "$(calc "${PARAMS[CURRENT_IDX]} + $step")"
+                    ;;
+                B) # down
+                    name="${NAMES[CURRENT_IDX]}"
+                    step=$(default_step "$name")
+                    set_param "$CURRENT_IDX" "$(calc "${PARAMS[CURRENT_IDX]} - $step")"
+                    ;;
+                C) # right
+                    CURRENT_IDX=$(( (CURRENT_IDX + 1) % NUM_FILTERS )) ;;
+                D) # left
+                    CURRENT_IDX=$(( (CURRENT_IDX - 1 + NUM_FILTERS) % NUM_FILTERS )) ;;
+            esac
+        fi
+    else
+        case "$c" in
+            k|K)
+                name="${NAMES[CURRENT_IDX]}"
+                step=$(default_step "$name")
+                set_param "$CURRENT_IDX" "$(calc "${PARAMS[CURRENT_IDX]} + $step")"
+                ;;
+            j|J)
+                name="${NAMES[CURRENT_IDX]}"
+                step=$(default_step "$name")
+                set_param "$CURRENT_IDX" "$(calc "${PARAMS[CURRENT_IDX]} - $step")"
+                ;;
+            l|L|$'\t')
+                CURRENT_IDX=$(( (CURRENT_IDX + 1) % NUM_FILTERS )) ;;
+            h|H)
+                CURRENT_IDX=$(( (CURRENT_IDX - 1 + NUM_FILTERS) % NUM_FILTERS )) ;;
+            r|R)
+                name="${NAMES[CURRENT_IDX]}"
+                def=$(default_param_for "$name")
+                set_param "$CURRENT_IDX" "$def"
+                ;;
+            x|X)
+                ipc "filter remove $CURRENT_IDX" >/dev/null
+                read_filters
+                NUM_FILTERS=${#NAMES[@]}
+                if [[ $NUM_FILTERS -eq 0 ]]; then
+                    echo ""
+                    echo "All filters removed."
+                    exit 0
+                fi
+                if [[ $CURRENT_IDX -ge $NUM_FILTERS ]]; then
+                    CURRENT_IDX=$((NUM_FILTERS - 1))
+                fi
+                ;;
+            q|Q) break ;;
+        esac
+    fi
+    draw
+done
+
+stty "$stty_orig"
+echo ""
+echo "Done. Final filter chain:"
+ipc_lines "filter list" | grep "^OK [0-9]" | sed 's/^OK /  /'
diff --git a/src/capture.c b/src/capture.c
new file mode 100644
index 0000000..4a8f706
--- /dev/null
+++ b/src/capture.c
@@ -0,0 +1,399 @@
+#include "vcam.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <errno.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <linux/videodev2.h>
+
+#include <libavcodec/avcodec.h>
+#include <libavutil/imgutils.h>
+#include <libswscale/swscale.h>
+
+#define NUM_BUFS 4
+
+typedef struct {
+    void   *start;
+    size_t  length;
+} Buffer;
+
+struct V4L2Capture {
+    int    fd;
+    int    width, height;
+    int    fps;
+    __u32  pixfmt;            /* actual V4L2 pixel format we got */
+    Buffer bufs[NUM_BUFS];
+    int    nbuf;
+
+    /* For MJPG: a libavcodec MJPEG decoder */
+    AVCodecContext *mjpeg_ctx;
+    AVPacket       *mjpeg_pkt;
+    AVFrame        *mjpeg_frame;
+
+    /* swscale: source pixel format → BGR24 */
+    struct SwsContext *sws;
+    int    sws_src_fmt;       /* AV_PIX_FMT_* */
+    int    sws_src_w, sws_src_h; /* may differ from cap->width when MJPEG */
+};
+
+/* ── helpers ─────────────────────────────────── */
+static int xioctl(int fd, unsigned long req, void *arg)
+{
+    int r;
+    do { r = ioctl(fd, req, arg); } while (r == -1 && errno == EINTR);
+    return r;
+}
+
+static const char *fourcc(__u32 f)
+{
+    static char s[5];
+    s[0]= f      & 0xff;
+    s[1]=(f>> 8) & 0xff;
+    s[2]=(f>>16) & 0xff;
+    s[3]=(f>>24) & 0xff;
+    s[4]= 0;
+    return s;
+}
+
+/*
+ * Check whether the camera supports a given pixel format at a given
+ * resolution and ≥ target_fps. Returns true if supported.
+ */
+static bool format_supported(int fd, __u32 pixfmt, int w, int h, int target_fps)
+{
+    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++) {
+        if (fi.type == V4L2_FRMIVAL_TYPE_DISCRETE) {
+            int fps = fi.discrete.denominator /
+                      (fi.discrete.numerator ? fi.discrete.numerator : 1);
+            if (fps >= target_fps) return true;
+        }
+    }
+    return false;
+}
+
+/*
+ * Pick the best (pixfmt, w, h) combination for our purposes:
+ *   - Prefer the requested w/h if both are supported at ≥ target_fps
+ *   - Otherwise prefer the largest resolution that supports ≥ target_fps
+ *   - Prefer MJPG over YUYV for high resolutions (cameras usually support
+ *     higher fps in MJPG); prefer YUYV for low resolutions (no decode cost)
+ *
+ * Writes chosen format into *out_*.
+ */
+static bool pick_format(int fd, int req_w, int req_h, int target_fps,
+                         __u32 *out_fmt, int *out_w, int *out_h)
+{
+    /* Candidate pixel formats in our preference order */
+    const __u32 prefs[] = {
+        V4L2_PIX_FMT_MJPEG,   /* high-bandwidth, decoded via libavcodec     */
+        V4L2_PIX_FMT_YUYV,    /* universal, no decode                       */
+        V4L2_PIX_FMT_NV12,
+        V4L2_PIX_FMT_YUV420,
+        V4L2_PIX_FMT_BGR24,
+        V4L2_PIX_FMT_RGB24,
+    };
+    const size_t nprefs = sizeof prefs / sizeof prefs[0];
+
+    /* If a specific size was requested, try to honour it first */
+    if (req_w > 0 && req_h > 0) {
+        for (size_t i = 0; i < nprefs; i++) {
+            if (format_supported(fd, prefs[i], req_w, req_h, target_fps)) {
+                *out_fmt = prefs[i]; *out_w = req_w; *out_h = req_h;
+                return true;
+            }
+        }
+    }
+
+    /* Otherwise enumerate all (format, size) pairs and pick the largest
+     * resolution that meets target_fps, preferring MJPG. */
+    int best_w = 0, best_h = 0;
+    __u32 best_fmt = 0;
+    int best_score = -1;
+
+    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++) {
+        /* Skip formats we don't handle */
+        size_t pref_rank = nprefs;
+        for (size_t i = 0; i < nprefs; i++)
+            if (prefs[i] == fd_desc.pixelformat) { pref_rank = i; break; }
+        if (pref_rank == nprefs) continue;
+
+        struct v4l2_frmsizeenum fs = {0};
+        fs.pixel_format = fd_desc.pixelformat;
+        for (fs.index = 0;
+             xioctl(fd, VIDIOC_ENUM_FRAMESIZES, &fs) == 0;
+             fs.index++) {
+            if (fs.type != V4L2_FRMSIZE_TYPE_DISCRETE) continue;
+            int w = fs.discrete.width, h = fs.discrete.height;
+            if (!format_supported(fd, fd_desc.pixelformat, w, h, target_fps))
+                continue;
+            /* Score: pixel count, with a small bonus for MJPG so it wins ties */
+            int score = w * h - (int)pref_rank;
+            if (score > best_score) {
+                best_score = score;
+                best_w = w; best_h = h;
+                best_fmt = fd_desc.pixelformat;
+            }
+        }
+    }
+
+    if (best_score < 0) return false;
+    *out_fmt = best_fmt; *out_w = best_w; *out_h = best_h;
+    return true;
+}
+
+/* ── open ─────────────────────────────────────── */
+V4L2Capture *capture_open(const char *device,
+                           int *out_width, int *out_height, int *out_fps)
+{
+    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: open");
+        free(cap);
+        return NULL;
+    }
+
+    /* ── pick the best format/size for what was requested ── */
+    int target_fps = *out_fps > 0 ? *out_fps : 30;
+    __u32 chosen_fmt = 0;
+    int   chosen_w = 0, chosen_h = 0;
+
+    if (!pick_format(cap->fd, *out_width, *out_height, target_fps,
+                      &chosen_fmt, &chosen_w, &chosen_h)) {
+        /* Fallback: ask driver for whatever it has */
+        fprintf(stderr, "[capture] No suitable format found at ≥%d fps; "
+                        "using driver default\n", target_fps);
+        struct v4l2_format gf = {0};
+        gf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
+        if (xioctl(cap->fd, VIDIOC_G_FMT, &gf) < 0) {
+            perror("VIDIOC_G_FMT"); goto err;
+        }
+        chosen_fmt = gf.fmt.pix.pixelformat;
+        chosen_w   = gf.fmt.pix.width;
+        chosen_h   = gf.fmt.pix.height;
+    }
+
+    /* ── apply the chosen format ── */
+    struct v4l2_format fmt = {0};
+    fmt.type                = V4L2_BUF_TYPE_VIDEO_CAPTURE;
+    fmt.fmt.pix.width       = chosen_w;
+    fmt.fmt.pix.height      = chosen_h;
+    fmt.fmt.pix.pixelformat = chosen_fmt;
+    fmt.fmt.pix.field       = V4L2_FIELD_NONE;
+    if (xioctl(cap->fd, VIDIOC_S_FMT, &fmt) < 0) {
+        perror("VIDIOC_S_FMT");
+        goto err;
+    }
+
+    cap->width  = fmt.fmt.pix.width;
+    cap->height = fmt.fmt.pix.height;
+    cap->pixfmt = fmt.fmt.pix.pixelformat;
+
+    fprintf(stderr, "[capture] %s  %dx%d  fmt=%s\n",
+            device, cap->width, cap->height, fourcc(cap->pixfmt));
+
+    /* ── set frame rate ── */
+    struct v4l2_streamparm parm = {0};
+    parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
+    if (xioctl(cap->fd, VIDIOC_G_PARM, &parm) == 0 &&
+        parm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
+        parm.parm.capture.timeperframe.numerator   = 1;
+        parm.parm.capture.timeperframe.denominator = target_fps;
+        xioctl(cap->fd, VIDIOC_S_PARM, &parm);
+        xioctl(cap->fd, VIDIOC_G_PARM, &parm);
+        struct v4l2_fract *tf = &parm.parm.capture.timeperframe;
+        cap->fps = tf->denominator / (tf->numerator ? tf->numerator : 1);
+    }
+    if (cap->fps <= 0) cap->fps = target_fps;
+
+    /* ── mmap buffers ── */
+    struct v4l2_requestbuffers req = {0};
+    req.count  = NUM_BUFS;
+    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;
+    }
+    cap->nbuf = req.count;
+
+    for (int i = 0; i < cap->nbuf; i++) {
+        struct v4l2_buffer buf = {0};
+        buf.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE;
+        buf.memory = V4L2_MEMORY_MMAP;
+        buf.index  = i;
+        if (xioctl(cap->fd, VIDIOC_QUERYBUF, &buf) < 0) {
+            perror("VIDIOC_QUERYBUF"); goto err;
+        }
+        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;
+        }
+    }
+
+    for (int i = 0; i < cap->nbuf; i++) {
+        struct v4l2_buffer buf = {0};
+        buf.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE;
+        buf.memory = V4L2_MEMORY_MMAP;
+        buf.index  = i;
+        if (xioctl(cap->fd, VIDIOC_QBUF, &buf) < 0) {
+            perror("VIDIOC_QBUF"); goto err;
+        }
+    }
+
+    enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
+    if (xioctl(cap->fd, VIDIOC_STREAMON, &type) < 0) {
+        perror("VIDIOC_STREAMON"); goto err;
+    }
+
+    /* ── 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; }
+        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;
+        }
+        cap->mjpeg_pkt   = av_packet_alloc();
+        cap->mjpeg_frame = av_frame_alloc();
+        /* sws will be set lazily on first decoded frame since the decoder
+         * tells us the exact pixfmt (typically YUVJ420P or YUVJ422P) */
+        cap->sws = NULL;
+    } else {
+        /* Set up swscale directly from the V4L2 pixel format */
+        int avfmt;
+        switch (cap->pixfmt) {
+        case V4L2_PIX_FMT_YUYV:   avfmt = AV_PIX_FMT_YUYV422; break;
+        case V4L2_PIX_FMT_YUV420: avfmt = AV_PIX_FMT_YUV420P; break;
+        case V4L2_PIX_FMT_NV12:   avfmt = AV_PIX_FMT_NV12;    break;
+        case V4L2_PIX_FMT_BGR24:  avfmt = AV_PIX_FMT_BGR24;   break;
+        case V4L2_PIX_FMT_RGB24:  avfmt = AV_PIX_FMT_RGB24;   break;
+        default:
+            fprintf(stderr, "[capture] unsupported format %s\n", fourcc(cap->pixfmt));
+            goto err;
+        }
+        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;
+}
+
+/* ── read one frame ───────────────────────────── */
+bool capture_read(V4L2Capture *cap, Frame *out)
+{
+    fd_set fds;
+    FD_ZERO(&fds);
+    FD_SET(cap->fd, &fds);
+    struct timeval tv = { .tv_sec = 2 };
+    if (select(cap->fd + 1, &fds, NULL, NULL, &tv) <= 0)
+        return false;
+
+    struct v4l2_buffer buf = {0};
+    buf.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE;
+    buf.memory = V4L2_MEMORY_MMAP;
+    if (xioctl(cap->fd, VIDIOC_DQBUF, &buf) < 0) {
+        if (errno == EAGAIN) return false;
+        perror("VIDIOC_DQBUF");
+        return false;
+    }
+
+    bool ok = false;
+
+    if (cap->pixfmt == V4L2_PIX_FMT_MJPEG) {
+        /* Decode JPEG → AVFrame → BGR24 via swscale */
+        cap->mjpeg_pkt->data = cap->bufs[buf.index].start;
+        cap->mjpeg_pkt->size = buf.bytesused;
+
+        if (avcodec_send_packet(cap->mjpeg_ctx, cap->mjpeg_pkt) == 0 &&
+            avcodec_receive_frame(cap->mjpeg_ctx, cap->mjpeg_frame) == 0) {
+
+            /* Build/refresh swscale context if needed */
+            int src_fmt = cap->mjpeg_frame->format;
+            int src_w   = cap->mjpeg_frame->width;
+            int src_h   = cap->mjpeg_frame->height;
+            if (!cap->sws ||
+                cap->sws_src_fmt != src_fmt ||
+                cap->sws_src_w   != src_w ||
+                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,
+                                           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;
+        }
+    } 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 };
+
+        sws_scale(cap->sws, src, sl, 0, cap->height, dst, dl);
+        ok = true;
+    }
+
+    if (xioctl(cap->fd, VIDIOC_QBUF, &buf) < 0)
+        perror("VIDIOC_QBUF (re-enqueue)");
+
+    return ok;
+}
+
+/* ── close ──────────────────────────────────── */
+void capture_close(V4L2Capture *cap)
+{
+    if (!cap) return;
+    enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
+    xioctl(cap->fd, VIDIOC_STREAMOFF, &type);
+    for (int i = 0; i < cap->nbuf; i++)
+        munmap(cap->bufs[i].start, cap->bufs[i].length);
+    if (cap->sws) sws_freeContext(cap->sws);
+    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);
+    free(cap);
+}
diff --git a/src/filter.c b/src/filter.c
new file mode 100644
index 0000000..10b2ed9
--- /dev/null
+++ b/src/filter.c
@@ -0,0 +1,1387 @@
+/*
+ * filter.c – per-pixel effects applied to a BGR24 frame in place.
+ *
+ * All effects operate on the captured webcam frame BEFORE overlays are
+ * composited on top. The chain is mutex-protected so the IPC thread can
+ * modify it while the main loop is applying it.
+ */
+
+#include "vcam.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <math.h>
+
+/* ──────────────────────────────────────────────────────────────
+ * Name <-> type
+ * ────────────────────────────────────────────────────────────── */
+static const struct { const char *name; FilterType t; } NAMES[] = {
+    {"grayscale",   FX_GRAYSCALE},
+    {"gray",        FX_GRAYSCALE},
+    {"sepia",       FX_SEPIA},
+    {"invert",      FX_INVERT},
+    {"mirror",      FX_MIRROR},
+    {"flip",        FX_FLIP},
+    {"pixelate",    FX_PIXELATE},
+    {"blur",        FX_BLUR},
+    {"vignette",    FX_VIGNETTE},
+    {"brightness",  FX_BRIGHTNESS},
+    {"contrast",    FX_CONTRAST},
+    {"posterize",   FX_POSTERIZE},
+    {"edges",       FX_EDGES},
+    /* fancy */
+    {"chromashift", FX_CHROMASHIFT},
+    {"glitch",      FX_GLITCH},
+    {"kaleidoscope",FX_KALEIDOSCOPE},
+    {"swirl",       FX_SWIRL},
+    {"thermal",     FX_THERMAL},
+    {"oldfilm",     FX_OLDFILM},
+    {"wave",        FX_WAVE},
+    {"cartoon",     FX_CARTOON},
+    {"solarize",    FX_SOLARIZE},
+    {"rainbow",     FX_RAINBOW},
+    /* soft/painterly */
+    {"dream",       FX_DREAM},
+    {"bloom",       FX_BLOOM},
+    {"glow",        FX_GLOW},
+    {"pinch",       FX_PINCH},
+    {"bulge",       FX_BULGE},
+    {"painterly",   FX_PAINTERLY},
+    /* themed looks */
+    {"modern",      FX_MODERN},
+    {"cyberpunk",   FX_CYBERPUNK},
+    {"romantic",    FX_ROMANTIC},
+    {"vangogh",     FX_VANGOGH},
+    {"picasso",     FX_PICASSO},
+    /* mathematical */
+    {"sine",        FX_SINE},
+    {"xor",         FX_XOR},
+    {"modulo",      FX_MODULO},
+    {"polar",       FX_POLAR},
+    {"voronoi",     FX_VORONOI},
+    /* pixel-crazy */
+    {"bitcrush",    FX_BITCRUSH},
+    {"melt",        FX_MELT},
+    {"popart",      FX_POPART},
+    {"displace",    FX_DISPLACE},
+    {"ripple",      FX_RIPPLE},
+};
+
+FilterType filter_type_from_name(const char *name)
+{
+    if (!name) return FX_UNKNOWN;
+    for (size_t i = 0; i < sizeof NAMES / sizeof NAMES[0]; i++)
+        if (strcasecmp(NAMES[i].name, name) == 0)
+            return NAMES[i].t;
+    return FX_UNKNOWN;
+}
+
+const char *filter_type_to_name(FilterType t)
+{
+    for (size_t i = 0; i < sizeof NAMES / sizeof NAMES[0]; i++)
+        if (NAMES[i].t == t) return NAMES[i].name;
+    return "unknown";
+}
+
+float filter_default_param(FilterType t)
+{
+    switch (t) {
+    case FX_PIXELATE:    return 8.0f;
+    case FX_BLUR:        return 2.0f;
+    case FX_VIGNETTE:    return 0.6f;
+    case FX_BRIGHTNESS:  return 1.2f;
+    case FX_CONTRAST:    return 1.4f;
+    case FX_POSTERIZE:   return 4.0f;
+    case FX_CHROMASHIFT: return 5.0f;
+    case FX_GLITCH:      return 0.3f;
+    case FX_KALEIDOSCOPE:return 6.0f;
+    case FX_SWIRL:       return 1.0f;
+    case FX_WAVE:        return 10.0f;
+    case FX_CARTOON:     return 50.0f;
+    case FX_SOLARIZE:    return 128.0f;
+    case FX_RAINBOW:     return 1.0f;
+    case FX_DREAM:       return 0.5f;  /* glow strength 0..1 */
+    case FX_BLOOM:       return 0.6f;  /* bloom strength 0..1 */
+    case FX_GLOW:        return 0.4f;  /* glow intensity 0..1 */
+    case FX_PINCH:       return 0.5f;  /* pinch strength 0..1 */
+    case FX_BULGE:       return 0.5f;  /* bulge strength 0..1 */
+    case FX_PAINTERLY:   return 3.0f;  /* neighborhood radius */
+    case FX_MODERN:      return 0.7f;
+    case FX_CYBERPUNK:   return 0.7f;
+    case FX_ROMANTIC:    return 0.7f;
+    case FX_VANGOGH:     return 3.0f;
+    case FX_PICASSO:     return 8.0f;
+    case FX_SINE:        return 15.0f;
+    case FX_XOR:         return 0.5f;
+    case FX_MODULO:      return 64.0f;
+    case FX_POLAR:       return 0.7f;
+    case FX_VORONOI:     return 20.0f;
+    case FX_BITCRUSH:    return 3.0f;
+    case FX_MELT:        return 0.5f;
+    case FX_POPART:      return 1.0f;
+    case FX_DISPLACE:    return 0.5f;
+    case FX_RIPPLE:      return 0.5f;
+    default:             return 0.0f;
+    }
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * Chain management
+ * ────────────────────────────────────────────────────────────── */
+void filter_chain_init(FilterChain *fc)
+{
+    memset(fc, 0, sizeof *fc);
+    pthread_mutex_init(&fc->lock, NULL);
+}
+
+void filter_chain_destroy(FilterChain *fc)
+{
+    pthread_mutex_destroy(&fc->lock);
+}
+
+bool filter_chain_add(FilterChain *fc, FilterType t, float param)
+{
+    if (t == FX_UNKNOWN) return false;
+    pthread_mutex_lock(&fc->lock);
+    if (fc->count >= MAX_FILTERS) {
+        pthread_mutex_unlock(&fc->lock);
+        return false;
+    }
+    fc->filters[fc->count].type  = t;
+    fc->filters[fc->count].param = param;
+    fc->count++;
+    pthread_mutex_unlock(&fc->lock);
+    return true;
+}
+
+bool filter_chain_remove(FilterChain *fc, int index)
+{
+    pthread_mutex_lock(&fc->lock);
+    if (index < 0 || index >= fc->count) {
+        pthread_mutex_unlock(&fc->lock);
+        return false;
+    }
+    for (int i = index; i < fc->count - 1; i++)
+        fc->filters[i] = fc->filters[i+1];
+    fc->count--;
+    pthread_mutex_unlock(&fc->lock);
+    return true;
+}
+
+void filter_chain_clear(FilterChain *fc)
+{
+    pthread_mutex_lock(&fc->lock);
+    fc->count = 0;
+    pthread_mutex_unlock(&fc->lock);
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * Effect implementations
+ * All operate on BGR24 (3 bytes/pixel, byte order B,G,R).
+ * ────────────────────────────────────────────────────────────── */
+static inline uint8_t clamp_u8(int v)
+{
+    return v < 0 ? 0 : v > 255 ? 255 : (uint8_t)v;
+}
+
+static void fx_grayscale(Frame *f)
+{
+    int n = f->width * f->height;
+    uint8_t *p = f->data;
+    for (int i = 0; i < n; i++, p += 3) {
+        /* Rec.601 luma */
+        int y = (p[2] * 299 + p[1] * 587 + p[0] * 114) / 1000;
+        p[0] = p[1] = p[2] = (uint8_t)y;
+    }
+}
+
+static void fx_sepia(Frame *f)
+{
+    int n = f->width * f->height;
+    uint8_t *p = f->data;
+    for (int i = 0; i < n; i++, p += 3) {
+        int b = p[0], g = p[1], r = p[2];
+        int nr = (r * 393 + g * 769 + b * 189) / 1000;
+        int ng = (r * 349 + g * 686 + b * 168) / 1000;
+        int nb = (r * 272 + g * 534 + b * 131) / 1000;
+        p[0] = clamp_u8(nb);
+        p[1] = clamp_u8(ng);
+        p[2] = clamp_u8(nr);
+    }
+}
+
+static void fx_invert(Frame *f)
+{
+    int n = f->width * f->height * 3;
+    uint8_t *p = f->data;
+    for (int i = 0; i < n; i++) p[i] = 255 - p[i];
+}
+
+static void fx_mirror(Frame *f)
+{
+    /* horizontal flip in place */
+    for (int y = 0; y < f->height; y++) {
+        uint8_t *row = f->data + y * f->stride;
+        for (int x = 0; x < f->width / 2; x++) {
+            int x2 = f->width - 1 - x;
+            uint8_t tmp[3] = { row[x*3+0], row[x*3+1], row[x*3+2] };
+            row[x*3+0] = row[x2*3+0];
+            row[x*3+1] = row[x2*3+1];
+            row[x*3+2] = row[x2*3+2];
+            row[x2*3+0] = tmp[0];
+            row[x2*3+1] = tmp[1];
+            row[x2*3+2] = tmp[2];
+        }
+    }
+}
+
+static void fx_flip(Frame *f)
+{
+    /* vertical flip in place */
+    uint8_t *tmp = malloc(f->stride);
+    if (!tmp) return;
+    for (int y = 0; y < f->height / 2; y++) {
+        uint8_t *a = f->data + y * f->stride;
+        uint8_t *b = f->data + (f->height - 1 - y) * f->stride;
+        memcpy(tmp, a, f->stride);
+        memcpy(a,   b, f->stride);
+        memcpy(b, tmp, f->stride);
+    }
+    free(tmp);
+}
+
+static void fx_pixelate(Frame *f, int block)
+{
+    if (block < 2) block = 2;
+    if (block > f->width / 2) block = f->width / 2;
+    for (int by = 0; by < f->height; by += block) {
+        for (int bx = 0; bx < f->width; bx += block) {
+            /* Average colour of this block */
+            int bw = bx + block > f->width  ? f->width  - bx : block;
+            int bh = by + block > f->height ? f->height - by : block;
+            int sb = 0, sg = 0, sr = 0;
+            for (int dy = 0; dy < bh; dy++) {
+                uint8_t *p = f->data + (by+dy) * f->stride + bx * 3;
+                for (int dx = 0; dx < bw; dx++, p += 3) {
+                    sb += p[0]; sg += p[1]; sr += p[2];
+                }
+            }
+            int cnt = bw * bh;
+            uint8_t cb = sb / cnt, cg = sg / cnt, cr = sr / cnt;
+            for (int dy = 0; dy < bh; dy++) {
+                uint8_t *p = f->data + (by+dy) * f->stride + bx * 3;
+                for (int dx = 0; dx < bw; dx++, p += 3) {
+                    p[0] = cb; p[1] = cg; p[2] = cr;
+                }
+            }
+        }
+    }
+}
+
+static void fx_blur(Frame *f, int radius)
+{
+    /* Box blur via two 1D passes. radius=1 → 3-tap, radius=2 → 5-tap, etc. */
+    if (radius < 1) radius = 1;
+    if (radius > 6) radius = 6;
+    int w = f->width, h = f->height;
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+
+    /* Horizontal pass: f → tmp */
+    for (int y = 0; y < h; y++) {
+        const uint8_t *src = f->data + y * f->stride;
+        uint8_t *dst = tmp + y * w * 3;
+        for (int x = 0; x < w; x++) {
+            int sb = 0, sg = 0, sr = 0, n = 0;
+            int x0 = x - radius, x1 = x + radius;
+            if (x0 < 0) x0 = 0;
+            if (x1 >= w) x1 = w - 1;
+            for (int xx = x0; xx <= x1; xx++) {
+                sb += src[xx*3+0]; sg += src[xx*3+1]; sr += src[xx*3+2]; n++;
+            }
+            dst[x*3+0] = sb / n; dst[x*3+1] = sg / n; dst[x*3+2] = sr / n;
+        }
+    }
+    /* Vertical pass: tmp → f */
+    for (int x = 0; x < w; x++) {
+        for (int y = 0; y < h; y++) {
+            int sb = 0, sg = 0, sr = 0, n = 0;
+            int y0 = y - radius, y1 = y + radius;
+            if (y0 < 0) y0 = 0;
+            if (y1 >= h) y1 = h - 1;
+            for (int yy = y0; yy <= y1; yy++) {
+                uint8_t *s = tmp + yy * w * 3 + x * 3;
+                sb += s[0]; sg += s[1]; sr += s[2]; n++;
+            }
+            uint8_t *d = f->data + y * f->stride + x * 3;
+            d[0] = sb / n; d[1] = sg / n; d[2] = sr / n;
+        }
+    }
+    free(tmp);
+}
+
+static void fx_vignette(Frame *f, float strength)
+{
+    if (strength < 0) strength = 0;
+    if (strength > 1) strength = 1;
+    int w = f->width, h = f->height;
+    float cx = w / 2.0f, cy = h / 2.0f;
+    float maxd = sqrtf(cx*cx + cy*cy);
+    for (int y = 0; y < h; y++) {
+        uint8_t *p = f->data + y * f->stride;
+        for (int x = 0; x < w; x++, p += 3) {
+            float dx = x - cx, dy = y - cy;
+            float d = sqrtf(dx*dx + dy*dy) / maxd;
+            float v = 1.0f - strength * d * d;
+            if (v < 0) v = 0;
+            p[0] = (uint8_t)(p[0] * v);
+            p[1] = (uint8_t)(p[1] * v);
+            p[2] = (uint8_t)(p[2] * v);
+        }
+    }
+}
+
+static void fx_brightness(Frame *f, float mult)
+{
+    int n = f->width * f->height * 3;
+    uint8_t *p = f->data;
+    for (int i = 0; i < n; i++)
+        p[i] = clamp_u8((int)(p[i] * mult));
+}
+
+static void fx_contrast(Frame *f, float mult)
+{
+    int n = f->width * f->height * 3;
+    uint8_t *p = f->data;
+    for (int i = 0; i < n; i++)
+        p[i] = clamp_u8((int)((p[i] - 128) * mult + 128));
+}
+
+static void fx_posterize(Frame *f, int levels)
+{
+    if (levels < 2) levels = 2;
+    if (levels > 16) levels = 16;
+    int step = 256 / levels;
+    int n = f->width * f->height * 3;
+    uint8_t *p = f->data;
+    for (int i = 0; i < n; i++)
+        p[i] = (uint8_t)((p[i] / step) * step);
+}
+
+static void fx_edges(Frame *f)
+{
+    /* Simple Sobel on luma */
+    int w = f->width, h = f->height;
+    uint8_t *luma = malloc((size_t)w * h);
+    if (!luma) return;
+    for (int y = 0; y < h; y++) {
+        const uint8_t *src = f->data + y * f->stride;
+        for (int x = 0; x < w; x++) {
+            luma[y*w + x] = (src[x*3+2]*299 + src[x*3+1]*587 + src[x*3+0]*114) / 1000;
+        }
+    }
+    for (int y = 1; y < h - 1; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        for (int x = 1; x < w - 1; x++) {
+            int gx = -luma[(y-1)*w + (x-1)] - 2*luma[y*w + (x-1)] - luma[(y+1)*w + (x-1)]
+                     +luma[(y-1)*w + (x+1)] + 2*luma[y*w + (x+1)] + luma[(y+1)*w + (x+1)];
+            int gy = -luma[(y-1)*w + (x-1)] - 2*luma[(y-1)*w + x] - luma[(y-1)*w + (x+1)]
+                     +luma[(y+1)*w + (x-1)] + 2*luma[(y+1)*w + x] + luma[(y+1)*w + (x+1)];
+            int v = abs(gx) + abs(gy);
+            uint8_t e = clamp_u8(v);
+            dst[x*3+0] = dst[x*3+1] = dst[x*3+2] = e;
+        }
+    }
+    /* Zero out the 1-pixel border for cleanliness */
+    memset(f->data, 0, f->stride);
+    memset(f->data + (h-1) * f->stride, 0, f->stride);
+    free(luma);
+}
+
+/* ══════════════════════════════════════════════════════════════
+ * Fancy effects
+ * ══════════════════════════════════════════════════════════════ */
+
+/* A monotonically increasing tick — drives animated effects */
+static unsigned long anim_tick(void)
+{
+    static unsigned long t = 0;
+    return t++;
+}
+
+/* Cheap pseudo-random for animation. Not crypto-grade, just chaotic. */
+static unsigned hash_u(unsigned x)
+{
+    x ^= x << 13; x ^= x >> 17; x ^= x << 5; return x;
+}
+
+/* ── chromashift: VHS-style RGB channel separation ──────────── */
+static void fx_chromashift(Frame *f, int dx)
+{
+    if (dx == 0) return;
+    int w = f->width, h = f->height;
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+    memcpy(tmp, f->data, (size_t)w * h * 3);
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        const uint8_t *src = tmp + y * w * 3;
+        for (int x = 0; x < w; x++) {
+            int xr = x + dx;  if (xr < 0) xr = 0;  if (xr >= w) xr = w - 1;
+            int xb = x - dx;  if (xb < 0) xb = 0;  if (xb >= w) xb = w - 1;
+            dst[x*3+0] = src[xb*3+0]; /* B from xb */
+            dst[x*3+1] = src[x*3+1];  /* G stays   */
+            dst[x*3+2] = src[xr*3+2]; /* R from xr */
+        }
+    }
+    free(tmp);
+}
+
+/* ── glitch: random horizontal slice displacement (animated) ── */
+static void fx_glitch(Frame *f, float intensity)
+{
+    if (intensity <= 0) return;
+    if (intensity > 1) intensity = 1;
+    int w = f->width, h = f->height;
+    unsigned seed = (unsigned)anim_tick();
+
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+    memcpy(tmp, f->data, (size_t)w * h * 3);
+
+    int slice_h = 4 + (int)((1.0f - intensity) * 20);
+    int max_shift = (int)(w * 0.15f * intensity);
+
+    for (int y = 0; y < h; y += slice_h) {
+        unsigned r = hash_u(seed + (unsigned)y);
+        if ((r & 7) > 5) continue; /* only ~25% of slices shift */
+        int shift = (int)((r >> 4) % (unsigned)(2 * max_shift + 1)) - max_shift;
+        int sh = (y + slice_h > h) ? h - y : slice_h;
+        for (int dy = 0; dy < sh; dy++) {
+            uint8_t *dst = f->data + (y+dy) * f->stride;
+            const uint8_t *src = tmp + (y+dy) * w * 3;
+            for (int x = 0; x < w; x++) {
+                int sx = x - shift;
+                if (sx < 0) sx += w;
+                if (sx >= w) sx -= w;
+                dst[x*3+0] = src[sx*3+0];
+                dst[x*3+1] = src[sx*3+1];
+                dst[x*3+2] = src[sx*3+2];
+            }
+        }
+    }
+    free(tmp);
+}
+
+/* ── kaleidoscope: mirror a wedge around the center ─────────── */
+static void fx_kaleidoscope(Frame *f, int segments)
+{
+    if (segments < 2) segments = 2;
+    if (segments > 32) segments = 32;
+    int w = f->width, h = f->height;
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+    memcpy(tmp, f->data, (size_t)w * h * 3);
+
+    float cx = w / 2.0f, cy = h / 2.0f;
+    float wedge = (float)(3.14159265358979f * 2.0f) / segments;
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        for (int x = 0; x < w; x++) {
+            float dx = x - cx, dy = y - cy;
+            float r = sqrtf(dx*dx + dy*dy);
+            float a = atan2f(dy, dx);
+            /* fold angle into one wedge then mirror */
+            float m = fmodf(a, wedge);
+            if (m < 0) m += wedge;
+            if (m > wedge / 2) m = wedge - m;
+            int sx = (int)(cx + r * cosf(m));
+            int sy = (int)(cy + r * sinf(m));
+            if (sx < 0) sx = 0;
+            if (sx >= w) sx = w - 1;
+            if (sy < 0) sy = 0;
+            if (sy >= h) sy = h - 1;
+            const uint8_t *src = tmp + sy * w * 3 + sx * 3;
+            dst[x*3+0] = src[0]; dst[x*3+1] = src[1]; dst[x*3+2] = src[2];
+        }
+    }
+    free(tmp);
+}
+
+/* ── swirl: radial rotation that intensifies with distance ── */
+static void fx_swirl(Frame *f, float strength)
+{
+    int w = f->width, h = f->height;
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+    memcpy(tmp, f->data, (size_t)w * h * 3);
+
+    float cx = w / 2.0f, cy = h / 2.0f;
+    float maxr = sqrtf(cx*cx + cy*cy);
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        for (int x = 0; x < w; x++) {
+            float dx = x - cx, dy = y - cy;
+            float r = sqrtf(dx*dx + dy*dy);
+            float theta = atan2f(dy, dx) + strength * (1.0f - r / maxr) * 3.14159f;
+            int sx = (int)(cx + r * cosf(theta));
+            int sy = (int)(cy + r * sinf(theta));
+            if (sx < 0 || sx >= w || sy < 0 || sy >= h) {
+                dst[x*3+0] = dst[x*3+1] = dst[x*3+2] = 0;
+            } else {
+                const uint8_t *src = tmp + sy * w * 3 + sx * 3;
+                dst[x*3+0] = src[0]; dst[x*3+1] = src[1]; dst[x*3+2] = src[2];
+            }
+        }
+    }
+    free(tmp);
+}
+
+/* ── thermal: map luma to a heatmap palette ─────────────────── */
+static void fx_thermal(Frame *f)
+{
+    /* black → blue → purple → red → orange → yellow → white */
+    int n = f->width * f->height;
+    uint8_t *p = f->data;
+    for (int i = 0; i < n; i++, p += 3) {
+        int y = (p[2] * 299 + p[1] * 587 + p[0] * 114) / 1000;
+        int b, g, r;
+        if (y < 51) {        /* 0-50: black → blue */
+            float t = y / 51.0f;
+            b = (int)(t * 255); g = 0; r = 0;
+        } else if (y < 102) { /* 51-101: blue → purple */
+            float t = (y - 51) / 51.0f;
+            b = 255; g = 0; r = (int)(t * 128);
+        } else if (y < 153) { /* 102-152: purple → red */
+            float t = (y - 102) / 51.0f;
+            b = (int)((1 - t) * 255); g = 0; r = (int)(128 + t * 127);
+        } else if (y < 204) { /* 153-203: red → orange */
+            float t = (y - 153) / 51.0f;
+            b = 0; g = (int)(t * 128); r = 255;
+        } else {              /* 204-255: orange → yellow → white */
+            float t = (y - 204) / 51.0f;
+            b = (int)(t * 255); g = (int)(128 + t * 127); r = 255;
+        }
+        p[0] = (uint8_t)b; p[1] = (uint8_t)g; p[2] = (uint8_t)r;
+    }
+}
+
+/* ── oldfilm: sepia + grain + vertical scratches + vignette ── */
+static void fx_oldfilm(Frame *f)
+{
+    int w = f->width, h = f->height;
+    unsigned seed = (unsigned)anim_tick();
+
+    /* sepia */
+    fx_sepia(f);
+
+    /* film grain */
+    for (int y = 0; y < h; y++) {
+        uint8_t *p = f->data + y * f->stride;
+        for (int x = 0; x < w; x++, p += 3) {
+            int g = (int)(hash_u(seed + (unsigned)(y * w + x)) % 41) - 20;
+            p[0] = clamp_u8(p[0] + g);
+            p[1] = clamp_u8(p[1] + g);
+            p[2] = clamp_u8(p[2] + g);
+        }
+    }
+
+    /* occasional vertical scratch lines */
+    int scratches = (int)(hash_u(seed) % 4);
+    for (int s = 0; s < scratches; s++) {
+        int x = (int)(hash_u(seed + 17 + (unsigned)s) % (unsigned)w);
+        for (int y = 0; y < h; y++) {
+            uint8_t *p = f->data + y * f->stride + x * 3;
+            p[0] = p[1] = p[2] = 240;
+        }
+    }
+
+    /* vignette */
+    fx_vignette(f, 0.7f);
+}
+
+/* ── wave: sinusoidal vertical wave displacement ────────────── */
+static void fx_wave(Frame *f, float amplitude)
+{
+    if (amplitude < 1) amplitude = 1;
+    int w = f->width, h = f->height;
+    unsigned long t = anim_tick();
+    float phase = (t * 0.1f);
+
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+    memcpy(tmp, f->data, (size_t)w * h * 3);
+
+    for (int y = 0; y < h; y++) {
+        int shift = (int)(amplitude * sinf(y * 0.05f + phase));
+        uint8_t *dst = f->data + y * f->stride;
+        const uint8_t *src = tmp + y * w * 3;
+        for (int x = 0; x < w; x++) {
+            int sx = x - shift;
+            if (sx < 0) sx = 0;
+            if (sx >= w) sx = w - 1;
+            dst[x*3+0] = src[sx*3+0];
+            dst[x*3+1] = src[sx*3+1];
+            dst[x*3+2] = src[sx*3+2];
+        }
+    }
+    free(tmp);
+}
+
+/* ── cartoon: posterize + emphasize edges ───────────────────── */
+static void fx_cartoon(Frame *f, float edge_thresh)
+{
+    int w = f->width, h = f->height;
+
+    /* Compute luma + Sobel magnitude */
+    uint8_t *luma = malloc((size_t)w * h);
+    if (!luma) return;
+    for (int y = 0; y < h; y++) {
+        const uint8_t *src = f->data + y * f->stride;
+        for (int x = 0; x < w; x++)
+            luma[y*w + x] = (src[x*3+2]*299 + src[x*3+1]*587 + src[x*3+0]*114) / 1000;
+    }
+
+    /* Posterize colors to 5 levels */
+    int step = 256 / 5;
+    int n = w * h * 3;
+    uint8_t *p = f->data;
+    for (int i = 0; i < n; i++) p[i] = (uint8_t)((p[i] / step) * step + step/2);
+
+    /* Black-out strong edges */
+    for (int y = 1; y < h - 1; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        for (int x = 1; x < w - 1; x++) {
+            int gx = -luma[(y-1)*w + (x-1)] - 2*luma[y*w + (x-1)] - luma[(y+1)*w + (x-1)]
+                     +luma[(y-1)*w + (x+1)] + 2*luma[y*w + (x+1)] + luma[(y+1)*w + (x+1)];
+            int gy = -luma[(y-1)*w + (x-1)] - 2*luma[(y-1)*w + x] - luma[(y-1)*w + (x+1)]
+                     +luma[(y+1)*w + (x-1)] + 2*luma[(y+1)*w + x] + luma[(y+1)*w + (x+1)];
+            if (abs(gx) + abs(gy) > edge_thresh)
+                dst[x*3+0] = dst[x*3+1] = dst[x*3+2] = 0;
+        }
+    }
+    free(luma);
+}
+
+/* ── solarize: invert pixels above threshold ────────────────── */
+static void fx_solarize(Frame *f, int threshold)
+{
+    int n = f->width * f->height * 3;
+    uint8_t *p = f->data;
+    for (int i = 0; i < n; i++)
+        if (p[i] > threshold) p[i] = 255 - p[i];
+}
+
+/* ── rainbow: animated additive hue rotation ────────────────── */
+static void fx_rainbow(Frame *f, float speed)
+{
+    unsigned long t = anim_tick();
+    /* Three offset sinusoids → smooth rainbow rotation per pixel */
+    float phase = t * 0.04f * speed;
+    int n = f->width * f->height;
+    uint8_t *p = f->data;
+    for (int i = 0; i < n; i++, p += 3) {
+        float y = (p[2]*299 + p[1]*587 + p[0]*114) / 1000.0f;
+        /* Add color back based on phase + position */
+        float sx = (i % f->width) * 0.01f;
+        float sy = (i / f->width) * 0.01f;
+        float a = phase + sx * 0.5f + sy * 0.3f;
+        int r = (int)(y * (0.5f + 0.5f * sinf(a)));
+        int g = (int)(y * (0.5f + 0.5f * sinf(a + 2.094f))); /* +120° */
+        int b = (int)(y * (0.5f + 0.5f * sinf(a + 4.189f))); /* +240° */
+        p[0] = clamp_u8(b);
+        p[1] = clamp_u8(g);
+        p[2] = clamp_u8(r);
+    }
+}
+
+/* ══════════════════════════════════════════════════════════════
+ * Soft / dreamy / painterly effects
+ * ══════════════════════════════════════════════════════════════ */
+
+/* Box-blur helper into a separate buffer. Used by glow effects so we
+ * don't lose the original image (unlike fx_blur which is in-place). */
+static void box_blur_into(const uint8_t *src, uint8_t *dst,
+                          int w, int h, int radius)
+{
+    if (radius < 1) radius = 1;
+    if (radius > 8) radius = 8;
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+
+    /* horizontal pass: src → tmp */
+    for (int y = 0; y < h; y++) {
+        for (int x = 0; x < w; x++) {
+            int sb=0, sg=0, sr=0, n=0;
+            int x0 = x - radius, x1 = x + radius;
+            if (x0 < 0) x0 = 0;
+            if (x1 >= w) x1 = w - 1;
+            for (int xx = x0; xx <= x1; xx++) {
+                const uint8_t *s = src + y * w * 3 + xx * 3;
+                sb += s[0]; sg += s[1]; sr += s[2]; n++;
+            }
+            uint8_t *t = tmp + y * w * 3 + x * 3;
+            t[0] = sb/n; t[1] = sg/n; t[2] = sr/n;
+        }
+    }
+    /* vertical pass: tmp → dst */
+    for (int x = 0; x < w; x++) {
+        for (int y = 0; y < h; y++) {
+            int sb=0, sg=0, sr=0, n=0;
+            int y0 = y - radius, y1 = y + radius;
+            if (y0 < 0) y0 = 0;
+            if (y1 >= h) y1 = h - 1;
+            for (int yy = y0; yy <= y1; yy++) {
+                const uint8_t *s = tmp + yy * w * 3 + x * 3;
+                sb += s[0]; sg += s[1]; sr += s[2]; n++;
+            }
+            uint8_t *d = dst + y * w * 3 + x * 3;
+            d[0] = sb/n; d[1] = sg/n; d[2] = sr/n;
+        }
+    }
+    free(tmp);
+}
+
+/* ── dream: heavy blur layered over original ─────────────────── */
+static void fx_dream(Frame *f, float strength)
+{
+    if (strength < 0) strength = 0;
+    if (strength > 1) strength = 1;
+    int w = f->width, h = f->height;
+    uint8_t *blur = malloc((size_t)w * h * 3);
+    if (!blur) return;
+    box_blur_into(f->data, blur, w, h, 6);
+
+    /* dst = (1-s)*orig + s*blur, then bias brightness up */
+    int total = w * h * 3;
+    uint8_t *p = f->data;
+    for (int i = 0; i < total; i++) {
+        int v = (int)((1.0f - strength) * p[i] + strength * blur[i]);
+        v += (int)(strength * 25); /* gentle brightness lift */
+        p[i] = clamp_u8(v);
+    }
+    free(blur);
+}
+
+/* ── bloom: extract bright pixels, blur, add back ────────────── */
+static void fx_bloom(Frame *f, float strength)
+{
+    if (strength < 0) strength = 0;
+    if (strength > 1) strength = 1;
+    int w = f->width, h = f->height;
+
+    /* extract highlights into a buffer (everything above threshold) */
+    uint8_t *hi = malloc((size_t)w * h * 3);
+    if (!hi) return;
+    const int thresh = 180;
+    int total = w * h * 3;
+    for (int i = 0; i < total; i++)
+        hi[i] = f->data[i] > thresh ? (uint8_t)(f->data[i] - thresh) * 2 : 0;
+
+    /* blur the highlights */
+    uint8_t *bloom = malloc((size_t)w * h * 3);
+    if (!bloom) { free(hi); return; }
+    box_blur_into(hi, bloom, w, h, 6);
+    free(hi);
+
+    /* add bloom on top of the original (screen blend-ish) */
+    for (int i = 0; i < total; i++) {
+        int v = f->data[i] + (int)(bloom[i] * strength);
+        f->data[i] = clamp_u8(v);
+    }
+    free(bloom);
+}
+
+/* ── glow: uniform gaussian-like haze over the whole image ──── */
+static void fx_glow(Frame *f, float intensity)
+{
+    if (intensity < 0) intensity = 0;
+    if (intensity > 1) intensity = 1;
+    int w = f->width, h = f->height;
+    uint8_t *blur = malloc((size_t)w * h * 3);
+    if (!blur) return;
+    box_blur_into(f->data, blur, w, h, 4);
+
+    /* Screen blend: 1 - (1-a)*(1-b) — softens highlights, lifts mids */
+    int total = w * h * 3;
+    for (int i = 0; i < total; i++) {
+        int a = f->data[i];
+        int b = (int)(blur[i] * intensity);
+        int v = 255 - ((255 - a) * (255 - b)) / 255;
+        f->data[i] = clamp_u8(v);
+    }
+    free(blur);
+}
+
+/* ── pinch: inward radial pull (subtle anamorphic squeeze) ──── */
+static void fx_pinch(Frame *f, float strength)
+{
+    int w = f->width, h = f->height;
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+    memcpy(tmp, f->data, (size_t)w * h * 3);
+
+    float cx = w / 2.0f, cy = h / 2.0f;
+    float maxr = sqrtf(cx*cx + cy*cy);
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        for (int x = 0; x < w; x++) {
+            float dx = x - cx, dy = y - cy;
+            float r = sqrtf(dx*dx + dy*dy) / maxr; /* 0..1 */
+            /* Pinch curve: pull r toward 0 by exponentiating */
+            float scaled = powf(r, 1.0f + strength);
+            float factor = (r > 0.001f) ? (scaled / r) : 1.0f;
+            int sx = (int)(cx + dx * factor);
+            int sy = (int)(cy + dy * factor);
+            if (sx < 0 || sx >= w || sy < 0 || sy >= h) {
+                dst[x*3+0] = dst[x*3+1] = dst[x*3+2] = 0;
+            } else {
+                const uint8_t *src = tmp + sy * w * 3 + sx * 3;
+                dst[x*3+0] = src[0]; dst[x*3+1] = src[1]; dst[x*3+2] = src[2];
+            }
+        }
+    }
+    free(tmp);
+}
+
+/* ── bulge: outward radial push (fisheye-like) ──────────────── */
+static void fx_bulge(Frame *f, float strength)
+{
+    int w = f->width, h = f->height;
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+    memcpy(tmp, f->data, (size_t)w * h * 3);
+
+    float cx = w / 2.0f, cy = h / 2.0f;
+    float maxr = sqrtf(cx*cx + cy*cy);
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        for (int x = 0; x < w; x++) {
+            float dx = x - cx, dy = y - cy;
+            float r = sqrtf(dx*dx + dy*dy) / maxr;
+            /* Bulge: push r away from 0 — sample from nearer */
+            float scaled = powf(r, 1.0f / (1.0f + strength));
+            float factor = (r > 0.001f) ? (scaled / r) : 1.0f;
+            int sx = (int)(cx + dx * factor);
+            int sy = (int)(cy + dy * factor);
+            if (sx < 0) sx = 0;
+            if (sx >= w) sx = w-1;
+            if (sy < 0) sy = 0;
+            if (sy >= h) sy = h-1;
+            const uint8_t *src = tmp + sy * w * 3 + sx * 3;
+            dst[x*3+0] = src[0]; dst[x*3+1] = src[1]; dst[x*3+2] = src[2];
+        }
+    }
+    free(tmp);
+}
+
+/* ── painterly: oil-painting via dominant color in neighborhood
+ *   For each pixel, bucket nearby pixels into a few intensity bins,
+ *   take the most popular bin's average color. */
+static void fx_painterly(Frame *f, int radius)
+{
+    if (radius < 1) radius = 1;
+    if (radius > 5) radius = 5;
+    int w = f->width, h = f->height;
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+    memcpy(tmp, f->data, (size_t)w * h * 3);
+
+    enum { NBINS = 6 };
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        for (int x = 0; x < w; x++) {
+            int cnt[NBINS] = {0};
+            int sb[NBINS] = {0}, sg[NBINS] = {0}, sr[NBINS] = {0};
+            int x0 = x - radius, x1 = x + radius;
+            int y0 = y - radius, y1 = y + radius;
+            if (x0 < 0) x0 = 0;
+            if (x1 >= w) x1 = w - 1;
+            if (y0 < 0) y0 = 0;
+            if (y1 >= h) y1 = h - 1;
+            for (int yy = y0; yy <= y1; yy++) {
+                for (int xx = x0; xx <= x1; xx++) {
+                    const uint8_t *s = tmp + yy * w * 3 + xx * 3;
+                    int luma = (s[2]*299 + s[1]*587 + s[0]*114) / 1000;
+                    int bin = (luma * NBINS) / 256;
+                    if (bin >= NBINS) bin = NBINS - 1;
+                    cnt[bin]++;
+                    sb[bin] += s[0]; sg[bin] += s[1]; sr[bin] += s[2];
+                }
+            }
+            int best = 0;
+            for (int b = 1; b < NBINS; b++) if (cnt[b] > cnt[best]) best = b;
+            int c = cnt[best];
+            dst[x*3+0] = sb[best] / c;
+            dst[x*3+1] = sg[best] / c;
+            dst[x*3+2] = sr[best] / c;
+        }
+    }
+    free(tmp);
+}
+
+#include <limits.h>  /* for INT_MAX */
+
+/* ══════════════════════════════════════════════════════════════
+ * Themed / aesthetic looks
+ * ══════════════════════════════════════════════════════════════ */
+
+/* ── modern: teal-orange cinematic grade ────────────────────── */
+static void fx_modern(Frame *f, float strength)
+{
+    if (strength < 0) strength = 0;
+    if (strength > 1) strength = 1;
+    int n = f->width * f->height;
+    uint8_t *p = f->data;
+    int push = (int)(20 * strength);
+    for (int i = 0; i < n; i++, p += 3) {
+        int b = p[0], g = p[1], r = p[2];
+        int luma = (r*299 + g*587 + b*114) / 1000;
+        if (luma < 128) {
+            /* shadows → teal */
+            p[0] = clamp_u8(b + push);
+            p[1] = clamp_u8(g + push/2);
+            p[2] = clamp_u8(r - push/2);
+        } else {
+            /* highlights → orange */
+            p[2] = clamp_u8(r + push);
+            p[1] = clamp_u8(g + push/4);
+            p[0] = clamp_u8(b - push);
+        }
+    }
+    fx_contrast(f, 1.0f + 0.15f * strength);
+    fx_vignette(f, 0.3f * strength);
+}
+
+/* ── cyberpunk: neon contrast + chromashift ─────────────────── */
+static void fx_cyberpunk(Frame *f, float intensity)
+{
+    if (intensity < 0) intensity = 0;
+    if (intensity > 1) intensity = 1;
+
+    /* Lift blues and magentas, drop yellows */
+    int n = f->width * f->height;
+    uint8_t *p = f->data;
+    int boost = (int)(25 * intensity);
+    for (int i = 0; i < n; i++, p += 3) {
+        p[0] = clamp_u8(p[0] + boost);            /* B up */
+        if (p[2] > p[1]) p[2] = clamp_u8(p[2] + boost); /* magenta zones */
+        if (p[1] > p[2]) p[1] = clamp_u8(p[1] - boost/2); /* drop yellow-green */
+    }
+    fx_contrast(f, 1.0f + 0.4f * intensity);
+    fx_chromashift(f, (int)(intensity * 10));
+}
+
+/* ── romantic: soft warm haze ──────────────────────────────── */
+static void fx_romantic(Frame *f, float strength)
+{
+    if (strength < 0) strength = 0;
+    if (strength > 1) strength = 1;
+
+    /* Warm tint */
+    int n = f->width * f->height;
+    uint8_t *p = f->data;
+    int warm = (int)(strength * 25);
+    for (int i = 0; i < n; i++, p += 3) {
+        p[0] = clamp_u8(p[0] - warm);     /* less B */
+        p[1] = clamp_u8(p[1] + warm/4);   /* tiny G */
+        p[2] = clamp_u8(p[2] + warm);     /* more R */
+    }
+    /* Soft blur, brightness lift, vignette */
+    fx_blur(f, 2);
+    fx_brightness(f, 1.0f + strength * 0.15f);
+    fx_vignette(f, strength * 0.55f);
+}
+
+/* ── vangogh: thick painterly with saturated brush strokes ── */
+static void fx_vangogh(Frame *f, float radius)
+{
+    int r = (int)radius;
+    if (r < 1) r = 1;
+    if (r > 5) r = 5;
+    fx_painterly(f, r);
+
+    /* Saturation boost — push every channel away from luma */
+    int n = f->width * f->height;
+    uint8_t *p = f->data;
+    for (int i = 0; i < n; i++, p += 3) {
+        int b = p[0], g = p[1], rr = p[2];
+        int luma = (rr*299 + g*587 + b*114) / 1000;
+        p[0] = clamp_u8(luma + (int)((b  - luma) * 1.6f));
+        p[1] = clamp_u8(luma + (int)((g  - luma) * 1.6f));
+        p[2] = clamp_u8(luma + (int)((rr - luma) * 1.6f));
+    }
+    fx_contrast(f, 1.15f);
+}
+
+/* ── picasso: cubist abstraction ───────────────────────────── */
+static void fx_picasso(Frame *f, float segments)
+{
+    int s = (int)segments;
+    if (s < 4) s = 4;
+    if (s > 16) s = 16;
+    fx_kaleidoscope(f, s);
+    fx_posterize(f, 4);
+    fx_cartoon(f, 35);
+}
+
+/* ══════════════════════════════════════════════════════════════
+ * Mathematical patterns
+ * ══════════════════════════════════════════════════════════════ */
+
+/* ── sine: animated sinusoidal x and y displacement ────────── */
+static void fx_sine(Frame *f, float amp)
+{
+    if (amp < 1) amp = 1;
+    int w = f->width, h = f->height;
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+    memcpy(tmp, f->data, (size_t)w * h * 3);
+
+    unsigned long t = anim_tick();
+    float phase = t * 0.06f;
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        for (int x = 0; x < w; x++) {
+            int sx = x + (int)(amp * sinf(y * 0.04f + phase));
+            int sy = y + (int)(amp * sinf(x * 0.04f + phase * 0.7f));
+            if (sx < 0) sx = 0;
+            if (sx >= w) sx = w - 1;
+            if (sy < 0) sy = 0;
+            if (sy >= h) sy = h - 1;
+            const uint8_t *src = tmp + sy * w * 3 + sx * 3;
+            dst[x*3+0] = src[0]; dst[x*3+1] = src[1]; dst[x*3+2] = src[2];
+        }
+    }
+    free(tmp);
+}
+
+/* ── xor: pixel-position XOR overlay ───────────────────────── */
+static void fx_xor(Frame *f, float strength)
+{
+    if (strength < 0) strength = 0;
+    if (strength > 1) strength = 1;
+    int w = f->width, h = f->height;
+    for (int y = 0; y < h; y++) {
+        uint8_t *p = f->data + y * f->stride;
+        for (int x = 0; x < w; x++, p += 3) {
+            int v = (x ^ y) & 0xff;
+            int delta = (int)(v * strength);
+            p[0] ^= (uint8_t)delta;
+            p[1] ^= (uint8_t)delta;
+            p[2] ^= (uint8_t)delta;
+        }
+    }
+}
+
+/* ── modulo: channel values mod N, scaled back to 0-255 ────── */
+static void fx_modulo(Frame *f, float div)
+{
+    int d = (int)div;
+    if (d < 2) d = 2;
+    if (d > 128) d = 128;
+    int scale = 255 / d;
+    int n = f->width * f->height * 3;
+    uint8_t *p = f->data;
+    for (int i = 0; i < n; i++) p[i] = (uint8_t)((p[i] % d) * scale);
+}
+
+/* ── polar: blend cartesian sampling with polar coordinates ── */
+static void fx_polar(Frame *f, float strength)
+{
+    if (strength < 0) strength = 0;
+    if (strength > 1) strength = 1;
+    int w = f->width, h = f->height;
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+    memcpy(tmp, f->data, (size_t)w * h * 3);
+
+    float cx = w / 2.0f, cy = h / 2.0f;
+    float maxr = sqrtf(cx*cx + cy*cy);
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        for (int x = 0; x < w; x++) {
+            float dx = x - cx, dy = y - cy;
+            float r = sqrtf(dx*dx + dy*dy) / maxr;
+            float theta = atan2f(dy, dx) / 3.14159265f;  /* -1..1 */
+
+            int polar_x = (int)((theta * 0.5f + 0.5f) * w);
+            int polar_y = (int)(r * h);
+
+            int sx = (int)((1 - strength) * x + strength * polar_x);
+            int sy = (int)((1 - strength) * y + strength * polar_y);
+            if (sx < 0) sx = 0;
+            if (sx >= w) sx = w - 1;
+            if (sy < 0) sy = 0;
+            if (sy >= h) sy = h - 1;
+            const uint8_t *src = tmp + sy * w * 3 + sx * 3;
+            dst[x*3+0] = src[0]; dst[x*3+1] = src[1]; dst[x*3+2] = src[2];
+        }
+    }
+    free(tmp);
+}
+
+/* ── voronoi: random seed cells flat-shaded with seed's color ── */
+static void fx_voronoi(Frame *f, float cell_count)
+{
+    int ncells = (int)cell_count;
+    if (ncells < 4) ncells = 4;
+    if (ncells > 64) ncells = 64;
+    int w = f->width, h = f->height;
+
+    /* Animate slowly — new seed positions every ~30 frames */
+    unsigned long t = anim_tick();
+    unsigned base = (unsigned)(t / 30);
+
+    int sx[64], sy[64];
+    uint8_t sb[64], sg[64], sr[64];
+    for (int i = 0; i < ncells; i++) {
+        sx[i] = (int)(hash_u(base + (unsigned)i * 13) % (unsigned)w);
+        sy[i] = (int)(hash_u(base + (unsigned)i * 41) % (unsigned)h);
+        const uint8_t *p = f->data + sy[i] * f->stride + sx[i] * 3;
+        sb[i] = p[0]; sg[i] = p[1]; sr[i] = p[2];
+    }
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *p = f->data + y * f->stride;
+        for (int x = 0; x < w; x++, p += 3) {
+            int best = 0, best_d = INT_MAX;
+            for (int i = 0; i < ncells; i++) {
+                int dx = x - sx[i], dy = y - sy[i];
+                int d = dx*dx + dy*dy;
+                if (d < best_d) { best_d = d; best = i; }
+            }
+            p[0] = sb[best]; p[1] = sg[best]; p[2] = sr[best];
+        }
+    }
+}
+
+/* ══════════════════════════════════════════════════════════════
+ * Pixel-crazy / animated
+ * ══════════════════════════════════════════════════════════════ */
+
+/* ── bitcrush: quantize each channel to `bits` bits ──────────── */
+static void fx_bitcrush(Frame *f, float bits)
+{
+    int b = (int)bits;
+    if (b < 1) b = 1;
+    if (b > 8) b = 8;
+    uint8_t mask = (uint8_t)(~((1 << (8 - b)) - 1));
+    int n = f->width * f->height * 3;
+    for (int i = 0; i < n; i++) f->data[i] &= mask;
+}
+
+/* ── melt: each column drifts downward by a random offset ────── */
+static void fx_melt(Frame *f, float intensity)
+{
+    if (intensity < 0) intensity = 0;
+    if (intensity > 1) intensity = 1;
+    int w = f->width, h = f->height;
+    unsigned long t = anim_tick();
+
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+    memcpy(tmp, f->data, (size_t)w * h * 3);
+
+    /* Per-column drip — same column gets the same drift across rows,
+     * which is what gives the "candle wax" look. The drift evolves
+     * slowly over time so it actually melts on screen. */
+    for (int x = 0; x < w; x++) {
+        unsigned r = hash_u((unsigned)x * 31 + (unsigned)(t / 3));
+        int drop = (int)((r % 200) * intensity / 3);
+        for (int y = 0; y < h; y++) {
+            int sy = y - drop;
+            if (sy < 0) sy = 0;
+            uint8_t *dst = f->data + y * f->stride + x * 3;
+            const uint8_t *src = tmp + sy * w * 3 + x * 3;
+            dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2];
+        }
+    }
+    free(tmp);
+}
+
+/* ── popart: 2x2 quadrants each with a different Warhol tint ── */
+static void fx_popart(Frame *f, float strength)
+{
+    if (strength < 0) strength = 0;
+    if (strength > 1) strength = 1;
+    int w = f->width, h = f->height;
+    int hw = w / 2, hh = h / 2;
+
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+    memcpy(tmp, f->data, (size_t)w * h * 3);
+
+    /* 4 Warhol-ish palettes, (B,G,R) */
+    const int tints[4][3] = {
+        {200, 100, 255},  /* pink   */
+        {255, 200, 100},  /* cyan   */
+        {100, 255, 200},  /* green  */
+        {100, 200, 255},  /* orange */
+    };
+
+    for (int y = 0; y < h; y++) {
+        int qy = (y < hh) ? 0 : 1;
+        for (int x = 0; x < w; x++) {
+            int qx = (x < hw) ? 0 : 1;
+            int q  = qy * 2 + qx;
+
+            /* Sample from a 2x downscale so every quadrant shows the
+             * full image, just smaller. */
+            int sx = (x % hw) * 2;
+            int sy = (y % hh) * 2;
+            if (sx >= w) sx = w - 1;
+            if (sy >= h) sy = h - 1;
+            const uint8_t *src = tmp + sy * w * 3 + sx * 3;
+            int luma = (src[2]*299 + src[1]*587 + src[0]*114) / 1000;
+
+            float lf = luma / 255.0f;
+            int tb = (int)(lf * tints[q][0]);
+            int tg = (int)(lf * tints[q][1]);
+            int tr = (int)(lf * tints[q][2]);
+
+            /* Blend tint with original by strength */
+            uint8_t *dst = f->data + y * f->stride + x * 3;
+            dst[0] = clamp_u8((int)((1.0f - strength) * src[0] + strength * tb));
+            dst[1] = clamp_u8((int)((1.0f - strength) * src[1] + strength * tg));
+            dst[2] = clamp_u8((int)((1.0f - strength) * src[2] + strength * tr));
+        }
+    }
+    free(tmp);
+}
+
+/* ── displace: luma at (x,y) shifts the sample x-position ───── */
+static void fx_displace(Frame *f, float strength)
+{
+    if (strength < 0) strength = 0;
+    if (strength > 1) strength = 1;
+    int w = f->width, h = f->height;
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+    memcpy(tmp, f->data, (size_t)w * h * 3);
+
+    int amount = (int)(strength * 40);
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        for (int x = 0; x < w; x++) {
+            const uint8_t *p = tmp + y * w * 3 + x * 3;
+            int luma = (p[2]*299 + p[1]*587 + p[0]*114) / 1000;
+            int dx = ((luma - 128) * amount) / 128;
+            int sx = x + dx;
+            if (sx < 0) sx = 0;
+            if (sx >= w) sx = w - 1;
+            const uint8_t *src = tmp + y * w * 3 + sx * 3;
+            dst[x*3+0] = src[0]; dst[x*3+1] = src[1]; dst[x*3+2] = src[2];
+        }
+    }
+    free(tmp);
+}
+
+/* ── ripple: animated water ripple radiating from center ────── */
+static void fx_ripple(Frame *f, float strength)
+{
+    if (strength < 0) strength = 0;
+    if (strength > 1) strength = 1;
+    int w = f->width, h = f->height;
+    uint8_t *tmp = malloc((size_t)w * h * 3);
+    if (!tmp) return;
+    memcpy(tmp, f->data, (size_t)w * h * 3);
+
+    float cx = w / 2.0f, cy = h / 2.0f;
+    unsigned long t = anim_tick();
+    float phase = t * 0.15f;
+    float amp   = strength * 25.0f;
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        for (int x = 0; x < w; x++) {
+            float dx = x - cx, dy = y - cy;
+            float r  = sqrtf(dx*dx + dy*dy);
+            if (r < 0.5f) {
+                const uint8_t *src = tmp + y * w * 3 + x * 3;
+                dst[x*3+0] = src[0]; dst[x*3+1] = src[1]; dst[x*3+2] = src[2];
+                continue;
+            }
+            float wave = sinf(r * 0.05f - phase) * amp;
+            float nx = dx / r, ny = dy / r;
+            int sx = (int)(x + nx * wave);
+            int sy = (int)(y + ny * wave);
+            if (sx < 0) sx = 0;
+            if (sx >= w) sx = w - 1;
+            if (sy < 0) sy = 0;
+            if (sy >= h) sy = h - 1;
+            const uint8_t *src = tmp + sy * w * 3 + sx * 3;
+            dst[x*3+0] = src[0]; dst[x*3+1] = src[1]; dst[x*3+2] = src[2];
+        }
+    }
+    free(tmp);
+}
+
+void filter_chain_apply(FilterChain *fc, Frame *frame)
+{
+    pthread_mutex_lock(&fc->lock);
+    int n = fc->count;
+    Filter local[MAX_FILTERS];
+    if (n > 0) memcpy(local, fc->filters, n * sizeof(Filter));
+    pthread_mutex_unlock(&fc->lock);
+
+    /* Apply outside the lock so adding/removing isn't blocked while we work */
+    for (int i = 0; i < n; i++) {
+        Filter *f = &local[i];
+        switch (f->type) {
+        case FX_GRAYSCALE:    fx_grayscale(frame); break;
+        case FX_SEPIA:        fx_sepia(frame); break;
+        case FX_INVERT:       fx_invert(frame); break;
+        case FX_MIRROR:       fx_mirror(frame); break;
+        case FX_FLIP:         fx_flip(frame); break;
+        case FX_PIXELATE:     fx_pixelate(frame, (int)f->param); break;
+        case FX_BLUR:         fx_blur(frame, (int)f->param); break;
+        case FX_VIGNETTE:     fx_vignette(frame, f->param); break;
+        case FX_BRIGHTNESS:   fx_brightness(frame, f->param); break;
+        case FX_CONTRAST:     fx_contrast(frame, f->param); break;
+        case FX_POSTERIZE:    fx_posterize(frame, (int)f->param); break;
+        case FX_EDGES:        fx_edges(frame); break;
+        case FX_CHROMASHIFT:  fx_chromashift(frame, (int)f->param); break;
+        case FX_GLITCH:       fx_glitch(frame, f->param); break;
+        case FX_KALEIDOSCOPE: fx_kaleidoscope(frame, (int)f->param); break;
+        case FX_SWIRL:        fx_swirl(frame, f->param); break;
+        case FX_THERMAL:      fx_thermal(frame); break;
+        case FX_OLDFILM:      fx_oldfilm(frame); break;
+        case FX_WAVE:         fx_wave(frame, f->param); break;
+        case FX_CARTOON:      fx_cartoon(frame, f->param); break;
+        case FX_SOLARIZE:     fx_solarize(frame, (int)f->param); break;
+        case FX_RAINBOW:      fx_rainbow(frame, f->param); break;
+        case FX_DREAM:        fx_dream(frame, f->param); break;
+        case FX_BLOOM:        fx_bloom(frame, f->param); break;
+        case FX_GLOW:         fx_glow(frame, f->param); break;
+        case FX_PINCH:        fx_pinch(frame, f->param); break;
+        case FX_BULGE:        fx_bulge(frame, f->param); break;
+        case FX_PAINTERLY:    fx_painterly(frame, (int)f->param); break;
+        case FX_MODERN:       fx_modern(frame, f->param); break;
+        case FX_CYBERPUNK:    fx_cyberpunk(frame, f->param); break;
+        case FX_ROMANTIC:     fx_romantic(frame, f->param); break;
+        case FX_VANGOGH:      fx_vangogh(frame, f->param); break;
+        case FX_PICASSO:      fx_picasso(frame, f->param); break;
+        case FX_SINE:         fx_sine(frame, f->param); break;
+        case FX_XOR:          fx_xor(frame, f->param); break;
+        case FX_MODULO:       fx_modulo(frame, f->param); break;
+        case FX_POLAR:        fx_polar(frame, f->param); break;
+        case FX_VORONOI:      fx_voronoi(frame, f->param); break;
+        case FX_BITCRUSH:     fx_bitcrush(frame, f->param); break;
+        case FX_MELT:         fx_melt(frame, f->param); break;
+        case FX_POPART:       fx_popart(frame, f->param); break;
+        case FX_DISPLACE:     fx_displace(frame, f->param); break;
+        case FX_RIPPLE:       fx_ripple(frame, f->param); break;
+        default: break;
+        }
+    }
+}
diff --git a/src/frame.c b/src/frame.c
new file mode 100644
index 0000000..260a138
--- /dev/null
+++ b/src/frame.c
@@ -0,0 +1,22 @@
+#include "vcam.h"
+#include <stdlib.h>
+#include <string.h>
+
+Frame *frame_alloc(int width, int height)
+{
+    Frame *f = calloc(1, sizeof *f);
+    if (!f) return NULL;
+    f->width  = width;
+    f->height = height;
+    f->stride = width * 3; /* BGR24 */
+    f->data   = malloc((size_t)f->stride * height);
+    if (!f->data) { free(f); return NULL; }
+    return f;
+}
+
+void frame_free(Frame *f)
+{
+    if (!f) return;
+    free(f->data);
+    free(f);
+}
diff --git a/src/ipc.c b/src/ipc.c
new file mode 100644
index 0000000..d883875
--- /dev/null
+++ b/src/ipc.c
@@ -0,0 +1,702 @@
+/*
+ * IPC server – Unix domain socket at /tmp/vcam.sock
+ *
+ * Protocol: newline-terminated UTF-8 text commands.
+ *
+ * Commands:
+ *   add img    <id> <x> <y> [<w> <h>] <file>
+ *   add vid    <id> <x> <y> [<w> <h>] <file>
+ *   add screen <id> <x> <y> [<w> <h>] <geometry>
+ *   remove <id>
+ *   move   <id> <x> <y>
+ *   resize <id> <w> <h>
+ *   list
+ *   quit
+ *
+ * Every command gets a one-line response: "OK ..." or "ERR ...".
+ */
+
+#include "vcam.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+
+/* ── helpers ─────────────────────────────────── */
+static void send_line(int fd, const char *msg)
+{
+    size_t len = strlen(msg);
+    char buf[512];
+    size_t n = len < sizeof buf - 2 ? len : sizeof buf - 2;
+    memcpy(buf, msg, n);
+    buf[n]   = '\n';
+    buf[n+1] = '\0';
+    ssize_t r = write(fd, buf, n + 1);
+    if (r < 0) { /* client disconnected – ignore */ }
+}
+
+/* Read a newline-terminated line from fd into buf (max len).
+ * Returns number of bytes (excluding '\n'), or -1 on error/EOF. */
+static int read_line(int fd, char *buf, int maxlen)
+{
+    int i = 0;
+    while (i < maxlen - 1) {
+        char c;
+        ssize_t n = read(fd, &c, 1);
+        if (n <= 0) return -1;
+        if (c == '\n') break;
+        if (c != '\r') buf[i++] = c;
+    }
+    buf[i] = '\0';
+    return i;
+}
+
+/*
+ * Parse optional size tokens before the final path/geometry argument.
+ * Accepts:
+ *   <w> <h> <path>   → both dimensions set
+ *   <w>   <path>     → only w set (h=0, resolved from aspect ratio later)
+ *   <path>           → neither set
+ *
+ * We decide by checking whether the token before the last is a number.
+ * The last token is always the path/geometry.
+ * Remaining tokens are collected into an array first.
+ */
+static void parse_size_and_path(char **save_ptr,
+                                 int *out_w, int *out_h, char **out_path)
+{
+    char *toks[3] = { NULL, NULL, NULL };
+    int n = 0;
+    char *t;
+    while (n < 3 && (t = strtok_r(NULL, " \t", save_ptr)) != NULL)
+        toks[n++] = t;
+
+    *out_w = 0; *out_h = 0; *out_path = NULL;
+
+    if (n == 0) return;          /* no path */
+    if (n == 1) {                /* just path */
+        *out_path = toks[0]; return;
+    }
+
+    /* Check if toks[0] is numeric */
+    char *ep;
+    long v0 = strtol(toks[0], &ep, 10);
+    bool t0_num = (*ep == '\0');
+
+    if (n == 2) {
+        if (t0_num) {            /* <w> <path> */
+            *out_w = (int)v0;
+            *out_path = toks[1];
+        } else {                 /* <path> (extra token lost – shouldn't happen) */
+            *out_path = toks[0];
+        }
+        return;
+    }
+
+    /* n == 3 */
+    long v1 = strtol(toks[1], &ep, 10);
+    bool t1_num = (*ep == '\0');
+
+    if (t0_num && t1_num) {      /* <w> <h> <path> */
+        *out_w = (int)v0; *out_h = (int)v1;
+        *out_path = toks[2];
+    } else if (t0_num) {         /* <w> <path> (toks[2] lost) */
+        *out_w = (int)v0;
+        *out_path = toks[1];
+    } else {                     /* <path> (extra tokens lost) */
+        *out_path = toks[0];
+    }
+}
+
+/* ── command handler ─────────────────────────── */
+extern FilterChain g_filters;  /* defined in main.c */
+
+static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
+{
+    char *save;
+    char *cmd = strtok_r(line, " \t", &save);
+    if (!cmd || cmd[0] == '#' || cmd[0] == '\0') {
+        send_line(client_fd, "OK noop");
+        return;
+    }
+
+    /* ── filter <subcmd> ──
+     *   filter help
+     *   filter add <name> [<param>]
+     *   filter remove <index>
+     *   filter clear
+     *   filter list
+     */
+    if (strcmp(cmd, "filter") == 0) {
+        char *sub = strtok_r(NULL, " \t", &save);
+        if (!sub || strcmp(sub, "help") == 0) {
+            send_line(client_fd, "OK filter commands:");
+            send_line(client_fd, "OK   filter list                    show active filters");
+            send_line(client_fd, "OK   filter add <name> [<param>]    append a filter");
+            send_line(client_fd, "OK   filter set <index> <param>     update a filter's parameter");
+            send_line(client_fd, "OK   filter remove <index>          remove filter at index");
+            send_line(client_fd, "OK   filter clear                   remove all filters");
+            send_line(client_fd, "OK   filter help                    this message");
+            send_line(client_fd, "OK");
+            send_line(client_fd, "OK basic filters:");
+            send_line(client_fd, "OK   grayscale                      Rec.601 luma");
+            send_line(client_fd, "OK   sepia                          warm brown tone");
+            send_line(client_fd, "OK   invert                         negative colors");
+            send_line(client_fd, "OK   mirror                         horizontal flip");
+            send_line(client_fd, "OK   flip                           vertical flip");
+            send_line(client_fd, "OK   pixelate <block>               mosaic, default block=8");
+            send_line(client_fd, "OK   blur <radius>                  box blur, radius 1..6, default 2");
+            send_line(client_fd, "OK   vignette <strength>            darken edges, 0..1, default 0.6");
+            send_line(client_fd, "OK   brightness <mult>              multiply brightness, default 1.2");
+            send_line(client_fd, "OK   contrast <mult>                contrast around 128, default 1.4");
+            send_line(client_fd, "OK   posterize <levels>             reduce color levels, default 4");
+            send_line(client_fd, "OK   edges                          Sobel edge detection");
+            send_line(client_fd, "OK");
+            send_line(client_fd, "OK fancy filters:");
+            send_line(client_fd, "OK   chromashift <offset>           VHS-style RGB channel split, default 5");
+            send_line(client_fd, "OK   glitch <intensity>             animated random horizontal slices, 0..1, default 0.3");
+            send_line(client_fd, "OK   kaleidoscope <segments>        radial mirror, default 6");
+            send_line(client_fd, "OK   swirl <strength>               radial twist, default 1.0");
+            send_line(client_fd, "OK   thermal                        heatmap palette (luma → fire colors)");
+            send_line(client_fd, "OK   oldfilm                        sepia + grain + scratches + vignette");
+            send_line(client_fd, "OK   wave <amplitude>               animated sinusoidal x-shift, default 10");
+            send_line(client_fd, "OK   cartoon <edge_thresh>          posterize + dark edges, default 50");
+            send_line(client_fd, "OK   solarize <threshold>           invert pixels above value, default 128");
+            send_line(client_fd, "OK   rainbow <speed>                animated hue rotation, default 1.0");
+            send_line(client_fd, "OK");
+            send_line(client_fd, "OK soft & dreamy filters:");
+            send_line(client_fd, "OK   dream <strength>               hazy soft glow, 0..1, default 0.5");
+            send_line(client_fd, "OK   bloom <strength>               highlight glow, 0..1, default 0.6");
+            send_line(client_fd, "OK   glow <intensity>               gentle gaussian glow, 0..1, default 0.4");
+            send_line(client_fd, "OK   pinch <strength>               radial inward pull, 0..1, default 0.5");
+            send_line(client_fd, "OK   bulge <strength>               fisheye-like outward push, 0..1, default 0.5");
+            send_line(client_fd, "OK   painterly <radius>             oil-painting effect, 1..5, default 3");
+            send_line(client_fd, "OK");
+            send_line(client_fd, "OK themed looks:");
+            send_line(client_fd, "OK   modern <strength>              teal-orange cinematic grade, default 0.7");
+            send_line(client_fd, "OK   cyberpunk <intensity>          neon contrast + chromashift, default 0.7");
+            send_line(client_fd, "OK   romantic <strength>            soft warm haze, default 0.7");
+            send_line(client_fd, "OK   vangogh <radius>               heavy painterly + saturation, 1..5, default 3");
+            send_line(client_fd, "OK   picasso <segments>             cubist: kaleidoscope+poster+edges, 4..16, default 8");
+            send_line(client_fd, "OK");
+            send_line(client_fd, "OK mathematical patterns:");
+            send_line(client_fd, "OK   sine <amplitude>               sin-wave x/y distortion, default 15");
+            send_line(client_fd, "OK   xor <strength>                 (x^y) bitwise overlay, 0..1, default 0.5");
+            send_line(client_fd, "OK   modulo <divisor>               color mod N, 2..128, default 64");
+            send_line(client_fd, "OK   polar <strength>               polar-coordinate warp, 0..1, default 0.7");
+            send_line(client_fd, "OK   voronoi <cells>                voronoi cell mosaic, 4..64, default 20");
+            send_line(client_fd, "OK");
+            send_line(client_fd, "OK pixel-crazy / animated:");
+            send_line(client_fd, "OK   bitcrush <bits>                quantize bits per channel, 1..8, default 3");
+            send_line(client_fd, "OK   melt <intensity>               animated downward drip, 0..1, default 0.5");
+            send_line(client_fd, "OK   popart <strength>              Warhol 2x2 tinted quadrants, 0..1, default 1");
+            send_line(client_fd, "OK   displace <strength>            luma-driven horizontal shift, 0..1, default 0.5");
+            send_line(client_fd, "OK   ripple <strength>              animated water ripple from center, 0..1, default 0.5");
+            return;
+        }
+
+        if (strcmp(sub, "list") == 0) {
+            pthread_mutex_lock(&g_filters.lock);
+            if (g_filters.count == 0) {
+                send_line(client_fd, "OK (no filters)");
+            } else {
+                char buf[128];
+                for (int i = 0; i < g_filters.count; i++) {
+                    Filter *f = &g_filters.filters[i];
+                    snprintf(buf, sizeof buf, "OK %d: %s param=%.2f",
+                             i, filter_type_to_name(f->type), f->param);
+                    send_line(client_fd, buf);
+                }
+            }
+            pthread_mutex_unlock(&g_filters.lock);
+            return;
+        }
+
+        if (strcmp(sub, "clear") == 0) {
+            filter_chain_clear(&g_filters);
+            send_line(client_fd, "OK all filters cleared");
+            return;
+        }
+
+        if (strcmp(sub, "add") == 0) {
+            char *name = strtok_r(NULL, " \t", &save);
+            if (!name) { send_line(client_fd, "ERR filter add: missing name"); return; }
+            FilterType t = filter_type_from_name(name);
+            if (t == FX_UNKNOWN) {
+                char b[128]; snprintf(b, sizeof b, "ERR unknown filter '%s'", name);
+                send_line(client_fd, b); return;
+            }
+            float param = filter_default_param(t);
+            char *pstr = strtok_r(NULL, " \t", &save);
+            if (pstr) {
+                char *ep; float v = strtof(pstr, &ep);
+                if (*ep == '\0') param = v;
+            }
+            if (filter_chain_add(&g_filters, t, param)) {
+                char b[128];
+                snprintf(b, sizeof b, "OK added filter '%s' param=%.2f",
+                         filter_type_to_name(t), param);
+                send_line(client_fd, b);
+            } else {
+                send_line(client_fd, "ERR filter chain full");
+            }
+            return;
+        }
+
+        if (strcmp(sub, "set") == 0) {
+            char *istr = strtok_r(NULL, " \t", &save);
+            char *pstr = strtok_r(NULL, " \t", &save);
+            if (!istr || !pstr) {
+                send_line(client_fd, "ERR filter set: usage 'filter set <index> <param>'");
+                return;
+            }
+            int idx = atoi(istr);
+            char *ep; float v = strtof(pstr, &ep);
+            if (*ep != '\0') { send_line(client_fd, "ERR filter set: bad number"); return; }
+            pthread_mutex_lock(&g_filters.lock);
+            if (idx < 0 || idx >= g_filters.count) {
+                pthread_mutex_unlock(&g_filters.lock);
+                send_line(client_fd, "ERR filter set: index out of range");
+                return;
+            }
+            g_filters.filters[idx].param = v;
+            const char *name = filter_type_to_name(g_filters.filters[idx].type);
+            pthread_mutex_unlock(&g_filters.lock);
+            char b[128]; snprintf(b, sizeof b, "OK %d: %s param=%.2f", idx, name, v);
+            send_line(client_fd, b);
+            return;
+        }
+
+        if (strcmp(sub, "remove") == 0) {
+            char *arg = strtok_r(NULL, " \t", &save);
+            if (!arg) {
+                send_line(client_fd, "ERR filter remove: missing <name> or <index>");
+                return;
+            }
+            int idx = -1;
+            /* If the whole arg is digits, treat as index; otherwise as name. */
+            bool all_digits = arg[0] != '\0';
+            for (char *p = arg; *p; p++)
+                if (*p < '0' || *p > '9') { all_digits = false; break; }
+
+            if (all_digits) {
+                idx = atoi(arg);
+            } else {
+                /* Look up filter type, then find it in the active chain. */
+                FilterType t = filter_type_from_name(arg);
+                if (t == FX_UNKNOWN) {
+                    char b[128];
+                    snprintf(b, sizeof b, "ERR filter remove: unknown filter '%s'", arg);
+                    send_line(client_fd, b); return;
+                }
+                pthread_mutex_lock(&g_filters.lock);
+                for (int i = 0; i < g_filters.count; i++)
+                    if (g_filters.filters[i].type == t) { idx = i; break; }
+                pthread_mutex_unlock(&g_filters.lock);
+                if (idx < 0) {
+                    char b[128];
+                    snprintf(b, sizeof b, "ERR filter '%s' is not in the active chain", arg);
+                    send_line(client_fd, b); return;
+                }
+            }
+            if (filter_chain_remove(&g_filters, idx)) {
+                char b[64];
+                snprintf(b, sizeof b, "OK removed filter at index %d", idx);
+                send_line(client_fd, b);
+            } else {
+                send_line(client_fd, "ERR no filter at that index");
+            }
+            return;
+        }
+
+        send_line(client_fd, "ERR filter: unknown subcommand (use add/remove/list/clear)");
+        return;
+    }
+
+    /* ── help ── */
+    if (strcmp(cmd, "help") == 0) {
+        send_line(client_fd, "OK vcam commands:");
+        send_line(client_fd, "OK   list                                 show active overlays (draw order)");
+        send_line(client_fd, "OK   add img|vid|vid-once|screen|webcam <id> <x> <y> [<w> [<h>]] <file|geo|dev>");
+        send_line(client_fd, "OK   remove <id>|all                      remove one or all overlays");
+        send_line(client_fd, "OK   move   <id> [x=N|N] [y=N|N]          x=/y= or positional; 'keep'/'-' to skip");
+        send_line(client_fd, "OK   resize <id> [w=N|N] [h=N|N]          w=/h= or positional; 'auto'/'-' = derive");
+        send_line(client_fd, "OK   raise  <id>                          draw on top (last in list)");
+        send_line(client_fd, "OK   lower  <id>                          draw at bottom (first in list)");
+        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   quit                                 close the connection");
+        return;
+    }
+
+    /* ── list ── */
+    if (strcmp(cmd, "list") == 0) {
+        pthread_mutex_lock(&reg->lock);
+        if (reg->count == 0) {
+            send_line(client_fd, "OK (no overlays)");
+        } else {
+            char buf[256];
+            for (int i = 0; i < reg->count; i++) {
+                OverlaySlot *s = &reg->slots[i];
+                OverlayType t  = overlay_get_type(s->overlay);
+                const char *type_str = t == OVERLAY_IMAGE  ? "img"    :
+                                       t == OVERLAY_VIDEO  ? "vid"    :
+                                       t == OVERLAY_WEBCAM ? "webcam" : "screen";
+                int ox, oy, ow, oh;
+                overlay_get_rect(s->overlay, &ox, &oy, &ow, &oh);
+                snprintf(buf, sizeof buf,
+                         "OK z=%d: [%s] id=%s pos=(%d,%d) size=%dx%d%s",
+                         i, type_str, s->id, ox, oy, ow, oh,
+                         (i == reg->count - 1) ? " (top)" :
+                         (i == 0)              ? " (bottom)" : "");
+                send_line(client_fd, buf);
+            }
+        }
+        pthread_mutex_unlock(&reg->lock);
+        return;
+    }
+
+    /* ── quit ── */
+    if (strcmp(cmd, "quit") == 0) {
+        send_line(client_fd, "OK bye");
+        return; /* connection will be closed after return */
+    }
+
+    /* ── remove <id> ── */
+    if (strcmp(cmd, "remove") == 0) {
+        char *id = strtok_r(NULL, " \t", &save);
+        if (!id) { send_line(client_fd, "ERR usage: remove <id>|all"); return; }
+
+        if (strcmp(id, "all") == 0) {
+            /* Snapshot the ID list under the lock, then remove each
+             * (registry_remove takes the lock itself so we can't hold it). */
+            pthread_mutex_lock(&reg->lock);
+            int n = reg->count;
+            char ids[MAX_OVERLAYS][64];
+            for (int i = 0; i < n; i++) {
+                strncpy(ids[i], reg->slots[i].id, sizeof ids[i] - 1);
+                ids[i][sizeof ids[i] - 1] = '\0';
+            }
+            pthread_mutex_unlock(&reg->lock);
+            for (int i = 0; i < n; i++) registry_remove(reg, ids[i]);
+            char buf[64]; snprintf(buf, sizeof buf, "OK removed %d overlay(s)", n);
+            send_line(client_fd, buf);
+            return;
+        }
+
+        if (registry_remove(reg, id)) {
+            char buf[128]; snprintf(buf, sizeof buf, "OK removed '%s'", id);
+            send_line(client_fd, buf);
+        } else {
+            char buf[128]; snprintf(buf, sizeof buf, "ERR id '%s' not found", id);
+            send_line(client_fd, buf);
+        }
+        return;
+    }
+
+    /* ── move <id> <args...> ──
+     * Args can be positional (x [y]) or keyed (x=N y=N).
+     * Each value can be a number, "keep" / "-" (default for move), or
+     * blank.  Missing → keep current value.
+     */
+    if (strcmp(cmd, "move") == 0) {
+        char *id = strtok_r(NULL, " \t", &save);
+        if (!id) { send_line(client_fd, "ERR usage: move <id> [x=N|N] [y=N|N]"); return; }
+
+        /* Collect remaining tokens */
+        char *toks[8] = {0};
+        int ntok = 0;
+        char *t;
+        while (ntok < 8 && (t = strtok_r(NULL, " \t", &save))) toks[ntok++] = t;
+
+        /* Pull x=, y= out of any tokens that contain them; otherwise
+         * positional (1st = x, 2nd = y). */
+        char *x_str = NULL, *y_str = NULL;
+        bool has_kv = false;
+        for (int i = 0; i < ntok; i++) {
+            if      (strncmp(toks[i], "x=", 2) == 0) { x_str = toks[i] + 2; has_kv = true; }
+            else if (strncmp(toks[i], "y=", 2) == 0) { y_str = toks[i] + 2; has_kv = true; }
+        }
+        if (!has_kv) {
+            if (ntok >= 1) x_str = toks[0];
+            if (ntok >= 2) y_str = toks[1];
+        }
+
+        pthread_mutex_lock(&reg->lock);
+        Overlay *o = registry_find(reg, id);
+        if (!o) {
+            pthread_mutex_unlock(&reg->lock);
+            char buf[128]; snprintf(buf, sizeof buf, "ERR id '%s' not found", id);
+            send_line(client_fd, buf); return;
+        }
+        int cx, cy, cw, ch; overlay_get_rect(o, &cx, &cy, &cw, &ch);
+
+        /* Resolve "keep" / "-" / missing → current value */
+        int x = cx, y = cy;
+        if (x_str && *x_str && strcmp(x_str, "keep") != 0 && strcmp(x_str, "-") != 0)
+            x = atoi(x_str);
+        if (y_str && *y_str && strcmp(y_str, "keep") != 0 && strcmp(y_str, "-") != 0)
+            y = atoi(y_str);
+
+        overlay_move(o, x, y);
+        pthread_mutex_unlock(&reg->lock);
+        char buf[128]; snprintf(buf, sizeof buf, "OK moved '%s' to (%d,%d)", id, x, y);
+        send_line(client_fd, buf);
+        return;
+    }
+
+    /* ── resize <id> <args...> ──
+     * Args can be positional (w [h]) or keyed (w=N h=N).
+     * Each value can be a number, "keep", "auto" / "-" (default for
+     * resize), or blank.  Missing → auto-derive from source aspect.
+     */
+    if (strcmp(cmd, "resize") == 0) {
+        char *id = strtok_r(NULL, " \t", &save);
+        if (!id) { send_line(client_fd, "ERR usage: resize <id> [w=N|N] [h=N|N]"); return; }
+
+        char *toks[8] = {0};
+        int ntok = 0;
+        char *t;
+        while (ntok < 8 && (t = strtok_r(NULL, " \t", &save))) toks[ntok++] = t;
+
+        char *w_str = NULL, *h_str = NULL;
+        bool has_kv = false;
+        for (int i = 0; i < ntok; i++) {
+            if      (strncmp(toks[i], "w=", 2) == 0) { w_str = toks[i] + 2; has_kv = true; }
+            else if (strncmp(toks[i], "h=", 2) == 0) { h_str = toks[i] + 2; has_kv = true; }
+        }
+        if (!has_kv) {
+            if (ntok >= 1) w_str = toks[0];
+            if (ntok >= 2) h_str = toks[1];
+        }
+
+        pthread_mutex_lock(&reg->lock);
+        Overlay *o = registry_find(reg, id);
+        if (!o) {
+            pthread_mutex_unlock(&reg->lock);
+            char buf[128]; snprintf(buf, sizeof buf, "ERR id '%s' not found", id);
+            send_line(client_fd, buf); return;
+        }
+        int cx, cy, cw, ch; overlay_get_rect(o, &cx, &cy, &cw, &ch);
+        int src_w, src_h; overlay_get_src(o, &src_w, &src_h);
+
+        /* Decode each arg into an explicit value:
+         *   "keep" / unspecified-and-mode-is-positional → keep current
+         *   "auto" / "-" / missing                       → derive from aspect
+         *   <number>                                     → explicit
+         */
+        int w = -2, h = -2; /* -2 = unset, -1 = keep, 0 = auto, >0 = explicit */
+        if (w_str) {
+            if (*w_str == '\0' || strcmp(w_str, "auto") == 0 || strcmp(w_str, "-") == 0) w = 0;
+            else if (strcmp(w_str, "keep") == 0) w = -1;
+            else w = atoi(w_str);
+        }
+        if (h_str) {
+            if (*h_str == '\0' || strcmp(h_str, "auto") == 0 || strcmp(h_str, "-") == 0) h = 0;
+            else if (strcmp(h_str, "keep") == 0) h = -1;
+            else h = atoi(h_str);
+        }
+        /* Default behavior for resize when arg is omitted = auto */
+        if (w == -2) w = 0;
+        if (h == -2) h = 0;
+        /* Translate -1 (keep) into the current value */
+        if (w == -1) w = cw;
+        if (h == -1) h = ch;
+        /* Translate 0 (auto) using source aspect */
+        if (w <= 0 && h <= 0) {
+            pthread_mutex_unlock(&reg->lock);
+            send_line(client_fd, "ERR resize: at least one of w/h must be a number");
+            return;
+        }
+        if (w <= 0 && src_h > 0) w = (int)((long)h * src_w / src_h);
+        if (h <= 0 && src_w > 0) h = (int)((long)w * src_h / src_w);
+        if (w <= 0 || h <= 0) {
+            pthread_mutex_unlock(&reg->lock);
+            send_line(client_fd, "ERR resize: invalid dimensions");
+            return;
+        }
+
+        overlay_resize(o, w, h);
+        pthread_mutex_unlock(&reg->lock);
+        char buf[128]; snprintf(buf, sizeof buf, "OK resized '%s' to %dx%d", id, w, h);
+        send_line(client_fd, buf);
+        return;
+    }
+
+    /* ── raise <id> / lower <id> ── */
+    if (strcmp(cmd, "raise") == 0 || strcmp(cmd, "lower") == 0) {
+        char *id = strtok_r(NULL, " \t", &save);
+        if (!id) {
+            char b[128]; snprintf(b, sizeof b, "ERR usage: %s <id>", cmd);
+            send_line(client_fd, b); return;
+        }
+        bool ok = (strcmp(cmd, "raise") == 0) ? registry_raise(reg, id)
+                                              : registry_lower(reg, id);
+        if (ok) {
+            char b[128]; snprintf(b, sizeof b, "OK %sd '%s'", cmd, id);
+            send_line(client_fd, b);
+        } else {
+            char b[128]; snprintf(b, sizeof b, "ERR id '%s' not found", id);
+            send_line(client_fd, b);
+        }
+        return;
+    }
+
+    /* ── z <id> <N> ──
+     * Move the overlay to position N in the draw order (0 = bottom,
+     * count-1 = top). Negative N counts from the top (-1 = top).
+     */
+    if (strcmp(cmd, "z") == 0) {
+        char *id = strtok_r(NULL, " \t", &save);
+        char *sn = strtok_r(NULL, " \t", &save);
+        if (!id || !sn) {
+            send_line(client_fd, "ERR usage: z <id> <index>  (0=bottom, -1=top)");
+            return;
+        }
+        int target = atoi(sn);
+        if (!registry_set_z(reg, id, target)) {
+            char b[128]; snprintf(b, sizeof b, "ERR id '%s' not found", id);
+            send_line(client_fd, b); return;
+        }
+        char b[128]; snprintf(b, sizeof b, "OK '%s' moved in draw order", id);
+        send_line(client_fd, b);
+        return;
+    }
+
+    /* ── add <type> <id> <x> <y> [<w>] [<h>] <file|geometry> ── */
+    if (strcmp(cmd, "add") == 0) {
+        char *type = strtok_r(NULL, " \t", &save);
+        char *id   = strtok_r(NULL, " \t", &save);
+        char *sx   = strtok_r(NULL, " \t", &save);
+        char *sy   = strtok_r(NULL, " \t", &save);
+
+        if (!type || !id || !sx || !sy) {
+            send_line(client_fd, "ERR usage: add <img|vid|screen> <id> <x> <y> [<w>] [<h>] <file>");
+            return;
+        }
+        int x = atoi(sx), y = atoi(sy);
+        int w = 0, h = 0;
+        char *path = NULL;
+
+        parse_size_and_path(&save, &w, &h, &path);
+
+        if (!path && strcmp(type, "webcam") != 0) {
+            send_line(client_fd, "ERR missing file/geometry argument");
+            return;
+        }
+
+        Overlay *o = NULL;
+        if (strcmp(type, "img") == 0) {
+            o = overlay_create_image(path, x, y, w, h);
+        } else if (strcmp(type, "vid") == 0) {
+            o = overlay_create_video(path, x, y, w, h, true);   /* loop */
+        } else if (strcmp(type, "vid-once") == 0) {
+            o = overlay_create_video(path, x, y, w, h, false);  /* play once */
+        } else if (strcmp(type, "screen") == 0) {
+            o = overlay_create_screen(path, x, y, w, h);
+        } else if (strcmp(type, "webcam") == 0) {
+            o = overlay_create_webcam(path, x, y, w, h);
+        } else {
+            char buf[128]; snprintf(buf, sizeof buf, "ERR unknown type '%s'", type);
+            send_line(client_fd, buf); return;
+        }
+
+        if (!o) {
+            send_line(client_fd, "ERR failed to create overlay (check stderr)");
+            return;
+        }
+
+        if (!registry_add(reg, id, o)) {
+            overlay_free(o);
+            char buf[128]; snprintf(buf, sizeof buf, "ERR id '%s' already exists", id);
+            send_line(client_fd, buf);
+            return;
+        }
+
+        char buf[256];
+        int ox, oy, ow, oh;
+        overlay_get_rect(o, &ox, &oy, &ow, &oh);
+        snprintf(buf, sizeof buf, "OK added %s overlay '%s' at (%d,%d) size=%dx%d",
+                 type, id, ox, oy, ow, oh);
+        send_line(client_fd, buf);
+        return;
+    }
+
+    char buf[256];
+    snprintf(buf, sizeof buf, "ERR unknown command '%s'", cmd);
+    send_line(client_fd, buf);
+}
+
+/* ── server thread ───────────────────────────── */
+static void *ipc_thread(void *arg)
+{
+    IPCServer *srv = arg;
+
+    while (srv->running) {
+        struct sockaddr_un peer;
+        socklen_t peer_len = sizeof peer;
+        int client = accept(srv->server_fd, (struct sockaddr *)&peer, &peer_len);
+        if (client < 0) {
+            if (srv->running) perror("[ipc] accept");
+            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;
+        }
+        close(client);
+    }
+    return NULL;
+}
+
+/* ── public API ──────────────────────────────── */
+bool ipc_start(IPCServer *srv, OverlayRegistry *reg)
+{
+    srv->registry = reg;
+    srv->running  = true;
+
+    unlink(VCAM_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);
+
+    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);
+
+    if (listen(srv->server_fd, 4) < 0) {
+        perror("[ipc] listen"); close(srv->server_fd); return false;
+    }
+
+    if (pthread_create(&srv->thread, NULL, ipc_thread, srv) != 0) {
+        perror("[ipc] pthread_create"); close(srv->server_fd); return false;
+    }
+
+    fprintf(stderr, "[ipc] Listening on %s\n", VCAM_SOCK_PATH);
+    return true;
+}
+
+void ipc_stop(IPCServer *srv)
+{
+    srv->running = false;
+    shutdown(srv->server_fd, SHUT_RDWR);
+    close(srv->server_fd);
+    pthread_join(srv->thread, NULL);
+    unlink(VCAM_SOCK_PATH);
+}
diff --git a/src/main.c b/src/main.c
new file mode 100644
index 0000000..475f454
--- /dev/null
+++ b/src/main.c
@@ -0,0 +1,335 @@
+/*
+ * vcam – virtual webcam pipeline with runtime control
+ *
+ * Usage:  vcam [OPTIONS]
+ *
+ * Pipeline options:
+ *   -i <device>   Input webcam device   (default: /dev/video1)
+ *   -o <device>   Output v4l2loopback   (default: /dev/video0)
+ *   -W <px>       Output width          (default: camera native)
+ *   -H <px>       Output height         (default: camera native)
+ *   -f <fps>      Output frame rate     (default: camera native)
+ *
+ * Startup overlays (same syntax as IPC 'add' command):
+ *   --img    <id> <x> <y> [<w> <h>] <file>
+ *   --vid    <id> <x> <y> [<w> <h>] <file>
+ *   --screen <id> <x> <y> [<w> <h>] <geometry>
+ *
+ * Runtime control via Unix socket /tmp/vcam.sock:
+ *   echo "list"                       | nc -U /tmp/vcam.sock
+ *   echo "add img logo 10 10 200 200 /path/to/logo.png" | nc -U /tmp/vcam.sock
+ *   echo "remove logo"                | nc -U /tmp/vcam.sock
+ *   echo "move logo 50 50"            | nc -U /tmp/vcam.sock
+ *   echo "resize logo 300 300"        | nc -U /tmp/vcam.sock
+ *   echo "add screen scr 0 0 640 360 1920x1080+0+0" | nc -U /tmp/vcam.sock
+ *   vcam-ctl <command>                (convenience wrapper)
+ */
+
+#include "vcam.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <stdbool.h>
+#include <time.h>
+#include <sys/wait.h>
+
+#include <libavutil/log.h>
+
+/* ── global state ─────────────────────────────── */
+static volatile bool    g_running = true;
+static OverlayRegistry  g_registry;
+static IPCServer        g_ipc;
+FilterChain             g_filters; /* extern'd by ipc.c */
+
+static void on_signal(int sig)
+{
+    (void)sig;
+    g_running = false;
+}
+
+static void on_sigchld(int sig)
+{
+    (void)sig;
+    /* Reap any dead screen-capture child processes */
+    while (waitpid(-1, NULL, WNOHANG) > 0) {}
+}
+
+/* ── arg helpers ───────────────────────────────── */
+static bool is_flag(const char *s)
+{
+    return s && s[0] == '-';
+}
+
+/* Parse optional [w] [h] before the final path/geometry token.
+ * Supports: "w h path", "w path", or just "path".
+ * Returns how many extra argv slots were consumed. */
+static int try_wh(char *argv[], int i, int argc, int *w, int *h)
+{
+    if (i >= argc || is_flag(argv[i])) return 0;
+    char *endp;
+    long v0 = strtol(argv[i], &endp, 10);
+    if (*endp != '\0') return 0;
+
+    if (i+1 < argc && !is_flag(argv[i+1])) {
+        long v1 = strtol(argv[i+1], &endp, 10);
+        if (*endp == '\0' && i+2 < argc) {
+            *w = (int)v0; *h = (int)v1;
+            return 2;
+        }
+    }
+    if (i+1 < argc) { *w = (int)v0; *h = 0; return 1; }
+    return 0;
+}
+
+/* ── main ──────────────────────────────────────── */
+int main(int argc, char *argv[])
+{
+    const char *input_dev  = "/dev/video1";
+    const char *output_dev = "/dev/video0";
+    int  width = 0, height = 0, fps = 0;
+    bool no_input = false;     /* --no-input: skip webcam capture entirely */
+
+    registry_init(&g_registry);
+    filter_chain_init(&g_filters);
+
+    /* ── parse args ── */
+    for (int i = 1; i < argc; i++) {
+        if (strcmp(argv[i], "-i") == 0 && i+1 < argc) {
+            input_dev = argv[++i];
+
+        } else if (strcmp(argv[i], "-o") == 0 && i+1 < argc) {
+            output_dev = argv[++i];
+
+        } else if (strcmp(argv[i], "-W") == 0 && i+1 < argc) {
+            width  = atoi(argv[++i]);
+
+        } else if (strcmp(argv[i], "-H") == 0 && i+1 < argc) {
+            height = atoi(argv[++i]);
+
+        } else if (strcmp(argv[i], "-f") == 0 && i+1 < argc) {
+            fps    = atoi(argv[++i]);
+
+        } else if (strcmp(argv[i], "--no-input") == 0) {
+            no_input = true;
+
+        } else if (strcmp(argv[i], "--filter") == 0 && i+1 < argc) {
+            /* --filter <name> [<param>] */
+            const char *name = argv[++i];
+            FilterType t = filter_type_from_name(name);
+            if (t == FX_UNKNOWN) {
+                fprintf(stderr, "[main] Unknown filter '%s'\n", name);
+                continue;
+            }
+            float param = filter_default_param(t);
+            if (i+1 < argc && !is_flag(argv[i+1])) {
+                char *ep;
+                float v = strtof(argv[i+1], &ep);
+                if (*ep == '\0') { param = v; i++; }
+            }
+            filter_chain_add(&g_filters, t, param);
+
+        } else if ((strcmp(argv[i], "--img") == 0 ||
+                    strcmp(argv[i], "--vid") == 0 ||
+                    strcmp(argv[i], "--vid-once") == 0 ||
+                    strcmp(argv[i], "--screen") == 0) && i+4 < argc) {
+
+            const char *flag = argv[i];
+            const char *kind = (strncmp(flag, "--vid", 5) == 0) ? "vid" :
+                               (strcmp(flag, "--img") == 0)     ? "img" : "screen";
+            bool vid_loop    = (strcmp(flag, "--vid-once") != 0); /* once = no loop */
+            const char *id   = argv[++i];
+            int x = atoi(argv[++i]);
+            int y = atoi(argv[++i]);
+            int w = 0, h = 0;
+            int extra = try_wh(argv, i+1, argc, &w, &h);
+            i += extra;
+            if (i+1 >= argc) {
+                fprintf(stderr, "[main] Missing file/geometry for %s\n", flag);
+                continue;
+            }
+            const char *path = argv[++i];
+
+            Overlay *o = NULL;
+            if (strcmp(kind, "img") == 0)
+                o = overlay_create_image(path, x, y, w, h);
+            else if (strcmp(kind, "vid") == 0)
+                o = overlay_create_video(path, x, y, w, h, vid_loop);
+            else
+                o = overlay_create_screen(path, x, y, w, h);
+
+            if (!o) {
+                fprintf(stderr, "[main] Failed to create %s overlay '%s'\n", kind, id);
+                continue;
+            }
+            if (!registry_add(&g_registry, id, o))
+                overlay_free(o);
+
+        } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
+            puts(
+"vcam – virtual webcam pipeline\n\n"
+"Usage: vcam [OPTIONS]\n\n"
+"Pipeline:\n"
+"  -i <dev>       Input webcam       (default /dev/video1)\n"
+"  -o <dev>       Output loopback    (default /dev/video0)\n"
+"  -W <px>        Width\n"
+"  -H <px>        Height\n"
+"  -f <fps>       Frame rate\n"
+"  --no-input     Don't open a webcam (use screen overlays as source).\n"
+"                 Combine with -W -H and a fullscreen --screen overlay.\n\n"
+"Startup overlays:\n"
+"  --img    <id> <x> <y> [<w> [<h>]] <file>\n"
+"  --vid    <id> <x> <y> [<w> [<h>]] <file>\n"
+"  --screen <id> <x> <y> [<w> [<h>]] <WxH+X+Y>\n\n"
+"Startup filters (chain order matters):\n"
+"  --filter <name> [<param>]\n"
+"  Available: grayscale, sepia, invert, mirror, flip,\n"
+"             pixelate <block>, blur <radius>, vignette <0..1>,\n"
+"             brightness <mult>, contrast <mult>, posterize <levels>, edges\n\n"
+"Runtime control (vcam-ctl):\n"
+"  vcam-ctl list\n"
+"  vcam-ctl add img|vid|screen <id> <x> <y> [<w> [<h>]] <file>\n"
+"  vcam-ctl remove|move|resize ...\n"
+"  vcam-ctl filter add <name> [<param>]\n"
+"  vcam-ctl filter remove <index>\n"
+"  vcam-ctl filter list / clear\n"
+            );
+            registry_destroy(&g_registry);
+            filter_chain_destroy(&g_filters);
+            return 0;
+
+        } else {
+            fprintf(stderr, "[main] Unknown option: %s  (try --help)\n", argv[i]);
+        }
+    }
+
+    /* ── signals ── */
+    signal(SIGINT,  on_signal);
+    signal(SIGTERM, on_signal);
+    signal(SIGCHLD, on_sigchld);
+    signal(SIGPIPE, SIG_IGN);
+
+    /* Silence libav's INFO/WARNING spam — "deprecated pixel format used"
+     * (JPEG full-range YUV), "EOI missing, emulating" (slightly malformed
+     * MJPEG from some webcams), etc. We still see real errors. */
+    av_log_set_level(AV_LOG_ERROR);
+
+    /* ── open capture (unless --no-input) ── */
+    V4L2Capture *cap = NULL;
+    if (!no_input) {
+        cap = capture_open(input_dev, &width, &height, &fps);
+        if (!cap) { registry_destroy(&g_registry); filter_chain_destroy(&g_filters); return 1; }
+    } else {
+        if (width <= 0 || height <= 0) {
+            fprintf(stderr, "[main] --no-input requires -W and -H\n");
+            registry_destroy(&g_registry); filter_chain_destroy(&g_filters); return 1;
+        }
+        if (fps <= 0) fps = 30;
+        fprintf(stderr, "[main] No-input mode: %dx%d @ %d fps (no webcam opened)\n",
+                width, height, fps);
+    }
+
+    /* ── open output ── */
+    V4L2Output *out = output_open(output_dev, width, height, fps);
+    if (!out) {
+        if (cap) capture_close(cap);
+        registry_destroy(&g_registry); filter_chain_destroy(&g_filters);
+        return 1;
+    }
+
+    /* ── start IPC server ── */
+    if (!ipc_start(&g_ipc, &g_registry)) {
+        fprintf(stderr, "[main] IPC server failed to start (continuing without it)\n");
+    }
+
+    /* ── allocate work frames ──
+     * cam_buf holds the filtered webcam (or stays black in --no-input
+     * mode); webcam overlays sample from it. frame is the output
+     * frame that overlays composite onto. Keeping them separate so
+     * overlay blits don't pollute the webcam source. */
+    Frame *cam_buf = frame_alloc(width, height);
+    Frame *frame   = frame_alloc(width, height);
+    if (!cam_buf || !frame) {
+        ipc_stop(&g_ipc);
+        output_close(out);
+        if (cap) capture_close(cap);
+        registry_destroy(&g_registry); filter_chain_destroy(&g_filters);
+        return 1;
+    }
+
+    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] %d startup overlay(s), %d startup filter(s).\n",
+            g_registry.count, g_filters.count);
+
+    long frame_ns = fps > 0 ? (1000000000L / fps) : 33333333L;
+
+    /* ── main loop ── */
+    while (g_running) {
+        struct timespec t0;
+        clock_gettime(CLOCK_MONOTONIC, &t0);
+
+        /* 1. Capture the webcam (if open) into cam_buf */
+        if (cap) {
+            if (!capture_read(cap, cam_buf))
+                continue;
+        } else {
+            memset(cam_buf->data, 0,
+                   (size_t)cam_buf->stride * cam_buf->height);
+        }
+
+        /* 2. Apply filter chain to cam_buf — filters operate on the
+         *    raw camera stream, so they affect both the base AND any
+         *    webcam-corner overlays consistently. */
+        filter_chain_apply(&g_filters, cam_buf);
+
+        /* 3. Build the base frame. Default = filtered cam. With
+         *    --no-input the base is black (screen/image overlays will
+         *    paint on top). */
+        if (!no_input) {
+            memcpy(frame->data, cam_buf->data,
+                   (size_t)cam_buf->stride * cam_buf->height);
+        } else {
+            memset(frame->data, 0,
+                   (size_t)frame->stride * frame->height);
+        }
+
+        /* 4. Composite overlays. Webcam overlays read from cam_buf
+         *    (so they always show the latest filtered cam, not the
+         *    accumulating composite). */
+        pthread_mutex_lock(&g_registry.lock);
+        for (int i = 0; i < g_registry.count; i++) {
+            Overlay *o = g_registry.slots[i].overlay;
+            overlay_tick(o, cam_buf);
+            overlay_blit(o, frame);
+        }
+        pthread_mutex_unlock(&g_registry.lock);
+
+        output_write(out, frame);
+
+        /* Frame pacing */
+        struct timespec t1;
+        clock_gettime(CLOCK_MONOTONIC, &t1);
+        long elapsed = (t1.tv_sec - t0.tv_sec) * 1000000000L
+                     + (t1.tv_nsec - t0.tv_nsec);
+        long remaining = frame_ns - elapsed;
+        if (remaining > 1000000L) {
+            struct timespec sl = { remaining / 1000000000L, remaining % 1000000000L };
+            nanosleep(&sl, NULL);
+        }
+    }
+
+    fprintf(stderr, "\n[main] Shutting down.\n");
+
+    ipc_stop(&g_ipc);
+    frame_free(frame);
+    frame_free(cam_buf);
+    output_close(out);
+    if (cap) capture_close(cap);
+    registry_destroy(&g_registry);
+    filter_chain_destroy(&g_filters);
+    return 0;
+}
diff --git a/src/output.c b/src/output.c
new file mode 100644
index 0000000..340ba89
--- /dev/null
+++ b/src/output.c
@@ -0,0 +1,256 @@
+/*
+ * V4L2 output to v4l2loopback using streaming I/O (MMAP buffers).
+ *
+ * This matches how real V4L2 capture drivers feed their output buffers,
+ * making the loopback device behave the same way as a physical webcam
+ * from the consumer's perspective (Firefox, Chromium, OBS, etc.).
+ *
+ * Flow:
+ *   1. open device
+ *   2. VIDIOC_S_FMT  (YUYV422, proper colorspace tags)
+ *   3. VIDIOC_REQBUFS (OUTPUT type, MMAP, N buffers)
+ *   4. mmap each buffer
+ *   5. for each frame:
+ *        - find a free (dequeued) buffer
+ *        - convert BGR24 → YUYV422 directly into the buffer
+ *        - VIDIOC_QBUF to publish it
+ *        - VIDIOC_STREAMON on the first publish
+ *        - VIDIOC_DQBUF when no free buffers remain to recycle one
+ */
+
+#include "vcam.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <errno.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <linux/videodev2.h>
+
+#include <libswscale/swscale.h>
+#include <libavutil/imgutils.h>
+
+#define NUM_OUT_BUFS 4
+
+typedef struct {
+    void  *start;
+    size_t length;
+    bool   queued; /* true if currently held by the kernel */
+} OutBuf;
+
+struct V4L2Output {
+    int    fd;
+    int    width, height;
+    int    frame_size;            /* bytes per YUYV frame */
+    OutBuf bufs[NUM_OUT_BUFS];
+    int    nbuf;
+    bool   streaming;             /* STREAMON called yet? */
+
+    struct SwsContext *sws;       /* BGR24 → YUYV422 */
+};
+
+static int xioctl(int fd, unsigned long req, void *arg)
+{
+    int r;
+    do { r = ioctl(fd, req, arg); } while (r == -1 && errno == EINTR);
+    return r;
+}
+
+V4L2Output *output_open(const char *device, int width, int height, int fps)
+{
+    V4L2Output *out = calloc(1, sizeof *out);
+    if (!out) return NULL;
+
+    out->fd = open(device, O_RDWR);
+    if (out->fd < 0) {
+        fprintf(stderr, "[output] Cannot open %s: %s\n"
+                        "  Load v4l2loopback with exclusive_caps=1:\n"
+                        "    sudo modprobe v4l2loopback video_nr=0 "
+                        "card_label=\"vcam\" exclusive_caps=1\n",
+                device, strerror(errno));
+        free(out);
+        return NULL;
+    }
+
+    /* ── verify device exposes V4L2_CAP_VIDEO_OUTPUT ── */
+    struct v4l2_capability cap = {0};
+    if (xioctl(out->fd, VIDIOC_QUERYCAP, &cap) < 0) {
+        perror("[output] VIDIOC_QUERYCAP");
+        close(out->fd); free(out); return NULL;
+    }
+    __u32 caps = cap.capabilities & V4L2_CAP_DEVICE_CAPS
+                ? cap.device_caps : cap.capabilities;
+    if (!(caps & V4L2_CAP_VIDEO_OUTPUT)) {
+        fprintf(stderr, "[output] %s does not support VIDEO_OUTPUT\n"
+                        "  Is this really a v4l2loopback device?\n", device);
+        close(out->fd); free(out); return NULL;
+    }
+
+    /* ── set format: YUYV422 with proper colorspace tags ── */
+    struct v4l2_format fmt = {0};
+    fmt.type                       = V4L2_BUF_TYPE_VIDEO_OUTPUT;
+    fmt.fmt.pix.width              = width;
+    fmt.fmt.pix.height             = height;
+    fmt.fmt.pix.pixelformat        = V4L2_PIX_FMT_YUYV;
+    fmt.fmt.pix.field              = V4L2_FIELD_NONE;
+    fmt.fmt.pix.bytesperline       = width * 2;
+    fmt.fmt.pix.sizeimage          = width * height * 2;
+    /* Use BT.709 for HD, BT.601 for SD — same as real cameras */
+    fmt.fmt.pix.colorspace         = (height >= 720)
+                                      ? V4L2_COLORSPACE_REC709
+                                      : V4L2_COLORSPACE_SMPTE170M;
+    fmt.fmt.pix.ycbcr_enc          = V4L2_YCBCR_ENC_DEFAULT;
+    fmt.fmt.pix.quantization       = V4L2_QUANTIZATION_DEFAULT;
+    fmt.fmt.pix.xfer_func          = V4L2_XFER_FUNC_DEFAULT;
+
+    if (xioctl(out->fd, VIDIOC_S_FMT, &fmt) < 0) {
+        perror("[output] VIDIOC_S_FMT");
+        close(out->fd); free(out); return NULL;
+    }
+
+    if (fmt.fmt.pix.pixelformat != V4L2_PIX_FMT_YUYV) {
+        char got[5] = {0};
+        memcpy(got, &fmt.fmt.pix.pixelformat, 4);
+        fprintf(stderr, "[output] WARNING: driver gave us '%s' not YUYV\n", got);
+    }
+
+    /* Use whatever the driver settled on (may have rounded dims) */
+    out->width      = fmt.fmt.pix.width;
+    out->height     = fmt.fmt.pix.height;
+    out->frame_size = out->width * out->height * 2;
+
+    /* ── advertise frame rate ── */
+    struct v4l2_streamparm parm = {0};
+    parm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
+    parm.parm.output.timeperframe.numerator   = 1;
+    parm.parm.output.timeperframe.denominator = fps > 0 ? fps : 30;
+    if (xioctl(out->fd, VIDIOC_S_PARM, &parm) < 0) {
+        /* not fatal — some drivers don't accept S_PARM on output */
+    }
+
+    /* ── request mmap output buffers ── */
+    struct v4l2_requestbuffers req = {0};
+    req.count  = NUM_OUT_BUFS;
+    req.type   = V4L2_BUF_TYPE_VIDEO_OUTPUT;
+    req.memory = V4L2_MEMORY_MMAP;
+    if (xioctl(out->fd, VIDIOC_REQBUFS, &req) < 0) {
+        perror("[output] VIDIOC_REQBUFS");
+        close(out->fd); free(out); return NULL;
+    }
+    out->nbuf = req.count;
+    if (out->nbuf < 2) {
+        fprintf(stderr, "[output] need at least 2 buffers, got %d\n", out->nbuf);
+        close(out->fd); free(out); return NULL;
+    }
+
+    /* ── mmap each buffer ── */
+    for (int i = 0; i < out->nbuf; i++) {
+        struct v4l2_buffer buf = {0};
+        buf.type   = V4L2_BUF_TYPE_VIDEO_OUTPUT;
+        buf.memory = V4L2_MEMORY_MMAP;
+        buf.index  = i;
+        if (xioctl(out->fd, VIDIOC_QUERYBUF, &buf) < 0) {
+            perror("[output] VIDIOC_QUERYBUF");
+            close(out->fd); free(out); return NULL;
+        }
+        out->bufs[i].length = buf.length;
+        out->bufs[i].start  = mmap(NULL, buf.length,
+                                    PROT_READ | PROT_WRITE, MAP_SHARED,
+                                    out->fd, buf.m.offset);
+        if (out->bufs[i].start == MAP_FAILED) {
+            perror("[output] mmap");
+            close(out->fd); free(out); return NULL;
+        }
+        out->bufs[i].queued = false;
+    }
+
+    /* ── BGR24 → YUYV422 converter ── */
+    out->sws = sws_getContext(out->width, out->height, AV_PIX_FMT_BGR24,
+                               out->width, out->height, AV_PIX_FMT_YUYV422,
+                               SWS_BILINEAR, NULL, NULL, NULL);
+    if (!out->sws) {
+        fprintf(stderr, "[output] sws_getContext failed\n");
+        close(out->fd); free(out); return NULL;
+    }
+
+    fprintf(stderr, "[output] %s  %dx%d @ %d fps  YUYV422  "
+                    "colorspace=%s  buffers=%d (streaming I/O)\n",
+            device, out->width, out->height, fps,
+            (out->height >= 720) ? "BT.709" : "BT.601",
+            out->nbuf);
+    return out;
+}
+
+bool output_write(V4L2Output *out, const Frame *frame)
+{
+    /* Find a free (not-queued) buffer */
+    int idx = -1;
+    for (int i = 0; i < out->nbuf; i++) {
+        if (!out->bufs[i].queued) { idx = i; break; }
+    }
+
+    if (idx < 0) {
+        /* All buffers in kernel — dequeue one back */
+        struct v4l2_buffer buf = {0};
+        buf.type   = V4L2_BUF_TYPE_VIDEO_OUTPUT;
+        buf.memory = V4L2_MEMORY_MMAP;
+        if (xioctl(out->fd, VIDIOC_DQBUF, &buf) < 0) {
+            if (errno == EAGAIN) return true;
+            perror("[output] VIDIOC_DQBUF");
+            return false;
+        }
+        idx = buf.index;
+        out->bufs[idx].queued = false;
+    }
+
+    /* Convert BGR24 → YUYV422 directly into the mmap'd buffer */
+    const uint8_t *src[4] = { frame->data, NULL, NULL, NULL };
+    int src_stride[4]     = { frame->stride, 0, 0, 0 };
+    uint8_t *dst[4]       = { out->bufs[idx].start, NULL, NULL, NULL };
+    int dst_stride[4]     = { out->width * 2, 0, 0, 0 };
+
+    sws_scale(out->sws, src, src_stride, 0, out->height, dst, dst_stride);
+
+    /* Queue it to the kernel */
+    struct v4l2_buffer qbuf = {0};
+    qbuf.type      = V4L2_BUF_TYPE_VIDEO_OUTPUT;
+    qbuf.memory    = V4L2_MEMORY_MMAP;
+    qbuf.index     = idx;
+    qbuf.bytesused = out->frame_size;
+    qbuf.field     = V4L2_FIELD_NONE;
+    if (xioctl(out->fd, VIDIOC_QBUF, &qbuf) < 0) {
+        perror("[output] VIDIOC_QBUF");
+        return false;
+    }
+    out->bufs[idx].queued = true;
+
+    /* Start streaming once the first buffer is queued */
+    if (!out->streaming) {
+        enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
+        if (xioctl(out->fd, VIDIOC_STREAMON, &type) < 0) {
+            perror("[output] VIDIOC_STREAMON");
+            return false;
+        }
+        out->streaming = true;
+        fprintf(stderr, "[output] streaming started\n");
+    }
+    return true;
+}
+
+void output_close(V4L2Output *out)
+{
+    if (!out) return;
+    if (out->streaming) {
+        enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
+        xioctl(out->fd, VIDIOC_STREAMOFF, &type);
+    }
+    for (int i = 0; i < out->nbuf; i++)
+        if (out->bufs[i].start && out->bufs[i].start != MAP_FAILED)
+            munmap(out->bufs[i].start, out->bufs[i].length);
+    if (out->sws) sws_freeContext(out->sws);
+    close(out->fd);
+    free(out);
+}
diff --git a/src/overlay.c b/src/overlay.c
new file mode 100644
index 0000000..3d7f38c
--- /dev/null
+++ b/src/overlay.c
@@ -0,0 +1,949 @@
+#include "vcam.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <unistd.h>
+#include <signal.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <time.h>
+#include <poll.h>
+
+#include <libavcodec/avcodec.h>
+#include <libavformat/avformat.h>
+#include <libavutil/imgutils.h>
+#include <libswscale/swscale.h>
+#include <png.h>
+
+/* ──────────────────────────────────────────────────────────────
+ * Overlay struct
+ * ────────────────────────────────────────────────────────────── */
+struct Overlay {
+    OverlayType type;
+
+    int dst_x, dst_y, dst_w, dst_h;
+
+    uint8_t *pixels;   /* BGR24 or BGRA pixel buffer */
+    int      bpp;      /* 3 = BGR24, 4 = BGRA        */
+
+    /* ── image-overlay-only: keep the decoded source at its native
+     * resolution so we can re-scale on resize without re-reading
+     * the file. NULL for non-image overlays. ── */
+    uint8_t *src_pixels;
+    int      src_bpp_img;
+
+    /* ── video fields ── */
+    AVFormatContext  *fmt_ctx;
+    AVCodecContext   *codec_ctx;
+    AVFrame          *av_frame;
+    AVPacket         *av_pkt;
+    struct SwsContext *sws;
+    int               stream_idx;
+    bool              vid_loop;        /* if true, restart on EOF */
+    bool              vid_eof_sent;    /* flush sentinel already sent */
+    bool              vid_finished;    /* play-once + EOF reached → keep last frame */
+
+    int src_w, src_h;
+
+    /* ── screen capture fields ── */
+    pid_t    child_pid;
+    int      pipe_fd;        /* read end of pipe/fifo from capture child   */
+    char     fifo_path[128]; /* path if using a FIFO (Wayland), else ""    */
+    int      src_bpp;        /* bytes per pixel from child: 3=BGR24 4=BGR0 */
+    size_t   raw_bytes;      /* bytes per frame from child                 */
+
+    /* Dedicated reader thread: pulls frames as fast as possible into
+     * latest_frame, so the main loop always uses the freshest data
+     * (minimizing capture-to-output latency). */
+    pthread_t       reader_thread;
+    bool            reader_running;
+    bool            reader_shutdown;
+    pthread_mutex_t latest_lock;
+    uint8_t        *latest_frame;  /* protected by latest_lock */
+    bool            has_frame;     /* protected by latest_lock */
+
+    /* ── webcam-overlay fields ──
+     * Webcam overlays don't open a V4L2 device themselves (V4L2 only
+     * permits one streamer per cam). Instead they reference the main
+     * pipeline's shared capture, which the main loop passes into
+     * overlay_tick() each frame. */
+    int webcam_src_w, webcam_src_h;  /* cached src dims for sws caching */
+};
+
+/* ──────────────────────────────────────────────────────────────
+ * Helpers
+ * ────────────────────────────────────────────────────────────── */
+static void rebuild_sws(Overlay *o, int sw, int sh, int sfmt)
+{
+    if (o->sws) sws_freeContext(o->sws);
+    o->sws = sws_getContext(sw, sh, sfmt,
+                             o->dst_w, o->dst_h, AV_PIX_FMT_BGR24,
+                             SWS_BILINEAR, NULL, NULL, NULL);
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * PNG loader → BGRA
+ * ────────────────────────────────────────────────────────────── */
+static uint8_t *load_png(const char *path, int *w, int *h, bool *has_alpha)
+{
+    FILE *fp = fopen(path, "rb");
+    if (!fp) { perror(path); return NULL; }
+
+    png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+    png_infop info  = png_create_info_struct(png);
+    if (!png || !info || setjmp(png_jmpbuf(png))) { fclose(fp); return NULL; }
+
+    png_init_io(png, fp);
+    png_read_info(png, info);
+
+    *w = (int)png_get_image_width(png, info);
+    *h = (int)png_get_image_height(png, info);
+    png_byte ct = png_get_color_type(png, info);
+    png_byte bd = png_get_bit_depth(png, info);
+
+    if (bd == 16) png_set_strip_16(png);
+    if (ct == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png);
+    if (ct == PNG_COLOR_TYPE_GRAY && bd < 8) png_set_expand_gray_1_2_4_to_8(png);
+    if (png_get_valid(png, info, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png);
+    if (ct == PNG_COLOR_TYPE_RGB || ct == PNG_COLOR_TYPE_GRAY ||
+        ct == PNG_COLOR_TYPE_PALETTE)
+        png_set_filler(png, 0xFF, PNG_FILLER_AFTER);
+    if (ct == PNG_COLOR_TYPE_GRAY || ct == PNG_COLOR_TYPE_GRAY_ALPHA)
+        png_set_gray_to_rgb(png);
+    png_read_update_info(png, info);
+
+    *has_alpha = !!(png_get_color_type(png, info) & PNG_COLOR_MASK_ALPHA);
+    size_t rb = png_get_rowbytes(png, info);
+    uint8_t *rgba = malloc(rb * *h);
+    png_bytep *rows = malloc(*h * sizeof *rows);
+    for (int i = 0; i < *h; i++) rows[i] = rgba + i * rb;
+    png_read_image(png, rows);
+    free(rows);
+    png_destroy_read_struct(&png, &info, NULL);
+    fclose(fp);
+
+    uint8_t *bgra = malloc((size_t)*w * *h * 4);
+    for (int i = 0; i < *w * *h; i++) {
+        bgra[i*4+0] = rgba[i*4+2];
+        bgra[i*4+1] = rgba[i*4+1];
+        bgra[i*4+2] = rgba[i*4+0];
+        bgra[i*4+3] = rgba[i*4+3];
+    }
+    free(rgba);
+    return bgra;
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * JPEG / generic image loader → BGR24 (via FFmpeg)
+ * ────────────────────────────────────────────────────────────── */
+static uint8_t *load_jpeg_bgr(const char *path, int *w, int *h)
+{
+    AVFormatContext *fmt = NULL;
+    if (avformat_open_input(&fmt, path, NULL, NULL) < 0) return NULL;
+    avformat_find_stream_info(fmt, NULL);
+
+    int idx = -1;
+    for (unsigned i = 0; i < fmt->nb_streams; i++)
+        if (fmt->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
+            { idx = (int)i; break; }
+    if (idx < 0) { avformat_close_input(&fmt); return NULL; }
+
+    const AVCodec *codec = avcodec_find_decoder(fmt->streams[idx]->codecpar->codec_id);
+    AVCodecContext *cc   = avcodec_alloc_context3(codec);
+    avcodec_parameters_to_context(cc, fmt->streams[idx]->codecpar);
+    avcodec_open2(cc, codec, NULL);
+
+    AVFrame  *frame = av_frame_alloc();
+    AVPacket *pkt   = av_packet_alloc();
+    uint8_t  *out   = NULL;
+
+    while (av_read_frame(fmt, pkt) >= 0 && !out) {
+        if (pkt->stream_index == idx) {
+            avcodec_send_packet(cc, pkt);
+            if (avcodec_receive_frame(cc, frame) == 0) {
+                *w = frame->width; *h = frame->height;
+                out = malloc((size_t)*w * *h * 3);
+                struct SwsContext *sws = sws_getContext(
+                    *w, *h, frame->format, *w, *h, AV_PIX_FMT_BGR24,
+                    SWS_BILINEAR, NULL, NULL, NULL);
+                uint8_t *d[4] = { out }; int dl[4] = { *w*3 };
+                sws_scale(sws, (const uint8_t *const *)frame->data,
+                          frame->linesize, 0, *h, d, dl);
+                sws_freeContext(sws);
+            }
+        }
+        av_packet_unref(pkt);
+    }
+    av_frame_free(&frame); av_packet_free(&pkt);
+    avcodec_free_context(&cc); avformat_close_input(&fmt);
+    return out;
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * Compute dst dimensions: support specifying only w or only h,
+ * deriving the other from the source aspect ratio.
+ * dst_w / dst_h of 0 means "not specified".
+ * ────────────────────────────────────────────────────────────── */
+static void resolve_dims(int src_w, int src_h,
+                          int req_w, int req_h,
+                          int *out_w, int *out_h)
+{
+    if (req_w > 0 && req_h > 0) {
+        *out_w = req_w; *out_h = req_h;
+    } else if (req_w > 0) {
+        *out_w = req_w;
+        *out_h = src_h > 0 ? (req_w * src_h / src_w) : req_w;
+    } else if (req_h > 0) {
+        *out_h = req_h;
+        *out_w = src_w > 0 ? (req_h * src_w / src_h) : req_h;
+    } else {
+        *out_w = src_w; *out_h = src_h;
+    }
+    /* Ensure even dimensions (some codecs require it) */
+    if (*out_w & 1) (*out_w)++;
+    if (*out_h & 1) (*out_h)++;
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * overlay_create_image
+ * ────────────────────────────────────────────────────────────── */
+Overlay *overlay_create_image(const char *path,
+                               int dst_x, int dst_y, int dst_w, int dst_h)
+{
+    Overlay *o = calloc(1, sizeof *o);
+    if (!o) return NULL;
+    o->type    = OVERLAY_IMAGE;
+    o->dst_x   = dst_x; o->dst_y = dst_y;
+    o->pipe_fd = -1;
+
+    const char *ext = strrchr(path, '.');
+    bool is_png = ext && strcasecmp(ext, ".png") == 0;
+
+    int sw = 0, sh = 0;
+    bool has_alpha = false;
+    uint8_t *src = NULL;
+
+    if (is_png) {
+        src = load_png(path, &sw, &sh, &has_alpha);
+        if (!src) { free(o); return NULL; }
+        o->bpp = 4;
+    } else {
+        src = load_jpeg_bgr(path, &sw, &sh);
+        if (!src) { free(o); return NULL; }
+        o->bpp = 3;
+    }
+
+    /* Keep source pixels for future resizes */
+    o->src_pixels   = src;
+    o->src_bpp_img  = o->bpp;
+    o->src_w = sw; o->src_h = sh;
+
+    resolve_dims(sw, sh, dst_w, dst_h, &o->dst_w, &o->dst_h);
+
+    /* Allocate dst buffer and scale into it */
+    o->pixels = calloc(1, (size_t)o->dst_w * o->dst_h * o->bpp);
+    if (!o->pixels) { overlay_free(o); return NULL; }
+
+    enum AVPixelFormat fmt = (o->bpp == 4) ? AV_PIX_FMT_BGRA : AV_PIX_FMT_BGR24;
+    if (sw == o->dst_w && sh == o->dst_h) {
+        memcpy(o->pixels, src, (size_t)sw * sh * o->bpp);
+    } else {
+        struct SwsContext *sws = sws_getContext(
+            sw, sh, fmt,
+            o->dst_w, o->dst_h, fmt,
+            SWS_BILINEAR, NULL, NULL, NULL);
+        const uint8_t *s[4] = { src }; int sl[4] = { sw * o->bpp };
+        uint8_t       *d[4] = { o->pixels }; int dl[4] = { o->dst_w * o->bpp };
+        sws_scale(sws, s, sl, 0, sh, d, dl);
+        sws_freeContext(sws);
+    }
+
+    fprintf(stderr, "[overlay] image '%s' %dx%d → %dx%d at (%d,%d)\n",
+            path, sw, sh, o->dst_w, o->dst_h, dst_x, dst_y);
+    return o;
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * overlay_create_video
+ * ────────────────────────────────────────────────────────────── */
+Overlay *overlay_create_video(const char *path,
+                               int dst_x, int dst_y, int dst_w, int dst_h,
+                               bool loop)
+{
+    Overlay *o = calloc(1, sizeof *o);
+    if (!o) return NULL;
+    o->type      = OVERLAY_VIDEO;
+    o->dst_x     = dst_x; o->dst_y = dst_y;
+    o->bpp       = 3;
+    o->pipe_fd   = -1;
+    o->vid_loop  = loop;
+
+    if (avformat_open_input(&o->fmt_ctx, path, NULL, NULL) < 0) {
+        fprintf(stderr, "[overlay] Cannot open %s\n", path);
+        free(o); return NULL;
+    }
+    avformat_find_stream_info(o->fmt_ctx, NULL);
+
+    o->stream_idx = -1;
+    for (unsigned i = 0; i < o->fmt_ctx->nb_streams; i++)
+        if (o->fmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
+            { o->stream_idx = (int)i; break; }
+    if (o->stream_idx < 0) { overlay_free(o); return NULL; }
+
+    AVCodecParameters *cp = o->fmt_ctx->streams[o->stream_idx]->codecpar;
+    const AVCodec *codec  = avcodec_find_decoder(cp->codec_id);
+    o->codec_ctx          = avcodec_alloc_context3(codec);
+    avcodec_parameters_to_context(o->codec_ctx, cp);
+    if (avcodec_open2(o->codec_ctx, codec, NULL) < 0) { overlay_free(o); return NULL; }
+
+    o->src_w = cp->width; o->src_h = cp->height;
+    resolve_dims(o->src_w, o->src_h, dst_w, dst_h, &o->dst_w, &o->dst_h);
+
+    fprintf(stderr, "[overlay] video '%s' %dx%d → %dx%d at (%d,%d) loop=%d\n",
+            path, o->src_w, o->src_h, o->dst_w, o->dst_h, dst_x, dst_y, loop);
+
+    o->av_frame = av_frame_alloc();
+    o->av_pkt   = av_packet_alloc();
+    /* DON'T build sws here — codec_ctx->pix_fmt may be NONE until the
+     * first frame is decoded. We build it lazily in overlay_tick using
+     * av_frame->format, which is always correct. */
+    o->sws = NULL;
+
+    o->pixels = calloc(1, (size_t)o->dst_w * o->dst_h * 3); /* black, not garbage */
+    if (!o->pixels) { overlay_free(o); return NULL; }
+    return o;
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * Screen reader thread
+ *
+ * Runs per-screen-overlay. Drains the FIFO/pipe as fast as the kernel
+ * delivers data, keeping `latest_frame` always pointing at the most
+ * recent fully-decoded frame. The main compositor thread just copies
+ * from latest_frame under the mutex.
+ *
+ * Uses poll() with a 100ms timeout so it can check `reader_shutdown`
+ * and exit promptly when the overlay is destroyed.
+ * ────────────────────────────────────────────────────────────── */
+static void *screen_reader_thread(void *arg)
+{
+    Overlay *o = arg;
+    uint8_t *acc = malloc(o->raw_bytes);
+    if (!acc) return NULL;
+    size_t partial = 0;
+
+    /*
+     * NOTE: on Linux, a FIFO opened read-only reports POLLHUP from poll()
+     * whenever no writer is currently connected — including BEFORE the
+     * writer (wf-recorder) has had a chance to open its end. So we must
+     * NOT treat POLLHUP as a signal to exit. The only authoritative EOF
+     * is `read() == 0` (which only happens after a writer connected and
+     * then closed). Until then we just keep polling.
+     */
+    while (!o->reader_shutdown) {
+        struct pollfd pfd = { .fd = o->pipe_fd, .events = POLLIN };
+        int pr = poll(&pfd, 1, 100);  /* 100 ms wakeup to check shutdown */
+        if (pr <= 0) continue;        /* timeout or interrupt */
+        if (!(pfd.revents & POLLIN)) continue; /* HUP w/o data — keep waiting */
+
+        ssize_t n = read(o->pipe_fd, acc + partial, o->raw_bytes - partial);
+        if (n > 0) {
+            partial += (size_t)n;
+            while (partial >= o->raw_bytes) {
+                pthread_mutex_lock(&o->latest_lock);
+                memcpy(o->latest_frame, acc, o->raw_bytes);
+                o->has_frame = true;
+                pthread_mutex_unlock(&o->latest_lock);
+
+                size_t leftover = partial - o->raw_bytes;
+                if (leftover > 0)
+                    memmove(acc, acc + o->raw_bytes, leftover);
+                partial = leftover;
+            }
+        } else if (n == 0) {
+            /* Real EOF — a writer connected and then closed. We can exit. */
+            break;
+        } else if (errno != EINTR && errno != EAGAIN) {
+            break;
+        }
+    }
+
+    free(acc);
+    return NULL;
+}
+
+/* Snap dimension DOWN to a multiple of `align`, but keep at least `align`. */
+static int snap_down(int v, int align)
+{
+    int r = (v / align) * align;
+    return r >= align ? r : align;
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * overlay_create_screen
+ *
+ * geometry: "WxH+X+Y"
+ *
+ * IMPORTANT: width and height are snapped DOWN to multiples of 16 to
+ * match the alignment that wf-recorder / wlr-screencopy actually
+ * deliver. Mismatched stride causes the captured image to "scroll"
+ * because each frame is offset from the previous by (real - requested).
+ * ────────────────────────────────────────────────────────────── */
+Overlay *overlay_create_screen(const char *geometry,
+                                int dst_x, int dst_y, int dst_w, int dst_h)
+{
+    Overlay *o = calloc(1, sizeof *o);
+    if (!o) return NULL;
+    o->type      = OVERLAY_SCREEN;
+    o->dst_x     = dst_x; o->dst_y = dst_y;
+    o->bpp       = 3;
+    o->pipe_fd   = -1;
+    o->fifo_path[0] = '\0';
+
+    /* Parse "WxH+X+Y" */
+    int gw = 0, gh = 0, gx = 0, gy = 0;
+    if (sscanf(geometry, "%dx%d+%d+%d", &gw, &gh, &gx, &gy) != 4) {
+        fprintf(stderr, "[screen] Bad geometry '%s' (expected WxH+X+Y)\n", geometry);
+        free(o); return NULL;
+    }
+
+    /* Snap to 16-pixel boundaries to match compositor stride */
+    int gw_snapped = snap_down(gw, 16);
+    int gh_snapped = snap_down(gh, 2);
+    if (gw_snapped != gw || gh_snapped != gh) {
+        fprintf(stderr, "[screen] Snapping %dx%d → %dx%d for stride alignment\n",
+                gw, gh, gw_snapped, gh_snapped);
+    }
+    gw = gw_snapped; gh = gh_snapped;
+
+    o->src_w = gw; o->src_h = gh;
+    resolve_dims(gw, gh, dst_w, dst_h, &o->dst_w, &o->dst_h);
+
+    bool wayland = getenv("WAYLAND_DISPLAY") != NULL;
+
+    if (wayland) {
+        /* Unique FIFO path: pid + monotonic counter so two overlays never collide */
+        static int fifo_counter = 0;
+        int n = __atomic_add_fetch(&fifo_counter, 1, __ATOMIC_RELAXED);
+        snprintf(o->fifo_path, sizeof o->fifo_path,
+                 "/tmp/vcam_screen_%d_%d.fifo", (int)getpid(), n);
+        unlink(o->fifo_path);
+        if (mkfifo(o->fifo_path, 0600) < 0) {
+            perror("[screen] mkfifo"); free(o); return NULL;
+        }
+        fprintf(stderr, "[screen] FIFO: %s\n", o->fifo_path);
+
+        /* Open the FIFO read end O_NONBLOCK to avoid blocking before the
+         * writer connects. We'll flip it back to blocking afterwards so
+         * the reader thread can use poll() + blocking read efficiently. */
+        o->pipe_fd = open(o->fifo_path, O_RDONLY | O_NONBLOCK);
+        if (o->pipe_fd < 0) {
+            perror("[screen] open fifo");
+            unlink(o->fifo_path); free(o); return NULL;
+        }
+
+        char wfr_geo[64];
+        snprintf(wfr_geo, sizeof wfr_geo, "%d,%d %dx%d", gx, gy, gw, gh);
+
+        /* wf-recorder asks "Overwrite? Y/n:" when the output file already
+         * exists (our FIFO does). With no terminal it hangs forever waiting
+         * for input — that's the silent black-screen bug. Fix: feed "y\n"
+         * via a stdin pipe so the prompt is auto-answered. */
+        int answer_pipe[2];
+        if (pipe(answer_pipe) < 0) {
+            perror("[screen] stdin pipe");
+            close(o->pipe_fd); unlink(o->fifo_path); free(o); return NULL;
+        }
+        /* Pre-load several "y\n"s — harmless if not consumed */
+        const char *yes = "y\ny\ny\n";
+        ssize_t wn = write(answer_pipe[1], yes, strlen(yes));
+        (void)wn;
+
+        pid_t pid = fork();
+        if (pid < 0) {
+            perror("[screen] fork");
+            close(answer_pipe[0]); close(answer_pipe[1]);
+            close(o->pipe_fd); unlink(o->fifo_path); free(o); return NULL;
+        }
+        if (pid == 0) {
+            /* Replace stdin with the answer pipe so wf-recorder reads "y\n" */
+            dup2(answer_pipe[0], STDIN_FILENO);
+            close(answer_pipe[0]);
+            close(answer_pipe[1]);
+            execlp("wf-recorder", "wf-recorder",
+                   "-g", wfr_geo,
+                   "-c", "rawvideo",
+                   "-x", "bgr0",
+                   "--muxer", "rawvideo",
+                   "-f", o->fifo_path,
+                   (char *)NULL);
+            perror("wf-recorder");
+            _exit(1);
+        }
+        /* parent: close both pipe fds — child already has the read end via dup2 */
+        close(answer_pipe[0]);
+        close(answer_pipe[1]);
+
+        o->child_pid = pid;
+        o->src_bpp   = 4;
+        o->raw_bytes = (size_t)gw * gh * 4;
+        rebuild_sws(o, gw, gh, AV_PIX_FMT_BGR0);
+
+        fprintf(stderr, "[screen] Wayland: wf-recorder -g '%s' (target overlay %dx%d)\n",
+                wfr_geo, o->dst_w, o->dst_h);
+
+        /* Brief sanity check: did the child immediately die? */
+        struct timespec ts200 = { .tv_nsec = 200000000L };
+        nanosleep(&ts200, NULL);
+        int status; pid_t r = waitpid(pid, &status, WNOHANG);
+        if (r == pid) {
+            fprintf(stderr, "[screen] ERROR: wf-recorder exited immediately "
+                            "(status=%d). Is it installed and does your "
+                            "compositor support wlr-screencopy?\n",
+                    WIFEXITED(status) ? WEXITSTATUS(status) : -1);
+            close(o->pipe_fd); unlink(o->fifo_path); free(o); return NULL;
+        }
+
+    } else {
+        int pipefd[2];
+        if (pipe(pipefd) < 0) { perror("[screen] pipe"); free(o); return NULL; }
+
+        pid_t pid = fork();
+        if (pid < 0) {
+            perror("[screen] fork");
+            close(pipefd[0]); close(pipefd[1]); free(o); return NULL;
+        }
+        if (pid == 0) {
+            dup2(pipefd[1], STDOUT_FILENO);
+            close(pipefd[0]); close(pipefd[1]);
+            int devnull = open("/dev/null", O_WRONLY);
+            if (devnull >= 0) { dup2(devnull, STDERR_FILENO); close(devnull); }
+
+            char input[64], size[32];
+            snprintf(input, sizeof input, ":0.0+%d,%d", gx, gy);
+            snprintf(size,  sizeof size,  "%dx%d", gw, gh);
+            execlp("ffmpeg", "ffmpeg",
+                   "-loglevel", "quiet",
+                   "-f", "x11grab",
+                   "-video_size", size,
+                   "-i", input,
+                   "-f", "rawvideo",
+                   "-pix_fmt", "bgr24",
+                   "pipe:1",
+                   (char *)NULL);
+            perror("[screen] ffmpeg x11grab");
+            _exit(1);
+        }
+        close(pipefd[1]);
+        o->child_pid = pid;
+        o->pipe_fd   = pipefd[0];
+        o->src_bpp   = 3;
+        o->raw_bytes = (size_t)gw * gh * 3;
+        rebuild_sws(o, gw, gh, AV_PIX_FMT_BGR24);
+
+        fprintf(stderr, "[screen] X11: ffmpeg x11grab → pipe\n");
+    }
+
+    /* Flip the fd back to BLOCKING — poll() in the reader thread is
+     * cleaner than spinning on EAGAIN. */
+    int flags = fcntl(o->pipe_fd, F_GETFL);
+    fcntl(o->pipe_fd, F_SETFL, flags & ~O_NONBLOCK);
+
+    /* Allocate the latest_frame buffer + pixels buffer (calloc so initial
+     * frames before the reader produces anything are black, not garbage). */
+    o->latest_frame = calloc(1, o->raw_bytes);
+    o->pixels       = calloc(1, (size_t)o->dst_w * o->dst_h * 3);
+    if (!o->latest_frame || !o->pixels) { overlay_free(o); return NULL; }
+
+    pthread_mutex_init(&o->latest_lock, NULL);
+    o->reader_shutdown = false;
+    if (pthread_create(&o->reader_thread, NULL, screen_reader_thread, o) != 0) {
+        perror("[screen] pthread_create");
+        overlay_free(o); return NULL;
+    }
+    o->reader_running = true;
+
+    fprintf(stderr, "[screen] Capturing %dx%d at (%d,%d) → overlay %dx%d at (%d,%d)\n",
+            gw, gh, gx, gy, o->dst_w, o->dst_h, dst_x, dst_y);
+    return o;
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * overlay_create_webcam
+ *
+ * A webcam overlay is just a movable/resizable window onto the main
+ * pipeline's captured webcam frame. It does NOT open a V4L2 device of
+ * its own — V4L2 only allows one streamer per camera, so we share the
+ * main capture and let any number of webcam overlays exist
+ * simultaneously (each at its own position/size).
+ *
+ * Source dimensions are unknown at creation time (we'd need to query
+ * the main loop). For aspect-ratio computation we assume 16:9 by
+ * default — the first tick with a real source frame corrects it.
+ * The user can also pass explicit <w> <h> at creation.
+ * ────────────────────────────────────────────────────────────── */
+Overlay *overlay_create_webcam(const char *device,
+                                int dst_x, int dst_y, int dst_w, int dst_h)
+{
+    (void)device; /* legacy arg — we no longer open per-overlay devices */
+
+    Overlay *o = calloc(1, sizeof *o);
+    if (!o) return NULL;
+    o->type    = OVERLAY_WEBCAM;
+    o->dst_x   = dst_x; o->dst_y = dst_y;
+    o->bpp     = 3;
+    o->pipe_fd = -1;
+
+    /* Default assumption: 16:9. Corrected on first tick. */
+    o->src_w = 640; o->src_h = 360;
+    o->webcam_src_w = 0; o->webcam_src_h = 0; /* "not yet seen" */
+
+    resolve_dims(o->src_w, o->src_h, dst_w, dst_h, &o->dst_w, &o->dst_h);
+
+    o->pixels = calloc(1, (size_t)o->dst_w * o->dst_h * 3);
+    if (!o->pixels) { overlay_free(o); return NULL; }
+
+    /* sws is built lazily on first tick (when we know the real src dims) */
+    o->sws = NULL;
+
+    fprintf(stderr, "[overlay] webcam → %dx%d at (%d,%d) "
+                    "(shares main pipeline's capture)\n",
+            o->dst_w, o->dst_h, dst_x, dst_y);
+    return o;
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * overlay_tick
+ * ────────────────────────────────────────────────────────────── */
+void overlay_tick(Overlay *o, const Frame *webcam_src)
+{
+    if (!o) return;
+
+    if (o->type == OVERLAY_SCREEN) {
+        /* Reader thread fills latest_frame asynchronously. We just
+         * snapshot it under the lock and convert to dst pixels. */
+        pthread_mutex_lock(&o->latest_lock);
+        if (!o->has_frame) {
+            pthread_mutex_unlock(&o->latest_lock);
+            return;
+        }
+        /* Copy out to a local-scope buffer pointer (the underlying memory
+         * stays stable for the rest of the overlay's lifetime). */
+        uint8_t *src = o->latest_frame;
+        int src_stride = o->src_w * o->src_bpp;
+
+        if (o->src_w == o->dst_w && o->src_h == o->dst_h && o->src_bpp == 3) {
+            memcpy(o->pixels, src, o->raw_bytes);
+        } else {
+            const uint8_t *s[4] = { src };       int sl[4] = { src_stride };
+            uint8_t       *d[4] = { o->pixels }; int dl[4] = { o->dst_w * 3 };
+            sws_scale(o->sws, s, sl, 0, o->src_h, d, dl);
+        }
+        pthread_mutex_unlock(&o->latest_lock);
+        return;
+    }
+
+    if (o->type == OVERLAY_WEBCAM) {
+        /* Sample from the shared webcam source the main loop provides.
+         * If no source (i.e. --no-input mode without a captured cam),
+         * leave the previous pixels alone — they'll be calloc'd black
+         * the first time round. */
+        if (!webcam_src || !webcam_src->data) return;
+
+        int sw = webcam_src->width, sh = webcam_src->height;
+
+        /* (Re)build sws if this is the first tick or src dims changed.
+         * Also handle the case where the user passed only -w at create
+         * time and we estimated h from 16:9 — once we know the actual
+         * src dims, recompute aspect and resize the buffer. */
+        if (sw != o->webcam_src_w || sh != o->webcam_src_h) {
+            /* First time we see real dims: if the user gave us width only
+             * (or width = src_w by default), recompute height to match. */
+            if (o->webcam_src_w == 0) {
+                /* Was our placeholder src 16:9 estimate close enough?
+                 * If the dst aspect matches our placeholder src aspect,
+                 * 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 != o->dst_h) {
+                    free(o->pixels);
+                    o->pixels = calloc(1, (size_t)new_dst_w * new_dst_h * 3);
+                    o->dst_h  = new_dst_h;
+                }
+            }
+            o->src_w = sw; o->src_h = sh;
+            o->webcam_src_w = sw; o->webcam_src_h = sh;
+
+            if (o->sws) sws_freeContext(o->sws);
+            o->sws = sws_getContext(sw, sh, AV_PIX_FMT_BGR24,
+                                     o->dst_w, o->dst_h, AV_PIX_FMT_BGR24,
+                                     SWS_BILINEAR, NULL, NULL, NULL);
+        }
+
+        /* Fast path: src == dst */
+        if (sw == o->dst_w && sh == o->dst_h) {
+            memcpy(o->pixels, webcam_src->data,
+                   (size_t)o->dst_w * o->dst_h * 3);
+        } else if (o->sws) {
+            const uint8_t *s[4] = { webcam_src->data };
+            int sl[4] = { webcam_src->stride };
+            uint8_t *d[4] = { o->pixels };
+            int dl[4] = { o->dst_w * 3 };
+            sws_scale(o->sws, s, sl, 0, sh, d, dl);
+        }
+        return;
+    }
+
+    if (o->type != OVERLAY_VIDEO) return;
+
+    /* ── video tick ──
+     * One overlay_tick = at most one decoded frame displayed.
+     * State machine:
+     *   receive_frame → 0       : display, return
+     *   receive_frame → EAGAIN  : feed more packets, retry
+     *   receive_frame → EOF     : either loop (seek+flush) or freeze
+     *
+     * vid_eof_sent prevents sending the NULL flush sentinel twice.
+     * vid_finished marks play-once playback as completed (we keep the
+     * last frame visible without further decoder activity).
+     */
+    if (o->vid_finished) return; /* play-once: keep last frame, don't touch decoder */
+
+    int safety = 512; /* generous — covers long GOPs and large packet runs */
+    while (safety-- > 0) {
+        int ret = avcodec_receive_frame(o->codec_ctx, o->av_frame);
+
+        if (ret == 0) {
+            /* Got a frame — build/refresh sws based on the actual format
+             * (codec_ctx->pix_fmt may be NONE until the first frame). */
+            int src_fmt = o->av_frame->format;
+            int src_w   = o->av_frame->width;
+            int src_h   = o->av_frame->height;
+            if (!o->sws || src_fmt != o->codec_ctx->pix_fmt) {
+                if (o->sws) sws_freeContext(o->sws);
+                o->sws = sws_getContext(src_w, src_h, src_fmt,
+                                         o->dst_w, o->dst_h, AV_PIX_FMT_BGR24,
+                                         SWS_BILINEAR, NULL, NULL, NULL);
+                o->codec_ctx->pix_fmt = src_fmt;
+                o->src_w = src_w; o->src_h = src_h;
+            }
+            if (o->sws) {
+                uint8_t *d[4] = { o->pixels }; int dl[4] = { o->dst_w*3 };
+                sws_scale(o->sws, (const uint8_t *const *)o->av_frame->data,
+                          o->av_frame->linesize, 0, src_h, d, dl);
+            }
+            return;
+        }
+
+        if (ret == AVERROR_EOF) {
+            /* Decoder fully drained. */
+            if (!o->vid_loop) {
+                o->vid_finished = true;
+                return;
+            }
+            /* Loop: rewind demuxer to start, reset decoder & EOF state */
+            av_seek_frame(o->fmt_ctx, o->stream_idx, 0, AVSEEK_FLAG_BACKWARD);
+            avcodec_flush_buffers(o->codec_ctx);
+            o->vid_eof_sent = false;
+            continue;
+        }
+
+        if (ret != AVERROR(EAGAIN)) return; /* hard error */
+
+        /* Decoder is hungry — feed one packet from the video stream */
+        bool sent = false;
+        while (av_read_frame(o->fmt_ctx, o->av_pkt) >= 0) {
+            if (o->av_pkt->stream_index == o->stream_idx) {
+                avcodec_send_packet(o->codec_ctx, o->av_pkt);
+                av_packet_unref(o->av_pkt);
+                sent = true;
+                break;
+            }
+            av_packet_unref(o->av_pkt);
+        }
+
+        if (!sent && !o->vid_eof_sent) {
+            /* True end of input stream — send flush sentinel ONCE.
+             * Don't send it again or send_packet returns an error. */
+            avcodec_send_packet(o->codec_ctx, NULL);
+            o->vid_eof_sent = true;
+        }
+        /* loop and try receive again */
+    }
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * overlay_blit
+ * ────────────────────────────────────────────────────────────── */
+void overlay_blit(Overlay *o, Frame *dst)
+{
+    if (!o || !o->pixels) return;
+
+    int bpp = o->bpp;
+    int ox = o->dst_x, oy = o->dst_y, ow = o->dst_w, oh = o->dst_h;
+
+    for (int row = 0; row < oh; row++) {
+        int dy = oy + row;
+        if (dy < 0 || dy >= dst->height) continue;
+        uint8_t       *dst_row = dst->data + dy * dst->stride + ox * 3;
+        const uint8_t *src_row = o->pixels + row * ow * bpp;
+
+        for (int col = 0; col < ow; col++) {
+            int dx = ox + col;
+            if (dx < 0 || dx >= dst->width) continue;
+            const uint8_t *s = src_row + col * bpp;
+            uint8_t       *d = dst_row + col * 3;
+
+            if (bpp == 4) {
+                uint8_t a = s[3];
+                if (a == 0) continue;
+                if (a == 255) { d[0]=s[0]; d[1]=s[1]; d[2]=s[2]; }
+                else {
+                    d[0] = (uint8_t)((s[0]*a + d[0]*(255-a)) / 255);
+                    d[1] = (uint8_t)((s[1]*a + d[1]*(255-a)) / 255);
+                    d[2] = (uint8_t)((s[2]*a + d[2]*(255-a)) / 255);
+                }
+            } else {
+                d[0]=s[0]; d[1]=s[1]; d[2]=s[2];
+            }
+        }
+    }
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * overlay_move / overlay_resize
+ * ────────────────────────────────────────────────────────────── */
+void overlay_move(Overlay *o, int x, int y)
+{
+    if (!o) return;
+    o->dst_x = x; o->dst_y = y;
+}
+
+void overlay_resize(Overlay *o, int w, int h)
+{
+    if (!o || w <= 0 || h <= 0) return;
+    if (w == o->dst_w && h == o->dst_h) return;  /* no-op */
+
+    /* Allocate a NEW pixel buffer (zeroed) and free the old one. We
+     * never resize in place because intermediate writes could be read
+     * by overlay_blit on the main thread mid-resize. The registry lock
+     * held by the IPC caller prevents that, but a fresh buffer is also
+     * simpler reasoning. */
+    uint8_t *newpx = calloc(1, (size_t)w * h * o->bpp);
+    if (!newpx) return;
+    free(o->pixels);
+    o->pixels = newpx;
+    o->dst_w  = w;
+    o->dst_h  = h;
+
+    switch (o->type) {
+    case OVERLAY_IMAGE: {
+        /* Rescale from the stored source pixels into the new buffer */
+        if (!o->src_pixels || o->src_w <= 0 || o->src_h <= 0) break;
+        enum AVPixelFormat fmt = (o->bpp == 4) ? AV_PIX_FMT_BGRA : AV_PIX_FMT_BGR24;
+        if (o->src_w == w && o->src_h == h) {
+            memcpy(o->pixels, o->src_pixels, (size_t)w * h * o->bpp);
+        } else {
+            struct SwsContext *sws = sws_getContext(
+                o->src_w, o->src_h, fmt,
+                w, h, fmt,
+                SWS_BILINEAR, NULL, NULL, NULL);
+            const uint8_t *s[4] = { o->src_pixels }; int sl[4] = { o->src_w * o->bpp };
+            uint8_t       *d[4] = { o->pixels };     int dl[4] = { w * o->bpp };
+            sws_scale(sws, s, sl, 0, o->src_h, d, dl);
+            sws_freeContext(sws);
+        }
+        break;
+    }
+
+    case OVERLAY_VIDEO:
+        /* sws is rebuilt lazily in overlay_tick — but it caches the LAST
+         * dst dims via the codec_ctx->pix_fmt sentinel trick. Free it
+         * now so the next tick definitely rebuilds with the new dims. */
+        if (o->sws) { sws_freeContext(o->sws); o->sws = NULL; }
+        /* Reset the cached pix_fmt marker so the lazy rebuild fires */
+        if (o->codec_ctx) o->codec_ctx->pix_fmt = AV_PIX_FMT_NONE;
+        break;
+
+    case OVERLAY_SCREEN: {
+        enum AVPixelFormat src_fmt = (o->src_bpp == 4)
+            ? AV_PIX_FMT_BGR0 : AV_PIX_FMT_BGR24;
+        rebuild_sws(o, o->src_w, o->src_h, src_fmt);
+        break;
+    }
+
+    case OVERLAY_WEBCAM:
+        if (o->sws) { sws_freeContext(o->sws); o->sws = NULL; }
+        if (o->src_w != w || o->src_h != h) {
+            o->sws = sws_getContext(o->src_w, o->src_h, AV_PIX_FMT_BGR24,
+                                     w, h, AV_PIX_FMT_BGR24,
+                                     SWS_BILINEAR, NULL, NULL, NULL);
+        }
+        break;
+    }
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * Accessors (for IPC list command)
+ * ────────────────────────────────────────────────────────────── */
+OverlayType overlay_get_type(const Overlay *o)
+{
+    return o ? o->type : OVERLAY_IMAGE;
+}
+
+void overlay_get_rect(const Overlay *o, int *x, int *y, int *w, int *h)
+{
+    if (!o) { *x=*y=*w=*h=0; return; }
+    *x = o->dst_x; *y = o->dst_y; *w = o->dst_w; *h = o->dst_h;
+}
+
+void overlay_get_src(const Overlay *o, int *w, int *h)
+{
+    if (!o) { *w = *h = 0; return; }
+    *w = o->src_w; *h = o->src_h;
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * overlay_free
+ * ────────────────────────────────────────────────────────────── */
+void overlay_free(Overlay *o)
+{
+    if (!o) return;
+    free(o->pixels);
+    free(o->src_pixels);
+    if (o->type == OVERLAY_SCREEN) {
+        /* Signal the reader thread to exit on its next poll() wakeup */
+        o->reader_shutdown = true;
+
+        /* Stop the capture child — this also causes EOF on the pipe */
+        if (o->child_pid > 0) {
+            kill(o->child_pid, SIGTERM);
+            struct timespec ts = { .tv_nsec = 500000000L };
+            nanosleep(&ts, NULL);
+            kill(o->child_pid, SIGKILL);
+            waitpid(o->child_pid, NULL, 0);
+        }
+
+        /* Reader sees shutdown flag OR EOF on pipe — joins quickly */
+        if (o->reader_running) pthread_join(o->reader_thread, NULL);
+        pthread_mutex_destroy(&o->latest_lock);
+
+        if (o->pipe_fd >= 0) close(o->pipe_fd);
+        if (o->fifo_path[0]) unlink(o->fifo_path);
+        free(o->latest_frame);
+        if (o->sws) sws_freeContext(o->sws);
+    } else if (o->type == OVERLAY_VIDEO) {
+        sws_freeContext(o->sws);
+        av_frame_free(&o->av_frame);
+        av_packet_free(&o->av_pkt);
+        avcodec_free_context(&o->codec_ctx);
+        avformat_close_input(&o->fmt_ctx);
+    } else if (o->type == OVERLAY_WEBCAM) {
+        if (o->sws) sws_freeContext(o->sws);
+    }
+    free(o);
+}
diff --git a/src/registry.c b/src/registry.c
new file mode 100644
index 0000000..e9ac86b
--- /dev/null
+++ b/src/registry.c
@@ -0,0 +1,143 @@
+#include "vcam.h"
+#include <string.h>
+#include <stdio.h>
+
+void registry_init(OverlayRegistry *r)
+{
+    memset(r, 0, sizeof *r);
+    pthread_mutex_init(&r->lock, NULL);
+}
+
+void registry_destroy(OverlayRegistry *r)
+{
+    /* Grab all overlays under the lock, then free them outside it.
+     * This avoids holding the lock during overlay_free, which can block
+     * (e.g. waitpid on a screen-capture child). */
+    Overlay *to_free[MAX_OVERLAYS];
+    int n = 0;
+
+    pthread_mutex_lock(&r->lock);
+    for (int i = 0; i < r->count; i++)
+        to_free[n++] = r->slots[i].overlay;
+    r->count = 0;
+    pthread_mutex_unlock(&r->lock);
+
+    for (int i = 0; i < n; i++)
+        overlay_free(to_free[i]);
+
+    pthread_mutex_destroy(&r->lock);
+}
+
+bool registry_add(OverlayRegistry *r, const char *id, Overlay *o)
+{
+    pthread_mutex_lock(&r->lock);
+    if (r->count >= MAX_OVERLAYS) {
+        pthread_mutex_unlock(&r->lock);
+        fprintf(stderr, "[registry] full (max %d)\n", MAX_OVERLAYS);
+        return false;
+    }
+    for (int i = 0; i < r->count; i++) {
+        if (strcmp(r->slots[i].id, id) == 0) {
+            pthread_mutex_unlock(&r->lock);
+            fprintf(stderr, "[registry] id '%s' already exists\n", id);
+            return false;
+        }
+    }
+    OverlaySlot *s = &r->slots[r->count++];
+    strncpy(s->id, id, sizeof s->id - 1);
+    s->overlay = o;
+    pthread_mutex_unlock(&r->lock);
+    return true;
+}
+
+bool registry_remove(OverlayRegistry *r, const char *id)
+{
+    /* Pluck the overlay out of the list under the lock, then free it
+     * outside the lock so overlay_free can block safely (e.g. waitpid). */
+    Overlay *victim = NULL;
+
+    pthread_mutex_lock(&r->lock);
+    for (int i = 0; i < r->count; i++) {
+        if (strcmp(r->slots[i].id, id) == 0) {
+            victim = r->slots[i].overlay;
+            for (int j = i; j < r->count - 1; j++)
+                r->slots[j] = r->slots[j+1];
+            r->count--;
+            break;
+        }
+    }
+    pthread_mutex_unlock(&r->lock);
+
+    if (!victim) return false;
+    overlay_free(victim);   /* may block (waitpid), but lock is released */
+    return true;
+}
+
+Overlay *registry_find(OverlayRegistry *r, const char *id)
+{
+    /* Caller must hold r->lock */
+    for (int i = 0; i < r->count; i++)
+        if (strcmp(r->slots[i].id, id) == 0)
+            return r->slots[i].overlay;
+    return NULL;
+}
+
+/* Move overlay with this id to the END of the registry list (drawn last
+ * = on top). Returns false if id not found. */
+bool registry_raise(OverlayRegistry *r, const char *id)
+{
+    pthread_mutex_lock(&r->lock);
+    int idx = -1;
+    for (int i = 0; i < r->count; i++)
+        if (strcmp(r->slots[i].id, id) == 0) { idx = i; break; }
+    if (idx < 0) { pthread_mutex_unlock(&r->lock); return false; }
+    if (idx == r->count - 1) { pthread_mutex_unlock(&r->lock); return true; }
+
+    OverlaySlot tmp = r->slots[idx];
+    for (int i = idx; i < r->count - 1; i++) r->slots[i] = r->slots[i+1];
+    r->slots[r->count - 1] = tmp;
+    pthread_mutex_unlock(&r->lock);
+    return true;
+}
+
+/* Move overlay with this id to the FRONT (drawn first = at the bottom). */
+bool registry_lower(OverlayRegistry *r, const char *id)
+{
+    pthread_mutex_lock(&r->lock);
+    int idx = -1;
+    for (int i = 0; i < r->count; i++)
+        if (strcmp(r->slots[i].id, id) == 0) { idx = i; break; }
+    if (idx < 0) { pthread_mutex_unlock(&r->lock); return false; }
+    if (idx == 0)  { pthread_mutex_unlock(&r->lock); return true; }
+
+    OverlaySlot tmp = r->slots[idx];
+    for (int i = idx; i > 0; i--) r->slots[i] = r->slots[i-1];
+    r->slots[0] = tmp;
+    pthread_mutex_unlock(&r->lock);
+    return true;
+}
+
+bool registry_set_z(OverlayRegistry *r, const char *id, int target)
+{
+    pthread_mutex_lock(&r->lock);
+    int idx = -1;
+    for (int i = 0; i < r->count; i++)
+        if (strcmp(r->slots[i].id, id) == 0) { idx = i; break; }
+    if (idx < 0) { pthread_mutex_unlock(&r->lock); return false; }
+
+    /* Negative target counts from the top: -1 = top, -2 = second-from-top */
+    if (target < 0) target = r->count + target;
+    if (target < 0)             target = 0;
+    if (target >= r->count)     target = r->count - 1;
+    if (target == idx) { pthread_mutex_unlock(&r->lock); return true; }
+
+    OverlaySlot tmp = r->slots[idx];
+    if (target > idx) {
+        for (int i = idx; i < target; i++) r->slots[i] = r->slots[i+1];
+    } else {
+        for (int i = idx; i > target; i--) r->slots[i] = r->slots[i-1];
+    }
+    r->slots[target] = tmp;
+    pthread_mutex_unlock(&r->lock);
+    return true;
+}
diff --git a/src/test_screen.c b/src/test_screen.c
new file mode 100644
index 0000000..28ecf82
--- /dev/null
+++ b/src/test_screen.c
@@ -0,0 +1,300 @@
+/*
+ * test_screen – heavy-diagnostic screen capture test
+ *
+ * Usage:
+ *   ./test_screen <WxH+X+Y> [output.raw]
+ *
+ * The goal of this program is to figure out WHY screen capture fails
+ * when it does. It prints every step verbosely.
+ */
+#define _POSIX_C_SOURCE 200809L
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <signal.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <time.h>
+
+static double now_ms(void)
+{
+    struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
+    return ts.tv_sec * 1000.0 + ts.tv_nsec / 1e6;
+}
+
+static int snap_down(int v, int align)
+{
+    int r = (v / align) * align;
+    return r >= align ? r : align;
+}
+
+/* Read up to `want` bytes within timeout_ms. Returns bytes obtained.
+ * Treats n==0 on a FIFO as "no writer yet" (waits up to deadline). */
+static size_t read_exact(int fd, uint8_t *buf, size_t want, double timeout_ms)
+{
+    size_t got = 0;
+    double deadline = now_ms() + timeout_ms;
+    while (got < want) {
+        ssize_t n = read(fd, buf + got, want - got);
+        if (n > 0) { got += (size_t)n; continue; }
+        if (now_ms() >= deadline) break;
+        if (n == 0 || (n < 0 && errno == EAGAIN)) { usleep(10000); continue; }
+        if (n < 0 && errno == EINTR) continue;
+        perror("read"); break;
+    }
+    return got;
+}
+
+static bool child_alive(pid_t pid)
+{
+    int status;
+    pid_t r = waitpid(pid, &status, WNOHANG);
+    if (r == 0) return true;
+    if (r == pid) {
+        if (WIFEXITED(status))
+            fprintf(stderr, "[diag] child exited with code %d\n", WEXITSTATUS(status));
+        else if (WIFSIGNALED(status))
+            fprintf(stderr, "[diag] child killed by signal %d\n", WTERMSIG(status));
+        return false;
+    }
+    return true;
+}
+
+int main(int argc, char *argv[])
+{
+    if (argc < 2) {
+        fprintf(stderr,
+            "Usage: %s <WxH+X+Y> [output.raw]\n"
+            "Example: %s 1280x720+0+0 frame.raw\n", argv[0], argv[0]);
+        return 1;
+    }
+    const char *geometry = argv[1];
+    const char *outfile  = argc >= 3 ? argv[2] : NULL;
+
+    int gw=0, gh=0, gx=0, gy=0;
+    if (sscanf(geometry, "%dx%d+%d+%d", &gw, &gh, &gx, &gy) != 4) {
+        fprintf(stderr, "Bad geometry '%s' — expected WxH+X+Y\n", geometry);
+        return 1;
+    }
+
+    /* Snap to alignment (same as vcam does) */
+    int gw_orig = gw, gh_orig = gh;
+    gw = snap_down(gw, 16);
+    gh = snap_down(gh, 2);
+
+    bool wayland = getenv("WAYLAND_DISPLAY") != NULL;
+    bool x11     = getenv("DISPLAY") != NULL;
+
+    printf("─── test_screen ───────────────────────────────────────\n");
+    printf("Requested  : %dx%d at (%d,%d)\n", gw_orig, gh_orig, gx, gy);
+    if (gw != gw_orig || gh != gh_orig)
+        printf("Snapped to : %dx%d (16/2-aligned for compositor stride)\n", gw, gh);
+    printf("WAYLAND_DISPLAY = %s\n", getenv("WAYLAND_DISPLAY") ?: "(unset)");
+    printf("DISPLAY         = %s\n", getenv("DISPLAY") ?: "(unset)");
+    printf("XDG_RUNTIME_DIR = %s\n", getenv("XDG_RUNTIME_DIR") ?: "(unset)");
+    printf("Backend         : %s\n", wayland ? "Wayland (wf-recorder)" :
+                                    (x11 ? "X11 (ffmpeg x11grab)" : "NONE"));
+    printf("───────────────────────────────────────────────────────\n");
+
+    int fd = -1;
+    pid_t pid = -1;
+    int   src_bpp = 3;
+    char  fifo_path[128] = "";
+
+    if (wayland) {
+        snprintf(fifo_path, sizeof fifo_path, "/tmp/test_screen_%d.fifo", (int)getpid());
+        unlink(fifo_path);
+        if (mkfifo(fifo_path, 0600) < 0) { perror("mkfifo"); return 1; }
+        printf("[step] created FIFO  : %s\n", fifo_path);
+
+        fd = open(fifo_path, O_RDONLY | O_NONBLOCK);
+        if (fd < 0) { perror("open fifo"); unlink(fifo_path); return 1; }
+        printf("[step] opened read end (O_NONBLOCK)\n");
+
+        char wfr_geo[64];
+        snprintf(wfr_geo, sizeof wfr_geo, "%d,%d %dx%d", gx, gy, gw, gh);
+        printf("[step] forking child to exec:\n");
+        printf("           wf-recorder -g '%s' -c rawvideo -x bgr0 --muxer rawvideo -f %s\n",
+               wfr_geo, fifo_path);
+        printf("[step] (stdin pre-loaded with 'y\\n' to auto-answer Overwrite prompt)\n");
+
+        /* Pre-load "y\n" on stdin so wf-recorder's "Overwrite?" prompt is
+         * answered automatically. Without this it hangs forever. */
+        int answer_pipe[2];
+        if (pipe(answer_pipe) < 0) { perror("answer pipe"); return 1; }
+        const char *yes = "y\ny\ny\n";
+        ssize_t wn = write(answer_pipe[1], yes, strlen(yes));
+        (void)wn;
+
+        pid = fork();
+        if (pid == 0) {
+            dup2(answer_pipe[0], STDIN_FILENO);
+            close(answer_pipe[0]); close(answer_pipe[1]);
+            execlp("wf-recorder", "wf-recorder",
+                   "-g", wfr_geo,
+                   "-c", "rawvideo",
+                   "-x", "bgr0",
+                   "--muxer", "rawvideo",
+                   "-f", fifo_path,
+                   (char *)NULL);
+            perror("execlp wf-recorder");
+            _exit(127);
+        }
+        close(answer_pipe[0]); close(answer_pipe[1]);
+        src_bpp = 4;
+
+    } else if (x11) {
+        int pipefd[2];
+        if (pipe(pipefd) < 0) { perror("pipe"); return 1; }
+        printf("[step] created stdout pipe\n");
+
+        char input[64], size[32];
+        snprintf(input, sizeof input, ":0.0+%d,%d", gx, gy);
+        snprintf(size,  sizeof size,  "%dx%d", gw, gh);
+        printf("[step] forking child to exec:\n");
+        printf("           ffmpeg -f x11grab -video_size %s -i %s -f rawvideo -pix_fmt bgr24 pipe:1\n",
+               size, input);
+
+        pid = fork();
+        if (pid == 0) {
+            dup2(pipefd[1], STDOUT_FILENO);
+            close(pipefd[0]); close(pipefd[1]);
+            execlp("ffmpeg", "ffmpeg",
+                   "-f", "x11grab", "-video_size", size, "-i", input,
+                   "-f", "rawvideo", "-pix_fmt", "bgr24", "pipe:1",
+                   (char *)NULL);
+            perror("execlp ffmpeg");
+            _exit(127);
+        }
+        close(pipefd[1]);
+        fd = pipefd[0];
+        src_bpp = 3;
+    } else {
+        fprintf(stderr, "[fail] Neither WAYLAND_DISPLAY nor DISPLAY is set.\n");
+        return 1;
+    }
+
+    printf("[step] child pid: %d\n", (int)pid);
+
+    /* Verify child is alive after a brief moment */
+    usleep(200000);
+    if (!child_alive(pid)) {
+        fprintf(stderr, "[fail] child exited immediately. See its error output above.\n");
+        if (fifo_path[0]) unlink(fifo_path);
+        return 1;
+    }
+    printf("[step] child still alive after 200ms — capture starting\n");
+
+    size_t frame_bytes = (size_t)gw * gh * src_bpp;
+    printf("Frame size : %zu bytes (%.2f MB)\n", frame_bytes, frame_bytes / 1e6);
+    printf("\n");
+
+    fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
+
+    uint8_t *buf = malloc(frame_bytes);
+    if (!buf) { perror("malloc"); kill(pid, SIGTERM); return 1; }
+
+    /* Wait up to 15s for first frame, polling child health */
+    printf("Waiting for first frame (up to 15s)...\n");
+    double t0 = now_ms();
+    double deadline = t0 + 15000;
+    size_t got = 0;
+
+    while (got < frame_bytes && now_ms() < deadline) {
+        if (!child_alive(pid)) {
+            fprintf(stderr, "[fail] capture process died before delivering a frame.\n");
+            free(buf);
+            if (fifo_path[0]) unlink(fifo_path);
+            return 1;
+        }
+        size_t step = read_exact(fd, buf + got, frame_bytes - got, 200);
+        got += step;
+        if (step > 0) {
+            printf("  +%zu bytes (total %zu / %zu, %.0f%%)\n",
+                   step, got, frame_bytes, 100.0 * got / frame_bytes);
+        }
+    }
+
+    if (got < frame_bytes) {
+        printf("\n[fail] only %zu / %zu bytes after 15s. Capture is producing nothing.\n",
+               got, frame_bytes);
+        printf("\nThings to try manually:\n");
+        if (wayland) {
+            printf("  wf-recorder -g '%d,%d %dx%d' -c rawvideo -x bgr0 --muxer rawvideo -f /tmp/raw.test\n",
+                   gx, gy, gw, gh);
+            printf("  sleep 2; pkill wf-recorder\n");
+            printf("  ls -la /tmp/raw.test    # should be many MB\n");
+            printf("\nIf wf-recorder writes nothing on its own either:\n");
+            printf("  - Your compositor may not expose wlr-screencopy (KDE/GNOME don't).\n");
+            printf("    Wayland compositors that DO: Sway, Hyprland, river, niri, wayfire.\n");
+            printf("  - Try a screenshot tool to check: grim /tmp/test.png\n");
+        } else {
+            printf("  ffmpeg -f x11grab -video_size %dx%d -i :0.0+%d,%d -frames:v 5 /tmp/test.mp4\n",
+                   gw, gh, gx, gy);
+        }
+        kill(pid, SIGTERM); waitpid(pid, NULL, 0);
+        free(buf);
+        if (fifo_path[0]) unlink(fifo_path);
+        return 1;
+    }
+
+    printf("\nFirst full frame in %.0f ms\n", now_ms() - t0);
+
+    /* Read 9 more frames to measure throughput */
+    printf("Reading 9 more frames for throughput measurement...\n");
+    double t1 = now_ms();
+    int frames = 0;
+    for (; frames < 9; frames++) {
+        size_t n = read_exact(fd, buf, frame_bytes, 5000.0);
+        if (n < frame_bytes) { printf("  pipe closed after %d frames\n", frames); break; }
+    }
+    double elapsed = now_ms() - t1;
+    if (frames > 0)
+        printf("Throughput : %.1f fps\n", frames * 1000.0 / elapsed);
+
+    /* Check for content */
+    uint64_t sum = 0, nonzero = 0;
+    for (size_t i = 0; i < frame_bytes; i++) {
+        sum += buf[i];
+        if (buf[i] != 0) nonzero++;
+    }
+    printf("Brightness : %llu (avg byte %.1f)\n",
+           (unsigned long long)sum, sum / (double)frame_bytes);
+    printf("Non-zero   : %llu / %zu bytes (%.1f%%)\n",
+           (unsigned long long)nonzero, frame_bytes,
+           100.0 * nonzero / frame_bytes);
+    if (nonzero < 100)
+        printf("WARNING    : frame is essentially all zero — capture works but content is black!\n"
+               "             Try a region that has actual content on screen.\n");
+
+    if (outfile) {
+        FILE *f = fopen(outfile, "wb");
+        if (f) {
+            fwrite(buf, 1, frame_bytes, f);
+            fclose(f);
+            printf("\nSaved to   : %s\n", outfile);
+            printf("View with  : ffmpeg -f rawvideo -pix_fmt %s -video_size %dx%d -i %s -frames:v 1 -y %s.png && xdg-open %s.png\n",
+                   src_bpp == 4 ? "bgr0" : "bgr24", gw, gh, outfile, outfile, outfile);
+        }
+    }
+
+    /* Robust shutdown: SIGTERM, wait up to 500ms, then SIGKILL */
+    fprintf(stderr, "\n[cleanup] stopping capture child...\n");
+    kill(pid, SIGTERM);
+    for (int i = 0; i < 50; i++) {
+        if (waitpid(pid, NULL, WNOHANG) == pid) goto reaped;
+        usleep(10000); /* 10ms */
+    }
+    kill(pid, SIGKILL);
+    waitpid(pid, NULL, 0);
+reaped:
+    free(buf);
+    if (fifo_path[0]) unlink(fifo_path);
+    fprintf(stderr, "[cleanup] done.\n");
+    return 0;
+}