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

@@ -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;