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:
@@ -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() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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":{}}]""")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
|
||||
Reference in New Issue
Block a user