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>
This commit is contained in:
2026-10-18 22:01:33 +02:00
parent 9efe1bcfd3
commit 422a37e830
19 changed files with 536 additions and 26 deletions

View File

@@ -132,6 +132,9 @@ async function serve(req: Request, id: string): Promise<Response> {
'content-type': reader.meta.mime ?? g.meta?.mime ?? 'application/octet-stream',
'accept-ranges': 'bytes',
'cache-control': 'no-store',
// The sealed meta, for the page (subtitles, title). Never leaves the
// browser: this response is made here, not fetched.
'x-shade-meta': toB64u(new TextEncoder().encode(JSON.stringify(reader.meta))),
};
if (reader.meta.name !== undefined) {
headers['content-disposition'] = `inline; filename*=UTF-8''${encodeURIComponent(reader.meta.name)}`;

View File

@@ -15,6 +15,7 @@
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';
@@ -22,10 +23,14 @@ 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;
@@ -84,6 +89,7 @@ function reset(): void {
delete stats.error;
delete stats.player;
delete stats.items;
delete stats.subtitles;
}
async function render(view: View): Promise<void> {
@@ -154,6 +160,11 @@ async function playMedia(g: MediaGrant): Promise<void> {
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;
@@ -177,6 +188,66 @@ async function playMedia(g: MediaGrant): Promise<void> {
$('#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';

View File

@@ -17,7 +17,7 @@
import { chmod, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
import { createWriteStream } from 'node:fs';
import { homedir, tmpdir } from 'node:os';
import { basename, extname, join } from 'node:path';
import { basename, dirname, extname, join } from 'node:path';
import { fromB64u, randomBytes, toB64u, toHex } from './bytes.js';
import { ALBUM_MIME } from './album.js';
import type { Album } from './album.js';
@@ -30,6 +30,8 @@ import { sealFile } from './node.js';
import { OwnerKey } from './owner.js';
import type { MediaMeta } from './sealed.js';
import { MediaSplitter } from './splitter.js';
import { SUBTITLE_EXTENSIONS, subtitleFor, subtitlesOf, withSubtitles } from './subtitles.js';
import type { SubtitleTrack } from './subtitles.js';
import type { LiveContainer } from './splitter.js';
type Flags = Record<string, string | true>;
@@ -148,7 +150,9 @@ async function mediaPut(pos: string[], flags: Flags): Promise<number> {
const oneDir = pos.length === 1 && (await stat(pos[0]!)).isDirectory();
let grant: MediaGrant;
if (pos.length === 1 && !oneDir && albumTitle === undefined) {
grant = await putFile(client, pos[0]!, flags, str(flags, 'name'));
const name = str(flags, 'name');
const mime = str(flags, 'mime');
grant = await putFile(client, pos[0]!, flags, { ...(name !== undefined ? { name } : {}), ...(mime !== undefined ? { mime } : {}) });
} else if (oneDir) {
// The directory is the album (`--album` renames it), not an album inside one.
grant = await putPath(client, pos[0]!, flags, albumTitle);
@@ -169,7 +173,10 @@ const naturally = new Intl.Collator(undefined, { numeric: true, sensitivity: 'ba
/** A file, or a directory as an album of its (non-hidden) entries. */
async function putPath(client: MediaClient, path: string, flags: Flags, titled?: string): Promise<MediaGrant> {
if (!(await stat(path)).isDirectory()) return putFile(client, path, flags);
const names = (await readdir(path)).filter((n) => !n.startsWith('.')).sort(naturally.compare);
const all = (await readdir(path)).filter((n) => !n.startsWith('.')).sort(naturally.compare);
// Subtitles next to a video travel inside it, not as items of their own.
const videos = all.filter((n) => guessMime(n)?.startsWith('video/')).map((n) => n.slice(0, -extname(n).length));
const names = all.filter((n) => !videos.some((v) => subtitleFor(v, n) !== null));
const items: Grant[] = [];
for (const n of names) items.push(await putPath(client, join(path, n), flags));
const title = titled ?? basename(path.replace(/\/+$/, ''));
@@ -177,15 +184,34 @@ async function putPath(client: MediaClient, path: string, flags: Flags, titled?:
return client.uploadAlbum({ title, items }, putOpts(flags));
}
/** Seal and upload `Film.srt`, `Film.no.srt`, `Film.en.vtt` … found next to `Film.mkv`. */
async function putSubtitles(client: MediaClient, video: string, flags: Flags): Promise<SubtitleTrack[]> {
const base = basename(video).slice(0, -extname(video).length);
const siblings = (await readdir(dirname(video))).sort(naturally.compare);
const tracks: SubtitleTrack[] = [];
for (const n of siblings) {
const lang = subtitleFor(base, n);
if (lang === null) continue;
const grant = await putFile(client, join(dirname(video), n), flags);
tracks.push(lang === '' ? { grant } : { grant, lang });
err(` subtitles: ${n}${lang ? ` (${lang})` : ''}`);
}
return tracks;
}
function putOpts(flags: Flags): { readToken?: null } {
return flags.public === true ? { readToken: null } : {};
}
async function putFile(client: MediaClient, file: string, flags: Flags, name?: string): Promise<MediaGrant> {
const meta: MediaMeta = { name: name ?? basename(file) };
// --mime names one file's type; in an album every file is guessed.
const mime = (name !== undefined || flags.album === undefined ? str(flags, 'mime') : undefined) ?? guessMime(file);
/** `as` overrides name and type — only for the one file named on the command line. */
async function putFile(client: MediaClient, file: string, flags: Flags, as: { name?: string; mime?: string } = {}): Promise<MediaGrant> {
let meta: MediaMeta = { name: as.name ?? basename(file) };
const mime = as.mime ?? guessMime(file);
if (mime !== undefined) meta.mime = mime;
if (mime?.startsWith('video/')) {
const tracks = await putSubtitles(client, file, flags);
if (tracks.length > 0) meta = withSubtitles(meta, tracks);
}
const size = (await stat(file)).size;
const tmp = join(tmpdir(), `shade-seal-${toHex(randomBytes(8))}.smf`);
try {
@@ -218,10 +244,38 @@ async function mediaGet(pos: string[], flags: Flags): Promise<number> {
}
const path = target ?? safeName(reader.meta.name, 'shade-media.bin');
await writeReader(reader, path);
if (path !== '-') err(`wrote ${path} (${reader.size} bytes, verified)`);
if (path !== '-') {
err(`wrote ${path} (${reader.size} bytes, verified)`);
await getSubtitles(reader.meta, path);
}
return 0;
}
/** A film's subtitles next to it, named the way `media put` finds them: `Film.no.srt`. */
async function getSubtitles(meta: MediaMeta, filmPath: string): Promise<number> {
let tracks;
try {
tracks = subtitlesOf(meta);
} catch (e) {
err(` (subtitles skipped: ${(e as Error).message})`);
return 0;
}
const stem = filmPath.slice(0, filmPath.length - extname(filmPath).length);
const used = new Set<string>();
let n = 0;
for (const t of tracks) {
const sub = await openGrant(t.grant);
const ext = SUBTITLE_EXTENSIONS.find((e) => sub.meta.name?.toLowerCase().endsWith(e)) ?? '.srt';
let path = `${stem}${t.lang !== undefined ? `.${t.lang}` : ''}${ext}`;
for (let i = 2; used.has(path); i++) path = `${stem}${t.lang !== undefined ? `.${t.lang}` : ''}.${i}${ext}`;
used.add(path);
await writeReader(sub, path);
err(` ${path}`);
n++;
}
return n;
}
/** Origin of the relay a grant points at, for watch links of live items. */
function server(g: MediaGrant): string {
return g.url !== undefined ? new URL(g.url).origin : 'http://localhost';
@@ -260,7 +314,7 @@ async function getAlbum(album: Album, dir: string, relay: string): Promise<numbe
const path = join(dir, unique(safeName(reader.meta.name, fallback)));
await writeReader(reader, path);
err(` ${path}`);
files++;
files += 1 + (await getSubtitles(reader.meta, path));
}
}
return files;

View File

@@ -36,3 +36,5 @@ export { WebmSplitter, webmMime } from './webm.js';
export type { WebmPiece } from './webm.js';
export { Fmp4Splitter, fmp4Mime } from './fmp4.js';
export type { Fmp4Piece } from './fmp4.js';
export { SUBTITLES_KEY, SUBTITLE_EXTENSIONS, withSubtitles, subtitlesOf, subtitleFor, srtToVtt } from './subtitles.js';
export type { SubtitleTrack } from './subtitles.js';

View File

@@ -0,0 +1,98 @@
/**
* Subtitles for sealed films.
*
* Subtitle files are sealed and uploaded like anything else; a film carries
* their grants in its own sealed meta, under `extra["shade.subtitles"]`:
*
* [{ "lang": "no", "label": "Norsk", "grant": { …media grant… } }, …]
*
* So the subtitles travel with the film, alone or in an album, and the relay
* sees three unrelated objects. Files are found by the usual naming:
* `Film.mkv` takes `Film.srt`, `Film.no.srt`, `Film.en.vtt`.
*/
import { MediaFormatError } from './errors.js';
import { encodeGrant, parseGrant } from './grant.js';
import type { MediaGrant } from './grant.js';
import type { MediaMeta } from './sealed.js';
export const SUBTITLES_KEY = 'shade.subtitles';
export const SUBTITLE_EXTENSIONS = ['.srt', '.vtt'] as const;
export interface SubtitleTrack {
grant: MediaGrant;
/** BCP 47 tag from the file name (`Film.no.srt` → `no`), if any. */
lang?: string;
label?: string;
}
const LANG_RE = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/;
const MAX_TRACKS = 64;
/** `meta` with these tracks attached (replacing any already there). */
export function withSubtitles(meta: MediaMeta, tracks: readonly SubtitleTrack[]): MediaMeta {
if (tracks.length > MAX_TRACKS) throw new MediaFormatError(`more than ${MAX_TRACKS} subtitle tracks`);
const wire = tracks.map((t) => ({
...(t.lang !== undefined ? { lang: checkLang(t.lang) } : {}),
...(t.label !== undefined ? { label: t.label } : {}),
grant: JSON.parse(encodeGrant(t.grant)) as unknown,
}));
return { ...meta, extra: { ...meta.extra, [SUBTITLES_KEY]: JSON.stringify(wire) } };
}
/** The subtitle tracks a film's meta names, strictly; none if it names none. */
export function subtitlesOf(meta: MediaMeta | undefined): SubtitleTrack[] {
const raw = meta?.extra?.[SUBTITLES_KEY];
if (raw === undefined) return [];
let list: unknown;
try {
list = JSON.parse(raw);
} catch {
throw new MediaFormatError('subtitles are not JSON');
}
if (!Array.isArray(list) || list.length > MAX_TRACKS) throw new MediaFormatError('subtitles must be a short array');
return list.map((t, i) => {
if (typeof t !== 'object' || t === null || Array.isArray(t)) throw new MediaFormatError(`subtitle ${i} is not an object`);
const o = t as Record<string, unknown>;
const g = parseGrant(JSON.stringify(o.grant));
if (g.kind !== 'shade.media-grant/v1') throw new MediaFormatError(`subtitle ${i} is not a sealed file`);
const track: SubtitleTrack = { grant: g };
if (o.lang !== undefined) {
if (typeof o.lang !== 'string') throw new MediaFormatError(`subtitle ${i}: bad lang`);
track.lang = checkLang(o.lang);
}
if (o.label !== undefined) {
if (typeof o.label !== 'string' || o.label.length > 200) throw new MediaFormatError(`subtitle ${i}: bad label`);
track.label = o.label;
}
return track;
});
}
/**
* Is `file` a subtitle for the video `videoBase` (its name without
* extension)? Returns the language from the name, `''` for none, or null.
*/
export function subtitleFor(videoBase: string, file: string): string | null {
const ext = SUBTITLE_EXTENSIONS.find((e) => file.toLowerCase().endsWith(e));
if (ext === undefined) return null;
const stem = file.slice(0, -ext.length);
if (stem === videoBase) return '';
if (!stem.startsWith(`${videoBase}.`)) return null;
const tag = stem.slice(videoBase.length + 1);
return LANG_RE.test(tag) ? tag : null;
}
/** SubRip → WebVTT, which is what `<track>` reads. VTT passes through. */
export function srtToVtt(text: string): string {
const t = text.replace(/^/, '').replace(/\r\n?/g, '\n');
if (t.startsWith('WEBVTT')) return t;
// Timestamps use a comma in SRT, a dot in VTT; cue numbers are valid VTT ids.
const body = t.replace(/(\d{2}:\d{2}:\d{2}),(\d{3})/g, '$1.$2');
return `WEBVTT\n\n${body.trim()}\n`;
}
function checkLang(lang: string): string {
if (!LANG_RE.test(lang)) throw new MediaFormatError(`bad subtitle language ${JSON.stringify(lang)}`);
return lang;
}