Skip to content

Camera passthrough for live view - #520

Draft
andrewleesteele wants to merge 5 commits into
mainfrom
hypeship/camera-passthrough-live-view
Draft

andrewleesteele wants to merge 5 commits into
mainfrom
hypeship/camera-passthrough-live-view

Conversation

@andrewleesteele

@andrewleesteele andrewleesteele commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Lets a live-view viewer share their real camera into the browser as a local camera device, on demand: when a page inside the browser calls getUserMedia(), the viewer's camera turns on; when the page releases it, it turns off. A manual toggle is also provided.

This turns the hand-built prototype from the spike (kernel-images#515) into reviewable, convention-matching code.

Scope / safety. This relays a real person's real camera so they can complete their own camera step (identity verification where the person is present, video, capture). It is not a way to feed synthetic or recorded video to a liveness check. The device and feed are made to present as what they genuinely are to the person sharing — a real camera, attached locally — so checks meant to catch injected video don't false-positive on a relayed live person (see "Device & signal realism" below).

How it works

viewer's camera ──WebRTC──▶ neko ──▶ /dev/video1 (ingest)
                                         │  camerad mixer (single writer)
                                         ▼
chromium getUserMedia ◀── /dev/video0 (camera pages see)
  • server/lib/camera + server/cmd/camerad — the manager owns the browser-facing loopback device as the single writer, so chromium never loses its source: it streams a placeholder frame until the viewer shares, then live ingest frames, then back to the placeholder. It detects when a page holds the device open (the on-demand signal) and publishes State both on a localhost endpoint and as a static file the live-view client can poll.
  • cmd/wrapper + supervisor/services/camerad.conf + Dockerfile — camerad starts and neko's webcam ingest is enabled only when a session sets KERNEL_ENABLE_CAMERA=true (which requires the headful WebRTC/live-view path).
  • client — kernel/camera.ts plus shareLocalCamera()/unshareLocalCamera() on the neko client: auto start/stop on the on-demand signal, a manual toggle, and re-request on orientationchange.

Test results (real browser, 2026-11-16)

  1. Passthrough works. A page's getUserMedia() auto-starts the viewer's camera; the browser gets live 1280×720; the camera stops ~3s after the page releases it. Verified on the WebRTC getUserMedia sample.
  2. A real liveness SDK rejects the virtual camera (expected). A widely used browser liveness demo refuses the session with a "3rd-party app is modifying the video / suspicious webcam configuration" error — it detects the loopback device. So passthrough alone won't carry a liveness step on a vendor that blocks virtual cameras; it's for flows whose vendor permits a relayed camera, and for non-liveness camera use.
  3. Orientation is a known limitation: capture is pinned to 1280×720 landscape, so rotating a phone doesn't change the aspect. The client re-requests on rotate; native per-orientation device caps are a follow-up.

bench/camera-passthrough-live-view/ has the findings and a no-image-build reproduction.

Verified here

  • go build / go vet / go test ./lib/camera/ — pass (manager, device helpers, state handler, ingest stall watchdog).
  • go build / go vet on cmd/camerad and the modified cmd/wrapper — pass.
  • Live, in a real browser with this PR's camerad installed by hand (image not rebuilt; the client controller injected as a script): a page's getUserMedia() auto-starts the viewer's camera, the page gets live video within ~1s, and the camera stops after the page releases it — for two sessions back to back. The second session exposed a bug (the ingest reader held the device after the first share ended), fixed in the second commit.

Not done yet (needs an owner)

  • Guest kernel / loopback module provisioning — done below: the image builds and ships the modules for the pinned guest kernel (keep CAMERA_KERNEL_TAG in the Dockerfile in sync with hypeman's DefaultKernelVersion). arm64 browsers need a cross build before the camera reaches them.
  • Browser image build not run here. The client controller is not wired in: nothing imports CameraController, so webpack tree-shakes it out — the viewer half does not ship in the image yet. app.vue/main.ts wiring + a vue-tsc build are a follow-up. (camera.ts transform-checks clean with esbuild.)
  • Companion kernel/API + SDK + docs change for a camera: true browser-create option and a media-share permission (read-only viewers must not be able to share).
  • Cleaner page-driven (CDP) on-demand signal instead of the /proc scan.

Draft — do not merge.

Hands-on test fixes (orientation, latency)

From testing on a phone:

  • Squashed portrait video — neko's webcam pipeline (hardcoded) scales whatever it receives to 1280x720 without keeping the aspect ratio. The viewer now always sends an upright 1280x720 frame, pillarboxing portrait; rotation needs no camera re-acquire. ✅ verified: a 300x300 square sent from a 720x1280 source arrives square (was ~3:1 flat).
  • "Mirrored" — not changed on purpose. The browser gets the camera unmirrored, as from any webcam (only selfie previews mirror); mirroring would flip documents held up to the camera. Pages that want a mirrored preview do it in CSS.
  • Latency — measured with a clock-stamped synthetic camera: network RTT ~9 ms, but ~100+ ms is spent in neko's webcam decode before camerad sees a frame, and the live-view return path adds ~130 ms to what the viewer sees. camerad changes: ingest flushes each frame immediately (was holding a partial frame until the next), the mixer forwards on arrival instead of sampling on a ticker, and 30 fps default (page went 15 → ~25 fps). End-to-end numbers are noisy run to run; most remaining lag lives in neko (follow-up: drop videorate, pin pixel-aspect-ratio=1/1 in its webcam caps).
  • Quick stop/start — the ingest reader now waits for v4l2loopback to report a producer instead of re-opening the device every 300 ms, which could race neko's pipeline start. ✅ 5/5 back-to-back sessions went live, zero open errors.

🤖 Generated with Claude Code

Review remediation (independent two-pass review)

Fixed on the branch and, where runtime-checkable, re-validated live with the rebuilt camerad:

  • wrapper env timing — NEKO_CAPTURE_WEBCAM_* was Setenv'd after supervisord forked, so neko never saw it and the feature was inert on the real image path (the earlier live test masked this by writing neko config directly). Moved before supervisord start; gate now sets ENABLED explicitly both ways; ingest device from camera.DefaultIngestDevice; wait on camerad /healthz before neko. Reasoned + builds; not runtime-verified (runs at image boot).
  • ingest watchdog — replaced killOnStall with a per-attempt context cancelled by a stall timer, so the cancel that kills ffmpeg also unblocks Wait (the old watchdog could retire before Wait and wedge ingest). ✅ back-to-back shares both go live.
  • device visibility — camerad now chmods ingest 0600 (root-only; chromium can't see/select it) and output 0666. ✅ verified /dev/video1 is root-only in a running browser.
  • on-demand false-positive — a page calling enumerateDevices() briefly opens the device; the /proc signal is now debounced over 3 polls, and the client gates auto-follow on a one-time manual share (consent) so a page can't turn on the viewer's camera on its own.
  • client lifecycle — poll/timer no longer runs after unmount() (was re-acquiring the camera), stop() cancels an in-flight start() via a generation counter, manual-off sticks, matchMedia listener removed.
  • structural — folded the duplicate state-file writer into the detector using canonical lib/statefile.WriteJSON (was a hand-rolled copy swallowing errors); one frameFreshFor const + live() accessor; clamped CAMERA_WIDTH/HEIGHT/FPS; ensureDevices checks both nodes.
  • nit — placeholder is now a plain dark frame (the "Waiting for camera…" text was an automation fingerprint).

Intentionally deferred (surfaced, not changed): relocating the controller to src/utils/ with injected deps + tests; whether the pinned neko build enforces can_share_media server-side for read-only viewers (outside this repo); trimming idle CPU of the always-on mixer/detector loops; and the page-driven CDP on-demand signal.

Review ran static-only (no tests run by reviewers); no GitHub review state was submitted by the reviewers.

Device & signal realism (2026-11-19)

The loopback device and the feed now present as an ordinary local camera instead of a relay, measured in Chromium 156 (harness + numbers in bench/camera-passthrough-live-view/):

Device (images/chromium-headful/camera/ — a camera-persona v4l2loopback built for the pinned guest kernel, shipped in-image and loaded by camerad with finit_module(2)):

  • uvcvideo driver + usb-… bus in VIDIOC_QUERYCAP; a two-level sysfs device hierarchy so device/interface + device/../idVendor|idProduct resolve like a UVC camera's (vid/pid/label are module params).
  • Realistic discrete modes (640x480, 800x600, 1280x720 @30…5, 1920x1080 @15…5): capture-side S_FMT negotiates any of them while streaming (snapped like a UVC driver; adopted without buffer realloc — buffers are allocated once at max size and never shrink, which stock upstream gets wrong).
  • The standard integrated-webcam control set (brightness…gain, auto exposure, white balance) so ImageCapture.getPhotoCapabilities() is populated. The stock loopback custom controls are removed: chromium resets every visible control to default on open, which pressed timeout_image_io and poisoned every later open into the loopback's timeout mode — the device then reported itself output-only and every later getUserMedia() failed with NotFoundError. That bug made any second camera use impossible; fixed and covered by an open/stop/open probe.
  • STREAMON(CAPTURE) tolerates a briefly-absent producer instead of -EIO.

Feed (camerad):

  • The mixer writes the device directly and holds it for the daemon's lifetime (the producer never detaches, so a renegotiation no longer makes the camera vanish from enumeration or breaks STREAMON mid-switch). Frames are written paced at the negotiated interval with sub-ms jitter — sensor-like timestamps, not network arrival times (measured mediaTime cadence 33.33ms, sd ~2ms). A Go bilinear center-crop/scale follows the negotiated size the way sensor modes crop/bin (720p→1080p ~10ms/frame on a weak vCPU; 720p/480p paths are cheap).
  • Every written frame gets a fresh sensor-noise realization (brightness-scaled temporal + static fixed-pattern, ≤±4 LSB): flat regions grain like a real sensor and no two frames are identical, including repeated content during network stalls and the placeholder.
  • YUYV end to end (packed, as UVC delivers).
  • Ingest node moved out of /dev/video* to /dev/kernel-camera/ingest: everything in the image runs as root, so permissions alone can't keep a page from seeing and selecting the raw feed; chromium only enumerates /dev/video*.
  • Client: shared track asks for detail, 6 Mbps ceiling, maintain-resolution.

Measured in a real Chromium 156 against the spike's fingerprint table: default 640x480, exact/ideal 640x480/1280x720/1920x1080 all resizeMode:"none", 320x240 crop-and-scale, rich photo caps, stable repeated open/stop cycles, zero identical frames. go test/vet pass; the module patch compiles and loads on the pinned guest kernel; the full client build (vue-tsc) and the image build were not run here (the client module transform-checks clean with esbuild). The liveness-vendor retest against the persona was deliberately not run — check vendor terms first.

andrewleesteele and others added 5 commits November 16, 2026 15:42
Let a live-view viewer share their real camera into the browser as a local
camera device, on demand: when a page inside the browser calls getUserMedia()
the viewer's camera turns on, and it turns off when the page releases it.

- server/lib/camera + cmd/camerad: a manager that owns the browser-facing
  loopback device as the single writer, streaming a placeholder frame until the
  viewer shares, then live ingest frames, then back — so chromium never loses
  its source. Reports an on-demand state the live-view client polls.
- wrapper/supervisor/Dockerfile: start camerad and enable neko webcam ingest
  only when a session sets KERNEL_ENABLE_CAMERA=true (rides the live-view path).
- client: a camera controller (kernel/camera.ts) plus shareLocalCamera on the
  neko client; auto start/stop on the on-demand signal, manual toggle, and
  re-request on orientation change.

Scope: this relays a real person's real camera. It does not feed synthetic or
recorded video to a liveness check — liveness vendors reject virtual cameras by
design, and a live test confirmed that; see bench/camera-passthrough-live-view.

Server builds, vets, and tests clean. The browser image build and the neko
client build/UI integration still need to run; the kernel/API camera option is
a companion change. Draft.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A v4l2loopback read blocks forever once its producer goes away. camerad's
ingest reader then kept the device open with the previous session's format,
so the next neko webcam session never reached the browser. Kill and reopen
the reader when no frame arrives for 3s.

Found testing in a real browser: the first share worked, the next never went
live. With the fix, back-to-back shares both go live in about a second.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… consent

From an independent two-pass review of this PR:

- wrapper: set NEKO_CAPTURE_WEBCAM_* before supervisord starts (it was set
  after the fork, so neko never saw it and the feature was inert on the image
  path); always set ENABLED explicitly so the wrapper is the gate; take the
  ingest device from camera.DefaultIngestDevice instead of a hardcoded path; and
  wait on camerad's /healthz before starting neko so the devices exist first.
- manager: replace killOnStall with a per-attempt context cancelled by a stall
  timer, so the same cancel that kills ffmpeg unblocks Wait (the old watchdog
  was retired before Wait and could leave ffmpeg wedged). camerad now secures
  the devices: ingest 0600 (root-only, so chromium can't see or select it) and
  output 0666. Fold the state-file writer into the detector using the canonical
  lib/statefile.WriteJSON (was a hand-rolled copy that swallowed errors). Debounce
  the /proc "wanted" signal across 3 polls so a brief device open (e.g. from
  enumerateDevices) doesn't flip it. One frameFreshFor const + live() accessor
  shared by the mixer and snapshot. Clamp Width/Height/FPS from env. ensureDevices
  checks both nodes.
- client: the controller now gates auto-follow on a one-time manual share
  (consent), so a page cannot turn on the viewer's real camera on its own; fixes
  the poll/timer that kept running after unmount and re-acquired the camera, the
  stop() that couldn't cancel an in-flight start(), manual-off not sticking, and
  a leaked matchMedia listener.
- placeholder is now a plain dark frame (the "Waiting for camera…" text was an
  automation fingerprint).

Re-validated live with the rebuilt camerad: back-to-back shares both go live,
the ingest device stays root-only, and the merged state writer works. The
wrapper env-timing fix is reasoned + builds but is not runtime-verified here (it
runs at image boot; the live test installs neko config directly). The client
controller is still not wired into the app UI — staged for a follow-up.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…ducer

- Portrait video arrived squashed: neko scales whatever it receives straight
  to its fixed webcam size without keeping the aspect ratio (its pipeline is
  hardcoded). The viewer now always sends an upright 1280x720 frame, pillarboxing
  portrait, via a canvas. Rotation just changes the source shape, so the
  stop/re-acquire on orientation change is gone. The image stays unmirrored, as
  a page gets from any webcam.
- Ingest ffmpeg flushes each frame as soon as it is muxed (the tail of every
  frame was waiting in the output buffer for the next one) and uses low-latency
  input flags. The mixer forwards each live frame on arrival instead of sampling
  on a ticker, and only fills gaps with the placeholder. Default mode is 30 fps.
- The ingest reader waits for v4l2loopback to report a producer instead of
  re-opening the device every 300ms, which raced neko's pipeline start on quick
  stop/start and spammed the log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Device realism (browser VM):
- Ship a camera-persona v4l2loopback (images/chromium-headful/camera) built
  for the guest kernel alongside the image: uvcvideo/usb QUERYCAP identity, a
  USB-device sysfs hierarchy so Chromium reads idVendor/idProduct/interface
  like a UVC cam, a realistic discrete mode table (640x480..1920x1080) with
  capture-side negotiation that snaps to the nearest mode, the standard
  integrated-webcam control set (the stock loopback controls are dropped:
  chromium resets every visible control on open, which pressed
  timeout_image_io and poisoned every later open into timeout mode -> the
  device went output-only and every later getUserMedia failed).
- camerad loads the modules with finit_module(2) from /usr/lib/kernel-camera
  (no kmod in the image), falling back to modprobe.
- The ingest node moves out of /dev/video* to /dev/kernel-camera/ingest:
  everything in the image runs as root, so permissions alone cannot keep a
  page from seeing and selecting the raw ingest feed.

Feed realism (camerad):
- The mixer writes the device directly and holds it open for the daemon's
  lifetime: the producer never detaches, so renegotiating the capture mode
  no longer makes the camera briefly disappear or STREAMON fail mid-switch.
  Frames are paced at the negotiated interval with sub-ms jitter (sensor-like
  timestamps) instead of network arrival times, and a Go bilinear crop/scale
  follows the negotiated size (center-crop to aspect, like sensor modes).
- Every frame gets a fresh sensor-noise realization (brightness-scaled
  temporal + static fixed-pattern): flat regions grain like a real sensor
  and no two frames are ever identical, including duplicated content during
  network stalls and the placeholder.
- YUYV end to end, the packed format UVC cameras actually deliver.

Client: the shared track asks for detail, a 6 Mbps ceiling, and
maintain-resolution so the encode doesn't smear flat regions or change size
mid-call.

Validated live (Chromium 156, bench/camera-passthrough-live-view): default
640x480, all modes native (resizeMode none), full ImageCapture photo caps,
stable open/stop/open rounds, mediaTime cadence 33.33ms sd ~2ms, zero
identical frames.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant