Files
unkernel/js/core/camera.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

764 lines
32 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// The host side of kwcam (kernel drivers/media/platform/kwcam.c): a V4L2
// camera, /dev/video0, whose frames come from a CameraSource. Universal.
//
// - wasm_driver_camera_init() answers -ENODEV without the camera option,
// and the kernel then registers no device; else 0.
// - wasm_driver_camera_stream(fourcc, width, height, num, den): a guest
// program started streaming (STREAMON) with that format and a frame
// every num/den s, or (fourcc 0) stopped (STREAMOFF, or it closed the
// device). Nothing before the first start: a page asks for the user's
// camera only then, and lets it go at the stop.
// - wasm_driver_camera_frame(addr, bytes): the kernel's timer, at the
// stream's rate, asks for the current frame for one buffer. The host
// writes the source's frame (CameraSource.read(), in the stream's format
// and size) into kernel memory during the call and returns `bytes`, or 0
// when the source has none, and the kernel delivers a black frame then.
// So the guest gets frames at its rate from the start, black ones until
// a camera gives a picture (not granted yet, refused, starting), and
// never waits. No import suspends, and none has an IRQ. With a frame the
// host also writes the frame's id (16 bytes) at a third argument, the
// kernel's record of that buffer (uapi/linux/kwcam.h): zero where nothing
// keeps frames (no CameraFrameStore, below), else the store's id of it.
//
// CameraFrameStore: where the host keeps the frames it gave the guest's
// buffers, for a consumer it also serves that names a buffer's frame by
// its id instead of sending its pixels (the VA-API encoder, va-enc.ts
// "camera": GStreamer's v4l2src io-mode=dmabuf into vavp9enc). It lives on
// the source's thread (the owner's in worker mode, with the VA host).
//
// Worker mode: the source is the owner's; the worker's CameraHost reads
// a CameraFrames mailbox (below) that the owner fills (worker-devices.ts
// CameraBridge), or the frames the owner posts without shared memory.
//
// Compressed (H.264): the source encodes and the guest copies the stream,
// as from a UVC camera with its own encoder (ffmpeg -input_format h264 -c:v
// copy). kwcam offers H.264 only where the source says it makes it
// (`compressed`, read at wasm_driver_camera_init(), whose answer has a bit
// per compressed format; the SDK awaits the source's prepare() before the
// kernel boots, so a page can probe its encoder first). At a compressed
// STREAMON (wasm_driver_camera_stream()'s sixth and seventh arguments: the
// guest's bitrate and GOP size controls) the source's onStream() gets a
// CameraChunkSink, into which it pushes the stream's chunks as its encoder
// gives them: Annex B access units, a key frame (IDR with SPS and PPS)
// first, no B-frames. They reach the kernel in order, each once
// (camera-chunks.ts: a CameraChunkQueue on the kernel's thread, the chunk
// ring or "camera-chunk" messages in worker mode); a chunk that does not
// fit drops it and those after it up to the next key frame, which the
// source is asked for (keyFrame()), as it is when the guest asks for one
// (V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME). The frame import then writes the
// next chunk and fills its fourth argument, the kernel's struct
// kwcam_chunk (flags: key frame; how long ago its frame was captured; in: the
// controls, which reach the source as onControls() when they change, and a
// key frame asked for), or returns 0 when no chunk waits: the kernel keeps
// the buffer for a later tick, never a black or repeated frame.
import { CAMERA_CODECS, cameraCompressed, cameraFrameBytes, cameraPixelFormat, testPattern, type CameraCodec, type CameraStreamFormat } from "./camera-pixels.ts";
import { CHUNK_CLOCK, CameraChunkQueue, type ChunkCounts, type ChunkRead } from "./camera-chunks.ts";
import { H264Pattern } from "./camera-h264.ts";
const ENODEV = 19;
/** The guest's stream: what a program asked for at STREAMON. */
export interface CameraFormat {
pixelFormat: CameraStreamFormat;
width: number;
height: number;
/** Frames a second (the driver offers 30, 25, 20, 15, 10 and 5). */
fps: number;
/** Bytes of one frame; compressed: of the guest's buffers, the largest chunk. */
bytes: number;
/** Compressed only: the bitrate (bits a second) and the frames from one key frame to the next, as the guest's controls say. */
bitrate?: number;
keyInterval?: number;
}
/** Where a source puts a compressed stream's chunks (CameraSource.onStream's second argument, for that stream only). */
export interface CameraChunkSink {
/**
* One chunk: an Annex B access unit (a key frame's with its SPS and PPS),
* in the encoder's order; its bytes are kept (give a copy you will not
* change). False when it was dropped (the guest is not taking them, or
* it is larger than its buffers, or the stream has stopped): a key frame
* is wanted then, and keyFrame() has been called. `at`: when its frame
* was captured (camera-chunks.ts CHUNK_CLOCK, ms), default now; the
* guest's buffer is timestamped that long before it got it.
*/
push(data: Uint8Array, key: boolean, at?: number): boolean;
}
/** @internal The kernel's side of a compressed stream's chunks where they come from another thread (worker mode). */
export interface CameraChunkReader {
read(out: Uint8Array): ChunkRead | null;
counts(): ChunkCounts;
}
/** Where the guest's camera frames come from (the camera option). */
export interface CameraSource {
/**
* A guest program started streaming with `format`, or stopped (null):
* a source that holds a device (the user's camera) opens it at the
* first and lets it go at the second. For a compressed format, `chunks`
* is where the stream goes (the source's encoder at the stream's size,
* rate, bitrate and key interval).
*/
onStream?: (format: CameraFormat | null, chunks?: CameraChunkSink) => void;
/**
* The compressed formats the source makes (kwcam offers them to the
* guest beside YUYV and NV12), read when the kernel's camera starts,
* after prepare(); none by default.
*/
readonly compressed?: readonly CameraCodec[];
/** Awaited before the kernel boots, e.g. to probe an encoder; `compressed` is read after it. */
prepare?: () => Promise<void> | void;
/** Compressed: the next chunk should be a key frame (the guest asked for one, or chunks were dropped). */
keyFrame?: () => void;
/** Compressed: the guest changed the running stream's bitrate or key interval (its V4L2 controls). */
onControls?: (format: CameraFormat) => void;
/** @internal The worker's: the kernel's side of the chunks the owner's source makes (instead of a sink of its own). */
chunkReader?: () => CameraChunkReader;
/**
* The current frame, pulled at the stream's rate from inside a kernel
* import (so return at once): write format.bytes bytes of it into
* `out` in the stream's format and size, and return true; false when
* there is none (the guest gets a black frame). Inline `out` is the
* guest's buffer in kernel memory, valid only during the call.
*/
read?: (out: Uint8Array, format: CameraFormat) => boolean;
/**
* The VideoFrame whose pixels the last successful read() wrote, exactly
* (a 4:2:0 frame of the stream's size, copied plane for plane), or null:
* owned by the source and valid until the next read() (clone it to keep
* it). Asked only while a consumer takes frames without a copy.
*/
lastFrame?: () => CameraVideoFrame | null;
/** @internal The id (16 bytes) of the frame the last read() gave, where another thread's store made it (worker mode). */
frameId?: () => Uint8Array | null;
}
/** The part of a VideoFrame the camera's consumers use. */
export interface CameraVideoFrame {
readonly displayWidth: number;
readonly displayHeight: number;
readonly visibleRect?: { x: number; y: number; width: number; height: number } | null;
readonly colorSpace?: { primaries?: string | null; transfer?: string | null; matrix?: string | null; fullRange?: boolean | null } | null;
clone(): CameraVideoFrame;
close(): void;
}
/** The camera option: false (no device), true (a camera that gives black frames), or a source. */
export type CameraOption = boolean | CameraSource;
export interface CameraStats {
starts: number;
stops: number;
/** Frames the guest got (compressed: chunks). */
frames: number;
/** Of those, black ones because the source had none. */
blackFrames: number;
/** Compressed streams only: the chunks' counts (camera-chunks.ts), all streams together. */
chunks?: ChunkCounts;
}
/** What a machine snapshot keeps of kwcam (CameraHost.saveState()). */
export interface CameraSnapshot {
/** The stream that was running, or null. */
format: CameraFormat | null;
/** The compressed formats the kernel offers (it was told at its init); absent: none. */
compressed?: CameraCodec[];
}
/** The bits of wasm_driver_camera_init()'s answer (kernel KWCAM_INIT_*) for compressed formats, in CAMERA_CODECS order. */
export function cameraInitBits(codecs: readonly CameraCodec[]): number {
let bits = 0;
CAMERA_CODECS.forEach((c, i) => {
if (codecs.includes(c)) bits |= 1 << i;
});
return bits;
}
/** The compressed formats a source says it makes (`compressed`), of those there are. */
export function cameraSourceCodecs(source: CameraSource): CameraCodec[] {
try {
const c = source.compressed;
return Array.isArray(c) ? CAMERA_CODECS.filter((k) => c.includes(k)) : [];
} catch {
return [];
}
}
/** Awaited before the kernel boots: a source's prepare() (an encoder probed), at most `ms`; a failure only logs. */
export async function prepareCamera(camera: CameraOption | undefined, log: (msg: string) => void, ms = 3000): Promise<void> {
if (!camera || typeof camera !== "object" || typeof camera.prepare !== "function") return;
let timer: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
Promise.resolve(camera.prepare()),
new Promise<void>((r) => (timer = setTimeout(() => {
log(`[camera] the camera's prepare() took more than ${ms} ms: booting without waiting for it`);
r();
}, ms))),
]);
} catch (e) {
log(`[camera] the camera's prepare() failed: ${(e as Error)?.message ?? e}`);
} finally {
if (timer !== undefined) clearTimeout(timer);
}
}
/** A chunk's capture time as given (CHUNK_CLOCK ms), if it is one: not after now, at most a minute before. */
export function chunkAt(at: unknown): number | undefined {
if (typeof at !== "number" || !Number.isFinite(at)) return undefined;
const now = CHUNK_CLOCK();
return Math.min(now, Math.max(now - 60_000, at));
}
/** The kernel's struct kwcam_chunk (the frame import's fourth argument): word offsets. */
const CHUNK_FLAGS = 0, CHUNK_AGE_US = 1, CHUNK_BITRATE = 2, CHUNK_GOP = 3, CHUNK_REQUEST = 4;
const CHUNK_STRUCT_BYTES = 32;
const KWCAM_CHUNK_KEY = 1, KWCAM_REQ_KEY = 1;
export interface CameraHostOptions {
enabled?: CameraOption;
/** Where the frames given to the guest are kept for the VA encoder (on this thread; inline mode). */
store?: CameraFrameStore;
/** The kernel's memory, read at call time. */
memory: () => WebAssembly.Memory;
log?: (msg: string) => void;
}
export class CameraHost {
readonly enabled: boolean;
probed = false;
/** The running stream, or null. */
format: CameraFormat | null = null;
stats: CameraStats = { starts: 0, stops: 0, frames: 0, blackFrames: 0 };
#source: CameraSource;
#store: CameraFrameStore | undefined;
#memory: () => WebAssembly.Memory;
#log: (msg: string) => void;
/** The compressed formats the kernel offers (from its init, or a snapshot). */
#offered: CameraCodec[] = [];
/** A compressed stream's chunks: this thread's queue, or the reader of another thread's. */
#chunks: CameraChunkQueue | CameraChunkReader | null = null;
/** Counts of the streams before this one. */
#chunkTotals: ChunkCounts | null = null;
#warned = new Set<string>();
constructor(opts: CameraHostOptions) {
this.enabled = !!opts.enabled;
this.#source = typeof opts.enabled === "object" ? opts.enabled : {};
this.#store = opts.store;
this.#memory = opts.memory;
this.#log = opts.log ?? (() => {});
}
/** A program streams. */
get streaming(): boolean {
return this.format !== null;
}
/** The compressed formats the kernel offers. */
get offered(): readonly CameraCodec[] {
return this.#offered;
}
#once(key: string, msg: string): void {
if (this.#warned.has(key)) return;
this.#warned.add(key);
this.#log(msg);
}
#endChunks(): void {
const c = this.#chunks;
this.#chunks = null;
if (!c) return;
const n = c instanceof CameraChunkQueue ? c.gate.counts : c.counts();
const t = (this.#chunkTotals ??= { pushed: 0, keys: 0, delivered: 0, dropped: 0, tooLarge: 0 });
for (const k of Object.keys(t) as (keyof ChunkCounts)[]) t[k] += n[k];
if (c instanceof CameraChunkQueue) c.clear();
}
#notify(format: CameraFormat | null): void {
this.#endChunks();
this.format = format;
this.#store?.stop();
const src = this.#source;
let sink: CameraChunkSink | undefined;
if (format && cameraCompressed(format.pixelFormat)) {
if (src.chunkReader) {
// (the worker's source: it posts the start to the owner, whose source fills what this reads)
try { src.onStream?.({ ...format }); } catch (e) { this.#log(`[camera] onStream failed: ${e}`); }
this.#chunks = src.chunkReader();
return;
}
const q = new CameraChunkQueue(format.bytes, () => {
try { src.keyFrame?.(); } catch (e) { this.#log(`[camera] keyFrame failed: ${e}`); }
});
this.#chunks = q;
sink = { push: (data, key, at) => this.#chunks === q && data instanceof Uint8Array ? q.push(data, !!key, chunkAt(at)) : false };
}
try { src.onStream?.(format && { ...format }, sink); } catch (e) { this.#log(`[camera] onStream failed: ${e}`); }
}
/** Why a snapshot's camera cannot be resumed with this source (one that cannot make a compressed format the kernel offers), or null. */
restoreMismatch(s: CameraSnapshot | null | undefined): string | null {
const have = this.#sourceCodecs();
const lack = (s?.compressed ?? []).filter((c) => !have.includes(c));
return lack.length ? `the snapshot's camera offers ${lack.join(", ")}, which this camera does not make` : null;
}
/** What the source makes, of the compressed formats there are. */
#sourceCodecs(): CameraCodec[] {
return cameraSourceCodecs(this.#source);
}
/** The chunk counts of every compressed stream so far, or undefined when there was none. */
chunkCounts(): ChunkCounts | undefined {
const t = this.#chunkTotals, c = this.#chunks;
if (!c) return t ? { ...t } : undefined;
const n = c instanceof CameraChunkQueue ? c.gate.counts : c.counts();
const out = { ...n };
if (t) for (const k of Object.keys(out) as (keyof ChunkCounts)[]) out[k] += t[k];
return out;
}
/** The kernel ended: a stream still running stops at the source. */
close(): void {
if (this.format) this.#notify(null);
}
saveState(): CameraSnapshot {
return { format: this.format && { ...this.format }, ...(this.#offered.length ? { compressed: [...this.#offered] } : {}) };
}
/**
* A restored snapshot: a stream that was running starts again at the
* source (a page asks for the camera again); a compressed one with a
* new encoder, so the guest's next chunk is a key frame.
*/
restoreState(s: CameraSnapshot): void {
this.probed = true;
this.format = null;
this.#offered = CAMERA_CODECS.filter((c) => s.compressed?.includes(c));
if (s.format) {
this.stats.starts++;
this.#notify({ ...s.format });
}
}
imports(): Record<string, unknown> {
return {
wasm_driver_camera_init: (): bigint => {
this.probed = true;
if (!this.enabled) return -BigInt(ENODEV);
this.#offered = this.#sourceCodecs();
return BigInt(cameraInitBits(this.#offered));
},
// (bitrate, gop: a compressed stream's controls; absent from older kernels)
wasm_driver_camera_stream: (fourcc: number, width: number, height: number, num: number, den: number, bitrate?: number, gop?: number): void => {
if (!fourcc) {
if (!this.format) return;
this.stats.stops++;
this.#notify(null);
return;
}
const pf = cameraPixelFormat(fourcc >>> 0);
if (!pf || !width || !height || !num || !den || (cameraCompressed(pf) && !this.#offered.includes(pf))) {
this.#log(`[camera] unexpected stream: fourcc 0x${(fourcc >>> 0).toString(16)}, ${width}x${height}, ${num}/${den} s`);
return;
}
this.stats.starts++;
const f: CameraFormat = { pixelFormat: pf, width, height, fps: den / num, bytes: cameraFrameBytes(pf, width, height) };
if (cameraCompressed(pf)) {
f.bitrate = (bitrate ?? 0) >>> 0 || Math.max(50_000, Math.round(width * height * f.fps / 10));
f.keyInterval = (gop ?? 0) >>> 0 || Math.max(1, Math.round(f.fps));
}
this.#notify(f);
},
// (idp: the kernel's 16 bytes for the frame's id, left zero where there is none; absent from older kernels;
// chunkp: a compressed stream's struct kwcam_chunk)
wasm_driver_camera_frame: (buf: bigint, bytes: bigint, idp?: bigint, chunkp?: bigint): bigint => {
const f = this.format, n = Number(bytes);
if (f && cameraCompressed(f.pixelFormat)) return this.#chunk(f, Number(buf), n, chunkp === undefined ? 0 : Number(chunkp));
this.stats.frames++;
if (!f || n !== f.bytes || !this.#source.read) {
this.stats.blackFrames++;
return 0n;
}
const addr = Number(buf), mem = this.#memory().buffer;
if (addr + n > mem.byteLength) return 0n;
let ok = false;
const out = new Uint8Array(mem, addr, n);
try { ok = !!this.#source.read(out, f); } catch (e) { this.#log(`[camera] read failed: ${e}`); }
if (!ok) {
this.stats.blackFrames++;
return 0n;
}
// the frame's id: the store's (inline), or the one the frame came with (worker mode); never in the way of the frame
try {
const src = this.#source;
const id = this.#store ? this.#store.add(out, f, src.lastFrame ? () => src.lastFrame!() : undefined) : (src.frameId?.() ?? null);
const at = idp === undefined ? 0 : Number(idp);
if (id && at > 0 && at + 16 <= mem.byteLength) new Uint8Array(mem, at, 16).set(id);
} catch (e) { this.#log(`[camera] frame id: ${e}`); }
return bytes;
},
};
}
/** A compressed stream's frame import: the controls and a key frame asked for, then the next chunk into the buffer. */
#chunk(f: CameraFormat, addr: number, n: number, cp: number): bigint {
const mem = this.#memory().buffer;
const st = cp > 0 && cp % 4 === 0 && cp + CHUNK_STRUCT_BYTES <= mem.byteLength ? new Uint32Array(mem, cp, CHUNK_STRUCT_BYTES >> 2) : null;
if (!st) {
this.#once("struct", "[camera] a compressed stream's frame import has no chunk record: none given");
return 0n;
}
const src = this.#source;
const bitrate = st[CHUNK_BITRATE]!, gop = st[CHUNK_GOP]!;
if ((bitrate && bitrate !== f.bitrate) || (gop && gop !== f.keyInterval)) {
if (bitrate) f.bitrate = bitrate;
if (gop) f.keyInterval = gop;
try { src.onControls?.({ ...f }); } catch (e) { this.#log(`[camera] onControls failed: ${e}`); }
}
if (st[CHUNK_REQUEST]! & KWCAM_REQ_KEY) {
try { src.keyFrame?.(); } catch (e) { this.#log(`[camera] keyFrame failed: ${e}`); }
}
const c = this.#chunks;
if (!c || n !== f.bytes || addr <= 0 || addr + n > mem.byteLength) return 0n;
const r = c.read(new Uint8Array(mem, addr, n));
if (!r) return 0n;
this.stats.frames++;
st[CHUNK_FLAGS] = r.key ? KWCAM_CHUNK_KEY : 0;
st[CHUNK_AGE_US] = Math.min(0xffffffff, Math.max(0, Math.round(r.ageMs * 1000)));
return BigInt(r.bytes);
}
/** The stats, with the chunk counts where a compressed stream ran. */
statsNow(): CameraStats {
const chunks = this.chunkCounts();
return { ...this.stats, ...(chunks ? { chunks } : {}) };
}
}
// CameraFrames: the latest frame from one producer (the owner's side of
// worker mode) to one consumer (the worker's kernel, in its frame
// import), on a SharedArrayBuffer: a triple buffer of slots of MAX bytes.
// The producer writes into its back slot and swaps it with the middle one
// (Atomics.exchange, NEW set); the consumer, when NEW is set, swaps its
// front slot with the middle one. Neither ever waits; the consumer reads
// the newest complete frame, or the last one again. Each slot records the
// stream generation it was made for (the consumer's starts), so a frame
// of an earlier stream is never delivered.
const MIDDLE = 0;
const NEW = 4;
/** Per slot: the stream generation and the bytes of its frame; its id (4 words a slot, zero: none). */
const SLOT_GEN = 4, SLOT_BYTES = 8, SLOT_ID = 16;
const HEADER_BYTES = 128;
/** The largest frame kwcam asks for: 1280x720 YUYV. */
export const CAMERA_MAX_FRAME_BYTES = 1280 * 720 * 2;
/** Allocate a frame mailbox for frames of up to `maxBytes`. */
export function createCameraFrames(maxBytes = CAMERA_MAX_FRAME_BYTES): SharedArrayBuffer {
const b = new SharedArrayBuffer(HEADER_BYTES + 3 * maxBytes);
// The consumer holds slot 0, the producer slot 2, slot 1 is in the middle; none has a frame.
const ctrl = new Int32Array(b, 0, HEADER_BYTES >> 2);
ctrl[MIDDLE] = 1;
ctrl[SLOT_GEN] = ctrl[SLOT_GEN + 1] = ctrl[SLOT_GEN + 2] = -1;
return b;
}
function slotsOf(buffer: SharedArrayBuffer): { ctrl: Int32Array; max: number } {
const max = Math.floor((buffer.byteLength - HEADER_BYTES) / 3);
if (max <= 0) throw new RangeError(`invalid camera frame buffer byteLength ${buffer.byteLength}`);
return { ctrl: new Int32Array(buffer, 0, HEADER_BYTES >> 2), max };
}
/** The producer's side. */
export class CameraFramesWriter {
readonly #buf: SharedArrayBuffer;
readonly #ctrl: Int32Array;
readonly max: number;
#back = 2;
constructor(buffer: SharedArrayBuffer) {
this.#buf = buffer;
const s = slotsOf(buffer);
this.#ctrl = s.ctrl;
this.max = s.max;
}
/** The back slot's bytes, to fill with a frame of `bytes` (<= max), then publish(). */
slot(bytes: number): Uint8Array {
return new Uint8Array(this.#buf, HEADER_BYTES + this.#back * this.max, Math.min(bytes, this.max));
}
/** Publish the back slot as the newest frame of stream `gen` (with its id: 16 bytes, or none). */
publish(gen: number, bytes: number, id?: Uint8Array | null): void {
Atomics.store(this.#ctrl, SLOT_GEN + this.#back, gen | 0);
Atomics.store(this.#ctrl, SLOT_BYTES + this.#back, bytes | 0);
const dv = id && id.length === 16 ? new DataView(id.buffer, id.byteOffset, 16) : null;
for (let i = 0; i < 4; i++) Atomics.store(this.#ctrl, SLOT_ID + 4 * this.#back + i, dv ? dv.getInt32(4 * i, true) : 0);
this.#back = Atomics.exchange(this.#ctrl, MIDDLE, this.#back | NEW) & 3;
}
}
/** The consumer's side (the worker's kernel). */
export class CameraFramesReader {
readonly #buf: SharedArrayBuffer;
readonly #ctrl: Int32Array;
readonly #max: number;
#front = 0;
constructor(buffer: SharedArrayBuffer) {
this.#buf = buffer;
const s = slotsOf(buffer);
this.#ctrl = s.ctrl;
this.#max = s.max;
}
/** Copy the newest frame of stream `gen` into `out` (its whole length); false when there is none. */
read(out: Uint8Array, gen: number): boolean {
if (Atomics.load(this.#ctrl, MIDDLE) & NEW) this.#front = Atomics.exchange(this.#ctrl, MIDDLE, this.#front) & 3;
const f = this.#front;
if (Atomics.load(this.#ctrl, SLOT_GEN + f) !== (gen | 0) || Atomics.load(this.#ctrl, SLOT_BYTES + f) !== out.length) return false;
out.set(new Uint8Array(this.#buf, HEADER_BYTES + f * this.#max, out.length));
return true;
}
/** The id of the frame read() last gave (16 bytes), or null for none. */
id(): Uint8Array | null {
const f = this.#front, id = new Uint8Array(16), dv = new DataView(id.buffer);
let any = 0;
for (let i = 0; i < 4; i++) {
const w = Atomics.load(this.#ctrl, SLOT_ID + 4 * f + i);
dv.setInt32(4 * i, w, true);
any |= w;
}
return any ? id : null;
}
}
// ---- CameraFrameStore ----
/** Frames kept (the newest; a kwcam stream has at most 16 buffers), and their bytes at most. */
const STORE_KEEP = 16;
const STORE_MAX_BYTES = 32 << 20;
/** Camera VideoFrames held (the newest frame's clone): a camera track's frame pool is small, and an unclosed frame stalls it. */
const STORE_FRAMES = 1;
/** What CameraFrameStore.stats() says. */
export interface CameraStoreStats {
/** ids made (frames the guest got while something could ask), frames kept now and their bytes, VideoFrames held now */
ids: number;
kept: number;
keptBytes: number;
framesHeld: number;
/** frames asked for by id and found; of those, with the camera's VideoFrame */
taken: number;
takenFrames: number;
/** asked for and not there (not kept yet, gone, a stream since, a bad id), or of another size or format */
missed: number;
/** ms spent copying frames into the store */
copyMs: number;
}
/** A frame the store keeps: what the guest's buffer got. */
export interface CameraStoredFrame {
/** the pixels as written into the guest's buffer (NV12: Y rows of `width` bytes, then CbCr rows); the store's own copy, never changed */
data: Uint8Array;
format: CameraFormat;
/** the source's VideoFrame those pixels are exactly, while the store holds it (the newest only): clone it to keep it */
frame: CameraVideoFrame | null;
}
const hex = (b: Uint8Array): string => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
/**
* The frames the host gave the guest's camera buffers, by id, for a
* consumer that names a buffer's frame instead of sending its pixels (the
* VA-API encoder). Every frame gets a fresh random id (128 bits: a guest
* program cannot name a frame it did not get); the store keeps frames only
* once something asked for one during the stream (an unknown id arms it)
* and only NV12 ones (the encoder's input format): its own copy of the
* pixels, and the camera's VideoFrame of the newest where the source has
* one. A new stream, a stop or close() forgets them all.
*/
export class CameraFrameStore {
#armed = false;
#frames = new Map<string, CameraStoredFrame>();
#bytes = 0;
#withFrame: CameraStoredFrame | null = null;
#stats: CameraStoreStats = { ids: 0, kept: 0, keptBytes: 0, framesHeld: 0, taken: 0, takenFrames: 0, missed: 0, copyMs: 0 };
readonly #random: (out: Uint8Array<ArrayBuffer>) => void;
constructor(opts: { random?: (out: Uint8Array<ArrayBuffer>) => void } = {}) {
this.#random = opts.random ?? ((out) => globalThis.crypto.getRandomValues(out));
}
stats(): CameraStoreStats {
return { ...this.#stats, kept: this.#frames.size, keptBytes: this.#bytes, framesHeld: this.#withFrame ? 1 : 0 };
}
/**
* A frame went into a guest buffer (`pixels`, valid during the call):
* its id (16 bytes, a fresh one), or null for a format the store does
* not take. `frame` gives the source's VideoFrame of exactly these
* pixels (asked only while armed; cloned).
*/
add(pixels: Uint8Array, format: CameraFormat, frame?: () => CameraVideoFrame | null): Uint8Array | null {
if (format.pixelFormat !== "NV12" || pixels.length !== format.bytes) return null;
const id = new Uint8Array(16);
this.#random(id);
this.#stats.ids++;
if (!this.#armed) return id;
const t = performance.now();
const e: CameraStoredFrame = { data: pixels.slice(), format: { ...format }, frame: null };
this.#stats.copyMs += performance.now() - t;
try {
const vf = frame?.();
if (vf && STORE_FRAMES > 0) {
e.frame = vf.clone();
this.#dropFrame();
this.#withFrame = e;
}
} catch {}
this.#frames.set(hex(id), e);
this.#bytes += e.data.length;
for (const [k, old] of this.#frames) {
if (this.#frames.size <= STORE_KEEP && this.#bytes <= STORE_MAX_BYTES) break;
this.#forget(k, old);
}
return id;
}
/**
* The frame `id` names (32 hex digits) if the store has it and it is
* NV12 of `width` x `height`; else why not (and the store keeps frames
* from now on). The pixels are the store's (never changed: keep the
* reference); `frame`, where there is one, is valid during the call.
*/
take(id: unknown, width: number, height: number): CameraStoredFrame | string {
const miss = (why: string) => {
this.#stats.missed++;
return why;
};
if (typeof id !== "string" || !/^[0-9a-f]{32}$/.test(id)) return miss("a bad id");
const e = this.#frames.get(id);
if (!e) {
if (this.#armed) return miss("gone");
this.#armed = true;
return miss("not kept yet");
}
if (e.format.width !== width || e.format.height !== height) return miss("size");
this.#stats.taken++;
if (e.frame) this.#stats.takenFrames++;
return e;
}
#forget(k: string, e: CameraStoredFrame): void {
this.#frames.delete(k);
this.#bytes -= e.data.length;
if (this.#withFrame === e) this.#dropFrame();
}
#dropFrame(): void {
const e = this.#withFrame;
this.#withFrame = null;
if (!e?.frame) return;
try { e.frame.close(); } catch {}
e.frame = null;
}
/** The guest's stream started or stopped: frames and ids of the last one are forgotten, and nothing is kept until asked again. */
stop(): void {
this.#dropFrame();
this.#frames.clear();
this.#bytes = 0;
this.#armed = false;
}
}
/** What patternSource() takes. */
export interface PatternSourceOptions {
/** Also make H.264 (camera-h264.ts H264Pattern: a stream at the stream's rate, from a timer). Default false. */
h264?: boolean;
/** The H.264 stream's first frame number (shown in its pictures). Default 0. */
start?: number;
/** Each H.264 chunk it made (n: the frame number in it), and whether the sink took it. */
onChunk?: (n: number, chunk: Uint8Array, key: boolean, taken: boolean, format: CameraFormat) => void;
/** Timers and the ms clock (tests): default setInterval, clearInterval and performance.now. */
setInterval?: (fn: () => void, ms: number) => unknown;
clearInterval?: (t: unknown) => void;
now?: () => number;
}
/** H.264 frames the pattern makes at once at most when its timer was late (more are skipped, as a camera drops them). */
const PATTERN_CATCH_UP = 8;
/**
* A synthetic camera: camera-pixels.ts testPattern(), frame 0, 1, 2, ...
* one per frame the guest gets (the CLI's --camera, tests). `onFrame` sees
* each frame it made. With `h264` it also offers H.264: H264Pattern's
* frames 0, 1, 2, ... pushed at the stream's rate from a timer (as an
* encoder's output comes), a key frame at the start, every key interval
* and when asked for.
*/
export function patternSource(onFrame?: (n: number, frame: Uint8Array, format: CameraFormat) => void, opts: PatternSourceOptions = {}): CameraSource {
let n = 0;
const si = opts.setInterval ?? ((fn: () => void, ms: number) => setInterval(fn, ms));
const ci = opts.clearInterval ?? ((t: unknown) => clearInterval(t as ReturnType<typeof setInterval>));
let timer: unknown, enc: H264Pattern | null = null, chunkN = opts.start ?? 0;
const now = opts.now ?? (() => performance.now());
const stop = () => {
if (timer !== undefined) ci(timer);
timer = undefined;
enc = null;
};
const src: CameraSource = {
read(out, f) {
if (cameraCompressed(f.pixelFormat)) return false;
testPattern(f.pixelFormat, f.width, f.height, n, out);
onFrame?.(n, out, f);
n++;
return true;
},
};
if (!opts.h264) return src;
return {
...src,
compressed: ["H264"],
onStream(f, sink) {
stop();
if (!f || !sink || f.pixelFormat !== "H264") return;
const fmt = { ...f };
const e = (enc = new H264Pattern({ width: f.width, height: f.height, fps: f.fps, keyInterval: f.keyInterval }));
// frames by the clock: a late timer (a busy thread) gives the frames it missed at once, each with its own time
const iv = 1000 / f.fps, t0 = now(), toChunkClock = CHUNK_CLOCK() - t0;
let made = 0;
const tick = () => {
if (enc !== e) return;
const due = Math.floor((now() - t0) / iv) + 1;
if (due - made > PATTERN_CATCH_UP) made = due - PATTERN_CATCH_UP;
for (; made < due && enc === e; made++) {
const k = chunkN++;
const { data, key } = e.frame(k);
const taken = sink.push(data, key, t0 + made * iv + toChunkClock);
opts.onChunk?.(k, data, key, taken, fmt);
}
};
tick();
timer = si(tick, iv / 2);
},
keyFrame() {
enc?.keyFrame();
},
onControls(f) {
if (enc && f.keyInterval) enc.keyInterval = f.keyInterval;
},
};
}