cast: wire the served content session end to end
- Commit
990d5fff4c5d9960f6992b90ddb7e70c742c3730- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-23 18:29 UTC (3 months ago)
- Parents
6e24c09
Diff
cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.kt b/cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.ktindex 63efdda1bf..64db2743b4 100644--- a/cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.kt+++ b/cast/src/main/java/com/vayunmathur/cast/network/ControlSocket.kt@@ -42,6 +42,16 @@ class ControlSocket(private val host: String, private val port: Int) { val codec = ControlCodec() + /**+ * Our own address on the interface that reaches the TV.+ *+ * The media proxy has to tell the TV where to fetch from, and a phone can have several+ * addresses - Wi-Fi, a VPN, a tethering bridge. This is the one the kernel actually chose to+ * reach this TV, so it is the only one guaranteed to be reachable back.+ */+ val localAddress: java.net.InetAddress?+ get() = socket?.localAddress+ /** Throws when the TV is not reachable, which the caller turns into a user-facing message. */ fun connect() { val plain = Socket()
cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.ktindex 5d3fa9ea1c..395ea7cbe8 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -24,7 +24,9 @@ import com.vayunmathur.cast.protocol.ByeReason import com.vayunmathur.cast.protocol.CodecNegotiation import com.vayunmathur.cast.protocol.CodecSelection import com.vayunmathur.cast.protocol.DecoderLimits+import com.vayunmathur.cast.protocol.MediaResourceResolver import com.vayunmathur.cast.protocol.PROTOCOL_VERSION+import com.vayunmathur.cast.protocol.PlayMedia import com.vayunmathur.cast.protocol.PlaybackCommand import com.vayunmathur.cast.protocol.PlaybackState import com.vayunmathur.cast.protocol.StreamConstants@@ -71,6 +73,18 @@ sealed interface ContentSessionResult { /** [reason] is one of `CastContract`'s `REASON_` values, ready to send straight back. */ class Failed(val reason: Int) : ContentSessionResult++ /**+ * Live, and served rather than encoded.+ *+ * No surface and no pipe, because nothing is being encoded: the TV fetches byte ranges of the+ * app's own media from the proxy and decodes them itself. No geometry either - the TV plays the+ * media at its own size, which is what stops this phone having to choose a frame it can encode.+ */+ class Serving(+ val receiverName: String,+ val hasVideo: Boolean,+ ) : ContentSessionResult } /**@@ -119,6 +133,15 @@ object CastController { /** The running mirror. Its retransmit buffers live per-stream inside it. */ private var engine: MirrorEngine? = null + /**+ * The HTTPS listener serving a content session, or null when there is not one.+ *+ * Beside [engine] rather than inside it, because the two are alternatives: a served session+ * starts no encoder at all. Torn down through the same paths, so a session that ends leaves no+ * open port behind.+ */+ private var proxy: MediaProxyServer? = null+ /** * The codec the running engine is encoding with. *@@ -466,6 +489,8 @@ object CastController { height: Int, wantAudio: Boolean, appLabel: String,+ wantVideo: Boolean = true,+ resources: MediaResourceResolver? = null, ): ContentSessionResult = withContext(Dispatchers.IO) { val appContext = context.applicationContext val activeClient = client@@ -483,6 +508,17 @@ object CastController { _degradation.value = MirrorDegradation() _failure.value = null + if (resources != null) {+ return@withContext startServedSession(+ context = appContext,+ device = device,+ activeClient = activeClient,+ resources = resources,+ wantVideo = wantVideo,+ appLabel = appLabel,+ )+ }+ val codec = when (val choice = chooseCodec(appContext, device, activeClient, width, height)) { is CodecOutcome.Refused -> { Log.w(TAG, "refusing an app-content session: ${choice.message}")@@ -565,11 +601,93 @@ object CastController { * to control, so it is not merely that the overlay should not appear on the TV - there is nothing * a command could be applied to on this end either. */+ /**+ * Start serving app content instead of encoding it.+ *+ * This is the whole architectural change on this end. The proxy binds an ephemeral HTTPS port,+ * the fingerprint of its throwaway certificate goes to the TV over the already-encrypted control+ * channel, and the TV fetches byte ranges from it. No encoder is created, no codec is negotiated+ * and no geometry is chosen: the file is already encoded, and the TV can decode it.+ *+ * The audio decoder *is* checked, before anything is started. A TV with no Opus decoder used to+ * accept an audio-only session and then play silence with nothing to explain it, and that is the+ * one refusal worth making early.+ */+ private suspend fun startServedSession(+ context: Context,+ device: CastDevice,+ activeClient: MirrorClient,+ resources: MediaResourceResolver,+ wantVideo: Boolean,+ appLabel: String,+ ): ContentSessionResult {+ val limits = activeClient.limits ?: DecoderLimits()+ if (!CodecNegotiation.canPlayAudio(limits)) {+ Log.w(TAG, "refusing a served session: '${device.friendlyName}' advertised no Opus decoder")+ _failure.value = context.getString(R.string.cast_mirror_tv_no_audio)+ _mirrorPhase.value = MirrorPhase.Failed+ return ContentSessionResult.Failed(CastContract.REASON_FAILED)+ }++ // The address the kernel chose to reach this TV, not whichever interface happens to be first:+ // a phone can be on Wi-Fi, a VPN and a tethering bridge at once, and only one of those is+ // reachable back from the television.+ val host = socket?.localAddress+ if (host == null || host.hostAddress == null) {+ Log.w(TAG, "no local address on the control channel; nothing could be served")+ _mirrorPhase.value = MirrorPhase.Failed+ return ContentSessionResult.Failed(CastContract.REASON_FAILED)+ }++ val token = MediaProxyServer.randomToken()+ val server = MediaProxyServer(token, resources)+ val endpoint = server.start(listOf(host))+ if (endpoint == null) {+ _mirrorPhase.value = MirrorPhase.Failed+ return ContentSessionResult.Failed(CastContract.REASON_FAILED)+ }+ proxy = server++ val outcome = mutex.withLock {+ activeClient.openContentSession(+ host = host.hostAddress!!,+ port = endpoint.port,+ certificateFingerprint = endpoint.certificateFingerprint,+ token = token,+ video = wantVideo,+ appLabel = appLabel,+ )+ }+ if (outcome is ContentOutcome.Refused) {+ // Nothing is going to fetch from it, and an open port outlives the session that needed it.+ server.stop()+ proxy = null+ _failure.value = outcome.detail.ifBlank { context.getString(R.string.cast_mirror_tv_no_audio) }+ _mirrorPhase.value = MirrorPhase.Failed+ return ContentSessionResult.Failed(CastContract.REASON_FAILED)+ }++ _mirrorPhase.value = MirrorPhase.Mirroring+ _sessionState.update { it.copy(phase = ClientPhase.Streaming) }+ startWatch(context, activeClient, device, codec = null, transportControls = true)+ return ContentSessionResult.Serving(+ receiverName = activeClient.receiverName ?: device.friendlyName,+ hasVideo = wantVideo,+ )+ }++ /** Tell the TV to play a resource the app will be asked for. */+ fun playMedia(media: PlayMedia) {+ val activeClient = client ?: return+ scope.launch { mutex.withLock { activeClient.playMedia(media) } }+ }+ private fun startWatch( appContext: Context, activeClient: MirrorClient, device: CastDevice,- codec: VideoCodec,+ /** Null for a served session, where nothing was encoded and there is no codec to demote. */+ codec: VideoCodec?, transportControls: Boolean = false, ) { watchJob = scope.launch {@@ -598,7 +716,7 @@ object CastController { teardown() // Published *after* the teardown, which resets the phase and clears the failure - the // order matters, and setting either first would only have it wiped.- val message = if (reason == ByeReason.MISSING_CODEC_CONFIG) {+ val message = if (reason == ByeReason.MISSING_CODEC_CONFIG && codec != null) { Log.w(TAG, "'${device.friendlyName}' never got ${codec.label}'s codec config") MirrorPreferences.demoteCodec(appContext, receiverId, codec) appContext.getString(R.string.cast_mirror_codec_config_failed)@@ -789,6 +907,10 @@ object CastController { engine?.stop() engine = null activeCodec = null+ // The served session's other half. An open HTTPS port outliving the session it belonged to+ // would serve a token that is no longer anybody's.+ proxy?.stop()+ proxy = null } /**
cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.ktindex 4e5ad3e27a..2e39dcb4cd 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt@@ -6,6 +6,8 @@ import com.vayunmathur.cast.domain.ClientFailure import com.vayunmathur.cast.network.ControlSocket import com.vayunmathur.cast.protocol.Bye import com.vayunmathur.cast.protocol.ByeReason+import com.vayunmathur.cast.protocol.ContentReady+import com.vayunmathur.cast.protocol.ContentSession import com.vayunmathur.cast.protocol.DecoderLimits import com.vayunmathur.cast.protocol.Hello import com.vayunmathur.cast.protocol.Negotiation@@ -15,6 +17,7 @@ import com.vayunmathur.cast.protocol.PairFailed import com.vayunmathur.cast.protocol.PairOk import com.vayunmathur.cast.protocol.PairProof import com.vayunmathur.cast.protocol.PairRequired+import com.vayunmathur.cast.protocol.PlayMedia import com.vayunmathur.cast.protocol.PlaybackCommand import com.vayunmathur.cast.protocol.PlaybackState import com.vayunmathur.cast.protocol.ProtocolBase64@@ -32,6 +35,21 @@ import java.security.SecureRandom private const val TAG = "MirrorClient" +/** Whether the TV took a content session, and why not if it did not. */+sealed interface ContentOutcome {++ data object Accepted : ContentOutcome++ /**+ * [detail] is the TV's own words, so the phone can say something true rather than "failed".+ *+ * The refusal that matters is a TV with no Opus decoder on an audio-only session: before it was+ * negotiated, that TV accepted the session and played silence, which is the failure this whole+ * reply exists to make visible.+ */+ data class Refused(val detail: String) : ContentOutcome+}+ /** What a handshake step produced, or why it stopped. */ sealed interface HandshakeOutcome { @@ -253,6 +271,58 @@ class MirrorClient( return HandshakeOutcome.Ready(Negotiation.of(config, ready, sessionKeys)) } + /**+ * `CONTENT_SESSION` → `CONTENT_READY`, for app content that has a file behind it.+ *+ * The replacement for [configureStream] on that path, and there is no `STREAM_READY` and no UDP+ * port because there is no RTP: the TV fetches byte ranges from the proxy instead. Nothing here+ * negotiates a codec, because nothing is being encoded - the TV decodes whatever the file already+ * is, which is the entire point.+ *+ * [certificateFingerprint] travels on this channel precisely because it is already encrypted and+ * bound to the pairing transcript. That is what lets the TV pin one certificate instead of+ * trusting an authority to vouch for an address on a LAN.+ */+ fun openContentSession(+ host: String,+ port: Int,+ certificateFingerprint: ByteArray,+ token: String,+ video: Boolean,+ appLabel: String,+ ): ContentOutcome {+ socket.send(+ ContentSession(+ host = host,+ port = port,+ certificateFingerprint = ProtocolBase64.encode(certificateFingerprint),+ token = token,+ video = video,+ appLabel = appLabel,+ ),+ )+ val ready = socket.receive()?.message as? ContentReady+ ?: return ContentOutcome.Refused("the TV did not answer")+ if (!ready.accepted) {+ Log.w(TAG, "the TV refused a content session: ${ready.detail}")+ return ContentOutcome.Refused(ready.detail)+ }+ Log.i(TAG, "serving ${if (video) "audio and video" else "audio"} from $host:$port")+ return ContentOutcome.Accepted+ }++ /**+ * Tell the TV what to play next from the proxy.+ *+ * Sent once per item rather than as a playlist, because the queue stays on the phone: it owns the+ * ordering, the artwork and the metadata, so "next" is a decision this end makes and then reports.+ */+ fun playMedia(media: PlayMedia) {+ Log.i(TAG, "asking the TV to play ${media.resourceId}")+ runCatching { socket.send(media) }+ .onFailure { Log.w(TAG, "could not send the play request", it) }+ }+ /** * Hand the TV the video codec configuration, for a codec that cannot carry it in-band. *
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 7ce0c1bf59..ee53d36d60 100644--- a/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt+++ b/cast/src/main/java/com/vayunmathur/cast/service/ContentCastService.kt@@ -121,6 +121,10 @@ class ContentCastService : Service() { val width = data?.getInt(CastContract.KEY_WIDTH) ?: 0 val height = data?.getInt(CastContract.KEY_HEIGHT) ?: 0 val wantAudio = data?.getBoolean(CastContract.KEY_WANT_AUDIO) ?: false+ // Absent means video, so a client written against the older contract still means what it did.+ val wantVideo = data?.getBoolean(CastContract.KEY_WANT_VIDEO, true) ?: true+ // A client that will answer resource requests is asking to be served rather than encoded.+ val served = data?.getBoolean(CastContract.KEY_SERVE_RESOURCES) == true scope.launch { val result = CastController.startContentSession(@@ -130,6 +134,8 @@ class ContentCastService : Service() { wantAudio = wantAudio, // Established by the picker from callingPackage, not by anything the client sent. appLabel = CastController.contentAppLabel,+ wantVideo = wantVideo,+ resources = if (served) resources else null, ) when (result) { is ContentSessionResult.Failed -> send(sessionEnded(result.reason))@@ -147,8 +153,34 @@ class ContentCastService : Service() { } sendReady(result) }+ is ContentSessionResult.Serving -> {+ sessionOpen = true+ CastController.onContentSessionEnded = { reason ->+ scope.launch { closeSession(reason, notify = true) }+ }+ CastController.onPlaybackCommand = { command ->+ scope.launch { send(playbackCommand(command)) }+ }+ sendServing(result)+ }+ }+ }+ }++ /**+ * Answer a served session: a name, and no surface.+ *+ * The absence of `KEY_SURFACE` is the signal, and it is why `CastClient.openContentSession` does+ * not look for one - there is nothing to draw into because nothing is being encoded.+ */+ private fun sendServing(serving: ContentSessionResult.Serving) {+ val message = Message.obtain(null, CastContract.MSG_SESSION_READY).apply {+ data = Bundle().apply {+ putString(CastContract.KEY_RECEIVER_NAME, serving.receiverName)+ putBoolean(CastContract.KEY_WANT_VIDEO, serving.hasVideo) } }+ if (!send(message)) closeSession(CastContract.REASON_CLIENT_CLOSED, notify = false) } /**
cast/src/main/res/values/strings.xml
diff --git a/cast/src/main/res/values/strings.xml b/cast/src/main/res/values/strings.xmlindex 6948ce7586..a5f28ed2bd 100644--- a/cast/src/main/res/values/strings.xml+++ b/cast/src/main/res/values/strings.xml@@ -49,6 +49,7 @@ <string name="cast_mirror_negotiation_failed">The TV refused to start a stream</string> <string name="cast_mirror_udp_failed">Could not reach the TV to send video</string> <string name="cast_mirror_no_encoder">This device has no usable screen encoder</string>+ <string name="cast_mirror_tv_no_audio">This TV cannot play Opus audio, so it cannot play music from this phone</string> <string name="cast_mirror_receiver_gone">The TV stopped accepting the stream</string> <!-- Naming the codecs is the point of these three. Mirroring needs hardware H.265 or AV1 and has no H.264 fallback, so a device that cannot do either will never work - and a message that did
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.ktindex bfe9ffae18..85a6ce2954 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/MirrorActivity.kt@@ -99,16 +99,23 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) surfaceView = SurfaceView(this).apply { holder.addCallback(this@MirrorActivity) }+ // An audio-only session has nothing to draw. The surface is not merely hidden but never+ // added: an unattached SurfaceView creates no surface, so `surfaceCreated` never fires and+ // the receiver is never handed somewhere to draw. A full-screen black rectangle over silence+ // would read as a fault rather than as music.+ val hasVideo = (ReceiverController.state.value.phase as? ReceiverPhase.Mirroring)?.hasVideo != false container = FrameLayout(this).apply { setBackgroundColor(android.graphics.Color.BLACK)- addView(- surfaceView,- FrameLayout.LayoutParams(- ViewGroup.LayoutParams.MATCH_PARENT,- ViewGroup.LayoutParams.MATCH_PARENT,- android.view.Gravity.CENTER,- ),- )+ if (hasVideo) {+ addView(+ surfaceView,+ FrameLayout.LayoutParams(+ ViewGroup.LayoutParams.MATCH_PARENT,+ ViewGroup.LayoutParams.MATCH_PARENT,+ android.view.Gravity.CENTER,+ ),+ )+ } addView(overlayView(), FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)) } setContentView(container)
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.ktindex 0e847d77a1..326d872a0b 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverController.kt@@ -6,6 +6,8 @@ import android.util.Log import android.view.Surface import com.vayunmathur.cast.protocol.Bye import com.vayunmathur.cast.protocol.ByeReason+import com.vayunmathur.cast.protocol.ContentReady+import com.vayunmathur.cast.protocol.ContentSession import com.vayunmathur.cast.protocol.DecodableFrame import com.vayunmathur.cast.protocol.DecoderLimits import com.vayunmathur.cast.protocol.Hello@@ -18,6 +20,7 @@ import com.vayunmathur.cast.protocol.PairProof import com.vayunmathur.cast.protocol.PairRequired import com.vayunmathur.cast.protocol.PairResult import com.vayunmathur.cast.protocol.PairingGate+import com.vayunmathur.cast.protocol.PlayMedia import com.vayunmathur.cast.protocol.PlaybackAction import com.vayunmathur.cast.protocol.PlaybackCommand import com.vayunmathur.cast.protocol.PlaybackState@@ -44,7 +47,9 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch+import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withContext import java.net.DatagramSocket import java.net.ServerSocket import java.security.SecureRandom@@ -124,6 +129,16 @@ object ReceiverController { @Volatile private var surface: Surface? = null + /**+ * The player for a served content session, or null when there is not one.+ *+ * Volatile because the Activity's surface callbacks read it while the session coroutine writes+ * it. Its own field rather than a branch inside the media loop: a served session has no RTP, no+ * decoder and no playout queue, so there is nothing for that loop to do.+ */+ @Volatile+ private var contentPlayer: ContentPlayer? = null+ /** The frame size the phone said it would send, so the Activity can letterbox to it. */ @Volatile var frameWidth: Int = 0@@ -239,6 +254,9 @@ object ReceiverController { /** Called by `MirrorActivity` once its `SurfaceView` has a surface to draw into. */ fun attachSurface(newSurface: Surface) { surface = newSurface+ // A served session hands the surface straight to its player. Nothing is being decoded here,+ // so there is no media loop to notice one appearing.+ contentPlayer?.setSurface(newSurface) } /**@@ -249,6 +267,9 @@ object ReceiverController { * call in flight. */ fun detachSurface() {+ // Taken off the player first: handing a released surface to ExoPlayer is what breaks the+ // *next* session rather than this one.+ contentPlayer?.setSurface(null) surface = null } @@ -313,7 +334,7 @@ object ReceiverController { [email protected] = channel sessionJob = scope.launch { try {- runSession(channel, store, identity, deviceId, name, limits)+ runSession(context, channel, store, identity, deviceId, name, limits) } catch (e: Exception) { Log.w(TAG, "session ended", e) } finally {@@ -343,6 +364,7 @@ object ReceiverController { // ---- one session ---- private suspend fun runSession(+ context: Context, channel: ControlChannel, store: PairingStore, identity: PqcIdentity,@@ -396,7 +418,17 @@ object ReceiverController { _state.update { it.copy(phase = ReceiverPhase.Connected(greeting.senderName)) } val configured = channel.receive() ?: return- val config = configured.message as? StreamConfig ?: return+ // The fork between the two kinds of session. Screen mirroring has no file behind it and keeps+ // the RTP path; anything with a file is served over HTTPS and decoded here, which is why+ // seeking becomes an offset and a pause is nobody's business but this end's.+ val config = when (val first = configured.message) {+ is StreamConfig -> first+ is ContentSession -> {+ serveContent(context, channel, first, greeting.senderName)+ return+ }+ else -> return+ } startStreaming(channel, keys, config, greeting.senderName) // The session now lives in the UDP loop; this coroutine stays here so a BYE or a dropped@@ -418,6 +450,84 @@ object ReceiverController { } } + /**+ * Serve a content session: the phone has the bytes, this end has the player.+ *+ * The whole of the new arrangement on this side. Nothing is decoded from RTP, nothing waits for a+ * key frame, and there is no picture-loss indicator to send because there are no lost pictures.+ * What is left is a URL, a pinned certificate and a player that owns its own clock.+ *+ * ExoPlayer must be built and driven from the thread whose looper it took, so every call into it+ * hops to the main thread. The control channel stays on this coroutine, because it is the same+ * blocking read it always was.+ */+ private suspend fun serveContent(+ context: Context,+ channel: ControlChannel,+ session: ContentSession,+ senderName: String,+ ) {+ if (!session.video && AudioPlayer.limits().isEmpty()) {+ // The failure that used to be silence. A TV with no Opus decoder and no picture to fall+ // back on has to say so, and the phone has to be told rather than left streaming into it.+ Log.w(TAG, "refusing an audio-only session: this TV has no Opus decoder")+ channel.send(ContentReady(accepted = false, detail = "this TV has no Opus decoder"))+ _state.update { it.copy(phase = ReceiverPhase.Failed(ReceiverFailure.NoAudioDecoder)) }+ return+ }++ val player = withContext(Dispatchers.Main) { ContentPlayer(context, session) }+ val started = withContext(Dispatchers.Main) {+ player.start { detail -> Log.w(TAG, "the served stream failed: $detail") }+ }+ if (!started) {+ channel.send(ContentReady(accepted = false, detail = "the player could not be built"))+ _state.update { it.copy(phase = ReceiverPhase.Failed(ReceiverFailure.Handshake)) }+ withContext(NonCancellable + Dispatchers.Main) { player.release() }+ return+ }++ contentPlayer = player+ // A surface may already exist from a previous session's Activity; an audio-only session wants+ // none, and handing it one would put a black rectangle over the now-playing screen.+ if (session.video) surface?.let { withContext(Dispatchers.Main) { player.setSurface(it) } }+ channel.send(ContentReady(accepted = true))+ _state.update {+ it.copy(+ phase = ReceiverPhase.Mirroring(+ senderName = senderName,+ // No frame size to letterbox to: the TV plays the media at its own size, which is+ // the point of not squeezing it through an encoder first.+ width = 0,+ height = 0,+ appLabel = session.appLabel,+ hasVideo = session.video,+ ),+ )+ }+ Log.i(TAG, "serving content from ${session.host}:${session.port} for '${session.appLabel}'")++ try {+ while (true) {+ val next = channel.receive() ?: break+ when (val message = next.message) {+ is Bye -> {+ Log.i(TAG, "'$senderName' said goodbye")+ return+ }+ is PlayMedia -> withContext(Dispatchers.Main) { player.play(message) }+ is PlaybackState -> onPlaybackState(message)+ else -> Unit+ }+ }+ } finally {+ contentPlayer = null+ // NonCancellable because this is the teardown path a cancelled session takes, and an+ // ExoPlayer left unreleased holds a codec the next session will ask for.+ withContext(NonCancellable + Dispatchers.Main) { player.release() }+ }+ }+ /** * Take a playback snapshot, and stamp it with the moment it arrived. *
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.ktindex a1a3e0626d..80c0e4b1c9 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ReceiverUiContract.kt@@ -41,6 +41,13 @@ sealed interface ReceiverPhase { * itself. */ val appLabel: String = "",+ /**+ * False for an audio-only session, where there is nothing to draw.+ *+ * `MirrorActivity` adds no `SurfaceView` at all in that case and fills the window with a+ * now-playing screen instead - a black surface over silence would look like a fault.+ */+ val hasVideo: Boolean = true, ) : ReceiverPhase { /** * Who to name on screen: the app if there is one, otherwise the phone.
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 500c44de8c..9464e63db2 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@@ -369,6 +369,7 @@ class CastClient(context: Context) { putInt(CastContract.KEY_HEIGHT, requestedHeight) putBoolean(CastContract.KEY_WANT_AUDIO, requestedAudio) putBoolean(CastContract.KEY_WANT_VIDEO, requestedVideo)+ putBoolean(CastContract.KEY_SERVE_RESOURCES, resources != null) } } try {
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 f75cbd63ec..551cf2afe5 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@@ -171,6 +171,16 @@ object CastContract { */ const val KEY_WANT_VIDEO = "wantVideo" + /**+ * Whether the client will answer [MSG_RESOURCE_REQUEST], which is what asks to be served rather+ * than encoded.+ *+ * Its own flag rather than inferred from the other fields: a served session and a `Surface`+ * session differ in what Cast *does*, not in what was asked for, and guessing from a geometry of+ * zero would make a client that simply forgot to state a size get a session with no picture.+ */+ const val KEY_SERVE_RESOURCES = "serveResources"+ // ---- MSG_SESSION_READY payload ---- /**
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 99ca9dce2f..b4a39578a8 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@@ -57,6 +57,7 @@ class CastContractTest { CastContract.KEY_HEIGHT, CastContract.KEY_WANT_AUDIO, CastContract.KEY_WANT_VIDEO,+ CastContract.KEY_SERVE_RESOURCES, CastContract.KEY_SURFACE, CastContract.KEY_AUDIO_FD, CastContract.KEY_GRANTED_WIDTH,