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

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