feat(media): browser playback, live WebM and log streaming, shade media/live CLI

- Service Worker plays sealed files in native <video>/<audio>/<img> with
  Range seeking; watch page served by the relay itself (#shade= fragment
  links, grant never sent to a server)
- MSE live player with keyframe-aware joining, gap detection, latency control
- WebM splitter (init + clusters, keyframe detection) that puts blocks in
  timecode order — Chrome rejects ffmpeg's interleaved Opus/VP8 otherwise
- Link mode for live channels: epoch seeds from a channel secret, so a
  link survives publisher restarts and scheduled rotations
- File store streams byte ranges itself (Bun.file().slice() in a Response
  sent whole files to Range requests)
- shade media serve|put|get|ls|rm, shade live text|webm|watch

Verified end to end in headless Chromium: VP9/Opus film plays and seeks,
live VP8/Opus at 2.9 s latency, live logs, sealed JPEG and Opus audio.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-18 21:01:52 +02:00
parent 9e64ec87be
commit f359cbd9ad
28 changed files with 1796 additions and 40 deletions

View File

@@ -0,0 +1,64 @@
/**
* Page-side helpers: hand grants to the Service Worker, and play live
* channels through Media Source Extensions.
*/
import { encodeGrant } from '../grant.js';
import type { MediaGrant } from '../grant.js';
import { toHex } from '../bytes.js';
export { LivePlayer } from './player.js';
export type { LivePlayerOptions, LivePlayerStats } from './player.js';
/**
* Register the media worker and wait until it controls this page. `scope`
* is the directory the virtual `media/<id>` URLs live under.
*/
export async function installMediaWorker(swUrl: string, scope?: string): Promise<MediaKeyring> {
if (!('serviceWorker' in navigator)) throw new Error('this browser has no Service Workers');
const reg = await navigator.serviceWorker.register(swUrl, scope !== undefined ? { scope } : {});
await navigator.serviceWorker.ready;
if (navigator.serviceWorker.controller === null) {
// First visit: the worker claims the page on activate.
await new Promise<void>((resolve) =>
navigator.serviceWorker.addEventListener('controllerchange', () => resolve(), { once: true }),
);
}
return new MediaKeyring(reg.scope);
}
/**
* The page's copy of its grants. The worker can be stopped by the browser at
* any time and loses its memory; it then asks the page, and this answers.
*/
export class MediaKeyring {
private readonly grants = new Map<string, string>();
constructor(readonly scope: string) {
navigator.serviceWorker.addEventListener('message', (e) => {
const msg = e.data as { type?: string; id?: string } | null;
if (msg?.type !== 'shade-media-need' || typeof msg.id !== 'string') return;
e.ports[0]?.postMessage(this.grants.get(msg.id) ?? null);
});
}
/** Register a grant with the worker; returns the URL to put in `src`. */
async add(grant: MediaGrant): Promise<string> {
const id = toHex(grant.mediaId);
const json = encodeGrant(grant);
this.grants.set(id, json);
const sw = navigator.serviceWorker.controller;
if (sw === null) throw new Error('media worker is not controlling this page');
const res = await new Promise<{ ok: boolean; error?: string }>((resolve) => {
const ch = new MessageChannel();
ch.port1.onmessage = (m) => resolve(m.data);
sw.postMessage({ type: 'shade-media-grant', grant: json }, [ch.port2]);
});
if (!res.ok) throw new Error(res.error ?? 'worker refused the grant');
return this.urlFor(grant);
}
urlFor(grant: MediaGrant): string {
return new URL(`media/${toHex(grant.mediaId)}`, this.scope).toString();
}
}

View File

@@ -0,0 +1,186 @@
/**
* Live video/audio in a `<video>` element via Media Source Extensions.
*
* Frames come from a `LiveWatchClient`; this turns them into SourceBuffer
* appends. The rules that make live MSE work:
*
* - the sticky `init` frame creates the SourceBuffer (its MIME names the
* codecs) and is appended first; the same init again is skipped;
* - media `chunk`s are dropped until the first keyframe — a decoder cannot
* start mid-GOP — and again after any gap, until the next keyframe;
* - a viewer that joins late has timestamps that start at, say, 37 s: the
* playhead is moved to the start of what is buffered;
* - the playhead is kept close to the live edge, and old media is evicted
* so the buffer does not hit the browser's quota.
*/
import { LiveWatchClient } from '../live/client.js';
import type { LiveState } from '../live/client.js';
import type { ReceivedFrame } from '../live/channel.js';
import type { LiveGrant } from '../grant.js';
import { equalBytes } from '../bytes.js';
export interface LivePlayerOptions {
/** Jump forward when further than this behind the live edge. Default 4 s. */
maxLatencySeconds?: number;
/** Media kept behind the playhead. Default 30 s. */
keepSeconds?: number;
onState?: (s: LiveState) => void;
onError?: (e: Error) => void;
/** Non-media frames (text, images, meta) on the same channel. */
onOther?: (f: ReceivedFrame) => void;
}
export interface LivePlayerStats {
trail: string[];
framesIn: number;
/** Times a frame was missing in the sequence (relay dropped it for a slow viewer). */
gaps: number;
appended: number;
droppedBeforeKeyframe: number;
bufferedSeconds: number;
latencySeconds: number;
}
export class LivePlayer {
readonly client: LiveWatchClient;
private readonly ms = new MediaSource();
private sb: SourceBuffer | null = null;
private lastInit: Uint8Array | null = null;
private queue: Uint8Array[] = [];
private needKeyframe = true;
private lastSeq = -1;
private lastEpoch = -1;
private readonly sourceOpen: Promise<void>;
private readonly stat = { framesIn: 0, appended: 0, droppedBeforeKeyframe: 0, gaps: 0 };
/** Last few frames handled, for diagnosing a player that stalls. */
private readonly trail: string[] = [];
constructor(
private readonly video: HTMLMediaElement,
grant: LiveGrant,
private readonly opts: LivePlayerOptions = {},
) {
this.sourceOpen = new Promise((r) => this.ms.addEventListener('sourceopen', () => r(), { once: true }));
video.src = URL.createObjectURL(this.ms);
this.client = new LiveWatchClient(grant, {
onFrame: (f) => this.onFrame(f),
...(opts.onState !== undefined ? { onState: opts.onState } : {}),
...(opts.onError !== undefined ? { onError: opts.onError } : {}),
});
setInterval(() => this.housekeeping(), 1000);
}
stats(): LivePlayerStats {
const b = this.video.buffered;
const end = b.length > 0 ? b.end(b.length - 1) : 0;
return {
...this.stat,
trail: [...this.trail],
bufferedSeconds: b.length > 0 ? end - b.start(0) : 0,
latencySeconds: Math.max(0, end - this.video.currentTime),
};
}
private async onFrame(f: ReceivedFrame): Promise<void> {
this.stat.framesIn++;
this.trail.push(`${f.epoch}/${f.seq}${f.keyframe ? '*' : ''}${f.sticky ? 's' : ''}:${f.content.type}`);
if (this.trail.length > 16) this.trail.shift();
// Every frame takes a seq, whatever it carries, so a gap is a frame lost
// (dropped by a relay for a slow viewer) — and that breaks the GOP.
// Sticky frames are replayed out of their chain position (a late joiner
// gets seq 0 then seq 119), so they do not count.
if (!f.sticky) {
if (f.epoch === this.lastEpoch && f.seq !== this.lastSeq + 1) {
this.stat.gaps++;
this.needKeyframe = true;
}
this.lastEpoch = f.epoch;
this.lastSeq = f.seq;
}
const c = f.content;
if (c.type === 'init') {
await this.sourceOpen;
if (this.lastInit !== null && equalBytes(this.lastInit, c.bytes)) return;
if (this.sb === null) {
if (!MediaSource.isTypeSupported(c.mime)) {
this.opts.onError?.(new Error(`this browser cannot play ${c.mime}`));
return;
}
this.sb = this.ms.addSourceBuffer(c.mime);
this.sb.mode = 'segments';
this.sb.addEventListener('updateend', () => this.pump());
}
this.lastInit = c.bytes.slice();
this.enqueue(c.bytes);
this.needKeyframe = true;
return;
}
if (c.type !== 'chunk') {
this.opts.onOther?.(f);
return;
}
if (this.sb === null || (this.needKeyframe && !f.keyframe)) {
this.stat.droppedBeforeKeyframe++;
return;
}
this.needKeyframe = false;
this.enqueue(c.bytes);
}
private enqueue(b: Uint8Array): void {
this.queue.push(b);
this.pump();
}
private pump(): void {
const sb = this.sb;
if (sb === null || sb.updating || this.queue.length === 0) return;
const next = this.queue.shift()!;
try {
sb.appendBuffer(next as Uint8Array<ArrayBuffer>);
this.stat.appended++;
} catch (e) {
if ((e as DOMException).name === 'QuotaExceededError') {
this.queue.unshift(next);
this.evict(5);
} else {
this.opts.onError?.(e as Error);
}
}
this.seekIntoBuffer();
}
private seekIntoBuffer(): void {
const b = this.video.buffered;
if (b.length === 0) return;
const start = b.start(0);
const end = b.end(b.length - 1);
const t = this.video.currentTime;
if (t < start || t > end) this.video.currentTime = start;
if (this.video.paused) void this.video.play().catch(() => {});
}
private evict(extra = 0): void {
const sb = this.sb;
const b = this.video.buffered;
if (sb === null || sb.updating || b.length === 0) return;
const keep = this.opts.keepSeconds ?? 30;
const cut = this.video.currentTime - keep + extra;
if (cut > b.start(0) + 1) sb.remove(b.start(0), cut);
}
private housekeeping(): void {
const b = this.video.buffered;
if (b.length === 0) return;
const end = b.end(b.length - 1);
const max = this.opts.maxLatencySeconds ?? 4;
if (end - this.video.currentTime > max) this.video.currentTime = Math.max(b.start(b.length - 1), end - 1);
this.evict();
}
close(): void {
this.client.close();
if (this.ms.readyState === 'open') this.ms.endOfStream();
}
}

View File

@@ -0,0 +1,20 @@
/** Single `bytes=` range against `size` — shared by the routes and the Service Worker. */
export function parseRange(
header: string | null | undefined,
size: number,
): { start: number; end: number } | 'invalid' | null {
if (header === null || header === undefined) return null;
const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
if (m === null) return 'invalid';
const [, a, b] = m;
if (a === '' && b === '') return 'invalid';
if (a === '') {
const n = Number(b);
if (n === 0 || size === 0) return 'invalid';
return { start: Math.max(0, size - n), end: size };
}
const start = Number(a);
const end = b === '' ? size : Math.min(size, Number(b) + 1);
if (start >= size || end <= start) return 'invalid';
return { start, end };
}

View File

@@ -0,0 +1,157 @@
/**
* Service Worker: makes a sealed file look like a normal one to the browser.
*
* The page points `<video src>` (or `<audio>`, `<img>`, a download link) at
* `<scope>media/<mediaId>`. This worker answers those requests itself —
* Range requests included, so seeking works — by fetching only the sealed
* segments under the requested range from wherever the grant says the file
* lives, verifying and decrypting them, and streaming the plaintext back.
*
* Keys live in this worker's memory only. A worker the browser stopped
* forgets them; it then asks the page (which still holds the grant) again.
*/
import { parseGrant, mediaKeysOf } from '../grant.js';
import type { MediaGrant } from '../grant.js';
import { MediaReader } from '../sealed.js';
import { HttpRangeSource } from '../source.js';
import { READ_TOKEN_HEADER } from '../owner.js';
import { toB64u } from '../bytes.js';
import { parseRange } from './range.js';
// The WebWorker lib cannot be combined with DOM in one tsconfig; this is the
// small slice of the worker scope we use.
interface FetchEventLike extends Event {
request: Request;
respondWith(r: Promise<Response> | Response): void;
}
interface ExtendableEventLike extends Event {
waitUntil(p: Promise<unknown>): void;
}
interface ExtendableMessageEventLike extends Event {
data: unknown;
ports: readonly MessagePort[];
}
interface ClientLike {
postMessage(msg: unknown, transfer?: Transferable[]): void;
}
interface WorkerScope {
registration: { scope: string };
clients: { claim(): Promise<void>; matchAll(o?: { includeUncontrolled?: boolean }): Promise<ClientLike[]> };
skipWaiting(): Promise<void>;
addEventListener(type: 'install' | 'activate', cb: (e: ExtendableEventLike) => void): void;
addEventListener(type: 'fetch', cb: (e: FetchEventLike) => void): void;
addEventListener(type: 'message', cb: (e: ExtendableMessageEventLike) => void): void;
}
declare const self: WorkerScope;
const grants = new Map<string, MediaGrant>();
const readers = new Map<string, Promise<MediaReader>>();
function hexId(g: MediaGrant): string {
let s = '';
for (const b of g.mediaId) s += b.toString(16).padStart(2, '0');
return s;
}
self.addEventListener('install', () => {
void self.skipWaiting();
});
self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim()));
self.addEventListener('message', (e) => {
const msg = e.data as { type?: string; grant?: string } | null;
if (msg?.type !== 'shade-media-grant' || typeof msg.grant !== 'string') return;
try {
const g = parseGrant(msg.grant);
if (g.kind !== 'shade.media-grant/v1') throw new Error('not a media grant');
grants.set(hexId(g), g);
e.ports[0]?.postMessage({ ok: true, id: hexId(g) });
} catch (err) {
e.ports[0]?.postMessage({ ok: false, error: String((err as Error).message) });
}
});
/** Ask every open page for a grant we lost (the worker was restarted). */
async function askPages(id: string): Promise<MediaGrant | null> {
const pages = await self.clients.matchAll({ includeUncontrolled: true });
const answers = pages.map(
(c) =>
new Promise<string | null>((resolve) => {
const ch = new MessageChannel();
const t = setTimeout(() => resolve(null), 3000);
ch.port1.onmessage = (m) => {
clearTimeout(t);
resolve(typeof m.data === 'string' ? m.data : null);
};
c.postMessage({ type: 'shade-media-need', id }, [ch.port2]);
}),
);
for (const a of await Promise.all(answers)) {
if (a === null) continue;
try {
const g = parseGrant(a);
if (g.kind === 'shade.media-grant/v1' && hexId(g) === id) {
grants.set(id, g);
return g;
}
} catch {
// A page answering garbage is ignored; another may answer properly.
}
}
return null;
}
function readerFor(id: string, g: MediaGrant): Promise<MediaReader> {
let r = readers.get(id);
if (r === undefined) {
if (g.url === undefined) return Promise.reject(new Error('grant has no URL'));
const source = new HttpRangeSource(g.url, {
...(g.readToken !== undefined ? { headers: { [READ_TOKEN_HEADER]: toB64u(g.readToken) } } : {}),
});
r = MediaReader.open(source, mediaKeysOf(g), { cacheSegments: 16, maxSegmentsPerFetch: 4 });
// A failed open must not be cached: the next request should retry.
r.catch(() => readers.delete(id));
readers.set(id, r);
}
return r;
}
async function serve(req: Request, id: string): Promise<Response> {
const g = grants.get(id) ?? (await askPages(id));
if (g === null) return new Response('no grant for this media in this browser', { status: 403 });
let reader: MediaReader;
try {
reader = await readerFor(id, g);
} catch (e) {
return new Response(`cannot open sealed media: ${(e as Error).message}`, { status: 502 });
}
const size = reader.size;
const headers: Record<string, string> = {
'content-type': reader.meta.mime ?? g.meta?.mime ?? 'application/octet-stream',
'accept-ranges': 'bytes',
'cache-control': 'no-store',
};
if (reader.meta.name !== undefined) {
headers['content-disposition'] = `inline; filename*=UTF-8''${encodeURIComponent(reader.meta.name)}`;
}
const range = parseRange(req.headers.get('range'), size);
if (range === 'invalid') {
return new Response(null, { status: 416, headers: { ...headers, 'content-range': `bytes */${size}` } });
}
const { start, end } = range ?? { start: 0, end: size };
headers['content-length'] = String(end - start);
if (range !== null) headers['content-range'] = `bytes ${start}-${end - 1}/${size}`;
const body = req.method === 'HEAD' ? null : reader.stream(start, end);
return new Response(body, { status: range !== null ? 206 : 200, headers });
}
self.addEventListener('fetch', (e) => {
const url = new URL(e.request.url);
const prefix = new URL('media/', self.registration.scope).pathname;
if (!url.pathname.startsWith(prefix)) return;
const id = url.pathname.slice(prefix.length);
if (!/^[0-9a-f]{32}$/.test(id)) return;
e.respondWith(serve(e.request, id));
});

View File

@@ -0,0 +1,180 @@
/**
* The watch page: open a capability link, play what it grants.
*
* /watch/#shade=<grant>
*
* A sealed file plays through the Service Worker in a native element —
* `<video>`, `<audio>`, `<img>` or a text view — with seeking. A live
* channel plays through MSE (video/audio) or as a scrolling log (text),
* with images replacing each other in place.
*
* The grant never leaves the browser: it is in the fragment, which is not
* sent to the server, and the page drops it from the address bar once read.
*/
import { fromCapabilityUrl } from '../grant.js';
import type { LiveGrant, MediaGrant } from '../grant.js';
import { LiveWatchClient } from '../live/client.js';
import type { ReceivedFrame } from '../live/channel.js';
import { installMediaWorker } from './index.js';
import { LivePlayer } from './player.js';
interface Stats {
kind: 'media' | 'live' | 'none';
state: string;
mime?: string;
frames: number;
lines: number;
images: number;
error?: string;
player?: () => unknown;
}
const stats: Stats = { kind: 'none', state: 'starting', frames: 0, lines: 0, images: 0 };
(globalThis as unknown as { __shade: Stats }).__shade = stats;
const $ = <T extends HTMLElement>(sel: string) => document.querySelector(sel) as T;
function setStatus(text: string, tone: 'ok' | 'warn' | 'bad' = 'ok'): void {
stats.state = text;
const el = $('#status');
el.textContent = text;
el.dataset.tone = tone;
}
function fail(message: string): void {
stats.error = message;
setStatus(message, 'bad');
}
function human(n: number): string {
const u = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0;
while (n >= 1024 && i < u.length - 1) {
n /= 1024;
i++;
}
return `${n.toFixed(i === 0 ? 0 : 1)} ${u[i]}`;
}
async function playMedia(g: MediaGrant): Promise<void> {
stats.kind = 'media';
setStatus('starting the decryption worker…');
const keyring = await installMediaWorker(new URL('sw.js', location.href).pathname, new URL('./', location.href).pathname);
const src = await keyring.add(g);
const head = await fetch(src, { method: 'HEAD' });
if (!head.ok) return fail(`could not open: ${head.status} ${await head.text()}`);
const mime = head.headers.get('content-type') ?? 'application/octet-stream';
const size = Number(head.headers.get('content-length'));
stats.mime = mime;
const name = decodeURIComponent(/filename\*=UTF-8''([^;]+)/.exec(head.headers.get('content-disposition') ?? '')?.[1] ?? '');
$('#title').textContent = g.meta?.name ?? (name || 'Sealed media');
$('#sub').textContent = `${mime} · ${human(size)} · end-to-end encrypted`;
const stage = $('#stage');
if (mime.startsWith('video/') || mime.startsWith('audio/')) {
const el = document.createElement(mime.startsWith('video/') ? 'video' : 'audio');
el.controls = true;
el.autoplay = true;
el.muted = true; // autoplay policy; the viewer unmutes
el.src = src;
el.id = 'player';
el.addEventListener('playing', () => setStatus('playing'));
el.addEventListener('waiting', () => setStatus('buffering…', 'warn'));
el.addEventListener('error', () => fail(`player error: ${el.error?.message ?? el.error?.code}`));
stage.append(el);
} else if (mime.startsWith('image/')) {
const img = document.createElement('img');
img.src = src;
img.id = 'player';
img.addEventListener('load', () => setStatus(`showing ${img.naturalWidth}×${img.naturalHeight}`));
img.addEventListener('error', () => fail('image failed to decode'));
stage.append(img);
} else if (mime.startsWith('text/') || mime === 'application/json') {
const pre = document.createElement('pre');
pre.id = 'log';
pre.textContent = await (await fetch(src)).text();
stage.append(pre);
setStatus('showing text');
} else {
setStatus('ready to download');
}
const a = document.createElement('a');
a.href = src;
a.download = name || 'download';
a.textContent = 'Download decrypted';
$('#actions').append(a);
}
function playLive(g: LiveGrant): void {
stats.kind = 'live';
$('#title').textContent = g.meta?.name ?? 'Live channel';
const mime = g.meta?.mime ?? '';
stats.mime = mime;
$('#sub').textContent = `live · ${mime || 'text'} · end-to-end encrypted`;
const stage = $('#stage');
const states = (s: string) => setStatus(s === 'live' ? 'live' : s === 'waiting' ? 'waiting for the publisher…' : s, s === 'live' ? 'ok' : 'warn');
const onErr = (e: Error) => {
stats.error = e.message;
};
let log: HTMLPreElement | null = null;
let img: HTMLImageElement | null = null;
const other = (f: ReceivedFrame) => {
stats.frames++;
const c = f.content;
if (c.type === 'text') {
if (log === null) {
log = document.createElement('pre');
log.id = 'log';
stage.append(log);
}
const atBottom = log.scrollTop + log.clientHeight >= log.scrollHeight - 4;
log.append(document.createTextNode(c.text));
stats.lines += c.text.split('\n').length - 1;
// Bound the DOM: a log stream runs for days.
while (log.childNodes.length > 5000) log.firstChild!.remove();
if (atBottom) log.scrollTop = log.scrollHeight;
} else if (c.type === 'image') {
if (img === null) {
img = document.createElement('img');
img.id = 'player';
stage.prepend(img);
}
const old = img.src;
img.src = URL.createObjectURL(new Blob([c.bytes as Uint8Array<ArrayBuffer>], { type: c.mime }));
if (old.startsWith('blob:')) URL.revokeObjectURL(old);
stats.images++;
} else if (c.type === 'end') {
setStatus('the broadcast has ended', 'warn');
}
};
if (mime.startsWith('video/') || mime.startsWith('audio/')) {
const el = document.createElement(mime.startsWith('video/') ? 'video' : 'audio');
el.controls = true;
el.autoplay = true;
el.muted = true;
el.id = 'player';
stage.append(el);
const player = new LivePlayer(el, g, { onState: states, onError: onErr, onOther: other });
stats.player = () => ({ ...player.stats(), currentTime: el.currentTime, paused: el.paused, readyState: el.readyState });
} else {
new LiveWatchClient(g, { onFrame: other, onState: states, onError: onErr });
}
}
async function main(): Promise<void> {
let grant;
try {
grant = fromCapabilityUrl(location.href);
} catch (e) {
$('#title').textContent = 'Shade';
return fail(`no grant in this link — ${(e as Error).message}`);
}
// Keep the key out of the history and out of anything that reads the URL later.
history.replaceState(null, '', location.pathname + location.search);
if (grant.kind === 'shade.media-grant/v1') await playMedia(grant);
else playLive(grant);
}
main().catch((e) => fail(String((e as Error)?.message ?? e)));