mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-02 06:29:37 +08:00
Microphone: kwsnd gains a capture substream fed by the host (SDK option soundIn, the page's Microphone setting and ?mic=0, the CLI's --sound-in-wav and --sound-in). Camera: kwcam is a V4L2 capture device (/dev/video0) fed by the host: I420, NV12 and YUYV at 320x240 to 1280x720, and H.264 encoded by the host's WebCodecs encoder where it has one, with bitrate, GOP and key frame controls (SDK option camera, the page's Camera setting and ?cam=0, the CLI's --camera). The base's rc writes the udev database entry of /dev/video*, so programs that list cameras through libudev find it. kwva (protocol 5): an encode whose input surface is a camera buffer's dma-buf names the frame to the host instead of sending its pixels, and pixels an app writes into an exported surface reach the host (put).
160 lines
8.7 KiB
JavaScript
160 lines
8.7 KiB
JavaScript
#!/usr/bin/env node
|
|
// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// The page's microphone (?mic, js/web/audio-in.ts) in headless Chromium,
|
|
// with Chromium's fake capture device playing a WAV this script writes (a
|
|
// 440 Hz sine at half scale) and its fake permission prompt answering yes.
|
|
// Starts the page's Vite dev server (web/, on --port, default 8093), loads
|
|
// the base shell (?distro=none, no data disk, no network) and, in worker
|
|
// mode, in worker mode without shared memory (?shared=0: the worklet's
|
|
// chunks as messages, pulled from this thread) and inline (?worker=0;
|
|
// --only worker|messages|inline for one), checks:
|
|
//
|
|
// 1 the page offers capture (KW.config.mic) and the guest has
|
|
// /dev/snd/pcmC0D0c, and nothing asked for the microphone at boot
|
|
// (no "[audio in]" line before the first recording)
|
|
// 2 kwrec (guest/src/test/kwrec.c: ALSA hw:0,0 with the raw ioctls, as
|
|
// arecord) records 2 s at 48 kHz S16_LE mono; after the silence until
|
|
// the microphone runs, the samples are the tone: its frequency from
|
|
// the zero crossings within 5% of 440 Hz, its RMS level above 1000
|
|
// 3 /dev/dsp (OSS: 8 kHz U8) gives the tone too, at 8 kHz
|
|
// 4 the page let the microphone go when the guest closed the device
|
|
// ("[audio in] microphone released")
|
|
//
|
|
// node test/mic-check.mjs [--port N] [--only worker|messages|inline] [--chrome BIN] [--server URL] [--keep]
|
|
//
|
|
// Needs a bundle with kwrec (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, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { findChrome, sleep, startServer } from "../web/test/lib.mjs";
|
|
|
|
const args = process.argv.slice(2);
|
|
const opt = (n, d) => (args.includes(n) ? args[args.indexOf(n) + 1] : d);
|
|
const port = Number(opt("--port", "8093"));
|
|
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-mic-"));
|
|
// The fake microphone: 10 s of 440 Hz at half scale, 48 kHz mono S16 (Chromium loops it).
|
|
const RATE = 48000, n = RATE * 10;
|
|
const wav = Buffer.alloc(44 + n * 2);
|
|
wav.write("RIFF", 0); wav.writeUInt32LE(36 + n * 2, 4); wav.write("WAVEfmt ", 8);
|
|
wav.writeUInt32LE(16, 16); wav.writeUInt16LE(1, 20); wav.writeUInt16LE(1, 22); wav.writeUInt32LE(RATE, 24);
|
|
wav.writeUInt32LE(RATE * 2, 28); wav.writeUInt16LE(2, 32); wav.writeUInt16LE(16, 34); wav.write("data", 36); wav.writeUInt32LE(n * 2, 40);
|
|
for (let i = 0; i < n; i++) wav.writeInt16LE(Math.round(16383 * Math.sin(2 * Math.PI * 440 * i / RATE)), 44 + i * 2);
|
|
writeFileSync(join(dir, "tone.wav"), wav);
|
|
|
|
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", `--use-file-for-fake-audio-capture=${join(dir, "tone.wav")}`,
|
|
`--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);
|
|
|
|
// The guest's analysis of a raw S16 or U8 mono recording: samples, first non-silent one, RMS and zero crossings after it.
|
|
const analyse = (file, type, silence, center) => `od -An -v -t${type} ${file} | awk '{ for (i = 1; i <= NF; i++) { v = $i - ${center}; n++; if (!f && $i != ${silence}) f = n; if (f) { s += v * v; m++; if (p < 0 && v >= 0) z++; p = v } } } END { printf "n=%d first=%d rms=%.1f crossings=%d\\n", n, f, m ? sqrt(s / m) : 0, z }'`;
|
|
const parse = (out) => Object.fromEntries([...out.matchAll(/(\w+)=([\d.]+)/g)].map((m) => [m[1], Number(m[2])]));
|
|
|
|
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 (/\[audio in\]|kwsnd/.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");
|
|
|
|
for (const mode of ["worker", "messages", "inline"]) {
|
|
if (only && only !== mode) continue;
|
|
lines = [];
|
|
const url = `${base}/?distro=none&data=0&net=0&cpus=1&autosuspend=0&askleave=0&autohide=0${mode === "inline" ? "&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)");
|
|
const cfg = await evaluate("JSON.stringify({ mic: KW.config.mic, sound: KW.config.sound, worker: KW.config.worker, isolated: crossOriginIsolated })");
|
|
const snd = await exec("ls /dev/snd; dmesg | grep kwsnd");
|
|
report(`${mode}: capture offered, nothing asked at boot`, JSON.parse(cfg).mic === true && /pcmC0D0c/.test(snd) && /with capture/.test(snd) && !lines.some((l) => /\[audio in\]/.test(l)),
|
|
`${cfg}; ${snd.trim().replace(/\s+/g, " ")}`);
|
|
|
|
say(`${mode}: kwrec 2 s at 48 kHz`);
|
|
const a = parse(await exec(`kwrec 48000 1 s16 96000 /tmp/m.raw && ${analyse("/tmp/m.raw", "d2", 0, 0)}`));
|
|
const hz = a.crossings / ((a.n - a.first) / 48000);
|
|
report(`${mode}: kwrec records the microphone's tone`, a.n === 96000 && a.first > 0 && a.n - a.first > 24000 && Math.abs(hz - 440) < 22 && a.rms > 1000,
|
|
`${JSON.stringify(a)}: ${hz.toFixed(1)} Hz over ${((a.n - a.first) / 48000).toFixed(2)} s after ${(a.first / 48000).toFixed(2)} s of silence`);
|
|
|
|
say(`${mode}: /dev/dsp 2 s at 8 kHz U8`);
|
|
const d = parse(await exec(`dd if=/dev/dsp of=/tmp/d.raw bs=16000 count=1 2>/dev/null; ${analyse("/tmp/d.raw", "u1", 128, 128)}`));
|
|
const hz2 = d.crossings / ((d.n - d.first) / 8000);
|
|
report(`${mode}: /dev/dsp records the tone`, d.n === 16000 && d.n - d.first > 4000 && Math.abs(hz2 - 440) < 22 && d.rms > 8,
|
|
`${JSON.stringify(d)}: ${hz2.toFixed(1)} Hz`);
|
|
|
|
await sleep(500);
|
|
report(`${mode}: the microphone is released at close`, lines.some((l) => /\[audio in\] microphone released/.test(l)) && (await evaluate("KW.vm.soundIn?.state.open")) === false,
|
|
lines.filter((l) => /\[audio in\]/.test(l)).join(" | "));
|
|
}
|
|
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);
|
|
}
|