feat(media,android): ExoPlayer DataSource for sealed files, demo player app

:shade-android-media wraps the Kotlin MediaReader as a Media3 DataSource,
so ExoPlayer plays and seeks any container from a sealed file; a tampered
segment fails the read instead of reaching the decoder. :shade-media-demo
opens a shared watch link and plays it.

Verified: Robolectric — byte-exact reads whole and in ranges, tamper
refusal, ExoPlayer plays a sealed H.264/AAC clip to the end and reopens
mid-file on seek. Kotlin suite 80/0. Not yet run on a device.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-18 21:33:32 +02:00
parent 75dbf530ce
commit e696d83283
15 changed files with 551 additions and 3 deletions

View File

@@ -0,0 +1,47 @@
plugins {
id("com.android.library")
kotlin("android")
}
// Sealed Shade media (SMF1) in Media3/ExoPlayer.
//
// `:shade-android` reads and verifies sealed files on the JVM; this module
// hands that reader to ExoPlayer as a DataSource, so any container the
// player understands (MP4, WebM, MKV, MP3, …) plays and seeks from a sealed
// file without the plaintext ever touching disk or the network.
android {
namespace = "no.zyon.shade.media.android"
compileSdk = 35
defaultConfig {
minSdk = 24
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
testOptions {
unitTests.isIncludeAndroidResources = true
}
}
val media3 = "1.5.1"
dependencies {
api(project(":shade-android"))
api("androidx.media3:media3-exoplayer:$media3")
api("androidx.media3:media3-datasource:$media3")
testImplementation("junit:junit:4.13.2")
testImplementation("org.robolectric:robolectric:4.14.1")
testImplementation("androidx.test:core:1.6.1")
testImplementation("androidx.media3:media3-test-utils:$media3")
testImplementation("androidx.media3:media3-test-utils-robolectric:$media3")
}

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />

View File

@@ -0,0 +1,41 @@
package no.zyon.shade.media.android
import android.net.Uri
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.source.MediaSource
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import no.zyon.shade.media.Grants
import no.zyon.shade.media.MediaFormatException
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.MediaReader
/**
* Sealed Shade media for ExoPlayer, from a link or grant to a [MediaSource].
*
* ```
* val reader = ShadeMedia.open(link) // network: off the main thread
* player.setMediaSource(ShadeMedia.mediaSource(reader))
* player.prepare()
* ```
*/
@UnstableApi
object ShadeMedia {
/** Open the sealed file a capability link (`…#shade=…`) grants. Blocking. */
fun open(link: String): MediaReader {
val grant = Grants.fromCapabilityUrl(link)
if (grant !is MediaGrant) throw MediaFormatException("that link is a live channel, not a sealed file")
return grant.open()
}
/** A progressive media source playing the reader's plaintext. */
fun mediaSource(reader: MediaReader): MediaSource {
val item = MediaItem.Builder()
.setUri(Uri.parse("shade-media://sealed"))
.apply { reader.meta.mime?.let { setMimeType(it) } }
.setMediaMetadata(MediaMetadata.Builder().setTitle(reader.meta.name).build())
.build()
return ProgressiveMediaSource.Factory(ShadeMediaDataSource.Factory(reader)).createMediaSource(item)
}
}

View File

@@ -0,0 +1,88 @@
package no.zyon.shade.media.android
import android.net.Uri
import androidx.media3.common.C
import androidx.media3.common.PlaybackException
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.BaseDataSource
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSourceException
import androidx.media3.datasource.DataSpec
import no.zyon.shade.media.MediaReader
import java.io.IOException
/**
* A Media3 [DataSource] over a sealed Shade file.
*
* ExoPlayer asks for byte ranges of the plaintext (the container's header,
* then wherever a seek lands); [MediaReader] fetches only the sealed segments
* under each range, checks them against the digest table and decrypts them.
* 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.
*/
@UnstableApi
class ShadeMediaDataSource(private val reader: MediaReader) : BaseDataSource(/* isNetwork = */ true) {
private var uri: Uri? = null
private var position = 0L
private var remaining = 0L
private var opened = false
override fun open(dataSpec: DataSpec): Long {
uri = dataSpec.uri
transferInitializing(dataSpec)
if (dataSpec.position > reader.size) {
throw DataSourceException(PlaybackException.ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE)
}
position = dataSpec.position
val left = reader.size - position
remaining = if (dataSpec.length == C.LENGTH_UNSET.toLong()) left else minOf(dataSpec.length, left)
opened = true
transferStarted(dataSpec)
return remaining
}
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
if (length == 0) return 0
if (remaining == 0L) return C.RESULT_END_OF_INPUT
val n = minOf(length.toLong(), remaining, MAX_READ).toInt()
val bytes = try {
reader.read(position, n)
} catch (e: IOException) {
throw e
} catch (e: Exception) {
// Tampered, truncated or foreign data: the file cannot be trusted
// from here on, and retrying will not change that.
throw DataSourceException(e, PlaybackException.ERROR_CODE_IO_UNSPECIFIED)
}
if (bytes.isEmpty()) return C.RESULT_END_OF_INPUT
System.arraycopy(bytes, 0, buffer, offset, bytes.size)
position += bytes.size
remaining -= bytes.size
bytesTransferred(bytes.size)
return bytes.size
}
override fun getUri(): Uri? = uri
override fun close() {
uri = null
if (opened) {
opened = false
transferEnded()
}
}
/** Data sources sharing one opened reader. */
class Factory(private val reader: MediaReader) : DataSource.Factory {
override fun createDataSource(): DataSource = ShadeMediaDataSource(reader)
}
private companion object {
/** One segment: the reader decrypts whole segments, so larger reads gain nothing. */
const val MAX_READ = 1L shl 20
}
}

View File

@@ -0,0 +1,127 @@
package no.zyon.shade.media.android
import android.net.Uri
import androidx.media3.common.C
import androidx.media3.common.MimeTypes
import androidx.media3.common.Player
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSourceException
import androidx.media3.datasource.DataSpec
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.test.utils.TestExoPlayerBuilder
import androidx.media3.test.utils.robolectric.TestPlayerRunHelper
import androidx.test.core.app.ApplicationProvider
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.MediaSealer
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.ByteArrayOutputStream
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class ShadeMediaDataSourceTest {
/** A 2 s H.264/AAC MP4, sealed in 4 KiB segments so every read crosses several. */
private val clip: ByteArray = javaClass.getResourceAsStream("/clip.mp4")!!.readBytes()
private fun sealed(plain: ByteArray = clip): Pair<ByteArray, MediaKeys> {
val (bytes, r) = MediaSealer.sealBytes(plain, MediaMeta(mime = "video/mp4", name = "clip.mp4"), segmentSize = 4096)
return bytes to MediaKeys(r.mediaId, r.mediaKey, r.rootDigest)
}
private fun reader(): MediaReader {
val (bytes, keys) = sealed()
return MediaReader.open(ByteArraySource(bytes), keys)
}
private fun readAll(ds: DataSource, spec: DataSpec): ByteArray {
val out = ByteArrayOutputStream()
val buf = ByteArray(3000) // not a divisor of the segment size
ds.open(spec)
while (true) {
val n = ds.read(buf, 0, buf.size)
if (n == C.RESULT_END_OF_INPUT) break
out.write(buf, 0, n)
}
ds.close()
return out.toByteArray()
}
@Test
fun readsThePlaintextWholeAndInRanges() {
val ds = ShadeMediaDataSource(reader())
val uri = Uri.parse("shade-media://sealed")
assertArrayEquals(clip, readAll(ds, DataSpec(uri)))
// Mid-file windows, as a seek produces: unbounded and bounded.
assertArrayEquals(clip.copyOfRange(9999, clip.size), readAll(ds, DataSpec.Builder().setUri(uri).setPosition(9999).build()))
assertArrayEquals(
clip.copyOfRange(4095, 4095 + 5000),
readAll(ds, DataSpec.Builder().setUri(uri).setPosition(4095).setLength(5000).build()),
)
// open() reports the length it will deliver.
assertEquals((clip.size - 100).toLong(), ds.open(DataSpec.Builder().setUri(uri).setPosition(100).build()))
ds.close()
assertEquals(0L, ds.open(DataSpec.Builder().setUri(uri).setPosition(clip.size.toLong()).build()))
assertEquals(C.RESULT_END_OF_INPUT, ds.read(ByteArray(10), 0, 10))
ds.close()
assertThrows(DataSourceException::class.java) {
ds.open(DataSpec.Builder().setUri(uri).setPosition(clip.size + 1L).build())
}
}
@Test
fun aTamperedSegmentFailsTheRead() {
val (bytes, keys) = sealed()
bytes[2 * 4096 + 100] = (bytes[2 * 4096 + 100].toInt() xor 1).toByte()
val ds = ShadeMediaDataSource(MediaReader.open(ByteArraySource(bytes), keys))
val e = assertThrows(DataSourceException::class.java) { readAll(ds, DataSpec(Uri.parse("shade-media://sealed"))) }
assertTrue(e.cause!!.message!!.contains("does not match its digest"))
}
@Test
fun exoPlayerPlaysAndSeeksASealedFilm() {
val reader = reader()
val opens = mutableListOf<Long>()
val counting = DataSource.Factory {
val inner = ShadeMediaDataSource(reader)
object : DataSource by inner {
override fun open(dataSpec: DataSpec): Long {
opens += dataSpec.position
return inner.open(dataSpec)
}
}
}
val player = TestExoPlayerBuilder(ApplicationProvider.getApplicationContext()).build()
val item = ShadeMedia.mediaSource(reader).mediaItem
player.setMediaSource(ProgressiveMediaSource.Factory(counting).createMediaSource(item))
player.prepare()
TestPlayerRunHelper.run(player).untilState(Player.STATE_READY)
val mimes = player.currentTracks.groups.map { it.getTrackFormat(0).sampleMimeType }
assertTrue("tracks: $mimes", MimeTypes.VIDEO_H264 in mimes)
assertTrue("tracks: $mimes", MimeTypes.AUDIO_AAC in mimes)
assertEquals(2000.0, player.duration.toDouble(), 100.0)
assertEquals("clip.mp4", player.mediaMetadata.title)
player.play()
TestPlayerRunHelper.run(player).untilState(Player.STATE_ENDED)
// A seek back into the film reopens the source mid-file.
opens.clear()
player.seekTo(1200)
TestPlayerRunHelper.run(player).untilState(Player.STATE_READY)
assertTrue("opened at $opens", opens.any { it > 0 })
assertTrue(player.currentPosition >= 1000)
player.play()
TestPlayerRunHelper.run(player).untilState(Player.STATE_ENDED)
player.release()
}
}