Files
unkernel/test/camera-check.mjs
Pooya Parsa b033dc7b50 web: add desktop themes: KDE Plasma, GNOME, iOS, Android and Windows 2000
A theme is a stylesheet under :root[data-desktop] and React parts in place of the top bar, the Dock, the launcher and a window's title bar (web/src/themes); it loads when first shown and switches without a reload. Without a choice the device picks it: iOS, Android, else KDE.

Also: the desktop's headless core (window manager, commands, apps, pins) moves to web/src/core with its tests; terminal tabs are drawn by the theme's title bar; Settings and System get a sidebar drawer in narrow windows; the first paint is a minimal splash; the console's auto-hide is removed.
2026-12-02 20:27:00 +00:00

284 lines
17 KiB
JavaScript

#!/usr/bin/env node
// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// The page's camera (?cam, js/web/camera.ts) in headless Chromium, with
// Chromium's fake capture device (a moving pattern with a frame counter)
// and its fake permission prompt answering yes. Starts the page's Vite dev
// server (web/, on --port, default 8094), loads the base shell
// (?distro=none, no data disk, no network) and, in worker mode, in worker
// mode without shared memory (?shared=0: the frames as messages), inline
// (?worker=0), inline without MediaStreamTrackProcessor ("video": a <video>
// element's frames as VideoFrames, the path of browsers with WebCodecs and
// no processor) and inline without MediaStreamTrackProcessor and VideoFrame
// ("fallback": a <video> element and a canvas, the path of browsers
// without them; --only worker|messages|inline|video|fallback for one),
// checks:
//
// 1 the page offers the camera (KW.config.cam), the guest has
// /dev/video0 (kwcam), and nothing asked for the camera at boot (no
// "[camera]" line before the first stream but the H.264 probe's)
// 2 kwcap (guest/src/test/kwcap.c: V4L2 MMAP streaming, as v4l2-ctl
// --stream-mmap) streams 45 frames of 640x480 YUYV at 30 fps: after
// the black frames until the camera runs, at least 15 are not black,
// most of them differ from the one before (the fake camera moves), the
// last one has a picture (its Y bytes, read in the guest, span more
// than 50 levels: the fake camera's dark green field and its bright
// pacman, counter and corners; 255 where its 4:2:0 planes are copied,
// about 80 through a canvas, whose RGB is limited to Y 16-235), and
// they came at the rate asked (the timestamps)
// 3 the same with 320x240 NV12 at 15 fps (20 frames), and 640x480 I420
// (kwcam's default format) at 30 fps (45 frames)
// 4 the page let the camera go when the guest stopped streaming
// ("[camera] camera released", vm.camera.format null) after each
// 5 H.264 (not in "fallback"): the page offers it where the browser's
// VideoEncoder makes it (kwcam's boot line says so; the headless
// Chromium here has OpenH264), and kwcap h264 copies 45 chunks of
// 640x480 at 30 fps: a key frame with SPS and PPS first, key-frame
// flags where the stream has IDR slices, at the rate asked; the
// stream copied out of the guest decodes in the page's VideoDecoder,
// every chunk a frame of 640x480, and the last one is the camera's
// picture (its Y spans more than 50 levels; the first ones may be the
// black frames encoded until the camera ran); every SPS in the stream
// has the same VUI colour description (the black frames are tagged
// with the camera's colour space, which the raw streams before taught
// the page), the page switched from black to the camera within the
// stream, and no two chunks are more than 4 intervals apart (a late
// camera frame is repeated, so more is a hole; inline a busy page
// thread delays the encoder's timer by up to 3 intervals); then 4
// as above
//
// node test/camera-check.mjs [--port N] [--only worker|messages|inline|video|fallback] [--chrome BIN] [--server URL] [--keep]
//
// Needs a bundle with kwcap (any build without KW_RELEASE=1). Exit 0 when
// every check passed, 1 on a failure, 2 when it could not run.
import { spawn } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { findChrome, sleep, startServer } from "../web/test/lib.mjs";
import { annexBUnits, parseSps, unescapeRbsp } from "../js/core/va-h264.ts";
const args = process.argv.slice(2);
const opt = (n, d) => (args.includes(n) ? args[args.indexOf(n) + 1] : d);
const port = Number(opt("--port", "8094"));
const only = opt("--only");
const chromeBin = opt("--chrome", process.env.CHROME || findChrome());
const t0 = performance.now();
const say = (s) => console.log(`[${((performance.now() - t0) / 1000).toFixed(1)}] ${s}`);
let fails = 0;
const report = (name, ok, detail) => {
console.log(`${ok ? "PASS" : "FAIL"} ${name} ${detail}`);
if (!ok) fails++;
};
const dir = mkdtempSync(join(tmpdir(), "kw-cam-"));
const serverUrl = opt("--server");
const base = serverUrl ? serverUrl.replace(/\/$/, "") : `http://127.0.0.1:${port}`;
say(serverUrl ? `the running server ${base}` : `dev server on 127.0.0.1:${port}`);
const server = serverUrl ? { kill: async () => {} } : await startServer({ port, host: "127.0.0.1", dev: true }).catch((e) => {
console.error(`the dev server did not start: ${e.message}`);
process.exit(2);
});
const dport = 30000 + Math.floor(Math.random() * 20000);
// --disable-dev-shm-usage: a container's /dev/shm (64 MiB by default) runs out by the second page
// load, and Chromium then fails the kernel worker's script with net::ERR_INSUFFICIENT_RESOURCES.
const chrome = spawn(chromeBin, [
"--headless=new", "--no-sandbox", "--hide-scrollbars", "--disable-dev-shm-usage", "--autoplay-policy=no-user-gesture-required",
"--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream",
`--remote-debugging-port=${dport}`, `--user-data-dir=${join(dir, "profile")}`, "about:blank",
], { stdio: ["ignore", "ignore", "ignore"] });
const cleanup = async () => {
chrome.kill("SIGKILL");
await server.kill();
if (!args.includes("--keep")) rmSync(dir, { recursive: true, force: true });
};
const watchdog = setTimeout(async () => {
console.error("no result within 600 s");
await cleanup();
process.exit(2);
}, 600000);
/** FNV-1a of a black frame (Y 16, Cb Cr 128), as kwcap prints it. */
const blackFnv = (format, w, h) => {
const planar = format === "nv12" || format === "i420", n = planar ? w * h * 3 / 2 : w * h * 2;
let x = 2166136261;
for (let i = 0; i < n; i++) {
const v = planar ? (i < w * h ? 16 : 128) : (i % 2 ? 128 : 16);
x = Math.imul(x ^ v, 16777619) >>> 0;
}
return x.toString(16).padStart(8, "0");
};
const parseChunks = (out) => [...out.matchAll(/^frame (\d+) seq (\d+) bytes (\d+) fnv ([0-9a-f]{8}) ms ([\d.]+) key ([01])$/gm)]
.map((m) => ({ seq: Number(m[2]), bytes: Number(m[3]), ms: Number(m[5]), key: m[6] === "1" }));
const parseFrames = (out) => [...out.matchAll(/^frame (\d+) seq (\d+) bytes (\d+) fnv ([0-9a-f]{8}) ms ([\d.]+)$/gm)]
.map((m) => ({ seq: Number(m[2]), fnv: m[4], ms: Number(m[5]) }));
try {
let target;
for (let i = 0; i < 100 && !target; i++) {
await sleep(100);
try { target = (await (await fetch(`http://127.0.0.1:${dport}/json/list`)).json()).find((t) => t.type === "page"); } catch {}
}
if (!target) throw new Error(`${chromeBin} did not start`);
const ws = new WebSocket(target.webSocketDebuggerUrl);
await new Promise((r, j) => { ws.onopen = r; ws.onerror = j; });
let id = 0;
const pending = new Map();
let lines = [];
ws.onmessage = (m) => {
const msg = JSON.parse(m.data);
if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); }
if (msg.method === "Runtime.consoleAPICalled") {
const line = msg.params.args.map((a) => a.value ?? a.description).join(" ");
lines.push(line);
if (/\[camera\]|kwcam/.test(line)) say(`page: ${line}`);
}
};
const send = (method, params = {}) => new Promise((r) => {
pending.set(++id, r);
ws.send(JSON.stringify({ id, method, params }));
});
const evaluate = async (expression) => {
const r = await send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
if (r.result?.exceptionDetails) throw new Error(r.result.exceptionDetails.exception?.description ?? r.result.exceptionDetails.text);
return r.result?.result?.value;
};
const exec = (cmd) => evaluate(`KW.vm.exec("sh", ["-c", ${JSON.stringify(cmd)}], { timeout: 120000 }).then((r) => r.stdout + r.stderr)`);
await send("Runtime.enable");
const stream = async (mode, format, w, h, fps, count) => {
const before = lines.length;
say(`${mode}: kwcap ${format} ${w}x${h} at ${fps} fps, ${count} frames`);
// The range of the last frame's Y bytes (YUYV: every other byte; NV12: the first plane).
const awkY = (step) => `awk 'BEGIN { lo = 255; hi = 0 } { for (i = 1; i <= NF; i += ${step}) { if ($i < lo) lo = $i; if ($i > hi) hi = $i } } END { printf "yrange=%d\\n", hi - lo }'`;
const planar = format === "nv12" || format === "i420";
const ymean = planar ? `head -c ${w * h} /tmp/last.raw | od -An -v -tu1 | ${awkY(1)}` : `od -An -v -tu1 /tmp/last.raw | ${awkY(2)}`;
const out = await exec(`kwcap ${format} ${w} ${h} ${fps} ${count} /tmp/c.raw && tail -c ${planar ? w * h * 3 / 2 : w * h * 2} /tmp/c.raw > /tmp/last.raw && ${ymean}`);
const frames = parseFrames(out);
const black = blackFnv(format, w, h);
const pictures = frames.filter((f) => f.fnv !== black);
let changed = 0;
for (let i = 1; i < pictures.length; i++) if (pictures[i].fnv !== pictures[i - 1].fnv) changed++;
const ym = Number(/yrange=(\d+)/.exec(out)?.[1] ?? 0);
const span = frames.length > 1 ? frames.at(-1).ms - frames[0].ms : 0;
const want = (frames.at(-1)?.seq - frames[0]?.seq) * 1000 / fps;
const summary = /kwcap: .*/.exec(out)?.[0] ?? out.trim().slice(-300);
report(`${mode}: ${format} ${w}x${h}: the guest captures the camera's moving picture`,
frames.length === count && pictures.length >= Math.min(15, count / 2) && changed >= pictures.length / 2 && ym > 50 && span >= want * 0.95,
`${summary}; ${pictures.length} of ${frames.length} not black, ${changed} changed, last frame's Y range ${ym}, ${span.toFixed(0)} ms (${want.toFixed(0)} at the rate)`);
await sleep(500);
const released = lines.slice(before).some((l) => /\[camera\] camera released/.test(l));
const fmt = await evaluate("JSON.stringify(KW.vm.camera?.format ?? null)");
report(`${mode}: ${format}: the camera is released when the guest stops`, released && fmt === "null",
lines.slice(before).filter((l) => /\[camera\]/.test(l)).join(" | "));
};
const released = async (mode, before, what) => {
await sleep(500);
const done = lines.slice(before).some((l) => /\[camera\] camera released/.test(l));
const fmt = await evaluate("JSON.stringify(KW.vm.camera?.format ?? null)");
report(`${mode}: ${what}: the camera is released when the guest stops`, done && fmt === "null",
lines.slice(before).filter((l) => /\[camera\]/.test(l)).join(" | "));
};
const streamH264 = async (mode, w, h, fps, count) => {
const before = lines.length;
say(`${mode}: kwcap h264 ${w}x${h} at ${fps} fps, ${count} chunks`);
const out = await exec(`kwcap h264 ${w} ${h} ${fps} ${count} /tmp/c.264`);
const cs = parseChunks(out);
const summary = /kwcap: .*/.exec(out)?.[0] ?? out.trim().slice(-300);
const b64 = (await exec("base64 /tmp/c.264 | tr -d '\\n'")).trim();
const span = cs.length > 1 ? cs.at(-1).ms - cs[0].ms : 0;
const want = (cs.length - 1) * 1000 / fps;
const gap = cs.slice(1).reduce((m, c, i) => Math.max(m, c.ms - cs[i].ms), 0);
// every SPS's VUI colour description (video_signal_type), in stream order
const bin = Buffer.from(b64, "base64");
const vuis = [];
let off = 0;
for (const c of cs) {
for (const u of annexBUnits(new Uint8Array(bin.subarray(off, off + c.bytes)))) {
if ((u[0] & 31) !== 7) continue;
const sig = parseSps(unescapeRbsp(u)).vui?.signal;
vuis.push(sig ? `${sig.fullRange ? "full" : "limited"} ${sig.colour ? `${sig.colour.primaries}/${sig.colour.transfer}/${sig.colour.matrix}` : "unspecified"}` : "none");
}
off += c.bytes;
}
const switched = lines.slice(before).some((l) => /\[camera\] the guest gets the camera/.test(l));
report(`${mode}: h264 ${w}x${h}: one colour description from the first key frame through the switch to the camera, and no hole`,
vuis.length >= 2 && new Set(vuis).size === 1 && switched && gap <= 4 * 1000 / fps,
`${vuis.length} SPS: ${[...new Set(vuis)].join(" | ")}; black to camera within the stream: ${switched}; longest gap ${gap.toFixed(1)} ms`);
// the copied stream through the page's decoder: each chunk at its size, with the guest's key-frame flags
const dec = JSON.parse(await evaluate(`(async () => {
const bin = Uint8Array.from(atob(${JSON.stringify(b64)}), (c) => c.charCodeAt(0));
const cs = ${JSON.stringify(cs.map((c) => [c.bytes, c.key]))};
const nals = (b) => { const t = []; for (let i = 0; i + 3 < b.length; i++) if (b[i] === 0 && b[i + 1] === 0 && b[i + 2] === 1) t.push(b[i + 3] & 31); return t; };
const hex = (n) => n.toString(16).padStart(2, "0");
const sps = bin.indexOf(0x67, 3);
const codec = "avc1." + hex(bin[sps + 1]) + hex(bin[sps + 2]) + hex(bin[sps + 3]);
let decoded = 0, err = null, last = null, o = 0, idrKeys = 0, firstTypes = null, sizes = new Set();
const d = new VideoDecoder({ output: (f) => { decoded++; sizes.add(f.displayWidth + "x" + f.displayHeight); last?.close(); last = f; }, error: (e) => (err = String(e)) });
d.configure({ codec, optimizeForLatency: true });
cs.forEach(([n, key], i) => {
const data = bin.subarray(o, o + n);
o += n;
const t = nals(data);
if (i === 0) firstTypes = t.join(",");
if (key === t.includes(5)) idrKeys++;
d.decode(new EncodedVideoChunk({ type: key ? "key" : "delta", timestamp: i * 33333, data }));
});
await d.flush().catch((e) => (err = String(e)));
let yrange = 0;
if (last) {
const buf = new Uint8Array(last.allocationSize());
const layout = await last.copyTo(buf);
let lo = 255, hi = 0;
for (let y = 0; y < last.codedHeight; y += 2) for (let x = 0; x < last.displayWidth; x += 2) { const v = buf[layout[0].offset + y * layout[0].stride + x]; lo = Math.min(lo, v); hi = Math.max(hi, v); }
yrange = hi - lo;
last.close();
}
return JSON.stringify({ codec, bytes: bin.length, decoded, err, sizes: [...sizes], yrange, idrKeys, firstTypes });
})()`));
const encLine = lines.slice(before).find((l) => /\[camera\] H\.264 encoder:/.test(l)) ?? "(no encoder line)";
report(`${mode}: h264 ${w}x${h}: the guest copies the browser's H.264 and it decodes`,
cs.length === count && cs[0]?.key && dec.firstTypes?.startsWith("7,8") && dec.idrKeys === count && dec.decoded === count && !dec.err
&& dec.sizes.length === 1 && dec.sizes[0] === `${w}x${h}` && dec.yrange > 50 && span >= want * 0.9 && /compressed, sizeimage \d+, frameioc refused/.test(summary),
`${summary}; ${cs.filter((c) => c.key).length} key frames; ${JSON.stringify(dec)}; ${span.toFixed(0)} ms (${want.toFixed(0)} at the rate); ${encLine}`);
await released(mode, before, "h264");
};
for (const mode of ["worker", "messages", "inline", "video", "fallback"]) {
if (only && only !== mode) continue;
lines = [];
const url = `${base}/?distro=none&data=0&net=0&cpus=1&autosuspend=0&askleave=0&desktop=unkernel${mode === "inline" || mode === "video" || mode === "fallback" ? "&worker=0" : mode === "messages" ? "&worker=1&shared=0" : "&worker=1"}`;
say(`open ${url}`);
await send("Page.navigate", { url });
await sleep(500);
for (let i = 0; i < 600 && !(await evaluate("typeof globalThis.KW?.ready === 'function' && !!globalThis.KW.config").catch(() => false)); i++) await sleep(200);
await evaluate("KW.ready().then(() => 1)");
if (mode === "fallback") await evaluate("delete globalThis.MediaStreamTrackProcessor; delete globalThis.VideoFrame; typeof MediaStreamTrackProcessor + typeof VideoFrame");
if (mode === "video") await evaluate("delete globalThis.MediaStreamTrackProcessor; typeof MediaStreamTrackProcessor");
const cfg = await evaluate("JSON.stringify({ cam: KW.config.cam, worker: KW.config.worker, isolated: crossOriginIsolated })");
const dev = await exec("cat /sys/class/video4linux/video0/name; ls /dev/video0; dmesg | grep kwcam");
report(`${mode}: camera offered, nothing asked at boot`, JSON.parse(cfg).cam === true && /^kwcam$/m.test(dev) && /\/dev\/video0/.test(dev) && !lines.some((l) => /\[camera\]/.test(l) && !/H\.264 (offered|probe)|does not make H\.264/.test(l)),
`${cfg}; ${dev.trim().replace(/\s+/g, " ")}`);
await stream(mode, "yuyv", 640, 480, 30, 45);
if (mode === "fallback" || mode === "video") report(`${mode}: frames came through a video element`,
lines.some((l) => /frames through a video element/.test(l)) && lines.some((l) => /\(video\)/.test(l)), lines.filter((l) => /\[camera\]/.test(l)).slice(0, 3).join(" | "));
await stream(mode, "nv12", 320, 240, 15, 20);
await stream(mode, "i420", 640, 480, 30, 45);
if (mode === "fallback") continue;
const h264 = /kwcam: video0, YUV420, NV12, YUYV and H\.264/.test(dev);
report(`${mode}: H.264 offered (this Chromium's VideoEncoder makes it)`, h264 && lines.some((l) => /\[camera\] H\.264 offered/.test(l)), dev.trim().replace(/\s+/g, " "));
if (h264) await streamH264(mode, 640, 480, 30, 45);
}
clearTimeout(watchdog);
await cleanup();
console.log(fails ? `${fails} check(s) failed` : "all checks passed");
process.exit(fails ? 1 : 0);
} catch (e) {
console.error(e);
clearTimeout(watchdog);
await cleanup();
process.exit(2);
}