Files
Shade/packages/shade-media/src/browser/watch-app.ts
Sterister 422a37e830 feat(media): subtitles that travel with the film — CLI, browser <track>, ExoPlayer
`shade media put Film.mkv` seals Film.srt / Film.no.srt / Film.en.vtt
found beside it and carries their grants in the film's sealed meta
(extra["shade.subtitles"]), so they follow the film alone or in an album
and the relay sees unrelated objects. /watch/ adds them as <track>s (SRT
to VTT, labels in the viewer's language, the viewer's language on, one at
a time); `media get` writes them back; Android opens them with
ShadeMedia.openFilm and gives them to ExoPlayer as side-loaded tracks
(ShadeMediaDataSource now resolves readers by URI).

Verified: 76 TS tests; Chromium nb-NO shows the Norwegian track only, en-US
the English one; film + subtitles round-trip bit-identical; Robolectric
ExoPlayer sees both text tracks with the Norwegian one default; a shared
vector checks the meta field in Kotlin (82/0).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:01:33 +02:00

393 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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. An album shows its items as a
* grid; opening one pushes a view, and Back returns to the album.
*
* 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 { ALBUM_MIME, parseAlbum } from '../album.js';
import type { Album } from '../album.js';
import { fromB64u } from '../bytes.js';
import { fromCapabilityUrl } from '../grant.js';
import type { Grant, LiveGrant, MediaGrant } from '../grant.js';
import { LiveWatchClient } from '../live/client.js';
import type { ReceivedFrame } from '../live/channel.js';
import { installMediaWorker } from './index.js';
import type { MediaKeyring } from './index.js';
import { LivePlayer } from './player.js';
import { srtToVtt, subtitlesOf } from '../subtitles.js';
import type { SubtitleTrack } from '../subtitles.js';
import type { MediaMeta } from '../sealed.js';
interface Stats {
kind: 'media' | 'live' | 'album' | 'none';
items?: number;
subtitles?: string[];
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]}`;
}
// ─── Views ──────────────────────────────────────────────────────
//
// A stack of views mirrored in the history, so Back leaves an item for its
// album. History entries hold only the depth: the grants stay in memory.
type View = () => Promise<void> | void;
const views: View[] = [];
let cleanups: (() => void)[] = [];
function reset(): void {
for (const c of cleanups) c();
cleanups = [];
const stage = $('#stage');
for (const m of stage.querySelectorAll('video, audio')) (m as HTMLMediaElement).pause();
stage.replaceChildren();
stage.className = '';
$('#actions').replaceChildren();
$('#sub').textContent = '';
Object.assign(stats, { kind: 'none', state: 'starting', frames: 0, lines: 0, images: 0 });
delete stats.error;
delete stats.player;
delete stats.items;
delete stats.subtitles;
}
async function render(view: View): Promise<void> {
reset();
if (views.length > 1) {
const back = document.createElement('a');
back.href = '#';
back.id = 'back';
back.textContent = '← Back';
back.addEventListener('click', (e) => {
e.preventDefault();
history.back();
});
$('#actions').append(back);
}
try {
await view();
} catch (e) {
fail(String((e as Error)?.message ?? e));
}
}
function push(view: View): Promise<void> {
views.push(view);
history.pushState({ depth: views.length - 1 }, '');
return render(view);
}
window.addEventListener('popstate', (e: PopStateEvent) => {
const depth = Math.min((e.state as { depth?: number } | null)?.depth ?? 0, views.length - 1);
views.length = depth + 1;
void render(views[depth]!);
});
let keyring: Promise<MediaKeyring> | null = null;
function ring(): Promise<MediaKeyring> {
keyring ??= installMediaWorker(new URL('sw.js', location.href).pathname, new URL('./', location.href).pathname);
return keyring;
}
async function open(g: Grant): Promise<void> {
if (g.kind === 'shade.media-grant/v1') await playMedia(g);
else playLive(g);
}
async function playMedia(g: MediaGrant): Promise<void> {
stats.kind = 'media';
setStatus('starting the decryption worker…');
const src = await (await ring()).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;
if (mime === ALBUM_MIME) return showAlbum(parseAlbum(new Uint8Array(await (await fetch(src)).arrayBuffer())));
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);
const metaHeader = head.headers.get('x-shade-meta');
if (el instanceof HTMLVideoElement && metaHeader !== null) {
const meta = JSON.parse(new TextDecoder().decode(fromB64u(metaHeader))) as MediaMeta;
void addSubtitles(el, meta);
}
} 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);
}
/**
* The film's subtitle files, decrypted through the worker like the film,
* as `<track>`s. One that fails to load is skipped; the film plays on.
*/
async function addSubtitles(video: HTMLVideoElement, meta: MediaMeta): Promise<void> {
let tracks: SubtitleTrack[];
try {
tracks = subtitlesOf(meta);
} catch {
return;
}
if (tracks.length === 0) return;
const kr = await ring();
const names = typeof Intl.DisplayNames === 'function' ? new Intl.DisplayNames([navigator.language], { type: 'language' }) : null;
// Macrolanguages: a browser set to Bokmål (nb) should pick a `no` file.
const base = (tag: string) => {
const l = tag.split('-')[0]!.toLowerCase();
return l === 'nb' || l === 'nn' ? 'no' : l;
};
const want = base(navigator.language);
let chosen = false;
stats.subtitles = [];
for (const t of tracks) {
try {
const text = await (await fetch(await kr.add(t.grant))).text();
const url = URL.createObjectURL(new Blob([srtToVtt(text)], { type: 'text/vtt' }));
cleanups.push(() => URL.revokeObjectURL(url));
const el = document.createElement('track');
el.kind = 'subtitles';
el.src = url;
if (t.lang !== undefined) el.srclang = t.lang;
el.label = t.label ?? (t.lang !== undefined ? (names?.of(t.lang) ?? t.lang) : 'Subtitles');
video.append(el);
// `default` on a track added after load is not honoured everywhere; say it.
if (!chosen && t.lang !== undefined && base(t.lang) === want) {
el.default = true;
el.track.mode = 'showing';
chosen = true;
}
stats.subtitles.push(el.label);
} catch {
// A broken subtitle file must not stop the film.
}
}
// One track at a time. Chromium switches on the first track it was given
// once it loads, after this has run, so hold the line where it changes:
// more than one showing → back to the current choice; exactly one → that
// is the viewer's pick from the menu, and becomes the choice.
let current: TextTrack | null = [...video.textTracks].find((t) => t.mode === 'showing' && base(t.language) === want) ?? null;
if (!chosen) current = null;
const enforce = () => {
const showing = [...video.textTracks].filter((t) => t.mode === 'showing');
if (showing.length === 1) current = showing[0]!;
else if (showing.length > 1) for (const t of showing) if (t !== current) t.mode = 'disabled';
};
video.textTracks.addEventListener('change', enforce);
cleanups.push(() => video.textTracks.removeEventListener('change', enforce));
enforce();
}
/** What an item is, from its grant's meta preview (before opening it). */
function itemKind(g: Grant): string {
if (g.kind === 'shade.live-grant/v1') return 'live';
const mime = g.meta?.mime ?? '';
if (mime === ALBUM_MIME) return 'album';
return mime.split('/')[0] || 'file';
}
const ICONS: Record<string, string> = { album: '▦', audio: '♪', text: '≡', live: '●', file: '⬚', video: '▶', image: '◩' };
async function showAlbum(album: Album): Promise<void> {
stats.kind = 'album';
stats.items = album.items.length;
$('#title').textContent = album.title || 'Album';
const counts = new Map<string, number>();
for (const it of album.items) counts.set(itemKind(it), (counts.get(itemKind(it)) ?? 0) + 1);
$('#sub').textContent = `album · ${[...counts].map(([k, n]) => `${n} ${k}`).join(', ') || 'empty'} · end-to-end encrypted`;
const stage = $('#stage');
stage.className = 'album';
const grid = document.createElement('div');
grid.className = 'grid';
stage.append(grid);
const kr = await ring();
for (const [i, item] of album.items.entries()) {
const kind = itemKind(item);
const card = document.createElement('button');
card.className = 'card';
card.dataset.kind = kind;
const thumb = document.createElement('div');
thumb.className = 'thumb';
thumb.textContent = ICONS[kind] ?? ICONS.file!;
const label = document.createElement('div');
label.className = 'name';
label.textContent = item.meta?.name ?? `Item ${i + 1}`;
const sub = document.createElement('div');
sub.className = 'kind';
sub.textContent = kind === 'live' ? 'live channel' : kind === 'album' ? 'album' : (item.meta?.mime ?? kind);
card.append(thumb, label, sub);
card.addEventListener('click', () => void push(() => open(item)));
grid.append(card);
// Previews decrypt through the worker like the item itself: an image
// shows itself, a video its first frame. Fetched only as cards scroll in.
if (item.kind === 'shade.media-grant/v1' && (kind === 'image' || kind === 'video')) {
const io = new IntersectionObserver(async (entries) => {
if (!entries.some((e) => e.isIntersecting)) return;
io.disconnect();
const src = await kr.add(item);
if (kind === 'image') {
const img = document.createElement('img');
img.alt = '';
img.addEventListener('load', () => thumb.replaceChildren(img));
img.src = src;
} else {
const v = document.createElement('video');
v.muted = true;
v.preload = 'metadata';
v.addEventListener('loadeddata', () => thumb.replaceChildren(v));
v.src = `${src}#t=1`;
}
});
io.observe(card);
cleanups.push(() => io.disconnect());
}
}
setStatus(`${album.items.length} item(s)`);
}
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 });
cleanups.push(() => player.close());
stats.player = () => ({ ...player.stats(), currentTime: el.currentTime, paused: el.paused, readyState: el.readyState });
} else {
const client = new LiveWatchClient(g, { onFrame: other, onState: states, onError: onErr });
cleanups.push(() => client.close());
}
}
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({ depth: 0 }, '', location.pathname + location.search);
views.push(() => open(grant));
await render(views[0]!);
}
main().catch((e) => fail(String((e as Error)?.message ?? e)));