Files
unkernel/test/camera-h264.test.ts
Pooya Parsa 1b229902b2 Add a guest microphone and camera: kwsnd capture, kwcam (V4L2, raw and host-encoded H.264), and camera frames named to the kwva encoder
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).
2026-11-29 10:23:01 +00:00

677 lines
32 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// The camera's H.264 (kwcam's compressed format) without a guest or a
// browser: the synthetic stream and the Annex B helpers
// (js/core/camera-h264.ts), the drop rules, the queue and the chunk ring
// (js/core/camera-chunks.ts), CameraHost's compressed frame import
// (js/core/camera.ts), and the browser's side on stand-ins for WebCodecs:
// the encoder driver (js/web/camera-encoder.ts) and createCamera()'s
// H.264 (js/web/camera.ts). The guest's side is in test/api.test.ts
// (kwcap h264), the real page's in test/camera-check.mjs.
//
// node --test test/camera-h264.test.ts
import assert from "node:assert/strict";
import { afterEach, beforeEach, describe, test } from "node:test";
import { CAMERA_FOURCC_H264, CAMERA_FOURCC_NV12, cameraFrameBytes } from "../js/core/camera-pixels.ts";
import { CHUNK_QUEUE_MAX, CameraChunkQueue, ChunkRingReader, ChunkRingWriter, KEY_ASK_MS, createChunkRing } from "../js/core/camera-chunks.ts";
import { H264Pattern, H264_PROFILES, avccToAnnexB, constrainBaseline, h264Codec, h264Level, nalTypes, nalUnits, parameterSets, withParameterSets } from "../js/core/camera-h264.ts";
import { CameraHost, patternSource, type CameraChunkSink, type CameraFormat } from "../js/core/camera.ts";
import { CameraEncoder, probeH264, type EncChunk, type EncFrame, type EncWebCodecs, type H264Rung } from "../js/web/camera-encoder.ts";
import { createCamera, type Camera } from "../js/web/camera.ts";
const H = (w: number, h: number, extra: Partial<CameraFormat> = {}): CameraFormat => ({ pixelFormat: "H264", width: w, height: h, fps: 30, bytes: cameraFrameBytes("H264", w, h), ...extra });
/** An Annex B chunk of `n` bytes: a key frame's NAL types 7, 8, 5 (or only 5 without `sets`), else 1. */
const chunk = (n: number, key: boolean, fill = 0x55, sets = true): Uint8Array => {
const b = new Uint8Array(Math.max(n, 16)).fill(fill);
const nal = (at: number, t: number) => b.set([0, 0, 0, 1, (3 << 5) | t], at);
if (key && sets) {
nal(0, 7);
nal(5, 8);
nal(10, 5);
} else nal(0, key ? 5 : 1);
return b.subarray(0, Math.max(n, 16));
};
describe("H.264 helpers", () => {
test("levels and codec strings: the lowest level that takes size, rate and bitrate", () => {
assert.equal(h264Level(320, 240, 30, 230_400), 13);
assert.equal(h264Level(640, 480, 30, 921_600), 30);
assert.equal(h264Level(1280, 720, 30, 2_764_800), 31);
assert.equal(h264Level(1280, 720, 30, 20_000_000), 32, "the bitrate control's top needs 3.2");
assert.equal(h264Level(640, 480, 30, 12_000_000), 31);
assert.equal(h264Codec(H264_PROFILES[0], 1280, 720, 30, 2_764_800), "avc1.42E01F");
assert.equal(h264Codec(H264_PROFILES[1], 640, 480, 15, 500_000), "avc1.4D4016");
assert.equal(h264Codec(H264_PROFILES[2], 320, 240, 30, 230_400), "avc1.64000D");
});
test("a Baseline SPS is marked Constrained Baseline, others are left alone", () => {
// start code, SPS header, profile_idc, constraint flags, level; then a PPS and a slice
const chunk = (idc: number, flags: number) => Uint8Array.of(0, 0, 0, 1, 0x67, idc, flags, 31, 0xaa, 0, 0, 1, 0x68, 0xce, 0, 0, 1, 0x65, 0x88);
const base = chunk(66, 0x80);
assert.equal(constrainBaseline(base), 1);
assert.deepEqual(base, chunk(66, 0xc0), "only constraint_set1_flag is set");
assert.equal(constrainBaseline(base), 0, "already constrained");
for (const [idc, flags] of [[77, 0x00], [100, 0x00], [66, 0xe0]] as const) {
const b = chunk(idc, flags);
assert.equal(constrainBaseline(b), 0);
assert.deepEqual(b, chunk(idc, flags));
}
assert.equal(constrainBaseline(Uint8Array.of(0, 0, 1, 0x67, 66)), 0, "a cut SPS is not touched");
});
test("NAL units, parameter sets and an avcC's as Annex B", () => {
const p = new H264Pattern({ width: 64, height: 48 });
const key = p.frame(0).data;
assert.deepEqual(nalTypes(key), [7, 8, 5]);
const sets = parameterSets(key)!;
assert.deepEqual(nalTypes(sets), [7, 8]);
const slice = key.subarray(nalUnits(key)[2]!.at - 4);
assert.deepEqual(nalTypes(slice), [5]);
assert.equal(withParameterSets(key, null), key, "a key frame with both is kept as it is");
assert.equal(withParameterSets(slice, null), null);
assert.deepEqual(withParameterSets(slice, sets), key, "SPS and PPS put back in front");
// avcC: version, profile, compat, level, 0xff (4-byte lengths), 0xe1 + one SPS, one PPS
const [s, q] = nalUnits(sets).map((u, i, a) => sets.subarray(u.at, i + 1 < a.length ? a[i + 1]!.at - 4 : sets.length));
const avcc = Uint8Array.of(1, s![1]!, s![2]!, s![3]!, 0xff, 0xe1, s!.length >> 8, s!.length & 255, ...s!, 1, q!.length >> 8, q!.length & 255, ...q!);
assert.deepEqual(avccToAnnexB(avcc), sets);
assert.equal(avccToAnnexB(Uint8Array.of(0, 1, 2)), null);
});
test("the synthetic stream: SPS, PPS and IDR, then P frames; key frames every interval and when asked; the same frames for the same calls", () => {
const a = new H264Pattern({ width: 320, height: 240, fps: 30, keyInterval: 5 });
const b = new H264Pattern({ width: 320, height: 240, fps: 30, keyInterval: 5 });
const keys: number[] = [];
for (let n = 0; n < 12; n++) {
const fa = a.frame(n), fb = b.frame(n);
assert.deepEqual(fa.data, fb.data, `frame ${n} is the same bytes`);
assert.deepEqual(nalTypes(fa.data), fa.key ? [7, 8, 5] : [1]);
if (fa.key) keys.push(n);
// emulation prevention: no 00 00 0x (x <= 3) after a NAL header but the start codes
const units = nalUnits(fa.data);
for (const u of units) {
const end = units[units.indexOf(u) + 1]?.at ?? fa.data.length + 4;
const body = fa.data.subarray(u.at + 1, end - 4);
for (let i = 0; i + 2 < body.length; i++) assert.ok(!(body[i] === 0 && body[i + 1] === 0 && body[i + 2]! <= 3), `frame ${n}: an unescaped 00 00 0${body[i + 2]} at ${i}`);
}
}
assert.deepEqual(keys, [0, 5, 10]);
a.keyFrame();
assert.equal(a.frame(12).key, true, "asked for");
assert.equal(a.frame(13).key, false);
const idr = new H264Pattern({ width: 1280, height: 720 }).frame(0).data;
assert.ok(idr.length < 12_000 && idr.length > 3600, `a 1280x720 key frame of ${idr.length} bytes`);
// another size than 16's multiples: cropped, still whole macroblocks inside
assert.deepEqual(nalTypes(new H264Pattern({ width: 100, height: 60 }).frame(0).data), [7, 8, 5]);
});
});
describe("drop rules and the queue", () => {
test("the first chunk must be a key frame; in order, each once; ages from the clock", () => {
let now = 1000, asks = 0;
const q = new CameraChunkQueue(1000, () => asks++, () => now);
assert.equal(q.push(chunk(20, false), false), false, "a P frame first is dropped");
assert.equal(asks, 0, "not asked for: the source starts with one");
assert.equal(q.push(chunk(30, true, 1), true), true);
assert.equal(q.push(chunk(40, false, 2), false), true);
assert.equal(q.push(chunk(50, false, 3), false, 990), true);
now = 1010;
const out = new Uint8Array(1000);
assert.deepEqual(q.read(out), { bytes: 30, key: true, ageMs: 10 });
assert.equal(out[29], 1);
assert.deepEqual(q.read(out), { bytes: 40, key: false, ageMs: 10 });
assert.deepEqual(q.read(out), { bytes: 50, key: false, ageMs: 20 }, "the capture time it was given");
assert.equal(q.read(out), null);
assert.deepEqual(q.gate.counts, { pushed: 4, keys: 1, delivered: 3, dropped: 1, tooLarge: 0 });
});
test("full: the newest are dropped up to the next key frame, which is asked for once (again only when a key frame is dropped)", () => {
let now = 0, asks = 0;
const q = new CameraChunkQueue(1000, () => asks++, () => now);
q.push(chunk(16, true), true);
for (let i = 1; i < CHUNK_QUEUE_MAX; i++) assert.equal(q.push(chunk(16, false, i), false), true);
assert.equal(q.push(chunk(16, false), false), false, "the 33rd does not fit");
assert.equal(asks, 1);
assert.equal(q.push(chunk(16, false), false), false);
assert.equal(asks, 1, "one ask a gap");
assert.equal(q.push(chunk(16, true), true), false, "a key frame while still full");
assert.equal(asks, 1, "within KEY_ASK_MS of the ask");
now += KEY_ASK_MS;
assert.equal(q.push(chunk(16, true), true), false);
assert.equal(asks, 2, "its answer was dropped: asked again");
const out = new Uint8Array(1000);
for (let i = 0; i < CHUNK_QUEUE_MAX; i++) assert.ok(q.read(out), `the ${i}th that waited`);
assert.equal(q.push(chunk(16, false), false), false, "room again, but not a key frame");
assert.equal(q.push(chunk(16, true, 9), true), true);
assert.equal(q.read(out)!.key, true, "after the gap, a key frame");
});
test("too large for the guest's buffers: dropped (with what follows up to a key frame) and a key frame asked for", () => {
let asks = 0;
const q = new CameraChunkQueue(100, () => asks++);
q.push(chunk(50, true), true);
assert.equal(q.push(chunk(101, false), false), false);
assert.equal(q.gate.counts.tooLarge, 1);
assert.equal(asks, 1);
assert.equal(q.push(chunk(50, false), false), false);
// a reader with a smaller buffer than the stream's
const g = new CameraChunkQueue(1000, () => asks++, () => 0);
g.push(chunk(60, true), true);
g.push(chunk(20, false), false);
g.push(chunk(20, true, 7), true);
const small = new Uint8Array(40);
assert.deepEqual(g.read(small), { bytes: 20, key: true, ageMs: 0 }, "skipped to the key frame");
assert.equal(small[19], 7);
assert.equal(asks, 2);
});
});
describe("the chunk ring", () => {
test("in order and bit for bit across many wraps; another stream's records are dropped", () => {
const buf = createChunkRing(65536);
let now = 0;
const w = new ChunkRingWriter(buf, () => now), r = new ChunkRingReader(buf, () => now);
r.start(1);
w.start(1, 20000, () => {});
const out = new Uint8Array(20000);
let seq = 0;
for (let round = 0; round < 200; round++) {
const n = 1 + ((round * 7919) % 5);
const sent: Uint8Array[] = [];
for (let i = 0; i < n; i++) {
const len = 100 + ((seq * 2654435761) >>> 0) % 9000;
const c = chunk(len, seq === 0 || seq % 10 === 0, seq & 0xff);
seq++;
assert.equal(w.push(c, c[4]! === 0x67, now - 5), true, `push ${seq}`);
sent.push(c);
}
now += 3;
for (const c of sent) {
const got = r.read(out)!;
assert.ok(got, "a record");
assert.equal(got.bytes, c.length);
assert.deepEqual(out.subarray(0, got.bytes), c);
assert.equal(got.ageMs, 8);
}
assert.equal(r.read(out), null);
}
// a stream's start drops what waits; the writer's late records of the old stream are skipped
w.push(chunk(100, false), false);
r.start(2);
assert.equal(r.read(out), null);
w.push(chunk(100, false), false);
assert.equal(r.read(out), null, "stream 1's record for stream 2");
w.start(2, 20000, () => {});
w.push(chunk(100, true, 3), true);
assert.equal(r.read(out)!.bytes, 100);
assert.equal(w.counts().skipped, 1);
});
test("full by records or bytes: the writer drops up to a key frame and asks for one; a record too large for the reader is a gap", () => {
const buf = createChunkRing(65536);
let asks = 0, gaps = 0;
const w = new ChunkRingWriter(buf), r = new ChunkRingReader(buf);
r.start(5);
w.start(5, 60000, () => asks++);
assert.equal(w.push(chunk(100, true), true), true);
for (let i = 1; i < CHUNK_QUEUE_MAX; i++) assert.equal(w.push(chunk(100, false), false), true);
assert.equal(w.push(chunk(100, false), false), false, "32 records wait");
assert.equal(asks, 1);
const out = new Uint8Array(60000);
while (r.read(out));
assert.equal(w.push(chunk(100, false), false), false, "not a key frame after the gap");
assert.equal(w.push(chunk(40000, true), true), true);
assert.equal(w.push(chunk(30000, false), false), false, "the bytes do not fit");
assert.equal(asks, 2);
assert.equal(r.read(out)!.bytes, 40000);
w.push(chunk(30000, true), true);
w.push(chunk(100, false), false);
w.push(chunk(100, true, 4), true);
const small = new Uint8Array(1000);
const got = r.read(small, () => gaps++)!;
assert.equal(gaps, 1);
assert.deepEqual([got.bytes, got.key, small[99]], [100, true, 4], "skipped to the next key frame");
});
});
describe("CameraHost, compressed", () => {
const memory = new WebAssembly.Memory({ initial: 2 });
const STRUCT = 4096, BUF = 8192;
const words = () => new Uint32Array(memory.buffer, STRUCT, 8);
type Im = Record<string, (...a: unknown[]) => unknown>;
test("offered only where the source makes it; the stream's controls; chunks into kernel memory with their flags; 0 when none waits", () => {
const told: Array<[CameraFormat | null, CameraChunkSink | undefined]> = [];
const controls: CameraFormat[] = [];
let keys = 0;
const h = new CameraHost({
enabled: { compressed: ["H264"], onStream: (f, s) => told.push([f, s]), keyFrame: () => keys++, onControls: (f) => controls.push(f) },
memory: () => memory,
});
const im = h.imports() as Im;
assert.equal(im.wasm_driver_camera_init!(), 1n, "KWCAM_INIT_H264");
im.wasm_driver_camera_stream!(CAMERA_FOURCC_H264, 32, 16, 1, 30, 400000, 15);
const f = told[0]![0]!, sink = told[0]![1]!;
assert.deepEqual(f, { pixelFormat: "H264", width: 32, height: 16, fps: 30, bytes: 768, bitrate: 400000, keyInterval: 15 });
assert.ok(sink, "a sink for the chunks");
words().fill(0);
assert.equal(im.wasm_driver_camera_frame!(BigInt(BUF), 768n, 0n, BigInt(STRUCT)), 0n, "none yet");
assert.equal(sink.push(chunk(100, true, 9), true), true);
assert.equal(sink.push(chunk(50, false, 8), false), true);
assert.equal(im.wasm_driver_camera_frame!(BigInt(BUF), 768n, 0n, BigInt(STRUCT)), 100n);
assert.equal(words()[0], 1, "KWCAM_CHUNK_KEY");
assert.equal(new Uint8Array(memory.buffer, BUF + 99, 1)[0], 9);
// the guest's controls and a key frame asked for, with the next chunk
words().set([0, 0, 800000, 30, 1]);
assert.equal(im.wasm_driver_camera_frame!(BigInt(BUF), 768n, 0n, BigInt(STRUCT)), 50n);
assert.equal(words()[0], 0);
assert.deepEqual(controls.map((c) => [c.bitrate, c.keyInterval]), [[800000, 30]]);
assert.equal(keys, 1);
assert.equal(im.wasm_driver_camera_frame!(BigInt(BUF), 768n, 0n, BigInt(STRUCT)), 0n);
assert.equal(im.wasm_driver_camera_frame!(BigInt(BUF), 768n, 0n), 0n, "an old kernel's call (no record): nothing");
assert.deepEqual(h.saveState(), { format: { ...f, bitrate: 800000, keyInterval: 30 }, compressed: ["H264"] });
im.wasm_driver_camera_stream!(0, 0, 0, 0, 0, 0, 0);
assert.equal(sink.push(chunk(100, true), true), false, "the stopped stream's sink takes nothing");
const st = h.statsNow();
assert.equal(st.frames, 2);
assert.deepEqual(st.chunks, { pushed: 2, keys: 1, delivered: 2, dropped: 0, tooLarge: 0 });
// a restore with a source that does not make H.264 is refused; one that does gets the stream again
const raw = new CameraHost({ enabled: { read: () => false }, memory: () => memory });
assert.match(raw.restoreMismatch(h.saveState())!, /offers H264, which this camera does not make/);
assert.equal(raw.restoreMismatch({ format: null }), null);
const im2 = raw.imports() as Im;
assert.equal(im2.wasm_driver_camera_init!(), 0n, "no compressed format: as before");
});
test("the pattern source offers H.264 and pushes its frames by the clock, a key frame first", () => {
let now = 0, timer: (() => void) | null = null;
const made: Array<[number, boolean, boolean]> = [];
const src = patternSource(undefined, { h264: true, now: () => now, setInterval: (fn) => (timer = fn), clearInterval: () => (timer = null), onChunk: (n, _c, key, taken) => made.push([n, key, taken]) });
assert.deepEqual(src.compressed, ["H264"]);
const got: boolean[] = [];
src.onStream!(H(64, 48, { keyInterval: 4 }), { push: (_d, key) => (got.push(key), true) });
assert.deepEqual(got, [true]);
now = 100; // three intervals late: the frames it missed, at once
timer!();
assert.deepEqual(got, [true, false, false, false]);
src.keyFrame!();
now = 134;
timer!();
assert.deepEqual(got, [true, false, false, false, true]);
src.onStream!(null);
assert.equal(timer, null);
assert.equal(made.length, 5);
assert.equal(src.read!(new Uint8Array(4608), H(64, 48)), false, "no raw frames of a compressed stream");
});
});
// WebCodecs stand-ins: frames record whether they were closed; the encoder records its configurations and frames, and
// gives a chunk per frame at the next flushOut() (a key frame's with SPS and PPS unless `sets` is off).
class VF implements EncFrame {
static made: VF[] = [];
closed = false;
readonly displayWidth: number;
readonly displayHeight: number;
readonly timestamp: number;
readonly source: unknown;
readonly init: any;
readonly colorSpace: any;
constructor(source: any, init?: any) {
this.source = source;
this.init = init;
this.colorSpace = init?.colorSpace ?? source?.colorSpace ?? null;
this.displayWidth = init?.codedWidth ?? source?.displayWidth ?? 0;
this.displayHeight = init?.codedHeight ?? source?.displayHeight ?? 0;
this.timestamp = init?.timestamp ?? 0;
VF.made.push(this);
}
close() { this.closed = true; }
}
class VE {
static all: VE[] = [];
static failConfigure = 0;
static sets = true;
state = "unconfigured";
encodeQueueSize = 0;
configs: Record<string, unknown>[] = [];
frames: Array<{ ts: number; key: boolean; source: unknown; colour?: any; y?: number }> = [];
pending: Array<{ ts: number; key: boolean }> = [];
readonly init: { output: (c: EncChunk, meta?: any) => void; error: (e: Error) => void };
constructor(init: VE["init"]) {
this.init = init;
VE.all.push(this);
}
configure(c: Record<string, unknown>) {
if (VE.failConfigure > 0) {
VE.failConfigure--;
throw Object.assign(new Error("unsupported"), { name: "NotSupportedError" });
}
this.configs.push(c);
this.state = "configured";
}
encode(f: VF, o?: { keyFrame?: boolean }) {
this.frames.push({ ts: f.timestamp, key: !!o?.keyFrame, source: f.source, colour: f.colorSpace, y: f.source instanceof Uint8Array ? f.source[0] : undefined });
this.pending.push({ ts: f.timestamp, key: !!o?.keyFrame });
}
flushOut() {
for (const p of this.pending.splice(0)) {
const data = chunk(64, p.key, 0x11, VE.sets);
this.init.output({ type: p.key ? "key" : "delta", byteLength: data.length, timestamp: p.ts, copyTo: (d: Uint8Array) => d.set(data) });
}
}
close() { this.state = "closed"; }
static isConfigSupported = async (c: { codec: string; width: number; hardwareAcceleration: string }) => ({ supported: VE.supported(c) });
static supported = (_c: { codec: string; width: number; hardwareAcceleration: string }) => true;
}
const wc = { VideoEncoder: VE, VideoFrame: VF } as unknown as EncWebCodecs;
const LADDER: H264Rung[] = [{ profile: H264_PROFILES[0], acc: "prefer-hardware" }, { profile: H264_PROFILES[1], acc: "no-preference" }];
describe("CameraEncoder (stand-ins)", () => {
let now: number, tick: (() => void) | null, pushed: Array<{ key: boolean; types: number[]; at?: number }>, accept: boolean, logs: string[];
const sink: CameraChunkSink = { push: (d, key, at) => (pushed.push({ key, types: nalTypes(d), at }), accept) };
const make = (f = H(64, 48, { fps: 10, keyInterval: 4 }), fit?: (fr: EncFrame, w: number, h: number, ts: number) => EncFrame | null) =>
new CameraEncoder(f, sink, { wc, ladder: LADDER, now: () => now, setInterval: (fn) => (tick = fn), clearInterval: () => (tick = null), log: (m) => logs.push(m), fit });
beforeEach(() => {
now = 0;
tick = null;
pushed = [];
accept = true;
logs = [];
VE.all = [];
VE.failConfigure = 0;
VE.sets = true;
VF.made = [];
});
const step = (ms: number) => {
now += ms;
tick?.();
};
const cam = (w = 64, h = 48) => new VF({ displayWidth: w, displayHeight: h });
test("black frames at the stream's rate until the camera runs, then its frames (a key frame at the switch), key frames every interval", () => {
const e = make();
assert.equal(VE.all.length, 1, "an encoder at the start");
const ve = VE.all[0]!;
assert.deepEqual(ve.configs[0], { codec: "avc1.42E00A", width: 64, height: 48, bitrate: 50000, framerate: 10, latencyMode: "realtime", hardwareAcceleration: "prefer-hardware", avc: { format: "annexb" } });
step(100);
step(100);
assert.deepEqual(ve.frames.map((f) => f.key), [true, false, false], "black frames, a key frame first");
assert.ok(VF.made.every((f) => f.closed), "the encoder's inputs are closed");
e.live(true);
const c1 = cam();
e.frame(c1);
assert.deepEqual(ve.frames.map((f) => f.key), [true, false, false, true], "the camera's first frame at once, a key frame");
e.frame(c1);
assert.equal(ve.frames.length, 4, "the next not due yet (100 ms a frame)");
assert.ok(ve.frames[3]!.source === c1, "the camera's frame itself, wrapped");
assert.equal(c1.closed, false, "the camera's frame stays the camera's");
for (let i = 0; i < 5; i++) {
now += 100;
tick!();
e.frame(cam());
}
assert.deepEqual(ve.frames.slice(3).map((f) => f.key), [true, false, false, false, true, false], "every 4 frames; no black ones while it runs");
ve.flushOut();
assert.deepEqual(pushed.map((p) => p.key), ve.frames.map((f) => f.key));
assert.deepEqual(pushed[0]!.types, [7, 8, 5]);
const ts = ve.frames.map((f) => f.ts);
assert.ok(ts.every((t, i) => !i || t > ts[i - 1]!), "timestamps go up");
assert.ok(pushed.every((p, i) => Math.abs(p.at! - pushed[0]!.at! - (ts[i]! - ts[0]!) / 1000) < 0.01), "capture times from the frames' timestamps");
e.close();
assert.equal(ve.state, "closed");
assert.equal(tick, null);
});
const BT709 = { primaries: "bt709", transfer: "bt709", matrix: "bt709", fullRange: false };
const BT601 = { primaries: "smpte170m", transfer: "smpte170m", matrix: "smpte170m", fullRange: false };
test("black frames take the camera's colour space: BT.709 limited before, the given one, the camera's once seen (and Y 0 for full range)", () => {
const seen: unknown[] = [];
const e = make();
const ve = VE.all[0]!;
assert.deepEqual(ve.frames[0]!.colour, BT709, "the default before any camera frame");
assert.equal(ve.frames[0]!.y, 16);
e.live(true);
e.frame(new VF({ displayWidth: 64, displayHeight: 48, colorSpace: BT601 }));
// the camera stalls: black frames again after a second, in the camera's colour space
for (let i = 0; i < 12; i++) step(100);
const blacks = ve.frames.filter((f) => f.source instanceof Uint8Array);
assert.deepEqual(blacks.at(-1)!.colour, BT601, "after a stall: the camera's colour space");
e.close();
VE.all = [];
const e2 = new CameraEncoder(H(64, 48, { fps: 10 }), sink, { wc, ladder: LADDER, now: () => now, setInterval: (fn) => (tick = fn), clearInterval: () => {}, colorSpace: BT601, onColorSpace: (c) => seen.push(c) });
assert.deepEqual(VE.all[0]!.frames[0]!.colour, BT601, "the one given (an earlier stream's)");
e2.live(true);
const full = { ...BT709, fullRange: true };
e2.frame(new VF({ displayWidth: 64, displayHeight: 48, colorSpace: full }));
assert.deepEqual(seen, [full], "a new colour space is told");
e2.frame(new VF({ displayWidth: 64, displayHeight: 48, colorSpace: full }));
assert.equal(seen.length, 1, "once");
e2.live(false);
step(100);
assert.deepEqual([VE.all[0]!.frames.at(-1)!.colour, VE.all[0]!.frames.at(-1)!.y], [full, 0], "full range black is Y 0");
assert.deepEqual(e2.stats().colorSpace, full);
});
test("chunks at the stream's rate from the start: a frame the camera is late with is its last one again", () => {
// 10 fps (100 ms); the timer ticks four times an interval
const e = make();
const ve = VE.all[0]!;
const at: number[] = [0];
const run = (ms: number, camera?: (t: number) => boolean) => {
for (let t = 0; t < ms; t += 25) {
now += 25;
tick!();
if (camera?.(t)) e.frame(cam());
while (at.length < ve.frames.length) at.push(now);
ve.flushOut(); // (chunks out: no stall)
}
};
run(300); // black while the camera is asked for
e.live(true);
e.frame(cam()); // its first frame, then a warm-up pause of 600 ms, then 10 fps
at.push(now);
run(600);
run(1000, (t) => t % 100 === 0);
const gaps = at.slice(1).map((t, i) => t - at[i]!);
// (a late frame waits three quarters of an interval for the camera before the repeat takes its slot; no slot is lost)
assert.ok(gaps.every((g) => g <= 200), `no hole longer than 1.75 intervals and a tick: ${gaps.join(" ")}`);
assert.ok(ve.frames.length >= 18 && ve.frames.length <= 21, `${ve.frames.length} frames in 1.9 s at 10 fps`);
assert.equal(e.stats().repeated, 5, "the first frame again while the camera warms up (600 ms)");
assert.equal(e.stats().black, 4, "at 0, then 75, 175 and 275 ms (a quarter early is on time)");
// a camera at half the stream's rate: every other frame is a repeat
const before = ve.frames.length, rep0 = e.stats().repeated;
run(1000, (t) => t % 200 === 0);
assert.ok(ve.frames.length - before >= 9 && ve.frames.length - before <= 11, `${ve.frames.length - before} in a second`);
assert.ok(e.stats().repeated - rep0 >= 4 && e.stats().repeated - rep0 <= 6, String(e.stats().repeated - rep0));
// on time, jittered by up to 40 ms: no repeats, nothing dropped
const b2 = ve.frames.length, r2 = e.stats().repeated, s2 = e.stats().skipped;
run(1000, (t) => t % 100 === (Math.floor(t / 100) % 2 ? 25 : 0));
assert.equal(e.stats().repeated, r2);
assert.equal(e.stats().skipped, s2);
assert.ok(ve.frames.length - b2 >= 9, String(ve.frames.length - b2));
});
test("a key frame when asked, and SPS and PPS put in front of one without them", () => {
const e = make();
const ve = VE.all[0]!;
ve.flushOut();
VE.sets = false;
e.keyFrame();
step(100);
ve.flushOut();
assert.deepEqual(pushed.map((p) => p.types), [[7, 8, 5], [7, 8, 5]]);
assert.equal(e.stats().setsAdded, 1);
});
test("another size is fitted (or dropped without fit); a busy encoder drops frames; a dropped chunk is counted", () => {
let fits = 0;
const e = make(undefined, (_f, w, h, ts) => (fits++, new VF({ displayWidth: w, displayHeight: h }, { timestamp: ts })));
const ve = VE.all[0]!;
e.live(true);
now += 100;
e.frame(cam(640, 480));
assert.equal(fits, 1);
assert.equal(ve.frames.length, 2);
ve.encodeQueueSize = 3;
now += 100;
e.frame(cam());
assert.equal(ve.frames.length, 2, "more than two in the encoder");
accept = false;
ve.flushOut();
assert.equal(e.stats().dropped, 2);
const e2 = make();
e2.live(true);
now += 100;
e2.frame(cam(32, 32));
assert.ok(logs.some((l) => /cannot be fitted/.test(l)), logs.join("\n"));
});
test("recovery: a configuration that fails moves down the ladder; an error after output makes a new encoder, a key frame first; a reclamation; three failures pause a second", () => {
VE.failConfigure = 1;
const e = make();
assert.equal(VE.all.length, 2, "the first configuration threw: the next rung");
assert.equal(VE.all[1]!.configs[0]!.hardwareAcceleration, "no-preference");
assert.equal(VE.all[1]!.configs[0]!.codec, "avc1.4D400A");
VE.all[1]!.flushOut();
step(100);
VE.all[1]!.init.error(new Error("boom"));
step(100);
assert.equal(VE.all.length, 3);
assert.equal(VE.all[2]!.frames[0]!.key, true);
VE.all[2]!.init.error(Object.assign(new Error("reclaimed"), { name: "QuotaExceededError" }));
step(100);
assert.equal(VE.all.length, 4);
assert.equal(e.stats().reclaims, 1);
// failures without output: after three in a row, a second's pause
for (let i = 0; i < 3; i++) {
VE.all.at(-1)!.init.error(new Error("again"));
step(100);
}
const n = VE.all.length;
step(100);
step(100);
assert.equal(VE.all.length, n, "paused");
now += 1000;
tick!();
assert.equal(VE.all.length, n + 1, "tried again");
// a stall: frames in the encoder, no chunk for 2 s
const ve = VE.all.at(-1)!;
for (let i = 0; i < 21; i++) step(100);
assert.equal(ve.state, "closed");
assert.ok(logs.some((l) => /gave nothing for 2000 ms/.test(l)), logs.join("\n"));
});
test("controls: another bitrate reconfigures the encoder", () => {
const e = make();
e.controls(H(64, 48, { fps: 10, bitrate: 700000, keyInterval: 4 }));
assert.deepEqual(VE.all[0]!.configs.map((c) => c.bitrate), [50000, 700000]);
});
test("probeH264: offered where every size has a configuration, in the ladder's order", async () => {
VE.supported = (c) => c.hardwareAcceleration === "no-preference" || (c.codec.startsWith("avc1.42") && c.width !== 1280);
const l = (await probeH264(wc))!;
assert.deepEqual(l.get("640x480")!.map((r) => `${r.profile.name}/${r.acc}`), ["constrained baseline/prefer-hardware", "constrained baseline/no-preference", "main/no-preference", "high/no-preference"]);
assert.equal(l.get("1280x720")![0]!.acc, "no-preference");
VE.supported = (c) => c.width !== 1280;
assert.equal(await probeH264(wc), null, "no configuration at 1280x720: not offered");
VE.supported = () => true;
assert.equal(await probeH264(undefined), null);
});
});
describe("createCamera's H.264 (stand-ins)", { concurrency: 1 }, () => {
let cam: Camera;
const saved = new Map<string, PropertyDescriptor | undefined>();
let push: ((f: unknown) => void) | null;
let grant: boolean;
const define = (name: string, get: () => unknown) => {
if (!saved.has(name)) saved.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
Object.defineProperty(globalThis, name, { configurable: true, get });
};
const settle = async () => {
for (let i = 0; i < 10; i++) await new Promise((r) => setImmediate(r));
};
beforeEach(() => {
VE.all = [];
VE.supported = () => true;
VE.sets = true;
VF.made = [];
push = null;
grant = false;
const track = { getSettings: () => ({ width: 320, height: 240, frameRate: 30 }), stop() {}, addEventListener() {} };
define("navigator", () => ({ mediaDevices: { getUserMedia: () => (grant ? Promise.resolve({ getTracks: () => [track], getVideoTracks: () => [track] }) : new Promise(() => {})) } }));
define("MediaStreamTrackProcessor", () => class {
readable = {
getReader: () => ({
read: () => new Promise((r) => (push = (f) => r({ value: f, done: false }))),
cancel: async () => {},
}),
};
});
});
afterEach(async () => {
await cam?.close();
for (const [name, d] of saved) {
if (d) Object.defineProperty(globalThis, name, d);
else delete (globalThis as Record<string, unknown>)[name];
}
saved.clear();
});
test("probed before the boot; black frames while the camera is asked for; the camera's frames as they come, never copied", async () => {
cam = createCamera({ webCodecs: wc, log: () => {} });
assert.deepEqual(cam.compressed, [], "not before the probe");
await cam.prepare!();
assert.deepEqual(cam.compressed, ["H264"]);
assert.equal(cam.stats().h264, true);
const got: boolean[] = [];
cam.onStream!(H(320, 240), { push: (_d, key) => (got.push(key), true) });
await settle();
const ve = VE.all[0]!;
assert.equal(ve.frames.length, 1, "a black frame at once, while the browser asks");
assert.equal(ve.frames[0]!.key, true);
ve.flushOut();
assert.deepEqual(got, [true]);
cam.onStream!(null);
assert.equal(ve.state, "closed");
grant = true;
const before = VE.all.length;
cam.onStream!(H(320, 240));
assert.equal(VE.all.length, before, "no sink: no encoder");
cam.onStream!(null);
cam.onStream!(H(320, 240), { push: () => true });
await settle();
const ve2 = VE.all.at(-1)!;
await new Promise((r) => setTimeout(r, 40));
const f = new VF({ displayWidth: 320, displayHeight: 240 });
(f as unknown as { format: string }).format = "I420";
push!(f);
await settle();
assert.equal(cam.state, "running");
assert.ok(ve2.frames.at(-1)!.source === f, "the track's VideoFrame went to the encoder");
assert.equal(ve2.frames.at(-1)!.key, true, "a key frame at the switch from black");
assert.equal(f.closed, false, "the camera keeps its frame (closed when the next one comes)");
assert.equal(cam.read!(new Uint8Array(115200), H(320, 240)), false);
cam.keyFrame!();
cam.onControls!(H(320, 240, { bitrate: 123000 }));
assert.equal(ve2.configs.at(-1)!.bitrate, 123000);
});
test("h264: false, or an encoder that does not take every size: not offered", async () => {
cam = createCamera({ webCodecs: wc, h264: false });
await cam.prepare!();
assert.deepEqual(cam.compressed, []);
await cam.close();
VE.supported = (c) => c.width !== 320;
cam = createCamera({ webCodecs: wc, log: () => {} });
await cam.prepare!();
assert.deepEqual(cam.compressed, []);
assert.equal(cam.stats().h264, false);
});
});
test("fourccs", () => {
assert.equal(CAMERA_FOURCC_H264, 0x34363248); // "H264"
assert.notEqual(CAMERA_FOURCC_H264, CAMERA_FOURCC_NV12);
assert.equal(cameraFrameBytes("H264", 1280, 720), 1382400);
});