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:
180
packages/shade-media/src/browser/watch-app.ts
Normal file
180
packages/shade-media/src/browser/watch-app.ts
Normal 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)));
|
||||
Reference in New Issue
Block a user