Nimbin[12]?Linux & System / webcam-loopback-manipulation-screensharing-and-stuff / API.md

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
API.md 15.7 KB · 418 lines raw

vcam Control API

100% Vibecode, but tested.
Self-contained reference. Hand this file to anyone (or any AI chat)
who writes a program that controls vcam.

<!-- Created-by: Claude Opus 5.5 -->

What it controls

vcam is a virtual webcam. It reads the real webcam, composes overlays, and writes to a v4l2loopback device that video-call apps use as a camera.

Through the API a program can:

vcam must already be running. The API does not start it.

Connection

TransportUnix domain socket, SOCK_STREAM
Path$VCAM_SOCK if set, else /tmp/vcam.sock
Accessfile mode 0600, so only the user running vcam can connect
Clientsup to 16 at once; the 17th gets ERR too many clients
Lifetimekeep the connection open, or connect per command; both work

vcam is running when the socket exists and connect() succeeds. When vcam exits, open connections get EOF.

Protocol

Number of reply lines

All commands in this file reply with exactly one line, except monitors, which replies with one line per monitor.

To read a reply of unknown length, send a marker line # after the command. vcam answers # with OK noop. Read lines until you see OK noop. Everything before it is the reply.

→ monitors
→ #
← OK 1 DP-1 1920x1080+0+0
← OK 2 HDMI-A-1 2560x1440+1920+0
← OK noop

Timing

Most commands answer in about a millisecond. share start takes around 0.3 s (it starts the screen capture). share stop can take up to about 1 s (it waits for the capture process to end). capture set takes 0.2 to 1 s (the camera is re-opened). Use a read timeout of at least 3 s.

Coordinates

Commands

status and status json

The whole state in one line.

→ status
← OK version=1.1.1 build=abc1234 input=webcam output_w=1280 output_h=720 fps=30 share=yes … recording=no
→ status json
← {"ok":true,"version":"1.1.1","build":"abc1234","input":"webcam","output_w":1280,…,"recording":false}

Plain form: key=value pairs separated by spaces, with booleans as yes / no. JSON form: one flat object, with booleans as true / false and integers as numbers. Values never contain spaces.

KeyTypeMeaning
versionstringvcam version, e.g. 1.1.1
buildstringmd5 build hash (7 chars)
inputstringwebcam, or none if vcam was started with --no-input
output_w, output_hintoutput frame size
fpsintoutput frame rate
captureboola camera is open and delivering
capture_devicestringcamera device, e.g. /dev/video1; - with --no-input
capture_fmtstringcamera format, e.g. MJPG; - when off
capture_w, capture_hintcamera resolution (0 when off)
capture_fpsintcamera frame rate (0 when off)
capture_fitstringcrop or stretch; - when off
shareboola screen overlay exists
share_idstringits overlay id (share when started via the API), - if none
share_fullscreenboolthe screen overlay covers the whole output
share_monitorstringmonitor name, - if unknown or not started via share start
share_geometrystringcaptured area WxH+X+Y, - if unknown
share_x, share_y, share_w, share_hintscreen overlay rect (0 when off)
camboola webcam overlay (PiP) exists
cam_idstringits overlay id (cam when made via the API), - if none
cam_posstringtl tr bl br center full custom, or - when off
cam_x, cam_y, cam_w, cam_hintcam rect (0 when off)
cam_zintdraw order index, 0 = bottom; -1 when off
cam_marginintgap (px) used for the corner positions
cam_over_screenboola cam is drawn above the screen, overlaps it, and is visible
overlaysinttotal overlays (images, videos, screens, cams)
filtersintactive filters
recordingboolvcam is recording to a file

Notes:

get <key>

One value from status, in plain form.

→ get cam_pos          ← OK br
→ get cam_over_screen  ← OK yes
→ get nope             ← ERR unknown key 'nope'

version

→ version   ← OK vcam 1.1.1 (build abc1234)

monitors

One line per monitor: OK <n> <name> <WxH+X+Y>. n starts at 1.

→ monitors
← OK 1 DP-1 1920x1080+0+0
← OK 2 HDMI-A-1 2560x1440+1920+0

Error: ERR no monitor detected. Detection uses sway, Hyprland, wlr-randr or xrandr, and falls back to /sys/class/drm, which knows sizes but reports every position as 0,0.

share start [<target>] [options]

Captures a monitor and shows it over the whole output. If a share is already running, it is replaced.

<target>, all optional:

FormExampleMeaning
(none)share startfirst monitor from monitors
numbershare start 2monitor #2
nameshare start DP-1monitor by name
geometryshare start 1920x1080+0+0any desktop area
monitor= / geo=share start monitor=DP-1same, explicit

Options:

OptionDefaultMeaning
fit=stretch / fit=containstretchcontain keeps the aspect ratio and centers it; the bars show the webcam
cam=<pos>—also show the cam PiP at <pos> (see cam on)
cam=off—also remove the cam PiP
camw=<px>current or 320cam width; on its own it also turns the cam on

Without cam= / camw=, an existing cam stays as it is and is raised above the screen.

Reply: the share keys plus cam, cam_pos and cam_over_screen:

→ share start 2 cam=br
← OK share=yes share_id=share share_fullscreen=yes share_monitor=HDMI-A-1 share_geometry=2560x1440+1920+0 share_x=0 share_y=0 share_w=1280 share_h=720 cam=yes cam_pos=br cam_over_screen=yes

Errors:

share stop · share toggle · share status

CommandEffect
share stop (or share off)removes the screen overlay; the webcam image is back
share toggle [<target>] [options]stop if sharing, else share start …
share status (or just share)no change, only the reply

All of them reply in the same format as share start.

cam …: webcam picture-in-picture

Positions (<pos>): tl tr bl br (corners), center, full (whole output).

CommandEffect
cam on [<pos>] [<w>]show the PiP, or re-place it if already shown. Defaults: current position, else tr; current width, else 320
cam pos <pos> [<w>]like cam on, but <pos> is required
cam move <x> <y>free position (top-left corner of the PiP), so cam_pos becomes custom
cam size <w> [<h>]resize but keep the position; <h> defaults to the camera's aspect ratio; resizing a full cam moves it to tr
cam margin [<px>]gap to the output edge for the corner positions (default 0); a cam sitting in a corner is moved at once; without <px>, replies OK margin=<n>
cam raisedraw the cam above every other overlay
cam offremove the PiP, reply OK cam=off
cam toggleoff if shown, else cam on
cam get (or just cam)no change, only the reply

The PiP is always drawn above the shared screen.

Reply (all except off and margin without a value):

OK cam=on id=cam pos=br x=960 y=540 w=320 h=180 z=1 over_screen=yes
OK cam=off

Errors: ERR cam is off … (from move, size and raise), ERR unknown position (use tl|tr|bl|br|center|full), ERR cam size too small.

capture …: camera format, resolution and fps

Switch the camera while vcam runs. The output size never changes: it is fixed at startup (vcam --res WxH), because apps reading the virtual camera depend on it. The camera picture is scaled to it.

CommandEffect
capture / capture getcurrent mode, no change
capture formatsevery mode, one line each: OK <fmt> <WxH> <max fps> (use the # marker)
capture formats jsonthe same as one line: {"ok":true,"formats":[{"fmt":"MJPG","w":1280,"h":720,"fps":30},…]}
`capture set [<fmt>] [<WxH>\max] [<fps>] [fit=crop\stretch]`switch the camera live
`capture fit crop\stretch`change only how the picture is fitted (no camera restart)

capture set takes its arguments in any order, and at least one is needed:

ArgumentValues
<fmt> or fmt=MJPG YUYV NV12 YU12 BGR3 RGB3 (any case, MJPEG also works), or auto = best for the size and fps
<WxH> or res=an exact size from capture formats, or max = the largest size that still reaches the fps
<fps> or fps=frame rate
fit=crop (default) keeps the aspect ratio and cuts the edges; stretch distorts instead

Rules:

Reply:

OK capture=on device=/dev/video1 fmt=YUYV w=640 h=480 fps=30 fit=crop output=1280x720

Examples, for a camera that offers YUYV 1280x720 at 10 fps max:

→ capture set YUYV 640x480 30   ← OK capture=on … fmt=YUYV w=640 h=480 fps=30 …
→ capture set YUYV 1280x720 30  ← ERR YUYV 1280x720 supports at most 10 fps
→ capture set YUYV              ← OK capture=on … fmt=YUYV w=1280 h=720 fps=10 …   (size kept)
→ capture set 15                ← OK capture=on … fps=15 …                          (fps only)

Errors:

A switch takes about 0.2 to 1 s, and the picture pauses briefly. A mode smaller than the output is upscaled, so it looks softer, but it needs less USB bandwidth and CPU.

Behaviour to know

Example: Python client

Standard library only. Handles multi-line replies, timeouts and errors.

import json, os, socket

class VcamError(Exception):
    pass

class Vcam:
    def __init__(self, path=None, timeout=3.0):
        self.path = path or os.environ.get("VCAM_SOCK", "/tmp/vcam.sock")
        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.sock.settimeout(timeout)
        self.sock.connect(self.path)          # raises if vcam is not running
        self.f = self.sock.makefile("rw", encoding="utf-8", newline="\n")

    def cmd(self, line):
        """Send one command, return its reply lines (without 'OK ')."""
        self.f.write(line + "\n#\n")          # '#' → 'OK noop' marks the end
        self.f.flush()
        out = []
        while True:
            r = self.f.readline()
            if not r:
                raise VcamError("vcam closed the connection")
            r = r.rstrip("\n")
            if r == "OK noop":
                break
            out.append(r)
        for r in out:
            if r.startswith("ERR"):
                raise VcamError(r[4:])
        return [r[3:] if r.startswith("OK ") else r for r in out]

    def status(self):
        return json.loads(self.cmd("status json")[0])

    def get(self, key):
        return self.cmd(f"get {key}")[0]

    def close(self):
        self.sock.close()


if __name__ == "__main__":
    v = Vcam()
    print(v.cmd("version")[0])
    print("monitors:", v.cmd("monitors"))
    v.cmd("share start cam=br")
    s = v.status()
    print("sharing:", s["share"], "cam at:", s["cam_pos"], "over screen:", s["cam_over_screen"])
    v.cmd("cam pos tl")
    v.cmd("share stop")
    v.close()

Other languages: anything that opens a Unix stream socket works (Node net.createConnection("/tmp/vcam.sock"), Go net.Dial("unix", …), C socket(AF_UNIX, SOCK_STREAM, 0)). Use the same line protocol.

Example: shell

vcam-ctl wraps the API. It prints bare values (no OK) and exits with 1 on ERR.

vcam-ctl share start cam=br          # share monitor 1, PiP bottom-right
vcam-ctl get cam_pos                 # → br
vcam-ctl get cam_over_screen         # → yes
vcam-ctl cam pos tl
vcam-ctl status                      # one key=value per line
vcam-ctl status --json               # one JSON line
vcam-ctl share stop

vcam-ctl status prints key=value lines, so a shell can load them directly:

eval "$(vcam-ctl status)"
[ "$share" = yes ] && echo "sharing $share_monitor, cam at $cam_pos"

Raw socket, without vcam-ctl:

printf 'status json\nquit\n' | ncat -U /tmp/vcam.sock     # or: socat - UNIX-CONNECT:/tmp/vcam.sock

Recipes

Share button. Call share toggle cam=br, then show share from the reply.

Status indicator (tray, bar). Poll status json every 0.5 to 1 s and read share, cam and cam_over_screen.

Corner hotkeys. Bind cam pos tl / tr / bl / br.

Quality picker. Fill a menu from capture formats json, then call capture set <fmt> <WxH> <fps> with the user's choice.

Wait for vcam. Retry connect() every 0.5 s until it succeeds.

Share a single window or area. Get its geometry from your compositor (e.g. slurp on Wayland, slop on X11), then call share start WxH+X+Y.