Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions bench/camera-passthrough-live-view/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Camera passthrough for live view — reproduction & findings

Harness and findings behind the production code in this PR (`server/lib/camera`,
`server/cmd/camerad`, the wrapper/neko wiring, the client controller in
`images/chromium-headful/client/src/kernel/camera.ts`, and the camera kernel
modules in `images/chromium-headful/camera/`). Follows the guest-kernel /
loopback-module spike in kernel-images#515.

## What this enables

A live-view viewer shares their **real** camera into the browser so a page
inside it can use it. On demand: the viewer's camera turns on when a page calls
`getUserMedia()` and off when it stops. This is for a real person completing
their own camera step — **not** for feeding synthetic or recorded video to a
liveness check.

## Findings (validated in a real browser, 2026-11-16; device work 2026-11-19)

1. **Passthrough works.** A page's `getUserMedia()` auto-starts the viewer's
camera; the browser receives live 1280×720; the camera stops ~3s after the
page releases it. Verified on the WebRTC getUserMedia sample.

2. **The device presents as an ordinary integrated webcam.** The
camera-persona v4l2loopback (see `images/chromium-headful/camera/`) plus
the camerad mixer make the loopback look and behave like local hardware to
a page, measured in Chromium 156 against the spike's fingerprint table:

| Signal | Stock loopback (spike) | Now |
| --- | --- | --- |
| Label | `Integrated Camera` (no USB suffix) | `Integrated Camera` via the USB `interface` file, `uvcvideo`/`usb-…` QUERYCAP (vid:pid files in place; see note) |
| Native modes | one (the producer's) | 640x480, 800x600, 1280x720, 1920x1080, all `resizeMode:"none"` |
| `getUserMedia({video:true})` default | 1280x720 | 640x480 (like a real cam) |
| `{width:{exact:1920}}` | `OverconstrainedError` | 1920x1080 native |
| `{resizeMode:"none", width:640}` | 1280x720 | 640x480 |
| ImageCapture photo caps | imageWidth/Height only | brightness, contrast, saturation, sharpness, exposure, white balance, color temperature |
| Frame cadence | network-paced | paced 33.33ms ±1ms jitter (mediaTime sd ≈2.5ms) |
| Flat-region pixels | codec-smooth | sensor-like grain (temporal + fixed-pattern), no two frames identical |
| open → stop → open | `NotFoundError` (loopback timeout mode) | stable across rounds |

Note on the label suffix: the sysfs `idVendor`/`idProduct` files are in
place for clients that read them, but current Chromium does not append
`(vid:pid)` to the JS label for every device, and integrated cameras
attached over CSI (no USB) genuinely show no suffix, so this is a weak
signal at worst.

3. **Liveness SDKs.** A widely used browser liveness demo was observed
(2026-11-16) to refuse the *stock* loopback session with a "3rd-party app
is modifying the video / suspicious webcam configuration" error. Whether
the persona device passes is not re-tested here — check the vendor's
terms before testing a relayed feed against a live liveness demo; the
point of the persona is that flows with a real, present person are not
false-flagged as *injected* video, not to carry recorded/synthetic video
(which remains out of scope and is exactly what those checks exist for).

4. **Orientation (known limitation).** Capture is pinned to 1280×720 landscape
end to end, so rotating a phone does not change the camera aspect. The client
controller re-requests `getUserMedia` on `orientationchange`; native
per-orientation device caps (reloading the loopback) remain a follow-up.

## Reproduce against a running browser (no image build)

Inside a browser VM (the modules are built for the guest kernel by
`images/chromium-headful/camera/build-modules.sh`):

```sh
# load the loopback pair, run the manager, enable neko webcam ingest
camerad & # loads /usr/lib/kernel-camera/*.ko itself
NEKO_CAPTURE_WEBCAM_ENABLED=true NEKO_CAPTURE_WEBCAM_DEVICE=/dev/kernel-camera/ingest \
supervisorctl restart neko
```

`kernel-camera.injected.js` is the exact client controller used in the live
test, as a drop-in `<script>` for a browser where you can't rebuild the neko
client; `src/kernel/camera.ts` is the same logic as a real client module.

## Local validation without a browser VM

On any machine running the matching guest kernel (e.g. a Hypeship task VM):
build the modules with `images/chromium-headful/camera/` (docker, bookworm),
insmod them, run camerad, feed the ingest device a pattern with ffmpeg
(`-f v4l2 /dev/kernel-camera/ingest`), and point a local Chromium's CDP at the
probes (`bun install` once): `fp.ts` (fingerprint dump), `cycle.ts` (open/stop
rounds), `timing.ts` (cadence + noise), `grab.ts` (save a page frame as PNG).
That is how the table above was measured.
13 changes: 13 additions & 0 deletions bench/camera-passthrough-live-view/camwatch.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#!/bin/bash
# Publishes whether a page in Chrome is using the camera (prototype).
STATE=/var/www/camera-state.json
last=""
while true; do
chrome=false
for p in $(pgrep -u kernel chrom); do
if ls -l /proc/$p/fd 2>/dev/null | grep -q '/dev/video0'; then chrome=true; break; fi
done
s="{\"wanted\":$chrome}"
if [ "$s" != "$last" ]; then echo "$s" > $STATE.tmp && mv $STATE.tmp $STATE; chmod 644 $STATE; last="$s"; echo "$(date +%T) $s"; fi
sleep 0.3
done
47 changes: 47 additions & 0 deletions bench/camera-passthrough-live-view/cycle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Open/stop the camera repeatedly and report per-attempt results.
// usage: bun cycle.ts <cdp-url> [rounds]
import { chromium } from "playwright-core";

const browser = await chromium.connectOverCDP(process.argv[2] ?? "http://127.0.0.1:9222");
const ctx = browser.contexts()[0];
await ctx.grantPermissions(["camera"], { origin: "https://webrtc.github.io" });
const page = await ctx.newPage();
await page.goto("https://webrtc.github.io/samples/src/content/getusermedia/gum/");
const rounds = parseInt(process.argv[3] ?? "6", 10);
for (let i = 0; i < rounds; i++) {
const constraint = i % 2 === 0 ? true : { width: { exact: 1280 }, height: { exact: 720 } };
const out = await page.evaluate(async (c: any) => {
try {
const s = await navigator.mediaDevices.getUserMedia({ video: c });
const t = s.getVideoTracks()[0];
await new Promise((r) => setTimeout(r, 400));
const se = t.getSettings();
// measure inter-frame timing over ~1s via rVFC
const video = document.createElement("video");
video.srcObject = s;
await video.play();
const deltas: number[] = [];
let last = 0;
await new Promise<void>((resolve) => {
const cb = (now: number, meta: any) => {
if (last) deltas.push(meta.mediaTime ? 0 : now - last);
last = now;
if (deltas.length >= 25) resolve();
else video.requestVideoFrameCallback(cb);
};
video.requestVideoFrameCallback(cb);
});
t.stop();
video.remove();
const d = deltas.slice(1);
const avg = d.reduce((a, b) => a + b, 0) / d.length;
const sd = Math.sqrt(d.reduce((a, b) => a + (b - avg) ** 2, 0) / d.length);
return `${se.width}x${se.height}@${se.frameRate} rVFC avg=${avg.toFixed(1)}ms sd=${sd.toFixed(2)}ms n=${d.length}`;
} catch (e: any) {
return `FAIL ${e.name}: ${e.message}`;
}
}, constraint);
console.log(`round ${i} (${constraint}): ${out}`);
}
await page.close();
await browser.close();
49 changes: 49 additions & 0 deletions bench/camera-passthrough-live-view/fp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Dump what a page can observe about the camera.
// usage: bun fp.ts <cdp-url>
import { chromium } from "playwright-core";

const browser = await chromium.connectOverCDP(process.argv[2] ?? "http://127.0.0.1:9222");
const ctx = browser.contexts()[0];
await ctx.grantPermissions(["camera"], { origin: "https://webrtc.github.io" });
const page = await ctx.newPage();
await page.goto("https://webrtc.github.io/samples/src/content/getusermedia/gum/");
const out = await page.evaluate(async () => {
const strip = (o: any) => { const { deviceId, groupId, ...rest } = o; return rest; };
const r: any = {};
r.supportedConstraints = Object.keys(navigator.mediaDevices.getSupportedConstraints()).length;
const s = await navigator.mediaDevices.getUserMedia({ video: true });
const t = s.getVideoTracks()[0];
r.devices = (await navigator.mediaDevices.enumerateDevices()).map((d) => `${d.kind}:${d.label}`);
r.label = t.label;
r.contentHint = t.contentHint;
r.settings = strip(t.getSettings());
r.capabilities = strip(t.getCapabilities());
try {
const ic = new (window as any).ImageCapture(t);
r.photoCapabilities = await ic.getPhotoCapabilities();
r.photoSettings = await ic.getPhotoSettings();
} catch (e) { r.imageCapture = String(e); }
t.stop();
r.resolutions = {};
for (const [w, h] of [[320, 240], [640, 480], [1280, 720], [1920, 1080]]) {
for (const mode of ["exact", "ideal"]) {
try {
const c = mode === "exact" ? { width: { exact: w }, height: { exact: h } } : { width: w, height: h };
const st = await navigator.mediaDevices.getUserMedia({ video: c });
const se = st.getVideoTracks()[0].getSettings();
r.resolutions[`${mode} ${w}x${h}`] = `${se.width}x${se.height} resize=${se.resizeMode}`;
st.getTracks().forEach((x) => x.stop());
} catch (e: any) { r.resolutions[`${mode} ${w}x${h}`] = e.name; }
}
}
try {
const st = await navigator.mediaDevices.getUserMedia({ video: { resizeMode: "none", width: 640 } });
const se = st.getVideoTracks()[0].getSettings();
r.nativeOnly640 = `${se.width}x${se.height}`;
st.getTracks().forEach((x) => x.stop());
} catch (e: any) { r.nativeOnly640 = e.name; }
return r;
});
console.log(JSON.stringify(out, null, 1));
await page.close();
await browser.close();
21 changes: 21 additions & 0 deletions bench/camera-passthrough-live-view/grab.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { chromium } from "playwright-core";
const browser = await chromium.connectOverCDP(process.argv[2] ?? "http://127.0.0.1:9222");
const ctx = browser.contexts()[0];
await ctx.grantPermissions(["camera"], { origin: "https://webrtc.github.io" });
const page = await ctx.newPage();
await page.goto("https://webrtc.github.io/samples/src/content/getusermedia/gum/");
const data = await page.evaluate(async () => {
const s = await navigator.mediaDevices.getUserMedia({ video: true });
const video = document.createElement("video");
video.muted = true; video.srcObject = s;
await video.play();
await new Promise((r) => setTimeout(r, 1500));
const c = document.createElement("canvas");
c.width = video.videoWidth; c.height = video.videoHeight;
c.getContext("2d")!.drawImage(video, 0, 0);
return c.toDataURL("image/png");
});
const base64 = data.split(",")[1];
await Bun.write("/tmp/page-frame.png", Buffer.from(base64, "base64"));
console.log("saved", data.length);
await browser.close();
80 changes: 80 additions & 0 deletions bench/camera-passthrough-live-view/kernel-camera.injected.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// NOTE: this harness auto-follows the on-demand signal for automated testing and
// omits the one-time consent gate the product controller (client/src/kernel/camera.ts)
// enforces. camera.ts is authoritative.
// Prototype: camera on demand for live view. Not production code.
// When a page inside the Kernel browser asks for the camera, the viewer's camera turns on
// automatically; when the page stops using it, it turns off. The button is a manual override.
(function () {
function client() { const el = document.querySelector("#neko"); return el && el.__vue__ && el.__vue__.$client; }
function connected() { const c = client(); return c && c._peer && ["connected", "completed"].includes(c._peer.iceConnectionState); }
let stream = null, shaped = null, sender = null, manual = false, starting = false, idleSince = 0;
// Always send an upright 1280x720 frame: neko scales whatever it receives to the
// browser's camera mode without keeping aspect, so portrait would be squashed.
// Portrait is pillarboxed; rotation needs no re-acquire. Not mirrored (like any webcam).
function toLandscape(src) {
const W = 1280, H = 720, v = document.createElement("video");
v.muted = true; v.playsInline = true; v.srcObject = new MediaStream([src]);
v.style.cssText = "position:fixed;width:1px;height:1px;opacity:0;pointer-events:none"; document.body.appendChild(v);
const c = document.createElement("canvas"); c.width = W; c.height = H; const g = c.getContext("2d");
const out = c.captureStream(30); let live = true;
const schedule = () => { if (live) v.requestVideoFrameCallback ? v.requestVideoFrameCallback(draw) : requestAnimationFrame(draw); };
const draw = () => { const w = v.videoWidth, h = v.videoHeight;
if (w && h) { const k = Math.min(W / w, H / h); g.fillStyle = "#000"; g.fillRect(0, 0, W, H); g.drawImage(v, (W - w * k) / 2, (H - h * k) / 2, w * k, h * k); }
schedule(); };
v.play().then(schedule, schedule);
return { track: out.getVideoTracks()[0], stop() { live = false; out.getTracks().forEach((t) => t.stop()); v.srcObject = null; v.remove(); } };
}
const ui = document.createElement("div");
ui.style.cssText = "position:fixed;left:16px;bottom:16px;z-index:99999;display:flex;flex-direction:column;align-items:flex-start;gap:8px;font:13px system-ui,sans-serif";
const note = document.createElement("div");
note.style.cssText = "padding:6px 10px;border-radius:8px;background:rgba(33,34,37,.88);color:#edeef0;display:none;max-width:280px";
const btn = document.createElement("button");
btn.style.cssText = "padding:9px 15px;border:0;border-radius:999px;font:600 13px system-ui,sans-serif;box-shadow:0 2px 8px rgba(0,0,0,.35);cursor:pointer";
ui.append(note, btn);
const say = (m) => { note.textContent = m || ""; note.style.display = m ? "block" : "none"; };
function render() {
if (stream) { btn.textContent = "● Camera on — stop"; btn.style.background = "#e5484d"; btn.style.color = "#fff"; }
else { btn.textContent = "📷 Camera off"; btn.style.background = "#81b300"; btn.style.color = "#212225"; }
}
async function start(reason) {
if (stream || starting || !connected()) return;
starting = true;
try {
stream = await navigator.mediaDevices.getUserMedia({ video: { width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } }, audio: false });
shaped = toLandscape(stream.getVideoTracks()[0]);
sender = client()._peer.addTrack(shaped.track, new MediaStream([shaped.track]));
say(reason === "auto" ? "The site asked for a camera, so your camera is on." : "");
if (reason === "auto") setTimeout(() => stream && say(""), 5000);
} catch (e) {
stream = null;
say(e.name === "NotAllowedError" ? "Camera blocked. Allow camera access for this page (icon left of the address bar) and try again." : "Camera error: " + e.name);
} finally { starting = false; render(); }
}
function stop() {
const c = client();
try { if (c && c._peer && sender) c._peer.removeTrack(sender); } catch (e) {}
if (shaped) shaped.stop();
if (stream) stream.getTracks().forEach((t) => t.stop());
stream = null; shaped = null; sender = null; render();
}
btn.onclick = () => { if (stream) { manual = false; stop(); say(""); } else { manual = true; start("manual"); } };
async function poll() {
try {
const base = location.pathname.replace(/\/?$/, "/");
const q = location.search ? location.search + "&" : "?";
let r = await fetch(base + "camera-state.json" + q + "t=" + Date.now(), { cache: "no-store" });
if (!r.ok) r = await fetch("camera-state.json?t=" + Date.now(), { cache: "no-store" });
if (r.ok) {
const s = await r.json();
if (s.wanted) { idleSince = 0; if (!stream) start("auto"); }
else if (stream && !manual) {
idleSince = idleSince || Date.now();
if (Date.now() - idleSince > 3000) { stop(); say("The site stopped using the camera, so your camera is off."); setTimeout(() => !stream && say(""), 4000); idleSince = 0; }
}
}
} catch (e) {}
setTimeout(poll, 700);
}
function mount() { document.body.appendChild(ui); render(); poll(); }
document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", mount) : mount();
})();
8 changes: 8 additions & 0 deletions bench/camera-passthrough-live-view/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "camera-passthrough-probes",
"private": true,
"type": "module",
"dependencies": {
"playwright-core": "^1.65.0"
}
}
Loading
Loading