Nimbin[12]?Linux & System / webcam-loopback-manipulation-screensharing-and-stuff / scripts/vcam-ctl

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
scripts/vcam-ctl 59.1 KB · 1195 lines raw
#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-only
# vcam — Copyright (C) 2026 the vcam authors. GPL-2.0, see LICENSE.
# Modified-by: Claude Opus 5.5 (control API wrappers)
#
# vcam-ctl – complete runtime control for a running vcam process.
#
# Usage:
#   vcam-ctl <command> [args...]
#
# Overlay commands:
#   list                                                  show active overlays
#                                                         (draw order: first = bottom,
#                                                          last = on top)
#   add img      <id> <x> <y> [<w> [<h>]] <file>          image (PNG/JPEG)
#   add vid      <id> <x> <y> [<w> [<h>]] <file>          video (loops)
#   add vid-once <id> <x> <y> [<w> [<h>]] <file>          video (plays once)
#   add screen   <id> <x> <y> [<w> [<h>]] <WxH+X+Y>       live screen region
#   add webcam   <id> <x> <y> [<w> [<h>]] [-]            same webcam as the main
#                                                         pipeline, shown at <x,y>
#                                                         scaled to <w x h>. Path arg
#                                                         is unused — pass "-" or
#                                                         anything. Multiple webcam
#                                                         overlays are fine; they
#                                                         all share one capture.
#   remove <id>                                           remove one overlay
#   remove all                                            remove every overlay
#   move   <id> [x=N|N] [y=N|N]    Positional or x=/y=. Each value may
#                                  be a number, "keep", or "-" (= keep).
#                                  Missing = keep current. Default action
#                                  for positions is "keep".
#   resize <id> [w=N|N] [h=N|N]    Positional or w=/h=. Each value may
#                                  be a number, "keep", or "auto" / "-"
#                                  (derive from source aspect ratio).
#                                  Missing = auto. Default action for
#                                  resize is "auto".
#   raise  <id>                    bring overlay to the top (drawn last)
#   lower  <id>                    send overlay to the bottom (drawn first)
#   z      <id> <N>                explicit z-index: 0 = bottom, -1 = top,
#                                  -2 = second-from-top, etc.
#
# Filter commands:
#   filter help                                           list available filters
#   filter list                                           show active chain
#   filter add <name> [<param>]
#   filter set <index> <param>                            update parameter live
#   filter remove <index>
#   filter clear
#
# Screen commands (formerly the vcam-screen script):
#   screen                       Pick a region with slurp/slop and add it.
#                                Auto-picks a free ID (screen, screen2, …).
#   screen --full                Capture the whole monitor. If multiple
#                                monitors are connected and you didn't pass
#                                --monitor, an interactive picker appears.
#   screen --monitor <name|N>    Pick a specific monitor for --full, by
#                                connector name (e.g. DP-1, HDMI-A-1) or
#                                1-based index. Suppresses the picker.
#   screen --monitors            List connected monitors and exit.
#   screen --list                List active screen overlays.
#   screen --remove [id]         Remove a screen overlay (default id: "screen").
#   screen --remove-all          Remove all active screen overlays.
#
#   Screen options accepted with or without --full:
#     -i <id>      Overlay ID                  (default: auto)
#     -x <px>      Destination X               (default: 0)
#     -y <px>      Destination Y               (default: 0)
#     -w <px>      Destination width           (only -w preserves aspect)
#     -h <px>      Destination height
#     -r           Replace existing overlay with the same ID first
#
# Webcam-as-overlay quick command (great for screencasting):
#   webcam <tl|tr|bl|br|center|full> [width] [id]
#                                Add a webcam overlay that shares the
#                                main pipeline's V4L2 capture. Multiple
#                                instances are fine — pass a different
#                                <id> to avoid replacing. Default id is
#                                "cam", default width 320, position tr.
#                                "full" stretches it to the full output.
#   webcam off                   Remove the "cam" overlay.
#
# Control API (script friendly: bare values, exit 1 on error):
#   status [--json]              Whole state, one key=value per line (or JSON).
#   get <key>                    One value, e.g. 'get cam_pos' → br
#                                keys: share share_fullscreen share_monitor
#                                cam cam_pos cam_x cam_y cam_w cam_h
#                                cam_over_screen input recording … (see status)
#   share start [<n>|<name>|<WxH+X+Y>] [fit=stretch|contain] [cam=<pos>|off] [camw=N]
#                                Fullscreen share of a monitor (default: first).
#   share stop | toggle | status
#   cam on [<pos>] [<w>]         Webcam PiP. pos: tl tr bl br center full
#   cam off | toggle | raise | get
#   cam pos <pos> | move <x> <y> | size <w> [<h>] | margin <px>
#   monitors                     List monitors as "n name WxH+X+Y".
#   capture [get] | formats      Current camera mode / every mode it offers.
#   capture set [<fmt>] [<WxH>|max] [<fps>] [fit=crop|stretch]
#                                Switch the camera live, e.g. 'capture set MJPG 640x480 30'.
#                                The output size stays; the picture is scaled to it.
#   capture fit crop|stretch     How a different aspect ratio is fitted (default crop).
#   version                      vcam version + build hash.
#   Full API reference (protocol, all keys, client examples):
#     API.md — installed to /usr/share/doc/vcam/API.md
#
# Recording (capture the vcam output to a file):
#   record start [-o <file>] [-m <alsa-dev>] [--no-audio] [--crf N]
#   record stop                  Flush + close file cleanly.
#   record pause / record resume Pause/resume in place (SIGSTOP/SIGCONT).
#   record status                "recording" / "paused" / "stopped".
#   record info                  Detailed status + elapsed duration.
#   record mics                  List ALSA capture devices.
#   record bar                   Print swaybar JSON for status_command.
#   record help                  Full record usage.
#
# Other:
#   help                                                  IPC command list
#   --help, -h                                            this message
#
# Notes:
#   - Passing only <w> (no <h>) preserves source aspect ratio for overlays.
#   - Default socket path is /tmp/vcam.sock. Override with VCAM_SOCK.
#   - See also: vcam-tune (interactive filter dial), vcam-setup (boot config).

SOCK="${VCAM_SOCK:-/tmp/vcam.sock}"

# ── ai "<text>": tell vcam what you want in plain words ─────
# Deterministic keyword router (local, no cloud). Examples:
#   vcam-ctl ai "make me invisible"     vcam-ctl ai "hologram with laser eyes"
#   vcam-ctl ai "blur my background"    vcam-ctl ai "reset"
if [ "${1:-}" = "ai" ]; then
    shift
    T=$(printf '%s' "$*" | tr '[:upper:]' '[:lower:]')
    [ -z "$T" ] && { echo "usage: vcam-ctl ai \"what you want\""; exit 1; }
    ADDED=0
    say() { printf '  + %s\n' "$1"; }
    # ── modifiers: adjust the LAST filter in the chain, live ──
    # "stronger/weaker" -> effect strength (p5 for personfx, p2 others)
    # "faster/slower"   -> speed (facefx p3)
    # "bigger/smaller"  -> amount (facefx p2) / fx (personfx p5)
    last_filter() {
        "$0" filter list 2>/dev/null | sed -n 's/^OK \([0-9]*\): \([a-z-]*\) .*/\1 \2/p' | tail -1
    }
    bump() {  # bump <p1|p2|p3|p5> <delta> <floor> <ceil>
        set -- "$1" "$2" "$3" "$4" "$(last_filter)"
        [ -z "$5" ] && { echo "  (no active filter to adjust)"; exit 1; }
        idx=${5%% *}; fname=${5#* }
        if [ "$1" = "p1" ]; then
            cur=$("$0" filter list 2>/dev/null | sed -n "s/^OK $idx: [a-z-]* param=\([0-9.-]*\).*/\1/p")
        else
            cur=$("$0" filter list 2>/dev/null | sed -n "s/^OK $idx: .*$1=\([0-9.-]*\).*/\1/p")
        fi
        [ -z "$cur" ] && cur=0
        nv=$(awk -v c="$cur" -v d="$2" -v lo="$3" -v hi="$4" \
             'BEGIN{v=c+d; if(v==d)v=1+d; if(v<lo)v=lo; if(v>hi)v=hi; printf "%.2f", v}')
        if [ "$1" = "p1" ]; then
            "$0" filter set "$idx" "$nv" >/dev/null 2>&1 \
                && echo "  ~ $fname param -> $nv"
        else
            "$0" filter set "$idx" "$1" "$nv" >/dev/null 2>&1 \
                && echo "  ~ $fname $1 -> $nv"
        fi
        exit 0
    }
    case "$T" in
        *stronger*|*"more intense"*|*harder*)
            f=$(last_filter); case "${f#* }" in
                personfx) bump p5  0.4 0.2 3.0 ;;
                facefx)   bump p2  0.3 0.3 2.5 ;;
                moodfx)   bump p2  0.3 0.1 2.0 ;;
                styleai)  bump p2  0.1 0.1 1.0 ;;
                *)        bump p1  0.2 0.0 3.0 ;;
            esac ;;
        *weaker*|*subtle*|*softer*|*"less intense"*)
            f=$(last_filter); case "${f#* }" in
                personfx) bump p5 -0.4 0.2 3.0 ;;
                facefx)   bump p2 -0.3 0.3 2.5 ;;
                moodfx)   bump p2 -0.3 0.1 2.0 ;;
                styleai)  bump p2 -0.1 0.1 1.0 ;;
                *)        bump p1 -0.2 0.0 3.0 ;;
            esac ;;
        *faster*)  bump p3  0.4 0.2 3.0 ;;
        *slower*)  bump p3 -0.4 0.2 3.0 ;;
        *bigger*|*larger*)  f=$(last_filter); case "${f#* }" in
                facefx) bump p2 0.3 0.3 2.5 ;; *) bump p5 0.4 0.2 3.0 ;; esac ;;
        *smaller*) f=$(last_filter); case "${f#* }" in
                facefx) bump p2 -0.3 0.3 2.5 ;; *) bump p5 -0.4 0.2 3.0 ;; esac ;;
        *"remove last"*|*"undo"*)
            f=$(last_filter); [ -n "$f" ] && { "$0" filter remove "${f%% *}" >/dev/null 2>&1;
                echo "  - removed ${f#* }"; }; exit 0 ;;
    esac
    fadd() { "$0" filter add $1 >/dev/null 2>&1 && { say "$2"; ADDED=$((ADDED+1)); }; }
    case "$T" in *reset*|*normal*|*clear*) "$0" filter clear >/dev/null 2>&1; echo "  cleared all filters"; exit 0;; esac
    case "$T" in *invisib*|*disappear*|*vanish*) fadd "personfx 4" "invisibility cloak";; esac
    case "$T" in *hologram*) fadd "personfx 10" "hologram you";; esac
    case "$T" in *laser*) fadd "facefx 5" "laser eyes";; esac
    case "$T" in *blur*back*|*back*blur*|*portrait*) fadd "personfx 0" "background blur";; esac
    case "$T" in *clone*|*army*) fadd "personfx 6" "clone army";; esac
    case "$T" in *tiny*|*shrink*) fadd "personfx 9" "tiny you";; esac
    case "$T" in *upside*|*flip*|*gravity*) fadd "personfx 14" "gravity flip";; esac
    case "$T" in *3d*|*window*|*parallax*) fadd "personfx 7" "window-3D";; esac
    case "$T" in *ghost*|*trail*|*echo*) fadd "personfx 15" "motion echo";; esac
    case "$T" in *glitch*) fadd "personfx 17" "glitch body";; esac
    case "$T" in *slice*) fadd "personfx 18" "sliced portrait";; esac
    case "$T" in *disintegrat*|*thanos*|*dissolve*|*ember*) fadd "personfx 19" "disintegration";; esac
    case "$T" in *lightpaint*|*"light paint"*) fadd "personfx 20" "light-paint silhouette";; esac
    case "$T" in *twin*|*double*) fadd "personfx 21" "mirror twin";; esac
    case "$T" in *crystal*|*"low poly"*|*lowpoly*|*triangle*) fadd "personfx 22" "crystal you";; esac
    case "$T" in *xray*|*"x-ray"*|*scan*) fadd "personfx 23" "x-ray scanner";; esac
    case "$T" in *wanted*|*poster*|*bounty*) fadd "personfx 24" "wanted poster";; esac
    case "$T" in *satellite*|*orbit*) fadd "facefx 14" "face satellites";; esac
    case "$T" in *melt*|*dali*|*drip*) fadd "facefx 15" "melting face";; esac
    case "$T" in *"mood ring"*|*border*) fadd "moodfx 6" "mood ring border";; esac
    case "$T" in *spotlight*|*stage*) fadd "personfx 25" "stage spotlight";; esac
    case "$T" in *shadow*|*haunt*) fadd "personfx 26" "haunted shadow";; esac
    case "$T" in *cosmic*|*star*|*space*) fadd "personfx 27" "cosmic you";; esac
    case "$T" in *sticker*|*paper*|*cutout*) fadd "personfx 28" "paper sticker";; esac
    case "$T" in *heat*|*thermal*|*predator*) fadd "personfx 29" "heat signature";; esac
    case "$T" in *afterimage*|*dodge*) fadd "personfx 30" "afterimage burst";; esac
    case "$T" in *sparkle*|*glint*) fadd "facefx 16" "sparkle eyes";; esac
    case "$T" in *halo*|*angel*|*saint*) fadd "facefx 17" "halo";; esac
    case "$T" in *clown*) fadd "facefx 18" "clown";; esac
    case "$T" in *director*|*follow*|*center*|*frame*me*) fadd "facefx 19" "auto-director";; esac
    case "$T" in *mandala*|*kaleido*) fadd "personfx 31" "mandala you";; esac
    case "$T" in *topo*|*radar*|*ring*) fadd "personfx 32" "topo aura";; esac
    case "$T" in *ball*|*bounc*|*juggle*) fadd "personfx 33" "ball pit";; esac
    case "$T" in *rim*|*studio*light*) fadd "personfx 34" "orbit rim light";; esac
    case "$T" in *vortex*|*spiral*|*swirl*) fadd "personfx 35" "mind vortex";; esac
    case "$T" in *glass*|*church*|*window*) fadd "personfx 36" "stained glass";; esac
    case "$T" in *upside*room*|*room*flip*|*world*flip*) fadd "personfx 37" "upside-down room";; esac
    case "$T" in *picasso*|*cubis*) fadd "facefx 20" "picasso face";; esac
    case "$T" in *ripple*|*"time wave"*|*timewave*) fadd "facefx 21" "time ripple";; esac
    case "$T" in *fisheye*|*lens*|*bulge*) fadd "facefx 22" "fisheye face";; esac
    case "$T" in *snow*|*winter*) fadd "personfx 38" "snowfall";; esac
    case "$T" in *fire*|*flame*|*burn*) fadd "personfx 39" "fire silhouette";; esac
    case "$T" in *bubble*|*pop*) fadd "personfx 40" "bubbles";; esac
    case "$T" in *thor*|*lightning*|*zeus*|*storm*) fadd "personfx 41" "thor lightning";; esac
    case "$T" in *firefl*|*glowworm*) fadd "personfx 42" "fireflies";; esac
    case "$T" in *stardust*|*glitter*|*shed*) fadd "personfx 43" "stardust";; esac
    case "$T" in *matrix*|*code*rain*) fadd "personfx 44" "matrix you";; esac
    case "$T" in *"black hole"*|*blackhole*|*suck*) fadd "personfx 45" "black hole";; esac
    case "$T" in *moon*|*planet*|*mini*me*) fadd "personfx 46" "pet moons";; esac
    case "$T" in *portal*|*teleport*) fadd "personfx 47" "portals";; esac
    case "$T" in *godray*|*"god ray"*|*volumetric*|*sunbeam*) fadd "personfx 48" "god rays";; esac
    case "$T" in *tron*|*neon*trace*|*circuit*) fadd "personfx 49" "tron trace";; esac
    case "$T" in *shockwave*|*kamehameha*|*blast*) fadd "personfx 50" "shockwave";; esac
    case "$T" in *rapture*|*levitat*|*ascend*|*"beam me"*) fadd "personfx 51" "rapture beam";; esac
    case "$T" in *kaleido*body*|*"body mandala"*|*wedge*) fadd "personfx 52" "kaleido-body";; esac
    case "$T" in *water*|*lake*|*"liquid floor"*|*reflect*) fadd "personfx 53" "liquid floor";; esac
    case "$T" in *soul*|*astral*|*spirit*) fadd "personfx 54" "astral soul";; esac
    case "$T" in *fog*|*mist*|*smoke*) fadd "personfx 55" "mystic fog";; esac
    case "$T" in *golden*|*ratio*|*davinci*|*"da vinci"*|*phi*) fadd "facefx 23" "golden ratio scan";; esac
    case "$T" in *cat*|*dog*|*animal*|*tiger*|*bear*|*"face image"*|*mask*me*)
        fadd "facefx 24" "face image overlay"
        echo "  hint: set the image first ->  vcam-ctl filter faceimage /path/animal.png";; esac
    case "$T" in *fountain*|*erupt*) fadd "moodfx 7" "emotion fountain";; esac
    case "$T" in *retro*|*sprite*|*pixel*game*|*8bit*|*"8-bit"*) fadd "personfx 66" "retro sprite";; esac
    case "$T" in *acid*|*psychedelic*|*"hue cycle"*) fadd "personfx 67" "acid you";; esac
    case "$T" in *ascii*|*terminal*) fadd "personfx 68" "ascii you";; esac
    case "$T" in *halftone*|*newspaper*|*print*me*) fadd "personfx 69" "halftone print";; esac
    case "$T" in *chrome*|*metal*|*t1000*|*terminator*) fadd "personfx 70" "liquid metal";; esac
    case "$T" in *contour*|*stripe*) fadd "personfx 71" "contour stripes";; esac
    case "$T" in *static*|*"signal lost"*|*"no signal"*) fadd "personfx 72" "static you";; esac
    case "$T" in *gold*|*statue*|*trophy*|*oscar*) fadd "personfx 73" "golden statue";; esac
    case "$T" in *comic*|*ink*) fadd "personfx 74" "comic ink";; esac
    case "$T" in *venetian*|*blind*|*shutter*) fadd "personfx 75" "venetian";; esac
    case "$T" in *burn*edge*|*smolder*|*ember*edge*) fadd "personfx 76" "burning edge";; esac
    case "$T" in *"glass body"*|*glass*me*|*refract*) fadd "personfx 77" "glass body";; esac
    case "$T" in *enhance*|*lighting*|*brighten*|*"bad light"*|*"low light"*|*"too dark"*|*"improve quality"*|*"better quality"*)
        fadd "enhance 1 0.4" "low-light rescue";; esac
    case "$T" in *blueprint*|*technical*) fadd "personfx 78" "blueprint";; esac
    case "$T" in *brick*|*lego*|*tile*) fadd "personfx 79" "brick tiles";; esac
    case "$T" in *silhouette*|*witness*|*anonymous*) fadd "personfx 80" "shadow caller";; esac
    case "$T" in *"glow in"*|*luminous*|*radioactive*) fadd "personfx 81" "glow in dark";; esac
    case "$T" in *graphite*|*pencil*me*|*sketch*me*) fadd "personfx 82" "graphite";; esac
    case "$T" in *"pop poster"*|*warhol*|*screenprint*) fadd "personfx 83" "pop poster";; esac
    case "$T" in *riso*|*misregist*|*"offset print"*) fadd "personfx 84" "riso outlines";; esac
    case "$T" in *haze*|*shimmer*|*mirage*) fadd "personfx 85" "heat haze";; esac
    case "$T" in *security*|*cctv*|*surveil*) fadd "personfx 86" "security cam";; esac
    case "$T" in *negative*|*inverted*me*) fadd "personfx 87" "negative you";; esac
    case "$T" in *vaporwave*|*aesthetic*|*synthwave*) fadd "personfx 88" "vaporwave";; esac
    case "$T" in *emboss*|*relief*) fadd "personfx 89" "emboss relief";; esac
    case "$T" in *drip*|*"pixel melt"*) fadd "personfx 90" "pixel drip";; esac
    case "$T" in *anaglyph*|*"3d glasses"*|*"red cyan"*) fadd "personfx 91" "anaglyph 3d";; esac
    case "$T" in *chalk*|*"crime scene"*) fadd "personfx 92" "chalk outline";; esac
    case "$T" in *"scan bar"*|*scanner*bar*) fadd "personfx 93" "scan bar";; esac
    case "$T" in *"test pattern"*|*"color bars"*|*"stand by"*) fadd "personfx 94" "test pattern";; esac
    case "$T" in *dither*|*"1 bit"*|*1bit*|*macintosh*) fadd "personfx 95" "dither 1bit";; esac
    case "$T" in *frost*|*ice*edge*|*frozen*) fadd "personfx 96" "frost edge";; esac
    case "$T" in *hollow*|*"empty shell"*|*"edges only"*) fadd "personfx 97" "hollow man";; esac
    case "$T" in *searchlight*|*"search light"*|*prison*|*"spot me"*) fadd "personfx 98" "searchlight";; esac
    case "$T" in *"pixel sort"*|*pixelsort*|*"glitch art"*) fadd "personfx 99" "pixel sort";; esac
    case "$T" in *laser*grid*|*"security laser"*|*heist*) fadd "personfx 100" "laser grid";; esac
    case "$T" in *"oil slick"*|*iridescent*|*petrol*) fadd "personfx 101" "oil slick";; esac
    case "$T" in *neon*sign*|*"neon outline"*|*"bar sign"*) fadd "personfx 102" "neon sign";; esac
    case "$T" in *rain*|*"weather"*) fadd "personfx 103" "rain shadow";; esac
    case "$T" in *shatter*|*"broken mirror"*|*shard*) fadd "personfx 104" "mirror shatter";; esac
    case "$T" in *magnet*|*"field lines"*) fadd "personfx 105" "magnet field";; esac
    case "$T" in *"presence"*|*"heat trail"*|*"where i"*been*) fadd "personfx 106" "presence heat";; esac
    case "$T" in *finale*|*celebrate*|*victory*|*golden*rim*) fadd "personfx 107" "grand finale";; esac
    case "$T" in *bubble*|*pop*) fadd "personfx 109" "bubble pop (touch to pop!)";; esac
    case "$T" in *punch*|*box*|*bag*|*hit*something*) fadd "personfx 110" "punching bag";; esac
    case "$T" in *goal*|*keeper*|*save*|*block*|*defend*) fadd "personfx 111" "goalkeeper (block the shots!)";; esac
    case "$T" in *paint*with*|*"motion paint"*|*"paint the room"*) fadd "personfx 112" "motion paint";; esac
    case "$T" in *"force field"*|*particle*|*stir*|*telekine*) fadd "personfx 113" "force field (shove the particles)";; esac
    case "$T" in *smoke*|*fluid*|*current*|*vortex*hand*) fadd "personfx 114" "smoke flow (stir the fluid)";; esac
    case "$T" in *ripple*|*water*|*wave*|*pool*) fadd "personfx 115" "ripple pool (the room is water)";; esac
    case "$T" in *cloth*|*net*|*fabric*|*mesh*push*) fadd "personfx 116" "cloth net (push it)";; esac
    case "$T" in *swarm*|*boid*|*flock*|*insect*|*bees*) fadd "personfx 117" "swarm (they flee your hands)";; esac
    case "$T" in *sand*|*grain*|*pile*|*snow*pile*) fadd "personfx 118" "sand fall (it piles on you)";; esac
    case "$T" in *bouncy*|*"balls"*|*rubber*|*"ball pit"*) fadd "personfx 119" "bouncy balls (bat them around)";; esac
    case "$T" in *liquid*|*fluid*pool*|*splash*|*slosh*) fadd "personfx 120" "liquid pool (scoop and splash it)";; esac
    case "$T" in *slime*|*goo*|*sticky*|*gunge*) fadd "personfx 121" "slime (it clings to you)";; esac
    case "$T" in *leaf*|*leaves*|*autumn*|*wind*) fadd "personfx 122" "leaf storm (your wake blows them)";; esac
    case "$T" in *filing*|*magnet*field*|*"iron"*) fadd "personfx 123" "iron filings (you are the magnet)";; esac
    case "$T" in *breakout*|*brick*break*|*arkanoid*) fadd "personfx 124" "breakout (you are the paddle)";; esac
    case "$T" in *pinata*|*piñata*|*candy*) fadd "personfx 125" "pinata (break it open!)";; esac
    case "$T" in *whip*|*wrecking*|*chain*|*pendulum*) fadd "personfx 126" "chain whip (swing it)";; esac
    case "$T" in *plasma*|*orbs*|*charged*|*repel*) fadd "personfx 127" "plasma orbs (shove the formation)";; esac
    case "$T" in *puck*|*hockey*|*target*) fadd "personfx 128" "target puck (shoot the ring)";; esac
    case "$T" in *crate*|*carry*|*grab*|*"pick up"*) fadd "personfx 129" "carry crates (grab and stack)";; esac
    case "$T" in *lift*|*beam*|*"both hands"*|*balance*) fadd "personfx 130" "two-hand lift (balance the beam)";; esac
    case "$T" in *"virtual room"*|*"sit together"*|*"next to"*|*"same room"*|*"together"*)
        fadd "personfx 132" "virtual room"
        echo "  then select the other person:  vcam-ctl room pick";; esac
    case "$T" in *wrist*|*"real hands"*|*"hand tracking"*|*gauntlet*)
        fadd "personfx 131" "wrist magnet (tracked hands)"
        echo "  hint: needs the pose model ->  vcam-setup --models-pose";; esac
    case "$T" in *ball*|*game*|*juggl*|*keepy*|*football*|*soccer*|*play*)
        fadd "personfx 108" "keepy-uppy (bounce the ball, keep it up!)";; esac
    case "$T" in *skeleton*|*bones*) fadd "posefx 0" "skeleton";; esac
    case "$T" in *"energy hands"*|*orb*|*"power up"*|*goku*) fadd "posefx 2" "energy hands";; esac
    case "$T" in *"wrist trail"*|*conduct*|*"draw in air"*) fadd "posefx 3" "wrist trails";; esac
    case "$T" in *wing*|*angel*wing*) fadd "posefx 4" "light wings";; esac
    case "$T" in *puppet*|*marionette*|*string*) fadd "posefx 5" "puppet strings";; esac
    case "$T" in *"depth of field"*|*dof*|*"real bokeh"*) fadd "depthfx 0" "true depth-of-field";; esac
    case "$T" in *"depth fog"*|*haze*|*atmosphere*) fadd "depthfx 1" "depth fog";; esac
    case "$T" in *"depth view"*|*"depth map"*|*distance*) fadd "depthfx 2" "depth view";; esac
    case "$T" in *parallax*|*wiggle*|*"3d effect"*) fadd "depthfx 3" "parallax wiggle";; esac
    case "$T" in *anime*|*toon*|*cartoon*me*|*gan*|*"neural transform"*)
        fadd "genai 1" "neural img2img"
        echo "  hint: needs a model ->  vcam-ctl filter genmodel /path/animegan.onnx";; esac
    case "$T" in *"color pop"*|*colorpop*|*"black and white"*) fadd "personfx 56" "color pop";; esac
    case "$T" in *cinema*|*movie*|*film*) fadd "personfx 57" "cinema grade";; esac
    case "$T" in *bokeh*) fadd "personfx 58" "bokeh pro";; esac
    case "$T" in *"studio"*|*"look better"*|*relight*) fadd "personfx 59" "studio light";; esac
    case "$T" in *night*|*dark*room*|*"low light"*) fadd "personfx 60" "night boost";; esac
    case "$T" in *"green screen"*|*greenscreen*|*chroma*) fadd "personfx 61" "green screen out";; esac
    case "$T" in *brb*|*away*|*privacy*mode*) fadd "personfx 62" "brb privacy";; esac
    case "$T" in *"pop out"*|*popout*|*depth*|*"3d shadow"*) fadd "personfx 63" "pop-out 3d";; esac
    case "$T" in *vertigo*|*dolly*|*hitchcock*) fadd "personfx 64" "dolly zoom";; esac
    case "$T" in *twotone*|*"two tone"*|*"gradient map"*|*spotify*) fadd "personfx 65" "duotone poster";; esac
    case "$T" in *crown*|*king*|*queen*) fadd "facefx 8" "crown";; esac
    case "$T" in *sunglass*|*shades*) fadd "facefx 4" "sunglasses";; esac
    case "$T" in *googly*) fadd "facefx 2" "googly eyes";; esac
    case "$T" in *bighead*|*bobble*) fadd "facefx 6" "bobblehead";; esac
    case "$T" in *cyclop*) fadd "facefx 10" "cyclops";; esac
    case "$T" in *heart*) fadd "facefx 11" "heart eyes";; esac
    case "$T" in *anonym*|*privacy*) fadd "facefx 0" "face pixelate";; esac
    case "$T" in *confetti*|*smile*|*party*) fadd "moodfx 2" "emotion party";; esac
    case "$T" in *emoji*) fadd "moodfx 3" "emoji face";; esac
    case "$T" in *red*|*warm*) fadd "duotone 0.8" "red-warm duotone";; esac
    case "$T" in *paint*|*style*|*art*) fadd "styleai 1 0.85" "neural style (candy)";; esac
    case "$T" in *mosaic*) fadd "styleai 0 0.85" "neural style (mosaic)";; esac
    case "$T" in *smear*|*liquid*) fadd "paintflow 1.5" "paint smear";; esac
    case "$T" in *anime*|*speed*) fadd "speedlines 1.5" "anime lines";; esac
    case "$T" in *cartoon*) fadd "cvcartoon 0.7" "cartoon";; esac
    case "$T" in *sketch*|*pencil*) fadd "cvpencil 1" "pencil sketch";; esac
    if [ "$ADDED" -eq 0 ]; then
        echo "  didn't recognize an effect. Try: invisible, hologram, laser,"
        echo "  blur background, clones, tiny, crown, confetti, painting,"
        echo "  cartoon, anime, red, reset"
        exit 1
    fi
    exit 0
fi


show_help() { sed -n '/^# vcam-ctl/,/^$/p' "$0" | sed 's/^# \?//'; }

# ── basic usage / help ───────────────────────────────────────
if [ $# -eq 0 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    show_help
    exit 0
fi

# ── room: virtual co-presence — you + a screen-region person ─
# Usage:  vcam-ctl room pick            (draw the region with the mouse)
#         vcam-ctl room set <x y w h>   (manual coordinates)
#         vcam-ctl room off
if [ "${1:-}" = "room" ]; then
    shift
    case "${1:-}" in
        pick)
            if ! command -v slop >/dev/null 2>&1; then
                echo "'slop' not found — install it (sudo apt install slop), or:"
                echo "    vcam-ctl room set <x> <y> <w> <h>"
                exit 1
            fi
            echo "draw a rectangle around the OTHER person's video..."
            G=$(slop -f "%x %y %w %h") || exit 1
            # shellcheck disable=SC2086
            set -- $G
            "$0" filter roomregion "$1" "$2" "$3" "$4"
            "$0" filter add personfx 132
            echo "their size:  vcam-ctl filter set <idx> p5 1.2    their seat: p2 0.8"
            ;;
        set)
            shift
            "$0" filter roomregion "${1:?x}" "${2:?y}" "${3:?w}" "${4:?h}"
            "$0" filter add personfx 132
            ;;
        off)
            "$0" filter roomregion off
            ;;
        *)
            echo "usage: vcam-ctl room pick | room set <x> <y> <w> <h> | room off"
            exit 1
            ;;
    esac
    exit 0
fi

# ── check vcam is alive ──────────────────────────────────────
require_running() {
    if [ ! -S "$SOCK" ]; then
        echo "Error: vcam is not running (socket $SOCK not found)" >&2
        exit 1
    fi
}

# ── send an IPC command and print the reply ──────────────────
ipc_send() {
    require_running
    printf '%s\nquit\n' "$*" | ncat -U "$SOCK"
}

# ── bare-metal monitor detection ─────────────────────────────
# Lists connected monitors as one line each: "NAME WxH X Y"
# Uses /sys/class/drm for resolution (works everywhere). For accurate
# X/Y positions on multi-monitor setups, falls back to swaymsg if
# present — without it we report 0,0 for all monitors (correct for
# single-monitor; possibly wrong offset for non-primary on multi).
detect_monitors() {
    # Try sway first — it gives us real positions, not just resolutions.
    if command -v swaymsg >/dev/null 2>&1 \
       && swaymsg -t get_outputs --pretty 2>/dev/null | grep -q "^Output "; then
        swaymsg -t get_outputs --pretty 2>/dev/null | awk '
            /^Output / { name=$2 }
            /Current mode: / { mode=$3 }
            /Position: / {
                gsub(",", " ", $2)
                if (name && mode) {
                    split($2, p, " ")
                    print name, mode, p[1], p[2]
                    name=""; mode=""
                }
            }
        '
        return 0
    fi
    # Bare-metal fallback: /sys/class/drm — only gives resolution.
    for status_file in /sys/class/drm/card*/status; do
        [ -r "$status_file" ] || continue
        echo "$status_file" | grep -qE '/card[0-9]+-[^/]+/status$' || continue
        if [ "$(cat "$status_file")" = "connected" ]; then
            local dir="${status_file%/status}"
            local name mode
            name=$(basename "$dir" | sed 's/^card[0-9]*-//')
            mode=$(head -1 "$dir/modes" 2>/dev/null)
            if [ -n "$mode" ] && echo "$mode" | grep -qE '^[0-9]+x[0-9]+$'; then
                echo "$name $mode 0 0"
            fi
        fi
    done
}

# Resolves a monitor selector (name or 1-based index) to a "NAME WxH X Y"
# line. Empty selector + single monitor → that monitor. Empty selector +
# multiple monitors → interactive prompt.
resolve_monitor() {
    local selector="$1"
    local lines
    lines=$(detect_monitors)
    [ -z "$lines" ] && { return 1; }

    local count
    count=$(echo "$lines" | wc -l)

    # Specific selector
    if [ -n "$selector" ]; then
        if echo "$selector" | grep -qE '^[0-9]+$'; then
            echo "$lines" | sed -n "${selector}p"
        else
            echo "$lines" | awk -v n="$selector" '$1 == n { print; exit }'
        fi
        return 0
    fi

    # Single monitor: just use it
    if [ $count -eq 1 ]; then
        echo "$lines"
        return 0
    fi

    # Multiple monitors: interactive prompt
    # Only require stdin to be a TTY — stdout is captured by $(...) so
    # -t 1 would always fail when called via command substitution.
    if [ ! -t 0 ]; then
        echo "$lines" | head -1
        return 0
    fi

    echo "Multiple monitors connected:" >&2
    local i=0
    while IFS= read -r line; do
        i=$((i+1))
        name=$(echo "$line" | awk '{print $1}')
        mode=$(echo "$line" | awk '{print $2}')
        x=$(echo "$line" | awk '{print $3}')
        y=$(echo "$line" | awk '{print $4}')
        printf "  %d) %-12s %s  at (%d,%d)\n" "$i" "$name" "$mode" "$x" "$y" >&2
    done <<EOF
$lines
EOF
    printf "Select monitor (1-%d, default 1): " "$count" >&2
    local choice
    read -r choice
    [ -z "$choice" ] && choice=1
    if ! echo "$choice" | grep -qE '^[0-9]+$' || [ "$choice" -lt 1 ] || [ "$choice" -gt "$count" ]; then
        echo "Invalid selection" >&2; return 1
    fi
    echo "$lines" | sed -n "${choice}p"
}

# ──────────────────────────────────────────────────────────────
# screen subcommand — fully merged from old vcam-screen
# ──────────────────────────────────────────────────────────────
if [ "$1" = "screen" ]; then
    shift
    require_running

    ID=""
    DST_X=0; DST_Y=0; DST_W=0; DST_H=0
    REPLACE=0
    FULL=0
    MONITOR=""
    ACTION="add"   # add | list | remove | remove-all | monitors

    while [ $# -gt 0 ]; do
        case "$1" in
            --help) show_help; exit 0 ;;
            -i) ID="$2"; shift 2 ;;
            -x) DST_X="$2"; shift 2 ;;
            -y) DST_Y="$2"; shift 2 ;;
            -w) DST_W="$2"; shift 2 ;;
            -h) DST_H="$2"; shift 2 ;;
            --full) FULL=1; shift ;;
            --monitor) MONITOR="$2"; shift 2 ;;
            --monitors) ACTION="monitors"; shift ;;
            -r|--replace) REPLACE=1; shift ;;
            --list) ACTION="list"; shift ;;
            --remove)
                ACTION="remove"
                if [ $# -ge 2 ] && [ "$2" != -* ]; then ID="$2"; shift 2
                else ID="screen"; shift; fi ;;
            --remove-all) ACTION="remove-all"; shift ;;
            *) echo "Unknown screen option: $1  (try --help)" >&2; exit 1 ;;
        esac
    done

    # ── list / remove / monitors paths ──
    if [ "$ACTION" = "monitors" ]; then
        lines=$(detect_monitors)
        if [ -z "$lines" ]; then
            echo "No monitors detected." >&2; exit 1
        fi
        i=0
        while IFS= read -r line; do
            i=$((i+1))
            name=$(echo "$line" | awk '{print $1}')
            mode=$(echo "$line" | awk '{print $2}')
            x=$(echo "$line" | awk '{print $3}')
            y=$(echo "$line" | awk '{print $4}')
            printf "  %d) %-12s %s  at (%d,%d)\n" "$i" "$name" "$mode" "$x" "$y"
        done <<EOF
$lines
EOF
        exit 0
    fi

    if [ "$ACTION" = "list" ]; then
        ipc_send list | grep '\[screen\]' || echo "no screen overlays"
        exit 0
    fi
    if [ "$ACTION" = "remove" ]; then
        ipc_send "remove $ID"
        exit 0
    fi
    if [ "$ACTION" = "remove-all" ]; then
        ipc_send list | grep -oE '\[screen\] id=[^ ]+' | \
            awk -F= '{print $2}' | while read -r oid; do
                [ -n "$oid" ] && { echo "removing $oid"; ipc_send "remove $oid"; }
            done
        exit 0
    fi

    # ── add path ──
    # Auto-pick a free ID if user didn't provide one
    if [ -z "$ID" ]; then
        EXISTING=$(ipc_send list 2>/dev/null | grep -oE 'id=[^ ]+' | awk -F= '{print $2}')
        if ! echo "$EXISTING" | grep -qx "screen"; then
            ID="screen"
        else
            i=2
            while echo "$EXISTING" | grep -qx "screen$i"; do i=$((i+1)); done
            ID="screen$i"
        fi
    fi

    # Detect display server
    if [ -n "${WAYLAND_DISPLAY:-}" ]; then DS="wayland"
    elif [ -n "${DISPLAY:-}" ]; then       DS="x11"
    else
        echo "Error: neither WAYLAND_DISPLAY nor DISPLAY is set" >&2; exit 1
    fi

    # Obtain geometry
    GEOMETRY=""
    if [ $FULL -eq 1 ]; then
        SEL=$(resolve_monitor "$MONITOR")
        if [ -z "$SEL" ]; then
            echo "Could not resolve monitor selection." >&2
            echo "Run 'vcam-ctl screen --monitors' to list connected monitors." >&2
            exit 1
        fi
        set -- $SEL
        MNAME="$1" MMODE="$2" MX="$3" MY="$4"
        GEOMETRY="${MMODE}+${MX}+${MY}"
        echo "Full screen on $MNAME: $GEOMETRY"
    else
        echo "Select a screen region..." >&2
        if [ "$DS" = "wayland" ]; then
            command -v slurp >/dev/null || { echo "slurp not installed" >&2; exit 1; }
            SLURP_RAW=$(slurp 2>/dev/null) || { echo "Cancelled." >&2; exit 1; }
            SX=$(echo "$SLURP_RAW" | cut -d',' -f1)
            SY=$(echo "$SLURP_RAW" | cut -d',' -f2 | cut -d' ' -f1)
            SW=$(echo "$SLURP_RAW" | cut -d' ' -f2 | cut -d'x' -f1)
            SH=$(echo "$SLURP_RAW" | cut -d' ' -f2 | cut -d'x' -f2)
            GEOMETRY="${SW}x${SH}+${SX}+${SY}"
        else
            if command -v slop >/dev/null; then
                GEOMETRY=$(slop -f "%wx%h+%x+%y" 2>/dev/null) || { echo "Cancelled." >&2; exit 1; }
            else
                echo "slop not installed. Enter geometry manually (WxH+X+Y):" >&2
                read -r GEOMETRY
            fi
        fi
        echo "Selected: $GEOMETRY" >&2
    fi

    if [ $REPLACE -eq 1 ]; then
        echo "Removing existing overlay '$ID'..." >&2
        ipc_send "remove $ID" >/dev/null || true
    fi

    ARGS="add screen $ID $DST_X $DST_Y"
    if   [ $DST_W -gt 0 ] && [ $DST_H -gt 0 ]; then ARGS="$ARGS $DST_W $DST_H"
    elif [ $DST_W -gt 0 ];                    then ARGS="$ARGS $DST_W"
    elif [ $DST_H -gt 0 ];                    then ARGS="$ARGS 0 $DST_H"
    fi
    ARGS="$ARGS $GEOMETRY"

    echo "Adding screen overlay '$ID'..." >&2
    ipc_send $ARGS
    echo "" >&2
    echo "Screen overlay '$ID' is live." >&2
    echo "  Remove:  vcam-ctl screen --remove $ID" >&2
    echo "  Move:    vcam-ctl move   $ID <x|-> [<y|->]" >&2
    echo "  Resize:  vcam-ctl resize $ID <w|-> [<h|->]" >&2
    exit 0
fi

# ──────────────────────────────────────────────────────────────
# webcam subcommand — add the webcam as a movable overlay
# ──────────────────────────────────────────────────────────────
# Useful in --no-input mode (or with a second camera) to show yourself
# in the corner while screensharing. Internally the webcam is an
# overlay just like images/videos, so move/resize/raise/lower work on
# it identically.
#
# Usage:
#   vcam-ctl webcam <position>     [width] [device]
#   vcam-ctl webcam off
#
#   position: tl|tr|bl|br|center   (top/bottom × left/right, or center)
#   width:    overlay width in px  (default 320; height auto from aspect)
#   device:   /dev/video<N>         (default /dev/video1)
#
# Examples:
#   vcam-ctl webcam tr             # 320-wide PiP in the top-right
#   vcam-ctl webcam br 480         # bigger, bottom-right
#   vcam-ctl webcam center         # centered on screen
#   vcam-ctl webcam off            # remove the webcam overlay
#
# Default ID is "cam". To run multiple webcam overlays, add them with
# the lower-level: vcam-ctl add webcam myid <x> <y> [<w>] <device>
if [ "$1" = "webcam" ]; then
    shift
    require_running
    POS="${1:-tr}"; WIDTH="${2:-320}"; ID="${3:-cam}"

    if [ "$POS" = "off" ] || [ "$POS" = "remove" ]; then
        ipc_send "remove $ID"
        exit 0
    fi

    # Output frame size — needed to compute corner positions.
    OUT="${VCAM_OUTPUT:-/dev/video0}"
    OUT_SIZE=""
    if command -v v4l2-ctl >/dev/null 2>&1; then
        OUT_SIZE=$(v4l2-ctl -d "$OUT" --get-fmt-video 2>/dev/null \
                   | awk -F'/' '/Width\/Height/{print $2}' | tr -d ' ')
    fi
    echo "$OUT_SIZE" | grep -qE '^[0-9]+x[0-9]+$' || OUT_SIZE="1280x720"
    OUT_W="${OUT_SIZE%x*}"; OUT_H="${OUT_SIZE#*x}"

    # Webcam is 16:9 (height computed from width)
    HEIGHT=$(( WIDTH * 9 / 16 ))
    case "$POS" in
        tl)     X=0;                    Y=0 ;;
        tr)     X=$(( OUT_W - WIDTH )); Y=0 ;;
        bl)     X=0;                    Y=$(( OUT_H - HEIGHT )) ;;
        br)     X=$(( OUT_W - WIDTH )); Y=$(( OUT_H - HEIGHT )) ;;
        center) X=$(( (OUT_W - WIDTH) / 2 )); Y=$(( (OUT_H - HEIGHT) / 2 )) ;;
        full)   X=0; Y=0; WIDTH=$OUT_W; HEIGHT=$OUT_H ;;
        *) echo "Unknown position '$POS' (use tl|tr|bl|br|center|full|off)" >&2; exit 1 ;;
    esac

    # Replace any existing overlay with this ID
    ipc_send "remove $ID" >/dev/null 2>&1 || true
    echo "Adding webcam overlay '$ID' at $POS (${X},${Y}) width=$WIDTH"
    # The webcam overlay shares the main pipeline's capture; pass "-" as
    # the path argument since the type doesn't need one.
    ipc_send "add webcam $ID $X $Y $WIDTH -"

    echo ""
    echo "Webcam overlay '$ID' is live. Tweak with:"
    echo "  vcam-ctl move   $ID x=N y=N"
    echo "  vcam-ctl resize $ID w=N"
    echo "  vcam-ctl raise  $ID         # bring to top"
    echo "  vcam-ctl lower  $ID         # send to bottom"
    echo "  vcam-ctl z      $ID <N>     # explicit z-index"
    echo "  vcam-ctl webcam off          # remove (if id was 'cam')"
    exit 0
fi

# ──────────────────────────────────────────────────────────────
# control API — status / get / share / cam / monitors / version
# [Claude Opus 5.5] Strips the "OK " / "OK bye" noise so output is
# directly usable in scripts; exits 1 if vcam answered ERR.
# ──────────────────────────────────────────────────────────────
case "$1" in
    status|get|share|cam|capture|monitors|version)
        require_running
        if [ "$1" = "status" ] && { [ "${2:-}" = "--json" ] || [ "${2:-}" = "json" ]; }; then
            ipc_send "status json" | head -n 1
            exit 0
        fi
        OUT=$(ipc_send "$*" | grep -v '^OK bye$')
        if printf '%s\n' "$OUT" | grep -q '^ERR'; then
            printf '%s\n' "$OUT" >&2
            exit 1
        fi
        if [ "$1" = "status" ]; then
            printf '%s\n' "${OUT#OK }" | tr ' ' '\n'
        else
            printf '%s\n' "$OUT" | sed 's/^OK //'
        fi
        exit 0
        ;;
esac

# ──────────────────────────────────────────────────────────────
# record subcommand — drive an ffmpeg child to capture the vcam
# output (and optionally a microphone).
#
# State lives in three small files under /tmp so any tool (swaybar,
# polybar, conky, custom scripts) can read them without going through
# IPC:
#
#   /tmp/vcam-record.pid     ← PID of the running ffmpeg child
#   /tmp/vcam-record.status  ← "recording" or "paused"
#   /tmp/vcam-record.info    ← key=value lines: file, mic, started, format
#   /tmp/vcam-record.log     ← ffmpeg stderr (for debugging)
#
# Recording survives a vcam restart — it's an independent ffmpeg
# process. State files self-clean when stale.
# ──────────────────────────────────────────────────────────────
REC_PID="/tmp/vcam-record.pid"
REC_STATUS="/tmp/vcam-record.status"
REC_INFO="/tmp/vcam-record.info"
REC_LOG="/tmp/vcam-record.log"

rec_is_active() {
    [ -f "$REC_PID" ] || return 1
    local pid; pid=$(cat "$REC_PID" 2>/dev/null) || return 1
    [ -z "$pid" ] && return 1
    kill -0 "$pid" 2>/dev/null
}

rec_cleanup_stale() {
    if ! rec_is_active; then
        rm -f "$REC_PID" "$REC_STATUS" "$REC_INFO"
    fi
}

rec_list_mics() {
    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)"
            printf '%s\n' "$sources" | while IFS= read -r src; do
                printf "  %-18s %s\n" "pulse:$src" "$src"
            done
            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" "------------------" "---------------------------------"
            printf '%s\n' "$lines" | while IFS= read -r line; do
                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
            echo ""
        fi
    fi

    if [ $have_any -eq 0 ]; then
        echo "No capture devices found."
        return 1
    fi

    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() {
    local dir="${XDG_VIDEOS_DIR:-$HOME/Videos}"
    [ -d "$dir" ] || dir="$HOME"
    echo "$dir/vcam-$(date +%Y-%m-%d_%H-%M-%S).mkv"
}

if [ "$1" = "record" ]; then
    shift
    ACTION="${1:-help}"
    shift || true

    case "$ACTION" in
        # ── start ────────────────────────────────────────────
        start)
            rec_cleanup_stale
            if rec_is_active; then
                echo "Already recording (pid $(cat $REC_PID))." >&2
                echo "Use 'vcam-ctl record stop' first, or pass --replace." >&2
                if [ " $* " != *" --replace "* ] && [ " $* " != *" -r "* ]; then
                    exit 1
                fi
                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="ultrafast"; AOFFSET="0.2"

            while [ $# -gt 0 ]; do
                case "$1" in
                    -o|--output)   OUT="$2"; shift 2 ;;
                    -m|--mic)      MIC="$2"; shift 2 ;;
                    --no-audio)    NO_AUDIO=1; shift ;;
                    --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
            done

            OUT="${OUT:-$(rec_default_output)}"
            mkdir -p "$(dirname "$OUT")"

            # 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 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
                    FIRST_HW=$(arecord -l 2>/dev/null \
                        | grep -E '^card [0-9]+' \
                        | head -1 \
                        | sed -E 's/^card ([0-9]+).* device ([0-9]+).*/plughw:\1,\2/')
                    if [ -n "$FIRST_HW" ] && echo "$FIRST_HW" | grep -qE '^plughw:'; then
                        MIC="$FIRST_HW"
                    fi
                fi
                if [ -n "$MIC" ]; then
                    echo "[record] auto-selected mic: $MIC" \
                         "(override with --mic, or skip with --no-audio)"
                else
                    echo "[record] no capture device found — recording video only"
                fi
            fi
            # Normalize plain "N,M" → "plughw:N,M"
            if [ -n "$MIC" ] && echo "$MIC" | grep -qE '^[0-9]+,[0-9]+$'; then
                MIC="plughw:$MIC"
                echo "[record] interpreting mic as $MIC"
            fi

            # 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
                REQ="$REQ mic=$MIC"
            fi
            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

            # 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"
                echo "mic=${MIC:-none}"
                echo "started=$(date +%s)"
                echo "started_human=$(date '+%Y-%m-%d %H:%M:%S')"
                echo "format=${OUT##*.}"
                echo "vcodec=$VCODEC"
                echo "crf=$CRF"
                echo "transport=pipe"
            } > "$REC_INFO"

            echo "● Recording started"
            echo "   file: $OUT"
            echo "   pid:  ${PID:-?}  (ffmpeg, child of vcam)"
            [ -n "$MIC" ] && echo "   mic:  $MIC"
            echo "   transport: pipe (vcam → ffmpeg stdin, no /dev/video0 read)"
            ;;

        # ── stop ─────────────────────────────────────────────
        stop)
            # 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
            rm -f "$REC_PID" "$REC_STATUS" "$REC_INFO"
            echo "■ Recording stopped"
            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 ────────────────────────────────────────────
        # 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)
            echo "pause is not supported in the pipe-based recorder." >&2
            echo "Use 'record stop' and 'record start' instead." >&2
            exit 1
            ;;

        resume|continue)
            echo "resume is not supported in the pipe-based recorder." >&2
            echo "Use 'record start' to begin a new recording." >&2
            exit 1
            ;;

        # ── status ───────────────────────────────────────────
        # Outputs one of: "recording", "paused", "stopped".
        # Designed for swaybar / polybar polling — exit code mirrors
        # the state so 'vcam-ctl record status >/dev/null' is enough.
        status)
            if rec_is_active; then
                cat "$REC_STATUS" 2>/dev/null || echo "recording"
                exit 0
            else
                rec_cleanup_stale
                echo "stopped"
                exit 1
            fi
            ;;

        # ── info ─────────────────────────────────────────────
        info)
            if ! rec_is_active; then
                rec_cleanup_stale
                echo "Not currently recording."
                exit 1
            fi
            echo "state=$(cat $REC_STATUS 2>/dev/null || echo recording)"
            echo "pid=$(cat $REC_PID)"
            [ -f "$REC_INFO" ] && cat "$REC_INFO"
            # Duration on the fly
            if [ -f "$REC_INFO" ]; then
                START=$(grep '^started=' "$REC_INFO" | cut -d= -f2)
                if [ -n "$START" ]; then
                    NOW=$(date +%s)
                    DUR=$((NOW - START))
                    printf "duration=%02d:%02d:%02d\n" \
                        $((DUR/3600)) $(((DUR%3600)/60)) $((DUR%60))
                fi
            fi
            ;;

        # ── mics: list available ALSA capture devices ─────────
        mics|devices)
            rec_list_mics
            ;;

        # ── bar: emit swaybar-compatible JSON (for status_command) ─
        bar)
            if rec_is_active; then
                STATE=$(cat "$REC_STATUS" 2>/dev/null || echo recording)
                START=$(grep '^started=' "$REC_INFO" 2>/dev/null | cut -d= -f2)
                NOW=$(date +%s)
                DUR=$((NOW - ${START:-NOW}))
                LBL=$(printf "%02d:%02d:%02d" $((DUR/3600)) $(((DUR%3600)/60)) $((DUR%60)))
                if [ "$STATE" = "paused" ]; then
                    printf '{"text":"⏸ REC %s","class":"paused","color":"#ffaa00"}\n' "$LBL"
                else
                    printf '{"text":"● REC %s","class":"recording","color":"#ff5555"}\n' "$LBL"
                fi
            else
                printf '{"text":"","class":"idle"}\n'
            fi
            ;;

        help|--help|-h|"")
            cat <<'HLP'
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>      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 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):
  /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 stderr (look here if it fails)
HLP
            ;;

        *) echo "Unknown record action: $ACTION (try 'vcam-ctl record help')" >&2; exit 1 ;;
    esac
    exit 0
fi

# ── default: pass everything else straight to the IPC server ─
ipc_send "$*"