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:
@@ -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)}`;
|
||||
|
||||
@@ -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';
|
||||
|
||||
Reference in New Issue
Block a user