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()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user