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:
98
packages/shade-media/src/subtitles.ts
Normal file
98
packages/shade-media/src/subtitles.ts
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user