Files
unkernel/js/web/camera.ts

475 lines
20 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// The guest's camera in a browser: a CameraSource (core/camera.ts) that
// gives the user's camera to kwcam (/dev/video0). createKernel({ camera: createCamera() })
//
// - Nothing is asked for until a guest program starts streaming: the
// stream's start calls getUserMedia (user-media.ts) with the stream's
// size and rate as ideal constraints, which is when the browser shows its
// permission prompt. Until it is granted (and after a refusal, without
// media devices, or once the track ends) the guest gets black frames,
// which the kernel fills where the source has none, at its rate. The
// tracks are stopped when the guest stops streaming (STREAMOFF, or it
// closed the device), so the browser's camera indicator goes off. A
// refusal is asked again at the next start, or at retry() (from a click:
// a page's Allow button) while the guest streams.
// - Frames: with MediaStreamTrackProcessor (Chromium) the track's
// VideoFrames are read as they come; otherwise a <video> element plays
// the stream and each new frame (requestVideoFrameCallback, else a timer
// at the stream's rate) is taken from it, as a VideoFrame where WebCodecs
// exists. At most one frame per frame interval of the guest's stream is
// converted, into the stream's format and size (camera-pixels.ts): a
// 4:2:0 frame (NV12, I420: what camera tracks give) of the stream's size
// is copied out with VideoFrame.copyTo(), straight into the stream's
// layout where it is the stream's format (I420 or NV12), else repacked
// (NV12's chroma split for I420, or to YUYV); anything else (another
// size, RGB, a <video> without WebCodecs) is drawn into a canvas of the
// stream's size, cropped to its aspect ratio from the centre, and
// converted from RGBA. read() copies the newest converted frame.
// - currentFrame() is the newest VideoFrame itself (null without
// WebCodecs): it belongs to the camera and is closed when the next one
// comes, so clone() it to keep it. lastFrame() (CameraSource) is the
// VideoFrame whose planes the last read() copied, where they were copied
// plane for plane (a 4:2:0 frame of the stream's size), for the VA-API
// encoder's camera path (core/camera.ts CameraFrameStore): the camera
// keeps a clone of the converted frame for that only once lastFrame() was
// asked for (one more frame held while a consumer takes them).
// - H.264 (kwcam's compressed format, camera-encoder.ts): created, the
// camera probes the browser's H.264 encoder at kwcam's sizes (prepare(),
// which the SDK awaits before the kernel boots) and, where it takes them
// all, says it makes H.264 (`compressed`), so the guest is offered it. A
// guest stream of H.264 gets a CameraEncoder: the track's VideoFrames go
// to it as they come, from either path (MediaStreamTrackProcessor or
// the <video> element's frames), with no pixel copy; one of another size
// is drawn into the stream's size first, cropped from the centre. Until
// the camera runs it encodes black frames at the stream's rate, tagged
// with the colour space of the camera's frames as last seen (in any
// stream, or `colorSpace`; `onColorSpace` hears a new one, for a page to
// keep it across loads), so the stream's VUI stays the same when the
// camera starts.
import type { CameraChunkSink, CameraFormat, CameraSource } from "../core/camera.ts";
import { camera420, camera420Layout, cameraCompressed, rgbaTo, yuv420To, type CameraCodec, type CameraPixelFormat, type PlaneLayout } from "../core/camera-pixels.ts";
import { CameraEncoder, colourOf, probeH264, type CameraColour, type CameraEncoderStats, type EncFrame, type EncWebCodecs, type H264Ladders } from "./camera-encoder.ts";
import { requestUserMedia, stopUserMedia } from "./user-media.ts";
/**
* What a Camera does:
* - "idle": no program streams, or the camera was released;
* - "asking": waiting for the user to allow the camera;
* - "running": the guest gets the camera's frames;
* - "denied": the user or a policy refused (black frames; asked again at the next start);
* - "unavailable": no camera, no media devices here, or the track ended;
* - "closed": after close().
*/
export type CameraState = "idle" | "asking" | "running" | "denied" | "unavailable" | "closed";
export interface CameraOptions {
log?: (msg: string) => void;
/** Constraints added to the video track's (default: the stream's size and rate as ideal values). */
constraints?: MediaTrackConstraints;
/** `state` changed (called from a microtask). */
onChange?: (state: CameraState) => void;
/** Offer H.264 where the browser's encoder makes it (camera-encoder.ts). Default true. */
h264?: boolean;
/** The camera's colour space as an earlier session saw it (onColorSpace): what H.264 black frames are tagged with until a frame says. */
colorSpace?: CameraColour | null;
/** The camera's frames named another colour space than known so far. */
onColorSpace?: (c: CameraColour) => void;
/** @internal WebCodecs' VideoEncoder and VideoFrame (default globalThis's): stand-ins in tests. */
webCodecs?: EncWebCodecs;
}
export interface CameraInStats {
/** "processor" (MediaStreamTrackProcessor), "video" (a <video> element), or null before the first stream. */
mode: "processor" | "video" | null;
/** What the track gives (0 before it runs). */
trackWidth: number;
trackHeight: number;
/** Frames converted for the guest, and of those, drawn through a canvas (scaled or RGB). */
converted: number;
scaled: number;
/** Whether H.264 is offered (the probe took every size), and the running or last H.264 stream's encoder. */
h264: boolean;
/** The camera's frames' colour space as last seen (or the option's), null before. */
colorSpace: CameraColour | null;
encoder?: CameraEncoderStats;
/** The camera's name as the browser gives it (its track's label), or "" while there is none. */
device: string;
}
/** A camera source for one kernel at a time; pass it to the next one, or close() it. */
export interface Camera extends CameraSource {
readonly state: CameraState;
stats(): CameraInStats;
/**
* Ask for the camera again now, while the guest streams and it was
* refused or unavailable ("denied", "unavailable" without a track): call
* it from a click (a browser may only ask again then). Otherwise nothing.
*/
retry(): void;
/** The newest VideoFrame (owned by the camera: clone() it to keep it), or null. */
currentFrame(): VideoFrame | null;
/** Stop for good: releases the camera. */
close(): Promise<void>;
}
/** Chromium's MediaStreamTrackProcessor, which lib.dom does not have. */
type TrackProcessor = new (init: { track: MediaStreamTrack }) => { readable: ReadableStream<VideoFrame> };
type Canvas2D = OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
/** A CameraSource that gives the user's camera to the guest (see the top of this file). */
export function createCamera(opts: CameraOptions = {}): Camera {
const log = opts.log ?? (() => {});
let state: CameraState = "idle", told: CameraState = "idle";
/** The guest's stream, or null. */
let want: CameraFormat | null = null;
let stream: MediaStream | null = null;
let mode: "processor" | "video" | null = null;
/** Bumped by every release: a pipeline that finds it changed stops. */
let epoch = 0;
let asking = false, refused = false, closed = false;
/** The newest converted frame, for which format, and a spare buffer to convert into. */
let latest: Uint8Array | null = null, latestKey = "", spare: Uint8Array | null = null;
let current: VideoFrame | null = null;
/** the frame `latest` was copied from plane for plane (kept only once lastFrame() was asked for), and the one the last read() gave */
let latestFrame: VideoFrame | null = null, readFrame: VideoFrame | null = null, wantFrames = false;
let busy = false, lastAt = 0;
let canvas: OffscreenCanvas | HTMLCanvasElement | null = null, ctx: Canvas2D | null = null;
let planar: Uint8Array | null = null;
let video: HTMLVideoElement | null = null, timer: ReturnType<typeof setInterval> | undefined;
const stats: CameraInStats = { mode: null, trackWidth: 0, trackHeight: 0, converted: 0, scaled: 0, h264: false, colorSpace: opts.colorSpace ? { ...opts.colorSpace } : null, device: "" };
/** A camera frame's colour space: kept for the next H.264 stream's black frames. */
const learn = (c: CameraColour | null): void => {
const k = stats.colorSpace;
if (!c || (k && k.primaries === c.primaries && k.transfer === c.transfer && k.matrix === c.matrix && k.fullRange === c.fullRange)) return;
stats.colorSpace = { ...c };
try { opts.onColorSpace?.({ ...c }); } catch (e) { log(`[camera] onColorSpace failed: ${e}`); }
};
/** H.264: the probe's configurations per size, and the running stream's encoder */
const wc: EncWebCodecs | undefined = opts.webCodecs ?? ((globalThis as { VideoEncoder?: unknown }).VideoEncoder ? (globalThis as unknown as EncWebCodecs) : undefined);
let ladders: H264Ladders | null = null;
let encoder: CameraEncoder | null = null;
const probe: Promise<void> = opts.h264 === false || !wc ? Promise.resolve() : probeH264(wc).then((l) => {
ladders = l;
stats.h264 = !!l;
log(l ? `[camera] H.264 offered (${[...l.values()][0]!.map((r) => `${r.profile.name} ${r.acc}`).join(", ")} at 640x480)` : "[camera] the browser's encoder does not make H.264 at every size: not offered");
}, (e) => log(`[camera] H.264 probe failed: ${(e as Error)?.message ?? e}`));
const keyOf = (f: CameraFormat) => `${f.pixelFormat} ${f.width}x${f.height}`;
const set = (next: CameraState): void => {
if (state === "closed" || next === state) return;
state = next;
queueMicrotask(() => {
if (told === state) return;
told = state;
try { opts.onChange?.(state); } catch (e) { log(`[camera] onChange failed: ${e}`); }
});
};
const release = (): void => {
epoch++;
if (timer !== undefined) clearInterval(timer);
timer = undefined;
if (video) {
video.pause();
video.srcObject = null;
video = null;
}
if (stream) log("[camera] camera released");
if (encoder) stats.encoder = encoder.stats();
encoder?.close();
encoder = null;
stopUserMedia(stream);
stream = null;
current?.close();
current = null;
latestFrame?.close();
latestFrame = readFrame = null;
wantFrames = false;
latest = spare = null;
latestKey = "";
asking = refused = busy = false;
set("idle");
};
const context2d = (w: number, h: number): Canvas2D => {
if (!canvas) {
canvas = typeof OffscreenCanvas === "function" ? new OffscreenCanvas(w, h) : document.createElement("canvas");
ctx = canvas.getContext("2d", { willReadFrequently: true }) as Canvas2D | null;
if (!ctx) throw new Error("no 2D canvas here");
}
if (canvas.width !== w || canvas.height !== h) {
canvas.width = w;
canvas.height = h;
}
return ctx!;
};
/** Draw `src` (sw x sh) into a canvas of w x h, cropped from the centre to its aspect ratio. */
const drawFit = (src: CanvasImageSource, sw: number, sh: number, w: number, h: number): Canvas2D => {
const c = context2d(w, h);
const scale = Math.max(w / sw, h / sh);
const cw = w / scale, ch = h / scale;
c.drawImage(src, (sw - cw) / 2, (sh - ch) / 2, cw, ch, 0, 0, w, h);
return c;
};
/** Draw `src` (sw x sh) into the stream's size, cropped from the centre to its aspect ratio, and convert. */
const drawConvert = (src: CanvasImageSource, sw: number, sh: number, f: CameraFormat, out: Uint8Array): void => {
const c = drawFit(src, sw, sh, f.width, f.height);
const px = c.getImageData(0, 0, f.width, f.height).data;
rgbaTo(f.pixelFormat as CameraPixelFormat, px, f.width, f.height, out);
stats.scaled++;
};
/** H.264: a camera frame of another size as a new frame of the stream's (the encoder closes it). */
const fitFrame = (frame: EncFrame, w: number, h: number, timestamp: number): EncFrame | null => {
drawFit(frame as unknown as CanvasImageSource, frame.displayWidth, frame.displayHeight, w, h);
stats.scaled++;
return new wc!.VideoFrame(canvas, { timestamp });
};
/** H.264: a camera frame to the running stream's encoder (it stays the camera's). */
const encodeFrame = (frame: VideoFrame): void => {
const enc = encoder;
if (!enc) return;
enc.live(true);
enc.frame(frame);
stats.converted++;
if (state !== "running") {
set("running");
log(`[camera] the guest gets the camera: ${stats.trackWidth}x${stats.trackHeight} as H.264 ${want?.width}x${want?.height} at ${want?.fps} fps (${mode})`);
}
};
/** Convert one frame for the guest's stream (at most one at a time, one per frame interval). */
const take = async (frame: VideoFrame | null, el: HTMLVideoElement | null, my: number): Promise<void> => {
const f = want;
const now = performance.now();
if (!f || cameraCompressed(f.pixelFormat) || busy || now - lastAt < 1000 / f.fps / 2) return;
busy = true;
lastAt = now;
let exact: VideoFrame | null = null;
try {
const out = spare && spare.length === f.bytes ? spare : new Uint8Array(f.bytes);
const fmt = frame?.format;
const vr = frame?.visibleRect;
if (frame && vr && (fmt === "NV12" || fmt === "I420") && vr.width === f.width && vr.height === f.height) {
// (cloned first: the frame is the camera's, closed when the next one comes)
if (wantFrames && f.pixelFormat === "NV12") try { exact = frame.clone(); } catch {}
if (fmt === f.pixelFormat && camera420(fmt)) {
// the stream's own format: the planes straight into the guest's layout, no repack
await frame.copyTo(out, { rect: vr, layout: camera420Layout(fmt, f.width, f.height) });
} else {
const size = frame.allocationSize({ rect: vr });
if (!planar || planar.length < size) planar = new Uint8Array(size);
const layout = await frame.copyTo(planar, { rect: vr }) as PlaneLayout[];
yuv420To(planar, layout, fmt, f.width, f.height, f.pixelFormat as CameraPixelFormat, out);
}
} else if (frame) {
drawConvert(frame, frame.displayWidth, frame.displayHeight, f, out);
} else if (el) {
drawConvert(el, el.videoWidth, el.videoHeight, f, out);
} else return;
if (my !== epoch || want !== f) return;
spare = latest && latest.length === f.bytes ? latest : null;
latest = out;
latestKey = keyOf(f);
latestFrame?.close();
latestFrame = exact;
exact = null;
stats.converted++;
if (state !== "running") {
set("running");
log(`[camera] the guest gets the camera: ${stats.trackWidth}x${stats.trackHeight} as ${keyOf(f)} at ${f.fps} fps (${mode})`);
}
} catch (e) {
log(`[camera] a frame failed: ${(e as Error)?.message ?? e}`);
} finally {
exact?.close();
busy = false;
}
};
/** The newest VideoFrame (the seam for consumers without a copy). */
const keep = (frame: VideoFrame): void => {
current?.close();
current = frame;
stats.trackWidth = frame.displayWidth;
stats.trackHeight = frame.displayHeight;
learn(colourOf(frame));
};
const runProcessor = async (track: MediaStreamTrack, my: number): Promise<void> => {
const P = (globalThis as { MediaStreamTrackProcessor?: TrackProcessor }).MediaStreamTrackProcessor!;
const reader = new P({ track }).readable.getReader();
try {
while (my === epoch && !closed) {
const { value, done } = await reader.read();
if (done || !value) break;
if (my !== epoch) {
value.close();
break;
}
keep(value);
if (encoder) encodeFrame(value);
else await take(value, null, my);
}
} finally {
reader.cancel().catch(() => {});
}
};
const runVideo = async (s: MediaStream, my: number): Promise<void> => {
const v = document.createElement("video");
v.muted = true;
v.playsInline = true;
v.srcObject = s;
video = v;
await v.play();
const VF = (globalThis as { VideoFrame?: typeof VideoFrame }).VideoFrame;
const step = (): void => {
if (my !== epoch || !v.videoWidth) return;
stats.trackWidth = v.videoWidth;
stats.trackHeight = v.videoHeight;
let frame: VideoFrame | null = null;
try { if (VF) frame = new VF(v, { timestamp: Math.round(performance.now() * 1000) }); } catch {}
if (frame) keep(frame);
if (encoder) {
if (frame) encodeFrame(frame);
} else void take(frame, frame ? null : v, my);
};
const rvfc = (v as HTMLVideoElement & { requestVideoFrameCallback?: (cb: () => void) => number }).requestVideoFrameCallback;
if (rvfc) {
const loop = (): void => {
if (my !== epoch) return;
step();
rvfc.call(v, loop);
};
rvfc.call(v, loop);
} else {
timer = setInterval(step, 1000 / (want?.fps ?? 30));
}
};
/** The guest streams `f`: ask for the camera, or go on with the one there is (the conversion follows `want`). */
const start = (f: CameraFormat): void => {
if (closed || refused || stream || asking) return;
asking = true;
set("asking");
const my = ++epoch;
log(`[camera] a guest program streams ${keyOf(f)} at ${f.fps} fps: asking for the camera`);
const constraints: MediaTrackConstraints = {
width: { ideal: f.width }, height: { ideal: f.height }, frameRate: { ideal: f.fps },
...opts.constraints,
};
void requestUserMedia({ video: constraints, audio: false }, "camera").then(async (r) => {
asking = false;
if (my !== epoch || closed || !want) {
if ("stream" in r) stopUserMedia(r.stream);
return;
}
if (!("stream" in r)) {
log(`[camera] ${r.message}; the guest gets black frames`);
if (r.error === "denied") {
refused = true;
set("denied");
} else set("unavailable");
return;
}
stream = r.stream;
const track = r.stream.getVideoTracks()[0];
if (!track) {
log("[camera] the stream has no video track; the guest gets black frames");
set("unavailable");
return;
}
track.addEventListener("ended", () => {
if (my !== epoch) return;
log("[camera] the camera's track ended; the guest gets black frames");
latest = null;
encoder?.live(false);
set("unavailable");
});
const s = track.getSettings();
stats.trackWidth = s.width ?? 0;
stats.trackHeight = s.height ?? 0;
const hasProcessor = typeof (globalThis as { MediaStreamTrackProcessor?: unknown }).MediaStreamTrackProcessor === "function";
mode = stats.mode = hasProcessor ? "processor" : "video";
log(`[camera] the camera runs at ${s.width}x${s.height}, ${s.frameRate} fps; frames through ${hasProcessor ? "MediaStreamTrackProcessor" : "a video element"}`);
try {
await (hasProcessor ? runProcessor(track, my) : runVideo(r.stream, my));
} catch (e) {
if (my === epoch) {
log(`[camera] ${(e as Error)?.message ?? e}; the guest gets black frames`);
set("unavailable");
}
}
});
};
return {
get compressed(): readonly CameraCodec[] {
return ladders ? ["H264"] : [];
},
prepare: () => probe,
onStream(f: CameraFormat | null, chunks?: CameraChunkSink): void {
if (closed) return;
if (encoder) stats.encoder = encoder.stats();
encoder?.close();
encoder = null;
if (!f) {
want = null;
release();
return;
}
want = { ...f };
lastAt = 0;
if (cameraCompressed(f.pixelFormat)) {
const ladder = ladders?.get(`${f.width}x${f.height}`);
if (!chunks || !wc || !ladder?.length) log(`[camera] an H.264 stream of ${f.width}x${f.height} without an encoder for it: the guest gets nothing`);
else encoder = new CameraEncoder(want, chunks, { wc, ladder, log, fit: fitFrame, colorSpace: stats.colorSpace, onColorSpace: learn });
// the camera, if it runs already, goes on into the encoder
if (encoder && stream && state === "running") encoder.live(true);
}
start(want);
},
keyFrame(): void {
encoder?.keyFrame();
},
onControls(f: CameraFormat): void {
if (want && f.bitrate) want.bitrate = f.bitrate;
if (want && f.keyInterval) want.keyInterval = f.keyInterval;
encoder?.controls(f);
},
read(out: Uint8Array, f: CameraFormat): boolean {
if (cameraCompressed(f.pixelFormat)) return false;
if (!latest || latestKey !== keyOf(f) || latest.length !== out.length) return false;
out.set(latest);
readFrame = latestFrame;
return true;
},
lastFrame(): VideoFrame | null {
wantFrames = true;
return readFrame && readFrame === latestFrame ? readFrame : null;
},
currentFrame: () => current,
get state() { return state; },
stats: () => ({ ...stats, colorSpace: stats.colorSpace && { ...stats.colorSpace }, ...(encoder ? { encoder: encoder.stats() } : {}), device: stream?.getVideoTracks()[0]?.label ?? "" }),
retry(): void {
if (closed || !want || stream || asking || (state !== "denied" && state !== "unavailable")) return;
refused = false;
start(want);
},
async close(): Promise<void> {
if (closed) return;
want = null;
release();
closed = true;
set("closed");
state = "closed";
},
};
}