// SPDX-License-Identifier: MIT // Copyright (C) 2026 Pooya Parsa // The camera's H.264 encoder (WebCodecs), for kwcam's compressed format // (core/camera.ts): the browser encodes the camera's frames and the guest // copies the stream, as from a UVC camera with its own encoder. Used by // createCamera() (camera.ts); the WebCodecs classes are passed in, so it // runs on stand-ins (test/camera.test.ts). // // - probeH264(): before the kernel boots (kwcam's formats are fixed at its // init), VideoEncoder.isConfigSupported for each size kwcam offers, for // Constrained Baseline, Main and High, with prefer-hardware and then // no-preference: a ladder of configurations per size, tried in that // order. H.264 is offered only when every size has one. // - CameraEncoder, one per guest stream: a VideoEncoder configured at the // stream's size, rate and bitrate (`latencyMode: "realtime"`: no // B-frames, a chunk per frame, in order; `avc: { format: "annexb" }`), // the codec string at the level the stream needs (core/camera-h264.ts). // The camera's VideoFrames are encoded as they are (wrapped with the // stream's own timestamps; never closed here: they stay the camera's), // one per frame interval at most; a frame of another size is fitted // (`fit`: the caller draws it into the stream's size, cropped from the // centre, as the raw path does), so the stream's SPS says the size the // guest negotiated. Until the camera runs (not granted yet, refused, no // camera, the track ended or stalled for a second) black frames go // through the same encoder at the stream's rate, so a program never // waits; the first camera frame after them is a key frame. While it runs, // a frame the camera is late with (none three quarters of an interval // past its time: a camera warming up, slower than the stream, or a busy // page) is its last frame again, so chunks come at the stream's rate from // the start (`repeated`). Black frames are tagged with the camera's // colour space (the last one seen, `colorSpace` before: BT.709 limited by // default, what HD webcams give), as the encoder writes each frame's into // the SPS's VUI and starts a new SPS where it changes: so the stream's // VUI stays the same when the camera starts and after a stall (a camera // of another colour space than the one given changes it once, at its // first frame, a key frame anyway); full range black is Y 0. Key frames: // the first, one every key interval (the guest's GOP size), and when // asked (keyFrame(): the guest's FORCE_KEY_FRAME, or the host dropped // chunks). A key frame without SPS and PPS gets the last ones (or the // avcC's) in front. Frames are dropped while the encoder holds more than // two. // - Recovery (as core/va-enc.ts): an encoder error or a reclamation // (QuotaExceededError, also an encoder found closed) makes a new encoder // at the next frame, a key frame first; a configuration that fails // before its first chunk moves down the ladder; frames in the encoder // for 2 s without a chunk count as a failure. After RECOVER_MAX failures // in a row without a chunk it waits a second before the next try (and // tries again from the top of the ladder), so the stream comes back when // the encoder does. What a lost encoder held is not encoded again: the // stream goes on at a key frame. import type { CameraChunkSink, CameraFormat } from "../core/camera.ts"; import { CHUNK_CLOCK } from "../core/camera-chunks.ts"; import { H264_PROFILES, avccToAnnexB, constrainBaseline, h264Codec, parameterSets, withParameterSets, type H264Profile } from "../core/camera-h264.ts"; /** The sizes kwcam offers (drivers/media/platform/kwcam.c kwcam_sizes). */ export const CAMERA_SIZES: readonly (readonly [number, number])[] = [[320, 240], [640, 480], [1280, 720]]; /** The part of a VideoFrame used here. */ export interface EncFrame { readonly displayWidth: number; readonly displayHeight: number; readonly timestamp?: number; readonly colorSpace?: { primaries?: string | null; transfer?: string | null; matrix?: string | null; fullRange?: boolean | null } | null; close(): void; } /** The part of an EncodedVideoChunk used here. */ export interface EncChunk { readonly type: string; readonly byteLength: number; readonly timestamp: number; copyTo(dest: Uint8Array): void; } export interface EncVideoEncoder { readonly state: string; readonly encodeQueueSize: number; configure(config: object): void; encode(frame: EncFrame, opts?: { keyFrame?: boolean }): void; close(): void; } /** VideoEncoder and VideoFrame (globalThis's, or stand-ins). */ export interface EncWebCodecs { VideoEncoder: { new (init: { output: (chunk: EncChunk, meta?: { decoderConfig?: { description?: BufferSource } }) => void; error: (e: Error) => void }): EncVideoEncoder; isConfigSupported(config: object): Promise<{ supported?: boolean }>; }; VideoFrame: new (source: any, init?: any) => EncFrame; } /** One configuration to try: a profile and a hardwareAcceleration. */ export interface H264Rung { profile: H264Profile; acc: "prefer-hardware" | "no-preference"; } /** Per size ("WxH"), the configurations isConfigSupported took, in the order to try them. */ export type H264Ladders = Map; const sizeKey = (w: number, h: number) => `${w}x${h}`; /** The stream's bitrate where the guest has none: about 0.1 bit a pixel (as kwcam's control follows). */ export const autoBitrate = (w: number, h: number, fps: number) => Math.max(50_000, Math.round(w * h * fps / 10)); function encoderConfig(f: CameraFormat, rung: H264Rung): Record { const bitrate = f.bitrate || autoBitrate(f.width, f.height, f.fps); return { codec: h264Codec(rung.profile, f.width, f.height, f.fps, bitrate), width: f.width, height: f.height, bitrate, framerate: f.fps, latencyMode: "realtime", hardwareAcceleration: rung.acc, avc: { format: "annexb" }, }; } /** * Which H.264 configurations the browser's encoder takes at each of * kwcam's sizes (at 30 frames a second and the default bitrate), or null * when some size has none (or there is no VideoEncoder). */ export async function probeH264(wc: EncWebCodecs | undefined, sizes = CAMERA_SIZES): Promise { if (!wc?.VideoEncoder || typeof wc.VideoEncoder.isConfigSupported !== "function" || !wc.VideoFrame) return null; const out: H264Ladders = new Map(); await Promise.all(sizes.map(async ([w, h]) => { const tries: H264Rung[] = []; for (const acc of ["prefer-hardware", "no-preference"] as const) for (const profile of H264_PROFILES) tries.push({ profile, acc }); const f: CameraFormat = { pixelFormat: "H264", width: w, height: h, fps: 30, bytes: w * h * 3 / 2 }; const ok = await Promise.all(tries.map((r) => wc.VideoEncoder.isConfigSupported(encoderConfig(f, r)).then((s) => !!s?.supported, () => false))); out.set(sizeKey(w, h), tries.filter((_, i) => ok[i])); })); return [...out.values()].every((l) => l.length) ? out : null; } /** Failures in a row without a chunk before a pause, the pause, and how long frames may wait in the encoder for a chunk. */ const RECOVER_MAX = 3; const RETRY_MS = 1000; const STALL_MS = 2000; /** Without a camera frame for this long, black frames again. */ const CAMERA_IDLE_MS = 1000; /** A camera frame this many intervals past its time is late: the last one is encoded again in its place. */ const LATE = 0.75; /** Timer ticks a frame interval (for black frames and late ones). */ const TICKS = 4; /** A VideoFrame's colour space (VideoColorSpaceInit's fields). */ export interface CameraColour { primaries: string | null; transfer: string | null; matrix: string | null; fullRange: boolean | null; } /** Black frames' colour space before the camera's is known: BT.709 limited range. */ export const DEFAULT_COLOUR: CameraColour = { primaries: "bt709", transfer: "bt709", matrix: "bt709", fullRange: false }; /** A frame's colour space, or null when it names none. */ export function colourOf(f: { colorSpace?: { primaries?: string | null; transfer?: string | null; matrix?: string | null; fullRange?: boolean | null } | null }): CameraColour | null { let cs; try { cs = f.colorSpace; } catch { return null; } if (!cs) return null; const c: CameraColour = { primaries: cs.primaries ?? null, transfer: cs.transfer ?? null, matrix: cs.matrix ?? null, fullRange: cs.fullRange ?? null }; return c.primaries === null && c.transfer === null && c.matrix === null && c.fullRange === null ? null : c; } const sameColour = (a: CameraColour | null, b: CameraColour | null) => !!a && !!b && a.primaries === b.primaries && a.transfer === b.transfer && a.matrix === b.matrix && a.fullRange === b.fullRange; /** Frames the encoder may hold before new ones are dropped. */ const BACKLOG = 2; /** What a CameraEncoder did. */ export interface CameraEncoderStats { /** frames encoded, of them black, of them the camera's last frame again (it was late), frames dropped (not due, or the encoder busy), chunks out, key frames out, bytes out */ frames: number; black: number; repeated: number; skipped: number; chunks: number; keyFrames: number; bytes: number; /** chunks the guest's side dropped (it asked for a key frame then) */ dropped: number; /** encoder errors, reclamations, encoders made, configurations moved past, key frames given SPS and PPS */ errors: number; reclaims: number; encoders: number; fallbacks: number; setsAdded: number; /** the configuration in use, or null */ codec: string | null; hardwareAcceleration: string | null; /** the colour space black frames get (the camera's once seen) */ colorSpace: CameraColour; } export interface CameraEncoderOptions { wc: EncWebCodecs; /** the configurations to try (probeH264()'s for the stream's size) */ ladder: readonly H264Rung[]; log?: (msg: string) => void; /** ms clock (default performance.now) */ now?: () => number; /** timers (default setInterval / clearInterval) */ setInterval?: (fn: () => void, ms: number) => unknown; clearInterval?: (t: unknown) => void; /** A frame of another size: a new frame of width x height (cropped from the centre to its aspect, then scaled) with that timestamp, or null; the encoder closes it. */ fit?: (frame: EncFrame, width: number, height: number, timestamp: number) => EncFrame | null; /** Black frames' colour space until a camera frame names one (the camera's from an earlier stream); default DEFAULT_COLOUR. */ colorSpace?: CameraColour | null; /** A camera frame named another colour space than black frames had (to remember it for the next stream). */ onColorSpace?: (c: CameraColour) => void; } /** The encoder of one guest stream (see the top of this file). */ export class CameraEncoder { readonly #f: CameraFormat; readonly #sink: CameraChunkSink; readonly #o: CameraEncoderOptions; readonly #now: () => number; readonly #log: (msg: string) => void; #enc: EncVideoEncoder | null = null; #configKey = ""; #rung = 0; #everOutput = false; #fails = 0; #retryAt = 0; #needKey = true; #sinceKey = 0; #inflight = 0; #progressAt = 0; #t0: number; /** CHUNK_CLOCK less `now`: a chunk's capture time from its timestamp */ #toChunkClock: number; #lastTs = -1; #nextDue = -Infinity; #live = false; #lastCameraAt = -Infinity; #lastBlack = true; /** the newest camera frame (the caller's: valid until its next frame() or close()), for a late one */ #last: EncFrame | null = null; #colour: CameraColour; #sets: Uint8Array | null = null; #black: Uint8Array | null = null; #blackY = -1; #timer: unknown; #closed = false; #warned = new Set(); readonly #stats: CameraEncoderStats = { frames: 0, black: 0, repeated: 0, skipped: 0, chunks: 0, keyFrames: 0, bytes: 0, dropped: 0, errors: 0, reclaims: 0, encoders: 0, fallbacks: 0, setsAdded: 0, codec: null, hardwareAcceleration: null, colorSpace: DEFAULT_COLOUR }; constructor(format: CameraFormat, sink: CameraChunkSink, opts: CameraEncoderOptions) { this.#f = { ...format }; this.#sink = sink; this.#o = opts; this.#now = opts.now ?? (() => performance.now()); this.#log = opts.log ?? (() => {}); this.#colour = { ...(opts.colorSpace ?? DEFAULT_COLOUR) }; this.#t0 = this.#now(); this.#toChunkClock = CHUNK_CLOCK() - this.#t0; const si = opts.setInterval ?? ((fn: () => void, ms: number) => setInterval(fn, ms)); this.#timer = si(() => this.#tick(), 1000 / format.fps / TICKS); this.#tick(); } stats(): CameraEncoderStats { return { ...this.#stats, colorSpace: { ...this.#colour } }; } #once(key: string, msg: string): void { if (this.#warned.has(key)) return; this.#warned.add(key); this.#log(msg); } /** The camera runs (its frames come to frame()) or not (black frames until it does). */ live(on: boolean): void { this.#live = on; } /** The next frame is a key frame. */ keyFrame(): void { this.#needKey = true; } /** The guest changed the bitrate or key interval. */ controls(f: CameraFormat): void { if (f.bitrate) this.#f.bitrate = f.bitrate; if (f.keyInterval) this.#f.keyInterval = f.keyInterval; const enc = this.#enc; if (!enc || enc.state === "closed") return; const cfg = encoderConfig(this.#f, this.#o.ladder[this.#rung]!), key = JSON.stringify(cfg); if (key === this.#configKey) return; try { enc.configure(cfg); this.#configKey = key; this.#stats.codec = cfg.codec as string; } catch (e) { this.#failed(enc, e as Error); } } close(): void { if (this.#closed) return; this.#closed = true; this.#last = null; (this.#o.clearInterval ?? ((t: unknown) => clearInterval(t as ReturnType)))(this.#timer); this.#closeEncoder(); } /** A camera frame (it stays the caller's, valid until its next frame() or close(): the last one is encoded again where the next is late). */ frame(vf: EncFrame): void { if (this.#closed) return; const now = this.#now(); this.#lastCameraAt = now; this.#last = vf; const c = colourOf(vf); if (c && !sameColour(c, this.#colour)) { this.#colour = c; try { this.#o.onColorSpace?.({ ...c }); } catch {} } if (!this.#live) return; // (the first camera frame after black ones is taken at once) if (this.#lastBlack) this.#nextDue = -Infinity; if (!this.#due(now)) return; this.#camera(vf, now); } /** A camera frame to the encoder now (wrapped with the stream's timestamp, or fitted). */ #camera(vf: EncFrame, now: number): void { const ts = this.#ts(now); let input: EncFrame | null = null; try { if (vf.displayWidth === this.#f.width && vf.displayHeight === this.#f.height) input = new this.#o.wc.VideoFrame(vf, { timestamp: ts }); else { input = this.#o.fit?.(vf, this.#f.width, this.#f.height, ts) ?? null; if (!input) this.#once("fit", `[camera] a ${vf.displayWidth}x${vf.displayHeight} frame for a ${this.#f.width}x${this.#f.height} stream cannot be fitted: dropped`); } } catch (e) { this.#once("wrap", `[camera] a camera frame could not be taken for the encoder: ${(e as Error)?.message ?? e}`); } if (!input) return; if (this.#lastBlack) this.#needKey = true; this.#lastBlack = false; this.#encode(input, ts); } /** At the stream's rate: a black frame while the camera does not run; the stall check. */ #tick(): void { if (this.#closed) return; const now = this.#now(); if (this.#enc && this.#inflight > 0 && now - this.#progressAt > STALL_MS) { this.#log(`[camera] the H.264 encoder gave nothing for ${STALL_MS} ms: made again`); this.#failed(this.#enc, new Error("stalled")); } if (this.#live && now - this.#lastCameraAt < CAMERA_IDLE_MS) { // the camera runs, but its frame is late: the last one again in its place const iv = 1000 / this.#f.fps; if (this.#last && !this.#lastBlack && now >= this.#nextDue + LATE * iv && this.#due(now)) { this.#stats.repeated++; this.#camera(this.#last, now); } return; } if (!this.#due(now, false)) return; const f = this.#f, n = f.width * f.height, cs = this.#colour, y = cs.fullRange ? 0 : 16; if (!this.#black || this.#blackY !== y) { this.#black = new Uint8Array(n * 3 / 2); this.#black.fill(y, 0, n); this.#black.fill(128, n); this.#blackY = y; } const ts = this.#ts(now); let input: EncFrame; try { input = new this.#o.wc.VideoFrame(this.#black, { format: "I420", codedWidth: f.width, codedHeight: f.height, timestamp: ts, colorSpace: { ...cs }, }); } catch (e) { this.#once("black", `[camera] no black frame: ${(e as Error)?.message ?? e}`); return; } if (!this.#lastBlack) this.#needKey = true; this.#lastBlack = true; this.#stats.black++; this.#encode(input, ts); } /** At most one frame a frame interval (a little early is on time). */ #due(now: number, camera = true): boolean { const iv = 1000 / this.#f.fps; if (now < this.#nextDue - iv / 4) { // (a camera frame dropped; the timer's ticks between frames are not) if (camera) this.#stats.skipped++; return false; } this.#nextDue = now - this.#nextDue > iv ? now + iv : this.#nextDue + iv; return true; } /** The stream's timestamp (µs from its start), increasing. */ #ts(now: number): number { const ts = Math.max(this.#lastTs + 1, Math.round((now - this.#t0) * 1000)); this.#lastTs = ts; return ts; } /** One frame to the encoder (made and configured where needed); `input` is closed here. */ #encode(input: EncFrame, _ts: number): void { try { const now = this.#now(); if (this.#enc && this.#enc.state === "closed") this.#failed(this.#enc, Object.assign(new Error("the encoder was closed"), { name: "QuotaExceededError" })); // (a configuration that throws: the next rung at once) for (let i = 0; !this.#enc && now >= this.#retryAt && i < this.#o.ladder.length; i++) this.#make(); if (!this.#enc) return; const enc = this.#enc!; if (enc.encodeQueueSize > BACKLOG) { this.#stats.skipped++; return; } const ki = Math.max(1, this.#f.keyInterval || Math.round(this.#f.fps)); const key = this.#needKey || this.#sinceKey >= ki; try { enc.encode(input, { keyFrame: key }); } catch (e) { this.#failed(enc, e as Error); return; } this.#needKey = false; this.#sinceKey = key ? 1 : this.#sinceKey + 1; if (this.#inflight++ === 0) this.#progressAt = now; this.#stats.frames++; } finally { try { input.close(); } catch {} } } #make(): void { const ladder = this.#o.ladder; if (!ladder.length) { this.#once("ladder", "[camera] no H.264 configuration to try"); return; } if (this.#rung >= ladder.length) this.#rung = 0; const rung = ladder[this.#rung]!, cfg = encoderConfig(this.#f, rung); const enc: EncVideoEncoder = new this.#o.wc.VideoEncoder({ output: (chunk, meta) => this.#output(enc, chunk, meta), error: (e) => this.#failed(enc, e), }); this.#enc = enc; this.#everOutput = false; this.#inflight = 0; this.#needKey = true; this.#stats.encoders++; try { enc.configure(cfg); } catch (e) { this.#failed(enc, e as Error); return; } this.#configKey = JSON.stringify(cfg); this.#stats.codec = cfg.codec as string; this.#stats.hardwareAcceleration = rung.acc; if (this.#stats.encoders === 1) this.#log(`[camera] H.264 encoder: ${cfg.codec} ${this.#f.width}x${this.#f.height} at ${this.#f.fps} fps, ${cfg.bitrate} bit/s, ${rung.acc}`); } #output(enc: EncVideoEncoder, chunk: EncChunk, meta?: { decoderConfig?: { description?: BufferSource } }): void { if (enc !== this.#enc || this.#closed) return; this.#everOutput = true; this.#fails = 0; this.#inflight = Math.max(0, this.#inflight - 1); this.#progressAt = this.#now(); let data: Uint8Array = new Uint8Array(chunk.byteLength); chunk.copyTo(data); const key = chunk.type === "key"; if (key) { const desc = meta?.decoderConfig?.description; const sets = parameterSets(data) ?? (desc ? avccToAnnexB(desc instanceof Uint8Array ? desc : ArrayBuffer.isView(desc) ? new Uint8Array(desc.buffer, desc.byteOffset, desc.byteLength) : new Uint8Array(desc)) : null); if (sets) this.#sets = sets; const full = withParameterSets(data, this.#sets); if (!full) this.#once("sets", "[camera] the encoder's key frame has no SPS and PPS, and none came before: the guest gets it as it is"); else if (full !== data) { this.#stats.setsAdded++; data = full; } if (constrainBaseline(data)) this.#once("cb", "[camera] the encoder's Baseline stream is marked Constrained Baseline for the guest's decoders"); } this.#stats.chunks++; this.#stats.bytes += data.length; if (key) this.#stats.keyFrames++; // (the chunk's timestamp is its frame's, from this stream's clock: the guest's buffer gets the capture time) if (!this.#sink.push(data, key, this.#t0 + chunk.timestamp / 1000 + this.#toChunkClock)) this.#stats.dropped++; } #closeEncoder(): void { const enc = this.#enc; this.#enc = null; this.#inflight = 0; if (enc && enc.state !== "closed") { try { enc.close(); } catch {} } } /** The encoder failed or was reclaimed: a new one at the next frame (see the top). */ #failed(enc: EncVideoEncoder, err: Error): void { if (enc !== this.#enc || this.#closed) return; const reclaimed = err?.name === "QuotaExceededError"; const ever = this.#everOutput; this.#closeEncoder(); this.#needKey = true; if (reclaimed) { this.#stats.reclaims++; this.#log(`[camera] the browser reclaimed the H.264 encoder: made again, a key frame next`); return; } this.#stats.errors++; this.#log(`[camera] H.264 encoder error: ${err?.name ?? "Error"}: ${err?.message ?? err}`); if (!ever && this.#rung + 1 < this.#o.ladder.length) { this.#rung++; this.#stats.fallbacks++; return; } if (++this.#fails >= RECOVER_MAX) { this.#fails = 0; this.#rung = 0; this.#retryAt = this.#now() + RETRY_MS; this.#log(`[camera] the H.264 encoder failed ${RECOVER_MAX} times in a row: trying again in ${RETRY_MS} ms`); } } }