Modern Apps git

← Modern-Apps.git

cast: add an SDK content session the app serves bytes into

Commit
9361d4d73f348727e667062ab43e9090f240ceab
Author
vayun-mathur <[email protected]>
When
2026-08-23 18:01 UTC (3 months ago)
Parents
47043bc

Diff

cast/src/main/java/com/vayunmathur/cast/service/ClientResourceResolver.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/service/ClientResourceResolver.kt b/cast/src/main/java/com/vayunmathur/cast/service/ClientResourceResolver.ktnew file mode 100644index 0000000000..3df4c921e8--- /dev/null+++ b/cast/src/main/java/com/vayunmathur/cast/service/ClientResourceResolver.kt@@ -0,0 +1,176 @@+package com.vayunmathur.cast.service++import android.os.Bundle+import android.os.Message+import android.os.ParcelFileDescriptor+import android.util.Log+import com.vayunmathur.cast.protocol.MediaResource+import com.vayunmathur.cast.protocol.MediaResourceResolver+import com.vayunmathur.sdk.cast.CastContract+import java.io.InputStream+import java.nio.ByteBuffer+import java.nio.channels.FileChannel+import java.util.concurrent.ArrayBlockingQueue+import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicInteger++private const val TAG = "ClientResources"++/**+ * How long the proxy waits for the app to hand over a descriptor.+ *+ * Generous for what it is - opening a MediaStore descriptor is one file open - but bounded, because+ * the caller is a thread serving an HTTP request. Waiting for ever there would turn an app that has+ * stopped answering into a TV sitting on a dead connection, which is the failure the old path was+ * full of.+ */+private const val REQUEST_TIMEOUT_MS = 5_000L++/**+ * Gets the bytes for the media proxy from the app being cast.+ *+ * The proxy needs a resource on demand, from an HTTP serving thread; the app answers over a+ * `Messenger`, asynchronously, on its own main looper. This is the join between the two: a blocking+ * [resolve] on one side, a request/response pair correlated by id on the other.+ *+ * Descriptors are cached per resource for the life of the session. One per resource rather than one+ * per range request is the whole reason a descriptor works here at all - a range is served by+ * reading at an offset, so the same descriptor answers every range of the same file.+ */+class ClientResourceResolver(+    /** Sends a message to the bound client, returning false when there is no client left. */+    private val send: (Message) -> Boolean,+) : MediaResourceResolver {++    private val nextRequestId = AtomicInteger(1)+    private val waiting = ConcurrentHashMap<Int, ArrayBlockingQueue<Answer>>()+    private val cache = ConcurrentHashMap<String, DescriptorResource>()++    /** Wrapped rather than nullable so that "the app said no" is distinguishable from a timeout. */+    private class Answer(val resource: DescriptorResource?)++    override fun resolve(resourceId: String): MediaResource? {+        cache[resourceId]?.let { return it }++        val requestId = nextRequestId.getAndIncrement()+        val mailbox = ArrayBlockingQueue<Answer>(1)+        waiting[requestId] = mailbox+        try {+            val request = Message.obtain(null, CastContract.MSG_RESOURCE_REQUEST).apply {+                data = Bundle().apply {+                    putInt(CastContract.KEY_REQUEST_ID, requestId)+                    putString(CastContract.KEY_RESOURCE_ID, resourceId)+                }+            }+            if (!send(request)) {+                Log.w(TAG, "no client to ask for '$resourceId'")+                return null+            }+            val answer = mailbox.poll(REQUEST_TIMEOUT_MS, TimeUnit.MILLISECONDS)+            if (answer == null) {+                Log.w(TAG, "the app did not answer for '$resourceId' within ${REQUEST_TIMEOUT_MS}ms")+                return null+            }+            val resource = answer.resource ?: return null++            // Two ranges of the same resource can be asked for at once - the TV fetches audio and+            // video independently - so the loser of that race closes its descriptor and uses the+            // winner's, rather than leaving two open on the same file.+            val existing = cache.putIfAbsent(resourceId, resource)+            return if (existing != null) {+                resource.close()+                existing+            } else {+                resource+            }+        } catch (_: InterruptedException) {+            Thread.currentThread().interrupt()+            return null+        } finally {+            waiting.remove(requestId)+        }+    }++    /** Hands a `MSG_RESOURCE_RESPONSE` to whichever [resolve] is waiting for it. */+    fun onResponse(data: Bundle?) {+        val requestId = data?.getInt(CastContract.KEY_REQUEST_ID) ?: return+        @Suppress("DEPRECATION")+        val descriptor = data.getParcelable(CastContract.KEY_RESOURCE_FD) as? ParcelFileDescriptor++        val mailbox = waiting[requestId]+        if (mailbox == null) {+            // Already timed out or the session ended. The descriptor was duplicated into this+            // process by the Binder transaction, so dropping it silently would leak a file+            // descriptor per late answer.+            runCatching { descriptor?.close() }+            return+        }++        val resource = descriptor?.let {+            DescriptorResource(+                descriptor = it,+                length = data.getLong(CastContract.KEY_RESOURCE_LENGTH),+                contentType = data.getString(CastContract.KEY_RESOURCE_TYPE)+                    ?: "application/octet-stream",+            )+        }+        if (!mailbox.offer(Answer(resource))) resource?.close()+    }++    /** Closes every descriptor the app handed over. Called when the session ends. */+    fun close() {+        cache.values.forEach { it.close() }+        cache.clear()+        waiting.clear()+    }++    /**+     * One of the app's files, read at offsets.+     *+     * Reads are positional rather than seek-then-read. A descriptor duplicated across Binder shares+     * its file offset with the app's original, so moving the offset would move the app's too, and+     * two ranges being served at once would each read from where the other left off.+     * [FileChannel.read] with an explicit position touches neither.+     */+    private class DescriptorResource(+        descriptor: ParcelFileDescriptor,+        override val length: Long,+        override val contentType: String,+    ) : MediaResource {++        private val stream = ParcelFileDescriptor.AutoCloseInputStream(descriptor)+        private val channel: FileChannel = stream.channel++        override fun open(offset: Long): InputStream = PositionalStream(channel, offset)++        fun close() {+            // Closes the descriptor with it, which is the point of AutoCloseInputStream.+            runCatching { stream.close() }+        }+    }++    private class PositionalStream(+        private val channel: FileChannel,+        private var position: Long,+    ) : InputStream() {++        override fun read(): Int {+            val one = ByteArray(1)+            return if (read(one, 0, 1) == 1) one[0].toInt() and 0xff else -1+        }++        override fun read(b: ByteArray, off: Int, len: Int): Int {+            if (len == 0) return 0+            val read = channel.read(ByteBuffer.wrap(b, off, len), position)+            if (read > 0) position += read+            return read+        }++        /**+         * Deliberately not closing the channel: it belongs to the resource and answers every range+         * of it, so closing it here would break the next request rather than this one.+         */+        override fun close() = Unit+    }+}
cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt b/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.ktindex 6e0fde31f4..7ce0c1bf59 100644--- a/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt+++ b/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt@@ -54,6 +54,15 @@ class ContentCastService : Service() {     /** True between a successful open and the session ending, so nothing is reported twice. */     private var sessionOpen = false +    /**+     * Where the media proxy gets its bytes.+     *+     * Held here rather than by `CastController` because the app is only reachable through this+     * binding, and the binding is the session's lifetime. The proxy is handed this when a content+     * session starts.+     */+    val resources = ClientResourceResolver { send(it) }+     private val incoming = Messenger(         Handler(Looper.getMainLooper()) { msg ->             when (msg.what) {@@ -73,6 +82,10 @@ class ContentCastService : Service() {                     }                     true                 }+                CastContract.MSG_RESOURCE_RESPONSE -> {+                    resources.onResponse(msg.data)+                    true+                }                 else -> false             }         },@@ -169,6 +182,8 @@ class ContentCastService : Service() {         sessionOpen = false         CastController.onContentSessionEnded = null         CastController.onPlaybackCommand = null+        // The app's descriptors are ours until the session ends, and nothing else will close them.+        resources.close()         // Back to a paired-but-idle TV rather than a dropped session: the pairing is per device and         // worth keeping, and the user may well cast again straight away.         CastController.stopMirroring(this)
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.ktindex 4497798bf4..500c44de8c 100644--- a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastClient.kt@@ -15,6 +15,8 @@ import android.os.RemoteException import android.view.Surface import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withTimeout+import java.util.concurrent.ExecutorService+import java.util.concurrent.Executors import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException @@ -75,6 +77,23 @@ class CastClient(context: Context) {         val receiverName: String,     ) +    /**+     * A live content session: Cast is serving this app's own media to the TV.+     *+     * Nothing to draw into and nothing to write, because nothing is being encoded. The TV fetches+     * byte ranges of whatever the app named and decodes them itself, so the app's only remaining+     * job is to answer [CastResourceProvider] and to keep sending [reportPlaybackState].+     *+     * There is no granted geometry either: the TV plays the media at its own size, which is the+     * point - the frame is no longer being squeezed through an encoder this phone had to choose.+     */+    class ContentSession(+        /** For a "Playing on <name>" panel where the local player used to be. */+        val receiverName: String,+        /** False for an audio-only session, where the TV shows a now-playing screen. */+        val hasVideo: Boolean,+    )+     /**      * Called when Cast ends the session on its own - the TV went away, screen mirroring took the      * slot - with one of [CastContract]'s `REASON_` values. Not called for a [close].@@ -98,8 +117,8 @@ class CastClient(context: Context) {     /** Set once [MSG_SESSION_READY][CastContract.MSG_SESSION_READY] has been answered. */     private var open = false -    /** Non-null only while [openSession] is waiting, so a failure can be reported to it. */-    private var pending: ((Result<Session>) -> Unit)? = null+    /** Non-null only while an open is waiting, so a failure can be reported to it. */+    private var pending: ((Result<Bundle>) -> Unit)? = null      private val incoming = Messenger(         Handler(Looper.getMainLooper()) { msg ->@@ -120,6 +139,10 @@ class CastClient(context: Context) {                     if (open) PlaybackCommand.from(msg.data)?.let { onCommand?.invoke(it) }                     true                 }+                CastContract.MSG_RESOURCE_REQUEST -> {+                    onResourceRequest(msg.data)+                    true+                }                 else -> false             }         },@@ -143,6 +166,20 @@ class CastClient(context: Context) {     private var requestedWidth = 0     private var requestedHeight = 0     private var requestedAudio = false+    private var requestedVideo = true++    /** Set for a content session, and what makes a missing `Surface` expected rather than a failure. */+    private var resources: CastResourceProvider? = null++    /**+     * Serialises resource opens off the main thread.+     *+     * Opening a MediaStore descriptor is disk I/O, and the request arrives on a `Handler` bound to+     * the main looper. Answering there would put a file open on the main thread of every app that+     * casts. One thread rather than a pool because the calls are rare - once per resource per+     * session - and ordering them keeps a provider from needing to be thread-safe.+     */+    private var resourceExecutor: ExecutorService? = null      /**      * Whether Cast can serve a session, from the installed package's `versionCode` alone.@@ -171,14 +208,72 @@ class CastClient(context: Context) {      * @throws CastSessionFailedException Cast could not start the stream.      */     suspend fun openSession(width: Int, height: Int, wantAudio: Boolean): Session {+        requestedWidth = width+        requestedHeight = height+        requestedAudio = wantAudio+        requestedVideo = true+        resources = null+        val ready = awaitReady()+        @Suppress("DEPRECATION")+        val surface = ready.getParcelable(CastContract.KEY_SURFACE) as? Surface+            ?: throw CastSessionFailedException(CastContract.REASON_FAILED)+        @Suppress("DEPRECATION")+        val audio = ready.getParcelable(CastContract.KEY_AUDIO_FD) as? ParcelFileDescriptor+        return Session(+            surface = surface,+            audio = audio,+            width = ready.getInt(CastContract.KEY_GRANTED_WIDTH, requestedWidth),+            height = ready.getInt(CastContract.KEY_GRANTED_HEIGHT, requestedHeight),+            frameRate = ready.getInt(CastContract.KEY_GRANTED_FRAME_RATE, DEFAULT_FRAME_RATE),+            receiverName = ready.getString(CastContract.KEY_RECEIVER_NAME).orEmpty(),+        )+    }++    /**+     * Bind Cast and open a session it serves this app's own media into.+     *+     * Nothing is encoded on this phone: Cast asks [resources] for a descriptor per resource and the+     * TV fetches byte ranges of it. So there is no size to request and no `Surface` to draw into -+     * seeking becomes a byte offset, and the TV owns the clock.+     *+     * [video] false opens an audio-only session, which the `Surface` path could not express at all.+     * The TV negotiates no video codec and shows a now-playing screen; a TV with no audio decoder+     * refuses outright rather than playing silence.+     *+     * Throws exactly what [openSession] throws.+     */+    suspend fun openContentSession(+        resources: CastResourceProvider,+        video: Boolean = true,+        wantAudio: Boolean = true,+    ): ContentSession {+        requestedWidth = 0+        requestedHeight = 0+        requestedAudio = wantAudio+        requestedVideo = video+        this.resources = resources+        resourceExecutor = Executors.newSingleThreadExecutor { runnable ->+            Thread(runnable, "cast-resources").apply { isDaemon = true }+        }+        val ready = awaitReady()+        return ContentSession(+            receiverName = ready.getString(CastContract.KEY_RECEIVER_NAME).orEmpty(),+            hasVideo = video,+        )+    }++    /**+     * Binds Cast and suspends until it answers `MSG_SESSION_READY`, or fails.+     *+     * Shared by both kinds of session because the binding, the timeout and every failure path are+     * identical; only what the caller makes of the answer differs.+     */+    private suspend fun awaitReady(): Bundle {         when (support()) {             Support.NOT_INSTALLED -> throw CastNotInstalledException()             Support.NEEDS_UPDATE -> throw CastNeedsUpdateException()             Support.READY -> {}         }-        requestedWidth = width-        requestedHeight = height-        requestedAudio = wantAudio         return withTimeout(OPEN_TIMEOUT_MS) {             suspendCancellableCoroutine { continuation ->                 pending = { result ->@@ -241,6 +336,11 @@ class CastClient(context: Context) {         onEnded = null         onCommand = null         pending = null+        resources = null+        // Shut down after clearing the provider so a request already in flight finds nothing to+        // open and answers with a 404 rather than handing out a descriptor nobody will read.+        resourceExecutor?.shutdown()+        resourceExecutor = null         if (open) {             try {                 service?.send(Message.obtain(null, CastContract.MSG_CLOSE_SESSION))@@ -268,6 +368,7 @@ class CastClient(context: Context) {                 putInt(CastContract.KEY_WIDTH, requestedWidth)                 putInt(CastContract.KEY_HEIGHT, requestedHeight)                 putBoolean(CastContract.KEY_WANT_AUDIO, requestedAudio)+                putBoolean(CastContract.KEY_WANT_VIDEO, requestedVideo)             }         }         try {@@ -277,28 +378,55 @@ class CastClient(context: Context) {         }     } +    /**+     * Answers Cast's request for the bytes behind a resource id.+     *+     * Always answers, even when there is no provider or the provider declines: Cast is holding a+     * request open for the TV, and a silent client turns into a stalled fetch rather than a `404`.+     *+     * Our copy of the descriptor is closed once sent. The Binder transaction duplicates it, so+     * keeping ours would leak one file descriptor per resource for the life of the session - and it+     * is the app's own descriptor, so the leak would be the app's.+     */+    private fun onResourceRequest(payload: Bundle?) {+        val requestId = payload?.getInt(CastContract.KEY_REQUEST_ID) ?: return+        val resourceId = payload.getString(CastContract.KEY_RESOURCE_ID) ?: return+        val provider = resources+        val executor = resourceExecutor ?: return+        executor.execute {+            val resource = provider?.let { runCatching { it.open(resourceId) }.getOrNull() }+            val reply = Message.obtain(null, CastContract.MSG_RESOURCE_RESPONSE).apply {+                data = Bundle().apply {+                    putInt(CastContract.KEY_REQUEST_ID, requestId)+                    if (resource != null) {+                        putParcelable(CastContract.KEY_RESOURCE_FD, resource.descriptor)+                        putLong(CastContract.KEY_RESOURCE_LENGTH, resource.length)+                        putString(CastContract.KEY_RESOURCE_TYPE, resource.contentType)+                    }+                }+            }+            try {+                service?.send(reply)+            } catch (_: RemoteException) {+                // Cast is gone; onServiceDisconnected reports it.+            }+            runCatching { resource?.descriptor?.close() }+        }+    }++    /**+     * Cast has a session. What is in the answer depends on which kind, so it is handed on whole.+     *+     * A content session has no `Surface` in it, so the check that one arrived belongs to+     * [openSession] rather than here.+     */     private fun onReady(data: Bundle?) {-        @Suppress("DEPRECATION")-        val surface = data?.getParcelable(CastContract.KEY_SURFACE) as? Surface-        if (surface == null) {+        if (data == null) {             finish(Result.failure(CastSessionFailedException(CastContract.REASON_FAILED)))             return         }-        @Suppress("DEPRECATION")-        val audio = data.getParcelable(CastContract.KEY_AUDIO_FD) as? ParcelFileDescriptor         open = true-        finish(-            Result.success(-                Session(-                    surface = surface,-                    audio = audio,-                    width = data.getInt(CastContract.KEY_GRANTED_WIDTH, requestedWidth),-                    height = data.getInt(CastContract.KEY_GRANTED_HEIGHT, requestedHeight),-                    frameRate = data.getInt(CastContract.KEY_GRANTED_FRAME_RATE, DEFAULT_FRAME_RATE),-                    receiverName = data.getString(CastContract.KEY_RECEIVER_NAME).orEmpty(),-                ),-            ),-        )+        finish(Result.success(data))     }      private fun onSessionEnded(reason: Int) {@@ -320,8 +448,8 @@ class CastClient(context: Context) {         onEnded?.invoke(reason)     } -    /** Hand one outcome to a waiting [openSession], unbinding first if it was a failure. */-    private fun finish(result: Result<Session>) {+    /** Hand one outcome to a waiting open, unbinding first if it was a failure. */+    private fun finish(result: Result<Bundle>) {         if (result.isFailure) {             // Nothing is going to arrive on this binding, and leaving it up would keep Cast alive.             if (bound) {
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.ktindex 0b6cc5b263..f75cbd63ec 100644--- a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastContract.kt@@ -25,6 +25,20 @@ package com.vayunmathur.sdk.cast  *       unbind, or MSG_CLOSE_SESSION      ─►  *                                    ◄──  MSG_SESSION_ENDED (reason)  * ```+ *+ * A **content session** replaces the middle of that. Instead of drawing into a `Surface`, the app+ * says what it wants played and then answers requests for the bytes:+ *+ * ```+ *       MSG_OPEN_SESSION                  ─►     (wantAudio, wantVideo = false for audio only)+ *                                    ◄──  MSG_SESSION_READY (no Surface)+ *                                    ◄──  MSG_RESOURCE_REQUEST (resourceId)+ *       MSG_RESOURCE_RESPONSE             ─►     (a seekable fd, length, MIME type)+ *       … Cast serves byte ranges of that fd to the TV, which decodes them itself …+ * ```+ *+ * Which is what lets an app cast with no encoder on the phone at all - and what lets an audio-only+ * app cast, which the `Surface` path could not do in any form.  */ object CastContract { @@ -93,6 +107,15 @@ object CastContract {      */     const val MSG_PLAYBACK_STATE = 5 +    /**+     * The bytes behind a [MSG_RESOURCE_REQUEST], as a seekable descriptor.+     *+     * Carries [KEY_REQUEST_ID] so the answer can be matched to the question - Cast may have more+     * than one outstanding, because the TV fetches audio, video and captions independently.+     * [KEY_RESOURCE_FD] absent means the app has no such resource, which the TV sees as a `404`.+     */+    const val MSG_RESOURCE_RESPONSE = 8+     // ---- service → client ----      /**@@ -114,6 +137,18 @@ object CastContract {      */     const val MSG_PLAYBACK_COMMAND = 6 +    /**+     * Cast needs the bytes behind [KEY_RESOURCE_ID], and expects a [MSG_RESOURCE_RESPONSE].+     *+     * Sent only for a content session, and only for ids the app itself named. Cast asks once per+     * resource per session and then serves byte ranges out of the descriptor, so this is not on+     * the hot path - it happens when a track changes or a caption track is switched to.+     *+     * A client that never answers stalls the TV's fetch until Cast times it out, which the TV sees+     * as a failed load rather than as a hang.+     */+    const val MSG_RESOURCE_REQUEST = 7+     // ---- MSG_OPEN_SESSION payload ----      /** Requested frame width in pixels. Clamped; read the granted size back, do not assume it. */@@ -123,6 +158,19 @@ object CastContract {     /** Whether the app intends to write PCM. False means video only and no pipe is created. */     const val KEY_WANT_AUDIO = "wantAudio" +    /**+     * Whether the session carries video at all. Absent means it does.+     *+     * False is how an audio-only app casts, and it is not a degradation of a video session: no+     * video codec is negotiated with the TV, no `Surface` comes back, and the TV shows a+     * now-playing screen rather than a black picture. Absent rather than required so that a client+     * written against the older contract keeps meaning what it meant.+     *+     * A TV with no audio decoder refuses an audio-only session outright, because silence with no+     * explanation is the worst available outcome.+     */+    const val KEY_WANT_VIDEO = "wantVideo"+     // ---- MSG_SESSION_READY payload ----      /**@@ -161,6 +209,39 @@ object CastContract {     /** The TV's name, for a "Playing on <TV>" panel where the video used to be. */     const val KEY_RECEIVER_NAME = "receiverName" +    // ---- MSG_RESOURCE_REQUEST / MSG_RESOURCE_RESPONSE payload ----++    /**+     * Which resource, in the app's own naming.+     *+     * Opaque to Cast beyond being a path segment: it is whatever the app used when it said what to+     * play. May contain slashes, so a segment can be addressed as `<itag>/<sequence>`.+     */+    const val KEY_RESOURCE_ID = "resourceId"++    /**+     * Matches a response to its request.+     *+     * Needed because more than one can be outstanding: the TV's player fetches audio, video and+     * captions independently, and answering them in a different order than they were asked is+     * normal rather than exceptional.+     */+    const val KEY_REQUEST_ID = "requestId"++    /**+     * A seekable read-only descriptor for the resource, or absent for "no such resource".+     *+     * Seekable is a requirement: Cast reads at offsets because the TV asks for byte ranges. A pipe+     * would make every seek a stall. Cast closes its copy when the session ends.+     */+    const val KEY_RESOURCE_FD = "resourceFd"++    /** The resource's total length in bytes, stated by the app rather than measured. */+    const val KEY_RESOURCE_LENGTH = "resourceLength"++    /** The resource's MIME type, which decides which extractor the TV's player reaches for. */+    const val KEY_RESOURCE_TYPE = "resourceType"+     // ---- MSG_SESSION_ENDED payload ----      /** One of the `REASON_` constants. */
sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastResource.kt
diff --git a/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastResource.kt b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastResource.ktnew file mode 100644index 0000000000..580d721f16--- /dev/null+++ b/sdk/cast/src/main/java/com/vayunmathur/sdk/cast/CastResource.kt@@ -0,0 +1,60 @@+package com.vayunmathur.sdk.cast++import android.os.ParcelFileDescriptor++/**+ * One thing this app can serve to the TV: a file descriptor and what is in it.+ *+ * Cast stopped re-encoding app content and became an origin server for it, so the TV fetches the+ * original bytes and decodes them itself. The bytes still belong to the app, though - `:music`+ * holds `READ_MEDIA_AUDIO` and the MediaStore URI, and YouPipe holds a download behind a token+ * Cast cannot mint - so the app hands over a descriptor and Cast puts it on the wire.+ *+ * A descriptor rather than bytes because the files already exist: copying a 4K video through a+ * `Bundle` would exceed Binder's transaction limit long before it finished, and copying it at all+ * would be pointless work.+ */+class CastResource(+    /**+     * A **seekable** descriptor, opened for reading.+     *+     * Seekable is the requirement, not a preference: the TV asks for byte ranges, so Cast reads at+     * offsets rather than from the start. A regular file works - `ParcelFileDescriptor.open`, or+     * `ContentResolver.openFileDescriptor` on a MediaStore URI. A pipe from+     * [ParcelFileDescriptor.createPipe] does not, and would turn every seek into a stall.+     *+     * Cast closes it when the session ends or the resource is replaced. The app should not.+     */+    val descriptor: ParcelFileDescriptor,+    /**+     * Total length in bytes.+     *+     * Stated by the app rather than measured, because a file still being written has a length its+     * author knows and `fstat` does not yet agree with. Cast reports it as the resource's length+     * and serves ranges against it.+     */+    val length: Long,+    /**+     * The MIME type, which decides what the TV's player does with it.+     *+     * `audio/ogg` for an Opus track, `video/mp4` for fragmented MP4, `text/vtt` for captions,+     * `image/jpeg` for artwork. Getting it wrong is not fatal - ExoPlayer sniffs - but it costs a+     * round trip and can pick the wrong extractor.+     */+    val contentType: String,+)++/**+ * Answers Cast's requests for the bytes behind a resource id.+ *+ * The ids are the app's own: whatever it put in the media it told Cast to play. Called on a+ * background thread, once per resource per session, and never for a resource the app did not+ * mention.+ *+ * Returning null means "no such resource", which the TV sees as a `404`. That is the right answer+ * for an id that has expired - a queue that has moved on, a caption track no longer offered - and+ * a better one than a descriptor to the wrong file.+ */+fun interface CastResourceProvider {+    fun open(resourceId: String): CastResource?+}
sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt
diff --git a/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt b/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.ktindex 45e8e926ec..99ca9dce2f 100644--- a/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt+++ b/sdk/cast/src/test/java/com/vayunmathur/sdk/cast/CastContractTest.kt@@ -42,6 +42,8 @@ class CastContractTest {             CastContract.MSG_SESSION_ENDED,             CastContract.MSG_PLAYBACK_STATE,             CastContract.MSG_PLAYBACK_COMMAND,+            CastContract.MSG_RESOURCE_REQUEST,+            CastContract.MSG_RESOURCE_RESPONSE,         )         assertEquals(codes.size, codes.toSet().size, "two Messenger `what` codes are the same")     }@@ -54,6 +56,7 @@ class CastContractTest {             CastContract.KEY_WIDTH,             CastContract.KEY_HEIGHT,             CastContract.KEY_WANT_AUDIO,+            CastContract.KEY_WANT_VIDEO,             CastContract.KEY_SURFACE,             CastContract.KEY_AUDIO_FD,             CastContract.KEY_GRANTED_WIDTH,@@ -71,6 +74,11 @@ class CastContractTest {             CastContract.KEY_HAS_PREVIOUS,             CastContract.KEY_ACTION,             CastContract.KEY_ACTION_VALUE,+            CastContract.KEY_RESOURCE_ID,+            CastContract.KEY_REQUEST_ID,+            CastContract.KEY_RESOURCE_FD,+            CastContract.KEY_RESOURCE_LENGTH,+            CastContract.KEY_RESOURCE_TYPE,         )         assertEquals(keys.size, keys.toSet().size, "two Bundle keys are the same string")         assertFalse(keys.any { it.isBlank() })