feat(media,android): live channels in ExoPlayer — LiveWatcher, ShadeLiveDataSource

LiveWatcher is the Android LiveWatchClient (OkHttp WebSocket, subscribe
with the read token, reconnect with backoff, backlog deduplicated by the
subscriber). ShadeLiveDataSource turns frames into one endless WebM/fMP4
stream for ExoPlayer's extractors: init, then media from the first
keyframe, and after a gap nothing until the next keyframe. Late joiners
start at 0:00 (fMP4: per-join TimestampAdjuster; WebM: cluster Timecode
rewritten in place). A changed init fails with a ParserException (not
retried). The demo app plays live video and follows log channels.
LiveSubscriber.close() wipes keys, as in TS.

Verified (Robolectric): late join on H.264/AAC fMP4 and VP8/Opus WebM cut
by the TS splitter (fixtures from scripts/make-live-fixtures.ts) plays
from the keyframe, rebased (mutation check: without the rebase the WebM
test fails, 5020 vs 4250 ms); gap recovery; format change; LiveWatcher
against MockWebServer with a dropped connection and backlog replay.
Kotlin 81/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:53:17 +02:00
parent 8c7300fa51
commit 9efe1bcfd3
13 changed files with 848 additions and 15 deletions

View File

@@ -26,6 +26,7 @@ decided: "2026-10-18 — Cardwell: neste steg er Shade-streaming av tekst, video
- [x] Android: `:shade-android-media` (Media3 `ShadeMediaDataSource`, Robolectric-test med ExoPlayer som spiller og spoler) + `:shade-media-demo`-APK - [x] Android: `:shade-android-media` (Media3 `ShadeMediaDataSource`, Robolectric-test med ExoPlayer som spiller og spoler) + `:shade-media-demo`-APK
- [x] Album: én lenke for en sesong/et fotoalbum (forseglet liste av grants), `shade media put dir/`, rutenett i `/watch/`, Kotlin-leser + vektor - [x] Album: én lenke for en sesong/et fotoalbum (forseglet liste av grants), `shade media put dir/`, rutenett i `/watch/`, Kotlin-leser + vektor
- [x] Sikkerhet: `shade media get` brukte `meta.name` som filsti (sti-traversering) — rettet - [x] Sikkerhet: `shade media get` brukte `meta.name` som filsti (sti-traversering) — rettet
- [x] Android live: `LiveWatcher` + `ShadeLiveDataSource` (WebM/fMP4 i ExoPlayer, sen innstigning, hull, tidslinje fra 0), demo-appen spiller live video og følger loggkanaler
## Neste ## Neste
- Kjør `:shade-media-demo` på dev-telefonen (RFCN504DWJF var ikke tilkoblet 2026-10-18) - Kjør `:shade-media-demo` på dev-telefonen (RFCN504DWJF var ikke tilkoblet 2026-10-18)

View File

@@ -50,6 +50,10 @@ New package **`@shade/media`** — see `docs/media.md`.
`:shade-android-media` plays sealed files in Media3/ExoPlayer `:shade-android-media` plays sealed files in Media3/ExoPlayer
(`ShadeMediaDataSource`, `ShadeMedia.mediaSource(reader)`), and (`ShadeMediaDataSource`, `ShadeMedia.mediaSource(reader)`), and
`:shade-media-demo` is a player app that opens a shared watch link. `:shade-media-demo` is a player app that opens a shared watch link.
Live channels on Android: `LiveWatcher` (OkHttp) and
`ShadeMedia.liveMediaSource(grant)` play live WebM/fMP4 in ExoPlayer,
with late joining from a keyframe, gap recovery and the timeline rebased
to 0:00.
### Fixed ### Fixed

View File

@@ -38,10 +38,13 @@ dependencies {
api(project(":shade-android")) api(project(":shade-android"))
api("androidx.media3:media3-exoplayer:$media3") api("androidx.media3:media3-exoplayer:$media3")
api("androidx.media3:media3-datasource:$media3") api("androidx.media3:media3-datasource:$media3")
// Live channels: the relay speaks WebSocket. `api`: LiveWatcher takes an OkHttpClient.
api("com.squareup.okhttp3:okhttp:4.12.0")
testImplementation("junit:junit:4.13.2") testImplementation("junit:junit:4.13.2")
testImplementation("org.robolectric:robolectric:4.14.1") testImplementation("org.robolectric:robolectric:4.14.1")
testImplementation("androidx.test:core:1.6.1") testImplementation("androidx.test:core:1.6.1")
testImplementation("androidx.media3:media3-test-utils:$media3") testImplementation("androidx.media3:media3-test-utils:$media3")
testImplementation("androidx.media3:media3-test-utils-robolectric:$media3") testImplementation("androidx.media3:media3-test-utils-robolectric:$media3")
testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")
} }

View File

@@ -0,0 +1,147 @@
package no.zyon.shade.media.android
import no.zyon.shade.media.LiveGrant
import no.zyon.shade.media.LiveSubscriber
import no.zyon.shade.media.ReceivedFrame
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import org.json.JSONObject
import java.io.Closeable
import java.util.Base64
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
/**
* Watch a live channel: the Android side of the TS `LiveWatchClient`.
*
* Connects to the relay named in the grant, subscribes with the read token,
* and hands every frame that verifies and decrypts to [Listener.onFrame], in
* arrival order. A dropped connection is retried with backoff; the relay's
* backlog on reconnect is deduplicated by the subscriber, so the listener
* sees each frame once.
*/
class LiveWatcher(
grant: LiveGrant,
private val listener: Listener,
private val client: OkHttpClient = sharedClient,
url: String? = null,
) : Closeable {
enum class State { CONNECTING, WAITING, LIVE, RECONNECTING, CLOSED }
interface Listener {
fun onFrame(frame: ReceivedFrame)
fun onState(state: State) {}
/** A frame failed to verify or decrypt, or the relay refused us. The stream continues. */
fun onError(error: Exception) {}
}
private val url: String = url ?: grant.url ?: throw IllegalArgumentException("grant has no relay URL")
private val token: String = grant.readToken?.let { Base64.getUrlEncoder().withoutPadding().encodeToString(it) }
?: throw IllegalArgumentException("grant has no read token")
/** Not thread-safe; every use is under `lock`. */
private val subscriber = LiveSubscriber(grant)
private val lock = Any()
private val timer: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor { r ->
Thread(r, "shade-live-reconnect").apply { isDaemon = true }
}
@Volatile private var closed = false
private var socket: WebSocket? = null
private var delayMs = INITIAL_DELAY_MS
private var everConnected = false
init {
connect()
}
/** Hand over the grant for a new epoch (it arrives over the Shade session). */
fun addGrant(g: LiveGrant) = synchronized(lock) {
subscriber.addGrant(g)
subscriber.forgetBefore(g.epoch)
}
private fun connect() {
if (closed) return
listener.onState(if (everConnected) State.RECONNECTING else State.CONNECTING)
val request = Request.Builder().url(url).build()
val ws = client.newWebSocket(request, Handler())
synchronized(lock) { socket = ws }
}
private inner class Handler : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
webSocket.send(JSONObject().put("type", "subscribe").put("token", token).toString())
}
override fun onMessage(webSocket: WebSocket, text: String) {
val msg = runCatching { JSONObject(text) }.getOrNull() ?: return
when (msg.optString("type")) {
"ready" -> {
synchronized(lock) {
delayMs = INITIAL_DELAY_MS
everConnected = true
}
listener.onState(if (msg.optBoolean("live")) State.LIVE else State.WAITING)
}
"error" -> listener.onError(LiveRelayException(msg.optString("message", "relay error")))
}
}
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
// OkHttp calls this on the socket's reader thread, one message at
// a time — frames are opened in arrival order, as the chain needs.
val frame = try {
synchronized(lock) { if (closed) return else subscriber.open(bytes.toByteArray()) }
} catch (e: Exception) {
listener.onError(e)
return
}
if (frame != null) listener.onFrame(frame)
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
webSocket.close(1000, null)
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = retry(webSocket)
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = retry(webSocket)
}
private fun retry(ws: WebSocket) {
val delay = synchronized(lock) {
if (closed || socket !== ws) return
socket = null
delayMs.also { delayMs = minOf(delayMs * 2, MAX_DELAY_MS) }
}
listener.onState(State.RECONNECTING)
timer.schedule({ connect() }, delay, TimeUnit.MILLISECONDS)
}
override fun close() {
val ws = synchronized(lock) {
if (closed) return
closed = true
socket.also { socket = null }
}
ws?.close(1000, null)
timer.shutdownNow()
synchronized(lock) { subscriber.close() }
listener.onState(State.CLOSED)
}
private companion object {
const val INITIAL_DELAY_MS = 250L
const val MAX_DELAY_MS = 10_000L
/** One client for every watcher: OkHttp shares its pools and threads. */
val sharedClient: OkHttpClient by lazy {
OkHttpClient.Builder().pingInterval(20, TimeUnit.SECONDS).readTimeout(0, TimeUnit.MILLISECONDS).build()
}
}
}
class LiveRelayException(message: String) : Exception(message)

View File

@@ -0,0 +1,253 @@
package no.zyon.shade.media.android
import android.net.Uri
import androidx.media3.common.C
import androidx.media3.common.ParserException
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.LiveContent
import no.zyon.shade.media.ReceivedFrame
import java.io.Closeable
import java.io.InterruptedIOException
import java.util.ArrayDeque
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* A live Shade channel (WebM or fragmented MP4) as one endless byte stream
* for ExoPlayer's progressive extractors.
*
* The stream is what a demuxer expects from a live muxer: the channel's
* init (sticky), then media pieces from the first keyframe on. Where frames
* are missing — a reconnect, the relay shedding a slow viewer — it skips to
* the next keyframe, so the decoder never sees a piece that depends on one
* it did not get. A late joiner's timeline is rebased to start at zero (see
* [ShadeMedia.liveMediaSource] for fMP4; WebM cluster timecodes here), or a
* player would wait out the minutes it missed.
*
* `connect` opens the frame feed: [LiveWatcher] by default, a fake in tests.
*/
@UnstableApi
class ShadeLiveDataSource(
private val connect: (LiveWatcher.Listener) -> Closeable,
) : BaseDataSource(/* isNetwork = */ true) {
private val lock = ReentrantLock()
private val ready = lock.newCondition()
private val queue = ArrayDeque<ByteArray>()
private var head: ByteArray? = null
private var headPos = 0
private var init: ByteArray? = null
private var webm = false
private var needKeyframe = true
private var lastEpoch = -1L
private var lastSeq = -1L
/** WebM: the first delivered cluster's timecode, subtracted from every cluster. */
private var webmBase = -1L
private var ended = false
private var failure: Exception? = null
private var feed: Closeable? = null
private var uri: Uri? = null
/** Frames skipped while waiting for a keyframe, for diagnostics. */
@Volatile var droppedFrames = 0L
private set
override fun open(dataSpec: DataSpec): Long {
// A live stream cannot resume mid-byte; ExoPlayer reopens an
// unseekable source from the start, which is a fresh join.
if (dataSpec.position != 0L) throw DataSourceException(PlaybackException.ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE)
uri = dataSpec.uri
transferInitializing(dataSpec)
lock.withLock { resetLocked() }
feed = connect(Feed())
transferStarted(dataSpec)
return C.LENGTH_UNSET.toLong()
}
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
if (length == 0) return 0
val n = lock.withLock {
while (head == null) {
failure?.let { throw it as? java.io.IOException ?: DataSourceException(it, PlaybackException.ERROR_CODE_IO_UNSPECIFIED) }
val next = queue.pollFirst()
if (next != null) {
head = next
headPos = 0
break
}
if (ended) return C.RESULT_END_OF_INPUT
// Wake now and then: ExoPlayer cancels a load by interrupting.
ready.await(250, TimeUnit.MILLISECONDS)
if (Thread.interrupted()) throw InterruptedIOException()
}
val h = head!!
val n = minOf(length, h.size - headPos)
System.arraycopy(h, headPos, buffer, offset, n)
headPos += n
if (headPos == h.size) head = null
n
}
bytesTransferred(n)
return n
}
override fun getUri(): Uri? = uri
override fun close() {
val f = feed
feed = null
f?.close()
lock.withLock {
resetLocked()
ended = true
ready.signalAll()
}
if (uri != null) {
uri = null
transferEnded()
}
}
private fun resetLocked() {
queue.clear()
head = null
init = null
webm = false
needKeyframe = true
lastEpoch = -1
lastSeq = -1
webmBase = -1
ended = false
failure = null
}
/** Frames in arrival order (from the watcher's thread) → bytes for the extractor. */
private inner class Feed : LiveWatcher.Listener {
override fun onFrame(frame: ReceivedFrame) {
lock.withLock { accept(frame) }
}
private fun accept(frame: ReceivedFrame) {
if (ended || failure != null) return
// Contiguous: the next seq in this epoch, or seq 0 of the next
// epoch (a rotation reseals the sticky frames first, numbered from 0).
val contiguous = (frame.epoch == lastEpoch && frame.seq == lastSeq + 1) ||
(frame.epoch == lastEpoch + 1 && frame.seq == 0L)
if (!contiguous && lastEpoch >= 0) needKeyframe = true
lastEpoch = frame.epoch
lastSeq = frame.seq
when (val c = frame.content) {
is LiveContent.Init -> {
val known = init
if (known == null) {
init = c.bytes
webm = c.mime.contains("webm")
queue.addLast(c.bytes)
ready.signalAll()
} else if (!known.contentEquals(c.bytes)) {
// A new init mid-stream is a new stream; the demuxer cannot
// splice it. A ParserException, because retrying cannot help
// and ExoPlayer's load policy does not retry those.
failure = ParserException.createForMalformedContainer(
"the live stream changed its format",
LiveFormatChangedException(),
)
ready.signalAll()
}
}
is LiveContent.Chunk -> {
if (init == null || (needKeyframe && !frame.keyframe)) {
droppedFrames++
return
}
needKeyframe = false
queue.addLast(if (webm) rebaseCluster(c.bytes) else c.bytes)
ready.signalAll()
}
is LiveContent.End -> {
ended = true
ready.signalAll()
}
else -> Unit // text, images and meta are not part of the media stream
}
}
override fun onError(error: Exception) {
// A frame that failed to verify is dropped by the watcher; the gap
// check above then waits for the next keyframe. Nothing to do here.
}
}
/** WebM: rewrite the cluster's Timecode so the first cluster delivered is at 0. */
private fun rebaseCluster(cluster: ByteArray): ByteArray {
val tc = Ebml.clusterTimecode(cluster) ?: return cluster
if (webmBase < 0) webmBase = tc.value
val v = tc.value - webmBase
if (v < 0) return cluster
val out = cluster.copyOf()
var x = v
for (i in tc.length - 1 downTo 0) {
out[tc.offset + i] = (x and 0xff).toByte()
x = x ushr 8
}
return out
}
class Factory(private val connect: (LiveWatcher.Listener) -> Closeable) : DataSource.Factory {
override fun createDataSource(): DataSource = ShadeLiveDataSource(connect)
}
}
class LiveFormatChangedException : Exception("the live stream changed its format; reopen it")
/** Just enough EBML to find a Cluster's Timecode. */
internal object Ebml {
class Field(val offset: Int, val length: Int, val value: Long)
private const val ID_CLUSTER = 0x1f43b675L
private const val ID_TIMECODE = 0xe7L
private fun vintLength(first: Int, max: Int): Int {
var len = 1
while (len <= max && (first and (0x80 shr (len - 1))) == 0) len++
return if (len > max) -1 else len
}
fun clusterTimecode(b: ByteArray): Field? {
val idLen = vintLength(b.getOrNull(0)?.toInt()?.and(0xff) ?: return null, 4)
if (idLen < 0 || readUInt(b, 0, idLen) != ID_CLUSTER) return null
val sizeLen = vintLength(b.getOrNull(idLen)?.toInt()?.and(0xff) ?: return null, 8)
if (sizeLen < 0) return null
var at = idLen + sizeLen
// The Timecode is the first child in practice; look a few elements in.
repeat(4) {
val first = b.getOrNull(at)?.toInt()?.and(0xff) ?: return null
val cl = vintLength(first, 4)
if (cl < 0) return null
val id = readUInt(b, at, cl)
val szFirst = b.getOrNull(at + cl)?.toInt()?.and(0xff) ?: return null
val sl = vintLength(szFirst, 8)
if (sl < 0) return null
var size = (szFirst and (0xff shr sl)).toLong()
for (i in 1 until sl) size = (size shl 8) or (b[at + cl + i].toLong() and 0xff)
val body = at + cl + sl
if (id == ID_TIMECODE) {
if (size !in 1..8 || body + size > b.size) return null
return Field(body, size.toInt(), readUInt(b, body, size.toInt()))
}
at = body + size.toInt()
}
return null
}
private fun readUInt(b: ByteArray, at: Int, len: Int): Long {
var v = 0L
for (i in 0 until len) v = (v shl 8) or (b[at + i].toLong() and 0xff)
return v
}
}

View File

@@ -5,8 +5,16 @@ import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata import androidx.media3.common.MediaMetadata
import androidx.media3.common.util.UnstableApi import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.source.MediaSource import androidx.media3.exoplayer.source.MediaSource
import androidx.media3.common.util.TimestampAdjuster
import androidx.media3.exoplayer.source.ProgressiveMediaSource import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.extractor.Extractor
import androidx.media3.extractor.ExtractorsFactory
import androidx.media3.extractor.mkv.MatroskaExtractor
import androidx.media3.extractor.mp4.FragmentedMp4Extractor
import androidx.media3.extractor.text.SubtitleParser
import no.zyon.shade.media.Grant
import no.zyon.shade.media.Grants import no.zyon.shade.media.Grants
import no.zyon.shade.media.LiveGrant
import no.zyon.shade.media.MediaFormatException import no.zyon.shade.media.MediaFormatException
import no.zyon.shade.media.MediaGrant import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.MediaReader import no.zyon.shade.media.MediaReader
@@ -18,13 +26,18 @@ import no.zyon.shade.media.MediaReader
* val reader = ShadeMedia.open(link) // network: off the main thread * val reader = ShadeMedia.open(link) // network: off the main thread
* player.setMediaSource(ShadeMedia.mediaSource(reader)) * player.setMediaSource(ShadeMedia.mediaSource(reader))
* player.prepare() * player.prepare()
*
* player.setMediaSource(ShadeMedia.liveMediaSource(liveGrant)) // a live channel
* ``` * ```
*/ */
@UnstableApi @UnstableApi
object ShadeMedia { object ShadeMedia {
/** Open the sealed file a capability link (`…#shade=…`) grants. Blocking. */ /** The grant in a capability link (`…#shade=…`). */
fun grant(link: String): Grant = Grants.fromCapabilityUrl(link)
/** Open the sealed file a capability link grants. Blocking. */
fun open(link: String): MediaReader { fun open(link: String): MediaReader {
val grant = Grants.fromCapabilityUrl(link) val grant = grant(link)
if (grant !is MediaGrant) throw MediaFormatException("that link is a live channel, not a sealed file") if (grant !is MediaGrant) throw MediaFormatException("that link is a live channel, not a sealed file")
return grant.open() return grant.open()
} }
@@ -38,4 +51,29 @@ object ShadeMedia {
.build() .build()
return ProgressiveMediaSource.Factory(ShadeMediaDataSource.Factory(reader)).createMediaSource(item) return ProgressiveMediaSource.Factory(ShadeMediaDataSource.Factory(reader)).createMediaSource(item)
} }
/**
* A live channel carrying WebM or fragmented MP4 (`shade live video`).
*
* `connect` opens the frame feed; the default is a [LiveWatcher] on the
* grant's relay. The fMP4 extractor gets a fresh [TimestampAdjuster] per
* join, so a viewer who arrives an hour in starts at 0:00 rather than
* waiting an hour for the first sample; WebM is rebased by the data source.
*/
fun liveMediaSource(
grant: LiveGrant,
connect: (LiveWatcher.Listener) -> java.io.Closeable = { l -> LiveWatcher(grant, l) },
): MediaSource {
val item = MediaItem.Builder()
.setUri(Uri.parse("shade-live://channel"))
.setMediaMetadata(MediaMetadata.Builder().setTitle(grant.meta?.name).build())
.build()
val extractors = ExtractorsFactory {
arrayOf<Extractor>(
FragmentedMp4Extractor(SubtitleParser.Factory.UNSUPPORTED, 0, TimestampAdjuster(0), null, emptyList(), null),
MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED),
)
}
return ProgressiveMediaSource.Factory(ShadeLiveDataSource.Factory(connect), extractors).createMediaSource(item)
}
} }

View File

@@ -0,0 +1,221 @@
package no.zyon.shade.media.android
import androidx.media3.common.MimeTypes
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.test.utils.TestExoPlayerBuilder
import androidx.media3.test.utils.robolectric.TestPlayerRunHelper
import androidx.test.core.app.ApplicationProvider
import no.zyon.shade.media.LiveContent
import no.zyon.shade.media.LiveGrant
import no.zyon.shade.media.LivePublisher
import no.zyon.shade.media.LiveSubscriber
import no.zyon.shade.media.ReceivedFrame
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okio.ByteString.Companion.toByteString
import org.json.JSONObject
import org.junit.Assert.assertEquals
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.Closeable
import java.nio.ByteBuffer
import java.security.SecureRandom
import java.util.Base64
import java.util.Collections
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class ShadeLiveTest {
/** A piece cut by the TS splitter (scripts/make-live-fixtures.ts). */
class Piece(val init: Boolean, val keyframe: Boolean, val bytes: ByteArray)
private fun pieces(name: String): List<Piece> {
val b = ByteBuffer.wrap(javaClass.getResourceAsStream("/$name")!!.readBytes())
val out = ArrayList<Piece>()
while (b.hasRemaining()) {
val kind = b.get().toInt()
val bytes = ByteArray(b.getInt()).also { b.get(it) }
out += Piece(kind == 0, kind == 1, bytes)
}
return out
}
private fun random(n: Int) = ByteArray(n).also { SecureRandom().nextBytes(it) }
/** A channel: the grant a viewer holds, and every frame the publisher sent, sealed and signed. */
private class Channel(val grant: LiveGrant, val frames: List<ByteArray>)
private fun channel(pieces: List<Piece>, mime: String, extra: (LivePublisher) -> List<ByteArray> = { emptyList() }): Channel {
val pub = LivePublisher(random(16), random(32), null)
val grant = pub.grant(from = "now", url = "ws://relay.invalid/v1/live/x", readToken = random(32))
val frames = ArrayList<ByteArray>()
for (p in pieces) {
frames += if (p.init) pub.frame(LiveContent.Init(mime, p.bytes), sticky = true) else pub.frame(LiveContent.Chunk(p.bytes), keyframe = p.keyframe)
}
frames += extra(pub)
frames += pub.frame(LiveContent.End)
return Channel(grant, frames)
}
/** A feed that opens and delivers the chosen frames on its own thread, as the watcher would. */
private fun feed(ch: Channel, pick: (Int) -> Boolean = { true }): (LiveWatcher.Listener) -> Closeable = { listener ->
val t = Thread {
val sub = LiveSubscriber(ch.grant)
ch.frames.forEachIndexed { i, f -> if (pick(i)) sub.open(f)?.let(listener::onFrame) }
}
t.start()
Closeable { t.join() }
}
private class Played(val mimes: List<String?>, val endPositionMs: Long)
private fun play(ch: Channel, connect: (LiveWatcher.Listener) -> Closeable): Played {
val player = TestExoPlayerBuilder(ApplicationProvider.getApplicationContext()).build()
player.setMediaSource(ShadeMedia.liveMediaSource(ch.grant, connect))
player.prepare()
TestPlayerRunHelper.run(player).untilState(Player.STATE_READY)
val mimes = player.currentTracks.groups.map { it.getTrackFormat(0).sampleMimeType }
player.play()
TestPlayerRunHelper.run(player).untilState(Player.STATE_ENDED)
val end = player.currentPosition
player.release()
return Played(mimes, end)
}
@Test
fun lateJoinOnFragmentedMp4StartsAtTheNextKeyframeAndAtZero() {
val pieces = pieces("live-h264.pieces")
val ch = channel(pieces, "video/mp4")
// Frame 0 is the init; a viewer joining mid-GOP sees media from frame 3.
val firstKey = (3 until pieces.size).first { pieces[it].keyframe }
val played = play(ch, feed(ch) { it == 0 || it >= 3 })
assertTrue("tracks: ${played.mimes}", MimeTypes.VIDEO_H264 in played.mimes && MimeTypes.AUDIO_AAC in played.mimes)
// 20 pieces of 250 ms; from the keyframe on that is what plays, from 0:00.
val expectMs = (pieces.size - firstKey) * 250L
assertEquals("rebased to zero, not ${firstKey * 250} ms in", expectMs.toDouble(), played.endPositionMs.toDouble(), 300.0)
}
@Test
fun lateJoinOnWebmIsRebasedToo() {
val pieces = pieces("live-vp8.pieces")
val ch = channel(pieces, "video/webm")
val firstKey = (3 until pieces.size).first { pieces[it].keyframe }
val played = play(ch, feed(ch) { it == 0 || it >= 3 })
assertTrue("tracks: ${played.mimes}", MimeTypes.VIDEO_VP8 in played.mimes && MimeTypes.AUDIO_OPUS in played.mimes)
val expectMs = (pieces.size - firstKey) * 250L
assertEquals(expectMs.toDouble(), played.endPositionMs.toDouble(), 350.0)
}
@Test
fun aGapWaitsForTheNextKeyframe() {
val pieces = pieces("live-h264.pieces")
val ch = channel(pieces, "video/mp4")
// Lose one frame inside a GOP: the rest of that GOP must not reach the decoder.
val lost = (2 until pieces.size).first { !pieces[it].keyframe && !pieces[it - 1].keyframe }
val ds = ShadeLiveDataSource(feed(ch) { it != lost })
val read = drain(ds)
val nextKey = (lost + 1 until pieces.size).first { pieces[it].keyframe }
val expected = pieces.filterIndexed { i, _ -> i < lost || i >= nextKey }.map { it.bytes }
assertEquals(expected.sumOf { it.size }, read.size)
assertEquals((nextKey - lost - 1).toLong(), ds.droppedFrames)
}
@Test
fun aDifferentInitMidStreamFailsPlaybackInsteadOfCorruptingIt() {
val pieces = pieces("live-h264.pieces")
val ch = channel(pieces.take(8), "video/mp4") { pub ->
listOf(pub.frame(LiveContent.Init("video/mp4", byteArrayOf(1, 2, 3)), sticky = true))
}
val player = TestExoPlayerBuilder(ApplicationProvider.getApplicationContext()).build()
player.setMediaSource(ShadeMedia.liveMediaSource(ch.grant, feed(ch)))
player.prepare()
player.play()
val error: PlaybackException = TestPlayerRunHelper.runUntilError(player)
var cause: Throwable? = error
while (cause != null && cause !is LiveFormatChangedException) cause = cause.cause
val chain = generateSequence(error as Throwable) { it.cause }.joinToString(" <- ") { "${it.javaClass.simpleName}(${it.message})" }
assertTrue("error: $chain", cause is LiveFormatChangedException)
player.release()
}
/** Read a data source to its end, as an extractor would. */
private fun drain(ds: ShadeLiveDataSource): ByteArray {
val out = java.io.ByteArrayOutputStream()
ds.open(androidx.media3.datasource.DataSpec(android.net.Uri.parse("shade-live://x")))
val buf = ByteArray(4096)
while (true) {
val n = ds.read(buf, 0, buf.size)
if (n < 0) break
out.write(buf, 0, n)
}
ds.close()
return out.toByteArray()
}
@Test
fun watcherSubscribesReconnectsAndDeliversEachFrameOnce() {
val pieces = pieces("live-h264.pieces").take(6)
val server = MockWebServer()
server.start()
val pub = LivePublisher(random(16), random(32), null)
val token = random(32)
val grant = pub.grant(from = "now", url = server.url("/v1/live/x").toString().replace("http", "ws"), readToken = token)
val frames = pieces.map {
if (it.init) pub.frame(LiveContent.Init("video/mp4", it.bytes), sticky = true) else pub.frame(LiveContent.Chunk(it.bytes), keyframe = it.keyframe)
} + pub.frame(LiveContent.End)
val subscribes = Collections.synchronizedList(ArrayList<String>())
// First connection: half the frames, then the relay drops us.
// Second: the backlog again from the start (as a relay does), then the rest.
for (attempt in 0..1) {
server.enqueue(
MockResponse().withWebSocketUpgrade(object : WebSocketListener() {
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
webSocket.close(1000, null)
}
override fun onMessage(webSocket: WebSocket, text: String) {
subscribes += text
webSocket.send("""{"type":"ready","live":true}""")
val upTo = if (attempt == 0) 4 else frames.size
for (f in frames.take(upTo)) webSocket.send(f.toByteString())
if (attempt == 0) webSocket.close(1001, "going away")
}
}),
)
}
val got = Collections.synchronizedList(ArrayList<ReceivedFrame>())
val states = Collections.synchronizedList(ArrayList<LiveWatcher.State>())
val done = CountDownLatch(1)
val watcher = LiveWatcher(grant, object : LiveWatcher.Listener {
override fun onFrame(frame: ReceivedFrame) {
got += frame
if (frame.content is LiveContent.End) done.countDown()
}
override fun onState(state: LiveWatcher.State) {
states += state
}
})
assertTrue("timed out; states $states, frames ${got.size}", done.await(10, TimeUnit.SECONDS))
watcher.close()
server.shutdown()
assertEquals(2, subscribes.size)
for (s in subscribes) {
val o = JSONObject(s)
assertEquals("subscribe", o.getString("type"))
assertEquals(Base64.getUrlEncoder().withoutPadding().encodeToString(token), o.getString("token"))
}
assertEquals((0L until frames.size).toList(), got.map { it.seq })
assertTrue("states: $states", states.count { it == LiveWatcher.State.LIVE } == 2 && LiveWatcher.State.RECONNECTING in states)
assertEquals(LiveWatcher.State.CLOSED, states.last())
}
}

View File

@@ -185,6 +185,13 @@ class LiveSubscriber(grant: LiveGrant) {
} }
} }
/** Wipe every key held; the subscriber opens nothing afterwards. */
fun close() {
forgetBefore(Long.MAX_VALUE)
link?.first?.fill(0)
link = null
}
private fun epochState(epoch: Long): EpochState? { private fun epochState(epoch: Long): EpochState? {
epochs[epoch]?.let { return it } epochs[epoch]?.let { return it }
val (secret, from) = link ?: return null val (secret, from) = link ?: return null

View File

@@ -10,6 +10,7 @@ import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.Button import android.widget.Button
import android.widget.EditText import android.widget.EditText
import android.widget.LinearLayout import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView import android.widget.TextView
import androidx.annotation.OptIn import androidx.annotation.OptIn
import androidx.media3.common.PlaybackException import androidx.media3.common.PlaybackException
@@ -17,12 +18,18 @@ import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView 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.MediaReader
import no.zyon.shade.media.ReceivedFrame
import no.zyon.shade.media.android.LiveWatcher
import no.zyon.shade.media.android.ShadeMedia import no.zyon.shade.media.android.ShadeMedia
import java.util.concurrent.Executors import java.util.concurrent.Executors
/** /**
* Plays a sealed Shade film, video, song or picture-less audio file. * Plays a sealed Shade film, video or song, or watches a live channel:
* live video/audio through ExoPlayer, a live log as scrolling text.
* *
* The link comes from a share (`ACTION_SEND` text), from * The link comes from a share (`ACTION_SEND` text), from
* `adb shell am start -n no.zyon.shade.mediademo/.PlayerActivity --es link '<link>'`, * `adb shell am start -n no.zyon.shade.mediademo/.PlayerActivity --es link '<link>'`,
@@ -34,8 +41,11 @@ class PlayerActivity : Activity() {
private val io = Executors.newSingleThreadExecutor() private val io = Executors.newSingleThreadExecutor()
private var player: ExoPlayer? = null private var player: ExoPlayer? = null
private var reader: MediaReader? = null private var reader: MediaReader? = null
private var watcher: LiveWatcher? = null
private lateinit var status: TextView private lateinit var status: TextView
private lateinit var view: PlayerView private lateinit var view: PlayerView
private lateinit var log: TextView
private lateinit var logScroll: ScrollView
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
@@ -52,6 +62,16 @@ class PlayerActivity : Activity() {
setPadding(24, 12, 24, 12) setPadding(24, 12, 24, 12)
} }
view = PlayerView(this).apply { setBackgroundColor(Color.BLACK) } view = PlayerView(this).apply { setBackgroundColor(Color.BLACK) }
log = TextView(this).apply {
setTextColor(Color.rgb(214, 219, 225))
typeface = android.graphics.Typeface.MONOSPACE
textSize = 11f
setPadding(24, 12, 24, 12)
}
logScroll = ScrollView(this).apply {
addView(log)
visibility = android.view.View.GONE
}
val bar = LinearLayout(this).apply { val bar = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL gravity = Gravity.CENTER_VERTICAL
@@ -65,6 +85,7 @@ class PlayerActivity : Activity() {
addView(bar, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)) addView(bar, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
addView(status, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)) addView(status, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
addView(view, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f)) addView(view, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
addView(logScroll, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
}, },
) )
linkFrom(intent)?.let { linkFrom(intent)?.let {
@@ -86,36 +107,100 @@ class PlayerActivity : Activity() {
private fun play(link: String) { private fun play(link: String) {
if (link.isEmpty()) return if (link.isEmpty()) return
stop() stop()
status.text = "Opening…" val grant = runCatching { ShadeMedia.grant(link) }.getOrElse {
io.execute { status.text = "Not a Shade link: ${it.message}"
val opened = runCatching { ShadeMedia.open(link) } return
runOnUiThread { }
opened.fold( when (grant) {
onSuccess = { start(it) }, is LiveGrant -> watch(grant)
onFailure = { status.text = "Cannot open: ${it.message}" }, is MediaGrant -> {
) status.text = "Opening…"
io.execute {
val opened = runCatching { grant.open() }
runOnUiThread {
opened.fold(
onSuccess = { start(it) },
onFailure = { status.text = "Cannot open: ${it.message}" },
)
}
}
} }
} }
} }
private fun start(r: MediaReader) { private fun watch(g: LiveGrant) {
reader = r val name = g.meta?.name ?: "live channel"
val mime = g.meta?.mime ?: ""
if (mime.startsWith("video/") || mime.startsWith("audio/")) {
showPlayer(true)
val p = newPlayer()
status.text = "$name · live · end-to-end encrypted"
p.setMediaSource(ShadeMedia.liveMediaSource(g))
p.prepare()
p.play()
return
}
// Text and images: follow the channel directly.
showPlayer(false)
log.text = ""
status.text = "$name · connecting…"
watcher = LiveWatcher(g, object : LiveWatcher.Listener {
override fun onFrame(frame: ReceivedFrame) {
val c = frame.content
runOnUiThread {
when (c) {
is LiveContent.Text -> appendLog(c.text)
is LiveContent.End -> status.text = "$name · the broadcast has ended"
else -> Unit
}
}
}
override fun onState(state: LiveWatcher.State) {
runOnUiThread { status.text = "$name · ${state.name.lowercase()} · end-to-end encrypted" }
}
})
}
private fun appendLog(text: String) {
val atBottom = !logScroll.canScrollVertically(1)
log.append(text)
// Bound the view: a log channel runs for days.
if (log.length() > MAX_LOG_CHARS) log.text = log.text.subSequence(log.length() - MAX_LOG_CHARS / 2, log.length())
if (atBottom) logScroll.post { logScroll.fullScroll(android.view.View.FOCUS_DOWN) }
}
private fun showPlayer(video: Boolean) {
view.visibility = if (video) android.view.View.VISIBLE else android.view.View.GONE
logScroll.visibility = if (video) android.view.View.GONE else android.view.View.VISIBLE
}
private fun newPlayer(): ExoPlayer {
val p = ExoPlayer.Builder(this).build() val p = ExoPlayer.Builder(this).build()
player = p player = p
view.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 { p.addListener(object : Player.Listener {
override fun onPlayerError(error: PlaybackException) { override fun onPlayerError(error: PlaybackException) {
status.text = "Playback failed: ${error.cause?.message ?: error.message}" status.text = "Playback failed: ${error.cause?.message ?: error.message}"
} }
}) })
return p
}
private fun start(r: MediaReader) {
reader = r
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)) p.setMediaSource(ShadeMedia.mediaSource(r))
p.prepare() p.prepare()
p.play() p.play()
} }
private fun stop() { private fun stop() {
watcher?.close()
watcher = null
view.player = null view.player = null
player?.release() player?.release()
player = null player = null
@@ -133,4 +218,8 @@ class PlayerActivity : Activity() {
io.shutdown() io.shutdown()
super.onDestroy() super.onDestroy()
} }
private companion object {
const val MAX_LOG_CHARS = 200_000
}
} }

View File

@@ -131,6 +131,18 @@ player.prepare()
`ShadeMediaDataSource` serves the plaintext ranges ExoPlayer asks for; a tampered `ShadeMediaDataSource` serves the plaintext ranges ExoPlayer asks for; a tampered
segment fails the read with a `DataSourceException` instead of reaching the decoder. segment fails the read with a `DataSourceException` instead of reaching the decoder.
Live channels play too: `ShadeMedia.liveMediaSource(liveGrant)` connects a
`LiveWatcher` (OkHttp WebSocket, reconnects with backoff, the relay's backlog
deduplicated) and turns the frames into one endless WebM or fMP4 stream for
ExoPlayer's own extractors: the init, then media from the first keyframe, and after
any gap (a reconnect, the relay shedding a slow viewer) nothing until the next
keyframe. A late joiner's timeline starts at 0:00: fMP4 through a per-join
`TimestampAdjuster`, WebM by rewriting each cluster's Timecode in place. Otherwise a
viewer arriving an hour in would wait an hour for the first sample. A different init
mid-stream fails playback with a `ParserException`, which is not retried, rather than
feeding the decoder a spliced stream. `LiveWatcher` on its own follows text and image
channels.
`:shade-media-demo` is a small player app for the dev phone: share a watch link to it, `: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>'`. 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 Against `shade media serve` on the PC, `adb reverse tcp:3910 tcp:3910` makes a

View File

@@ -0,0 +1,58 @@
/**
* Live-stream fixtures for the Android tests (`:shade-android-media`).
*
* Encodes a short H.264/AAC fragmented MP4 and a VP8/Opus WebM with ffmpeg,
* cuts both with the TS `MediaSplitter` — the same cut `shade live video`
* sends — and writes the pieces as `[u8 kind][u32 length][bytes]…`, kind 0 =
* init, 1 = keyframe piece, 2 = other piece. The Kotlin tests seal them into
* live frames and play them through ExoPlayer.
*
* Run: bun scripts/make-live-fixtures.ts
*/
import { writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { MediaSplitter } from '../packages/shade-media/src/splitter.js';
const OUT = join(import.meta.dir, '../android/shade-android-media/src/test/resources');
const SRC = [
'-f', 'lavfi', '-i', 'testsrc2=size=160x120:rate=15,format=yuv420p',
'-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=48000', '-t', '5',
];
async function ffmpeg(args: string[]): Promise<Uint8Array> {
const p = Bun.spawn(['ffmpeg', '-hide_banner', '-loglevel', 'error', ...SRC, ...args, 'pipe:1'], { stdout: 'pipe', stderr: 'inherit' });
const out = new Uint8Array(await new Response(p.stdout).arrayBuffer());
if ((await p.exited) !== 0) throw new Error('ffmpeg failed');
return out;
}
async function write(name: string, stream: Uint8Array): Promise<void> {
const s = new MediaSplitter();
const pieces = [...s.push(stream), ...s.finish()];
const parts: Uint8Array[] = [];
for (const p of pieces) {
const head = new Uint8Array(5);
head[0] = p.type === 'init' ? 0 : p.keyframe ? 1 : 2;
new DataView(head.buffer).setUint32(1, p.bytes.length);
parts.push(head, p.bytes);
}
await writeFile(join(OUT, name), Buffer.concat(parts));
const keys = pieces.filter((p) => p.type === 'media' && p.keyframe).length;
console.log(`${name}: ${pieces[0]?.type === 'init' ? pieces[0].mime : '?'}, ${pieces.length - 1} pieces, ${keys} keyframes`);
}
await write(
'live-h264.pieces',
await ffmpeg([
'-c:v', 'libx264', '-preset', 'veryfast', '-g', '15', '-keyint_min', '15', '-sc_threshold', '0', '-crf', '35',
'-c:a', 'aac', '-b:a', '32k',
'-f', 'mp4', '-movflags', 'frag_keyframe+empty_moov+default_base_moof', '-frag_duration', '250000',
]),
);
await write(
'live-vp8.pieces',
await ffmpeg([
'-c:v', 'libvpx', '-deadline', 'realtime', '-g', '15', '-b:v', '100k', '-c:a', 'libopus', '-b:a', '32k',
'-f', 'webm', '-live', '1', '-cluster_time_limit', '250',
]),
);