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

@@ -23,8 +23,10 @@ decided: "2026-10-18 — Cardwell: neste steg er Shade-streaming av tekst, video
- [x] fMP4 (H.264/HEVC/AV1 + AAC/Opus) i live-splitteren ved siden av WebM, `shade live video` autodetekterer
- [x] Android: `:shade-android-media` (Media3 `ShadeMediaDataSource`, Robolectric-test med ExoPlayer som spiller og spoler) + `:shade-media-demo`-APK
## Neste
- Android-demo: ExoPlayer `DataSource` som spiller en forseglet film på dev-telefonen
- Kjør `:shade-media-demo` på dev-telefonen (RFCN504DWJF var ikke tilkoblet 2026-10-18)
- Postgres/S3-medielager
## Senere

View File

@@ -358,11 +358,18 @@ tasks:
- id: media-android-exoplayer
title: "Android-demo: ExoPlayer DataSource for forseglede filmer"
description: "MediaReader.inputStream finnes; mangler en Media3 DataSource og en demo-app på dev-telefonen (RFCN504DWJF)."
status: todo
column: todo
status: doing
column: doing
priority: medium
assignee: claude
branch: streaming
todos:
- text: "ShadeMediaDataSource + ShadeMedia (Media3), Robolectric: ExoPlayer spiller og spoler forseglet H.264/AAC"
done: true
- text: "Demo-app :shade-media-demo bygger (debug-APK)"
done: true
- text: "Installer og spill på dev-telefonen RFCN504DWJF — ikke tilkoblet ennå"
done: false
created: 2026-10-19
updated: 2026-10-19
completed_at: null

View File

@@ -40,6 +40,9 @@ New package **`@shade/media`** — see `docs/media.md`.
that publish from their own source.
- **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
(`ShadeMediaDataSource`, `ShadeMedia.mediaSource(reader)`), and
`:shade-media-demo` is a player app that opens a shared watch link.
### Fixed

View File

@@ -2,4 +2,5 @@ plugins {
kotlin("jvm") version "2.0.20" apply false
kotlin("android") version "2.0.20" apply false
id("com.android.library") version "8.7.3" apply false
id("com.android.application") version "8.7.3" apply false
}

View File

@@ -21,3 +21,7 @@ project(":shade-android").projectDir = file("shade-android")
include(":shade-android-keystore")
project(":shade-android-keystore").projectDir = file("shade-android-keystore")
include(":shade-android-media")
project(":shade-android-media").projectDir = file("shade-android-media")
include(":shade-media-demo")
project(":shade-media-demo").projectDir = file("shade-media-demo")

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()
}
}

View File

@@ -0,0 +1,45 @@
plugins {
id("com.android.application")
kotlin("android")
}
// Demo player for sealed Shade media: open a `…/watch/#shade=…` link and
// play it with ExoPlayer through `ShadeMediaDataSource`. Debug-signed, for
// the dev phone; not a product.
android {
namespace = "no.zyon.shade.mediademo"
compileSdk = 35
defaultConfig {
applicationId = "no.zyon.shade.mediademo"
minSdk = 24
targetSdk = 35
versionCode = 1
versionName = "4.15.0"
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
buildTypes {
release {
isMinifyEnabled = false
}
}
packaging {
resources.excludes += setOf("META-INF/versions/9/OSGI-INF/MANIFEST.MF")
}
}
dependencies {
implementation(project(":shade-android-media"))
implementation("androidx.media3:media3-ui:1.5.1")
}

View File

@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<!-- Cleartext is allowed so the demo can reach a relay on the LAN
(`shade media serve` speaks plain HTTP). The media is sealed end to
end either way; TLS would hide only which file is fetched. -->
<application
android:label="Shade Media"
android:usesCleartextTraffic="true"
android:theme="@android:style/Theme.Material.NoActionBar">
<activity
android:name=".PlayerActivity"
android:exported="true"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Share a watch link to the app from any browser or chat. -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,136 @@
package no.zyon.shade.mediademo
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.OptIn
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import no.zyon.shade.media.MediaReader
import no.zyon.shade.media.android.ShadeMedia
import java.util.concurrent.Executors
/**
* Plays a sealed Shade film, video, song or picture-less audio file.
*
* The link comes from a share (`ACTION_SEND` text), from
* `adb shell am start -n no.zyon.shade.mediademo/.PlayerActivity --es link '<link>'`,
* or is pasted into the field. Opening the reader fetches the footer and
* trailer over the network, so it runs off the main thread.
*/
@OptIn(UnstableApi::class)
class PlayerActivity : Activity() {
private val io = Executors.newSingleThreadExecutor()
private var player: ExoPlayer? = null
private var reader: MediaReader? = null
private lateinit var status: TextView
private lateinit var view: PlayerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val field = EditText(this).apply {
hint = "https://…/watch/#shade=…"
setSingleLine()
}
val open = Button(this).apply {
text = "Open"
setOnClickListener { play(field.text.toString().trim()) }
}
status = TextView(this).apply {
setTextColor(Color.LTGRAY)
setPadding(24, 12, 24, 12)
}
view = PlayerView(this).apply { setBackgroundColor(Color.BLACK) }
val bar = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
addView(field, LinearLayout.LayoutParams(0, WRAP_CONTENT, 1f))
addView(open)
}
setContentView(
LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setBackgroundColor(Color.rgb(15, 17, 21))
addView(bar, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
addView(status, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
addView(view, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
},
)
linkFrom(intent)?.let {
field.setText(it)
play(it)
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
linkFrom(intent)?.let { play(it) }
}
private fun linkFrom(intent: Intent?): String? = when (intent?.action) {
Intent.ACTION_SEND -> intent.getStringExtra(Intent.EXTRA_TEXT)
else -> intent?.getStringExtra("link")
}?.let { text -> Regex("\\S*#\\S*shade=[A-Za-z0-9_-]+").find(text)?.value }
private fun play(link: String) {
if (link.isEmpty()) return
stop()
status.text = "Opening…"
io.execute {
val opened = runCatching { ShadeMedia.open(link) }
runOnUiThread {
opened.fold(
onSuccess = { start(it) },
onFailure = { status.text = "Cannot open: ${it.message}" },
)
}
}
}
private fun start(r: MediaReader) {
reader = r
val p = ExoPlayer.Builder(this).build()
player = p
view.player = p
val name = r.meta.name ?: "sealed file"
status.text = "$name · ${r.meta.mime ?: "?"} · ${r.size / 1024} KiB · end-to-end encrypted"
p.addListener(object : Player.Listener {
override fun onPlayerError(error: PlaybackException) {
status.text = "Playback failed: ${error.cause?.message ?: error.message}"
}
})
p.setMediaSource(ShadeMedia.mediaSource(r))
p.prepare()
p.play()
}
private fun stop() {
view.player = null
player?.release()
player = null
reader?.close()
reader = null
}
override fun onStop() {
super.onStop()
player?.pause()
}
override fun onDestroy() {
stop()
io.shutdown()
super.onDestroy()
}
}

View File

@@ -116,6 +116,22 @@ On Android/JVM, `no.zyon.shade.media`: `Grants.fromCapabilityUrl(link)`,
`inputStream()`. `LiveSubscriber(grant).open(frame)` handles live frames, and
`MediaSealer` and `LivePublisher` write both formats byte for byte the way TS does.
For playback, `:shade-android-media` hands a reader to Media3/ExoPlayer, so any
container ExoPlayer understands plays and seeks from a sealed file:
```kotlin
val reader = ShadeMedia.open(link) // blocking: footer + trailer over HTTP
player.setMediaSource(ShadeMedia.mediaSource(reader))
player.prepare()
```
`ShadeMediaDataSource` serves the plaintext ranges ExoPlayer asks for; a tampered
segment fails the read with a `DataSourceException` instead of reaching the decoder.
`:shade-media-demo` is a small player app for the dev phone: share a watch link to it,
or start it with `adb shell am start -n no.zyon.shade.mediademo/.PlayerActivity --es link '<link>'`.
Against `shade media serve` on the PC, `adb reverse tcp:3910 tcp:3910` makes a
`http://localhost:3910/…` link work on the phone.
## SMF1 — the sealed file (cross-language contract)
All integers are big-endian.