mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-02 00:59:32 +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).
438 lines
21 KiB
TypeScript
438 lines
21 KiB
TypeScript
// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// The camera to the VA-API encoder without the pixels crossing (va.md,
|
|
// Camera to encoder; va/PROTOCOL.md "enc", src.camera): the host's frame
|
|
// store (camera.ts CameraFrameStore), the kernel's frame import writing
|
|
// each frame's id (CameraHost, inline and through the worker's mailbox),
|
|
// and VaHost on a fake vsock and a fake WebCodecs whose encoder keeps every
|
|
// frame's planes: frames named by id are encoded from the host's copy,
|
|
// bit for bit what the guest's buffer got (patternSource, the CLI's
|
|
// --camera), or from the camera's VideoFrame where it is exactly that;
|
|
// what the host cannot take is refused (the driver then sends the pixels):
|
|
// a frame gone, a new stream, a restore (a new store), another size, ids
|
|
// that are wrong, malformed or of another type; nothing is left open.
|
|
import assert from "node:assert/strict";
|
|
import { test } from "node:test";
|
|
import { CameraFrameStore, CameraFramesReader, CameraFramesWriter, CameraHost, createCameraFrames, patternSource, type CameraFormat, type CameraVideoFrame } from "../js/core/camera.ts";
|
|
import { prepareVa, startVa, type VaHost } from "../js/core/va.ts";
|
|
import { fakeWebCodecs, guest, type Guest } from "./va-fake.ts";
|
|
|
|
const FOURCC_NV12 = 0x3231564e, FOURCC_YUYV = 0x56595559;
|
|
const nv12Format = (w: number, h: number): CameraFormat => ({ pixelFormat: "NV12", width: w, height: h, fps: 30, bytes: w * h + w * ((h + 1) >> 1) });
|
|
const hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
|
|
// ---- a fake camera VideoFrame: its own NV12 planes, with a colour space ----
|
|
|
|
const BT601 = { primaries: "smpte170m", transfer: "smpte170m", matrix: "smpte170m", fullRange: false };
|
|
|
|
class CamFrame implements CameraVideoFrame {
|
|
static open = 0;
|
|
static twice = 0;
|
|
displayWidth: number;
|
|
displayHeight: number;
|
|
visibleRect: { x: number; y: number; width: number; height: number };
|
|
#closed = false;
|
|
readonly data: Uint8Array;
|
|
readonly width: number;
|
|
readonly height: number;
|
|
readonly colorSpace: typeof BT601;
|
|
constructor(data: Uint8Array, width: number, height: number, colorSpace: typeof BT601) {
|
|
this.data = data;
|
|
this.width = width;
|
|
this.height = height;
|
|
this.colorSpace = colorSpace;
|
|
this.displayWidth = width;
|
|
this.displayHeight = height;
|
|
this.visibleRect = { x: 0, y: 0, width, height };
|
|
CamFrame.open++;
|
|
}
|
|
get closed() {
|
|
return this.#closed;
|
|
}
|
|
clone(): CamFrame {
|
|
if (this.#closed) throw new Error("clone of a closed frame");
|
|
return new CamFrame(this.data, this.width, this.height, this.colorSpace);
|
|
}
|
|
close() {
|
|
if (this.#closed) CamFrame.twice++;
|
|
else CamFrame.open--;
|
|
this.#closed = true;
|
|
}
|
|
}
|
|
|
|
// ---- a fake encoder side that keeps each frame's visible NV12 planes ----
|
|
|
|
function fakeEnc() {
|
|
const encoded: { y: Uint8Array; uv: Uint8Array; viaFrame: boolean; colour: unknown }[] = [];
|
|
const frames = { open: 0, twice: 0 };
|
|
class VideoFrame {
|
|
timestamp: number;
|
|
visibleRect: { x: number; y: number; width: number; height: number };
|
|
displayWidth: number;
|
|
displayHeight: number;
|
|
planes: { y: Uint8Array; uv: Uint8Array; viaFrame: boolean; colour: unknown };
|
|
#closed = false;
|
|
constructor(src: Uint8Array | VideoFrame | CamFrame, init: any) {
|
|
if (src instanceof Uint8Array) {
|
|
const l = init.layout, vr = init.visibleRect ?? { x: 0, y: 0, width: init.codedWidth, height: init.codedHeight };
|
|
if (init.format !== "NV12" || !l || l.length !== 2) throw new Error("not NV12");
|
|
const w = vr.width, h = vr.height, y = new Uint8Array(w * h), uv = new Uint8Array(w * ((h + 1) >> 1));
|
|
for (let r = 0; r < h; r++) y.set(src.subarray(l[0].offset + r * l[0].stride, l[0].offset + r * l[0].stride + w), r * w);
|
|
for (let r = 0; r < (h + 1) >> 1; r++) uv.set(src.subarray(l[1].offset + r * l[1].stride, l[1].offset + r * l[1].stride + w), r * w);
|
|
this.planes = { y, uv, viaFrame: false, colour: init.colorSpace };
|
|
this.visibleRect = vr;
|
|
} else if (src instanceof CamFrame) {
|
|
if (src.closed) throw new Error("a closed camera frame");
|
|
const n = src.width * src.height;
|
|
this.planes = { y: src.data.slice(0, n), uv: src.data.slice(n), viaFrame: true, colour: src.colorSpace };
|
|
this.visibleRect = init.visibleRect ?? src.visibleRect;
|
|
} else {
|
|
if (src.closed) throw new Error("a closed frame");
|
|
this.planes = src.planes;
|
|
this.visibleRect = init.visibleRect ?? src.visibleRect;
|
|
}
|
|
this.displayWidth = this.visibleRect.width;
|
|
this.displayHeight = this.visibleRect.height;
|
|
this.timestamp = init.timestamp ?? 0;
|
|
frames.open++;
|
|
}
|
|
get closed() {
|
|
return this.#closed;
|
|
}
|
|
close() {
|
|
if (this.#closed) frames.twice++;
|
|
else frames.open--;
|
|
this.#closed = true;
|
|
}
|
|
}
|
|
class VideoEncoder {
|
|
state = "unconfigured";
|
|
encodeQueueSize = 0;
|
|
#out: (c: any) => void;
|
|
#n = 0;
|
|
constructor(i: { output: (c: any) => void; error: (e: Error) => void }) {
|
|
this.#out = i.output;
|
|
}
|
|
static async isConfigSupported(c: any) {
|
|
return { supported: String(c.codec).startsWith("vp09.00") };
|
|
}
|
|
configure() {
|
|
this.state = "configured";
|
|
}
|
|
encode(f: VideoFrame, opts: any) {
|
|
if (f.closed) throw new Error("encode of a closed frame");
|
|
const n = ++this.#n, ts = f.timestamp, idx = encoded.push(f.planes) - 1;
|
|
queueMicrotask(() => this.#out({ type: opts?.keyFrame || n === 1 ? "key" : "delta", timestamp: ts, byteLength: 4, copyTo: (d: Uint8Array) => new DataView(d.buffer, d.byteOffset).setUint32(0, idx, true) }));
|
|
}
|
|
async flush() {}
|
|
close() {
|
|
this.state = "closed";
|
|
}
|
|
}
|
|
return { wc: { VideoEncoder, VideoFrame }, encoded, frames };
|
|
}
|
|
|
|
/** VAEncPictureParameterBufferVP9 (132 bytes): a w x h frame. */
|
|
function vp9Pic(w: number, h: number, key: boolean): Uint8Array {
|
|
const b = new Uint8Array(132), dv = new DataView(b.buffer);
|
|
dv.setUint32(0, w, true), dv.setUint32(4, h, true), dv.setUint32(8, w, true), dv.setUint32(12, h, true);
|
|
dv.setUint32(60, (key ? 0 : 1) | 2, true);
|
|
b[64] = 0xff;
|
|
b[65] = 100;
|
|
return b;
|
|
}
|
|
|
|
async function withHost(fn: (g: Guest, host: VaHost, store: CameraFrameStore, enc: ReturnType<typeof fakeEnc>) => Promise<void>, store = new CameraFrameStore()) {
|
|
const glob = globalThis as Record<string, unknown>;
|
|
const dec = fakeWebCodecs({ name: "decode order", hold: 0, honourReorder: false, drop: false, ts: "pass" });
|
|
const enc = fakeEnc();
|
|
Object.assign(glob, { VideoDecoder: dec.VideoDecoder, EncodedVideoChunk: dec.EncodedVideoChunk, VideoEncoder: enc.wc.VideoEncoder, VideoFrame: enc.wc.VideoFrame });
|
|
const g = guest();
|
|
const host = startVa(prepareVa(true, true, () => {}), g.vsock, () => {}, undefined, store)!;
|
|
try {
|
|
g.connect();
|
|
await fn(g, host, store, enc);
|
|
} finally {
|
|
host.shutdown();
|
|
for (const k of ["VideoDecoder", "EncodedVideoChunk", "VideoEncoder", "VideoFrame"]) delete glob[k];
|
|
}
|
|
}
|
|
|
|
let r = 1000, picId = 0;
|
|
/** An `enc` as the driver sends it for a camera buffer: a request when it names a frame (`camera`), else the pixels with why. */
|
|
async function encCamera(g: Guest, ctx: number, w: number, h: number, src: object, pixels?: Uint8Array, key = false): Promise<{ pic: number; reply: any }> {
|
|
const pp = vp9Pic(w, h, key), pic = ++picId, id = ++r;
|
|
const bin = new Uint8Array(pp.length + (pixels?.length ?? 0));
|
|
bin.set(pp);
|
|
if (pixels) bin.set(pixels, pp.length);
|
|
const isCam = "camera" in src;
|
|
g.send({ op: "enc", ctx, surface: 0x30000001, pic, profile: "vp9.0", bufs: [[23, pp.length, 1]], src, ...(isCam ? { r: id } : {}) }, bin);
|
|
const reply = isCam ? (await g.next((f) => f.json.r === id)).json : null;
|
|
return { pic, reply };
|
|
}
|
|
const codedOf = (g: Guest, pic: number) => g.next((f) => f.json.ev === "coded" && f.json.pic === pic);
|
|
/** the encoded planes of a coded notice (the fake's chunk is the frame's index) */
|
|
const planesOf = (enc: ReturnType<typeof fakeEnc>, bin: Uint8Array) => enc.encoded[new DataView(bin.buffer, bin.byteOffset).getUint32(0, true)]!;
|
|
|
|
/** The guest's camera: a CameraHost on a fake kernel memory, its frame import as the kernel's timer calls it. */
|
|
function camera(store: CameraFrameStore | undefined, source = patternSource()) {
|
|
const mem = new WebAssembly.Memory({ initial: 64 });
|
|
const host = new CameraHost({ enabled: source, store, memory: () => mem });
|
|
const imp = host.imports() as any;
|
|
imp.wasm_driver_camera_init();
|
|
const BUF = 4096, ID = 64;
|
|
return {
|
|
host,
|
|
start: (w: number, h: number, fourcc = FOURCC_NV12) => imp.wasm_driver_camera_stream(fourcc, w, h, 1, 30),
|
|
stop: () => imp.wasm_driver_camera_stream(0, 0, 0, 0, 0),
|
|
/** a frame into "a buffer": its pixels and the id the kernel keeps with it */
|
|
frame: (bytes: number) => {
|
|
new Uint8Array(mem.buffer, ID, 16).fill(0);
|
|
const got = Number(imp.wasm_driver_camera_frame(BigInt(BUF), BigInt(bytes), BigInt(ID)));
|
|
return { got, pixels: new Uint8Array(mem.buffer, BUF, bytes).slice(), id: new Uint8Array(mem.buffer, ID, 16).slice() };
|
|
},
|
|
/** an older kernel: no id argument */
|
|
frameOld: (bytes: number) => Number(imp.wasm_driver_camera_frame(BigInt(BUF), BigInt(bytes))),
|
|
};
|
|
}
|
|
|
|
test("CameraFrameStore: fresh 128-bit ids, nothing kept until asked, then the frames as written, bounded, forgotten at a stop", () => {
|
|
const s = new CameraFrameStore(), f = nv12Format(32, 16);
|
|
const px = (v: number) => new Uint8Array(f.bytes).fill(v);
|
|
const a = s.add(px(1), f)!, b = s.add(px(2), f)!;
|
|
assert.equal(a.length, 16);
|
|
assert.notEqual(hex(a), hex(b));
|
|
assert.equal(s.stats().kept, 0, "not armed: nothing kept");
|
|
assert.equal(s.take(hex(a), 32, 16), "not kept yet");
|
|
const c = s.add(px(3), f)!;
|
|
const e = s.take(hex(c), 32, 16);
|
|
assert.ok(typeof e !== "string" && e.data[0] === 3 && e.data.length === f.bytes);
|
|
assert.equal(s.take(hex(c), 64, 16), "size");
|
|
assert.equal(s.take(hex(a), 32, 16), "gone");
|
|
for (const bad of [42, null, {}, "x", hex(c).toUpperCase(), hex(c) + "0", "../" + hex(c)]) assert.equal(s.take(bad, 32, 16), "a bad id");
|
|
// the store's copy: later writes into the guest's buffer do not change it
|
|
const buf = px(7), d = s.add(buf, f)!;
|
|
buf.fill(9);
|
|
assert.equal((s.take(hex(d), 32, 16) as { data: Uint8Array }).data[0], 7);
|
|
// at most 16 kept, the oldest go first
|
|
const ids = Array.from({ length: 20 }, (_, i) => s.add(px(i), f)!);
|
|
assert.equal(s.stats().kept, 16);
|
|
assert.equal(s.take(hex(ids[0]!), 32, 16), "gone");
|
|
assert.equal((s.take(hex(ids[19]!), 32, 16) as { data: Uint8Array }).data[0], 19);
|
|
// YUYV: no ids (the encoder takes NV12)
|
|
assert.equal(s.add(new Uint8Array(32 * 16 * 2), { pixelFormat: "YUYV", width: 32, height: 16, fps: 30, bytes: 32 * 16 * 2 }), null);
|
|
s.stop();
|
|
assert.equal(s.stats().kept, 0);
|
|
assert.equal(s.take(hex(ids[19]!), 32, 16), "not kept yet", "a stop forgets, and disarms");
|
|
});
|
|
|
|
test("CameraFrameStore: the camera's VideoFrame of the newest frame only (one held), closed when it goes", () => {
|
|
const s = new CameraFrameStore(), f = nv12Format(8, 4);
|
|
s.take("0".repeat(32), 8, 4); // arm
|
|
const frames = [0, 1, 2].map((i) => new CamFrame(new Uint8Array(f.bytes).fill(i), 8, 4, BT601));
|
|
const ids = frames.map((fr) => s.add(new Uint8Array(f.bytes).fill(1), f, () => fr)!);
|
|
for (const fr of frames) fr.close(); // the source's own; the store holds clones
|
|
assert.equal(CamFrame.open, 1, "one clone held");
|
|
assert.equal((s.take(hex(ids[0]!), 8, 4) as { frame: unknown }).frame, null);
|
|
assert.ok((s.take(hex(ids[2]!), 8, 4) as { frame: unknown }).frame);
|
|
s.stop();
|
|
assert.equal(CamFrame.open, 0);
|
|
assert.equal(CamFrame.twice, 0);
|
|
});
|
|
|
|
test("CameraHost: the frame import writes the frame and the store's id of it; none without a store, YUYV or an older kernel", () => {
|
|
const store = new CameraFrameStore();
|
|
const cam = camera(store);
|
|
const f = nv12Format(64, 32);
|
|
cam.start(64, 32);
|
|
const a = cam.frame(f.bytes);
|
|
assert.equal(a.got, f.bytes);
|
|
assert.ok(a.id.some((x) => x), "an id");
|
|
assert.equal(store.take(hex(a.id), 64, 32), "not kept yet");
|
|
const b = cam.frame(f.bytes);
|
|
const e = store.take(hex(b.id), 64, 32);
|
|
assert.ok(typeof e !== "string");
|
|
assert.deepEqual(e.data, b.pixels, "the store's copy is what the buffer got");
|
|
assert.equal(cam.frameOld(f.bytes), f.bytes, "a kernel without the id argument still gets frames");
|
|
// a new stream forgets the last one's frames
|
|
cam.stop();
|
|
cam.start(64, 32);
|
|
assert.equal(store.take(hex(b.id), 64, 32), "not kept yet");
|
|
// YUYV: frames, no id
|
|
cam.stop();
|
|
cam.start(64, 32, FOURCC_YUYV);
|
|
const y = cam.frame(64 * 32 * 2);
|
|
assert.equal(y.got, 64 * 32 * 2);
|
|
assert.ok(y.id.every((x) => !x));
|
|
// no store (no VA host): no id
|
|
const plain = camera(undefined);
|
|
plain.start(64, 32);
|
|
const p = plain.frame(f.bytes);
|
|
assert.equal(p.got, f.bytes);
|
|
assert.ok(p.id.every((x) => !x));
|
|
});
|
|
|
|
test("worker mode: the frame mailbox carries each frame's id with it", () => {
|
|
const buf = createCameraFrames(1024);
|
|
const w = new CameraFramesWriter(buf), rd = new CameraFramesReader(buf);
|
|
const id = Uint8Array.from({ length: 16 }, (_, i) => i * 17 + 1);
|
|
w.slot(100).fill(5);
|
|
w.publish(1, 100, id);
|
|
const out = new Uint8Array(100);
|
|
assert.ok(rd.read(out, 1));
|
|
assert.deepEqual(rd.id(), id);
|
|
w.slot(100).fill(6);
|
|
w.publish(1, 100, null);
|
|
assert.ok(rd.read(out, 1));
|
|
assert.equal(out[0], 6);
|
|
assert.equal(rd.id(), null);
|
|
});
|
|
|
|
test("VaHost: camera frames named by id are encoded from the host's copy, bit for bit; the pixels where it has none; lying ids refused", async () => {
|
|
await withHost(async (g, host, store, enc) => {
|
|
const hello = await g.call({ op: "hello", version: 5 });
|
|
assert.equal(hello.json.camera, true);
|
|
const W = 64, H = 48, f = nv12Format(W, H);
|
|
assert.equal((await g.call({ op: "ctx", id: 2, profile: "vp9.0", width: W, height: H, entry: "enc", rc: "cbr" })).json.err, undefined);
|
|
const cam = camera(store);
|
|
cam.start(W, H);
|
|
// the first frame asked for: not kept yet (the store keeps frames from then on); the driver sends its pixels
|
|
const f0 = cam.frame(f.bytes);
|
|
const a = await encCamera(g, 2, W, H, { camera: { id: hex(f0.id), width: W, height: H, seq: 0 } }, undefined, true);
|
|
assert.equal(a.reply.err, "not kept yet");
|
|
const a2 = await encCamera(g, 2, W, H, { pixels: { gen: 1, width: W, height: H, pitch: W }, why: "host" }, f0.pixels, true);
|
|
assert.deepEqual(planesOf(enc, (await codedOf(g, a2.pic)).bin).y, f0.pixels.subarray(0, W * H));
|
|
// then each frame by id: nothing sent, and the encoder gets exactly the buffer's pixels
|
|
for (let i = 1; i <= 5; i++) {
|
|
const fr = cam.frame(f.bytes);
|
|
const x = await encCamera(g, 2, W, H, { camera: { id: hex(fr.id), width: W, height: H, seq: i } });
|
|
assert.deepEqual(x.reply, { r: x.reply.r });
|
|
const p = planesOf(enc, (await codedOf(g, x.pic)).bin);
|
|
assert.deepEqual(p.y, fr.pixels.subarray(0, W * H), `frame ${i}: Y`);
|
|
assert.deepEqual(p.uv, fr.pixels.subarray(W * H), `frame ${i}: CbCr`);
|
|
assert.equal(p.viaFrame, false);
|
|
assert.deepEqual(p.colour, BT601, "tagged as the guest's pixels are");
|
|
}
|
|
// a frame named twice (two buffers got the same frame, or an encode again): the same picture
|
|
const twice = cam.frame(f.bytes);
|
|
for (let k = 0; k < 2; k++) {
|
|
const x = await encCamera(g, 2, W, H, { camera: { id: hex(twice.id), width: W, height: H, seq: 9 } });
|
|
assert.deepEqual(planesOf(enc, (await codedOf(g, x.pic)).bin).y, twice.pixels.subarray(0, W * H));
|
|
}
|
|
// what the host refuses (the reply says why, no picture is made, the stream goes on)
|
|
const refused = async (src: object) => {
|
|
const before = host.stats.encode.pictures;
|
|
const x = await encCamera(g, 2, W, H, src);
|
|
assert.equal(host.stats.encode.pictures, before, "no picture");
|
|
return x.reply.err;
|
|
};
|
|
assert.equal(await refused({ camera: { id: "0".repeat(32), width: W, height: H } }), "gone");
|
|
assert.equal(await refused({ camera: { id: hex(twice.id), width: W * 2, height: H } }), "size");
|
|
assert.equal(await refused({ camera: { id: hex(twice.id), width: -1, height: 1e9 } }), "size");
|
|
for (const id of [12, null, { $: 1 }, [1, 2], "f".repeat(31), "g".repeat(32), "f".repeat(4096), hex(twice.id).toUpperCase()]) assert.equal(await refused({ camera: { id, width: W, height: H } }), "a bad id");
|
|
assert.equal(await refused({ camera: "nonsense" }), "size");
|
|
// a frame gone: 16 newer ones evict it
|
|
const old = cam.frame(f.bytes);
|
|
for (let i = 0; i < 16; i++) cam.frame(f.bytes);
|
|
assert.equal(await refused({ camera: { id: hex(old.id), width: W, height: H } }), "gone");
|
|
// a new stream (stop, start): the last stream's frames are gone, the next is kept again after it is asked for
|
|
cam.stop();
|
|
cam.start(W, H);
|
|
assert.equal(await refused({ camera: { id: hex(twice.id), width: W, height: H } }), "not kept yet");
|
|
const after = cam.frame(f.bytes);
|
|
const y = await encCamera(g, 2, W, H, { camera: { id: hex(after.id), width: W, height: H } });
|
|
assert.equal(y.reply.err, undefined);
|
|
assert.deepEqual(planesOf(enc, (await codedOf(g, y.pic)).bin).y, after.pixels.subarray(0, W * H));
|
|
// an encode context that does not exist: the picture fails by its notice (the reply says nothing more)
|
|
const z = await encCamera(g, 99, W, H, { camera: { id: hex(after.id), width: W, height: H } });
|
|
assert.equal(z.reply.err, undefined);
|
|
assert.match((await codedOf(g, z.pic)).json.err, /no encode context/);
|
|
// the driver's reasons for sending pixels are counted
|
|
const px = cam.frame(f.bytes);
|
|
const w = await encCamera(g, 2, W, H, { pixels: { gen: 2, width: W, height: H, pitch: W }, why: "not dequeued" }, px.pixels);
|
|
await codedOf(g, w.pic);
|
|
// a reason the host does not know (a guest's own words) is counted as "other", not as a key of its own
|
|
const w2 = await encCamera(g, 2, W, H, { pixels: { gen: 0, width: W, height: H, pitch: W }, why: "x".repeat(500) }, px.pixels);
|
|
await codedOf(g, w2.pic);
|
|
const st = host.stats;
|
|
assert.equal(st.encode.camera, 8);
|
|
assert.equal(st.encode.cameraFrames, 0);
|
|
assert.deepEqual(st.encode.cameraFallbacks, { "not kept yet": 2, gone: 2, size: 3, "a bad id": 8, "not dequeued": 1, other: 1 });
|
|
assert.ok(st.camera && st.camera.taken === 8);
|
|
assert.equal(enc.frames.open, 0);
|
|
assert.equal(enc.frames.twice, 0);
|
|
});
|
|
});
|
|
|
|
test("VaHost: the camera's own VideoFrame where it is exactly the frame and BT.601 limited; else the host's copy; a restore (a new store) knows no old id", async () => {
|
|
CamFrame.open = 0;
|
|
const W = 32, H = 16, f = nv12Format(W, H);
|
|
let n = 0, colour = BT601;
|
|
// a source with VideoFrames: frame n's pixels, and its VideoFrame (the camera's own)
|
|
let last: CamFrame | null = null;
|
|
const source = {
|
|
read(out: Uint8Array) {
|
|
out.fill(n & 0xff, 0, W * H);
|
|
out.fill(128, W * H);
|
|
last?.close();
|
|
last = new CamFrame(out.slice(), W, H, colour);
|
|
n++;
|
|
return true;
|
|
},
|
|
lastFrame: () => last,
|
|
};
|
|
await withHost(async (g, host, store, enc) => {
|
|
await g.call({ op: "hello", version: 5 });
|
|
await g.call({ op: "ctx", id: 3, profile: "vp9.0", width: W, height: H, entry: "enc", rc: "cbr" });
|
|
const cam = camera(store, source);
|
|
cam.start(W, H);
|
|
const f0 = cam.frame(f.bytes);
|
|
assert.equal((await encCamera(g, 3, W, H, { camera: { id: hex(f0.id), width: W, height: H } })).reply.err, "not kept yet");
|
|
const f1 = cam.frame(f.bytes);
|
|
const x = await encCamera(g, 3, W, H, { camera: { id: hex(f1.id), width: W, height: H } });
|
|
const p = planesOf(enc, (await codedOf(g, x.pic)).bin);
|
|
assert.equal(p.viaFrame, true, "the camera's VideoFrame itself");
|
|
assert.deepEqual(p.y, f1.pixels.subarray(0, W * H));
|
|
// another colour space: the host's copy instead (tagged as the guest's pixels, so one stream is alike)
|
|
colour = { ...BT601, matrix: "bt709", primaries: "bt709", transfer: "bt709" };
|
|
const f2 = cam.frame(f.bytes);
|
|
const y = await encCamera(g, 3, W, H, { camera: { id: hex(f2.id), width: W, height: H } });
|
|
const q = planesOf(enc, (await codedOf(g, y.pic)).bin);
|
|
assert.equal(q.viaFrame, false);
|
|
assert.deepEqual(q.y, f2.pixels.subarray(0, W * H));
|
|
assert.equal(host.stats.encode.cameraFrames, 1);
|
|
cam.stop();
|
|
assert.equal(enc.frames.open, 0);
|
|
(last as CamFrame | null)?.close();
|
|
assert.equal(CamFrame.open, 0, "every camera frame closed");
|
|
assert.equal(CamFrame.twice, 0);
|
|
});
|
|
// a restored machine has a new host and store: ids of before are unknown to it, so the driver sends pixels
|
|
await withHost(async (g) => {
|
|
await g.call({ op: "hello", version: 5 });
|
|
await g.call({ op: "ctx", id: 3, profile: "vp9.0", width: W, height: H, entry: "enc", rc: "cbr" });
|
|
const x = await encCamera(g, 3, W, H, { camera: { id: "ab".repeat(16), width: W, height: H } });
|
|
assert.equal(x.reply.err, "not kept yet");
|
|
});
|
|
});
|
|
|
|
test("VaHost: without a store (no camera, or va.camera false) the hello says so, and a camera src is refused", async () => {
|
|
const glob = globalThis as Record<string, unknown>;
|
|
const dec = fakeWebCodecs({ name: "decode order", hold: 0, honourReorder: false, drop: false, ts: "pass" });
|
|
const enc = fakeEnc();
|
|
Object.assign(glob, { VideoDecoder: dec.VideoDecoder, EncodedVideoChunk: dec.EncodedVideoChunk, VideoEncoder: enc.wc.VideoEncoder, VideoFrame: enc.wc.VideoFrame });
|
|
for (const [opts, store] of [[true, undefined], [{ camera: false }, new CameraFrameStore()]] as const) {
|
|
const g = guest();
|
|
const host = startVa(prepareVa(opts, true, () => {}), g.vsock, () => {}, undefined, store)!;
|
|
try {
|
|
g.connect();
|
|
assert.equal((await g.call({ op: "hello", version: 5 })).json.camera, false);
|
|
await g.call({ op: "ctx", id: 2, profile: "vp9.0", width: 16, height: 16, entry: "enc", rc: "cbr" });
|
|
assert.equal((await encCamera(g, 2, 16, 16, { camera: { id: "ab".repeat(16), width: 16, height: 16 } })).reply.err, "not kept here");
|
|
} finally {
|
|
host.shutdown();
|
|
}
|
|
}
|
|
for (const k of ["VideoDecoder", "EncodedVideoChunk", "VideoEncoder", "VideoFrame"]) delete glob[k];
|
|
});
|