// SPDX-License-Identifier: MIT // Copyright (C) 2026 Pooya Parsa // The camera without a guest or a browser: the pixel conversions and the // test pattern (js/core/camera-pixels.ts), the frame mailbox and the // kernel imports (js/core/camera.ts), and createCamera() (js/web/camera.ts) // on stand-ins for getUserMedia, MediaStreamTrackProcessor and VideoFrame. // The guest's side is in test/api.test.ts (kwcap), the real page's in // test/camera-check.mjs. // // node --test test/camera.test.ts import assert from "node:assert/strict"; import { afterEach, beforeEach, describe, test } from "node:test"; import { CAMERA_FOURCC_I420, CAMERA_FOURCC_NV12, CAMERA_FOURCC_YUYV, blackFrame, cameraFourcc, cameraFrameBytes, cameraPixelFormat, rgbaToI420, rgbaToNv12, rgbaToYuyv, testPattern, yuv420To, type CameraPixelFormat, } from "../js/core/camera-pixels.ts"; import { CameraFramesReader, CameraFramesWriter, CameraHost, createCameraFrames, type CameraFormat } from "../js/core/camera.ts"; import { createCamera, type Camera } from "../js/web/camera.ts"; /** RGBA of a w x h picture where pixel (x, y) is `px(x, y)`. */ const rgba = (w: number, h: number, px: (x: number, y: number) => [number, number, number]) => { const b = new Uint8ClampedArray(w * h * 4); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const [r, g, bl] = px(x, y); b.set([r, g, bl, 255], (y * w + x) * 4); } return b; }; describe("camera pixels", () => { test("frame sizes and fourccs", () => { assert.equal(cameraFrameBytes("YUYV", 640, 480), 614400); assert.equal(cameraFrameBytes("NV12", 1280, 720), 1382400); assert.equal(CAMERA_FOURCC_YUYV, 0x56595559); // "YUYV" little endian assert.equal(CAMERA_FOURCC_NV12, 0x3231564e); // "NV12" assert.equal(cameraFrameBytes("I420", 640, 480), 460800); assert.equal(CAMERA_FOURCC_I420, 0x32315559); // "YU12" (V4L2_PIX_FMT_YUV420) for (const f of ["I420", "NV12", "YUYV", "H264"] as const) assert.equal(cameraPixelFormat(cameraFourcc(f)), f); }); test("RGBA to BT.601 limited range: black, white and the primaries", () => { // [r, g, b] -> [Y, Cb, Cr] by the BT.601 integer formulas. const cases: Array<[[number, number, number], [number, number, number]]> = [ [[0, 0, 0], [16, 128, 128]], [[255, 255, 255], [235, 128, 128]], [[255, 0, 0], [82, 90, 240]], [[0, 255, 0], [144, 54, 34]], [[0, 0, 255], [41, 240, 110]], ]; for (const [c, [Y, U, V]] of cases) { const src = rgba(4, 2, () => c); const yuyv = new Uint8Array(cameraFrameBytes("YUYV", 4, 2)); rgbaToYuyv(src, 4, 2, yuyv); assert.deepEqual([...yuyv.subarray(0, 4)], [Y, U, Y, V], `YUYV of ${c}`); const nv12 = new Uint8Array(cameraFrameBytes("NV12", 4, 2)); rgbaToNv12(src, 4, 2, nv12); assert.deepEqual([...nv12.subarray(0, 8)], Array(8).fill(Y), `NV12 Y of ${c}`); assert.deepEqual([...nv12.subarray(8)], [U, V, U, V], `NV12 CbCr of ${c}`); const i420 = new Uint8Array(cameraFrameBytes("I420", 4, 2)); rgbaToI420(src, 4, 2, i420); assert.deepEqual([...i420], [...Array(8).fill(Y), U, U, V, V], `I420 of ${c}`); } }); test("RGBA chroma is the average of the pixels it covers; each pixel keeps its own Y", () => { // Left pixel of each pair black, right one white: Y alternates, chroma is grey's. const src = rgba(4, 2, (x) => (x & 1 ? [255, 255, 255] : [0, 0, 0])); const yuyv = new Uint8Array(16); rgbaToYuyv(src, 4, 2, yuyv); assert.deepEqual([...yuyv.subarray(0, 8)], [16, 128, 235, 128, 16, 128, 235, 128]); const nv12 = new Uint8Array(12); rgbaToNv12(src, 4, 2, nv12); assert.deepEqual([...nv12.subarray(0, 4)], [16, 235, 16, 235]); assert.deepEqual([...nv12.subarray(8)], [128, 128, 128, 128]); }); /** A 4:2:0 frame w x h with padded rows, Y(x, y) = 10 + x + 8y, Cb = 100 + i, Cr = 200 + i (i the chroma sample). */ const yuv420 = (w: number, h: number, chroma: "I420" | "NV12", pad: number) => { const ys = w + pad, cs = chroma === "I420" ? w / 2 + pad : w + pad; const layout = chroma === "I420" ? [{ offset: 0, stride: ys }, { offset: ys * h, stride: cs }, { offset: ys * h + cs * h / 2, stride: cs }] : [{ offset: 0, stride: ys }, { offset: ys * h, stride: cs }]; const buf = new Uint8Array(ys * h + (chroma === "I420" ? 2 : 1) * cs * h / 2).fill(0xee); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) buf[y * ys + x] = 10 + x + 8 * y; for (let y = 0; y < h / 2; y++) for (let x = 0; x < w / 2; x++) { const i = y * (w / 2) + x; if (chroma === "I420") { buf[layout[1]!.offset + y * cs + x] = 100 + i; buf[layout[2]!.offset + y * cs + x] = 200 + i; } else { buf[layout[1]!.offset + y * cs + 2 * x] = 100 + i; buf[layout[1]!.offset + y * cs + 2 * x + 1] = 200 + i; } } return { buf, layout }; }; for (const chroma of ["I420", "NV12"] as const) test(`${chroma} with padded rows to I420, NV12 and YUYV`, () => { const w = 4, h = 4; const { buf, layout } = yuv420(w, h, chroma, 3); const nv12 = new Uint8Array(cameraFrameBytes("NV12", w, h)); yuv420To(buf, layout, chroma, w, h, "NV12", nv12); assert.deepEqual([...nv12.subarray(0, 16)], Array.from({ length: 16 }, (_, k) => 10 + (k % 4) + 8 * Math.floor(k / 4))); assert.deepEqual([...nv12.subarray(16)], [100, 200, 101, 201, 102, 202, 103, 203]); const yuyv = new Uint8Array(cameraFrameBytes("YUYV", w, h)); yuv420To(buf, layout, chroma, w, h, "YUYV", yuyv); // Row 0 and row 1 share chroma row 0; rows 2 and 3 chroma row 1. assert.deepEqual([...yuyv.subarray(0, 8)], [10, 100, 11, 200, 12, 101, 13, 201]); assert.deepEqual([...yuyv.subarray(8, 16)], [18, 100, 19, 200, 20, 101, 21, 201]); assert.deepEqual([...yuyv.subarray(16, 24)], [26, 102, 27, 202, 28, 103, 29, 203]); const i420 = new Uint8Array(cameraFrameBytes("I420", w, h)); yuv420To(buf, layout, chroma, w, h, "I420", i420); assert.deepEqual([...i420.subarray(0, 16)], [...nv12.subarray(0, 16)]); assert.deepEqual([...i420.subarray(16)], [100, 101, 102, 103, 200, 201, 202, 203], "the Cb plane, then the Cr plane"); }); test("I420 and NV12 of the same picture are the same samples (RGBA, the test pattern)", () => { const w = 16, h = 8; const split = (nv12: Uint8Array) => { const n = w * h, out = nv12.slice(0, n * 3 / 2); for (let i = 0; i < n / 4; i++) { out[n + i] = nv12[n + 2 * i]!; out[n + n / 4 + i] = nv12[n + 2 * i + 1]!; } return out; }; const src = rgba(w, h, (x, y) => [x * 16, y * 30, (x * y) & 255]); const a = new Uint8Array(w * h * 3 / 2), b = a.slice(); rgbaToNv12(src, w, h, a); rgbaToI420(src, w, h, b); assert.deepEqual(b, split(a)); testPattern("NV12", w, h, 3, a); testPattern("I420", w, h, 3, b); assert.deepEqual(b, split(a)); }); test("black frames, as the kernel fills them", () => { const y = new Uint8Array(8), n = new Uint8Array(6), i = new Uint8Array(6); blackFrame("YUYV", 2, 2, y); blackFrame("NV12", 2, 2, n); blackFrame("I420", 2, 2, i); assert.deepEqual([...y], [16, 128, 16, 128, 16, 128, 16, 128]); assert.deepEqual([...n], [16, 16, 16, 16, 128, 128]); assert.deepEqual([...i], [16, 16, 16, 16, 128, 128]); }); for (const f of ["YUYV", "NV12", "I420"] as CameraPixelFormat[]) test(`the test pattern (${f}): the same frame for the same number, another for the next`, () => { const a = new Uint8Array(cameraFrameBytes(f, 320, 240)), b = a.slice(), c = a.slice(); testPattern(f, 320, 240, 7, a); testPattern(f, 320, 240, 7, b); testPattern(f, 320, 240, 8, c); assert.deepEqual(a, b); assert.notDeepEqual(a, c); // The counter's box is white (Y 235) with black digits, in the top left corner; the bars are not grey. assert.equal(a[0], 235); const row = (y: number) => f !== "YUYV" ? a.subarray(y * 320, y * 320 + 320) : a.subarray(y * 640, y * 640 + 640).filter((_, i) => i % 2 === 0); assert.ok(row(10).includes(16), "a digit's ink"); assert.ok(new Set(row(200)).size >= 8, "eight bars"); }); }); describe("camera frame mailbox", () => { test("the reader gets the newest frame of its stream, again until a newer one comes, never another stream's", () => { const buf = createCameraFrames(16); const w = new CameraFramesWriter(buf), r = new CameraFramesReader(buf); const out = new Uint8Array(16); assert.equal(r.read(out, 1), false, "nothing yet"); const put = (gen: number, v: number, bytes = 16) => { w.slot(bytes).fill(v); w.publish(gen, bytes); }; put(1, 5); put(1, 6); assert.equal(r.read(out, 1), true); assert.deepEqual([...out], Array(16).fill(6), "the newest"); assert.equal(r.read(out, 1), true); assert.equal(out[0], 6, "the last one again"); for (let v = 7; v < 20; v++) put(1, v); assert.equal(r.read(out, 1), true); assert.equal(out[0], 19); put(2, 30); assert.equal(r.read(out, 1), false, "a frame of stream 2 for stream 1"); assert.equal(r.read(out, 2), true); assert.equal(out[0], 30); put(2, 31, 8); assert.equal(r.read(out, 2), false, "a frame of another size"); }); }); describe("CameraHost", () => { const memory = new WebAssembly.Memory({ initial: 1 }); test("no camera: init answers -ENODEV", () => { const h = new CameraHost({ enabled: false, memory: () => memory }); assert.equal((h.imports().wasm_driver_camera_init as () => bigint)(), -19n); }); test("a stream: the source is told, frames go into kernel memory, none or a short one is black", () => { const told: Array = []; let have = true; const h = new CameraHost({ enabled: { onStream: (f) => told.push(f), read: (out, f) => { if (have) out.fill(f.width & 0xff); return have; } }, memory: () => memory, }); const im = h.imports() as Record unknown>; assert.equal(im.wasm_driver_camera_init!(), 0n); im.wasm_driver_camera_stream!(CAMERA_FOURCC_NV12, 16, 8, 1, 30); assert.deepEqual(told, [{ pixelFormat: "NV12", width: 16, height: 8, fps: 30, bytes: 192 }]); assert.equal(im.wasm_driver_camera_frame!(1024n, 192n), 192n); assert.equal(new Uint8Array(memory.buffer, 1024, 192).every((v) => v === 16), true); assert.equal(im.wasm_driver_camera_frame!(1024n, 100n), 0n, "not the stream's size"); have = false; assert.equal(im.wasm_driver_camera_frame!(1024n, 192n), 0n, "the source has none"); assert.deepEqual(h.saveState(), { format: told[0] }); im.wasm_driver_camera_stream!(0, 0, 0, 0, 0); assert.equal(told.at(-1), null); assert.deepEqual(h.stats, { starts: 1, stops: 1, frames: 3, blackFrames: 2 }); // A restore replays the stream to the (new) source. const told2: Array = []; const h2 = new CameraHost({ enabled: { onStream: (f) => told2.push(f) }, memory: () => memory }); h2.restoreState({ format: told[0]! }); assert.deepEqual(told2, [told[0]]); assert.equal(h2.streaming, true); }); }); // createCamera() on stand-ins. class Track { stopped = false; listeners: Record void>> = {}; readonly settings: { width: number; height: number; frameRate: number }; constructor(settings: { width: number; height: number; frameRate: number }) { this.settings = settings; } getSettings() { return this.settings; } stop() { this.stopped = true; } addEventListener(ev: string, fn: () => void) { (this.listeners[ev] ??= []).push(fn); } } /** A camera frame: I420 (or NV12) at the track's size, Y = the frame number, Cb 100, Cr 200. */ class FakeFrame { closed = false; readonly format: "I420" | "NV12"; readonly visibleRect: { x: number; y: number; width: number; height: number }; readonly n: number; readonly displayWidth: number; readonly displayHeight: number; /** the layouts copyTo() was asked for (undefined: its own) */ copies: Array | undefined> = []; constructor(n: number, displayWidth: number, displayHeight: number, format: "I420" | "NV12" = "I420") { this.n = n; this.format = format; this.displayWidth = displayWidth; this.displayHeight = displayHeight; this.visibleRect = { x: 0, y: 0, width: displayWidth, height: displayHeight }; } allocationSize() { return this.displayWidth * this.displayHeight * 3 / 2; } /** As VideoFrame.copyTo(): its planes into `dst`, at `layout` where given (else packed), and that layout back. */ async copyTo(dst: Uint8Array, opts?: { layout?: Array<{ offset: number; stride: number }> }) { const w = this.displayWidth, h = this.displayHeight, nv12 = this.format === "NV12"; this.copies.push(opts?.layout); const layout = opts?.layout ?? (nv12 ? [{ offset: 0, stride: w }, { offset: w * h, stride: w }] : [{ offset: 0, stride: w }, { offset: w * h, stride: w / 2 }, { offset: w * h * 5 / 4, stride: w / 2 }]); for (let y = 0; y < h; y++) dst.fill(this.n, layout[0]!.offset + y * layout[0]!.stride, layout[0]!.offset + y * layout[0]!.stride + w); for (let y = 0; y < h / 2; y++) { if (nv12) for (let x = 0; x < w / 2; x++) dst.set([100, 200], layout[1]!.offset + y * layout[1]!.stride + 2 * x); else { dst.fill(100, layout[1]!.offset + y * layout[1]!.stride, layout[1]!.offset + y * layout[1]!.stride + w / 2); dst.fill(200, layout[2]!.offset + y * layout[2]!.stride, layout[2]!.offset + y * layout[2]!.stride + w / 2); } } return layout; } close() { this.closed = true; } } class Env { answer: "grant" | "deny" | "none" = "grant"; asks: MediaStreamConstraints[] = []; tracks: Track[] = []; frames: FakeFrame[] = []; /** Hand the next frame to every open processor. */ push: Array<(f: FakeFrame | null) => void> = []; } let env: Env; const saved = new Map(); function define(name: string, get: () => unknown): void { if (!saved.has(name)) saved.set(name, Object.getOwnPropertyDescriptor(globalThis, name)); Object.defineProperty(globalThis, name, { configurable: true, get }); } const settle = async (): Promise => { for (let i = 0; i < 10; i++) await new Promise((r) => setImmediate(r)); }; describe("createCamera", { concurrency: 1 }, () => { let cam: Camera; let logs: string[]; const F: CameraFormat = { pixelFormat: "YUYV", width: 8, height: 4, fps: 30, bytes: 64 }; const frame = (n: number, w = 8, h = 4, format: "I420" | "NV12" = "I420") => { const f = new FakeFrame(n, w, h, format); env.frames.push(f); for (const p of env.push) p(f); }; beforeEach(() => { env = new Env(); logs = []; define("navigator", () => ({ mediaDevices: { getUserMedia: (c: MediaStreamConstraints) => { env.asks.push(c); if (env.answer === "deny") return Promise.reject(Object.assign(new Error("Permission denied"), { name: "NotAllowedError" })); if (env.answer === "none") return Promise.reject(Object.assign(new Error("Requested device not found"), { name: "NotFoundError" })); const v = c.video as { width: { ideal: number }; height: { ideal: number }; frameRate: { ideal: number } }; const t = new Track({ width: v.width.ideal, height: v.height.ideal, frameRate: v.frameRate.ideal }); env.tracks.push(t); return Promise.resolve({ getTracks: () => [t], getVideoTracks: () => [t] }); }, }, })); define("MediaStreamTrackProcessor", () => class { readable: { getReader(): { read(): Promise<{ value?: FakeFrame; done: boolean }>; cancel(): Promise } }; constructor() { const queue: Array = []; let wake: (() => void) | null = null; env.push.push((f) => { queue.push(f); wake?.(); }); this.readable = { getReader: () => ({ read: async () => { while (!queue.length) await new Promise((r) => { wake = r; }); const f = queue.shift()!; return f ? { value: f, done: false } : { done: true }; }, cancel: async () => {}, }), }; } }); cam = createCamera({ log: (m) => logs.push(m) }); }); afterEach(async () => { await cam.close(); for (const [name, d] of saved) { if (d) Object.defineProperty(globalThis, name, d); else delete (globalThis as Record)[name]; } saved.clear(); }); test("asks for the camera at the stream's start only, with its size and rate, converts frames, and lets it go at the stop", async () => { const out = new Uint8Array(F.bytes); assert.equal(cam.read!(out, F), false, "no frame before a stream"); assert.equal(env.asks.length, 0); cam.onStream!(F); await settle(); assert.equal(env.asks.length, 1); assert.deepEqual(env.asks[0]!.video, { width: { ideal: 8 }, height: { ideal: 4 }, frameRate: { ideal: 30 } }); assert.equal(cam.read!(out, F), false, "black until the first frame"); frame(50); await settle(); assert.equal(cam.state, "running"); assert.equal(cam.read!(out, F), true); assert.deepEqual([...out.subarray(0, 8)], [50, 100, 50, 200, 50, 100, 50, 200], "I420 repacked as YUYV"); assert.equal(cam.currentFrame(), env.frames[0], "the newest VideoFrame, for consumers without a copy"); assert.equal(cam.stats().mode, "processor"); cam.onStream!(null); await settle(); assert.equal(env.tracks[0]!.stopped, true, "the track stops: the camera light goes off"); assert.equal(env.frames[0]!.closed, true); assert.equal(cam.state, "idle"); assert.equal(cam.read!(out, F), false); assert.ok(logs.some((l) => /camera released/.test(l)), logs.join("\n")); }); for (const [src, want] of [["I420", "I420"], ["NV12", "I420"], ["NV12", "NV12"], ["I420", "NV12"]] as const) test(`a ${src} frame into an ${want} stream${src === want ? ": copied straight into the guest's layout" : ""}`, async () => { const f: CameraFormat = { pixelFormat: want, width: 8, height: 4, fps: 30, bytes: 48 }; cam.onStream!(f); await settle(); frame(7, 8, 4, src); await settle(); const out = new Uint8Array(48); assert.equal(cam.read!(out, f), true); assert.deepEqual([...out.subarray(0, 32)], Array(32).fill(7)); assert.deepEqual([...out.subarray(32)], want === "I420" ? [...Array(8).fill(100), ...Array(8).fill(200)] : Array(8).fill([100, 200]).flat()); const copied = env.frames[0]!.copies[0]; if (src === want) assert.deepEqual(copied, want === "I420" ? [{ offset: 0, stride: 8 }, { offset: 32, stride: 4 }, { offset: 40, stride: 4 }] : [{ offset: 0, stride: 8 }, { offset: 32, stride: 8 }]); else assert.equal(copied, undefined, "its own layout, then repacked"); }); test("a track of another size goes through a canvas (none here: the frame fails, and the guest gets black)", async () => { cam.onStream!(F); await settle(); frame(1, 16, 8); await settle(); assert.equal(cam.read!(new Uint8Array(F.bytes), F), false); assert.ok(logs.some((l) => /a frame failed/.test(l)), logs.join("\n")); }); test("a refusal gives black frames and is asked again at the next start", async () => { env.answer = "deny"; cam.onStream!(F); await settle(); assert.equal(cam.state, "denied"); assert.ok(logs.some((l) => /camera: permission denied/.test(l)), logs.join("\n")); assert.equal(cam.read!(new Uint8Array(F.bytes), F), false); cam.onStream!(null); env.answer = "grant"; cam.onStream!(F); await settle(); assert.equal(env.asks.length, 2); frame(9); await settle(); assert.equal(cam.read!(new Uint8Array(F.bytes), F), true); }); test("no camera: unavailable, black frames", async () => { env.answer = "none"; cam.onStream!(F); await settle(); assert.equal(cam.state, "unavailable"); assert.equal(cam.read!(new Uint8Array(F.bytes), F), false); }); });