Something went wrong. Try again.
An experimental port of NetBSD, FreeBSD, OpenBSD, and XNU to unkernel unkernel.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355// SPDX-License-Identifier: MIT// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>// A compressed camera stream on its way to the guest (kwcam's H.264,// camera.ts): the chunks a source's encoder gives, in order, each once.// Universal.//// - The rules (ChunkGate): the first chunk of a stream must be a key frame;// a chunk that does not fit (more chunks than CHUNK_QUEUE_MAX waiting, or// bytes past the capacity: a guest that does not take them) or that is// larger than the guest's buffers (the format's `bytes`) is dropped, and// so is every chunk after it up to the next key frame, which is asked for// (`onKeyWanted`; again when a key frame is dropped, the answer to the// last ask, at most every KEY_ASK_MS); so the guest sees a gap only// before a key frame and the stream it copies stays decodable. What// waits stays: the newest are dropped, not the oldest.// - CameraChunkQueue: the chunks as a queue on one thread, read by the// kernel's frame import: inline (the source pushes from the kernel's// thread), and the worker's side without shared memory ("camera-chunk"// messages, worker-serve.ts).// - The chunk ring: the same between threads on a SharedArrayBuffer, from// one producer (the owner's CameraBridge, which the source pushes into)// to one consumer (the worker's frame import). Records never wrap: one// that does not fit before the end goes to the start, and the reader// skips the rest (a WRAP record, or less room than a record header).// COUNT is the publish point (the writer adds to it after the record is// written; the reader takes from it after it read one), USED the bytes// held, padding and skipped ends included. Each record has its stream's// generation (the reader's starts): the reader drops records of another.// - Each chunk carries when its frame was captured (`at`, ms on// CHUNK_CLOCK, which threads of one process share; the push's time where// the source gives none), so the reader says how old it is: the kernel// back-dates the buffer's timestamp by that much.
/** Chunks waiting at most (about a second at 30 frames a second): more, and the newest are dropped. */export const CHUNK_QUEUE_MAX = 32;/** Bytes of chunks waiting at most (the queue), and the ring's data size. */export const CHUNK_QUEUE_BYTES = 4 << 20;
/** A key frame asked for again at most this often while key frames are dropped. */export const KEY_ASK_MS = 200;
/** A clock that the threads of one process share (ms). */export const CHUNK_CLOCK = (): number => performance.timeOrigin + performance.now();
/** One chunk of the stream as the guest gets it. */export interface ChunkRead { bytes: number; key: boolean; /** ms it waited since it was pushed */ ageMs: number;}
/** What a stream's chunks went through: pushed (and key frames of them), delivered, dropped (by the rules above, and of those too large). */export interface ChunkCounts { pushed: number; keys: number; delivered: number; dropped: number; tooLarge: number;}
const counts = (): ChunkCounts => ({ pushed: 0, keys: 0, delivered: 0, dropped: 0, tooLarge: 0 });
/** The rules for one stream (see the top): whether a chunk is taken, given whether it fits. */export class ChunkGate { #needKey = true; #askedAt = -Infinity; readonly counts = counts(); readonly #maxBytes: number; readonly #onKeyWanted: () => void; readonly #clock: () => number;
constructor(maxBytes: number, onKeyWanted: () => void, clock: () => number = CHUNK_CLOCK) { this.#maxBytes = maxBytes; this.#onKeyWanted = onKeyWanted; this.#clock = clock; }
/** A chunk of `bytes` (a key frame or not): true if it goes in; `fits` says whether there is room for it. */ admit(bytes: number, key: boolean, fits: () => boolean): boolean { this.counts.pushed++; if (key) this.counts.keys++; if (bytes <= 0 || bytes > this.#maxBytes) { this.counts.tooLarge++; return this.#drop(key); } if (this.#needKey && !key) return this.#drop(false, false); if (!fits()) return this.#drop(key); this.#needKey = false; return true; }
/** Drop it and wait for a key frame; ask for one where this starts a gap, or where a key frame (the last answer) was dropped. */ #drop(wasKey: boolean, ask = true): boolean { this.counts.dropped++; const first = !this.#needKey; this.#needKey = true; const now = this.#clock(); if (ask && (first || (wasKey && now - this.#askedAt >= KEY_ASK_MS))) { this.#askedAt = now; try { this.#onKeyWanted(); } catch {} } return false; }
/** The reader dropped something (a record too large for the guest's buffer): wait for a key frame. */ gap(): void { this.#drop(false); this.counts.dropped--; }}
/** The chunks of one stream as a queue (see the top). */export class CameraChunkQueue { readonly gate: ChunkGate; #chunks: { data: Uint8Array; key: boolean; at: number }[] = []; #bytes = 0; #skipToKey = false; readonly #clock: () => number;
/** `maxBytes`: the guest's buffer size (the format's bytes); `onKeyWanted`: ask the source for a key frame. */ constructor(maxBytes: number, onKeyWanted: () => void, clock: () => number = CHUNK_CLOCK) { this.gate = new ChunkGate(maxBytes, onKeyWanted, clock); this.#clock = clock; }
get length(): number { return this.#chunks.length; }
/** A chunk from the source (its bytes are kept: give a copy it will not change); `at`: when (CHUNK_CLOCK), default now. */ push(data: Uint8Array, key: boolean, at?: number): boolean { const fits = () => this.#chunks.length < CHUNK_QUEUE_MAX && this.#bytes + data.length <= CHUNK_QUEUE_BYTES; if (!this.gate.admit(data.length, key, fits)) return false; this.#chunks.push({ data, key, at: at ?? this.#clock() }); this.#bytes += data.length; return true; }
/** The oldest chunk into `out` (a guest buffer), or null when none waits. One larger than `out` is dropped, with what follows up to a key frame. */ read(out: Uint8Array): ChunkRead | null { for (;;) { const c = this.#chunks.shift(); if (!c) return null; this.#bytes -= c.data.length; if (this.#skipToKey && !c.key) { this.gate.counts.dropped++; continue; } this.#skipToKey = false; if (c.data.length > out.length) { this.gate.counts.tooLarge++; this.gate.counts.dropped++; this.#skipToKey = true; this.gate.gap(); continue; } out.set(c.data); this.gate.counts.delivered++; return { bytes: c.data.length, key: c.key, ageMs: Math.max(0, this.#clock() - c.at) }; } }
clear(): void { this.#chunks = []; this.#bytes = 0; }}
// ---- the chunk ring ----
const HEAD = 0, TAIL = 1, USED = 2, COUNT = 3, GEN = 4, DROPPED = 5, SKIPPED = 6, PUSHED = 7, KEYS = 8, TOO_LARGE = 9;export const CHUNK_RING_HEADER_BYTES = 64;/** A record: len, flags, gen, 0, at (f64), then the chunk; 8-byte aligned. */const REC = 24;const F_KEY = 1, F_WRAP = 2;
/** Allocate a chunk ring of `bytes` of data (a multiple of 8, at least 64 KiB). */export function createChunkRing(bytes = CHUNK_QUEUE_BYTES): SharedArrayBuffer { if (!Number.isInteger(bytes) || bytes < 65536 || bytes % 8) throw new RangeError(`chunk ring size must be a multiple of 8 >= 65536, got ${bytes}`); return new SharedArrayBuffer(CHUNK_RING_HEADER_BYTES + bytes);}
function ringViews(buffer: SharedArrayBuffer): { ctrl: Int32Array; dv: DataView; bytes: Uint8Array; cap: number } { const cap = buffer.byteLength - CHUNK_RING_HEADER_BYTES; if (cap < 65536 || cap % 8) throw new RangeError(`invalid chunk ring byteLength ${buffer.byteLength}`); return { ctrl: new Int32Array(buffer, 0, CHUNK_RING_HEADER_BYTES >> 2), dv: new DataView(buffer, CHUNK_RING_HEADER_BYTES, cap), bytes: new Uint8Array(buffer, CHUNK_RING_HEADER_BYTES, cap), cap };}
const align8 = (n: number) => (n + 7) & ~7;
/** The producer's side (the owner's thread), one per ring; a stream's rules (ChunkGate) come with each start(). */export class ChunkRingWriter { readonly #ctrl: Int32Array; readonly #dv: DataView; readonly #bytes: Uint8Array; readonly #cap: number; #head = 0; #gen = -1; #gate: ChunkGate | null = null; readonly #clock: () => number;
constructor(buffer: SharedArrayBuffer, clock: () => number = CHUNK_CLOCK) { const v = ringViews(buffer); this.#ctrl = v.ctrl; this.#dv = v.dv; this.#bytes = v.bytes; this.#cap = v.cap; this.#head = Atomics.load(this.#ctrl, HEAD); this.#clock = clock; }
/** A stream numbered `gen` starts: chunks of up to `maxBytes`, a key frame first. */ start(gen: number, maxBytes: number, onKeyWanted: () => void): ChunkGate { this.#gen = gen | 0; this.#gate = new ChunkGate(maxBytes, onKeyWanted, this.#clock); return this.#gate; }
stop(): void { this.#gate = null; }
/** A chunk of the running stream (copied), captured at `at` (default now); false when dropped (or no stream runs). */ push(data: Uint8Array, key: boolean, at?: number): boolean { const gate = this.#gate; if (!gate) return false; const size = align8(REC + data.length); let skip = 0; const fits = (): boolean => { if (size > this.#cap) return false; const room = this.#cap - this.#head; skip = room < size ? room : 0; return Atomics.load(this.#ctrl, COUNT) < CHUNK_QUEUE_MAX && skip + size <= this.#cap - Atomics.load(this.#ctrl, USED); }; const large = gate.counts.tooLarge; Atomics.add(this.#ctrl, PUSHED, 1); if (key) Atomics.add(this.#ctrl, KEYS, 1); if (!gate.admit(data.length, key, fits)) { Atomics.add(this.#ctrl, DROPPED, 1); if (gate.counts.tooLarge !== large) Atomics.add(this.#ctrl, TOO_LARGE, 1); return false; } if (skip) { if (skip >= REC) this.#dv.setInt32(this.#head + 4, F_WRAP, true); this.#head = 0; } const o = this.#head; this.#dv.setInt32(o, data.length, true); this.#dv.setInt32(o + 4, key ? F_KEY : 0, true); this.#dv.setInt32(o + 8, this.#gen, true); this.#dv.setInt32(o + 12, 0, true); this.#dv.setFloat64(o + 16, at ?? this.#clock(), true); this.#bytes.set(data, o + REC); this.#head = (o + size) % this.#cap; Atomics.store(this.#ctrl, HEAD, this.#head); Atomics.add(this.#ctrl, USED, skip + size); Atomics.add(this.#ctrl, COUNT, 1); return true; }
/** Records the writer dropped, and the reader skipped (another stream's, or too large for the guest's buffer). */ counts(): { dropped: number; skipped: number } { return { dropped: Atomics.load(this.#ctrl, DROPPED), skipped: Atomics.load(this.#ctrl, SKIPPED) }; }}
/** The consumer's side (the worker's kernel), exactly one per ring. */export class ChunkRingReader { readonly #ctrl: Int32Array; readonly #dv: DataView; readonly #bytes: Uint8Array; readonly #cap: number; #tail = 0; #gen = 0; #skipToKey = false; readonly #clock: () => number; /** chunks delivered, and dropped here (another stream's, too large, or after a too large one up to a key frame) */ delivered = 0; dropped = 0;
/** The counts so far (the writer's too: chunks pushed, of them key frames, dropped there and too large), for ChunkCounts. */ totals(): ChunkCounts { const c = this.#ctrl; return { pushed: Atomics.load(c, PUSHED), keys: Atomics.load(c, KEYS), delivered: this.delivered, dropped: this.dropped + Atomics.load(c, DROPPED), tooLarge: Atomics.load(c, TOO_LARGE) }; }
constructor(buffer: SharedArrayBuffer, clock: () => number = CHUNK_CLOCK) { const v = ringViews(buffer); this.#ctrl = v.ctrl; this.#dv = v.dv; this.#bytes = v.bytes; this.#cap = v.cap; this.#tail = Atomics.load(this.#ctrl, TAIL); this.#clock = clock; }
/** A stream numbered `gen` starts (or 0: none runs): what waits is another stream's. */ start(gen: number): void { this.#gen = gen | 0; Atomics.store(this.#ctrl, GEN, this.#gen); this.#skipToKey = false; while (Atomics.load(this.#ctrl, COUNT) > 0) this.#next(null); }
/** The oldest chunk of the stream into `out`, or null when none waits; `onGap` when one was too large (a key frame is then wanted). */ read(out: Uint8Array, onGap?: () => void): ChunkRead | null { while (Atomics.load(this.#ctrl, COUNT) > 0) { const r = this.#next(out); if (r === "gap") { try { onGap?.(); } catch {} continue; } if (r) return r; } return null; }
/** Consume one record: into `out` if it is the stream's and fits (null `out`: drop it). */ #next(out: Uint8Array | null): ChunkRead | "gap" | null { let t = this.#tail, freed = 0; const room = this.#cap - t; if (room < REC || (this.#dv.getInt32(t + 4, true) & F_WRAP)) { freed = room; t = 0; } const len = this.#dv.getInt32(t, true), flags = this.#dv.getInt32(t + 4, true), gen = this.#dv.getInt32(t + 8, true); const at = this.#dv.getFloat64(t + 16, true); const size = align8(REC + Math.max(0, len)); const key = (flags & F_KEY) !== 0; let res: ChunkRead | "gap" | null = null; if (!out || gen !== this.#gen || len < 0 || t + REC + len > this.#cap) { if (out) Atomics.add(this.#ctrl, SKIPPED, 1); this.dropped++; } else if (this.#skipToKey && !key) { this.dropped++; } else if (len > out.length) { Atomics.add(this.#ctrl, SKIPPED, 1); this.dropped++; this.#skipToKey = true; res = "gap"; } else { this.#skipToKey = false; out.set(this.#bytes.subarray(t + REC, t + REC + len)); this.delivered++; res = { bytes: len, key, ageMs: Math.max(0, this.#clock() - at) }; } this.#tail = (t + size) % this.#cap; Atomics.store(this.#ctrl, TAIL, this.#tail); Atomics.sub(this.#ctrl, USED, freed + size); Atomics.sub(this.#ctrl, COUNT, 1); return res; }}