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

@@ -27,6 +27,7 @@ decided: "2026-10-18 — Cardwell: neste steg er Shade-streaming av tekst, video
- [x] Album: én lenke for en sesong/et fotoalbum (forseglet liste av grants), `shade media put dir/`, rutenett i `/watch/`, Kotlin-leser + vektor
- [x] Sikkerhet: `shade media get` brukte `meta.name` som filsti (sti-traversering) — rettet
- [x] Android live: `LiveWatcher` + `ShadeLiveDataSource` (WebM/fMP4 i ExoPlayer, sen innstigning, hull, tidslinje fra 0), demo-appen spiller live video og følger loggkanaler
- [x] Undertekster: `Film.no.srt` ved siden av filmen forsegles og følger filmen i dens meta; `<track>` i nettleseren (språkvalg, SRT→VTT), ExoPlayer på Android, `media get` skriver dem tilbake
## Neste
- Kjør `:shade-media-demo` på dev-telefonen (RFCN504DWJF var ikke tilkoblet 2026-10-18)

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

View File

@@ -4,3 +4,4 @@
04 — Et forseglet JPEG-bilde vist via Service Worker; lyd (Opus) spiller og spoler på samme måte
05 — Live H.264/AAC som fragmentert MP4 (ffmpeg → shade live video → relay → Chromium), sen innstigning på keyframe-fragment, 3,2 s forsinkelse
06 — Et album («Ferie 2026»): én lenke åpner film, video, lyd, bilde og et nøstet album; forhåndsvisningene dekrypteres i nettleseren, relayen ser bare én ugjennomsiktig fil til
07 — En forseglet film med Testfilm.no.srt og Testfilm.en.srt ved siden av: undertekstene følger filmen kryptert, og nettleseren velger norsk fordi den er satt til bokmål

View File

@@ -45,6 +45,12 @@ New package **`@shade/media`** — see `docs/media.md`.
natural order); `shade media get` downloads an album back into a
directory; `/watch/` shows it as a grid with decrypted previews.
`uploadAlbum`, `openAlbum`, `Albums.read` (Kotlin), and a shared vector.
- **Subtitles.** `shade media put Film.mkv` seals `Film.srt`,
`Film.no.srt`, `Film.en.vtt` … beside it and carries their grants in the
film's sealed meta; `/watch/` shows them as `<track>`s (SRT converted to
VTT, the viewer's language on), `media get` writes them back, and
Android plays them as side-loaded ExoPlayer text tracks
(`ShadeMedia.openFilm`).
- **Kotlin.** `no.zyon.shade.media`: SMF1 reader and sealer, grants, live
subscriber and publisher — byte-for-byte against `test-vectors/media.json`.
`:shade-android-media` plays sealed files in Media3/ExoPlayer

View File

@@ -4,6 +4,9 @@ import android.net.Uri
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.util.UnstableApi
import androidx.media3.common.C
import androidx.media3.common.MimeTypes
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.exoplayer.source.MediaSource
import androidx.media3.common.util.TimestampAdjuster
import androidx.media3.exoplayer.source.ProgressiveMediaSource
@@ -18,6 +21,8 @@ import no.zyon.shade.media.LiveGrant
import no.zyon.shade.media.MediaFormatException
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.MediaReader
import no.zyon.shade.media.SubtitleTrack
import no.zyon.shade.media.Subtitles
/**
* Sealed Shade media for ExoPlayer, from a link or grant to a [MediaSource].
@@ -42,6 +47,50 @@ object ShadeMedia {
return grant.open()
}
/**
* Open a sealed film and the subtitle files its meta names. Blocking. A
* subtitle that cannot be opened is skipped; the film plays without it.
*/
fun openFilm(grant: MediaGrant): ShadeFilm {
val reader = grant.open()
val tracks = runCatching { Subtitles.of(reader.meta) }.getOrDefault(emptyList())
val subs = tracks.mapNotNull { t -> runCatching { t to t.grant.open() }.getOrNull() }
return ShadeFilm(grant, reader, subs)
}
/**
* A film with its subtitles as side-loaded text tracks. ExoPlayer parses
* SubRip and WebVTT itself; each file is read through its own reader.
*/
fun mediaSource(film: ShadeFilm, locale: java.util.Locale = java.util.Locale.getDefault()): MediaSource {
// The track in the viewer's language is on by default (Bokmål and
// Nynorsk match a `no` file); otherwise none is.
val base = { tag: String -> tag.substringBefore('-').lowercase().let { if (it == "nb" || it == "nn") "no" else it } }
val preferred = film.subtitles.indexOfFirst { (t, _) -> t.lang != null && base(t.lang!!) == base(locale.language) }
val readers = HashMap<Uri, MediaReader>()
val filmUri = uriOf(film.grant).also { readers[it] = film.reader }
val configs = film.subtitles.mapIndexed { i, (track, reader) ->
val uri = uriOf(track.grant).also { readers[it] = reader }
val vtt = reader.meta.name?.lowercase()?.endsWith(".vtt") == true || reader.meta.mime == "text/vtt"
MediaItem.SubtitleConfiguration.Builder(uri)
.setMimeType(if (vtt) MimeTypes.TEXT_VTT else MimeTypes.APPLICATION_SUBRIP)
.apply { track.lang?.let { setLanguage(it) } }
.apply { (track.label ?: track.lang)?.let { setLabel(it) } }
.setSelectionFlags(if (i == preferred) C.SELECTION_FLAG_DEFAULT else 0)
.build()
}
val item = MediaItem.Builder()
.setUri(filmUri)
.apply { film.reader.meta.mime?.let { setMimeType(it) } }
.setMediaMetadata(MediaMetadata.Builder().setTitle(film.reader.meta.name).build())
.setSubtitleConfigurations(configs)
.build()
return DefaultMediaSourceFactory(ShadeMediaDataSource.Factory { u -> readers[u] }).createMediaSource(item)
}
private fun uriOf(g: MediaGrant): Uri =
Uri.parse("shade-media://" + g.mediaId.joinToString("") { "%02x".format(it) })
/** A progressive media source playing the reader's plaintext. */
fun mediaSource(reader: MediaReader): MediaSource {
val item = MediaItem.Builder()
@@ -77,3 +126,15 @@ object ShadeMedia {
return ProgressiveMediaSource.Factory(ShadeLiveDataSource.Factory(connect), extractors).createMediaSource(item)
}
}
/** A sealed film and its opened subtitle files. Close it when done. */
class ShadeFilm(
val grant: MediaGrant,
val reader: MediaReader,
val subtitles: List<Pair<SubtitleTrack, MediaReader>>,
) : java.io.Closeable {
override fun close() {
reader.close()
subtitles.forEach { it.second.close() }
}
}

View File

@@ -20,18 +20,25 @@ import java.io.IOException
* The plaintext lives in the reader's small segment cache and the player's
* buffers, never on disk.
*
* The URI in the [DataSpec] is only a label: the reader already knows which
* file it reads. One reader may back many data sources (it is thread-safe),
* which is what [Factory] does.
* The URI picks the reader (`resolve`): a film and its subtitle files are
* separate sealed files, each with its own `shade-media://<id>`. Readers are
* thread-safe, so one may back many data sources, which is what [Factory]
* does.
*/
@UnstableApi
class ShadeMediaDataSource(private val reader: MediaReader) : BaseDataSource(/* isNetwork = */ true) {
class ShadeMediaDataSource(private val resolve: (Uri) -> MediaReader?) : BaseDataSource(/* isNetwork = */ true) {
/** Every URI reads this one file. */
constructor(reader: MediaReader) : this({ _: Uri -> reader })
private lateinit var reader: MediaReader
private var uri: Uri? = null
private var position = 0L
private var remaining = 0L
private var opened = false
override fun open(dataSpec: DataSpec): Long {
reader = resolve(dataSpec.uri)
?: throw DataSourceException(PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND)
uri = dataSpec.uri
transferInitializing(dataSpec)
if (dataSpec.position > reader.size) {
@@ -76,9 +83,12 @@ class ShadeMediaDataSource(private val reader: MediaReader) : BaseDataSource(/*
}
}
/** Data sources sharing one opened reader. */
class Factory(private val reader: MediaReader) : DataSource.Factory {
override fun createDataSource(): DataSource = ShadeMediaDataSource(reader)
/** Data sources sharing opened readers, chosen by URI. */
class Factory(private val resolve: (Uri) -> MediaReader?) : DataSource.Factory {
/** Every URI reads this one file. */
constructor(reader: MediaReader) : this({ _: Uri -> reader })
override fun createDataSource(): DataSource = ShadeMediaDataSource(resolve)
}
private companion object {

View File

@@ -15,7 +15,9 @@ import no.zyon.shade.media.ByteArraySource
import no.zyon.shade.media.MediaKeys
import no.zyon.shade.media.MediaMeta
import no.zyon.shade.media.MediaReader
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.MediaSealer
import no.zyon.shade.media.SubtitleTrack
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
@@ -124,4 +126,35 @@ class ShadeMediaDataSourceTest {
TestPlayerRunHelper.run(player).untilState(Player.STATE_ENDED)
player.release()
}
@Test
fun aFilmPlaysWithItsSubtitlesAndPicksTheViewersLanguage() {
fun sealedFile(bytes: ByteArray, meta: MediaMeta): Pair<MediaGrant, MediaReader> {
val (sealed, r) = MediaSealer.sealBytes(bytes, meta, segmentSize = 4096)
val grant = MediaGrant(r.mediaId, r.mediaKey, r.rootDigest, url = "https://relay.invalid/x")
return grant to MediaReader.open(ByteArraySource(sealed), MediaKeys(r.mediaId, r.mediaKey, r.rootDigest))
}
val no = sealedFile("1\r\n00:00:00,100 --> 00:00:01,900\r\nHei, æøå!\r\n".toByteArray(), MediaMeta(name = "clip.no.srt"))
val en = sealedFile("WEBVTT\n\n00:00.100 --> 00:01.900\nHello!\n".toByteArray(), MediaMeta(name = "clip.en.vtt", mime = "text/vtt"))
val film = sealedFile(clip, MediaMeta(mime = "video/mp4", name = "clip.mp4"))
val shadeFilm = ShadeFilm(
film.first,
film.second,
listOf(SubtitleTrack(en.first, "en") to en.second, SubtitleTrack(no.first, "no", "Norsk") to no.second),
)
val player = TestExoPlayerBuilder(ApplicationProvider.getApplicationContext()).build()
player.setMediaSource(ShadeMedia.mediaSource(shadeFilm, java.util.Locale.forLanguageTag("nb-NO")))
player.prepare()
TestPlayerRunHelper.run(player).untilState(Player.STATE_READY)
val text = player.currentTracks.groups.filter { it.type == C.TRACK_TYPE_TEXT }
assertEquals("text tracks: ${text.map { it.getTrackFormat(0) }}", 2, text.size)
// The test player has no text renderer to select with; what we decide
// is which track is the default, and the player reports that flag.
val defaults = text.filter { it.getTrackFormat(0).selectionFlags and C.SELECTION_FLAG_DEFAULT != 0 }.map { it.getTrackFormat(0).language }
assertEquals(listOf("no"), defaults)
assertTrue(text.any { it.getTrackFormat(0).label == "Norsk" })
player.play()
TestPlayerRunHelper.run(player).untilState(Player.STATE_ENDED)
player.release()
}
}

View File

@@ -0,0 +1,36 @@
package no.zyon.shade.media
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
/**
* Subtitles — mirror of `@shade/media/src/subtitles.ts`. A film carries the
* grants of its sealed subtitle files in its own sealed meta, under
* `extra["shade.subtitles"]`: `[{"lang":"no","label":"…","grant":{…}}, …]`.
*/
const val SUBTITLES_KEY = "shade.subtitles"
private const val MAX_TRACKS = 64
private val LANG_RE = Regex("^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$")
class SubtitleTrack(val grant: MediaGrant, val lang: String? = null, val label: String? = null)
object Subtitles {
/** The subtitle tracks a film's meta names, strictly; none if it names none. */
fun of(meta: MediaMeta?): List<SubtitleTrack> {
val raw = meta?.extra?.get(SUBTITLES_KEY) ?: return emptyList()
val list = try { JSONArray(raw) } catch (e: JSONException) { throw MediaFormatException("subtitles are not a JSON array") }
if (list.length() > MAX_TRACKS) throw MediaFormatException("more than $MAX_TRACKS subtitle tracks")
return (0 until list.length()).map { i ->
val o = list.opt(i) as? JSONObject ?: throw MediaFormatException("subtitle $i is not an object")
val g = Grants.parse((o.opt("grant") as? JSONObject ?: throw MediaFormatException("subtitle $i has no grant")).toString())
if (g !is MediaGrant) throw MediaFormatException("subtitle $i is not a sealed file")
val lang = if (!o.has("lang")) null else (o.opt("lang") as? String)?.takeIf { LANG_RE.matches(it) }
?: throw MediaFormatException("subtitle $i: bad lang")
val label = if (!o.has("label")) null else (o.opt("label") as? String)?.takeIf { it.length <= 200 }
?: throw MediaFormatException("subtitle $i: bad label")
SubtitleTrack(g, lang, label)
}
}
}

View File

@@ -19,6 +19,7 @@ import no.zyon.shade.media.MediaKeys
import no.zyon.shade.media.MediaMeta
import no.zyon.shade.media.MediaReader
import no.zyon.shade.media.MediaSealer
import no.zyon.shade.media.Subtitles
import no.zyon.shade.media.chainStep
import no.zyon.shade.media.decodeFrame
import no.zyon.shade.media.deriveMediaSubkeys
@@ -208,4 +209,23 @@ class MediaVectorTest {
assertThrows(MediaFormatException::class.java) { Albums.parse("""{"kind":"shade.album/v2","title":"","items":[]}""".toByteArray()) }
assertThrows(MediaFormatException::class.java) { Albums.parse(byteArrayOf(0xff.toByte(), 0xfe.toByte())) }
}
@Test
fun subtitlesInAFilmsMetaParse() {
val v = byPrefix("subtitles:").single()
val tracks = Subtitles.of(MediaMeta.fromJson(v.getString("meta")))
val langs = v.getJSONArray("langs")
val labels = v.getJSONArray("labels")
val ids = v.getJSONArray("mediaIds")
assertEquals(langs.length(), tracks.size)
tracks.forEachIndexed { i, t ->
assertEquals(langs.getString(i), t.lang)
assertEquals(if (labels.isNull(i)) null else labels.getString(i), t.label)
assertEquals(ids.getString(i), toHex(t.grant.mediaId))
}
assertEquals(emptyList<Any>(), Subtitles.of(MediaMeta(name = "no subtitles")))
assertThrows(MediaFormatException::class.java) {
Subtitles.of(MediaMeta(extra = mapOf("shade.subtitles" to """[{"lang":"no; x","grant":{}}]""")))
}
}
}

View File

@@ -21,9 +21,9 @@ import androidx.media3.ui.PlayerView
import no.zyon.shade.media.LiveContent
import no.zyon.shade.media.LiveGrant
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.MediaReader
import no.zyon.shade.media.ReceivedFrame
import no.zyon.shade.media.android.LiveWatcher
import no.zyon.shade.media.android.ShadeFilm
import no.zyon.shade.media.android.ShadeMedia
import java.util.concurrent.Executors
@@ -40,7 +40,7 @@ import java.util.concurrent.Executors
class PlayerActivity : Activity() {
private val io = Executors.newSingleThreadExecutor()
private var player: ExoPlayer? = null
private var reader: MediaReader? = null
private var film: ShadeFilm? = null
private var watcher: LiveWatcher? = null
private lateinit var status: TextView
private lateinit var view: PlayerView
@@ -116,7 +116,7 @@ class PlayerActivity : Activity() {
is MediaGrant -> {
status.text = "Opening…"
io.execute {
val opened = runCatching { grant.open() }
val opened = runCatching { ShadeMedia.openFilm(grant) }
runOnUiThread {
opened.fold(
onSuccess = { start(it) },
@@ -187,13 +187,14 @@ class PlayerActivity : Activity() {
return p
}
private fun start(r: MediaReader) {
reader = r
private fun start(f: ShadeFilm) {
film = f
showPlayer(true)
val p = newPlayer()
val name = r.meta.name ?: "sealed file"
status.text = "$name · ${r.meta.mime ?: "?"} · ${r.size / 1024} KiB · end-to-end encrypted"
p.setMediaSource(ShadeMedia.mediaSource(r))
val meta = f.reader.meta
val subs = if (f.subtitles.isEmpty()) "" else " · ${f.subtitles.size} subtitle track(s)"
status.text = "${meta.name ?: "sealed file"} · ${meta.mime ?: "?"} · ${f.reader.size / 1024} KiB$subs · end-to-end encrypted"
p.setMediaSource(ShadeMedia.mediaSource(f))
p.prepare()
p.play()
}
@@ -204,8 +205,8 @@ class PlayerActivity : Activity() {
view.player = null
player?.release()
player = null
reader?.close()
reader = null
film?.close()
film = null
}
override fun onStop() {

View File

@@ -298,6 +298,30 @@ in TS, `Albums.parse` / `Albums.read` in Kotlin. The `/watch/` page shows an alb
grid with decrypted previews, and Back returns from an item to its album. History
entries hold only a depth, never a grant.
## Subtitles
`shade media put Film.mkv` also seals and uploads the subtitle files next to it, named
the usual way: `Film.srt`, `Film.no.srt`, `Film.en-GB.vtt`. Their grants go into the
film's own sealed meta, under `extra["shade.subtitles"]`:
```jsonc
[{ "lang": "no", "label": "Norsk", "grant": { "kind": "shade.media-grant/v1", … } }, …]
```
So the subtitles travel with the film, shared alone or inside an album, and the relay
sees unrelated objects. In a directory, subtitles that belong to a video are not listed
as album items of their own. `shade media get` writes them back next to the film as
`Film.<lang>.srt`.
The `/watch/` page decrypts them through the worker, turns SubRip into WebVTT, and adds
them as `<track>`s with names in the viewer's language. The track in the browser's
language is on (Bokmål and Nynorsk match a `no` file), and only one is shown at a time.
On Android, `ShadeMedia.openFilm(grant)` opens the film and its subtitle files, and
`ShadeMedia.mediaSource(film)` gives them to ExoPlayer as side-loaded text tracks, the
one in the device's language marked default. A subtitle that cannot be opened is
skipped; the film plays without it. `withSubtitles` / `subtitlesOf` (TS) and
`Subtitles.of` (Kotlin) read and write the field, checked against a shared vector.
## What the relay learns
- **Sealed:** that an opaque id exists, its size (to within a segment), when it was

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

View File

@@ -0,0 +1,59 @@
import { describe, test, expect } from 'bun:test';
import { MediaFormatError, validateMeta } from '../src/index.js';
import type { MediaGrant } from '../src/index.js';
import { SUBTITLES_KEY, srtToVtt, subtitleFor, subtitlesOf, withSubtitles } from '../src/subtitles.js';
const grant = (fill: number): MediaGrant => ({
kind: 'shade.media-grant/v1',
mediaId: new Uint8Array(16).fill(fill),
mediaKey: new Uint8Array(32).fill(fill),
rootDigest: new Uint8Array(32).fill(fill),
url: `https://relay.example/v1/media/${fill}`,
meta: { name: `sub-${fill}.srt` },
});
describe('subtitles', () => {
test.each([
['Film', 'Film.srt', ''],
['Film', 'Film.no.srt', 'no'],
['Film', 'Film.en-GB.vtt', 'en-GB'],
['Film', 'Film.NO.SRT', 'NO'],
['Film', 'Film 2.srt', null],
['Film', 'Film.mkv', null],
['Film', 'Film.forced.english.srt', null],
['Film', 'Other.no.srt', null],
['S01E02', 'S01E02.nb-NO.srt', 'nb-NO'],
] as const)('subtitleFor(%p, %p) = %p', (base, file, want) => {
expect(subtitleFor(base, file)).toBe(want);
});
test('travel in the meta, and survive meta validation', () => {
const meta = withSubtitles({ name: 'Film.mkv', mime: 'video/x-matroska', extra: { series: 'X' } }, [
{ grant: grant(1), lang: 'no' },
{ grant: grant(2), lang: 'en', label: 'English (SDH)' },
{ grant: grant(3) },
]);
expect(meta.extra?.series).toBe('X');
const back = subtitlesOf(validateMeta(JSON.parse(JSON.stringify(meta))));
expect(back.map((t) => [t.lang, t.label])).toEqual([['no', undefined], ['en', 'English (SDH)'], [undefined, undefined]]);
expect(back[0]!.grant).toEqual(grant(1));
expect(subtitlesOf({ name: 'no subs' })).toEqual([]);
expect(subtitlesOf(undefined)).toEqual([]);
});
test('strict: junk, live grants and bad language tags are refused', () => {
const bad = (v: string) => () => subtitlesOf({ extra: { [SUBTITLES_KEY]: v } });
expect(bad('{')).toThrow(MediaFormatError);
expect(bad('{}')).toThrow(MediaFormatError);
expect(bad('[{"grant":{"kind":"shade.media-grant/v1"}}]')).toThrow(MediaFormatError);
expect(bad(JSON.stringify([{ lang: 'no; drop', grant: JSON.parse(JSON.stringify({ kind: 'x' })) }]))).toThrow(MediaFormatError);
expect(() => withSubtitles({}, [{ grant: grant(1), lang: '../../x' }])).toThrow(/language/);
});
test('SubRip becomes WebVTT; WebVTT passes through', () => {
const srt = '1\r\n00:00:01,000 --> 00:00:02,500\r\nHei, verden!\r\n\r\n2\r\n00:01:00,250 --> 00:01:02,000\r\nÆ, ø og å\r\n';
expect(srtToVtt(srt)).toBe('WEBVTT\n\n1\n00:00:01.000 --> 00:00:02.500\nHei, verden!\n\n2\n00:01:00.250 --> 00:01:02.000\nÆ, ø og å\n');
const vtt = 'WEBVTT\n\n00:00.000 --> 00:01.000\nx\n';
expect(srtToVtt(vtt)).toBe(vtt);
});
});

View File

@@ -60,6 +60,7 @@ import type { LiveContent } from '../packages/shade-media/src/live/frame.js';
import { encodeGrant } from '../packages/shade-media/src/grant.js';
import type { MediaGrant } from '../packages/shade-media/src/grant.js';
import { albumMeta, encodeAlbum } from '../packages/shade-media/src/album.js';
import { withSubtitles } from '../packages/shade-media/src/subtitles.js';
import { ed25519PublicKeyFromSeed as edPub } from '../packages/shade-crypto-web/src/index.js';
const VECTOR_FILE_VERSION = 2;
@@ -1108,6 +1109,19 @@ async function generateMediaVectors(): Promise<Vector[]> {
itemKinds: ['shade.media-grant/v1', 'shade.media-grant/v1', 'shade.live-grant/v1'],
itemNames: ['Episode 1.mkv', 'Ekstra', grant.meta?.name ?? ''],
});
// Subtitles: a film's meta carrying its subtitle grants.
const subMeta = withSubtitles({ name: 'Film.mkv', mime: 'video/x-matroska' }, [
{ grant: { ...film, mediaId: new Uint8Array(16).fill(0x55), meta: { name: 'Film.no.srt' } }, lang: 'no', label: 'Norsk' },
{ grant: { ...film, mediaId: new Uint8Array(16).fill(0x66), meta: { name: 'Film.en.vtt' } }, lang: 'en' },
]);
vectors.push({
description: 'subtitles: film meta with extra["shade.subtitles"] naming two sealed subtitle files',
meta: JSON.stringify(subMeta),
langs: ['no', 'en'],
labels: ['Norsk', null],
mediaIds: [hex(new Uint8Array(16).fill(0x55)), hex(new Uint8Array(16).fill(0x66))],
});
return vectors;
}

View File

@@ -155,6 +155,22 @@
"Ekstra",
"kanal"
]
},
{
"description": "subtitles: film meta with extra[\"shade.subtitles\"] naming two sealed subtitle files",
"meta": "{\"name\":\"Film.mkv\",\"mime\":\"video/x-matroska\",\"extra\":{\"shade.subtitles\":\"[{\\\"lang\\\":\\\"no\\\",\\\"label\\\":\\\"Norsk\\\",\\\"grant\\\":{\\\"kind\\\":\\\"shade.media-grant/v1\\\",\\\"mediaId\\\":\\\"VVVVVVVVVVVVVVVVVVVVVQ\\\",\\\"key\\\":\\\"IiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiI\\\",\\\"root\\\":\\\"3333333333333333333333333333333333333333333333333333333333333333\\\",\\\"url\\\":\\\"https://relay.example/v1/media/11111111111111111111111111111111\\\",\\\"meta\\\":{\\\"name\\\":\\\"Film.no.srt\\\"}}},{\\\"lang\\\":\\\"en\\\",\\\"grant\\\":{\\\"kind\\\":\\\"shade.media-grant/v1\\\",\\\"mediaId\\\":\\\"ZmZmZmZmZmZmZmZmZmZmZg\\\",\\\"key\\\":\\\"IiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiI\\\",\\\"root\\\":\\\"3333333333333333333333333333333333333333333333333333333333333333\\\",\\\"url\\\":\\\"https://relay.example/v1/media/11111111111111111111111111111111\\\",\\\"meta\\\":{\\\"name\\\":\\\"Film.en.vtt\\\"}}}]\"}}",
"langs": [
"no",
"en"
],
"labels": [
"Norsk",
null
],
"mediaIds": [
"55555555555555555555555555555555",
"66666666666666666666666666666666"
]
}
]
}