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:
@@ -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)
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,16 @@ 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.common.util.TimestampAdjuster
|
||||
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.LiveGrant
|
||||
import no.zyon.shade.media.MediaFormatException
|
||||
import no.zyon.shade.media.MediaGrant
|
||||
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
|
||||
* player.setMediaSource(ShadeMedia.mediaSource(reader))
|
||||
* player.prepare()
|
||||
*
|
||||
* player.setMediaSource(ShadeMedia.liveMediaSource(liveGrant)) // a live channel
|
||||
* ```
|
||||
*/
|
||||
@UnstableApi
|
||||
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 {
|
||||
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")
|
||||
return grant.open()
|
||||
}
|
||||
@@ -38,4 +51,29 @@ object ShadeMedia {
|
||||
.build()
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user