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

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

Record video got Added

Christian Immanuel · 2026-07-04 09:51 · 55eb075480d87a64c328416d19824ce7facd393c

 Makefile           |    3 +-
 README.md          |   56 +-
 include/vcam.h     |  104 +-
 scripts/vcam-ctl   |  351 ++++---
 scripts/vcam-setup |    8 +-
 scripts/vcam-tune  |  336 ++++++-
 src/filter.c       | 2784 ++++++++++++++++++++++++++++++++++++++++++++++++++--
 src/ipc.c          |  288 +++++-
 src/main.c         |   16 +
 src/record.c       |  726 ++++++++++++++
 10 files changed, 4383 insertions(+), 289 deletions(-)

diff --git a/Makefile b/Makefile
index be114de..a72215c 100644
--- a/Makefile
+++ b/Makefile
@@ -18,7 +18,8 @@ PREFIX  ?= /usr/local
 BINDIR  ?= $(PREFIX)/bin
 
 SRCS := src/main.c src/frame.c src/capture.c src/output.c \
-        src/overlay.c src/registry.c src/ipc.c src/filter.c
+        src/overlay.c src/registry.c src/ipc.c src/filter.c \
+        src/record.c
 OBJS := $(SRCS:.c=.o)
 BIN  := vcam
 TEST := test_screen
diff --git a/README.md b/README.md
index df9724c..0288d1d 100644
--- a/README.md
+++ b/README.md
@@ -449,8 +449,60 @@ vcam-ctl record mics                                 # list available ALSA devic
 Audio policy: ALSA only by design (no Pulse/PipeWire daemon dependency).
 On systems running PipeWire, the pipewire-alsa compatibility plugin
 generally exposes `default` as a working capture device, which `record
-start` will pick automatically. If you have multiple capture cards or a
-preferred one, list them with `record mics` and pass `-m hw:N,M`.
+start` will pick automatically.
+
+Mic identifiers accepted by `--mic`:
+
+| Form | Behaviour |
+|---|---|
+| *(omitted)*    | auto-pick: `default` if present, else first `plughw:N,M` from `arecord -l` |
+| `N,M`          | expanded to `plughw:N,M` for you |
+| `plughw:N,M`   | ALSA auto-converts sample format/channels (recommended) |
+| `hw:N,M`       | raw access — only if you know the device's native format |
+| `default`      | system default |
+
+Run `vcam-ctl record mics` for a ready-to-paste table of what's
+available on your machine.
+
+### Recording while vcam is already streaming
+
+This now works without contention. Two things had to be right:
+
+1. **v4l2loopback needs enough buffers.** Older `vcam-setup` defaulted
+   to `max_buffers=2`; the current default is `8`. If you set this up
+   previously and `record start` fails with `Device or resource busy`,
+   re-apply and reload:
+
+   ```bash
+   sudo vcam-setup --install      # rewrites /etc/modprobe.d/vcam.conf
+   sudo modprobe -r v4l2loopback
+   sudo modprobe v4l2loopback
+   ```
+
+2. **The ffmpeg command must not call `VIDIOC_S_PARM`.** v4l2loopback
+   rejects framerate changes from any consumer while a producer is
+   active, returning EBUSY. `vcam-ctl record start` deliberately
+   omits the `-framerate` flag for this reason — it lets the loopback
+   keep whatever framerate vcam set. (This is why `ffplay` worked but
+   a hand-rolled `ffmpeg -framerate 30 -f v4l2 -i /dev/video0` would
+   not.) If you ever invoke ffmpeg by hand against vcam, leave out
+   `-framerate`.
+
+With both in place: vcam writing + a browser reading + a recording
+capturing all run simultaneously without any contention.
+
+### If audio crackles
+
+The most common cause is ffmpeg's default `thread_queue_size` of 8
+packets being too small for live capture; `record start` passes
+`-thread_queue_size 1024` plus `aresample=async=1000` to mitigate
+this. If you're still hearing crackles:
+
+* Try a different mic with `record mics` + `--mic plughw:N,M`. Laptop
+  DMICs (AMD acp etc.) are often the culprit.
+* If your system runs PipeWire, the `pipewire-alsa` shim sometimes
+  introduces extra resampling latency. Routing through `default` may
+  be smoother than `plughw:N,M` in that case.
 
 The recording lives in a separate process from vcam, so it survives a
 vcam restart. State is published in three plain files under `/tmp` so any
diff --git a/include/vcam.h b/include/vcam.h
index 6956eec..7339b43 100644
--- a/include/vcam.h
+++ b/include/vcam.h
@@ -3,6 +3,7 @@
 #include <stdint.h>
 #include <stdbool.h>
 #include <pthread.h>
+#include <sys/types.h>
 
 /* ──────────────────────────────────────────────
  * Frame  (internal BGR24)
@@ -133,15 +134,60 @@ typedef enum {
     FX_RIPPLE,      /* animated water ripple from center, default 0.5     */
     FX_SCANLINES,   /* black scanlines every N rows, gap 2..8, def 3      */
 
+    /* ── glitch art / generative animated ── */
+    FX_SHUFFLE,     /* roving pixel-shuffle blocks, intensity 0..1, def 0.4 */
+    FX_PIXELSORT,   /* glitch-art row pixel-sort, density 0..1, def 0.3     */
+    FX_RGB_DELAY,   /* chromatic lag (G+R from past frames), 0..1, def 0.7  */
+    FX_DRIFT,       /* horizontal scanline drift, band height px, def 8     */
+    FX_RAIN,        /* matrix-style digital rain trails, density 0..1, def 0.4 */
+
+    /* ── temporal / time-bending (rgbdelay's siblings) ── */
+    FX_ECHO,        /* motion trails: blend of past frames, 0..1, def 0.6   */
+    FX_SLITSCAN,    /* time gradient top→bottom rows from the past, 0..1    */
+    FX_MOSH,        /* fake datamosh: only update pixels that move, 0..1    */
+    FX_STUTTER,     /* freeze each frame for N frames (temporal pixelate)   */
+    FX_HALFTONE,    /* newspaper dot grid, cell size px, def 8              */
+    FX_NEON,        /* glowing colored edges on darkened scene, 0..1        */
+
+    /* ── batch 3: retro & warp ── */
+    FX_EMBOSS,      /* grayscale relief, strength 0..2, def 1               */
+    FX_DITHER,      /* ordered Bayer dither, levels/channel 2..8, def 2     */
+    FX_TILES,       /* mirror-tile grid, tiles per row 2..8, def 3          */
+    FX_ZOOMPULSE,   /* breathing zoom oscillation, 0..1, def 0.5            */
+    FX_OILSLICK,    /* iridescent luma-keyed hue warp, 0..1, def 0.6        */
+
+    /* ── batch 4: interactive & extravagant ── */
+    FX_FEEDBACK,    /* video-feedback tunnel; decay 0..1 (+zoom,rot), def 0.85 */
+    FX_RIPPLES,     /* INTERACTIVE: motion spawns water ripples, 0..1       */
+    FX_LIGHTPAINT,  /* INTERACTIVE: motion paints glowing trails, fade 0..1 */
+    FX_HOLOGRAM,    /* sci-fi hologram: cyan, scanlines, flicker, 0..1      */
+    FX_LIFE,        /* Conway's Life seeded by image edges, density 0..1    */
+    FX_MATHWARP,    /* expression-driven warp — see 'filter expr', amp mult */
+
+    /* ── batch 5: demoscene & particles ── */
+    FX_PLASMA,      /* classic demoscene plasma blend, 0..1 (+speed,scale)  */
+    FX_CONTOUR,     /* glowing topographic iso-lines, levels (+dim)         */
+    FX_FIREWORKS,   /* INTERACTIVE: motion sparks particle bursts, 0..1     */
+    FX_INFINITY,    /* recursive picture-in-picture droste, scale (+rot)    */
+    FX_MOIRE,       /* rotating interference rings, spacing px (+speed)     */
+
+    /* ── batch 6: text, tone & tracking ── */
+    FX_ASCII,       /* real ASCII-art rendering, cell px (+colormode)       */
+    FX_DUOTONE,     /* two-color gradient map, hueA deg (+hueB, mix)        */
+    FX_SKETCH,      /* pencil sketch (dodge blend), detail (+darkness)      */
+    FX_SPOTLIGHT,   /* INTERACTIVE: spotlight follows your motion, radius   */
+
     FX_UNKNOWN,
 } FilterType;
 
 typedef struct {
     FilterType type;
-    float      param;
+    float      param;         /* primary — kept for backwards compat */
+    float      param2, param3, param4;  /* optional additional knobs */
 } Filter;
 
 #define MAX_FILTERS 16
+#define FILTER_MAX_PARAMS 4
 
 typedef struct {
     Filter          filters[MAX_FILTERS];
@@ -151,11 +197,24 @@ typedef struct {
 
 void        filter_chain_init   (FilterChain *fc);
 void        filter_chain_destroy(FilterChain *fc);
+/* Add a filter with just the primary param. */
 bool        filter_chain_add    (FilterChain *fc, FilterType t, float param);
+/* Add a filter with up to FILTER_MAX_PARAMS params (unused → 0.0). */
+bool        filter_chain_add_multi(FilterChain *fc, FilterType t,
+                                   const float *params, int n_params);
 bool        filter_chain_remove (FilterChain *fc, int index);
 void        filter_chain_clear  (FilterChain *fc);
 void        filter_chain_apply  (FilterChain *fc, Frame *f); /* takes lock */
 
+/* mathwarp: compile displacement expressions used by FX_MATHWARP.
+ * Variables: x y (pixel coords), w h (frame size), t (seconds),
+ * r (distance from center), a (angle from center).
+ * Functions: sin cos abs sqrt. Operators: + - * / ( ) unary -.
+ * NO SPACES inside an expression. Returns false + err message on
+ * parse failure. */
+bool mathwarp_set_expr(const char *dx_expr, const char *dy_expr,
+                       char *err, size_t errlen);
+
 FilterType  filter_type_from_name(const char *name);
 const char *filter_type_to_name  (FilterType t);
 float       filter_default_param (FilterType t);
@@ -235,3 +294,46 @@ extern int g_output_w;
 extern int g_output_h;
 bool        output_write(V4L2Output *out, const Frame *frame);
 void        output_close(V4L2Output *out);
+
+/* ──────────────────────────────────────────────
+ * Recorder — spawns ffmpeg as a child process and feeds it our raw
+ * BGR24 frames via a pipe. Bypasses /dev/video0 entirely, so it never
+ * contends with browser / ffplay / OBS consumers of the v4l2loopback.
+ * ────────────────────────────────────────────── */
+typedef struct Recorder Recorder;
+
+Recorder *recorder_new(void);
+void      recorder_free(Recorder *r);
+
+/* Start recording. file is the output path; mic may be NULL or an
+ * ALSA device string ("default", "plughw:1,0", etc.). w/h/fps are
+ * the dimensions of the BGR24 frames you'll pass to
+ * recorder_write_frame. Returns false if ffmpeg failed to start.
+ *
+ * crf:     x264 quality (0..51, lower = better)
+ * preset, vcodec: x264 preset / codec name
+ * aoffset: audio delay in seconds (positive shifts audio LATER).
+ *          Compensates for the video path's buffering latency
+ *          (webcam driver + decode + pipe), which otherwise makes
+ *          audio lead video by a constant ~0.3-0.5s. */
+bool recorder_start(Recorder *r,
+                    const char *file, const char *mic,
+                    int w, int h, int fps,
+                    int crf, const char *vcodec, const char *vpreset,
+                    float aoffset);
+
+/* Stop recording. Sends EOF to ffmpeg via closing the pipe so it
+ * finalises the container, then reaps the child. Safe to call when
+ * not recording (no-op). */
+void recorder_stop(Recorder *r);
+
+bool        recorder_active(const Recorder *r);
+pid_t       recorder_pid   (const Recorder *r);
+const char *recorder_file  (const Recorder *r);
+
+/* Send one frame to ffmpeg's stdin. Frame must be BGR24, width*height*3
+ * bytes. Non-blocking — if ffmpeg's pipe is full (typically because the
+ * encoder briefly stalled) the frame is silently dropped rather than
+ * blocking the main loop. Returns true if frame was sent (or recording
+ * is inactive), false if ffmpeg died unexpectedly. */
+bool recorder_write_frame(Recorder *r, const uint8_t *bgr24, size_t bytes);
diff --git a/scripts/vcam-ctl b/scripts/vcam-ctl
index 15f1044..2460190 100755
--- a/scripts/vcam-ctl
+++ b/scripts/vcam-ctl
@@ -463,20 +463,61 @@ rec_cleanup_stale() {
 }
 
 rec_list_mics() {
-    if ! command -v arecord >/dev/null 2>&1; then
-        echo "arecord not installed (sudo apt install alsa-utils)" >&2
+    local have_any=0
+
+    # ── PulseAudio / PipeWire sources (RECOMMENDED) ──
+    if command -v pactl >/dev/null 2>&1 && pactl info >/dev/null 2>&1; then
+        local sources
+        sources=$(pactl list sources short 2>/dev/null \
+                  | awk '{print $2}' | grep -v '\.monitor$' || true)
+        if [[ -n "$sources" ]]; then
+            have_any=1
+            echo "PipeWire/PulseAudio sources (RECOMMENDED — robust buffering):"
+            echo ""
+            printf "  %-18s %s\n" "--mic" "source"
+            printf "  %-18s %s\n" "------------------" "---------------------------------"
+            printf "  %-18s %s\n" "pulse" "(default source)"
+            while IFS= read -r src; do
+                printf "  %-18s %s\n" "pulse:$src" "$src"
+            done <<<"$sources"
+            echo ""
+        fi
+    fi
+
+    # ── Raw ALSA devices ──
+    if command -v arecord >/dev/null 2>&1; then
+        local lines
+        lines=$(arecord -l 2>/dev/null | grep -E '^card [0-9]+' || true)
+        if [[ -n "$lines" ]]; then
+            have_any=1
+            echo "Raw ALSA capture devices:"
+            echo ""
+            printf "  %-18s %s\n" "--mic" "device"
+            printf "  %-18s %s\n" "------------------" "---------------------------------"
+            while IFS= read -r line; do
+                local card dev name
+                card=$(echo "$line" | sed -E 's/^card ([0-9]+):.*/\1/')
+                dev=$(echo  "$line" | sed -E 's/.*device ([0-9]+):.*/\1/')
+                name=$(echo "$line" | sed -E 's/.*\[([^]]*)\][[:space:]]*$/\1/')
+                printf "  %-18s %s\n" "plughw:${card},${dev}" "$name (card $card, device $dev)"
+            done <<<"$lines"
+            echo ""
+        fi
+    fi
+
+    if [[ $have_any -eq 0 ]]; then
+        echo "No capture devices found."
         return 1
     fi
-    echo "Hardware capture devices:"
-    arecord -l 2>/dev/null | grep -E "^card|^  Subdev" \
-        | awk -F: '/^card/{c=$1$2; printf "  %s\n", $0} /^  Subdev/{print "      " $0}'
-    echo ""
-    echo "ALSA PCM names (use with --mic):"
-    # Filter to interesting ones — skip null/iec/loopback/dmix internals
-    arecord -L 2>/dev/null | awk '
-        /^[a-zA-Z]/ && !/^null$/ && !/^iec/ && !/^Loopback/ \
-            && !/^dmix/ && !/^dsnoop/ && !/^plugequal/ \
-            { name=$0; getline desc; printf "  %-25s %s\n", name, desc }'
+
+    echo "  Notes:"
+    echo "  * 'pulse' (PipeWire/PulseAudio) is RECOMMENDED when available."
+    echo "    Its buffering handles flaky hardware (e.g. AMD acp DMICs)"
+    echo "    far better than ffmpeg's direct ALSA capture, which can"
+    echo "    stall mid-recording with buffer xruns."
+    echo "  * 'plughw:N,M' talks to ALSA directly with auto format"
+    echo "    conversion. 'hw:N,M' is raw. 'default' = ALSA default."
+    echo "  * Shortcut: '--mic N,M' expands to 'plughw:N,M'."
 }
 
 rec_default_output() {
@@ -497,18 +538,16 @@ if [[ "$1" == "record" ]]; then
             if rec_is_active; then
                 echo "Already recording (pid $(cat $REC_PID))." >&2
                 echo "Use 'vcam-ctl record stop' first, or pass --replace." >&2
-                # Allow --replace
                 if [[ " $* " != *" --replace "* && " $* " != *" -r "* ]]; then
                     exit 1
                 fi
-                kill -TERM "$(cat $REC_PID)" 2>/dev/null
-                sleep 0.5
+                ipc_send "record stop" >/dev/null 2>&1 || true
+                sleep 0.3
                 rm -f "$REC_PID" "$REC_STATUS" "$REC_INFO"
             fi
 
             OUT=""; MIC=""; NO_AUDIO=0; CRF=23
-            VCODEC="libx264"; VPRESET="veryfast"
-            VCAM_OUT="${VCAM_OUTPUT:-/dev/video0}"
+            VCODEC="libx264"; VPRESET="ultrafast"; AOFFSET="0.2"
 
             while [[ $# -gt 0 ]]; do
                 case "$1" in
@@ -518,6 +557,7 @@ if [[ "$1" == "record" ]]; then
                     --crf)         CRF="$2"; shift 2 ;;
                     --vcodec)      VCODEC="$2"; shift 2 ;;
                     --preset)      VPRESET="$2"; shift 2 ;;
+                    -A|--aoffset)  AOFFSET="$2"; shift 2 ;;
                     -r|--replace)  shift ;;   # already handled
                     *) echo "Unknown record start option: $1" >&2; exit 1 ;;
                 esac
@@ -526,26 +566,25 @@ if [[ "$1" == "record" ]]; then
             OUT="${OUT:-$(rec_default_output)}"
             mkdir -p "$(dirname "$OUT")"
 
-            if ! command -v ffmpeg >/dev/null 2>&1; then
-                echo "ffmpeg not installed. (sudo apt install ffmpeg)" >&2
-                exit 1
-            fi
-
-            # Auto-pick a microphone if user didn't ask for --no-audio and
-            # didn't supply --mic. We try the ALSA "default" PCM first
-            # (works on most systems including PipeWire's ALSA shim), then
-            # fall back to the first hardware capture card we find via
-            # arecord -l. Pass --no-audio to skip this entirely.
+            # Auto-pick a mic if --mic and --no-audio both absent.
+            # Preference order:
+            #   1. PulseAudio/PipeWire ("pulse") — far more robust
+            #      buffering than raw ALSA capture; the AMD acp DMIC
+            #      in particular can wedge the kernel driver under
+            #      ffmpeg's direct ALSA reads.
+            #   2. ALSA "default"
+            #   3. First hardware capture device as plughw:N,M
             if [[ $NO_AUDIO -eq 0 && -z "$MIC" ]]; then
-                if arecord -L 2>/dev/null | grep -q '^default$'; then
+                if command -v pactl >/dev/null 2>&1 && pactl info >/dev/null 2>&1; then
+                    MIC="pulse"
+                elif arecord -L 2>/dev/null | grep -q '^default$'; then
                     MIC="default"
                 elif command -v arecord >/dev/null 2>&1; then
-                    # Parse "card N: ..., device M: ..." → "hw:N,M"
                     FIRST_HW=$(arecord -l 2>/dev/null \
                         | grep -E '^card [0-9]+' \
                         | head -1 \
-                        | sed -E 's/^card ([0-9]+).* device ([0-9]+).*/hw:\1,\2/')
-                    if [[ -n "$FIRST_HW" && "$FIRST_HW" =~ ^hw: ]]; then
+                        | sed -E 's/^card ([0-9]+).* device ([0-9]+).*/plughw:\1,\2/')
+                    if [[ -n "$FIRST_HW" && "$FIRST_HW" =~ ^plughw: ]]; then
                         MIC="$FIRST_HW"
                     fi
                 fi
@@ -553,80 +592,75 @@ if [[ "$1" == "record" ]]; then
                     echo "[record] auto-selected mic: $MIC" \
                          "(override with --mic, or skip with --no-audio)"
                 else
-                    echo "[record] no ALSA capture device found — recording video only"
+                    echo "[record] no capture device found — recording video only"
                 fi
             fi
-
-            # Query the loopback's CURRENT format so ffmpeg doesn't try to
-            # change it (which v4l2loopback rejects while vcam is writing
-            # to it — that's what was making recording fail while ffplay/
-            # browsers had the cam open). Passing matching parameters
-            # turns ffmpeg's S_FMT call into a no-op.
-            FMT_W=""; FMT_H=""; FMT_PIX=""; FMT_FPS=""
-            if command -v v4l2-ctl >/dev/null 2>&1; then
-                FMT_LINE=$(v4l2-ctl -d "$VCAM_OUT" --get-fmt-video 2>/dev/null \
-                           | tr -d ' ')
-                FMT_W=$(echo "$FMT_LINE" | awk -F'Width/Height:' '{print $2}' \
-                        | awk -F'/' '{print $1}')
-                FMT_H=$(echo "$FMT_LINE" | awk -F'Width/Height:' '{print $2}' \
-                        | awk -F'/' '{print $2}' | awk -F',' '{print $1}')
-                # PixelFormat is like "PixelFormat:'YUYV'(YUYV4:2:2)"
-                FMT_RAW=$(v4l2-ctl -d "$VCAM_OUT" --get-fmt-video 2>/dev/null \
-                          | awk -F"'" '/Pixel Format/{print $2}')
-                # ffmpeg names: YUYV -> yuyv422, NV12 -> nv12, etc.
-                case "$FMT_RAW" in
-                    YUYV) FMT_PIX="yuyv422" ;;
-                    UYVY) FMT_PIX="uyvy422" ;;
-                    NV12) FMT_PIX="nv12" ;;
-                    RGB3) FMT_PIX="rgb24" ;;
-                    BGR3) FMT_PIX="bgr24" ;;
-                    *)    FMT_PIX="" ;; # let ffmpeg figure it out
-                esac
-                # Frame rate
-                FMT_FPS=$(v4l2-ctl -d "$VCAM_OUT" --get-parm 2>/dev/null \
-                          | awk '/Frames per second/{print $4; exit}')
-            fi
-
-            # Build ffmpeg command — read the vcam loopback output.
-            # v4l2loopback supports multiple readers, so this doesn't
-            # interfere with browsers/OBS/ffplay also reading the cam,
-            # as long as we don't ask for a format change.
-            CMD=(ffmpeg -y -hide_banner -loglevel warning)
-
-            # Pre-input options must come BEFORE -i
-            [[ -n "$FMT_PIX" ]] && CMD+=(-input_format "$FMT_PIX")
-            [[ -n "$FMT_W" && -n "$FMT_H" ]] && CMD+=(-video_size "${FMT_W}x${FMT_H}")
-            [[ -n "$FMT_FPS" ]] && CMD+=(-framerate "$FMT_FPS")
-
-            CMD+=(-f v4l2 -i "$VCAM_OUT")
-
-            if [[ $NO_AUDIO -eq 0 && -n "$MIC" ]]; then
-                # Try ALSA first. Many "PipeWire" systems still expose
-                # ALSA via the pipewire-alsa plugin, so "default" usually
-                # works without going to pulse/pipewire-pulse.
-                CMD+=(-f alsa -ac 2 -i "$MIC")
+            # Normalize plain "N,M" → "plughw:N,M"
+            if [[ -n "$MIC" && "$MIC" =~ ^[0-9]+,[0-9]+$ ]]; then
+                MIC="plughw:$MIC"
+                echo "[record] interpreting mic as $MIC"
             fi
 
-            CMD+=(-c:v "$VCODEC" -preset "$VPRESET" -crf "$CRF" -pix_fmt yuv420p)
+            # Tell vcam to start the recording. vcam spawns ffmpeg as
+            # a child and pipes our composed BGR24 frames into it.
+            # Because we're NOT reading /dev/video0, there's no
+            # v4l2loopback contention with browser / ffplay / OBS
+            # consumers regardless of who attached first.
+            require_running
+            REQ="record start file=$OUT crf=$CRF vcodec=$VCODEC preset=$VPRESET aoffset=$AOFFSET"
             if [[ $NO_AUDIO -eq 0 && -n "$MIC" ]]; then
-                CMD+=(-c:a aac -b:a 160k)
+                REQ="$REQ mic=$MIC"
             fi
-            CMD+=("$OUT")
-
-            # Spawn detached so it survives this shell exiting
-            nohup "${CMD[@]}" </dev/null >"$REC_LOG" 2>&1 &
-            PID=$!
-            disown 2>/dev/null || true
-
-            # Give it a moment to fail fast (bad device etc.)
-            sleep 0.3
-            if ! kill -0 "$PID" 2>/dev/null; then
-                echo "ffmpeg exited immediately — see $REC_LOG:" >&2
-                tail -n 5 "$REC_LOG" >&2
+            RESP=$(ipc_send "$REQ")
+            if ! echo "$RESP" | grep -qE '^OK recording'; then
+                echo "Failed to start recording. Response from vcam:" >&2
+                echo "$RESP" >&2
+                if [[ -s /tmp/vcam-record.log ]]; then
+                    echo "" >&2
+                    echo "ffmpeg log (last 20 lines, full at /tmp/vcam-record.log):" >&2
+                    tail -n 20 /tmp/vcam-record.log >&2
+                fi
                 exit 1
             fi
 
-            echo "$PID" > "$REC_PID"
+            # recorder_start returns immediately (by design — it never
+            # blocks vcam's IPC thread), so a bad ffmpeg invocation is
+            # only detectable a moment later. Wait briefly, then verify
+            # the recording is still live; if ffmpeg died, show its log.
+            #
+            # Special case: "audio device busy" usually means the
+            # PREVIOUS recording's ffmpeg is still in its shutdown
+            # grace period (vcam escalates SIGINT→TERM→KILL over ~5s).
+            # In that case wait and retry once automatically.
+            ATTEMPT=1
+            while :; do
+                sleep 0.5
+                CHECK=$(ipc_send "record status")
+                if echo "$CHECK" | grep -q "recording"; then
+                    break   # alive and well
+                fi
+                if [[ $ATTEMPT -eq 1 ]] && grep -q "audio device.*busy\|Device or resource busy" /tmp/vcam-record.log 2>/dev/null; then
+                    echo "[record] mic still held by the previous recording — retrying in 2s..."
+                    sleep 2
+                    ATTEMPT=2
+                    RESP=$(ipc_send "$REQ")
+                    if echo "$RESP" | grep -qE '^OK recording'; then
+                        continue    # loop back to verify this attempt
+                    fi
+                fi
+                echo "✗ ffmpeg exited immediately after start." >&2
+                if [[ -s /tmp/vcam-record.log ]]; then
+                    echo "" >&2
+                    echo "ffmpeg log (last 20 lines, full at /tmp/vcam-record.log):" >&2
+                    tail -n 20 /tmp/vcam-record.log >&2
+                fi
+                rm -f "$REC_PID" "$REC_STATUS" "$REC_INFO"
+                exit 1
+            done
+
+            # Pull pid from the OK line. State files for status-bar use.
+            PID=$(echo "$RESP" | sed -nE 's/^OK recording pid=([0-9]+).*/\1/p' | head -1)
+            echo "${PID:-0}" > "$REC_PID"
             echo "recording" > "$REC_STATUS"
             {
                 echo "file=$OUT"
@@ -636,58 +670,63 @@ if [[ "$1" == "record" ]]; then
                 echo "format=${OUT##*.}"
                 echo "vcodec=$VCODEC"
                 echo "crf=$CRF"
+                echo "transport=pipe"
             } > "$REC_INFO"
 
             echo "● Recording started"
             echo "   file: $OUT"
-            echo "   pid:  $PID"
+            echo "   pid:  ${PID:-?}  (ffmpeg, child of vcam)"
             [[ -n "$MIC" ]] && echo "   mic:  $MIC"
+            echo "   transport: pipe (vcam → ffmpeg stdin, no /dev/video0 read)"
             ;;
 
         # ── stop ─────────────────────────────────────────────
         stop)
-            if ! rec_is_active; then
-                echo "Not currently recording." >&2
-                rec_cleanup_stale
-                exit 1
-            fi
-            PID=$(cat "$REC_PID")
-            # Send 'q' on stdin? We redirected to /dev/null so use SIGINT,
-            # which makes ffmpeg flush + write the trailer cleanly.
-            kill -INT "$PID" 2>/dev/null || true
-            for _ in $(seq 1 50); do
-                kill -0 "$PID" 2>/dev/null || break
-                sleep 0.1
-            done
-            if kill -0 "$PID" 2>/dev/null; then
-                kill -TERM "$PID" 2>/dev/null
-                sleep 0.5
-                kill -KILL "$PID" 2>/dev/null
+            # Ask vcam to close its end of the pipe; ffmpeg finalises
+            # the file in the background.
+            require_running 2>/dev/null && ipc_send "record stop" >/dev/null 2>&1 || true
+            if [[ -f "$REC_INFO" ]]; then
+                OUT=$(grep '^file=' "$REC_INFO" 2>/dev/null | cut -d= -f2-)
             fi
-            OUT=$(grep '^file=' "$REC_INFO" 2>/dev/null | cut -d= -f2-)
             rm -f "$REC_PID" "$REC_STATUS" "$REC_INFO"
             echo "■ Recording stopped"
-            [[ -n "$OUT" ]] && echo "   saved: $OUT"
+            if [[ -n "${OUT:-}" ]]; then
+                # Give ffmpeg a moment to finish the container, then
+                # verify the file actually exists. If it doesn't, the
+                # recording failed at some point — surface the log.
+                for _ in 1 2 3 4 5 6 7 8 9 10; do
+                    [[ -s "$OUT" ]] && break
+                    sleep 0.2
+                done
+                if [[ -s "$OUT" ]]; then
+                    echo "   saved: $OUT"
+                else
+                    echo "   ✗ expected output $OUT was not created!" >&2
+                    if [[ -s /tmp/vcam-record.log ]]; then
+                        echo "" >&2
+                        echo "ffmpeg log (last 20 lines, full at /tmp/vcam-record.log):" >&2
+                        tail -n 20 /tmp/vcam-record.log >&2
+                    fi
+                    exit 1
+                fi
+            fi
             ;;
 
         # ── pause ────────────────────────────────────────────
-        # SIGSTOP halts ffmpeg in place. Audio device may buffer a bit
-        # of data while stopped; expect a tiny glitch on resume.
+        # In the new pipe-based architecture the recorder is a child
+        # of vcam, not of this shell. SIGSTOP from this process would
+        # be... fine actually, since we have the pid. But cleaner to
+        # just stop and tell the user to restart.
         pause)
-            if ! rec_is_active; then echo "Not recording." >&2; exit 1; fi
-            PID=$(cat "$REC_PID")
-            kill -STOP "$PID"
-            echo "paused" > "$REC_STATUS"
-            echo "⏸ Recording paused (pid $PID)"
+            echo "pause is not supported in the pipe-based recorder." >&2
+            echo "Use 'record stop' and 'record start' instead." >&2
+            exit 1
             ;;
 
-        # ── resume ───────────────────────────────────────────
         resume|continue)
-            if [[ ! -f "$REC_PID" ]]; then echo "No paused recording." >&2; exit 1; fi
-            PID=$(cat "$REC_PID")
-            kill -CONT "$PID"
-            echo "recording" > "$REC_STATUS"
-            echo "● Recording resumed (pid $PID)"
+            echo "resume is not supported in the pipe-based recorder." >&2
+            echo "Use 'record start' to begin a new recording." >&2
+            exit 1
             ;;
 
         # ── status ───────────────────────────────────────────
@@ -752,40 +791,48 @@ if [[ "$1" == "record" ]]; then
 
         help|--help|-h|"")
             cat <<'HLP'
-vcam-ctl record — capture the vcam loopback output to a file.
+vcam-ctl record — capture vcam's composed output to a file.
+
+How it works (pipe-based, since v0.x):
+  vcam runs ffmpeg as a child process and pipes raw BGR24 frames into
+  ffmpeg's stdin. No reading of /dev/video0 is involved, so you can
+  freely have browsers, ffplay, OBS, etc. consuming the cam at the
+  same time without any v4l2loopback contention.
 
   record start [options]    Start recording.
     -o, --output <path>     Output file (default: $XDG_VIDEOS_DIR/vcam-<ts>.mkv)
-    -m, --mic <device>      ALSA capture device (e.g. "default", "hw:1,0").
-                            If omitted, vcam-ctl auto-picks: ALSA "default"
-                            if present, otherwise the first hw:N,M from
-                            'arecord -l'. Use 'vcam-ctl record mics' to see
-                            available devices.
+    -m, --mic <device>      Audio source. Forms accepted:
+                              pulse                 → PipeWire/Pulse default (RECOMMENDED)
+                              pulse:<source-name>   → specific PipeWire/Pulse source
+                              N,M                   → expanded to plughw:N,M
+                              plughw:N,M            → ALSA with auto-conversion
+                              hw:N,M                → raw ALSA
+                              default               → ALSA default
+                            Run 'vcam-ctl record mics' to see what's available.
+                            If omitted, auto-picks: pulse if PipeWire/Pulse is
+                            running, else ALSA default, else first plughw:N,M.
     --no-audio              Record video only (skip mic auto-detect).
     --crf <n>               x264 quality 0–51 (default 23, lower = better)
     --vcodec <name>         video codec (default libx264)
-    --preset <name>         x264 preset (default veryfast)
-    -r, --replace           kill any existing recording first
-
-  record stop                Flush & close, write the file out cleanly.
-  record pause               SIGSTOP the ffmpeg process (audio may glitch on resume).
-  record resume              SIGCONT the ffmpeg process.
-  record status              Print "recording" / "paused" / "stopped". Exit code
-                             0 if active, 1 if not — handy for shell scripts.
+    --preset <name>         x264 preset (default ultrafast — CPU-light; use veryfast for smaller files)
+    -A, --aoffset <sec>     audio sync offset in seconds (default 0.2).
+                            Positive shifts audio LATER. If voices come
+                            BEFORE lips move, increase it; if lips move
+                            first, decrease it. Typical range 0.2–0.8,
+                            constant per machine — find yours once.
+    -r, --replace           stop any existing recording first
+
+  record stop                Send EOF to ffmpeg (clean flush + trailer).
+  record status              "recording" / "stopped"
   record info                Detailed info about the current recording.
   record mics                List available ALSA capture devices.
   record bar                 Emit one line of swaybar JSON for status_command.
 
-State files (live under /tmp, readable by anything):
-  /tmp/vcam-record.pid      PID of ffmpeg
-  /tmp/vcam-record.status   "recording" or "paused"
+State files (live under /tmp):
+  /tmp/vcam-record.pid      PID of the ffmpeg child of vcam
+  /tmp/vcam-record.status   "recording"
   /tmp/vcam-record.info     file=, mic=, started=, format=
-  /tmp/vcam-record.log      ffmpeg's own stderr
-
-Swaybar (~/.config/sway/config):
-  bar { status_command while date +'%T'; do vcam-ctl record bar; sleep 1; done }
-
-Or simpler, use a custom status block that polls 'vcam-ctl record status'.
+  /tmp/vcam-record.log      ffmpeg's stderr (look here if it fails)
 HLP
             ;;
 
diff --git a/scripts/vcam-setup b/scripts/vcam-setup
index 6a4be81..db32a11 100755
--- a/scripts/vcam-setup
+++ b/scripts/vcam-setup
@@ -127,8 +127,12 @@ if [[ "${1:-}" == "--install" ]]; then
 # 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
+# max_buffers=8    enough to support vcam-write + multiple simultaneous
+#                  readers (browser, ffmpeg recording, ffplay preview).
+#                  With max_buffers=2 the second reader gets EBUSY at
+#                  VIDIOC_REQBUFS — so e.g. 'vcam-ctl record start'
+#                  failed if the cam was already in use.
+options v4l2loopback video_nr=0 card_label="vcam" exclusive_caps=1 max_buffers=8
 MODPROBE
     echo "Wrote /etc/modprobe.d/vcam.conf"
 
diff --git a/scripts/vcam-tune b/scripts/vcam-tune
index 49336c4..b7c49be 100755
--- a/scripts/vcam-tune
+++ b/scripts/vcam-tune
@@ -48,32 +48,204 @@ 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 current filter list as parallel arrays: NAMES[], PARAMS[] (primary),
+# and PARAMS2..4[] (extra tunable knobs — 0 unless the filter uses them).
+declare -a NAMES PARAMS PARAMS2 PARAMS3 PARAMS4 DEFAULTS
 read_filters() {
-    NAMES=(); PARAMS=(); DEFAULTS=()
-    local lines name param
+    NAMES=(); PARAMS=(); PARAMS2=(); PARAMS3=(); PARAMS4=(); DEFAULTS=()
+    local line
     while IFS= read -r line; do
-        if [[ "$line" =~ ^OK\ ([0-9]+):\ ([a-z]+)\ param=([0-9.\-]+) ]]; then
+        if [[ "$line" =~ ^OK\ ([0-9]+):\ ([a-z-]+)\ param=([0-9.\-]+)\ p2=([0-9.\-]+)\ p3=([0-9.\-]+)\ p4=([0-9.\-]+) ]]; then
             local idx="${BASH_REMATCH[1]}"
-            name="${BASH_REMATCH[2]}"
-            param="${BASH_REMATCH[3]}"
-            NAMES[idx]="$name"
-            PARAMS[idx]="$param"
+            NAMES[idx]="${BASH_REMATCH[2]}"
+            PARAMS[idx]="${BASH_REMATCH[3]}"
+            PARAMS2[idx]="${BASH_REMATCH[4]}"
+            PARAMS3[idx]="${BASH_REMATCH[5]}"
+            PARAMS4[idx]="${BASH_REMATCH[6]}"
+        elif [[ "$line" =~ ^OK\ ([0-9]+):\ ([a-z-]+)\ param=([0-9.\-]+) ]]; then
+            # Older vcam without multi-param support
+            local idx="${BASH_REMATCH[1]}"
+            NAMES[idx]="${BASH_REMATCH[2]}"
+            PARAMS[idx]="${BASH_REMATCH[3]}"
+            PARAMS2[idx]=0; PARAMS3[idx]=0; PARAMS4[idx]=0
         fi
     done < <(ipc_lines "filter list")
 }
 
+# Which extra params does a filter actually use? Returns the highest
+# param slot (1–4) that's meaningful for this filter, so the tuner
+# doesn't offer dead knobs on single-param filters.
+n_params_for() {
+    case "$1" in
+        neon|kaleidoscope|wave) echo 4 ;;
+        chromashift|glitch|vignette|feedback|ripples|life|plasma) echo 3 ;;
+        swirl|pinch|bulge|shuffle|rain|lightpaint|hologram|duotone|spotlight) echo 3 ;;
+        contour|fireworks|infinity|moire) echo 2 ;;
+        cartoon|drift|slitscan|mosh|zoompulse|oilslick|ascii|sketch) echo 2 ;;
+        *) echo 1 ;;
+    esac
+}
+
+# Human labels for each param slot per filter (slot 1 is generic).
+param_label() {
+    local name=$1 slot=$2
+    case "$name:$slot" in
+        chromashift:1) echo "r-shift" ;;
+        chromashift:2) echo "b-shift" ;;
+        chromashift:3) echo "r-vshift" ;;
+        kaleidoscope:1) echo "segments" ;;
+        kaleidoscope:2) echo "rot-deg" ;;
+        kaleidoscope:3) echo "spin" ;;
+        glitch:1) echo "intensity" ;;
+        glitch:2) echo "slice-h" ;;
+        glitch:3) echo "shift-pct" ;;
+        vignette:1) echo "strength" ;;
+        vignette:2) echo "radius" ;;
+        vignette:3) echo "warmth" ;;
+        wave:1) echo "amp" ;;
+        wave:2) echo "freq" ;;
+        wave:3) echo "speed" ;;
+        wave:4) echo "vert" ;;
+        feedback:1) echo "decay" ;;
+        feedback:2) echo "zoom" ;;
+        feedback:3) echo "rot" ;;
+        kaleidoscope:4) echo "zoom" ;;
+        neon:1) echo "strength" ;;
+        neon:2) echo "thresh" ;;
+        neon:3) echo "huespd" ;;
+        neon:4) echo "glow" ;;
+        ripples:1) echo "sens" ;;
+        ripples:2) echo "rain" ;;
+        ripples:3) echo "refract" ;;
+        life:1) echo "density" ;;
+        life:2) echo "color" ;;
+        life:3) echo "speed" ;;
+        plasma:1) echo "blend" ;;
+        plasma:2) echo "speed" ;;
+        plasma:3) echo "scale" ;;
+        contour:1) echo "levels" ;;
+        contour:2) echo "dim" ;;
+        fireworks:1) echo "sens" ;;
+        fireworks:2) echo "burst" ;;
+        infinity:1) echo "scale" ;;
+        infinity:2) echo "rot" ;;
+        moire:1) echo "spacing" ;;
+        moire:2) echo "speed" ;;
+        swirl:2) echo "radius" ;;
+        swirl:3) echo "spin" ;;
+        pinch:2|bulge:2) echo "cx" ;;
+        pinch:3|bulge:3) echo "cy" ;;
+        cartoon:2) echo "levels" ;;
+        shuffle:2) echo "size" ;;
+        shuffle:3) echo "phase-s" ;;
+        rain:2) echo "speed" ;;
+        rain:3) echo "trail" ;;
+        drift:2) echo "max-shift" ;;
+        slitscan:2) echo "dir" ;;
+        mosh:2) echo "keyint" ;;
+        lightpaint:2) echo "thresh" ;;
+        lightpaint:3) echo "huespd" ;;
+        hologram:2) echo "gap" ;;
+        hologram:3) echo "glitch" ;;
+        zoompulse:2) echo "rate" ;;
+        oilslick:2) echo "speed" ;;
+        ascii:1) echo "cell" ;;
+        ascii:2) echo "mode" ;;
+        duotone:1) echo "hueA" ;;
+        duotone:2) echo "hueB" ;;
+        duotone:3) echo "mix" ;;
+        sketch:1) echo "detail" ;;
+        sketch:2) echo "dark" ;;
+        spotlight:1) echo "radius" ;;
+        spotlight:2) echo "dark" ;;
+        spotlight:3) echo "speed" ;;
+        *:1) echo "param" ;;
+        *) echo "p$slot" ;;
+    esac
+}
+
+# Per-slot steps where the primary step isn't right
+param_step() {
+    local name=$1 slot=$2
+    case "$name:$slot" in
+        kaleidoscope:2) echo 5 ;;      # rotation degrees
+        kaleidoscope:3) echo 0.25 ;;   # spin deg/frame
+        glitch:2)       echo 2 ;;      # slice height px
+        glitch:3)       echo 2 ;;      # shift percent
+        vignette:2)     echo 0.05 ;;
+        vignette:3)     echo 0.05 ;;
+        wave:2)         echo 0.5 ;;    # waves/screen
+        wave:3)         echo 0.02 ;;   # phase speed
+        wave:4)         echo 1 ;;      # vert toggle
+        feedback:2)     echo 0.01 ;;   # zoom per frame
+        feedback:3)     echo 0.5 ;;    # degrees per frame
+        kaleidoscope:4) echo 0.05 ;;   # wedge zoom
+        neon:2)         echo 5 ;;      # edge threshold
+        neon:3)         echo 0.2 ;;    # hue speed
+        neon:4)         echo 0.05 ;;   # glow
+        ripples:2)      echo 1 ;;      # rain drops/sec
+        ripples:3)      echo 0.5 ;;    # refraction
+        life:2)         echo 1 ;;      # color mode toggle
+        life:3)         echo 1 ;;      # frames per generation
+        plasma:2)       echo 0.1 ;;    # speed
+        plasma:3)       echo 5 ;;      # scale px
+        contour:2)      echo 0.05 ;;   # dim
+        fireworks:2)    echo 0.25 ;;   # burst multiplier
+        infinity:2)     echo 1 ;;      # rotation deg
+        moire:2)        echo 0.1 ;;    # speed
+        swirl:2)        echo 0.05 ;;
+        swirl:3)        echo 0.2 ;;
+        pinch:2|pinch:3|bulge:2|bulge:3) echo 0.05 ;;
+        cartoon:2)      echo 1 ;;
+        shuffle:2)      echo 8 ;;
+        shuffle:3)      echo 0.25 ;;
+        rain:2)         echo 0.2 ;;
+        rain:3)         echo 4 ;;
+        drift:2)        echo 5 ;;
+        slitscan:2)     echo 1 ;;
+        mosh:2)         echo 30 ;;
+        lightpaint:2)   echo 5 ;;
+        lightpaint:3)   echo 0.2 ;;
+        hologram:2)     echo 1 ;;
+        hologram:3)     echo 0.1 ;;
+        zoompulse:2)    echo 0.1 ;;
+        oilslick:2)     echo 0.2 ;;
+        duotone:2)      echo 10 ;;
+        duotone:3)      echo 0.05 ;;
+        sketch:2)       echo 0.05 ;;
+        spotlight:2)    echo 0.05 ;;
+        spotlight:3)    echo 0.02 ;;
+        chromashift:2)  echo 1 ;;
+        chromashift:3)  echo 1 ;;
+        *) default_step "$name" ;;
+    esac
+}
+
 # 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|scanlines) echo 1 ;;
         bitcrush) echo 1 ;;
+        drift) echo 1 ;;
         cartoon|solarize) echo 5 ;;
         brightness|contrast|swirl|rainbow|saturate) echo 0.1 ;;
         vignette|glitch|dream|bloom|glow|pinch|bulge|modern|cyberpunk|romantic|xor|polar) echo 0.05 ;;
         melt|popart|displace|ripple|crt|velvet|noir|julia|edges) echo 0.05 ;;
+        shuffle|pixelsort|rgbdelay|rain) echo 0.05 ;;
+        echo|slitscan|mosh|neon) echo 0.05 ;;
+        stutter) echo 1 ;;
+        halftone) echo 2 ;;
+        dither|tiles) echo 1 ;;
+        emboss|zoompulse|oilslick|ripples|hologram|life|feedback) echo 0.05 ;;
+        lightpaint) echo 0.01 ;;
+        mathwarp) echo 0.1 ;;
+        plasma|fireworks|infinity) echo 0.05 ;;
+        contour|moire) echo 1 ;;
+        ascii) echo 8 ;;
+        duotone) echo 10 ;;
+        sketch) echo 1 ;;
+        spotlight) echo 20 ;;
         *) echo 0.1 ;;
     esac
 }
@@ -112,6 +284,37 @@ default_param_for() {
         velvet) echo 0.6 ;;
         noir) echo 0.8 ;;
         scanlines) echo 3 ;;
+        shuffle) echo 0.4 ;;
+        pixelsort) echo 0.3 ;;
+        rgbdelay) echo 0.7 ;;
+        drift) echo 8 ;;
+        rain) echo 0.4 ;;
+        echo) echo 0.6 ;;
+        slitscan) echo 0.7 ;;
+        mosh) echo 0.5 ;;
+        stutter) echo 6 ;;
+        halftone) echo 8 ;;
+        neon) echo 0.7 ;;
+        emboss) echo 1 ;;
+        dither) echo 2 ;;
+        tiles) echo 3 ;;
+        zoompulse) echo 0.5 ;;
+        oilslick) echo 0.6 ;;
+        feedback) echo 0.85 ;;
+        ripples) echo 0.6 ;;
+        lightpaint) echo 0.94 ;;
+        hologram) echo 0.8 ;;
+        life) echo 0.5 ;;
+        mathwarp) echo 1 ;;
+        plasma) echo 0.5 ;;
+        contour) echo 8 ;;
+        fireworks) echo 0.6 ;;
+        infinity) echo 0.55 ;;
+        moire) echo 12 ;;
+        ascii) echo 8 ;;
+        duotone) echo 220 ;;
+        sketch) echo 2 ;;
+        spotlight) echo 180 ;;
         *) echo 1 ;;
     esac
 }
@@ -120,17 +323,38 @@ default_param_for() {
 calc() { awk "BEGIN { printf \"%g\", $1 }"; }
 
 # ── set a single parameter ───────────────────────────────────
+# set_param <index> <value> [<slot>]   slot: 1 (default) .. 4
 set_param() {
-    local index=$1 value=$2
+    local index=$1 value=$2 slot="${3:-1}"
     local resp
-    resp=$(ipc "filter set $index $value")
+    if [[ "$slot" == "1" ]]; then
+        resp=$(ipc "filter set $index $value")
+    else
+        resp=$(ipc "filter set $index p$slot $value")
+    fi
     if [[ "$resp" =~ ^OK ]]; then
-        PARAMS[index]="$value"
+        case "$slot" in
+            1) PARAMS[index]="$value" ;;
+            2) PARAMS2[index]="$value" ;;
+            3) PARAMS3[index]="$value" ;;
+            4) PARAMS4[index]="$value" ;;
+        esac
         return 0
     fi
     return 1
 }
 
+# get the current value of a slot
+get_param() {
+    local index=$1 slot="${2:-1}"
+    case "$slot" in
+        1) echo "${PARAMS[index]}" ;;
+        2) echo "${PARAMS2[index]:-0}" ;;
+        3) echo "${PARAMS3[index]:-0}" ;;
+        4) echo "${PARAMS4[index]:-0}" ;;
+    esac
+}
+
 # All available filters, grouped by category.
 # Updated when src/filter.c changes — keep in sync with the help table.
 FILTER_CATEGORIES=(
@@ -140,6 +364,12 @@ FILTER_CATEGORIES=(
     "Themed:modern cyberpunk romantic vangogh picasso noir"
     "Math:sine xor modulo polar voronoi julia"
     "Pixel-crazy:bitcrush melt popart displace ripple scanlines"
+    "Glitch-art:shuffle pixelsort rgbdelay drift rain"
+    "Temporal:echo slitscan mosh stutter halftone neon"
+    "Retro/Warp:emboss dither tiles zoompulse oilslick"
+    "Interactive:ripples lightpaint fireworks spotlight feedback hologram life mathwarp"
+    "Demoscene:plasma contour infinity moire"
+    "Artistic:ascii duotone sketch"
 )
 
 # Show an interactive picker, return chosen filter name on stdout
@@ -287,9 +517,21 @@ 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  a=add  q=quit"
+echo "  ↑↓/kj = adjust value      Tab/p/1-4 = switch PARAM of this filter"
+echo "  ←→/hn = switch FILTER     r=reset  x=remove  a=add  q=quit"
 echo ""
 
+CUR_SLOT=1
+
+# adjust the selected slot of the current filter by +/- its step
+adjust() {
+    local dir=$1
+    local name="${NAMES[CURRENT_IDX]}"
+    local step; step=$(param_step "$name" "$CUR_SLOT")
+    local cur;  cur=$(get_param "$CURRENT_IDX" "$CUR_SLOT")
+    set_param "$CURRENT_IDX" "$(calc "$cur $dir $step")" "$CUR_SLOT"
+}
+
 draw() {
     local idx=$CURRENT_IDX
     printf '\r\033[K'
@@ -299,10 +541,23 @@ draw() {
     fi
     printf '[%d/%d]  ' $((idx + 1)) "$NUM_FILTERS"
     for i in "${!NAMES[@]}"; do
+        local name="${NAMES[i]}"
+        local np; np=$(n_params_for "$name")
         if [[ $i -eq $idx ]]; then
-            printf '\033[1;36m▶ %s=%s \033[0m' "${NAMES[i]}" "${PARAMS[i]}"
+            printf '\033[1;36m▶ %s\033[0m' "$name"
+            # Show each tunable slot; highlight the selected one
+            for ((s=1; s<=np; s++)); do
+                local lbl; lbl=$(param_label "$name" "$s")
+                local val; val=$(get_param "$i" "$s")
+                if [[ $s -eq $CUR_SLOT ]]; then
+                    printf ' \033[1;33m[%s=%s]\033[0m' "$lbl" "$val"
+                else
+                    printf ' %s=%s' "$lbl" "$val"
+                fi
+            done
+            printf ' '
         else
-            printf '  %s=%s ' "${NAMES[i]}" "${PARAMS[i]}"
+            printf '  %s=%s ' "$name" "${PARAMS[i]}"
         fi
     done
 }
@@ -318,20 +573,10 @@ while :; do
             # All directional keys need at least one filter
             if [[ $NUM_FILTERS -eq 0 ]]; then draw; continue; fi
             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 )) ;;
+                A) adjust "+" ;;
+                B) adjust "-" ;;
+                C) CURRENT_IDX=$(( (CURRENT_IDX + 1) % NUM_FILTERS )); CUR_SLOT=1 ;;
+                D) CURRENT_IDX=$(( (CURRENT_IDX - 1 + NUM_FILTERS) % NUM_FILTERS )); CUR_SLOT=1 ;;
             esac
         fi
     else
@@ -347,29 +592,39 @@ while :; do
                 ;;
         esac
         case "$c" in
-            k|K)
+            k|K) adjust "+" ;;
+            j|J) adjust "-" ;;
+            p|P|$'\t')
+                # Tab / p: cycle through the current filter's tunable
+                # param slots (only moves if the filter has extras)
                 name="${NAMES[CURRENT_IDX]}"
-                step=$(default_step "$name")
-                set_param "$CURRENT_IDX" "$(calc "${PARAMS[CURRENT_IDX]} + $step")"
+                np=$(n_params_for "$name")
+                CUR_SLOT=$(( CUR_SLOT % np + 1 ))
                 ;;
-            j|J)
+            1|2|3|4)
+                # jump straight to a slot if the filter has it
                 name="${NAMES[CURRENT_IDX]}"
-                step=$(default_step "$name")
-                set_param "$CURRENT_IDX" "$(calc "${PARAMS[CURRENT_IDX]} - $step")"
+                np=$(n_params_for "$name")
+                if [[ $c -le $np ]]; then CUR_SLOT=$c; fi
                 ;;
-            l|L|$'\t')
-                CURRENT_IDX=$(( (CURRENT_IDX + 1) % NUM_FILTERS )) ;;
+            l|L|n|N)
+                CURRENT_IDX=$(( (CURRENT_IDX + 1) % NUM_FILTERS )); CUR_SLOT=1 ;;
             h|H)
-                CURRENT_IDX=$(( (CURRENT_IDX - 1 + NUM_FILTERS) % NUM_FILTERS )) ;;
+                CURRENT_IDX=$(( (CURRENT_IDX - 1 + NUM_FILTERS) % NUM_FILTERS )); CUR_SLOT=1 ;;
             r|R)
                 name="${NAMES[CURRENT_IDX]}"
-                def=$(default_param_for "$name")
-                set_param "$CURRENT_IDX" "$def"
+                if [[ $CUR_SLOT -eq 1 ]]; then
+                    def=$(default_param_for "$name")
+                else
+                    def=0
+                fi
+                set_param "$CURRENT_IDX" "$def" "$CUR_SLOT"
                 ;;
             x|X)
                 ipc "filter remove $CURRENT_IDX" >/dev/null
                 read_filters
                 NUM_FILTERS=${#NAMES[@]}
+                CUR_SLOT=1
                 if [[ $NUM_FILTERS -eq 0 ]]; then
                     echo ""
                     echo "All filters removed. Press 'a' to add one, or 'q' to quit."
@@ -392,6 +647,7 @@ while :; do
                     read_filters
                     NUM_FILTERS=${#NAMES[@]}
                     CURRENT_IDX=$((NUM_FILTERS - 1))   # focus the new one
+                    CUR_SLOT=1
                 fi
                 # Back to raw mode for the walk
                 stty -echo -icanon time 0 min 1
diff --git a/src/filter.c b/src/filter.c
index f9f9165..a7cc271 100644
--- a/src/filter.c
+++ b/src/filter.c
@@ -69,6 +69,61 @@ static const struct { const char *name; FilterType t; } NAMES[] = {
     {"displace",    FX_DISPLACE},
     {"ripple",      FX_RIPPLE},
     {"scanlines",   FX_SCANLINES},
+    /* glitch art */
+    {"shuffle",     FX_SHUFFLE},
+    {"pixelsort",   FX_PIXELSORT},
+    {"rgbdelay",    FX_RGB_DELAY},
+    {"rgb-delay",   FX_RGB_DELAY},
+    {"drift",       FX_DRIFT},
+    {"rain",        FX_RAIN},
+    /* temporal */
+    {"echo",        FX_ECHO},
+    {"trails",      FX_ECHO},
+    {"slitscan",    FX_SLITSCAN},
+    {"timewarp",    FX_SLITSCAN},
+    {"mosh",        FX_MOSH},
+    {"datamosh",    FX_MOSH},
+    {"stutter",     FX_STUTTER},
+    {"halftone",    FX_HALFTONE},
+    {"neon",        FX_NEON},
+    /* retro & warp */
+    {"emboss",      FX_EMBOSS},
+    {"dither",      FX_DITHER},
+    {"tiles",       FX_TILES},
+    {"zoompulse",   FX_ZOOMPULSE},
+    {"pulse",       FX_ZOOMPULSE},
+    {"oilslick",    FX_OILSLICK},
+    {"iridescent",  FX_OILSLICK},
+    /* interactive & extravagant */
+    {"feedback",    FX_FEEDBACK},
+    {"tunnel",      FX_FEEDBACK},
+    {"ripples",     FX_RIPPLES},
+    {"water",       FX_RIPPLES},
+    {"lightpaint",  FX_LIGHTPAINT},
+    {"paint",       FX_LIGHTPAINT},
+    {"hologram",    FX_HOLOGRAM},
+    {"holo",        FX_HOLOGRAM},
+    {"life",        FX_LIFE},
+    {"conway",      FX_LIFE},
+    {"mathwarp",    FX_MATHWARP},
+    {"expr",        FX_MATHWARP},
+    /* demoscene & particles */
+    {"plasma",      FX_PLASMA},
+    {"contour",     FX_CONTOUR},
+    {"topo",        FX_CONTOUR},
+    {"fireworks",   FX_FIREWORKS},
+    {"sparks",      FX_FIREWORKS},
+    {"infinity",    FX_INFINITY},
+    {"droste",      FX_INFINITY},
+    {"moire",       FX_MOIRE},
+    /* text, tone & tracking */
+    {"ascii",       FX_ASCII},
+    {"matrix-text", FX_ASCII},
+    {"duotone",     FX_DUOTONE},
+    {"sketch",      FX_SKETCH},
+    {"pencil",      FX_SKETCH},
+    {"spotlight",   FX_SPOTLIGHT},
+    {"followme",    FX_SPOTLIGHT},
     /* new effect additions */
     {"saturate",    FX_SATURATE},
     {"crt",         FX_CRT},
@@ -137,6 +192,39 @@ float filter_default_param(FilterType t)
     case FX_NOIR:        return 0.8f;
     case FX_JULIA:       return 0.5f;
     case FX_SCANLINES:   return 3.0f;
+    /* glitch art */
+    case FX_SHUFFLE:     return 0.4f;
+    case FX_PIXELSORT:   return 0.3f;
+    case FX_RGB_DELAY:   return 0.7f;
+    case FX_DRIFT:       return 8.0f;
+    case FX_RAIN:        return 0.4f;
+    /* temporal */
+    case FX_ECHO:        return 0.6f;
+    case FX_SLITSCAN:    return 0.7f;
+    case FX_MOSH:        return 0.5f;
+    case FX_STUTTER:     return 6.0f;
+    case FX_HALFTONE:    return 8.0f;
+    case FX_NEON:        return 0.7f;
+    case FX_EMBOSS:      return 1.0f;
+    case FX_DITHER:      return 2.0f;
+    case FX_TILES:       return 3.0f;
+    case FX_ZOOMPULSE:   return 0.5f;
+    case FX_OILSLICK:    return 0.6f;
+    case FX_FEEDBACK:    return 0.85f;
+    case FX_RIPPLES:     return 0.6f;
+    case FX_LIGHTPAINT:  return 0.94f;
+    case FX_HOLOGRAM:    return 0.8f;
+    case FX_LIFE:        return 0.5f;
+    case FX_MATHWARP:    return 1.0f;
+    case FX_PLASMA:      return 0.5f;
+    case FX_CONTOUR:     return 8.0f;
+    case FX_FIREWORKS:   return 0.6f;
+    case FX_INFINITY:    return 0.55f;
+    case FX_MOIRE:       return 12.0f;
+    case FX_ASCII:       return 8.0f;
+    case FX_DUOTONE:     return 220.0f;
+    case FX_SKETCH:      return 2.0f;
+    case FX_SPOTLIGHT:   return 180.0f;
     default:             return 0.0f;
     }
 }
@@ -163,8 +251,33 @@ bool filter_chain_add(FilterChain *fc, FilterType t, float param)
         pthread_mutex_unlock(&fc->lock);
         return false;
     }
-    fc->filters[fc->count].type  = t;
-    fc->filters[fc->count].param = param;
+    fc->filters[fc->count].type   = t;
+    fc->filters[fc->count].param  = param;
+    fc->filters[fc->count].param2 = 0.0f;
+    fc->filters[fc->count].param3 = 0.0f;
+    fc->filters[fc->count].param4 = 0.0f;
+    fc->count++;
+    pthread_mutex_unlock(&fc->lock);
+    return true;
+}
+
+bool filter_chain_add_multi(FilterChain *fc, FilterType t,
+                            const float *params, int n_params)
+{
+    if (t == FX_UNKNOWN) return false;
+    if (n_params < 1) return false;
+    if (n_params > FILTER_MAX_PARAMS) n_params = FILTER_MAX_PARAMS;
+    pthread_mutex_lock(&fc->lock);
+    if (fc->count >= MAX_FILTERS) {
+        pthread_mutex_unlock(&fc->lock);
+        return false;
+    }
+    Filter *f = &fc->filters[fc->count];
+    f->type   = t;
+    f->param  = params[0];
+    f->param2 = (n_params > 1) ? params[1] : 0.0f;
+    f->param3 = (n_params > 2) ? params[2] : 0.0f;
+    f->param4 = (n_params > 3) ? params[3] : 0.0f;
     fc->count++;
     pthread_mutex_unlock(&fc->lock);
     return true;
@@ -336,23 +449,49 @@ static void fx_blur(Frame *f, int radius)
     free(tmp);
 }
 
-static void fx_vignette(Frame *f, float strength)
+/* ── vignette ──
+ * strength   : 0..1 darkening amount at the corners
+ * radius     : where darkening starts as fraction of half-diagonal (0..1);
+ *              0 = start at center, 1 = start at corner. Default 0 (original).
+ * warmth     : 0..1 shift the darkened areas toward warm brown (film look);
+ *              0 = pure darkening. Default 0.
+ */
+static void fx_vignette(Frame *f, float strength, float radius, float warmth)
 {
     if (strength < 0) strength = 0;
     if (strength > 1) strength = 1;
+    if (radius   < 0) radius   = 0;
+    if (radius   > 0.95f) radius = 0.95f;
+    if (warmth   < 0) warmth   = 0;
+    if (warmth   > 1) warmth   = 1;
+
     int w = f->width, h = f->height;
     float cx = w / 2.0f, cy = h / 2.0f;
     float maxd = sqrtf(cx*cx + cy*cy);
+    float denom = 1.0f - radius;
+    if (denom < 0.05f) denom = 0.05f;
+
     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;
+            float t = (d - radius) / denom;
+            if (t < 0) t = 0;
+            float v = 1.0f - strength * t * t;
             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);
+
+            /* Blend toward warm tone: (B G R) → (30 60 90)*(1-v)*warmth */
+            float warmB = 30.0f  * (1.0f - v) * warmth;
+            float warmG = 60.0f  * (1.0f - v) * warmth;
+            float warmR = 90.0f  * (1.0f - v) * warmth;
+
+            int b = (int)(p[0] * v + warmB);
+            int g = (int)(p[1] * v + warmG);
+            int r = (int)(p[2] * v + warmR);
+            p[0] = clamp_u8(b);
+            p[1] = clamp_u8(g);
+            p[2] = clamp_u8(r);
         }
     }
 }
@@ -434,31 +573,46 @@ 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)
+/* ── chromashift: VHS-style RGB channel separation ──────────
+ * dx      : horizontal offset for R (opposite direction for B)
+ * dxb     : optional independent horizontal offset for B; 0 = mirror dx
+ * dy_r    : optional vertical offset for R (0 = none)
+ */
+static void fx_chromashift(Frame *f, int dx, int dxb, int dy_r)
 {
-    if (dx == 0) return;
+    if (dx == 0 && dxb == 0 && dy_r == 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);
 
+    if (dxb == 0) dxb = -dx;   /* default: B opposite of R */
+
     for (int y = 0; y < h; y++) {
         uint8_t *dst = f->data + y * f->stride;
-        const uint8_t *src = tmp + y * w * 3;
+        int yr = y + dy_r;
+        if (yr < 0) yr = 0;
+        if (yr >= h) yr = h - 1;
+        const uint8_t *src_g = tmp + y  * w * 3;
+        const uint8_t *src_r = tmp + yr * 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 */
+            int xr = x + dx;   if (xr < 0) xr = 0; if (xr >= w) xr = w - 1;
+            int xb = x + dxb;  if (xb < 0) xb = 0; if (xb >= w) xb = w - 1;
+            dst[x*3+0] = src_g[xb*3+0];   /* B */
+            dst[x*3+1] = src_g[x*3+1];    /* G — reference */
+            dst[x*3+2] = src_r[xr*3+2];   /* R */
         }
     }
     free(tmp);
 }
 
-/* ── glitch: random horizontal slice displacement (animated) ── */
-static void fx_glitch(Frame *f, float intensity)
+/* ── glitch: random horizontal slice displacement (animated) ──
+ * intensity   : how far shifts go and how often (0..1)
+ * slice_h_override : forced slice height in px (0 = derive from intensity)
+ * max_shift_pct    : override on max shift as %-of-width (0 = default 15%)
+ */
+static void fx_glitch(Frame *f, float intensity, int slice_h_override,
+                       float max_shift_pct)
 {
     if (intensity <= 0) return;
     if (intensity > 1) intensity = 1;
@@ -469,12 +623,16 @@ static void fx_glitch(Frame *f, float intensity)
     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);
+    int slice_h = slice_h_override > 0
+                ? slice_h_override
+                : 4 + (int)((1.0f - intensity) * 20);
+    float pct = (max_shift_pct > 0.0f) ? max_shift_pct * 0.01f : 0.15f;
+    int max_shift = (int)((float)w * pct * intensity);
+    if (max_shift < 1) max_shift = 1;
 
     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 */
+        if ((r & 7) > 5) continue;
         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++) {
@@ -493,11 +651,19 @@ static void fx_glitch(Frame *f, float intensity)
     free(tmp);
 }
 
-/* ── kaleidoscope: mirror a wedge around the center ─────────── */
-static void fx_kaleidoscope(Frame *f, int segments)
+/* ── kaleidoscope v2: mirror a wedge around the center ─────────
+ * segments : number of wedges
+ * rot_deg  : static rotation applied to output
+ * spin     : additional per-frame spin rate (deg/frame)
+ * zoom     : magnification of the sampled wedge (0 → 1.0; >1 zooms in,
+ *            <1 zooms out — animate it via vcam-tune for tunnel vibes)
+ */
+static void fx_kaleidoscope(Frame *f, int segments, float rot_deg,
+                            float spin, float zoom)
 {
     if (segments < 2) segments = 2;
     if (segments > 32) segments = 32;
+    if (zoom <= 0.05f) zoom = 1.0f;
     int w = f->width, h = f->height;
     uint8_t *tmp = malloc((size_t)w * h * 3);
     if (!tmp) return;
@@ -505,14 +671,15 @@ static void fx_kaleidoscope(Frame *f, int segments)
 
     float cx = w / 2.0f, cy = h / 2.0f;
     float wedge = (float)(3.14159265358979f * 2.0f) / segments;
+    float rot   = (rot_deg + spin * (float)anim_tick()) * 3.14159265f / 180.0f;
+    float inv_zoom = 1.0f / zoom;
 
     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 r = sqrtf(dx*dx + dy*dy) * inv_zoom;
+            float a = atan2f(dy, dx) + rot;
             float m = fmodf(a, wedge);
             if (m < 0) m += wedge;
             if (m > wedge / 2) m = wedge - m;
@@ -530,22 +697,34 @@ static void fx_kaleidoscope(Frame *f, int segments)
 }
 
 /* ── swirl: radial rotation that intensifies with distance ── */
-static void fx_swirl(Frame *f, float strength)
+/* ── swirl v2 ──
+ * strength : twist amount (radians at center)
+ * radius   : p2 — fraction of frame the swirl covers, 0.2..1 (0 → 1)
+ * spin     : p3 — animate the twist over time (rate; 0 = static)
+ */
+static void fx_swirl(Frame *f, float strength, float radius_frac, float spin)
 {
     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);
 
+    if (radius_frac <= 0.05f) radius_frac = 1.0f;
+    if (radius_frac > 1.0f) radius_frac = 1.0f;
+    float s = strength;
+    if (spin != 0.0f)
+        s += sinf((float)anim_tick() / 30.0f * spin) * strength;
+
     float cx = w / 2.0f, cy = h / 2.0f;
-    float maxr = sqrtf(cx*cx + cy*cy);
+    float maxr = sqrtf(cx*cx + cy*cy) * radius_frac;
 
     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;
+            if (r >= maxr) continue;   /* outside swirl radius: untouched */
+            float theta = atan2f(dy, dx) + s * (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) {
@@ -619,41 +798,72 @@ static void fx_oldfilm(Frame *f)
     }
 
     /* vignette */
-    fx_vignette(f, 0.7f);
+    fx_vignette(f, 0.7f, 0.0f, 0.0f);
 }
 
 /* ── wave: sinusoidal vertical wave displacement ────────────── */
-static void fx_wave(Frame *f, float amplitude)
+/* ── wave: sinusoidal x-shift, now with frequency and orientation ──
+ * amplitude : pixel-magnitude of the displacement
+ * freq_hz   : spatial frequency (waves per screen); 0 = default
+ * speed     : phase advance rate (px/frame); 0 = default
+ * vertical  : if nonzero, shifts columns vertically instead of rows horizontally
+ */
+static void fx_wave(Frame *f, float amplitude, float freq_hz, float speed,
+                    int vertical)
 {
     if (amplitude < 1) amplitude = 1;
     int w = f->width, h = f->height;
     unsigned long t = anim_tick();
-    float phase = (t * 0.1f);
+    /* Defaults calibrated to match the original behaviour. */
+    float phase = t * (speed > 0.0f ? speed : 0.1f);
+    /* freq_hz: convert "waves per screen" → radians per pixel. */
+    float k = (freq_hz > 0.0f)
+            ? (freq_hz * 2.0f * 3.14159265f / (vertical ? (float)w : (float)h))
+            : 0.05f;   /* original: sin(y*0.05) */
 
     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;
+    if (!vertical) {
+        for (int y = 0; y < h; y++) {
+            int shift = (int)(amplitude * sinf(y * k + 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];
+            }
+        }
+    } else {
+        /* Vertical: each column shifts up/down by sin(x * k + phase). */
         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];
+            int shift = (int)(amplitude * sinf(x * k + phase));
+            for (int y = 0; y < h; y++) {
+                int sy = y - shift;
+                if (sy < 0) sy = 0;
+                if (sy >= h) sy = h - 1;
+                const uint8_t *src = tmp + sy * w * 3 + x * 3;
+                uint8_t       *dst = f->data + y * f->stride + x * 3;
+                dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2];
+            }
         }
     }
     free(tmp);
 }
 
 /* ── cartoon: posterize + emphasize edges ───────────────────── */
-static void fx_cartoon(Frame *f, float edge_thresh)
+/* cartoon v2: levels (p2) = posterize color levels, 2..12 (0 → 5) */
+static void fx_cartoon(Frame *f, float edge_thresh, float levels_f)
 {
     int w = f->width, h = f->height;
+    int levels = (int)levels_f;
+    if (levels < 2) levels = 5;
+    if (levels > 12) levels = 12;
 
     /* Compute luma + Sobel magnitude */
     uint8_t *luma = malloc((size_t)w * h);
@@ -664,8 +874,8 @@ static void fx_cartoon(Frame *f, float edge_thresh)
             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;
+    /* Posterize colors */
+    int step = 256 / levels;
     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);
@@ -835,15 +1045,18 @@ static void fx_glow(Frame *f, float intensity)
     free(blur);
 }
 
-/* ── pinch: inward radial pull (subtle anamorphic squeeze) ──── */
-static void fx_pinch(Frame *f, float strength)
+/* ── pinch v2: inward radial pull ──
+ * strength; cx_frac/cy_frac (p2/p3): center position as 0..1 of the
+ * frame (0 → centered). Off-center pinches look like gravity wells. */
+static void fx_pinch(Frame *f, float strength, float cx_frac, float cy_frac)
 {
     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 cx = (cx_frac > 0.01f && cx_frac < 0.99f) ? cx_frac * w : w / 2.0f;
+    float cy = (cy_frac > 0.01f && cy_frac < 0.99f) ? cy_frac * h : h / 2.0f;
     float maxr = sqrtf(cx*cx + cy*cy);
 
     for (int y = 0; y < h; y++) {
@@ -867,15 +1080,17 @@ static void fx_pinch(Frame *f, float strength)
     free(tmp);
 }
 
-/* ── bulge: outward radial push (fisheye-like) ──────────────── */
-static void fx_bulge(Frame *f, float strength)
+/* ── bulge v2: outward radial push (fisheye-like) ──
+ * strength; cx_frac/cy_frac (p2/p3): center as 0..1 (0 → centered). */
+static void fx_bulge(Frame *f, float strength, float cx_frac, float cy_frac)
 {
     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 cx = (cx_frac > 0.01f && cx_frac < 0.99f) ? cx_frac * w : w / 2.0f;
+    float cy = (cy_frac > 0.01f && cy_frac < 0.99f) ? cy_frac * h : h / 2.0f;
     float maxr = sqrtf(cx*cx + cy*cy);
 
     for (int y = 0; y < h; y++) {
@@ -974,7 +1189,7 @@ static void fx_modern(Frame *f, float strength)
         }
     }
     fx_contrast(f, 1.0f + 0.15f * strength);
-    fx_vignette(f, 0.3f * strength);
+    fx_vignette(f, 0.3f * strength, 0.0f, 0.0f);
 }
 
 /* ── cyberpunk: neon contrast + chromashift ─────────────────── */
@@ -993,7 +1208,7 @@ static void fx_cyberpunk(Frame *f, float intensity)
         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));
+    fx_chromashift(f, (int)(intensity * 10), 0, 0);
 }
 
 /* ── romantic: soft warm haze ──────────────────────────────── */
@@ -1014,7 +1229,7 @@ static void fx_romantic(Frame *f, float strength)
     /* Soft blur, brightness lift, vignette */
     fx_blur(f, 2);
     fx_brightness(f, 1.0f + strength * 0.15f);
-    fx_vignette(f, strength * 0.55f);
+    fx_vignette(f, strength * 0.55f, 0.0f, 0.0f);
 }
 
 /* ── vangogh: thick painterly with saturated brush strokes ── */
@@ -1044,9 +1259,9 @@ 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_kaleidoscope(f, s, 0.0f, 0.0f, 0.0f);
     fx_posterize(f, 4);
-    fx_cartoon(f, 35);
+    fx_cartoon(f, 35, 0);
 }
 
 /* ══════════════════════════════════════════════════════════════
@@ -1556,6 +1771,2402 @@ static void fx_scanlines(Frame *f, float gap)
     }
 }
 
+/* ──────────────────────────────────────────────────────────────
+ * Glitch-art filters — generative, stateful, time-varying.
+ * These maintain per-filter persistent state across frames (in
+ * function-local static variables) so they can animate. All state
+ * survives until the process exits; toggling a filter on and off
+ * resumes from where it left off, which is what users typically
+ * expect for these effects.
+ * ────────────────────────────────────────────────────────────── */
+
+/* ─── fx_shuffle ──
+ * Roving pixel-shuffle blocks. Picks random regions of the frame,
+ * gradually scrambles them over ~1.5 seconds, holds fully shuffled
+ * briefly, then UNSHUFFLES back over another ~1.5 seconds. Multiple
+ * regions active simultaneously (cap scales with intensity), each
+ * on its own life cycle.
+ *
+ * intensity (0..1): caps how many blocks can be active at once, and
+ * also sets the block size (higher intensity → larger blocks).
+ *
+ * The gradual shuffle uses partial-progress permutations: at progress
+ * p in [0..1], we apply p × N random swaps of the block's pixels
+ * (where N is enough for a full shuffle). The exact same swap
+ * sequence is played back in reverse for the unshuffle phase, so
+ * the block ends up pixel-perfect where it started — no smearing,
+ * no loss.
+ */
+#define SHUFFLE_MAX_ACTIVE   16
+#define SHUFFLE_BLOCK_MIN    32
+#define SHUFFLE_BLOCK_MAX    96
+#define SHUFFLE_PHASE_FRAMES 45   /* ~1.5s at 30fps for each of the 3 phases */
+#define SHUFFLE_MAX_SWAPS   (SHUFFLE_BLOCK_MAX * SHUFFLE_BLOCK_MAX / 2)
+
+typedef struct {
+    int x, y;             /* top-left of block */
+    int size;             /* actual block side in px */
+    int frame;            /* frames since spawn, counts up */
+    /* Fixed swap sequence generated at spawn. Each entry is a pair
+     * of pixel indices to swap. Playing the whole sequence forward
+     * fully shuffles the block; playing it in reverse un-shuffles it.
+     * We store pairs as uint16_t indices packed 2 per uint32_t. */
+    uint32_t swaps[SHUFFLE_MAX_SWAPS];
+    int      n_swaps;
+} ShuffleBlock;
+
+/* Apply the first k swaps of a block's swap sequence to its pixels
+ * (in place). Passing k=0 leaves the block untouched. Passing
+ * k=n_swaps fully shuffles it. Passing the same k twice = no-op
+ * because each swap is its own inverse — so playing 0..k forward
+ * followed by 0..k reverse restores original. */
+static void shuffle_apply_swaps(uint8_t *tmp, int size,
+                                const uint32_t *swaps, int k)
+{
+    for (int i = 0; i < k; i++) {
+        int a = (int)(swaps[i] & 0xFFFF);
+        int b = (int)((swaps[i] >> 16) & 0xFFFF);
+        uint8_t *pa = tmp + a * 3;
+        uint8_t *pb = tmp + b * 3;
+        uint8_t t0 = pa[0], t1 = pa[1], t2 = pa[2];
+        pa[0] = pb[0]; pa[1] = pb[1]; pa[2] = pb[2];
+        pb[0] = t0;    pb[1] = t1;    pb[2] = t2;
+    }
+    (void)size;
+}
+
+/* shuffle v2:
+ *   size_px (p2): block size override, 16..96 (0 → scale by intensity)
+ *   phase_s (p3): seconds per phase (shuffle-in / hold / unshuffle),
+ *                 0.3..5 (0 → 1.5) */
+static void fx_shuffle(Frame *f, float intensity, float size_px, float phase_s)
+{
+    static ShuffleBlock blocks[SHUFFLE_MAX_ACTIVE];
+    static int n_active = 0;
+
+    if (intensity < 0.0f) intensity = 0.0f;
+    if (intensity > 1.0f) intensity = 1.0f;
+
+    int max_active = 1 + (int)(intensity * (SHUFFLE_MAX_ACTIVE - 1));
+    int block_size;
+    if (size_px >= 16.0f) {
+        block_size = (int)size_px;
+        if (block_size > SHUFFLE_BLOCK_MAX) block_size = SHUFFLE_BLOCK_MAX;
+    } else {
+        block_size = SHUFFLE_BLOCK_MIN
+                   + (int)(intensity * (SHUFFLE_BLOCK_MAX - SHUFFLE_BLOCK_MIN));
+    }
+    block_size = (block_size / 4) * 4;
+
+    int phase_frames = SHUFFLE_PHASE_FRAMES;
+    if (phase_s >= 0.3f && phase_s <= 5.0f)
+        phase_frames = (int)(phase_s * 30.0f);
+    const int total_life = 3 * phase_frames;
+
+    /* Age & evict */
+    int kept = 0;
+    for (int i = 0; i < n_active; i++) {
+        blocks[i].frame++;
+        if (blocks[i].frame < total_life) {
+            if (kept != i) blocks[kept] = blocks[i];
+            kept++;
+        }
+    }
+    n_active = kept;
+
+    /* Spawn new blocks: max 1 per frame, low probability so it doesn't
+     * fill up in a burst. Roughly every 2 seconds one new block on
+     * average at intensity 0.5. */
+    if (n_active < max_active && (rand() % 60) < 1 + (int)(intensity * 4)) {
+        int cols = (f->width  - block_size) / block_size;
+        int rows = (f->height - block_size) / block_size;
+        if (cols >= 1 && rows >= 1) {
+            ShuffleBlock *b = &blocks[n_active++];
+            b->x = (rand() % cols) * block_size;
+            b->y = (rand() % rows) * block_size;
+            b->size = block_size;
+            b->frame = 0;
+
+            /* Generate the swap sequence. Roughly N/2 random-pair
+             * swaps is enough to fully shuffle N pixels (Fisher–Yates
+             * uses N swaps, but they're not independent — for a
+             * pairwise-swap "reversible shuffle" N/2 is enough to
+             * make the result look uniformly random). */
+            int npx = block_size * block_size;
+            int n_swaps = npx / 2;
+            if (n_swaps > SHUFFLE_MAX_SWAPS) n_swaps = SHUFFLE_MAX_SWAPS;
+            b->n_swaps = n_swaps;
+            for (int j = 0; j < n_swaps; j++) {
+                int a = rand() % npx;
+                int c = rand() % npx;
+                b->swaps[j] = ((uint32_t)c << 16) | (uint32_t)a;
+            }
+        }
+    }
+
+    /* Scratch: big enough for the biggest possible block. */
+    static uint8_t tmp[SHUFFLE_BLOCK_MAX * SHUFFLE_BLOCK_MAX * 3];
+
+    for (int i = 0; i < n_active; i++) {
+        ShuffleBlock *b = &blocks[i];
+        int size = b->size;
+        if (b->x + size > f->width || b->y + size > f->height) continue;
+
+        /* Determine how many swaps to apply based on which phase we're in.
+         *   Phase 0 (frame 0             .. PHASE_FRAMES-1):   shuffle IN, 0 → n_swaps
+         *   Phase 1 (PHASE_FRAMES        .. 2*PHASE_FRAMES-1): hold fully shuffled
+         *   Phase 2 (2*PHASE_FRAMES      .. 3*PHASE_FRAMES-1): unshuffle,  n_swaps → 0
+         */
+        int k;
+        if (b->frame < phase_frames) {
+            k = (b->frame * b->n_swaps) / phase_frames;
+        } else if (b->frame < 2 * phase_frames) {
+            k = b->n_swaps;
+        } else {
+            int rev = b->frame - 2 * phase_frames;
+            k = b->n_swaps - (rev * b->n_swaps) / phase_frames;
+        }
+        if (k <= 0) continue;  /* no-op frame (shouldn't change pixels) */
+
+        /* Copy the current block into tmp, apply k swaps, copy back. */
+        for (int by = 0; by < size; by++) {
+            uint8_t *src = f->data + (b->y + by) * f->stride + b->x * 3;
+            memcpy(tmp + by * size * 3, src, (size_t)size * 3);
+        }
+        shuffle_apply_swaps(tmp, size, b->swaps, k);
+        for (int by = 0; by < size; by++) {
+            uint8_t *dst = f->data + (b->y + by) * f->stride + b->x * 3;
+            memcpy(dst, tmp + by * size * 3, (size_t)size * 3);
+        }
+    }
+}
+
+/* ─── fx_pixelsort ──
+ * The classic pixel-sort glitch effect. Picks random horizontal spans
+ * across random rows and sorts the pixels by luminance, creating
+ * the unmistakable "vertical bleed" look used in glitch-art.
+ *
+ * density (0..1): how many active sort lines to maintain at once.
+ */
+#define PIXELSORT_MAX_ACTIVE 24
+
+typedef struct {
+    int row, x0, x1;
+    int descending;       /* 0 = light→dark, 1 = dark→light */
+    int frames_left;
+} SortLine;
+
+static int sort_cmp_asc(const void *a, const void *b)
+{
+    const uint8_t *pa = a, *pb = b;
+    int la = pa[0] + 2 * pa[1] + pa[2];  /* B + 2G + R, cheap luma */
+    int lb = pb[0] + 2 * pb[1] + pb[2];
+    return la - lb;
+}
+static int sort_cmp_desc(const void *a, const void *b)
+{
+    return sort_cmp_asc(b, a);
+}
+
+static void fx_pixelsort(Frame *f, float density)
+{
+    static SortLine lines[PIXELSORT_MAX_ACTIVE];
+    static int n_active = 0;
+
+    if (density < 0.0f) density = 0.0f;
+    if (density > 1.0f) density = 1.0f;
+    int max_active = (int)(density * PIXELSORT_MAX_ACTIVE);
+    if (max_active < 1) max_active = 1;
+
+    int kept = 0;
+    for (int i = 0; i < n_active; i++) {
+        lines[i].frames_left--;
+        if (lines[i].frames_left > 0) {
+            if (kept != i) lines[kept] = lines[i];
+            kept++;
+        }
+    }
+    n_active = kept;
+
+    int spawn_budget = 2;
+    while (n_active < max_active && spawn_budget-- > 0 && (rand() % 100) < 40) {
+        SortLine *l = &lines[n_active++];
+        l->row = rand() % f->height;
+        int len = 80 + rand() % (f->width / 2 + 1);
+        l->x0 = rand() % (f->width > len ? f->width - len : 1);
+        l->x1 = l->x0 + len;
+        if (l->x1 > f->width) l->x1 = f->width;
+        l->descending  = rand() & 1;
+        l->frames_left = 3 + (rand() % 10);
+    }
+
+    for (int i = 0; i < n_active; i++) {
+        SortLine *l = &lines[i];
+        uint8_t *row = f->data + l->row * f->stride + l->x0 * 3;
+        int n = l->x1 - l->x0;
+        if (n < 2) continue;
+        qsort(row, (size_t)n, 3, l->descending ? sort_cmp_desc : sort_cmp_asc);
+    }
+}
+
+/* ─── fx_rgb_delay ──
+ * Chromatic lag. Each color channel comes from a different point in
+ * recent history: B is "live", G is 1 frame behind, R is up to N
+ * frames behind (where N grows with strength). When you move, you
+ * leave a green and red "ghost" trail. Subtle at strength=0.3,
+ * trippy at strength=1.0.
+ *
+ * Stores past frames in a 4-deep ring buffer that grows/shrinks
+ * with the frame size. Memory: 4 × stride × height ≈ 11 MB for 720p.
+ */
+typedef struct {
+    uint8_t *frames[4];
+    int      frame_w, frame_h, stride;
+    int      write_idx;
+    int      filled;       /* how many slots have been written into */
+} RGBDelayState;
+
+static RGBDelayState g_rgb_delay = {{0}, 0, 0, 0, 0, 0};
+
+static void fx_rgb_delay(Frame *f, float strength)
+{
+    if (strength < 0.0f) strength = 0.0f;
+    if (strength > 1.0f) strength = 1.0f;
+    int max_delay = 1 + (int)(strength * 2.5f);   /* 1..3 frames */
+    if (max_delay > 3) max_delay = 3;
+
+    int size = f->stride * f->height;
+
+    /* (Re)allocate if first call or size changed. */
+    if (g_rgb_delay.frame_w != f->width ||
+        g_rgb_delay.frame_h != f->height ||
+        g_rgb_delay.stride  != f->stride) {
+        for (int i = 0; i < 4; i++) {
+            free(g_rgb_delay.frames[i]);
+            g_rgb_delay.frames[i] = malloc((size_t)size);
+            if (!g_rgb_delay.frames[i]) {
+                /* OOM — leave everything cleared, skip filter this frame */
+                for (int j = 0; j < 4; j++) {
+                    free(g_rgb_delay.frames[j]);
+                    g_rgb_delay.frames[j] = NULL;
+                }
+                g_rgb_delay.frame_w = g_rgb_delay.frame_h = g_rgb_delay.stride = 0;
+                return;
+            }
+            memcpy(g_rgb_delay.frames[i], f->data, (size_t)size);
+        }
+        g_rgb_delay.frame_w   = f->width;
+        g_rgb_delay.frame_h   = f->height;
+        g_rgb_delay.stride    = f->stride;
+        g_rgb_delay.write_idx = 0;
+        g_rgb_delay.filled    = 4;
+    }
+
+    /* Store the CURRENT (unmodified) frame in the ring first, so the
+     * G/R reads further down pull from a clean history rather than
+     * compounding their own modifications across frames. */
+    int w = g_rgb_delay.write_idx;
+    memcpy(g_rgb_delay.frames[w], f->data, (size_t)size);
+
+    int idx_g = (w - 1 + 4) % 4;
+    int idx_r = (w - max_delay + 4) % 4;
+
+    uint8_t *cur   = f->data;
+    uint8_t *gpast = g_rgb_delay.frames[idx_g];
+    uint8_t *rpast = g_rgb_delay.frames[idx_r];
+
+    int n = f->width * f->height;
+    for (int i = 0; i < n; i++) {
+        int o = i * 3;
+        /* cur[o+0] = B (live, untouched) */
+        cur[o + 1] = gpast[o + 1];   /* G from 1 frame ago     */
+        cur[o + 2] = rpast[o + 2];   /* R from max_delay back  */
+    }
+
+    g_rgb_delay.write_idx = (w + 1) % 4;
+}
+
+/* ─── fx_drift ──
+ * Horizontal scanline drift. The image is split into bands of
+ * configurable height, and each band gets its own slowly-drifting
+ * horizontal offset. Looks like a misaligned VHS or a corrupted
+ * data stream. Each band's target offset is randomised every few
+ * frames; current offsets ease toward target so the motion is
+ * smooth rather than jittery.
+ *
+ * param: band height in pixels (clamped 2..32, default 8).
+ */
+typedef struct {
+    int    band_h;
+    int    n_bands;
+    float *offset;        /* current x-offset, smoothed */
+    float *target;        /* target x-offset, updated periodically */
+    int    frame_w, frame_h;
+} DriftState;
+
+static DriftState g_drift = {0, 0, NULL, NULL, 0, 0};
+
+/* drift v2: max_shift (p2) px 5..120 (0 → 20 with occasional 60 jolts) */
+static void fx_drift(Frame *f, float param, float max_shift_f)
+{
+    int band_h = (int)param;
+    if (band_h < 2)  band_h = 2;
+    if (band_h > 32) band_h = 32;
+
+    if (g_drift.frame_w  != f->width ||
+        g_drift.frame_h  != f->height ||
+        g_drift.band_h   != band_h) {
+        free(g_drift.offset);
+        free(g_drift.target);
+        g_drift.n_bands = (f->height + band_h - 1) / band_h;
+        g_drift.offset = calloc((size_t)g_drift.n_bands, sizeof(float));
+        g_drift.target = calloc((size_t)g_drift.n_bands, sizeof(float));
+        g_drift.band_h  = band_h;
+        g_drift.frame_w = f->width;
+        g_drift.frame_h = f->height;
+        if (!g_drift.offset || !g_drift.target) {
+            free(g_drift.offset); free(g_drift.target);
+            g_drift.offset = g_drift.target = NULL;
+            g_drift.frame_w = g_drift.frame_h = 0;
+            return;
+        }
+    }
+    if (!g_drift.offset || !g_drift.target) return;
+
+    /* Every ~8 frames, randomly pick new targets for a fraction of
+     * the bands. Small magnitudes most of the time, occasional jolts. */
+    static int frame_count = 0;
+    frame_count++;
+    if (frame_count % 8 == 0) {
+        for (int i = 0; i < g_drift.n_bands; i++) {
+            if (rand() % 5 == 0) {
+                int base = 20, big = 60;
+                if (max_shift_f >= 5.0f && max_shift_f <= 120.0f) {
+                    big  = (int)max_shift_f;
+                    base = big / 3 > 2 ? big / 3 : 2;
+                }
+                int jolt = (rand() % 7 == 0) ? big : base;
+                g_drift.target[i] = (float)((rand() % (2 * jolt + 1)) - jolt);
+            }
+        }
+    }
+
+    /* Ease current → target each frame */
+    for (int i = 0; i < g_drift.n_bands; i++)
+        g_drift.offset[i] = g_drift.offset[i] * 0.85f + g_drift.target[i] * 0.15f;
+
+    /* Apply: for each row, shift by its band's offset. Use a scratch
+     * row buffer so we don't read-after-write. */
+    uint8_t *tmp = malloc((size_t)f->stride);
+    if (!tmp) return;
+
+    for (int y = 0; y < f->height; y++) {
+        int band = y / band_h;
+        if (band >= g_drift.n_bands) band = g_drift.n_bands - 1;
+        int offset = (int)g_drift.offset[band];
+        if (offset == 0) continue;
+
+        uint8_t *row = f->data + y * f->stride;
+        memcpy(tmp, row, (size_t)f->stride);
+        for (int x = 0; x < f->width; x++) {
+            int sx = x - offset;
+            if (sx < 0) sx = 0;
+            if (sx >= f->width) sx = f->width - 1;
+            row[x * 3 + 0] = tmp[sx * 3 + 0];
+            row[x * 3 + 1] = tmp[sx * 3 + 1];
+            row[x * 3 + 2] = tmp[sx * 3 + 2];
+        }
+    }
+    free(tmp);
+}
+
+/* ─── fx_rain ──
+ * Digital "Matrix"-style rain. Random columns of the frame get a
+ * bright-green head moving downward, with a fading trail behind it.
+ * The webcam content shows through (it's tinted, not replaced), so
+ * it overlays cleanly on top of the rest of the pipeline.
+ *
+ * density (0..1): how many simultaneous rain columns to spawn.
+ */
+typedef struct {
+    int *head;       /* y-position of leading edge, -1 = inactive */
+    int *speed;      /* pixels per frame for active columns */
+    int frame_w, frame_h;
+} RainState;
+
+static RainState g_rain = {NULL, NULL, 0, 0};
+
+/* rain v2: speed_mult (p2) 0.3..3 (0 → 1); trail (p3) px 8..80 (0 → 28) */
+static void fx_rain(Frame *f, float density, float speed_mult, float trail_f)
+{
+    if (density < 0.0f) density = 0.0f;
+    if (density > 1.0f) density = 1.0f;
+
+    if (g_rain.frame_w != f->width || g_rain.frame_h != f->height) {
+        free(g_rain.head);
+        free(g_rain.speed);
+        g_rain.head  = malloc((size_t)f->width * sizeof(int));
+        g_rain.speed = malloc((size_t)f->width * sizeof(int));
+        g_rain.frame_w = f->width;
+        g_rain.frame_h = f->height;
+        if (!g_rain.head || !g_rain.speed) {
+            free(g_rain.head); free(g_rain.speed);
+            g_rain.head = g_rain.speed = NULL;
+            g_rain.frame_w = g_rain.frame_h = 0;
+            return;
+        }
+        for (int x = 0; x < f->width; x++) {
+            g_rain.head[x] = -1;
+            g_rain.speed[x] = 0;
+        }
+    }
+    if (!g_rain.head) return;
+
+    /* Spawn up to target_active simultaneous trails. Density 1.0
+     * roughly means 1 trail per 20 columns active. */
+    int target_active = (int)((float)f->width * density / 20.0f);
+    int active = 0;
+    for (int x = 0; x < f->width; x++) if (g_rain.head[x] >= 0) active++;
+
+    int spawn_attempts = (target_active - active) * 2;
+    if (spawn_attempts > 32) spawn_attempts = 32;
+    for (int i = 0; i < spawn_attempts; i++) {
+        int x = rand() % f->width;
+        if (g_rain.head[x] < 0) {
+            g_rain.head[x]  = 0;
+            float sm = (speed_mult >= 0.3f && speed_mult <= 3.0f) ? speed_mult : 1.0f;
+            g_rain.speed[x] = 1 + (int)((2 + rand() % 7) * sm);
+        }
+    }
+
+    /* Apply each trail as a luma-tinting overlay */
+    int trail_len = 28;
+    if (trail_f >= 8.0f && trail_f <= 80.0f) trail_len = (int)trail_f;
+    for (int x = 0; x < f->width; x++) {
+        if (g_rain.head[x] < 0) continue;
+        int head_y = g_rain.head[x];
+
+        for (int t = 0; t < trail_len; t++) {
+            int y = head_y - t;
+            if (y < 0 || y >= f->height) continue;
+            uint8_t *p = f->data + y * f->stride + x * 3;
+
+            /* Fade is 1.0 at head, 0 at tail. Head is white-green;
+             * trail becomes pure green, fading to nothing. */
+            float fade = 1.0f - (float)t / (float)trail_len;
+            float g_boost = fade * 220.0f;
+            float dim     = 1.0f - fade * 0.7f;
+
+            int g = (int)((float)p[1] * dim + g_boost);
+            if (g > 255) g = 255;
+            p[0] = (uint8_t)((float)p[0] * dim);
+            p[1] = (uint8_t)g;
+            p[2] = (uint8_t)((float)p[2] * dim);
+
+            /* Head pixel: pure white for a single-frame "spark" */
+            if (t == 0) { p[0] = 240; p[1] = 255; p[2] = 240; }
+        }
+
+        g_rain.head[x] += g_rain.speed[x];
+        if (g_rain.head[x] > f->height + trail_len) {
+            g_rain.head[x] = -1;
+        }
+    }
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * Temporal filters — rgbdelay's siblings. All maintain persistent
+ * frame history and re-allocate transparently on resolution change.
+ * ────────────────────────────────────────────────────────────── */
+
+/* Shared helper: (re)allocate a persistent BGR frame buffer to match
+ * the current frame, seeding it with the current content on (re)alloc.
+ * Returns NULL on OOM. */
+static uint8_t *temporal_buf(uint8_t **buf, int *bw, int *bh, int *bs,
+                             const Frame *f)
+{
+    int size = f->stride * f->height;
+    if (*bw != f->width || *bh != f->height || *bs != f->stride) {
+        free(*buf);
+        *buf = malloc((size_t)size);
+        if (!*buf) { *bw = *bh = *bs = 0; return NULL; }
+        memcpy(*buf, f->data, (size_t)size);
+        *bw = f->width; *bh = f->height; *bs = f->stride;
+    }
+    return *buf;
+}
+
+/* ─── fx_echo ──
+ * Motion trails. Keeps an exponential moving average of past frames
+ * and blends the current frame into it. Anything that moves leaves a
+ * fading ghost behind. strength (0..1): trail persistence — 0.3 is a
+ * subtle smear, 0.9 is full "light painting".
+ */
+static void fx_echo(Frame *f, float strength)
+{
+    static uint8_t *acc = NULL;
+    static int aw = 0, ah = 0, as = 0;
+
+    if (strength < 0.0f) strength = 0.0f;
+    if (strength > 0.97f) strength = 0.97f;
+
+    if (!temporal_buf(&acc, &aw, &ah, &as, f)) return;
+
+    int n = f->stride * f->height;
+    float keep = strength, mix = 1.0f - strength;
+    for (int i = 0; i < n; i++) {
+        int v = (int)(acc[i] * keep + f->data[i] * mix);
+        acc[i] = (uint8_t)v;
+        f->data[i] = acc[i];
+    }
+}
+
+/* ─── fx_slitscan ──
+ * Time gradient: the top row of the output is "now", and each row
+ * further down samples a progressively OLDER frame from a ring
+ * buffer. Wave your hand and it bends through time like taffy.
+ * depth (0..1): how far back the bottom row reaches (up to the ring
+ * size). One of the all-time great video-art effects.
+ */
+#define SLITSCAN_RING 16
+
+/* slitscan v2: dir (p2): 0 = top is 'now' (default), 1 = bottom is
+ * 'now' (time flows upward) */
+static void fx_slitscan(Frame *f, float depth, float dir)
+{
+    static uint8_t *ring[SLITSCAN_RING] = {0};
+    static int rw = 0, rh = 0, rs = 0, widx = 0;
+
+    if (depth < 0.0f) depth = 0.0f;
+    if (depth > 1.0f) depth = 1.0f;
+
+    int size = f->stride * f->height;
+
+    if (rw != f->width || rh != f->height || rs != f->stride) {
+        for (int i = 0; i < SLITSCAN_RING; i++) {
+            free(ring[i]);
+            ring[i] = malloc((size_t)size);
+            if (!ring[i]) {
+                for (int j = 0; j <= i; j++) { free(ring[j]); ring[j] = NULL; }
+                rw = rh = rs = 0;
+                return;
+            }
+            memcpy(ring[i], f->data, (size_t)size);
+        }
+        rw = f->width; rh = f->height; rs = f->stride;
+        widx = 0;
+    }
+
+    /* Store current frame */
+    memcpy(ring[widx], f->data, (size_t)size);
+
+    int max_back = (int)(depth * (SLITSCAN_RING - 1));
+    if (max_back < 1) max_back = 1;
+
+    int flip = dir >= 0.5f;
+    for (int y = 0; y < f->height; y++) {
+        /* Row y reads from (y/h)*max_back frames ago */
+        int ry = flip ? (f->height - 1 - y) : y;
+        int back = (ry * max_back) / (f->height > 1 ? f->height - 1 : 1);
+        int idx = (widx - back + SLITSCAN_RING) % SLITSCAN_RING;
+        memcpy(f->data + y * f->stride,
+               ring[idx] + y * f->stride,
+               (size_t)f->width * 3);
+    }
+
+    widx = (widx + 1) % SLITSCAN_RING;
+}
+
+/* ─── fx_mosh ──
+ * Fake datamosh. Keeps a "held" frame and only lets pixels through
+ * when they've changed enough since the hold — so static background
+ * freezes and smears while motion punches through, like a corrupted
+ * P-frame stream. Every ~90 frames the hold refreshes (a fake
+ * "I-frame") so it doesn't diverge forever.
+ * sensitivity (0..1): lower = more smear (higher change threshold).
+ */
+/* mosh v2: keyint (p2) frames between auto-resync keyframes,
+ * 30..600 (0 → 90). Longer = deeper smear before reality returns. */
+static void fx_mosh(Frame *f, float sensitivity, float keyint_f)
+{
+    static uint8_t *held = NULL;
+    static int hw = 0, hh = 0, hs = 0;
+    static int frames_since_key = 0;
+
+    if (sensitivity < 0.0f) sensitivity = 0.0f;
+    if (sensitivity > 1.0f) sensitivity = 1.0f;
+    int thresh = 12 + (int)((1.0f - sensitivity) * 80.0f);  /* 12..92 */
+
+    if (!temporal_buf(&held, &hw, &hh, &hs, f)) return;
+
+    int keyint = 90;
+    if (keyint_f >= 30.0f && keyint_f <= 600.0f) keyint = (int)keyint_f;
+
+    /* Periodic keyframe: resync so the mosh doesn't decay into mud */
+    if (++frames_since_key >= keyint) {
+        memcpy(held, f->data, (size_t)(f->stride * f->height));
+        frames_since_key = 0;
+        return;
+    }
+
+    for (int y = 0; y < f->height; y++) {
+        uint8_t *cur = f->data + y * f->stride;
+        uint8_t *hld = held    + y * f->stride;
+        for (int x = 0; x < f->width; x++) {
+            int o = x * 3;
+            int d = abs(cur[o] - hld[o]) + abs(cur[o+1] - hld[o+1])
+                  + abs(cur[o+2] - hld[o+2]);
+            if (d > thresh) {
+                /* Motion: let it through and update the hold */
+                hld[o]   = cur[o];
+                hld[o+1] = cur[o+1];
+                hld[o+2] = cur[o+2];
+            } else {
+                /* Static: keep showing the held (possibly stale) pixel */
+                cur[o]   = hld[o];
+                cur[o+1] = hld[o+1];
+                cur[o+2] = hld[o+2];
+            }
+        }
+    }
+}
+
+/* ─── fx_stutter ──
+ * Temporal pixelation: capture a frame, freeze it for N frames, then
+ * capture the next. The classic music-video stop-motion stutter.
+ * period: frames to hold each capture (2..30, default 6).
+ */
+static void fx_stutter(Frame *f, float period)
+{
+    static uint8_t *held = NULL;
+    static int hw = 0, hh = 0, hs = 0;
+    static int countdown = 0;
+
+    int p = (int)period;
+    if (p < 2)  p = 2;
+    if (p > 30) p = 30;
+
+    int size = f->stride * f->height;
+    if (hw != f->width || hh != f->height || hs != f->stride) {
+        free(held);
+        held = malloc((size_t)size);
+        if (!held) { hw = hh = hs = 0; return; }
+        memcpy(held, f->data, (size_t)size);
+        hw = f->width; hh = f->height; hs = f->stride;
+        countdown = p;
+    }
+
+    if (--countdown <= 0) {
+        memcpy(held, f->data, (size_t)size);  /* grab a fresh frame */
+        countdown = p;
+    } else {
+        memcpy(f->data, held, (size_t)size);  /* keep showing the hold */
+    }
+}
+
+/* ─── fx_halftone ──
+ * Newspaper print: divide into cells, average each cell's color, and
+ * draw a filled disc whose radius scales with brightness on a dark
+ * background. CMYK-ish pop look, works great over motion.
+ * cell: cell size in px (4..32, default 8).
+ */
+static void fx_halftone(Frame *f, float cell_f)
+{
+    int cell = (int)cell_f;
+    if (cell < 4)  cell = 4;
+    if (cell > 32) cell = 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);
+
+    for (int cy = 0; cy < h; cy += cell) {
+        for (int cx = 0; cx < w; cx += cell) {
+            int cw = (cx + cell > w) ? w - cx : cell;
+            int ch = (cy + cell > h) ? h - cy : cell;
+
+            /* average color + luma of the cell */
+            long sb = 0, sg = 0, sr = 0;
+            for (int y = 0; y < ch; y++) {
+                const uint8_t *p = tmp + (cy+y) * w * 3 + cx * 3;
+                for (int x = 0; x < cw; x++, p += 3) {
+                    sb += p[0]; sg += p[1]; sr += p[2];
+                }
+            }
+            int npx = cw * ch;
+            int ab = (int)(sb / npx), ag = (int)(sg / npx), ar = (int)(sr / npx);
+            int luma = (ab * 114 + ag * 587 + ar * 299) / 1000;
+
+            /* disc radius proportional to brightness */
+            float max_r = cell * 0.5f;
+            float r = max_r * (float)luma / 255.0f;
+            float r2 = r * r;
+            float ccx = cx + cw / 2.0f, ccy = cy + ch / 2.0f;
+
+            for (int y = 0; y < ch; y++) {
+                uint8_t *p = f->data + (cy+y) * f->stride + cx * 3;
+                for (int x = 0; x < cw; x++, p += 3) {
+                    float dx = (cx + x) - ccx, dy = (cy + y) - ccy;
+                    if (dx*dx + dy*dy <= r2) {
+                        p[0] = (uint8_t)ab; p[1] = (uint8_t)ag; p[2] = (uint8_t)ar;
+                    } else {
+                        p[0] = 12; p[1] = 10; p[2] = 14;   /* near-black paper */
+                    }
+                }
+            }
+        }
+    }
+    free(tmp);
+}
+
+/* ─── fx_neon v2 ──
+ * Glowing colored edges over a darkened scene, now with real bloom.
+ *   strength (p1): glow intensity + background darkening, 0..1
+ *   thresh   (p2): edge sensitivity 10..120 (lower = more lines; 0 → 40)
+ *   huespeed (p3): rainbow drift rate (0 → 1.0)
+ *   glow     (p4): bloom spread 0..1 (0 → 0.5) — edges bleed light
+ * Edge hue still comes from gradient direction, so contours sweep
+ * through the spectrum as they curve.
+ */
+static void fx_neon(Frame *f, float strength, float thresh_f,
+                    float huespeed, float glow)
+{
+    if (strength < 0.0f) strength = 0.0f;
+    if (strength > 1.0f) strength = 1.0f;
+    int thresh = (int)thresh_f;
+    if (thresh <= 0) thresh = 40;
+    if (thresh < 10) thresh = 10;
+    if (thresh > 120) thresh = 120;
+    if (huespeed <= 0.0f) huespeed = 1.0f;
+    if (glow < 0.0f) glow = 0.0f;
+    if (glow == 0.0f) glow = 0.5f;
+    if (glow > 1.0f) glow = 1.0f;
+
+    int w = f->width, h = f->height;
+    uint8_t *luma = malloc((size_t)w * h);
+    uint8_t *ebuf = calloc((size_t)w * h * 3, 1);   /* edge-light layer */
+    if (!luma || !ebuf) { free(luma); free(ebuf); return; }
+
+    for (int y = 0; y < h; y++) {
+        const uint8_t *p = f->data + y * f->stride;
+        for (int x = 0; x < w; x++, p += 3)
+            luma[y*w + x] = (uint8_t)((p[0]*114 + p[1]*587 + p[2]*299) / 1000);
+    }
+
+    unsigned long t = anim_tick();
+    float hue_drift = (float)(t % 6283) * 0.001f * huespeed;
+
+    /* Pass 1: edge light into ebuf */
+    for (int y = 1; y < h - 1; y++) {
+        for (int x = 1; x < w - 1; x++) {
+            int gx = -luma[(y-1)*w + (x-1)] + luma[(y-1)*w + (x+1)]
+                     -2*luma[y*w + (x-1)]   + 2*luma[y*w + (x+1)]
+                     -luma[(y+1)*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 mag = abs(gx) + abs(gy);
+            if (mag <= thresh) continue;
+            float ang = atan2f((float)gy, (float)gx) + hue_drift;
+            float e = (float)(mag > 255 ? 255 : mag) / 255.0f * strength;
+            uint8_t *ep = ebuf + (y*w + x) * 3;
+            ep[0] = clamp_u8((int)((sinf(ang)          * 0.5f + 0.5f) * 255.0f * e));
+            ep[1] = clamp_u8((int)((sinf(ang + 2.094f) * 0.5f + 0.5f) * 255.0f * e));
+            ep[2] = clamp_u8((int)((sinf(ang + 4.189f) * 0.5f + 0.5f) * 255.0f * e));
+        }
+    }
+
+    /* Pass 2: composite — darken base, add edge light + bloom taps */
+    float dim = 1.0f - strength * 0.85f;
+    int gpix = (int)(glow * 96.0f);   /* bloom contribution scale */
+    for (int y = 2; y < h - 2; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        for (int x = 2; x < w - 2; x++) {
+            int o = x * 3;
+            const uint8_t *e0 = ebuf + (y*w + x) * 3;
+            /* bloom: sample 4 neighbours at distance 2 */
+            const uint8_t *e1 = ebuf + (y*w + x - 2) * 3;
+            const uint8_t *e2 = ebuf + (y*w + x + 2) * 3;
+            const uint8_t *e3 = ebuf + ((y-2)*w + x) * 3;
+            const uint8_t *e4 = ebuf + ((y+2)*w + x) * 3;
+            for (int c = 0; c < 3; c++) {
+                int bloom = (e1[c] + e2[c] + e3[c] + e4[c]) * gpix / 255;
+                dst[o+c] = clamp_u8((int)(dst[o+c] * dim) + e0[c] + bloom);
+            }
+        }
+    }
+    free(luma);
+    free(ebuf);
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * Batch 3: retro & warp
+ * ────────────────────────────────────────────────────────────── */
+
+/* ─── fx_emboss ──
+ * Classic relief: diagonal difference + mid-gray. Face becomes a
+ * pencil-carved bas-relief. strength 0..2.
+ */
+static void fx_emboss(Frame *f, float strength)
+{
+    if (strength < 0.1f) strength = 0.1f;
+    if (strength > 2.0f) strength = 2.0f;
+    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 = 1; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        const uint8_t *cur  = tmp + y * w * 3;
+        const uint8_t *diag = tmp + (y-1) * w * 3;
+        for (int x = 1; x < w; x++) {
+            int o = x * 3, od = (x-1) * 3;
+            /* luma difference against the up-left neighbour */
+            int lc = (cur[o]  *114 + cur[o+1] *587 + cur[o+2] *299) / 1000;
+            int ld = (diag[od]*114 + diag[od+1]*587 + diag[od+2]*299) / 1000;
+            int v = 128 + (int)((lc - ld) * strength * 2.0f);
+            uint8_t g = clamp_u8(v);
+            dst[o] = dst[o+1] = dst[o+2] = g;
+        }
+    }
+    free(tmp);
+}
+
+/* ─── fx_dither ──
+ * Ordered Bayer 4×4 dithering to N levels per channel. levels=2 gives
+ * the beloved 8-color retro-computer look with the characteristic
+ * crosshatch texture; higher levels are subtler.
+ */
+static void fx_dither(Frame *f, float levels_f)
+{
+    int levels = (int)levels_f;
+    if (levels < 2) levels = 2;
+    if (levels > 8) levels = 8;
+
+    /* 4x4 Bayer matrix, values 0..15 */
+    static const int bayer[4][4] = {
+        { 0,  8,  2, 10},
+        {12,  4, 14,  6},
+        { 3, 11,  1,  9},
+        {15,  7, 13,  5},
+    };
+
+    int w = f->width, h = f->height;
+    float step = 255.0f / (float)(levels - 1);
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *p = f->data + y * f->stride;
+        for (int x = 0; x < w; x++, p += 3) {
+            /* threshold offset in [-0.5, +0.5) scaled to one level step */
+            float t = ((float)bayer[y & 3][x & 3] / 16.0f - 0.5f) * step;
+            for (int c = 0; c < 3; c++) {
+                float v = (float)p[c] + t;
+                int q = (int)((v / step) + 0.5f);
+                if (q < 0) q = 0;
+                if (q > levels - 1) q = levels - 1;
+                p[c] = clamp_u8((int)(q * step));
+            }
+        }
+    }
+}
+
+/* ─── fx_tiles ──
+ * Mirror-tile grid: the frame becomes an n×n grid of downscaled
+ * copies, alternately mirrored horizontally/vertically so edges meet
+ * seamlessly — a wallpaper of yourself. n = tiles per row (2..8).
+ */
+static void fx_tiles(Frame *f, float n_f)
+{
+    int n = (int)n_f;
+    if (n < 2) n = 2;
+    if (n > 8) n = 8;
+
+    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;
+        int ty = y * n;               /* position within a virtual n× tall image */
+        int tile_y = ty / h;          /* which tile row */
+        int sy = ty % h;              /* source y within the tile */
+        if (tile_y & 1) sy = h - 1 - sy;  /* mirror odd rows */
+        for (int x = 0; x < w; x++) {
+            int tx = x * n;
+            int tile_x = tx / w;
+            int sx = tx % w;
+            if (tile_x & 1) sx = w - 1 - sx;  /* mirror odd cols */
+            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);
+}
+
+/* ─── fx_zoompulse ──
+ * The image breathes: zoom factor oscillates sinusoidally around 1.
+ * strength (0..1) controls the amplitude (up to ±25% zoom).
+ */
+/* zoompulse v2: rate (p2) oscillation speed (0 → 1) */
+static void fx_zoompulse(Frame *f, float strength, float rate)
+{
+    if (strength < 0.0f) strength = 0.0f;
+    if (strength > 1.0f) strength = 1.0f;
+
+    unsigned long t = anim_tick();
+    if (rate <= 0.0f) rate = 1.0f;
+    float zoom = 1.0f + strength * 0.25f * sinf((float)t * 0.12f * rate);
+
+    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 inv = 1.0f / zoom;
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        float sy_f = cy + (y - cy) * inv;
+        int sy = (int)sy_f;
+        if (sy < 0) sy = 0;
+        if (sy >= h) sy = h - 1;
+        for (int x = 0; x < w; x++) {
+            float sx_f = cx + (x - cx) * inv;
+            int sx = (int)sx_f;
+            if (sx < 0) sx = 0;
+            if (sx >= w) sx = w - 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);
+}
+
+/* ─── fx_oilslick ──
+ * Iridescence: each pixel's hue rotates by an angle keyed to its own
+ * brightness plus a slow time drift — like light on an oil film or
+ * soap bubble. Bright and dark areas swirl through different colors.
+ * strength (0..1): how far hues rotate.
+ */
+/* oilslick v2: speed (p2) hue drift rate (0 → 1) */
+static void fx_oilslick(Frame *f, float strength, float spd)
+{
+    if (strength < 0.0f) strength = 0.0f;
+    if (strength > 1.0f) strength = 1.0f;
+
+    unsigned long t = anim_tick();
+    if (spd <= 0.0f) spd = 1.0f;
+    float drift = (float)(t % 62830) * 0.001f * spd;
+
+    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 B = p[0], G = p[1], R = p[2];
+            int luma = (B*114 + G*587 + R*299) / 1000;
+
+            /* rotation angle: luma sweep + time drift */
+            float a = strength * ((float)luma * 0.045f + drift * 3.0f);
+            float s = sinf(a), c = cosf(a);
+
+            /* rotate the color vector in an isoluminant-ish plane:
+             * cheap approximation using two channel-difference axes */
+            float u = (float)(R - G) * 0.7071f;
+            float v = (float)(B - (R + G) / 2) * 0.8165f;
+            float u2 = u * c - v * s;
+            float v2 = u * s + v * c;
+
+            int nr = luma + (int)(u2 * 0.7071f * 1.0f) + (int)(v2 * -0.4082f);
+            int ng = luma + (int)(u2 * -0.7071f)       + (int)(v2 * -0.4082f);
+            int nb = luma + (int)(v2 * 0.8165f);
+
+            p[0] = clamp_u8(nb);
+            p[1] = clamp_u8(ng);
+            p[2] = clamp_u8(nr);
+        }
+    }
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * Batch 4: interactive & extravagant
+ * ────────────────────────────────────────────────────────────── */
+
+/* ─── fx_feedback ──
+ * Video feedback — like pointing a camera at its own monitor. The
+ * previous OUTPUT frame is zoomed and rotated around the center,
+ * then the current camera frame is blended on top. Anything bright
+ * spirals off into an infinite recursive tunnel behind you.
+ *   decay (0..1): how much of the past survives each frame (0.85)
+ *   zoom  (p2):   scale per frame, e.g. 1.03 pushes outward,
+ *                 0.97 pulls inward; 0 → default 1.04
+ *   rot   (p3):   degrees rotated per frame (default 1.5)
+ */
+static void fx_feedback(Frame *f, float decay, float zoom, float rot_deg)
+{
+    static uint8_t *prev = NULL;
+    static int pw = 0, ph = 0, ps = 0;
+
+    if (decay < 0.0f) decay = 0.0f;
+    if (decay > 0.98f) decay = 0.98f;
+    if (zoom <= 0.01f) zoom = 1.04f;
+    if (rot_deg == 0.0f) rot_deg = 1.5f;
+
+    int w = f->width, h = f->height;
+    int size = f->stride * h;
+
+    if (pw != w || ph != h || ps != f->stride) {
+        free(prev);
+        prev = malloc((size_t)size);
+        if (!prev) { pw = ph = ps = 0; return; }
+        memcpy(prev, f->data, (size_t)size);
+        pw = w; ph = h; ps = f->stride;
+    }
+
+    float cx = w / 2.0f, cy = h / 2.0f;
+    float ang = rot_deg * 3.14159265f / 180.0f;
+    /* Inverse mapping: to fill dst pixel, sample prev at the
+     * inverse transform (rotate -ang, scale 1/zoom). */
+    float ca = cosf(-ang) / zoom, sa = sinf(-ang) / zoom;
+
+    float keep = decay, mix = 1.0f - decay;
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        float dy0 = y - cy;
+        for (int x = 0; x < w; x++) {
+            float dx0 = x - cx;
+            int sx = (int)(cx + dx0 * ca - dy0 * sa);
+            int sy = (int)(cy + dx0 * sa + dy0 * ca);
+            int o = x * 3;
+            if (sx >= 0 && sx < w && sy >= 0 && sy < h) {
+                const uint8_t *pp = prev + sy * f->stride + sx * 3;
+                dst[o]   = (uint8_t)(dst[o]   * mix + pp[0] * keep);
+                dst[o+1] = (uint8_t)(dst[o+1] * mix + pp[1] * keep);
+                dst[o+2] = (uint8_t)(dst[o+2] * mix + pp[2] * keep);
+            }
+            /* outside prev: current frame stays as-is */
+        }
+    }
+    memcpy(prev, f->data, (size_t)size);
+}
+
+/* ─── fx_ripples v2 — INTERACTIVE ──
+ * Water-wave simulation driven by YOUR MOTION, now with weather.
+ *   sensitivity (p1): how easily motion excites the water, 0..1
+ *   rain        (p2): ambient droplets per second, 0 = off (try 3-8)
+ *   refract     (p3): refraction strength (0 → 2.0; up to ~6 = glassy)
+ * Simulation runs at 1/4 resolution.
+ */
+static void fx_ripples(Frame *f, float sensitivity, float rain,
+                       float refract)
+{
+    static float  *u0 = NULL, *u1 = NULL;
+    static uint8_t *prev_luma = NULL;
+    static int gw = 0, gh = 0, fw = 0, fh = 0;
+
+    if (sensitivity < 0.05f) sensitivity = 0.05f;
+    if (sensitivity > 1.0f)  sensitivity = 1.0f;
+    if (rain < 0.0f) rain = 0.0f;
+    if (rain > 30.0f) rain = 30.0f;
+    if (refract <= 0.0f) refract = 2.0f;
+    if (refract > 8.0f) refract = 8.0f;
+
+    int w = f->width, h = f->height;
+    int GW = w / 4, GH = h / 4;
+    if (GW < 8 || GH < 8) return;
+
+    if (fw != w || fh != h) {
+        free(u0); free(u1); free(prev_luma);
+        u0 = calloc((size_t)GW * GH, sizeof(float));
+        u1 = calloc((size_t)GW * GH, sizeof(float));
+        prev_luma = calloc((size_t)GW * GH, 1);
+        if (!u0 || !u1 || !prev_luma) {
+            free(u0); free(u1); free(prev_luma);
+            u0 = u1 = NULL; prev_luma = NULL;
+            fw = fh = 0;
+            return;
+        }
+        gw = GW; gh = GH; fw = w; fh = h;
+    }
+
+    /* 1. Downsampled luma + motion injection */
+    float inject = 12.0f * sensitivity;
+    int thresh = 14;
+    for (int gy = 1; gy < gh - 1; gy++) {
+        for (int gx = 1; gx < gw - 1; gx++) {
+            const uint8_t *p = f->data + (gy*4) * f->stride + (gx*4) * 3;
+            uint8_t l = (uint8_t)((p[0]*114 + p[1]*587 + p[2]*299) / 1000);
+            int gi = gy * gw + gx;
+            int d = abs((int)l - (int)prev_luma[gi]);
+            prev_luma[gi] = l;
+            if (d > thresh)
+                u1[gi] -= inject * ((float)d / 255.0f);
+        }
+    }
+
+    /* 1b. Ambient rain: random droplets at `rain` per second */
+    if (rain > 0.0f) {
+        int chance = (int)(1000.0f * rain / 30.0f);   /* per-mille per frame */
+        while (chance > 0) {
+            if ((rand() % 1000) < (chance > 1000 ? 1000 : chance)) {
+                int gx = 2 + rand() % (gw - 4);
+                int gy = 2 + rand() % (gh - 4);
+                float amp = 6.0f + (float)(rand() % 100) / 12.0f;
+                u1[gy * gw + gx] -= amp;
+                /* small splash: neighbours too */
+                u1[gy * gw + gx + 1]  -= amp * 0.4f;
+                u1[gy * gw + gx - 1]  -= amp * 0.4f;
+                u1[(gy+1) * gw + gx]  -= amp * 0.4f;
+                u1[(gy-1) * gw + gx]  -= amp * 0.4f;
+            }
+            chance -= 1000;
+        }
+    }
+
+    /* 2. Wave equation step */
+    for (int gy = 1; gy < gh - 1; gy++) {
+        for (int gx = 1; gx < gw - 1; gx++) {
+            int gi = gy * gw + gx;
+            float nsum = u1[gi-1] + u1[gi+1] + u1[gi-gw] + u1[gi+gw];
+            u0[gi] = (nsum * 0.5f - u0[gi]) * 0.985f;
+        }
+    }
+    { float *tmpp = u0; u0 = u1; u1 = tmpp; }
+
+    /* 3. Refract + shimmer */
+    uint8_t *src = malloc((size_t)w * h * 3);
+    if (!src) return;
+    memcpy(src, f->data, (size_t)w * h * 3);
+
+    for (int y = 4; y < h - 4; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        int gy = y / 4;
+        if (gy < 1) gy = 1;
+        if (gy > gh - 2) gy = gh - 2;
+        for (int x = 4; x < w - 4; x++) {
+            int gx = x / 4;
+            if (gx < 1) gx = 1;
+            if (gx > gw - 2) gx = gw - 2;
+            int gi = gy * gw + gx;
+            float ddx = u1[gi+1]  - u1[gi-1];
+            float ddy = u1[gi+gw] - u1[gi-gw];
+            int sx = x + (int)(ddx * refract);
+            int sy = y + (int)(ddy * refract);
+            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 *sp = src + sy * w * 3 + sx * 3;
+            int spec = (int)((ddx + ddy) * 6.0f * refract);
+            int o = x * 3;
+            dst[o]   = clamp_u8(sp[0] + spec);
+            dst[o+1] = clamp_u8(sp[1] + spec);
+            dst[o+2] = clamp_u8(sp[2] + spec);
+        }
+    }
+    free(src);
+}
+
+/* ─── fx_lightpaint — INTERACTIVE ──
+ * Motion leaves glowing trails: wherever the image changes, glowing
+ * color (hue cycling over time) is deposited into a persistent
+ * canvas that slowly fades. Wave your arms and paint light.
+ *   fade (0..1): trail persistence per frame (0.94 ≈ a few seconds).
+ */
+/* lightpaint v2: thresh (p2) 10..120 motion sensitivity (0 → 40, lower
+ * = easier to paint); huespd (p3) brush color cycle rate (0 → 1) */
+static void fx_lightpaint(Frame *f, float fade, float thresh_f, float huespd)
+{
+    static uint8_t *canvas = NULL;   /* additive glow layer */
+    static uint8_t *prevf  = NULL;   /* previous frame for motion */
+    static int cw = 0, chh = 0, cs = 0;
+
+    if (fade < 0.5f) fade = 0.5f;
+    if (fade > 0.995f) fade = 0.995f;
+
+    int w = f->width, h = f->height;
+    int size = f->stride * h;
+
+    if (cw != w || chh != h || cs != f->stride) {
+        free(canvas); free(prevf);
+        canvas = calloc(1, (size_t)size);
+        prevf  = malloc((size_t)size);
+        if (!canvas || !prevf) {
+            free(canvas); free(prevf);
+            canvas = prevf = NULL;
+            cw = chh = cs = 0;
+            return;
+        }
+        memcpy(prevf, f->data, (size_t)size);
+        cw = w; chh = h; cs = f->stride;
+    }
+
+    int mthresh = 40;
+    if (thresh_f >= 10.0f && thresh_f <= 120.0f) mthresh = (int)thresh_f;
+    if (huespd <= 0.0f) huespd = 1.0f;
+
+    /* Brush color cycles through the spectrum */
+    unsigned long t = anim_tick();
+    float hue = (float)(t % 3000) / 300.0f * 6.28318f * huespd;
+    int br = (int)((sinf(hue)            * 0.5f + 0.5f) * 255.0f);
+    int bg = (int)((sinf(hue + 2.094f)   * 0.5f + 0.5f) * 255.0f);
+    int bb = (int)((sinf(hue + 4.189f)   * 0.5f + 0.5f) * 255.0f);
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *cur = f->data + y * f->stride;
+        uint8_t *pre = prevf   + y * f->stride;
+        uint8_t *can = canvas  + y * f->stride;
+        for (int x = 0; x < w; x++) {
+            int o = x * 3;
+            int d = abs(cur[o] - pre[o]) + abs(cur[o+1] - pre[o+1])
+                  + abs(cur[o+2] - pre[o+2]);
+            /* fade the canvas */
+            can[o]   = (uint8_t)(can[o]   * fade);
+            can[o+1] = (uint8_t)(can[o+1] * fade);
+            can[o+2] = (uint8_t)(can[o+2] * fade);
+            if (d > mthresh) {
+                /* deposit brush proportional to motion energy */
+                int e = d > 255 ? 255 : d;
+                int nb = can[o]   + (bb * e) / 255;
+                int ng = can[o+1] + (bg * e) / 255;
+                int nr = can[o+2] + (br * e) / 255;
+                can[o]   = clamp_u8(nb);
+                can[o+1] = clamp_u8(ng);
+                can[o+2] = clamp_u8(nr);
+            }
+            /* remember current frame, then composite additively */
+            pre[o] = cur[o]; pre[o+1] = cur[o+1]; pre[o+2] = cur[o+2];
+            cur[o]   = clamp_u8(cur[o]   + can[o]);
+            cur[o+1] = clamp_u8(cur[o+1] + can[o+1]);
+            cur[o+2] = clamp_u8(cur[o+2] + can[o+2]);
+        }
+    }
+}
+
+/* ─── fx_hologram ──
+ * Sci-fi hologram projection: cyan-blue tint, horizontal scanlines,
+ * brightness flicker, a faint vertical ghost, and occasional
+ * horizontal band displacement. "Help me, Obi-Wan."
+ */
+/* hologram v2: gap (p2) scanline spacing 2..8 (0 → 3);
+ * glitchrate (p3) 0..1 band-glitch frequency (0 → 0.3) */
+static void fx_hologram(Frame *f, float strength, float gap_f, float glitchrate)
+{
+    if (strength < 0.0f) strength = 0.0f;
+    if (strength > 1.0f) strength = 1.0f;
+
+    int w = f->width, h = f->height;
+    unsigned long t = anim_tick();
+
+    /* Flicker: slow sine + per-frame jitter */
+    float flick = 0.92f
+                + 0.06f * sinf((float)t * 0.9f)
+                + 0.02f * (float)(hash_u((unsigned)t) & 0xFF) / 255.0f;
+
+    int gap = 3;
+    if (gap_f >= 2.0f && gap_f <= 8.0f) gap = (int)gap_f;
+    if (glitchrate <= 0.0f) glitchrate = 0.3f;
+    if (glitchrate > 1.0f) glitchrate = 1.0f;
+    unsigned glitch_mod = (unsigned)(4 + (1.0f - glitchrate) * 90.0f);
+
+    /* Occasional glitch band */
+    int band_y0 = -1, band_h = 0, band_shift = 0;
+    if ((hash_u((unsigned)t * 7u) % glitch_mod) == 0) {
+        band_y0    = (int)(hash_u((unsigned)t * 13u) % (unsigned)h);
+        band_h     = 8 + (int)(hash_u((unsigned)t * 17u) % 24u);
+        band_shift = (int)(hash_u((unsigned)t * 23u) % 41u) - 20;
+    }
+
+    uint8_t *src = malloc((size_t)w * h * 3);
+    if (!src) return;
+    memcpy(src, f->data, (size_t)w * h * 3);
+
+    const int ghost_dy = 5;
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        int sy = y;
+        if (band_y0 >= 0 && y >= band_y0 && y < band_y0 + band_h) sy = y; /* row kept, x shifted below */
+        float scan = (y % gap == 0) ? 0.55f : 1.0f;   /* scanline darkening */
+        float lum = flick * scan;
+        int gy = y + ghost_dy < h ? y + ghost_dy : y;
+
+        for (int x = 0; x < w; x++) {
+            int sx = x;
+            if (band_y0 >= 0 && y >= band_y0 && y < band_y0 + band_h) {
+                sx = x + band_shift;
+                if (sx < 0) sx = 0;
+                if (sx >= w) sx = w - 1;
+            }
+            const uint8_t *sp = src + sy * w * 3 + sx * 3;
+            const uint8_t *gp = src + gy * w * 3 + sx * 3;
+
+            /* luma of source + faint ghost */
+            int l  = (sp[0]*114 + sp[1]*587 + sp[2]*299) / 1000;
+            int lg = (gp[0]*114 + gp[1]*587 + gp[2]*299) / 1000;
+            float v = (l + lg * 0.25f) * lum;
+
+            /* map to hologram cyan */
+            int hb = (int)(v * 1.15f);
+            int hg = (int)(v * 0.95f);
+            int hr = (int)(v * 0.30f);
+
+            int o = x * 3;
+            /* blend with original by strength */
+            dst[o]   = clamp_u8((int)(sp[0] * (1-strength) + hb * strength));
+            dst[o+1] = clamp_u8((int)(sp[1] * (1-strength) + hg * strength));
+            dst[o+2] = clamp_u8((int)(sp[2] * (1-strength) + hr * strength));
+        }
+    }
+    free(src);
+}
+
+/* ─── fx_life v2 ──
+ * Conway's Game of Life living on your image, now tracking CELL AGE.
+ *   density (p1): seeding rate from edges, 0..1
+ *   color   (p2): 0 = classic green; 1 = age rainbow (newborns cyan,
+ *                 elders migrate through the spectrum)
+ *   speed   (p3): frames between generations, 1..6 (0 → 2)
+ * Cells store their age; colors evolve as colonies persist.
+ */
+static void fx_life(Frame *f, float density, float colormode, float speed)
+{
+    static uint8_t *cells = NULL, *next = NULL;   /* 0=dead, else age */
+    static int gw = 0, gh = 0, fw = 0, fh = 0;
+
+    if (density < 0.05f) density = 0.05f;
+    if (density > 1.0f)  density = 1.0f;
+    int step_iv = (int)speed;
+    if (step_iv <= 0) step_iv = 2;
+    if (step_iv > 6)  step_iv = 6;
+    int rainbow = colormode >= 0.5f;
+
+    int w = f->width, h = f->height;
+    int GW = w / 4, GH = h / 4;
+    if (GW < 8 || GH < 8) return;
+
+    if (fw != w || fh != h) {
+        free(cells); free(next);
+        cells = calloc((size_t)GW * GH, 1);
+        next  = calloc((size_t)GW * GH, 1);
+        if (!cells || !next) {
+            free(cells); free(next);
+            cells = next = NULL;
+            fw = fh = 0;
+            return;
+        }
+        gw = GW; gh = GH; fw = w; fh = h;
+    }
+
+    /* 1. Seed from edges */
+    int seed_chance = 4 + (int)((1.0f - density) * 28.0f);
+    for (int gy = 1; gy < gh - 1; gy++) {
+        const uint8_t *row = f->data + (gy*4) * f->stride;
+        for (int gx = 1; gx < gw - 1; gx++) {
+            const uint8_t *p0 = row + (gx*4 - 4) * 3;
+            const uint8_t *p1 = row + (gx*4 + 4) * 3;
+            int l0 = p0[0] + 2*p0[1] + p0[2];
+            int l1 = p1[0] + 2*p1[1] + p1[2];
+            if (abs(l1 - l0) > 160 && (rand() % seed_chance) == 0)
+                if (!cells[gy * gw + gx]) cells[gy * gw + gx] = 1;
+        }
+    }
+
+    /* 2. Life step every step_iv frames; survivors age */
+    static int tick = 0;
+    if ((tick++ % step_iv) == 0) {
+        for (int gy = 1; gy < gh - 1; gy++) {
+            for (int gx = 1; gx < gw - 1; gx++) {
+                int gi = gy * gw + gx;
+                int n = (cells[gi-1]      ? 1:0) + (cells[gi+1]      ? 1:0)
+                      + (cells[gi-gw]     ? 1:0) + (cells[gi+gw]     ? 1:0)
+                      + (cells[gi-gw-1]   ? 1:0) + (cells[gi-gw+1]   ? 1:0)
+                      + (cells[gi+gw-1]   ? 1:0) + (cells[gi+gw+1]   ? 1:0);
+                if (cells[gi]) {
+                    if (n == 2 || n == 3) {
+                        int age = cells[gi] + 1;
+                        next[gi] = (uint8_t)(age > 250 ? 250 : age);
+                    } else next[gi] = 0;
+                } else {
+                    next[gi] = (n == 3) ? 1 : 0;
+                }
+            }
+        }
+        uint8_t *tmpp = cells; cells = next; next = tmpp;
+    }
+
+    /* 3. Render */
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        int gy = y / 4;
+        if (gy >= gh) gy = gh - 1;
+        for (int x = 0; x < w; x++) {
+            int gx = x / 4;
+            if (gx >= gw) gx = gw - 1;
+            int o = x * 3;
+            uint8_t age = cells[gy * gw + gx];
+            if (age) {
+                int cb, cg, cr;
+                if (rainbow) {
+                    float ha = (float)age * 0.10f;   /* hue by age */
+                    cb = (int)((sinf(ha + 4.189f) * 0.5f + 0.5f) * 235.0f) + 20;
+                    cg = (int)((sinf(ha + 2.094f) * 0.5f + 0.5f) * 235.0f) + 20;
+                    cr = (int)((sinf(ha)          * 0.5f + 0.5f) * 235.0f) + 20;
+                } else {
+                    cb = 40; cg = 200; cr = 60;
+                }
+                dst[o]   = clamp_u8(dst[o]   / 2 + cb);
+                dst[o+1] = clamp_u8(dst[o+1] / 2 + cg);
+                dst[o+2] = clamp_u8(dst[o+2] / 2 + cr);
+            } else {
+                dst[o]   = (uint8_t)(dst[o]   * 3 / 4);
+                dst[o+1] = (uint8_t)(dst[o+1] * 3 / 4);
+                dst[o+2] = (uint8_t)(dst[o+2] * 3 / 4);
+            }
+        }
+    }
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * mathwarp — user-supplied displacement expressions, compiled at
+ * runtime by a small recursive-descent parser into an AST that's
+ * evaluated on a coarse grid (every 4th pixel) and bilinearly
+ * upsampled — fast enough for 720p30 with plenty of headroom.
+ *
+ * Grammar:  expr   := term (('+'|'-') term)*
+ *           term   := factor (('*'|'/') factor)*
+ *           factor := NUM | var | fn '(' expr ')' | '(' expr ')'
+ *                     | '-' factor
+ *           var    := x | y | w | h | t | r | a
+ *           fn     := sin | cos | abs | sqrt
+ * ────────────────────────────────────────────────────────────── */
+
+enum {
+    EN_CONST, EN_X, EN_Y, EN_W, EN_H, EN_T, EN_R, EN_A,
+    EN_ADD, EN_SUB, EN_MUL, EN_DIV, EN_MOD, EN_NEG,
+    EN_SIN, EN_COS, EN_ABS, EN_SQRT, EN_FLOOR,
+    EN_GT, EN_LT, EN_GE, EN_LE, EN_EQ, EN_NE,
+    EN_TERN,          /* a = condition, b = then, c = else */
+};
+
+#define EXPR_MAX_NODES 96
+
+typedef struct {
+    uint8_t op;
+    float   val;      /* EN_CONST */
+    int16_t a, b, c;  /* child node indices */
+} ExprNode;
+
+typedef struct {
+    ExprNode nodes[EXPR_MAX_NODES];
+    int      n;
+    int      root;
+    bool     valid;
+} ExprProg;
+
+typedef struct {
+    const char *s;
+    ExprProg   *prog;
+    char       *err;
+    size_t      errlen;
+    bool        failed;
+} ExprParser;
+
+static void expr_fail(ExprParser *p, const char *msg)
+{
+    if (!p->failed && p->err)
+        snprintf(p->err, p->errlen, "%s near '%.12s'", msg, *p->s ? p->s : "end");
+    p->failed = true;
+}
+
+static int expr_node(ExprParser *p, int op, float val, int a, int b)
+{
+    if (p->failed) return -1;
+    if (p->prog->n >= EXPR_MAX_NODES) { expr_fail(p, "expression too long"); return -1; }
+    ExprNode *nd = &p->prog->nodes[p->prog->n];
+    nd->op = (uint8_t)op; nd->val = val;
+    nd->a = (int16_t)a; nd->b = (int16_t)b; nd->c = -1;
+    return p->prog->n++;
+}
+
+static int expr_node3(ExprParser *p, int op, int a, int b, int c)
+{
+    int idx = expr_node(p, op, 0, a, b);
+    if (idx >= 0) p->prog->nodes[idx].c = (int16_t)c;
+    return idx;
+}
+
+static int expr_parse_ternary(ExprParser *p);
+
+static int expr_parse_factor(ExprParser *p)
+{
+    if (p->failed) return -1;
+    const char *s = p->s;
+
+    if (*s == '-') { p->s = s + 1; int c = expr_parse_factor(p); return expr_node(p, EN_NEG, 0, c, -1); }
+    if (*s == '(') {
+        p->s = s + 1;
+        int c = expr_parse_ternary(p);
+        if (*p->s != ')') { expr_fail(p, "expected ')'"); return -1; }
+        p->s++;
+        return c;
+    }
+    if ((*s >= '0' && *s <= '9') || *s == '.') {
+        char *end;
+        float v = strtof(s, &end);
+        p->s = end;
+        return expr_node(p, EN_CONST, v, -1, -1);
+    }
+    /* functions */
+    if (strncmp(s, "sin", 3) == 0 || strncmp(s, "cos", 3) == 0 ||
+        strncmp(s, "abs", 3) == 0 || strncmp(s, "sqrt", 4) == 0 ||
+        strncmp(s, "floor", 5) == 0) {
+        int op; int len;
+        if      (strncmp(s, "floor", 5) == 0) { op = EN_FLOOR; len = 5; }
+        else if (strncmp(s, "sqrt",  4) == 0) { op = EN_SQRT;  len = 4; }
+        else if (strncmp(s, "sin",   3) == 0) { op = EN_SIN;   len = 3; }
+        else if (strncmp(s, "cos",   3) == 0) { op = EN_COS;   len = 3; }
+        else                                   { op = EN_ABS;   len = 3; }
+        s += len;
+        if (*s != '(') { p->s = s; expr_fail(p, "expected '(' after function"); return -1; }
+        p->s = s + 1;
+        int c = expr_parse_ternary(p);
+        if (*p->s != ')') { expr_fail(p, "expected ')'"); return -1; }
+        p->s++;
+        return expr_node(p, op, 0, c, -1);
+    }
+    switch (*s) {
+    case 'x': p->s = s + 1; return expr_node(p, EN_X, 0, -1, -1);
+    case 'y': p->s = s + 1; return expr_node(p, EN_Y, 0, -1, -1);
+    case 'w': p->s = s + 1; return expr_node(p, EN_W, 0, -1, -1);
+    case 'h': p->s = s + 1; return expr_node(p, EN_H, 0, -1, -1);
+    case 't': p->s = s + 1; return expr_node(p, EN_T, 0, -1, -1);
+    case 'r': p->s = s + 1; return expr_node(p, EN_R, 0, -1, -1);
+    case 'a': p->s = s + 1; return expr_node(p, EN_A, 0, -1, -1);
+    }
+    expr_fail(p, "unexpected character");
+    return -1;
+}
+
+static int expr_parse_term(ExprParser *p)
+{
+    int lhs = expr_parse_factor(p);
+    while (!p->failed && (*p->s == '*' || *p->s == '/' || *p->s == '%')) {
+        char op = *p->s;
+        p->s++;
+        int rhs = expr_parse_factor(p);
+        int en = (op == '*') ? EN_MUL : (op == '/') ? EN_DIV : EN_MOD;
+        lhs = expr_node(p, en, 0, lhs, rhs);
+    }
+    return lhs;
+}
+
+static int expr_parse_sum(ExprParser *p)
+{
+    int lhs = expr_parse_term(p);
+    while (!p->failed && (*p->s == '+' || *p->s == '-')) {
+        char op = *p->s;
+        p->s++;
+        int rhs = expr_parse_term(p);
+        lhs = expr_node(p, op == '+' ? EN_ADD : EN_SUB, 0, lhs, rhs);
+    }
+    return lhs;
+}
+
+/* comparisons: return 1.0 or 0.0. One comparison per level (no
+ * chaining like a<b<c — parenthesize if you need to combine). */
+static int expr_parse_cmp(ExprParser *p)
+{
+    int lhs = expr_parse_sum(p);
+    if (p->failed) return lhs;
+    int op = -1, adv = 0;
+    if      (p->s[0] == '>' && p->s[1] == '=') { op = EN_GE; adv = 2; }
+    else if (p->s[0] == '<' && p->s[1] == '=') { op = EN_LE; adv = 2; }
+    else if (p->s[0] == '=' && p->s[1] == '=') { op = EN_EQ; adv = 2; }
+    else if (p->s[0] == '!' && p->s[1] == '=') { op = EN_NE; adv = 2; }
+    else if (p->s[0] == '>')                   { op = EN_GT; adv = 1; }
+    else if (p->s[0] == '<')                   { op = EN_LT; adv = 1; }
+    if (op < 0) return lhs;
+    p->s += adv;
+    int rhs = expr_parse_sum(p);
+    return expr_node(p, op, 0, lhs, rhs);
+}
+
+/* ternary: cond ? then : else  (right-associative, lowest precedence) */
+static int expr_parse_ternary(ExprParser *p)
+{
+    int cond = expr_parse_cmp(p);
+    if (p->failed || *p->s != '?') return cond;
+    p->s++;
+    int then_e = expr_parse_ternary(p);
+    if (*p->s != ':') { expr_fail(p, "expected ':' in ?:"); return -1; }
+    p->s++;
+    int else_e = expr_parse_ternary(p);
+    return expr_node3(p, EN_TERN, cond, then_e, else_e);
+}
+
+typedef struct { float x, y, w, h, t, r, a; } ExprVars;
+
+static float expr_eval(const ExprProg *pr, int node, const ExprVars *v)
+{
+    const ExprNode *n = &pr->nodes[node];
+    switch (n->op) {
+    case EN_CONST: return n->val;
+    case EN_X: return v->x;
+    case EN_Y: return v->y;
+    case EN_W: return v->w;
+    case EN_H: return v->h;
+    case EN_T: return v->t;
+    case EN_R: return v->r;
+    case EN_A: return v->a;
+    case EN_ADD: return expr_eval(pr, n->a, v) + expr_eval(pr, n->b, v);
+    case EN_SUB: return expr_eval(pr, n->a, v) - expr_eval(pr, n->b, v);
+    case EN_MUL: return expr_eval(pr, n->a, v) * expr_eval(pr, n->b, v);
+    case EN_DIV: {
+        float d = expr_eval(pr, n->b, v);
+        return d != 0.0f ? expr_eval(pr, n->a, v) / d : 0.0f;
+    }
+    case EN_MOD: {
+        float d = expr_eval(pr, n->b, v);
+        return d != 0.0f ? fmodf(expr_eval(pr, n->a, v), d) : 0.0f;
+    }
+    case EN_NEG:   return -expr_eval(pr, n->a, v);
+    case EN_SIN:   return sinf(expr_eval(pr, n->a, v));
+    case EN_COS:   return cosf(expr_eval(pr, n->a, v));
+    case EN_ABS:   return fabsf(expr_eval(pr, n->a, v));
+    case EN_FLOOR: return floorf(expr_eval(pr, n->a, v));
+    case EN_SQRT: {
+        float s = expr_eval(pr, n->a, v);
+        return s > 0.0f ? sqrtf(s) : 0.0f;
+    }
+    case EN_GT: return expr_eval(pr, n->a, v) >  expr_eval(pr, n->b, v) ? 1.0f : 0.0f;
+    case EN_LT: return expr_eval(pr, n->a, v) <  expr_eval(pr, n->b, v) ? 1.0f : 0.0f;
+    case EN_GE: return expr_eval(pr, n->a, v) >= expr_eval(pr, n->b, v) ? 1.0f : 0.0f;
+    case EN_LE: return expr_eval(pr, n->a, v) <= expr_eval(pr, n->b, v) ? 1.0f : 0.0f;
+    case EN_EQ: return expr_eval(pr, n->a, v) == expr_eval(pr, n->b, v) ? 1.0f : 0.0f;
+    case EN_NE: return expr_eval(pr, n->a, v) != expr_eval(pr, n->b, v) ? 1.0f : 0.0f;
+    case EN_TERN:
+        return expr_eval(pr, n->a, v) != 0.0f
+             ? expr_eval(pr, n->b, v)
+             : expr_eval(pr, n->c, v);
+    }
+    return 0.0f;
+}
+
+static bool expr_compile(ExprProg *prog, const char *src,
+                         char *err, size_t errlen)
+{
+    ExprParser p = { src, prog, err, errlen, false };
+    prog->n = 0;
+    prog->valid = false;
+    prog->root = expr_parse_ternary(&p);
+    if (!p.failed && *p.s != '\0')
+        expr_fail(&p, "trailing characters");
+    if (p.failed || prog->root < 0) return false;
+    prog->valid = true;
+    return true;
+}
+
+/* Global mathwarp program (one instance; protected by its own lock
+ * because IPC compiles while the render thread evaluates). */
+static ExprProg g_mw_dx, g_mw_dy;
+static pthread_mutex_t g_mw_lock = PTHREAD_MUTEX_INITIALIZER;
+
+bool mathwarp_set_expr(const char *dx_expr, const char *dy_expr,
+                       char *err, size_t errlen)
+{
+    ExprProg dx, dy;
+    if (!expr_compile(&dx, dx_expr, err, errlen)) return false;
+    if (!expr_compile(&dy, dy_expr, err, errlen)) return false;
+    pthread_mutex_lock(&g_mw_lock);
+    g_mw_dx = dx;
+    g_mw_dy = dy;
+    pthread_mutex_unlock(&g_mw_lock);
+    return true;
+}
+
+/* ─── fx_mathwarp ──
+ * Displaces each pixel by (dx, dy) computed from the user's
+ * expressions. Evaluated every 4th pixel, bilinearly upsampled.
+ *   amp (param): global multiplier on the displacement.
+ * Set expressions live:  vcam-ctl filter expr <dx> <dy>
+ */
+static void fx_mathwarp(Frame *f, float amp)
+{
+    pthread_mutex_lock(&g_mw_lock);
+    if (!g_mw_dx.valid) {
+        /* Sensible default so 'filter add mathwarp' shows something */
+        char e[64];
+        expr_compile(&g_mw_dx, "sin(y/20+t*2)*12", e, sizeof e);
+        expr_compile(&g_mw_dy, "cos(x/20+t*2)*12", e, sizeof e);
+    }
+    ExprProg dx_prog = g_mw_dx;
+    ExprProg dy_prog = g_mw_dy;
+    pthread_mutex_unlock(&g_mw_lock);
+    if (!dx_prog.valid || !dy_prog.valid) return;
+
+    int w = f->width, h = f->height;
+    int GW = w / 4 + 2, GH = h / 4 + 2;
+
+    float *grid = malloc((size_t)GW * GH * 2 * sizeof(float));
+    uint8_t *src = malloc((size_t)w * h * 3);
+    if (!grid || !src) { free(grid); free(src); return; }
+    memcpy(src, f->data, (size_t)w * h * 3);
+
+    ExprVars v;
+    v.w = (float)w;
+    v.h = (float)h;
+    v.t = (float)anim_tick() / 30.0f;
+    float cx = w / 2.0f, cy = h / 2.0f;
+
+    for (int gy = 0; gy < GH; gy++) {
+        v.y = (float)(gy * 4);
+        for (int gx = 0; gx < GW; gx++) {
+            v.x = (float)(gx * 4);
+            float ddx = v.x - cx, ddy = v.y - cy;
+            v.r = sqrtf(ddx*ddx + ddy*ddy);
+            v.a = atan2f(ddy, ddx);
+            int gi = (gy * GW + gx) * 2;
+            grid[gi]     = expr_eval(&dx_prog, dx_prog.root, &v) * amp;
+            grid[gi + 1] = expr_eval(&dy_prog, dy_prog.root, &v) * amp;
+        }
+    }
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        int gy = y / 4;
+        float fy = (float)(y & 3) / 4.0f;
+        for (int x = 0; x < w; x++) {
+            int gx = x / 4;
+            float fx = (float)(x & 3) / 4.0f;
+            int g00 = (gy * GW + gx) * 2;
+            int g10 = g00 + 2;
+            int g01 = g00 + GW * 2;
+            int g11 = g01 + 2;
+            float ddx = grid[g00]   * (1-fx)*(1-fy) + grid[g10]   * fx*(1-fy)
+                      + grid[g01]   * (1-fx)*fy     + grid[g11]   * fx*fy;
+            float ddy = grid[g00+1] * (1-fx)*(1-fy) + grid[g10+1] * fx*(1-fy)
+                      + grid[g01+1] * (1-fx)*fy     + grid[g11+1] * fx*fy;
+            int sx = x + (int)ddx;
+            int sy = y + (int)ddy;
+            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 *sp = src + sy * w * 3 + sx * 3;
+            int o = x * 3;
+            dst[o] = sp[0]; dst[o+1] = sp[1]; dst[o+2] = sp[2];
+        }
+    }
+    free(grid);
+    free(src);
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * Batch 5: demoscene & particles
+ * ────────────────────────────────────────────────────────────── */
+
+/* ─── fx_plasma ──
+ * The classic demoscene plasma — layered animated sines mapped
+ * through a sin-RGB palette, blended over the video.
+ *   blend (p1): mix amount 0..1
+ *   speed (p2): animation rate (0 → 1)
+ *   scale (p3): pattern size in px (0 → 60)
+ * Computed on a 1/4 grid + upsampled, so it's nearly free.
+ */
+static void fx_plasma(Frame *f, float blend, float speed, float scale)
+{
+    if (blend < 0.0f) blend = 0.0f;
+    if (blend > 0.9f) blend = 0.9f;
+    if (speed <= 0.0f) speed = 1.0f;
+    if (scale <= 1.0f) scale = 60.0f;
+
+    int w = f->width, h = f->height;
+    int GW = w / 4 + 2, GH = h / 4 + 2;
+    uint8_t *grid = malloc((size_t)GW * GH * 3);
+    if (!grid) return;
+
+    float t = (float)anim_tick() / 30.0f * speed;
+    float inv = 1.0f / scale;
+    float cx = w / 2.0f, cy = h / 2.0f;
+
+    for (int gy = 0; gy < GH; gy++) {
+        float y = (float)(gy * 4);
+        for (int gx = 0; gx < GW; gx++) {
+            float x = (float)(gx * 4);
+            float dx = x - cx, dy = y - cy;
+            float v = sinf(x * inv + t)
+                    + sinf(y * inv * 1.3f - t * 1.2f)
+                    + sinf((x + y) * inv * 0.7f + t * 0.7f)
+                    + sinf(sqrtf(dx*dx + dy*dy) * inv + t * 1.5f);
+            uint8_t *g = grid + (gy * GW + gx) * 3;
+            g[0] = (uint8_t)((sinf(v * 1.57f)          * 0.5f + 0.5f) * 255.0f);
+            g[1] = (uint8_t)((sinf(v * 1.57f + 2.094f) * 0.5f + 0.5f) * 255.0f);
+            g[2] = (uint8_t)((sinf(v * 1.57f + 4.189f) * 0.5f + 0.5f) * 255.0f);
+        }
+    }
+
+    float keep = 1.0f - blend;
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        int gy = y / 4;
+        for (int x = 0; x < w; x++) {
+            const uint8_t *g = grid + (gy * GW + x / 4) * 3;
+            int o = x * 3;
+            dst[o]   = (uint8_t)(dst[o]   * keep + g[0] * blend);
+            dst[o+1] = (uint8_t)(dst[o+1] * keep + g[1] * blend);
+            dst[o+2] = (uint8_t)(dst[o+2] * keep + g[2] * blend);
+        }
+    }
+    free(grid);
+}
+
+/* ─── fx_contour ──
+ * Topographic map of your face: luma is quantized into N bands, and
+ * the borders between bands are drawn as glowing iso-lines whose hue
+ * follows the elevation. Everything else fades toward dark.
+ *   levels (p1): number of elevation bands, 3..24 (default 8)
+ *   dim    (p2): how much of the original survives, 0..1 (0 → 0.25)
+ */
+static void fx_contour(Frame *f, float levels_f, float dim)
+{
+    int levels = (int)levels_f;
+    if (levels < 3)  levels = 3;
+    if (levels > 24) levels = 24;
+    if (dim <= 0.0f) dim = 0.25f;
+    if (dim > 1.0f)  dim = 1.0f;
+
+    int w = f->width, h = f->height;
+    uint8_t *q = malloc((size_t)w * h);
+    if (!q) return;
+    int step = 256 / levels;
+    for (int y = 0; y < h; y++) {
+        const uint8_t *p = f->data + y * f->stride;
+        for (int x = 0; x < w; x++, p += 3)
+            q[y*w + x] = (uint8_t)(((p[0]*114 + p[1]*587 + p[2]*299) / 1000) / step);
+    }
+
+    unsigned long t = anim_tick();
+    float hue_t = (float)(t % 6283) * 0.0005f;
+
+    for (int y = 0; y < h - 1; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        for (int x = 0; x < w - 1; x++) {
+            int o = x * 3;
+            uint8_t here = q[y*w + x];
+            if (here != q[y*w + x + 1] || here != q[(y+1)*w + x]) {
+                /* iso-line: hue by elevation + slow drift */
+                float ha = (float)here * 0.7f + hue_t;
+                dst[o]   = clamp_u8(dst[o]/3   + (int)((sinf(ha+4.189f)*0.5f+0.5f)*255));
+                dst[o+1] = clamp_u8(dst[o+1]/3 + (int)((sinf(ha+2.094f)*0.5f+0.5f)*255));
+                dst[o+2] = clamp_u8(dst[o+2]/3 + (int)((sinf(ha)       *0.5f+0.5f)*255));
+            } else {
+                dst[o]   = (uint8_t)(dst[o]   * dim);
+                dst[o+1] = (uint8_t)(dst[o+1] * dim);
+                dst[o+2] = (uint8_t)(dst[o+2] * dim);
+            }
+        }
+    }
+    free(q);
+}
+
+/* ─── fx_fireworks — INTERACTIVE ──
+ * Your motion strikes sparks: movement spawns bursts of glowing
+ * particles that fly out, arc under gravity, and fade. Snap your
+ * fingers in front of the camera and watch it detonate.
+ *   sensitivity (p1): 0..1 — how easily motion sparks
+ *   burst       (p2): particles per burst multiplier (0 → 1)
+ */
+#define FW_MAX_PARTICLES 640
+
+typedef struct {
+    float x, y, vx, vy;
+    int   life;           /* frames remaining; 0 = dead */
+    uint8_t cb, cg, cr;
+} FwParticle;
+
+static void fx_fireworks(Frame *f, float sensitivity, float burst_mult)
+{
+    static FwParticle ps[FW_MAX_PARTICLES];
+    static uint8_t *prev_luma = NULL;
+    static int gw = 0, gh = 0, fw2 = 0, fh2 = 0;
+
+    if (sensitivity < 0.05f) sensitivity = 0.05f;
+    if (sensitivity > 1.0f)  sensitivity = 1.0f;
+    if (burst_mult <= 0.0f) burst_mult = 1.0f;
+    if (burst_mult > 3.0f)  burst_mult = 3.0f;
+
+    int w = f->width, h = f->height;
+    int GW = w / 8, GH = h / 8;
+    if (GW < 8 || GH < 8) return;
+
+    if (fw2 != w || fh2 != h) {
+        free(prev_luma);
+        prev_luma = calloc((size_t)GW * GH, 1);
+        if (!prev_luma) { fw2 = fh2 = 0; return; }
+        gw = GW; gh = GH; fw2 = w; fh2 = h;
+        memset(ps, 0, sizeof ps);
+    }
+
+    /* 1. Motion detection on an 8px grid; strong changes spawn bursts */
+    int thresh = 30 + (int)((1.0f - sensitivity) * 60.0f);
+    int spawn_budget = 3;   /* max bursts per frame — keeps it tasteful */
+    for (int gy = 1; gy < gh - 1 && spawn_budget > 0; gy++) {
+        for (int gx = 1; gx < gw - 1 && spawn_budget > 0; gx++) {
+            const uint8_t *p = f->data + (gy*8) * f->stride + (gx*8) * 3;
+            uint8_t l = (uint8_t)((p[0]*114 + p[1]*587 + p[2]*299) / 1000);
+            int gi = gy * gw + gx;
+            int d = abs((int)l - (int)prev_luma[gi]);
+            prev_luma[gi] = l;
+            if (d > thresh && (rand() % 6) == 0) {
+                spawn_budget--;
+                /* burst! */
+                int n = (int)((10 + rand() % 10) * burst_mult);
+                float hue = (float)(rand() % 628) * 0.01f;
+                uint8_t cb = (uint8_t)((sinf(hue+4.189f)*0.5f+0.5f)*255);
+                uint8_t cg = (uint8_t)((sinf(hue+2.094f)*0.5f+0.5f)*255);
+                uint8_t cr = (uint8_t)((sinf(hue)       *0.5f+0.5f)*255);
+                for (int k = 0; k < n; k++) {
+                    /* find a dead slot */
+                    for (int s = 0; s < FW_MAX_PARTICLES; s++) {
+                        if (ps[s].life > 0) continue;
+                        float ang = (float)(rand() % 628) * 0.01f;
+                        float spd = 1.5f + (float)(rand() % 100) * 0.05f;
+                        ps[s].x = (float)(gx * 8);
+                        ps[s].y = (float)(gy * 8);
+                        ps[s].vx = cosf(ang) * spd;
+                        ps[s].vy = sinf(ang) * spd - 1.0f;  /* slight up-kick */
+                        ps[s].life = 20 + rand() % 25;
+                        ps[s].cb = cb; ps[s].cg = cg; ps[s].cr = cr;
+                        break;
+                    }
+                }
+            }
+        }
+    }
+
+    /* 2. Update + render particles (additive 2×2 with fading tail) */
+    for (int s = 0; s < FW_MAX_PARTICLES; s++) {
+        if (ps[s].life <= 0) continue;
+        ps[s].life--;
+        ps[s].x += ps[s].vx;
+        ps[s].y += ps[s].vy;
+        ps[s].vy += 0.18f;              /* gravity */
+        ps[s].vx *= 0.985f;             /* drag */
+
+        int px = (int)ps[s].x, py = (int)ps[s].y;
+        if (px < 1 || px >= w - 2 || py < 1 || py >= h - 2) {
+            ps[s].life = 0;
+            continue;
+        }
+        float fade = (float)ps[s].life / 45.0f;
+        if (fade > 1.0f) fade = 1.0f;
+        int ab = (int)(ps[s].cb * fade);
+        int ag = (int)(ps[s].cg * fade);
+        int ar = (int)(ps[s].cr * fade);
+        for (int dy = 0; dy < 2; dy++) {
+            uint8_t *dst = f->data + (py + dy) * f->stride + px * 3;
+            for (int dx = 0; dx < 2; dx++) {
+                dst[0] = clamp_u8(dst[0] + ab);
+                dst[1] = clamp_u8(dst[1] + ag);
+                dst[2] = clamp_u8(dst[2] + ar);
+                dst += 3;
+            }
+        }
+    }
+}
+
+/* ─── fx_infinity ──
+ * Recursive picture-in-picture (droste-style): a scaled copy of the
+ * PREVIOUS output frame is drawn into the center — which itself
+ * contained a smaller copy, which contained a smaller copy… turtles
+ * all the way down, one cheap blit per frame.
+ *   scale (p1): size of the inner copy, 0.2..0.85 (default 0.55)
+ *   rot   (p2): degrees the inner world rotates per level (default 0)
+ */
+static void fx_infinity(Frame *f, float scale, float rot_deg)
+{
+    static uint8_t *prev = NULL;
+    static int pw = 0, ph = 0, ps = 0;
+
+    if (scale < 0.2f)  scale = 0.55f;
+    if (scale > 0.85f) scale = 0.85f;
+
+    int w = f->width, h = f->height;
+    int size = f->stride * h;
+
+    if (pw != w || ph != h || ps != f->stride) {
+        free(prev);
+        prev = malloc((size_t)size);
+        if (!prev) { pw = ph = ps = 0; return; }
+        memcpy(prev, f->data, (size_t)size);
+        pw = w; ph = h; ps = f->stride;
+    }
+
+    /* Inner rect, centered */
+    int iw = (int)(w * scale), ih = (int)(h * scale);
+    int x0 = (w - iw) / 2,     y0 = (h - ih) / 2;
+
+    float ang = rot_deg * 3.14159265f / 180.0f;
+    float ca = cosf(-ang), sa = sinf(-ang);
+    float cx = w / 2.0f, cy = h / 2.0f;
+    float inv = 1.0f / scale;
+
+    for (int y = 0; y < ih; y++) {
+        uint8_t *dst = f->data + (y0 + y) * f->stride + x0 * 3;
+        for (int x = 0; x < iw; x++) {
+            /* map inner-rect pixel back to full prev frame,
+             * with optional rotation about the center */
+            float fx0 = (float)(x0 + x) - cx;
+            float fy0 = (float)(y0 + y) - cy;
+            float rx = fx0 * ca - fy0 * sa;
+            float ry = fx0 * sa + fy0 * ca;
+            int sx = (int)(cx + rx * inv);
+            int sy = (int)(cy + ry * inv);
+            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 *sp = prev + sy * f->stride + sx * 3;
+            dst[0] = sp[0]; dst[1] = sp[1]; dst[2] = sp[2];
+            dst += 3;
+        }
+    }
+    /* Thin frame border around the inner world for legibility */
+    for (int x = x0; x < x0 + iw; x++) {
+        uint8_t *a = f->data + y0 * f->stride + x * 3;
+        uint8_t *b = f->data + (y0 + ih - 1) * f->stride + x * 3;
+        a[0] = a[1] = a[2] = 230;
+        b[0] = b[1] = b[2] = 230;
+    }
+    for (int y = y0; y < y0 + ih; y++) {
+        uint8_t *a = f->data + y * f->stride + x0 * 3;
+        uint8_t *b = f->data + y * f->stride + (x0 + iw - 1) * 3;
+        a[0] = a[1] = a[2] = 230;
+        b[0] = b[1] = b[2] = 230;
+    }
+
+    memcpy(prev, f->data, (size_t)size);
+}
+
+/* ─── fx_moire ──
+ * Two ring systems — one centered, one orbiting — multiply into
+ * living interference patterns over the image. Deeply hypnotic.
+ *   spacing (p1): ring spacing in px, 4..40 (default 12)
+ *   speed   (p2): orbit + phase animation rate (0 → 1)
+ */
+static void fx_moire(Frame *f, float spacing, float speed)
+{
+    if (spacing < 4.0f)  spacing = 12.0f;
+    if (spacing > 40.0f) spacing = 40.0f;
+    if (speed <= 0.0f) speed = 1.0f;
+
+    int w = f->width, h = f->height;
+    float t = (float)anim_tick() / 30.0f * speed;
+    float k = 6.28318f / spacing;
+
+    float cx1 = w / 2.0f, cy1 = h / 2.0f;
+    /* second center orbits the first */
+    float orb = (float)(w < h ? w : h) * 0.18f;
+    float cx2 = cx1 + cosf(t * 0.7f) * orb;
+    float cy2 = cy1 + sinf(t * 0.9f) * orb;
+
+    /* Coarse grid + upsample (two sqrts per grid point only) */
+    int GW = w / 2 + 1, GH = h / 2 + 1;
+    int8_t *grid = malloc((size_t)GW * GH);
+    if (!grid) return;
+    for (int gy = 0; gy < GH; gy++) {
+        float y = (float)(gy * 2);
+        for (int gx = 0; gx < GW; gx++) {
+            float x = (float)(gx * 2);
+            float d1 = sqrtf((x-cx1)*(x-cx1) + (y-cy1)*(y-cy1));
+            float d2 = sqrtf((x-cx2)*(x-cx2) + (y-cy2)*(y-cy2));
+            float m = sinf(d1 * k + t * 2.0f) * sinf(d2 * k);
+            grid[gy * GW + gx] = (int8_t)(m * 100.0f);  /* -100..100 */
+        }
+    }
+
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        const int8_t *grow = grid + (y / 2) * GW;
+        for (int x = 0; x < w; x++) {
+            int m = grow[x / 2];   /* -100..100 */
+            int o = x * 3;
+            /* multiply brightness by 0.55..1.45; extremes tint */
+            dst[o]   = clamp_u8(dst[o]   + (dst[o]   * m) / 220 + (m > 60 ? 30 : 0));
+            dst[o+1] = clamp_u8(dst[o+1] + (dst[o+1] * m) / 220);
+            dst[o+2] = clamp_u8(dst[o+2] + (dst[o+2] * m) / 220 + (m < -60 ? 30 : 0));
+        }
+    }
+    free(grid);
+}
+
+/* ──────────────────────────────────────────────────────────────
+ * Batch 6: text, tone & tracking
+ * ────────────────────────────────────────────────────────────── */
+
+/* ─── fx_ascii ──
+ * Real ASCII-art: the frame becomes a grid of characters chosen by
+ * brightness from the classic density ramp " .:-=+*#%@", rendered
+ * from an embedded 8×8 bitmap font.
+ *   cell (p1): 8 or 16 px (16 = chunkier, glyphs pixel-doubled)
+ *   mode (p2): 0 = green terminal, 1 = source-colored, 2 = white
+ */
+static const uint8_t ascii_font[10][8] = {
+    /* ' ' */ {0,0,0,0,0,0,0,0},
+    /* '.' */ {0,0,0,0,0,0x18,0x18,0},
+    /* ':' */ {0,0x18,0x18,0,0,0x18,0x18,0},
+    /* '-' */ {0,0,0,0x7E,0,0,0,0},
+    /* '=' */ {0,0,0x7E,0,0x7E,0,0,0},
+    /* '+' */ {0,0x18,0x18,0x7E,0x7E,0x18,0x18,0},
+    /* '*' */ {0,0x66,0x3C,0xFF,0x3C,0x66,0,0},
+    /* '#' */ {0x24,0x24,0x7E,0x24,0x7E,0x24,0x24,0},
+    /* '%' */ {0x62,0x64,0x08,0x10,0x26,0x46,0,0},
+    /* '@' */ {0x3C,0x42,0x5A,0x5A,0x5C,0x40,0x3C,0},
+};
+
+static void fx_ascii(Frame *f, float cell_f, float mode_f)
+{
+    int scale = ((int)cell_f >= 16) ? 2 : 1;   /* 8 or 16 px cells */
+    int cell = 8 * scale;
+    int mode = (int)mode_f;
+    if (mode < 0) mode = 0;
+    if (mode > 2) mode = 2;
+
+    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 cy = 0; cy + cell <= h; cy += cell) {
+        for (int cx = 0; cx + cell <= w; cx += cell) {
+            /* cell average color + luma */
+            long sb = 0, sg = 0, sr = 0;
+            for (int y = 0; y < cell; y += scale) {
+                const uint8_t *p = tmp + (cy+y) * w * 3 + cx * 3;
+                for (int x = 0; x < cell; x += scale, p += 3 * scale) {
+                    sb += p[0]; sg += p[1]; sr += p[2];
+                }
+            }
+            int npx = (cell/scale) * (cell/scale);
+            int ab = (int)(sb/npx), ag = (int)(sg/npx), ar = (int)(sr/npx);
+            int luma = (ab*114 + ag*587 + ar*299) / 1000;
+            int gi = (luma * 10) / 256;          /* glyph index 0..9 */
+            if (gi > 9) gi = 9;
+
+            int fb, fg2, fr;                     /* foreground color */
+            switch (mode) {
+            case 1:  fb = ab*3/2; fg2 = ag*3/2; fr = ar*3/2; break;
+            case 2:  fb = fg2 = fr = 235; break;
+            default: fb = 40; fg2 = 220; fr = 60; break;
+            }
+            if (fb > 255) fb = 255;
+            if (fg2 > 255) fg2 = 255;
+            if (fr > 255) fr = 255;
+
+            for (int y = 0; y < cell; y++) {
+                uint8_t *dst = f->data + (cy+y) * f->stride + cx * 3;
+                uint8_t bits = ascii_font[gi][y / scale];
+                for (int x = 0; x < cell; x++) {
+                    int on = bits & (0x80 >> (x / scale));
+                    if (on) {
+                        dst[0] = (uint8_t)fb;
+                        dst[1] = (uint8_t)fg2;
+                        dst[2] = (uint8_t)fr;
+                    } else {
+                        dst[0] = 8; dst[1] = 10; dst[2] = 8;
+                    }
+                    dst += 3;
+                }
+            }
+        }
+    }
+    free(tmp);
+}
+
+/* ─── fx_duotone ──
+ * Maps luma onto a gradient between two hues — the classic music-
+ * poster look (shadows one color, highlights another).
+ *   hueA (p1): shadow hue in degrees, 0..360 (default 220 = blue)
+ *   hueB (p2): highlight hue in degrees (0 → 30 = orange)
+ *   mix  (p3): blend with the original, 0..1 (0 → 1 = full duotone)
+ */
+static void fx_duotone(Frame *f, float hueA, float hueB, float mix)
+{
+    if (hueB <= 0.0f) hueB = 30.0f;
+    if (mix <= 0.0f || mix > 1.0f) mix = 1.0f;
+    float a = hueA * 3.14159265f / 180.0f;
+    float b = hueB * 3.14159265f / 180.0f;
+
+    /* Endpoint colors from hue via sin palette, darkened / lightened */
+    float Ab = (sinf(a+4.189f)*0.5f+0.5f) * 90.0f;
+    float Ag = (sinf(a+2.094f)*0.5f+0.5f) * 90.0f;
+    float Ar = (sinf(a)       *0.5f+0.5f) * 90.0f;
+    float Bb = 120.0f + (sinf(b+4.189f)*0.5f+0.5f) * 135.0f;
+    float Bg = 120.0f + (sinf(b+2.094f)*0.5f+0.5f) * 135.0f;
+    float Br = 120.0f + (sinf(b)       *0.5f+0.5f) * 135.0f;
+
+    float keep = 1.0f - mix;
+    int n = f->width * f->height;
+    uint8_t *p = f->data;
+    for (int i = 0; i < n; i++, p += 3) {
+        float l = (float)(p[0]*114 + p[1]*587 + p[2]*299) / 255000.0f; /* 0..1 */
+        int db = (int)((Ab + (Bb - Ab) * l) * mix + p[0] * keep);
+        int dg = (int)((Ag + (Bg - Ag) * l) * mix + p[1] * keep);
+        int dr = (int)((Ar + (Br - Ar) * l) * mix + p[2] * keep);
+        p[0] = clamp_u8(db);
+        p[1] = clamp_u8(dg);
+        p[2] = clamp_u8(dr);
+    }
+}
+
+/* ─── fx_sketch ──
+ * Pencil sketch via the classic color-dodge trick: grayscale, invert,
+ * blur the inversion, then dodge-blend — lines survive, flats go
+ * paper-white.
+ *   detail   (p1): blur radius 1..4 — smaller = finer pencil (def 2)
+ *   darkness (p2): 0..1 line darkness boost (0 → 0.5)
+ */
+static void fx_sketch(Frame *f, float detail, float darkness)
+{
+    int radius = (int)detail;
+    if (radius < 1) radius = 1;
+    if (radius > 4) radius = 4;
+    if (darkness <= 0.0f) darkness = 0.5f;
+    if (darkness > 1.0f) darkness = 1.0f;
+
+    int w = f->width, h = f->height;
+    uint8_t *g  = malloc((size_t)w * h);    /* grayscale */
+    uint8_t *bi = malloc((size_t)w * h);    /* blurred inverse */
+    if (!g || !bi) { free(g); free(bi); return; }
+
+    for (int y = 0; y < h; y++) {
+        const uint8_t *p = f->data + y * f->stride;
+        for (int x = 0; x < w; x++, p += 3)
+            g[y*w + x] = (uint8_t)((p[0]*114 + p[1]*587 + p[2]*299) / 1000);
+    }
+    /* box blur of the inverse */
+    for (int y = 0; y < h; y++) {
+        for (int x = 0; x < w; x++) {
+            int sum = 0, cnt = 0;
+            for (int dy = -radius; dy <= radius; dy++) {
+                int yy = y + dy;
+                if (yy < 0 || yy >= h) continue;
+                for (int dx = -radius; dx <= radius; dx++) {
+                    int xx = x + dx;
+                    if (xx < 0 || xx >= w) continue;
+                    sum += 255 - g[yy*w + xx];
+                    cnt++;
+                }
+            }
+            bi[y*w + x] = (uint8_t)(sum / cnt);
+        }
+    }
+    /* color dodge: result = g / (1 - bi) */
+    float dk = 1.0f - darkness * 0.35f;
+    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 base = g[y*w + x];
+            int blur = bi[y*w + x];
+            int v = (blur >= 255) ? 255 : (base * 255) / (255 - blur);
+            if (v > 255) v = 255;
+            v = (int)(v * dk + 255 * (1.0f - dk) * ((float)v / 255.0f));
+            p[0] = p[1] = p[2] = (uint8_t)v;
+        }
+    }
+    free(g);
+    free(bi);
+}
+
+/* ─── fx_spotlight — INTERACTIVE ──
+ * A theatrical spotlight that FOLLOWS YOUR MOTION. The motion
+ * centroid is tracked on a coarse grid and the light glides toward
+ * it; everything outside the beam falls into darkness. Walk across
+ * the frame and the light chases you.
+ *   radius (p1): beam radius in px (default 180)
+ *   dark   (p2): outside darkness 0..1 (0 → 0.85; 1 = pitch black)
+ *   speed  (p3): follow smoothing 0.02..0.5 (0 → 0.12)
+ */
+static void fx_spotlight(Frame *f, float radius, float dark, float speed)
+{
+    static uint8_t *prev_luma = NULL;
+    static int gw = 0, gh = 0, fw3 = 0, fh3 = 0;
+    static float sx = -1.0f, sy = -1.0f;   /* smoothed spotlight center */
+
+    if (radius < 40.0f) radius = 180.0f;
+    if (dark <= 0.0f) dark = 0.85f;
+    if (dark > 1.0f) dark = 1.0f;
+    if (speed <= 0.0f) speed = 0.12f;
+    if (speed > 0.5f) speed = 0.5f;
+
+    int w = f->width, h = f->height;
+    int GW = w / 8, GH = h / 8;
+    if (GW < 8 || GH < 8) return;
+
+    if (fw3 != w || fh3 != h) {
+        free(prev_luma);
+        prev_luma = calloc((size_t)GW * GH, 1);
+        if (!prev_luma) { fw3 = fh3 = 0; return; }
+        gw = GW; gh = GH; fw3 = w; fh3 = h;
+        sx = w / 2.0f; sy = h / 2.0f;
+    }
+
+    /* Motion centroid on the coarse grid */
+    long mx = 0, my = 0, mtot = 0;
+    for (int gy = 1; gy < gh - 1; gy++) {
+        for (int gx = 1; gx < gw - 1; gx++) {
+            const uint8_t *p = f->data + (gy*8) * f->stride + (gx*8) * 3;
+            uint8_t l = (uint8_t)((p[0]*114 + p[1]*587 + p[2]*299) / 1000);
+            int gi = gy * gw + gx;
+            int d = abs((int)l - (int)prev_luma[gi]);
+            prev_luma[gi] = l;
+            if (d > 18) {
+                mx += (long)gx * 8 * d;
+                my += (long)gy * 8 * d;
+                mtot += d;
+            }
+        }
+    }
+    if (mtot > 200) {   /* enough motion to retarget */
+        float tx = (float)mx / (float)mtot;
+        float ty = (float)my / (float)mtot;
+        sx += (tx - sx) * speed;
+        sy += (ty - sy) * speed;
+    }
+
+    /* Render: smooth radial falloff, slight boost inside the beam */
+    float r2 = radius * radius;
+    float fall = radius * 0.5f;              /* soft edge width */
+    float fall2 = (radius + fall) * (radius + fall);
+    for (int y = 0; y < h; y++) {
+        uint8_t *dst = f->data + y * f->stride;
+        float dy = (float)y - sy;
+        for (int x = 0; x < w; x++) {
+            float dx = (float)x - sx;
+            float d2 = dx*dx + dy*dy;
+            float lum;
+            if (d2 <= r2)        lum = 1.12f;                 /* in beam */
+            else if (d2 >= fall2) lum = 1.0f - dark;          /* outside */
+            else {
+                float tt = (sqrtf(d2) - radius) / fall;       /* 0..1 */
+                lum = 1.12f + tt * ((1.0f - dark) - 1.12f);
+            }
+            int o = x * 3;
+            dst[o]   = clamp_u8((int)(dst[o]   * lum));
+            dst[o+1] = clamp_u8((int)(dst[o+1] * lum));
+            dst[o+2] = clamp_u8((int)(dst[o+2] * lum));
+        }
+    }
+}
+
 void filter_chain_apply(FilterChain *fc, Frame *frame)
 {
     pthread_mutex_lock(&fc->lock);
@@ -1575,28 +4186,33 @@ void filter_chain_apply(FilterChain *fc, Frame *frame)
         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_VIGNETTE:     fx_vignette(frame, f->param, f->param2, f->param3); 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, f->param); break;
         case FX_SATURATE:     fx_saturate(frame, f->param); 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_CHROMASHIFT:  fx_chromashift(frame, (int)f->param,
+                                             (int)f->param2, (int)f->param3); break;
+        case FX_GLITCH:       fx_glitch(frame, f->param,
+                                        (int)f->param2, f->param3); break;
+        case FX_KALEIDOSCOPE: fx_kaleidoscope(frame, (int)f->param,
+                                              f->param2, f->param3,
+                                              f->param4); break;
+        case FX_SWIRL:        fx_swirl(frame, f->param, f->param2, f->param3); 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_WAVE:         fx_wave(frame, f->param, f->param2,
+                                      f->param3, (int)f->param4); break;
+        case FX_CARTOON:      fx_cartoon(frame, f->param, f->param2); break;
         case FX_SOLARIZE:     fx_solarize(frame, (int)f->param); break;
         case FX_RAINBOW:      fx_rainbow(frame, f->param); break;
         case FX_CRT:          fx_crt(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_PINCH:        fx_pinch(frame, f->param, f->param2, f->param3); break;
+        case FX_BULGE:        fx_bulge(frame, f->param, f->param2, f->param3); break;
         case FX_PAINTERLY:    fx_painterly(frame, (int)f->param); break;
         case FX_VELVET:       fx_velvet(frame, f->param); break;
         case FX_MODERN:       fx_modern(frame, f->param); break;
@@ -1617,6 +4233,44 @@ void filter_chain_apply(FilterChain *fc, Frame *frame)
         case FX_DISPLACE:     fx_displace(frame, f->param); break;
         case FX_RIPPLE:       fx_ripple(frame, f->param); break;
         case FX_SCANLINES:    fx_scanlines(frame, f->param); break;
+        /* glitch art */
+        case FX_SHUFFLE:      fx_shuffle(frame, f->param, f->param2, f->param3); break;
+        case FX_PIXELSORT:    fx_pixelsort(frame, f->param); break;
+        case FX_RGB_DELAY:    fx_rgb_delay(frame, f->param); break;
+        case FX_DRIFT:        fx_drift(frame, f->param, f->param2); break;
+        case FX_RAIN:         fx_rain(frame, f->param, f->param2, f->param3); break;
+        /* temporal */
+        case FX_ECHO:         fx_echo(frame, f->param); break;
+        case FX_SLITSCAN:     fx_slitscan(frame, f->param, f->param2); break;
+        case FX_MOSH:         fx_mosh(frame, f->param, f->param2); break;
+        case FX_STUTTER:      fx_stutter(frame, f->param); break;
+        case FX_HALFTONE:     fx_halftone(frame, f->param); break;
+        case FX_NEON:         fx_neon(frame, f->param, f->param2,
+                                      f->param3, f->param4); break;
+        /* retro & warp */
+        case FX_EMBOSS:       fx_emboss(frame, f->param); break;
+        case FX_DITHER:       fx_dither(frame, f->param); break;
+        case FX_TILES:        fx_tiles(frame, f->param); break;
+        case FX_ZOOMPULSE:    fx_zoompulse(frame, f->param, f->param2); break;
+        case FX_OILSLICK:     fx_oilslick(frame, f->param, f->param2); break;
+        /* interactive & extravagant */
+        case FX_FEEDBACK:     fx_feedback(frame, f->param, f->param2, f->param3); break;
+        case FX_RIPPLES:      fx_ripples(frame, f->param, f->param2, f->param3); break;
+        case FX_LIGHTPAINT:   fx_lightpaint(frame, f->param, f->param2, f->param3); break;
+        case FX_HOLOGRAM:     fx_hologram(frame, f->param, f->param2, f->param3); break;
+        case FX_LIFE:         fx_life(frame, f->param, f->param2, f->param3); break;
+        case FX_MATHWARP:     fx_mathwarp(frame, f->param); break;
+        /* demoscene & particles */
+        case FX_PLASMA:       fx_plasma(frame, f->param, f->param2, f->param3); break;
+        case FX_CONTOUR:      fx_contour(frame, f->param, f->param2); break;
+        case FX_FIREWORKS:    fx_fireworks(frame, f->param, f->param2); break;
+        case FX_INFINITY:     fx_infinity(frame, f->param, f->param2); break;
+        case FX_MOIRE:        fx_moire(frame, f->param, f->param2); break;
+        /* text, tone & tracking */
+        case FX_ASCII:        fx_ascii(frame, f->param, f->param2); break;
+        case FX_DUOTONE:      fx_duotone(frame, f->param, f->param2, f->param3); break;
+        case FX_SKETCH:       fx_sketch(frame, f->param, f->param2); break;
+        case FX_SPOTLIGHT:    fx_spotlight(frame, f->param, f->param2, f->param3); break;
         default: break;
         }
     }
diff --git a/src/ipc.c b/src/ipc.c
index 9f80f7b..647e9b4 100644
--- a/src/ipc.c
+++ b/src/ipc.c
@@ -27,6 +27,8 @@
 #include <sys/un.h>
 #include <sys/stat.h>
 #include <fcntl.h>
+#include <signal.h>
+#include <pthread.h>
 
 /* ── helpers ─────────────────────────────────── */
 static void send_line(int fd, const char *msg)
@@ -49,6 +51,7 @@ static int read_line(int fd, char *buf, int maxlen)
     while (i < maxlen - 1) {
         char c;
         ssize_t n = read(fd, &c, 1);
+        if (n < 0 && errno == EINTR) continue;   /* signal — retry */
         if (n <= 0) return -1;
         if (c == '\n') break;
         if (c != '\r') buf[i++] = c;
@@ -116,6 +119,10 @@ static void parse_size_and_path(char **save_ptr,
 
 /* ── command handler ─────────────────────────── */
 extern FilterChain g_filters;  /* defined in main.c */
+extern Recorder   *g_recorder; /* defined in main.c, may be NULL pre-init */
+extern int         g_output_w;
+extern int         g_output_h;
+extern int         g_output_fps;
 
 static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
 {
@@ -137,13 +144,17 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
         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 list                    show active filters + all params");
+            send_line(client_fd, "OK   filter add <name> <p> [<p2> [<p3> [<p4>]]]");
+            send_line(client_fd, "OK                                    append a filter with up to 4 params");
+            send_line(client_fd, "OK   filter set <index> <param>       update the primary param");
+            send_line(client_fd, "OK   filter set <index> p2|p3|p4 <v>  update a specific extra param");
             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 filters marked (*) accept extra params — see the notes below each.");
+            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");
@@ -152,7 +163,7 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
             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   vignette <strength> [<r> <warmth>](*) darken edges 0..1 (def 0.6); r=inner radius; warmth 0..1 = brown tint");
             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");
@@ -160,14 +171,14 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
             send_line(client_fd, "OK   saturate <factor>              chroma boost, 0=gray, 1=normal, 0..3, default 1.5");
             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   chromashift <dx> [<dxb> <dy_r>](*) RGB split; dx=R shift (B=-dx unless dxb given); dy_r=R vertical shift");
+            send_line(client_fd, "OK   glitch <intensity> [<slice_h> <shift_pct>](*) animated slice shift; slice_h in px, shift_pct=max shift as %-of-width");
+            send_line(client_fd, "OK   kaleidoscope <segments> [<rot> <spin> <zoom>](*) radial mirror; spin deg/frame; zoom of the wedge");
+            send_line(client_fd, "OK   swirl <strength> [<radius> <spin>](*) radial twist; radius 0.2..1 of frame; spin animates it");
             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   wave <amp> [<freq> <speed> <vert>](*) sinusoidal displacement; freq=waves/screen, speed=px/frame, vert=1 for vertical");
+            send_line(client_fd, "OK   cartoon <edge_thresh> [<levels>](*) posterize + dark edges; levels 2..12 (def 5)");
             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   crt <strength>                 CRT scanlines + barrel + RGB fringe, 0..1, default 0.7");
@@ -176,8 +187,8 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
             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   pinch <strength> [<cx> <cy>](*) radial inward pull; cx/cy = center 0..1 (off-center = gravity well)");
+            send_line(client_fd, "OK   bulge <strength> [<cx> <cy>](*) fisheye push; cx/cy = center 0..1");
             send_line(client_fd, "OK   painterly <radius>             oil-painting effect, 1..5, default 3");
             send_line(client_fd, "OK   velvet <strength>              soft desat + warm tint + blur, 0..1, default 0.6");
             send_line(client_fd, "OK");
@@ -204,6 +215,52 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
             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");
             send_line(client_fd, "OK   scanlines <gap>                black scanline every N rows, 2..16, default 3");
+            send_line(client_fd, "OK");
+            send_line(client_fd, "OK glitch art / generative:");
+            send_line(client_fd, "OK   shuffle <intensity> [<size> <phase_s>](*) shuffle/unshuffle blocks; size 16..96 px; phase seconds 0.3..5");
+            send_line(client_fd, "OK   pixelsort <density>            glitch-art row sort by luminance, 0..1, default 0.3");
+            send_line(client_fd, "OK   rgbdelay <strength>            chromatic lag — G & R from past frames, 0..1, default 0.7");
+            send_line(client_fd, "OK   drift <band_h> [<max_shift>](*) scanline drift; max shift 5..120 px");
+            send_line(client_fd, "OK   rain <density> [<speed> <trail>](*) Matrix rain; speed mult 0.3..3; trail length 8..80 px");
+            send_line(client_fd, "OK");
+            send_line(client_fd, "OK temporal / time-bending:");
+            send_line(client_fd, "OK   echo <persistence>             motion trails (ghosting), 0..0.97, default 0.6");
+            send_line(client_fd, "OK   slitscan <depth> [<dir>](*)    rows sample older frames; dir 1 = time flows upward");
+            send_line(client_fd, "OK   mosh <sensitivity> [<keyint>](*) datamosh; keyint = frames between resyncs 30..600 (def 90)");
+            send_line(client_fd, "OK   stutter <period>               freeze each frame for N frames, 2..30, default 6");
+            send_line(client_fd, "OK   halftone <cell>                newspaper dot grid, cell 4..32 px, default 8");
+            send_line(client_fd, "OK   neon <strength> [<thresh> <huespd> <glow>](*) glowing rainbow edges + real bloom; thresh 10..120");
+            send_line(client_fd, "OK");
+            send_line(client_fd, "OK retro & warp:");
+            send_line(client_fd, "OK   emboss <strength>              carved gray relief, 0.1..2, default 1");
+            send_line(client_fd, "OK   dither <levels>                ordered Bayer dither, levels/channel 2..8, default 2 (retro 8-color)");
+            send_line(client_fd, "OK   tiles <n>                      n x n mirror-tile wallpaper grid, 2..8, default 3");
+            send_line(client_fd, "OK   zoompulse <strength> [<rate>](*) breathing zoom; rate = oscillation speed");
+            send_line(client_fd, "OK   oilslick <strength> [<speed>](*) iridescent hue swirl; speed = drift rate");
+            send_line(client_fd, "OK");
+            send_line(client_fd, "OK interactive & extravagant:");
+            send_line(client_fd, "OK   feedback <decay> [<zoom> <rot>](*) infinite video-feedback tunnel; zoom/frame (def 1.04), deg/frame (def 1.5)");
+            send_line(client_fd, "OK   ripples <sens> [<rain> <refract>](*) INTERACTIVE water sim; rain=drops/sec ambient, refract 0..8");
+            send_line(client_fd, "OK   lightpaint <fade> [<thresh> <huespd>](*) INTERACTIVE painting; thresh 10..120; hue cycle rate");
+            send_line(client_fd, "OK   hologram <strength> [<gap> <glitch>](*) sci-fi projection; scanline gap 2..8; glitch rate 0..1");
+            send_line(client_fd, "OK   life <density> [<color> <speed>](*) Conway's Life on your edges; color 1=age-rainbow; speed=frames/gen");
+            send_line(client_fd, "OK   mathwarp <amp>                 warp by YOUR math — set with: filter expr <dx> <dy>");
+            send_line(client_fd, "OK                                    vars x y w h t r a; fns sin cos abs sqrt floor");
+            send_line(client_fd, "OK                                    ops + - * / % ; cmp > < >= <= == != ; ternary c?a:b");
+            send_line(client_fd, "OK                                    e.g. filter expr (x-w/2)*(sin(t*5)>0?0.08:0) 0");
+            send_line(client_fd, "OK");
+            send_line(client_fd, "OK demoscene & particles:");
+            send_line(client_fd, "OK   plasma <blend> [<speed> <scale>](*) classic demoscene plasma over the video, blend 0..0.9");
+            send_line(client_fd, "OK   contour <levels> [<dim>](*)    glowing topographic iso-lines of your luma, 3..24 bands");
+            send_line(client_fd, "OK   fireworks <sens> [<burst>](*)  INTERACTIVE: motion detonates particle bursts w/ gravity");
+            send_line(client_fd, "OK   infinity <scale> [<rot>](*)    recursive picture-in-picture (droste), scale 0.2..0.85");
+            send_line(client_fd, "OK   moire <spacing> [<speed>](*)   two orbiting ring systems interfere over the image");
+            send_line(client_fd, "OK");
+            send_line(client_fd, "OK text, tone & tracking:");
+            send_line(client_fd, "OK   ascii <cell> [<mode>](*)       REAL ASCII-art from an 8x8 font; cell 8|16; mode 0=green 1=color 2=white");
+            send_line(client_fd, "OK   duotone <hueA> [<hueB> <mix>](*) two-color gradient map; hues in degrees (def 220/30 = teal-orange)");
+            send_line(client_fd, "OK   sketch <detail> [<darkness>](*) pencil sketch via dodge blend; detail 1..4");
+            send_line(client_fd, "OK   spotlight <radius> [<dark> <speed>](*) INTERACTIVE: the light FOLLOWS your motion");
             return;
         }
 
@@ -215,8 +272,10 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
                 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);
+                    snprintf(buf, sizeof buf,
+                        "OK %d: %s param=%.2f p2=%.2f p3=%.2f p4=%.2f",
+                        i, filter_type_to_name(f->type),
+                        f->param, f->param2, f->param3, f->param4);
                     send_line(client_fd, buf);
                 }
             }
@@ -238,16 +297,33 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
                 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) {
+            /* Parse 0–4 numeric params. Missing ones default: primary
+             * → filter_default_param(t); the rest → 0. */
+            float params[FILTER_MAX_PARAMS] = {
+                filter_default_param(t), 0.0f, 0.0f, 0.0f
+            };
+            int n_parsed = 0;
+            for (int p = 0; p < FILTER_MAX_PARAMS; p++) {
+                char *pstr = strtok_r(NULL, " \t", &save);
+                if (!pstr) break;
                 char *ep; float v = strtof(pstr, &ep);
-                if (*ep == '\0') param = v;
+                if (*ep != '\0') {
+                    char b[128];
+                    snprintf(b, sizeof b, "ERR filter add: '%s' isn't a number", pstr);
+                    send_line(client_fd, b);
+                    return;
+                }
+                params[p] = v;
+                n_parsed++;
             }
-            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);
+            if (n_parsed == 0) n_parsed = 1;  /* use the default */
+
+            if (filter_chain_add_multi(&g_filters, t, params, n_parsed)) {
+                char b[192];
+                snprintf(b, sizeof b,
+                    "OK added filter '%s' param=%.2f p2=%.2f p3=%.2f p4=%.2f",
+                    filter_type_to_name(t),
+                    params[0], params[1], params[2], params[3]);
                 send_line(client_fd, b);
             } else {
                 send_line(client_fd, "ERR filter chain full");
@@ -255,14 +331,49 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
             return;
         }
 
+        if (strcmp(sub, "expr") == 0) {
+            /* filter expr <dx-expression> <dy-expression>
+             * NO SPACES within an expression. Vars: x y w h t r a.
+             * Fns: sin cos abs sqrt. Applies to the mathwarp filter. */
+            char *dxs = strtok_r(NULL, " \t", &save);
+            char *dys = strtok_r(NULL, " \t", &save);
+            if (!dxs || !dys) {
+                send_line(client_fd, "ERR usage: filter expr <dx> <dy>   (no spaces inside expressions)");
+                send_line(client_fd, "ERR   vars: x y w h t r a   fns: sin cos abs sqrt floor");
+                send_line(client_fd, "ERR   ops: + - * / % ( )  comparisons > < >= <= == !=  ternary c?a:b");
+                send_line(client_fd, "ERR   example: filter expr (x-w/2)*(sin(t*5)>0?0.08:0) (y-h/2)*(sin(t*5)>0?0.08:0)");
+                return;
+            }
+            char err[128] = "";
+            if (!mathwarp_set_expr(dxs, dys, err, sizeof err)) {
+                char b[192];
+                snprintf(b, sizeof b, "ERR expression: %s", err);
+                send_line(client_fd, b);
+                return;
+            }
+            send_line(client_fd, "OK mathwarp expressions updated (add the 'mathwarp' filter to see them)");
+            return;
+        }
+
         if (strcmp(sub, "set") == 0) {
+            /* Usage:
+             *   filter set <index> <param>              → primary
+             *   filter set <index> p2|p3|p4 <param>     → specific extra
+             */
             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>'");
+            char *first = strtok_r(NULL, " \t", &save);
+            if (!istr || !first) {
+                send_line(client_fd, "ERR filter set: usage 'filter set <index> [p2|p3|p4] <param>'");
                 return;
             }
             int idx = atoi(istr);
+            int which = 1;
+            char *pstr = first;
+            if (!strcmp(first, "p2") || !strcmp(first, "p3") || !strcmp(first, "p4")) {
+                which = first[1] - '0';
+                pstr = strtok_r(NULL, " \t", &save);
+                if (!pstr) { send_line(client_fd, "ERR filter set: missing value"); return; }
+            }
             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);
@@ -271,7 +382,12 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
                 send_line(client_fd, "ERR filter set: index out of range");
                 return;
             }
-            g_filters.filters[idx].param = v;
+            switch (which) {
+            case 1: g_filters.filters[idx].param  = v; break;
+            case 2: g_filters.filters[idx].param2 = v; break;
+            case 3: g_filters.filters[idx].param3 = v; break;
+            case 4: g_filters.filters[idx].param4 = v; break;
+            }
             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);
@@ -576,6 +692,110 @@ static void handle_command(int client_fd, char *line, OverlayRegistry *reg)
         return;
     }
 
+    /* ── record start [file=<path>] [mic=<dev>] [crf=N] [preset=<p>] [vcodec=<v>]
+     *    record stop
+     *    record status
+     *    record info
+     *
+     * Spawns ffmpeg as a child of vcam and pipes our composed BGR24
+     * frames into it. This avoids all v4l2loopback contention because
+     * we don't read /dev/video0 at all on the recording side.
+     */
+    if (strcmp(cmd, "record") == 0) {
+        char *sub = strtok_r(NULL, " \t", &save);
+        if (!sub) { send_line(client_fd, "ERR usage: record start|stop|status|info"); return; }
+
+        if (strcmp(sub, "status") == 0) {
+            if (recorder_active(g_recorder))
+                send_line(client_fd, "OK recording");
+            else
+                send_line(client_fd, "OK stopped");
+            return;
+        }
+
+        if (strcmp(sub, "info") == 0) {
+            if (!recorder_active(g_recorder)) {
+                send_line(client_fd, "OK stopped");
+                return;
+            }
+            char buf[256];
+            snprintf(buf, sizeof buf,
+                     "OK recording pid=%d file=%s",
+                     (int)recorder_pid(g_recorder),
+                     recorder_file(g_recorder));
+            send_line(client_fd, buf);
+            return;
+        }
+
+        if (strcmp(sub, "stop") == 0) {
+            if (!recorder_active(g_recorder)) {
+                send_line(client_fd, "OK already stopped");
+                return;
+            }
+            recorder_stop(g_recorder);
+            send_line(client_fd, "OK stopped");
+            return;
+        }
+
+        if (strcmp(sub, "start") == 0) {
+            if (!g_recorder) {
+                send_line(client_fd, "ERR recorder not initialised");
+                return;
+            }
+            if (recorder_active(g_recorder)) {
+                send_line(client_fd, "ERR already recording");
+                return;
+            }
+
+            /* Parse key=value tokens for file=, mic=, crf=, preset=, vcodec=, aoffset= */
+            char file[512] = {0};
+            char mic[128]  = {0};
+            char vcodec[64] = "libx264";
+            char vpreset[32] = "ultrafast";
+            int  crf = 23;
+            float aoffset = 0.2f;   /* default: shift audio 0.2s later to
+                                     * match the video path's buffering
+                                     * latency; tune with aoffset= */
+            char *tok;
+            while ((tok = strtok_r(NULL, " \t", &save))) {
+                if      (strncmp(tok, "file=",   5) == 0)
+                    strncpy(file, tok + 5, sizeof file - 1);
+                else if (strncmp(tok, "mic=",    4) == 0)
+                    strncpy(mic, tok + 4, sizeof mic - 1);
+                else if (strncmp(tok, "crf=",    4) == 0)
+                    crf = atoi(tok + 4);
+                else if (strncmp(tok, "vcodec=", 7) == 0)
+                    strncpy(vcodec, tok + 7, sizeof vcodec - 1);
+                else if (strncmp(tok, "preset=", 7) == 0)
+                    strncpy(vpreset, tok + 7, sizeof vpreset - 1);
+                else if (strncmp(tok, "aoffset=", 8) == 0)
+                    aoffset = strtof(tok + 8, NULL);
+            }
+            if (!file[0]) {
+                send_line(client_fd, "ERR record start: file= argument required");
+                return;
+            }
+
+            if (!recorder_start(g_recorder, file,
+                                mic[0] ? mic : NULL,
+                                g_output_w, g_output_h, g_output_fps,
+                                crf, vcodec, vpreset, aoffset)) {
+                send_line(client_fd, "ERR ffmpeg failed to start (see /tmp/vcam-record.log)");
+                return;
+            }
+
+            char buf[256];
+            snprintf(buf, sizeof buf,
+                     "OK recording pid=%d file=%s",
+                     (int)recorder_pid(g_recorder), file);
+            send_line(client_fd, buf);
+            return;
+        }
+
+        send_line(client_fd, "ERR record: unknown subcommand (use start|stop|status|info)");
+        return;
+    }
+
     /* ── add <type> <id> <x> <y> [<w>] [<h>] <file|geometry> ── */
     if (strcmp(cmd, "add") == 0) {
         char *type = strtok_r(NULL, " \t", &save);
@@ -645,11 +865,27 @@ static void *ipc_thread(void *arg)
 {
     IPCServer *srv = arg;
 
+    /* Block SIGCHLD in this thread. When ffmpeg (the recorder child)
+     * exits, SIGCHLD fires on whichever thread the kernel picks; if
+     * that's the IPC thread mid-accept(), accept() returns EINTR.
+     * We now retry on EINTR (see below), but blocking the signal here
+     * means the main thread handles it and the IPC thread stays
+     * quietly in accept(). Belt and braces. */
+    sigset_t block;
+    sigemptyset(&block);
+    sigaddset(&block, SIGCHLD);
+    sigaddset(&block, SIGPIPE);
+    pthread_sigmask(SIG_BLOCK, &block, NULL);
+
     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) {
+            /* Signals (SIGCHLD when a child ffmpeg exits, etc.) can
+             * interrupt accept(). Don't kill the server thread just
+             * because a child died — retry. */
+            if (errno == EINTR) continue;
             if (srv->running) perror("[ipc] accept");
             break;
         }
diff --git a/src/main.c b/src/main.c
index 932d3e7..68fcf6c 100644
--- a/src/main.c
+++ b/src/main.c
@@ -44,6 +44,8 @@ static IPCServer        g_ipc;
 FilterChain             g_filters; /* extern'd by ipc.c */
 int                     g_output_w = 0; /* extern'd by overlay.c */
 int                     g_output_h = 0;
+int                     g_output_fps = 30; /* extern'd by ipc.c (record) */
+Recorder               *g_recorder = NULL; /* extern'd by ipc.c */
 
 static void on_signal(int sig)
 {
@@ -241,6 +243,10 @@ int main(int argc, char *argv[])
     }
     g_output_w = width;
     g_output_h = height;
+    g_output_fps = fps;
+
+    /* Recorder: idle until 'record start' IPC fires it up. */
+    g_recorder = recorder_new();
 
     /* ── start IPC server ── */
     if (!ipc_start(&g_ipc, &g_registry)) {
@@ -314,6 +320,14 @@ int main(int argc, char *argv[])
 
         output_write(out, frame);
 
+        /* Mirror the composed frame to the recorder, if active.
+         * This is BGR24 — same format we asked ffmpeg to expect
+         * via -f rawvideo -pixel_format bgr24. */
+        if (recorder_active(g_recorder)) {
+            recorder_write_frame(g_recorder, frame->data,
+                                 (size_t)frame->stride * frame->height);
+        }
+
         /* Frame pacing */
         struct timespec t1;
         clock_gettime(CLOCK_MONOTONIC, &t1);
@@ -329,6 +343,8 @@ int main(int argc, char *argv[])
     fprintf(stderr, "\n[main] Shutting down.\n");
 
     ipc_stop(&g_ipc);
+    recorder_free(g_recorder);   /* stops + finalises any active recording */
+    g_recorder = NULL;
     frame_free(frame);
     frame_free(cam_buf);
     output_close(out);
diff --git a/src/record.c b/src/record.c
new file mode 100644
index 0000000..9fecb2f
--- /dev/null
+++ b/src/record.c
@@ -0,0 +1,726 @@
+/*
+ * src/record.c — vcam's recording subsystem.
+ *
+ * Spawns ffmpeg as a child process and feeds it BGR24 frames via a
+ * pipe. ffmpeg encodes (x264 + AAC) to the output file the user
+ * specified. Avoids /dev/video0 contention entirely.
+ *
+ * Threading model:
+ *   - The main loop calls recorder_write_frame() every iteration.
+ *   - The IPC thread calls recorder_start() and recorder_stop()
+ *     in response to "record" commands.
+ *   - SIGCHLD handler reaps the ffmpeg child after it exits.
+ *
+ * Synchronisation: an internal mutex protects state transitions
+ * (start/stop). The mutex is held only briefly — never during
+ * write() or waitpid() — so it doesn't block the main loop or
+ * delay IPC responses.
+ *
+ * Stop is non-blocking: we close ffmpeg's stdin (it sees EOF and
+ * cleanly finalises the file) but do NOT waitpid. SIGCHLD reaps
+ * the child in the background. This is critical: ffmpeg can take
+ * several seconds to write the MP4 trailer, and blocking the main
+ * loop on that would freeze the webcam stream for the duration.
+ */
+
+#define _GNU_SOURCE  /* for F_SETPIPE_SZ */
+#include "vcam.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <sys/wait.h>
+#include <strings.h>      /* strcasecmp */
+#include <stdint.h>       /* intptr_t */
+#include <pthread.h>
+#include <sys/stat.h>     /* mkfifo */
+
+/* Per-recording context owned by the paced writer thread. The writer
+ * duplicates/skips frames to feed ffmpeg at EXACTLY the target fps,
+ * which makes plain -framerate timestamps true and reduces A/V sync
+ * to a small constant (camera latency). */
+typedef struct RecCtx {
+    struct Recorder *r;
+    uint64_t gen;          /* recording generation this ctx belongs to */
+    int      fd;           /* video pipe write end (blocking) — owned  */
+    int      fps;
+    size_t   size;         /* one frame in bytes */
+    uint8_t *latest;       /* most recent submitted frame (r->lock)    */
+    uint8_t *scratch;      /* writer's private copy for the write()    */
+    int      have_frame;   /* has anything been submitted yet?         */
+    int      missed;       /* ticks where ffmpeg couldn't keep up      */
+} RecCtx;
+
+struct Recorder {
+    pthread_mutex_t lock;
+    uint64_t gen;       /* bumped every start; stale threads detect it */
+    pid_t pid;          /* ffmpeg */
+    pid_t arec_pid;     /* arecord audio-capture child, or -1 */
+    RecCtx *ctx;        /* live writer context, or NULL */
+    int   fifo_fd;      /* our O_RDWR handle on the audio FIFO, or -1 */
+    char  fifo_path[64];
+    bool  active;
+    char  file[512];
+    int   frame_w, frame_h;
+};
+
+Recorder *recorder_new(void)
+{
+    Recorder *r = calloc(1, sizeof *r);
+    if (!r) return NULL;
+    pthread_mutex_init(&r->lock, NULL);
+    r->pid = -1;
+    r->arec_pid = -1;
+    r->ctx = NULL;
+    r->fifo_fd = -1;
+    return r;
+}
+
+void recorder_free(Recorder *r)
+{
+    if (!r) return;
+    recorder_stop(r);
+    pthread_mutex_destroy(&r->lock);
+    free(r);
+}
+
+bool recorder_active(const Recorder *r) { return r && r->active; }
+pid_t recorder_pid(const Recorder *r)   { return r ? r->pid : -1; }
+const char *recorder_file(const Recorder *r) { return r ? r->file : ""; }
+
+/* Build the argv array for ffmpeg.
+ * audio_fifo: path to a WAV FIFO being fed by arecord (preferred for
+ *             ALSA mics — see recorder_start); NULL if not used.
+ * mic:        original mic string; used directly only for "pulse..."
+ *             sources or as a direct-ALSA fallback when the FIFO
+ *             couldn't be set up. */
+static char **build_argv(const char *file, const char *mic,
+                         const char *audio_fifo, float aoffset,
+                         int w, int h, int fps,
+                         int crf, const char *vcodec, const char *vpreset)
+{
+    /* Slot budget: base(5) + video input(14) + audio input(≤10)
+     * + encode(8) + ts flags(4) + cfr(4) + audio encode(8)
+     * + movflags(2) + interleave(2) + file+NULL(2) = 59 used today.
+     * 96 leaves generous headroom — a silent overflow here previously
+     * CORRUPTED THE HEAP and randomly produced an empty output
+     * filename ("Unable to choose an output format for ''"). */
+    char **argv = calloc(96, sizeof *argv);
+    if (!argv) return NULL;
+
+    int i = 0;
+    char buf[64];
+
+    argv[i++] = strdup("ffmpeg");
+    argv[i++] = strdup("-y");
+    argv[i++] = strdup("-hide_banner");
+    argv[i++] = strdup("-loglevel"); argv[i++] = strdup("warning");
+
+    /* ── video input: raw BGR24 from our pipe ──
+     * SHARED-CLOCK SYNC DESIGN: both this input and the audio input
+     * are stamped with -use_wallclock_as_timestamps — the REAL moment
+     * each packet arrives, from one common clock. Combined with
+     * -copyts -start_at_zero on the output (see below), ffmpeg
+     * preserves the true relative timing between audio and video no
+     * matter when each stream started or how either momentarily
+     * stalls. This is what "record the sound that plays during this
+     * exact frame" means mechanically.
+     *
+     * The paced writer thread delivers frames at real 30fps, so the
+     * wallclock stamps are smooth; -fps_mode cfr regularizes any
+     * residual jitter by dup/drop WITHOUT moving content in time. */
+    argv[i++] = strdup("-thread_queue_size"); argv[i++] = strdup("1024");
+    argv[i++] = strdup("-use_wallclock_as_timestamps"); argv[i++] = strdup("1");
+    argv[i++] = strdup("-f");          argv[i++] = strdup("rawvideo");
+    argv[i++] = strdup("-pixel_format"); argv[i++] = strdup("bgr24");
+    snprintf(buf, sizeof buf, "%dx%d", w, h);
+    argv[i++] = strdup("-video_size"); argv[i++] = strdup(buf);
+    snprintf(buf, sizeof buf, "%d", fps);
+    argv[i++] = strdup("-framerate");  argv[i++] = strdup(buf);
+    argv[i++] = strdup("-i");          argv[i++] = strdup("pipe:0");
+
+    /* ── audio input ──
+     * Three paths, best first:
+     *
+     * 1. WAV FIFO fed by arecord (audio_fifo set). ffmpeg reads a
+     *    plain pipe — fully interruptible, nothing can wedge in the
+     *    kernel. arecord's large-period blocking capture is exactly
+     *    what flaky drivers (AMD acp DMIC!) tolerate, while ffmpeg's
+     *    own small-period ALSA reads can hang the driver in
+     *    uninterruptible sleep — observed as: SIGINT/SIGTERM ignored,
+     *    SIGKILL required, torn MP4 fragments.
+     *    WAV timestamps come from the sample count — a monotonic
+     *    audio clock. No wallclock stamping here (pipe jitter would
+     *    make wallclock stamps WORSE than the sample clock).
+     *
+     * 2. PulseAudio/PipeWire ("pulse" / "pulse:<source>") for systems
+     *    that have it.
+     *
+     * 3. Direct ALSA — only as a fallback if the FIFO setup failed.
+     */
+    /* Audio inputs also get wallclock stamps — SAME clock as video.
+     * (For the WAV FIFO this overrides the sample-count timestamps
+     * with arrival times; the aresample async filter then absorbs
+     * the small jitter between the ALSA crystal and the wall clock.)
+     * -itsoffset shifts audio slightly later to compensate for the
+     * video path's capture latency (webcam driver + decode) which
+     * happens BEFORE our wallclock stamp. */
+    char offbuf[32];
+    snprintf(offbuf, sizeof offbuf, "%.3f", aoffset);
+
+    if (audio_fifo && *audio_fifo) {
+        argv[i++] = strdup("-thread_queue_size"); argv[i++] = strdup("1024");
+        argv[i++] = strdup("-use_wallclock_as_timestamps"); argv[i++] = strdup("1");
+        if (aoffset != 0.0f) {
+            argv[i++] = strdup("-itsoffset"); argv[i++] = strdup(offbuf);
+        }
+        argv[i++] = strdup("-f");  argv[i++] = strdup("wav");
+        argv[i++] = strdup("-i");  argv[i++] = strdup(audio_fifo);
+    } else if (mic && strncmp(mic, "pulse", 5) == 0) {
+        argv[i++] = strdup("-thread_queue_size"); argv[i++] = strdup("1024");
+        argv[i++] = strdup("-use_wallclock_as_timestamps"); argv[i++] = strdup("1");
+        if (aoffset != 0.0f) {
+            argv[i++] = strdup("-itsoffset"); argv[i++] = strdup(offbuf);
+        }
+        argv[i++] = strdup("-f");  argv[i++] = strdup("pulse");
+        argv[i++] = strdup("-i");
+        argv[i++] = strdup(mic[5] == ':' && mic[6] ? mic + 6 : "default");
+    } else if (mic && *mic) {
+        argv[i++] = strdup("-thread_queue_size"); argv[i++] = strdup("1024");
+        argv[i++] = strdup("-use_wallclock_as_timestamps"); argv[i++] = strdup("1");
+        if (aoffset != 0.0f) {
+            argv[i++] = strdup("-itsoffset"); argv[i++] = strdup(offbuf);
+        }
+        argv[i++] = strdup("-f");  argv[i++] = strdup("alsa");
+        argv[i++] = strdup("-i");  argv[i++] = strdup(mic);
+    }
+
+    bool have_audio = (audio_fifo && *audio_fifo) || (mic && *mic);
+
+    /* ── encoding ── */
+    argv[i++] = strdup("-threads");  argv[i++] = strdup("0");  /* all cores */
+    argv[i++] = strdup("-c:v");      argv[i++] = strdup(vcodec ? vcodec : "libx264");
+    argv[i++] = strdup("-preset");   argv[i++] = strdup(vpreset ? vpreset : "ultrafast");
+    snprintf(buf, sizeof buf, "%d", crf > 0 ? crf : 23);
+    argv[i++] = strdup("-crf");      argv[i++] = strdup(buf);
+    argv[i++] = strdup("-pix_fmt");  argv[i++] = strdup("yuv420p");
+
+    /* ── PRESERVE cross-input alignment ──
+     * Without -copyts, ffmpeg re-zeroes each input INDEPENDENTLY
+     * (subtracting each input's own first timestamp) — which throws
+     * away exactly the relative offset we carefully captured with the
+     * shared wallclock stamps. -copyts keeps timestamps as-is;
+     * -start_at_zero then shifts ALL streams together by one common
+     * amount so the file starts at 0. -avoid_negative_ts make_zero is
+     * a mux-level belt-and-braces that also shifts uniformly. */
+    argv[i++] = strdup("-copyts");
+    argv[i++] = strdup("-start_at_zero");
+    argv[i++] = strdup("-avoid_negative_ts"); argv[i++] = strdup("make_zero");
+
+    /* ── enforce CFR at the requested fps on the OUTPUT ──
+     * Converts the wallclock arrival stamps into a clean constant
+     * frame rate by duplicating/dropping frames — timing stays true
+     * even if the writer or encoder momentarily stalls (a stall
+     * becomes a briefly frozen picture, never a desync). */
+    snprintf(buf, sizeof buf, "%d", fps);
+    argv[i++] = strdup("-r");        argv[i++] = strdup(buf);
+    argv[i++] = strdup("-fps_mode"); argv[i++] = strdup("cfr");
+
+    if (have_audio) {
+        /* Audio timestamp strategy — third iteration, and the one
+         * that handles BOTH failure modes:
+         *
+         *   - FIFO burst jitter (±0.1-0.2s packet wobble): must NOT
+         *     be chased with hard sample trims — that chops audible
+         *     chunks out (aresample's default hard threshold is 0.1s,
+         *     SMALLER than the jitter → constant trimming).
+         *   - Real capture gaps (ALSA overrun when ffmpeg stalls and
+         *     the FIFO backs up): MUST be corrected, or the timeline
+         *     glues shut across the hole and everything afterwards
+         *     plays early — a permanent A/V offset after a crackle.
+         *
+         * aresample=async=1000:min_hard_comp=0.5 does exactly this:
+         * deviations under 0.5s get only gentle soft resampling
+         * (≤ ~2% rate, inaudible), while a genuine ≥0.5s gap is
+         * silence-padded ONCE, restoring sync. */
+        argv[i++] = strdup("-af");
+        argv[i++] = strdup("aresample=async=1000:min_hard_comp=0.5");
+        argv[i++] = strdup("-c:a");  argv[i++] = strdup("aac");
+        argv[i++] = strdup("-b:a");  argv[i++] = strdup("160k");
+        argv[i++] = strdup("-ac");   argv[i++] = strdup("2");
+    }
+
+    /* ── container-specific flags ──
+     * MP4 needs fragmented mode for live recording; otherwise the
+     * moov atom is buffered in memory and only written on clean
+     * close, and an interrupted recording is unplayable. */
+    const char *ext = strrchr(file, '.');
+    if (ext && strcasecmp(ext, ".mp4") == 0) {
+        argv[i++] = strdup("-movflags");
+        argv[i++] = strdup("+frag_keyframe+empty_moov+default_base_moof");
+    }
+
+    /* ── never let audio hold video hostage ──
+     * The muxer interleaves streams by timestamp and BUFFERS video
+     * while waiting for matching audio packets. Default
+     * max_interleave_delta is 10 SECONDS — so if the mic stalls
+     * (AMD acp DMICs are notorious for wedging in the kernel driver;
+     * observed as "ALSA buffer xrun" then silence), every video frame
+     * after the stall sits in RAM and never reaches the disk. A
+     * 7-second recording with audio that died at 1s plays back as a
+     * 1-second file. With 1s max delta, video flushes to disk at most
+     * 1 second behind real time no matter what audio does. */
+    argv[i++] = strdup("-max_interleave_delta");
+    argv[i++] = strdup("1000000");   /* 1s in microseconds */
+
+    argv[i++] = strdup(file);
+    argv[i]   = NULL;
+    return argv;
+}
+
+/* ── paced writer thread ──
+ * Feeds ffmpeg's stdin one frame every 1/fps on a monotonic clock.
+ * If the camera runs slower than fps, the latest frame is duplicated;
+ * if faster, extra frames are skipped (only the newest survives).
+ * Result: the rawvideo stream is EXACTLY constant-rate, which makes
+ * -framerate timestamps true, playback duration equal to wall time,
+ * and A/V sync independent of camera behaviour.
+ *
+ * The thread OWNS ctx and the pipe fd: it closes the fd and frees the
+ * buffers when it exits. recorder_stop never touches them — it only
+ * flips r->active, which the writer notices within one tick. This
+ * removes every close-vs-write race by construction. */
+static void *writer_thread(void *arg)
+{
+    RecCtx *c = arg;
+    Recorder *r = c->r;
+
+    /* Signals are the main thread's job. */
+    sigset_t block;
+    sigemptyset(&block);
+    sigaddset(&block, SIGCHLD);
+    sigaddset(&block, SIGPIPE);
+    pthread_sigmask(SIG_BLOCK, &block, NULL);
+
+    const long period_ns = 1000000000L / (c->fps > 0 ? c->fps : 30);
+    struct timespec next;
+    clock_gettime(CLOCK_MONOTONIC, &next);
+
+    for (;;) {
+        /* Sleep until the next tick (EINTR-safe, absolute deadline
+         * so error never accumulates). */
+        next.tv_nsec += period_ns;
+        while (next.tv_nsec >= 1000000000L) {
+            next.tv_nsec -= 1000000000L;
+            next.tv_sec  += 1;
+        }
+        while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME,
+                               &next, NULL) == EINTR)
+            ;
+
+        /* Still the live recording? Grab the newest frame. */
+        pthread_mutex_lock(&r->lock);
+        bool live = r->active && r->ctx == c && r->gen == c->gen;
+        int have = c->have_frame;
+        if (live && have)
+            memcpy(c->scratch, c->latest, c->size);
+        pthread_mutex_unlock(&r->lock);
+
+        if (!live) break;
+        if (!have) continue;   /* nothing submitted yet — wait a tick */
+
+        /* Blocking write of the whole frame. If ffmpeg briefly
+         * stalls we block here — that's fine, it's our own thread —
+         * and any ticks we miss just mean the newest frame gets
+         * duplicated less / content skips slightly. */
+        size_t written = 0;
+        bool dead = false;
+        while (written < c->size) {
+            ssize_t n = write(c->fd, c->scratch + written, c->size - written);
+            if (n > 0) { written += (size_t)n; continue; }
+            if (n < 0 && errno == EINTR) continue;
+            dead = true;   /* EPIPE etc. — ffmpeg is gone */
+            break;
+        }
+        if (dead) {
+            /* ffmpeg exited unexpectedly. Mark the recording dead and
+             * clean up the audio side so arecord doesn't block forever
+             * writing into a FIFO nobody drains. */
+            pthread_mutex_lock(&r->lock);
+            if (r->active && r->ctx == c && r->gen == c->gen) {
+                r->active = false;
+                fprintf(stderr, "[record] ffmpeg exited mid-recording "
+                                "(file=%s)\n", r->file);
+                if (r->arec_pid > 0) { kill(r->arec_pid, SIGTERM); r->arec_pid = -1; }
+                if (r->fifo_fd >= 0) { close(r->fifo_fd); r->fifo_fd = -1; }
+                if (r->fifo_path[0]) { unlink(r->fifo_path); r->fifo_path[0] = '\0'; }
+            }
+            pthread_mutex_unlock(&r->lock);
+            break;
+        }
+
+        /* If the deadline slipped past a whole period (long stall),
+         * rebase rather than bursting to catch up. */
+        struct timespec now;
+        clock_gettime(CLOCK_MONOTONIC, &now);
+        long behind = (now.tv_sec - next.tv_sec) * 1000000000L
+                    + (now.tv_nsec - next.tv_nsec);
+        if (behind > period_ns) {
+            c->missed += (int)(behind / period_ns);
+            next = now;
+        }
+    }
+
+    /* Thread owns the teardown of its resources. Detach ctx from the
+     * recorder first (under lock) so no submitter can touch it after
+     * we free. */
+    pthread_mutex_lock(&r->lock);
+    if (r->ctx == c) r->ctx = NULL;
+    pthread_mutex_unlock(&r->lock);
+
+    close(c->fd);          /* EOF → ffmpeg's video input ends */
+    free(c->latest);
+    free(c->scratch);
+    if (c->missed > 0)
+        fprintf(stderr, "[record] writer: %d duplicated/missed tick(s)\n",
+                c->missed);
+    free(c);
+    return NULL;
+}
+
+bool recorder_start(Recorder *r,
+                    const char *file, const char *mic,
+                    int w, int h, int fps,
+                    int crf, const char *vcodec, const char *vpreset,
+                    float aoffset)
+{
+    if (!r || !file) return false;
+
+    pthread_mutex_lock(&r->lock);
+    if (r->active) {
+        pthread_mutex_unlock(&r->lock);
+        fprintf(stderr, "[record] already active — stop first\n");
+        return false;
+    }
+    pthread_mutex_unlock(&r->lock);
+
+    /* ── audio setup: arecord → WAV FIFO for ALSA mics ──
+     * Keeps ALSA out of ffmpeg entirely. arecord's large-period
+     * blocking capture works reliably on hardware where ffmpeg's own
+     * ALSA reads wedge the kernel driver (AMD acp DMICs). ffmpeg then
+     * only reads pipes, so SIGINT always works and stops are clean.
+     *
+     * We also keep our own O_RDWR handle on the FIFO. This means
+     * ffmpeg's open() of the FIFO never blocks waiting for a writer —
+     * even if arecord dies instantly, ffmpeg starts up, records
+     * video, and simply gets no audio (the muxer won't stall thanks
+     * to -max_interleave_delta). */
+    char fifo_path[64] = "";
+    int   fifo_fd = -1;
+    pid_t arec    = -1;
+    bool  use_pulse = mic && strncmp(mic, "pulse", 5) == 0;
+
+    if (mic && *mic && !use_pulse) {
+        snprintf(fifo_path, sizeof fifo_path,
+                 "/tmp/vcam-audio-%d.wav", (int)getpid());
+        unlink(fifo_path);
+        if (mkfifo(fifo_path, 0600) < 0) {
+            perror("[record] mkfifo (falling back to direct ALSA)");
+            fifo_path[0] = '\0';
+        } else {
+            fifo_fd = open(fifo_path, O_RDWR);   /* never blocks */
+            /* Grow the FIFO to 1MB ≈ 10 SECONDS of 48kHz mono S16.
+             * The default 64KB is only 0.68s — any ffmpeg stall longer
+             * than that blocked arecord, overran the ALSA ring, and
+             * lost audio at capture (heard as missing chunks; visible
+             * as a low average audio bitrate in the file). With a 10s
+             * cushion, encoder pressure can no longer reach the mic. */
+            if (fifo_fd >= 0)
+                fcntl(fifo_fd, F_SETPIPE_SZ, 1 << 20);
+            arec = fork();
+            if (arec == 0) {
+                /* arecord child: own log, no stdin, closed fds */
+                int log = open("/tmp/vcam-record-audio.log",
+                               O_WRONLY | O_CREAT | O_TRUNC, 0644);
+                if (log >= 0) { dup2(log, 2); close(log); }
+                int devnull = open("/dev/null", O_RDWR);
+                if (devnull >= 0) {
+                    dup2(devnull, 0);
+                    dup2(devnull, 1);
+                    close(devnull);
+                }
+                long mx = sysconf(_SC_OPEN_MAX);
+                if (mx < 0 || mx > 4096) mx = 4096;
+                for (int fd = 3; fd < (int)mx; fd++) close(fd);
+
+                /* Mono 48kHz S16 — the 'plug' layer converts from
+                 * whatever the device natively does. Output side
+                 * upmixes to stereo AAC. */
+                /* -B 1500000: 1.5s ALSA ring buffer — the driver
+                 * side can ride out stalls without overrunning. */
+                execlp("arecord", "arecord", "-q",
+                       "-B", "1500000",
+                       "-D", mic,
+                       "-f", "S16_LE", "-c", "1", "-r", "48000",
+                       "-t", "wav", fifo_path, (char *)NULL);
+                _exit(127);
+            }
+            if (arec < 0) {
+                perror("[record] fork arecord (falling back to direct ALSA)");
+                close(fifo_fd); fifo_fd = -1;
+                unlink(fifo_path);
+                fifo_path[0] = '\0';
+            }
+        }
+    }
+
+    int pipefd[2];
+    if (pipe(pipefd) < 0) {
+        perror("[record] pipe");
+        if (arec > 0) kill(arec, SIGTERM);
+        if (fifo_fd >= 0) close(fifo_fd);
+        if (fifo_path[0]) unlink(fifo_path);
+        return false;
+    }
+
+    pid_t pid = fork();
+    if (pid < 0) {
+        perror("[record] fork");
+        close(pipefd[0]); close(pipefd[1]);
+        if (arec > 0) kill(arec, SIGTERM);
+        if (fifo_fd >= 0) close(fifo_fd);
+        if (fifo_path[0]) unlink(fifo_path);
+        return false;
+    }
+
+    if (pid == 0) {
+        /* Child: pipe → stdin, log → stderr, /dev/null → stdout, exec */
+        if (dup2(pipefd[0], 0) < 0) _exit(127);
+        close(pipefd[0]); close(pipefd[1]);
+
+        int log = open("/tmp/vcam-record.log",
+                       O_WRONLY | O_CREAT | O_TRUNC, 0644);
+        if (log >= 0) { dup2(log, 2); close(log); }
+
+        int devnull = open("/dev/null", O_WRONLY);
+        if (devnull >= 0) { dup2(devnull, 1); close(devnull); }
+
+        /* CRITICAL: close every other inherited fd. vcam has the IPC
+         * client socket, the V4L2 devices, overlay pipes etc. open at
+         * fork time. If ffmpeg inherits the IPC client socket, the
+         * client (vcam-ctl / ncat) never sees the connection close
+         * and hangs until ffmpeg exits — which is exactly the
+         * "record start doesn't return" symptom. */
+        long max_fd = sysconf(_SC_OPEN_MAX);
+        if (max_fd < 0 || max_fd > 4096) max_fd = 4096;
+        for (int fd = 3; fd < (int)max_fd; fd++)
+            close(fd);
+
+        char **argv = build_argv(file, mic,
+                                  fifo_path[0] ? fifo_path : NULL,
+                                  aoffset,
+                                  w, h, fps,
+                                  crf, vcodec, vpreset);
+        if (!argv) _exit(127);
+        execvp("ffmpeg", argv);
+        perror("[record] execvp ffmpeg");
+        _exit(127);
+    }
+
+    /* Parent */
+    close(pipefd[0]);
+    /* Pipe stays BLOCKING — the paced writer thread owns it, and
+     * blocking there is harmless (it's not the main loop). */
+
+    /* Build the writer context. The writer thread owns it (and the
+     * pipe fd) from the moment it starts. */
+    size_t frame_size = (size_t)w * h * 3;
+    RecCtx *ctx = calloc(1, sizeof *ctx);
+    uint8_t *latest  = ctx ? malloc(frame_size) : NULL;
+    uint8_t *scratch = ctx ? malloc(frame_size) : NULL;
+    if (!ctx || !latest || !scratch) {
+        fprintf(stderr, "[record] out of memory for writer buffers\n");
+        free(ctx); free(latest); free(scratch);
+        close(pipefd[1]);
+        kill(pid, SIGKILL);
+        if (arec > 0) kill(arec, SIGTERM);
+        if (fifo_fd >= 0) close(fifo_fd);
+        if (fifo_path[0]) unlink(fifo_path);
+        return false;
+    }
+
+    /* Publish state atomically under the lock, then start the writer.
+     * No blocking anywhere — vcam-ctl record start returns in
+     * milliseconds; if ffmpeg failed to exec, the writer's first
+     * write hits EPIPE and tears the recording down cleanly. */
+    pthread_mutex_lock(&r->lock);
+    r->gen++;
+    ctx->r    = r;
+    ctx->gen  = r->gen;
+    ctx->fd   = pipefd[1];
+    ctx->fps  = fps > 0 ? fps : 30;
+    ctx->size = frame_size;
+    ctx->latest  = latest;
+    ctx->scratch = scratch;
+    ctx->have_frame = 0;
+    ctx->missed = 0;
+    r->ctx = ctx;
+    r->pid = pid;
+    r->arec_pid = arec;
+    r->fifo_fd = fifo_fd;
+    strncpy(r->fifo_path, fifo_path, sizeof r->fifo_path - 1);
+    r->fifo_path[sizeof r->fifo_path - 1] = '\0';
+    r->active = true;
+    r->frame_w = w;
+    r->frame_h = h;
+    strncpy(r->file, file, sizeof r->file - 1);
+    r->file[sizeof r->file - 1] = '\0';
+    pthread_mutex_unlock(&r->lock);
+
+    pthread_t wt;
+    if (pthread_create(&wt, NULL, writer_thread, ctx) != 0) {
+        perror("[record] writer thread");
+        pthread_mutex_lock(&r->lock);
+        r->ctx = NULL;
+        r->active = false;
+        r->pid = -1;
+        r->arec_pid = -1;
+        r->fifo_fd = -1;
+        r->fifo_path[0] = '\0';
+        pthread_mutex_unlock(&r->lock);
+        close(pipefd[1]);
+        free(latest); free(scratch); free(ctx);
+        kill(pid, SIGKILL);
+        if (arec > 0) kill(arec, SIGTERM);
+        if (fifo_fd >= 0) close(fifo_fd);
+        if (fifo_path[0]) unlink(fifo_path);
+        return false;
+    }
+    pthread_detach(wt);
+
+    fprintf(stderr, "[record] started — ffmpeg=%d%s file=%s (paced %d fps)\n",
+            (int)pid,
+            arec > 0 ? " (+arecord)" : "",
+            file, ctx->fps);
+    return true;
+}
+
+/* ── stop watchdog ──
+ * SIGINT asks ffmpeg to shut down gracefully (flush + trailer), but
+ * a graceful shutdown can wedge — e.g. when the ALSA input thread is
+ * stuck in xrun recovery. If the old ffmpeg survives, it keeps the
+ * microphone open and the next 'record start' fails with
+ * "cannot open audio device (Device or resource busy)".
+ *
+ * So after signalling we verify the process actually dies, escalating
+ * politely: SIGINT (sent by recorder_stop) → 3s grace → SIGTERM →
+ * 2s grace → SIGKILL. Runs in a detached thread; recorder_stop still
+ * returns instantly. kill(pid, 0) is used for liveness — it works
+ * whether or not the SIGCHLD handler already reaped the child
+ * (ESRCH once fully gone). */
+static void *stop_watchdog(void *arg)
+{
+    pid_t pid = (pid_t)(intptr_t)arg;
+
+    /* Phase 1: up to 3s for graceful SIGINT shutdown */
+    for (int i = 0; i < 15; i++) {
+        if (kill(pid, 0) != 0) return NULL;   /* gone — clean exit */
+        usleep(200000);
+    }
+
+    fprintf(stderr, "[record] child %d ignored SIGINT — sending SIGTERM\n",
+            (int)pid);
+    kill(pid, SIGTERM);
+
+    /* Phase 2: up to 2s for SIGTERM */
+    for (int i = 0; i < 10; i++) {
+        if (kill(pid, 0) != 0) return NULL;
+        usleep(200000);
+    }
+
+    fprintf(stderr, "[record] child %d ignored SIGTERM — SIGKILL\n",
+            (int)pid);
+    kill(pid, SIGKILL);
+    return NULL;
+}
+
+void recorder_stop(Recorder *r)
+{
+    if (!r) return;
+
+    pthread_mutex_lock(&r->lock);
+    if (!r->active) {
+        pthread_mutex_unlock(&r->lock);
+        return;
+    }
+    /* Mark inactive FIRST — the paced writer thread sees this within
+     * one frame tick, closes the video pipe itself (EOF), frees its
+     * buffers, and exits. We never touch its fd here, so there is no
+     * close-vs-write race by construction. */
+    r->active = false;
+    int   fifo_fd = r->fifo_fd;
+    pid_t pid     = r->pid;
+    pid_t arec    = r->arec_pid;
+    char  file[512], fifo_path[64];
+    strncpy(file, r->file, sizeof file);
+    file[sizeof file - 1] = '\0';
+    strncpy(fifo_path, r->fifo_path, sizeof fifo_path);
+    fifo_path[sizeof fifo_path - 1] = '\0';
+    r->fifo_fd = -1;
+    r->pid = -1;
+    r->arec_pid = -1;
+    r->file[0] = '\0';
+    r->fifo_path[0] = '\0';
+    pthread_mutex_unlock(&r->lock);
+
+    /* Teardown:
+     *   1. Stop arecord — audio EOFs.
+     *   2. Close our O_RDWR FIFO handle — no writers remain.
+     *   3. SIGINT ffmpeg — graceful flush + trailer. Both its inputs
+     *      are plain pipes, so nothing can wedge; the watchdog's
+     *      SIGTERM/SIGKILL escalation is a never-expected safety net.
+     * (The video pipe closes moments later when the writer thread
+     * exits.) No waitpid anywhere — SIGCHLD reaps, stop returns
+     * instantly. */
+    if (arec > 0) {
+        kill(arec, SIGTERM);
+        pthread_t at;
+        if (pthread_create(&at, NULL, stop_watchdog,
+                           (void *)(intptr_t)arec) == 0)
+            pthread_detach(at);
+    }
+    if (fifo_fd >= 0) close(fifo_fd);
+    if (pid > 0) {
+        kill(pid, SIGINT);
+        pthread_t tid;
+        if (pthread_create(&tid, NULL, stop_watchdog,
+                           (void *)(intptr_t)pid) == 0)
+            pthread_detach(tid);
+    }
+    if (fifo_path[0]) unlink(fifo_path);
+
+    fprintf(stderr, "[record] stop initiated — file=%s ffmpeg=%d%s "
+                    "(finalises in background)\n",
+            file, (int)pid, arec > 0 ? " +arecord" : "");
+}
+
+bool recorder_write_frame(Recorder *r, const uint8_t *bgr24, size_t bytes)
+{
+    if (!r || !bgr24) return true;
+
+    /* Just publish the newest frame; the paced writer thread ships it
+     * to ffmpeg on its own clock. A single memcpy (~2.7MB at 720p,
+     * ~0.3ms) under the lock — the main loop never blocks on ffmpeg. */
+    pthread_mutex_lock(&r->lock);
+    RecCtx *c = r->ctx;
+    if (r->active && c && bytes >= c->size) {
+        memcpy(c->latest, bgr24, c->size);
+        c->have_frame = 1;
+    }
+    pthread_mutex_unlock(&r->lock);
+    return true;
+}