cast-tv: transport controls on the TV remote
- Commit
5296145fbe6f072b603e3005bfd1282cf35ac536- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-23 07:11 UTC (3 months ago)
- Parents
5322797
Diff
cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ControlChannel.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ControlChannel.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ControlChannel.ktindex e7af273dd7..63ef09087c 100644--- a/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ControlChannel.kt+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/platform/ControlChannel.kt@@ -34,12 +34,19 @@ class ControlChannel(private val socket: Socket) { socket.soTimeout = READ_TIMEOUT_MS } - /** Returns the body bytes, for the transcript. */- fun send(message: ControlMessage): ByteArray {+ /**+ * Returns the body bytes, for the transcript.+ *+ * Synchronised because there are now three writers: the session coroutine, the media loop's `Bye`+ * path, and the UI thread whenever the remote is pressed. Two encodes interleaving would also+ * advance the cipher's nonce twice for one frame, which is not a corrupted message but an+ * undecryptable one.+ */+ fun send(message: ControlMessage): ByteArray = synchronized(output) { val body = codec.encode(message) output.write(ControlFraming.encode(body)) output.flush()- return body+ body } /**
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 91dfd183ed..6304cf1752 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@@ -2,15 +2,28 @@ package com.vayunmathur.cast.tv.platform import android.os.Bundle import android.util.Log+import android.view.KeyEvent import android.view.SurfaceHolder import android.view.SurfaceView import android.view.ViewGroup import android.widget.FrameLayout import androidx.activity.ComponentActivity+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.platform.ComposeView import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat import androidx.lifecycle.lifecycleScope+import com.vayunmathur.cast.protocol.PlaybackAction+import com.vayunmathur.cast.protocol.PlaybackCommand+import com.vayunmathur.cast.tv.ui.CastTvTheme+import com.vayunmathur.cast.tv.ui.TransportOverlay+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch @@ -19,15 +32,22 @@ private const val TAG = "MirrorActivity" /** * The picture: one full-screen `SurfaceView` the decoder writes straight into. *- * **Deliberately not Compose.** Nothing here is a composable - it is one surface handed to- * `MediaCodec` - and going through `AndroidView` would add a recomposition path between the decoder- * and the display for no benefit. It also means this Activity needs no theme work to be full-screen- * black.+ * **The surface is deliberately not Compose, and the overlay deliberately is.** The surface is one+ * handle given to `MediaCodec`; routing it through `AndroidView` would put a recomposition path+ * between the decoder and the display for no benefit. The transport controls have the opposite+ * requirement - they are state-driven and change constantly - so they are a *second child* of the same+ * `FrameLayout`, a `ComposeView` above the surface. The decoder's path is untouched by this; only the+ * overlay recomposes. * * **Letterboxing is done here, and that is the point.** The old sender scaled the phone's portrait * screen into a 1920x1080 frame and sent mostly black pixels, because a Cast receiver answers * `scaling: "sender"` and will not pad for you. Owning the receiver means the phone can send its own * aspect ratio at full resolution and the TV pads it - so none of the encoded frame is wasted.+ *+ * **This is also the app's whole input surface.** [dispatchKeyEvent] handles the remote directly rather+ * than moving a focus ring between buttons, because a media overlay's D-pad presses are gestures -+ * left seeks, up is volume - and there is nothing to focus. Keys are only claimed while a phone is+ * actually reporting playback, so screen mirroring keeps the ordinary behaviour of every key. */ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback { @@ -47,6 +67,21 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback { private var frameWidth = 0 private var frameHeight = 0 + /** Whether the controls are on screen. Any key press reveals them; a timer takes them away. */+ private var overlayVisible by mutableStateOf(false)++ /**+ * A scrub the user is still composing, in milliseconds, or -1 when none is in progress.+ *+ * **Accumulate here and commit on release.** Sending a seek per keypress would put a storm of them+ * on the control channel and into an ExoPlayer that is simultaneously feeding a hardware encoder;+ * holding a local preview and sending one `SeekTo` at the end is both kinder and what the user+ * means by holding the button down.+ */+ private var scrubPreviewMs by mutableLongStateOf(NO_SCRUB)++ private var hideJob: Job? = null+ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) surfaceView = SurfaceView(this).apply { holder.addCallback(this@MirrorActivity) }@@ -60,6 +95,7 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback { android.view.Gravity.CENTER, ), )+ addView(overlayView(), FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)) } setContentView(container) preferLargestDisplayMode()@@ -96,6 +132,139 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback { ReceiverController.detachSurface() } + /**+ * The controls, as a transparent layer above the picture.+ *+ * Composes to nothing at all until the phone reports playback, which is what keeps it off a+ * mirrored phone screen: screen mirroring has no transport, so it never sends a snapshot.+ */+ private fun overlayView(): ComposeView = ComposeView(this).apply {+ setContent {+ CastTvTheme {+ val state by ReceiverController.state.collectAsState()+ val playback = state.playback+ if (playback != null && overlayVisible) {+ TransportOverlay(+ snapshot = playback,+ sourceName = (state.phase as? ReceiverPhase.Mirroring)?.sourceName.orEmpty(),+ scrubPreviewMs = scrubPreviewMs.takeIf { it != NO_SCRUB },+ )+ }+ }+ }+ }++ /**+ * The remote, in full.+ *+ * Only claims a key while the phone is reporting playback - otherwise every one of these falls+ * through to the system, which is what a mirrored phone screen needs. `BACK` is the exception worth+ * pointing at: it dismisses the controls before it will leave the session, because a user who has+ * just brought up a seek bar and presses back means "put that away", not "stop watching".+ *+ * Left and right accumulate into [scrubPreviewMs] and commit on release; everything else is one+ * message per press. `ACTION_MULTIPLE` is not handled: a held D-pad repeats as `ACTION_DOWN`.+ */+ override fun dispatchKeyEvent(event: KeyEvent): Boolean {+ val playback = ReceiverController.state.value.playback+ ?: return super.dispatchKeyEvent(event)++ if (event.keyCode == KeyEvent.KEYCODE_BACK) {+ if (event.action == KeyEvent.ACTION_UP && overlayVisible) {+ hideOverlay()+ return true+ }+ return super.dispatchKeyEvent(event)+ }++ // Committing the scrub is the *release*, so it is handled before the reveal below - a release+ // must not be mistaken for a fresh press.+ if (event.action == KeyEvent.ACTION_UP && isScrubKey(event.keyCode)) {+ commitScrub()+ return true+ }+ if (event.action != KeyEvent.ACTION_DOWN) return super.dispatchKeyEvent(event)++ // Any press at all brings the controls up, and re-arms the timer that takes them away. The+ // press still does its own job: a user who reaches for pause should not have to press twice.+ revealOverlay()++ when (event.keyCode) {+ KeyEvent.KEYCODE_DPAD_CENTER,+ KeyEvent.KEYCODE_ENTER,+ KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,+ -> ReceiverController.send(PlaybackCommand(PlaybackAction.Toggle))++ KeyEvent.KEYCODE_MEDIA_PLAY -> ReceiverController.send(PlaybackCommand(PlaybackAction.Play))+ KeyEvent.KEYCODE_MEDIA_PAUSE -> ReceiverController.send(PlaybackCommand(PlaybackAction.Pause))++ KeyEvent.KEYCODE_DPAD_RIGHT -> scrubBy(SCRUB_STEP_MS, playback)+ KeyEvent.KEYCODE_DPAD_LEFT -> scrubBy(-SCRUB_STEP_MS, playback)++ // The remote's dedicated keys, where it has them. Distinct from a D-pad scrub: these are+ // a discrete "skip", so the phone's own interval applies rather than an accumulated one.+ KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> ReceiverController.skip(forward = true)+ KeyEvent.KEYCODE_MEDIA_REWIND -> ReceiverController.skip(forward = false)++ KeyEvent.KEYCODE_MEDIA_NEXT ->+ ReceiverController.send(PlaybackCommand(PlaybackAction.Next))+ KeyEvent.KEYCODE_MEDIA_PREVIOUS ->+ ReceiverController.send(PlaybackCommand(PlaybackAction.Previous))++ // Volume is left to the system for now: the level is shared with the phone, and wiring+ // only this end would have the two disagree the moment either was touched.+ else -> return super.dispatchKeyEvent(event)+ }+ return true+ }++ private fun isScrubKey(keyCode: Int): Boolean =+ keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT++ /**+ * Move the preview position, starting it from where playback actually is on the first press.+ *+ * Interpolated rather than taken from the last report, so a scrub begun mid-playback starts from+ * the frame on screen rather than from up to half a second behind it.+ */+ private fun scrubBy(deltaMs: Long, playback: PlaybackSnapshot) {+ val duration = playback.state.durationMs+ if (duration <= 0) return+ val from = scrubPreviewMs.takeIf { it != NO_SCRUB }+ ?: playback.positionAt(System.currentTimeMillis())+ scrubPreviewMs = (from + deltaMs).coerceIn(0, duration)+ }++ private fun commitScrub() {+ val target = scrubPreviewMs+ scrubPreviewMs = NO_SCRUB+ if (target == NO_SCRUB) return+ ReceiverController.send(+ PlaybackCommand(PlaybackAction.SeekTo, value = target.toDouble()),+ )+ // The preview is dropped here rather than held until the phone confirms: the next snapshot is+ // at most half a second away, and holding a stale preview would freeze the bar if the seek was+ // refused - which the phone does while its own slider is under a thumb.+ revealOverlay()+ }++ private fun revealOverlay() {+ overlayVisible = true+ hideJob?.cancel()+ hideJob = lifecycleScope.launch {+ delay(OVERLAY_AUTO_HIDE_MS)+ // A scrub in progress is an interaction, however long the user has been holding the key.+ if (scrubPreviewMs == NO_SCRUB) overlayVisible = false+ }+ }++ private fun hideOverlay() {+ hideJob?.cancel()+ hideJob = null+ scrubPreviewMs = NO_SCRUB+ overlayVisible = false+ }+ override fun surfaceCreated(holder: SurfaceHolder) { Log.i(TAG, "surface ready") ReceiverController.attachSurface(holder.surface)@@ -187,4 +356,22 @@ class MirrorActivity : ComponentActivity(), SurfaceHolder.Callback { "@ ${largest.refreshRate}Hz of ${modes.size} modes", ) }++ private companion object {+ const val MATCH_PARENT = ViewGroup.LayoutParams.MATCH_PARENT++ /** No scrub in progress. A sentinel rather than a nullable, so the Compose state is primitive. */+ const val NO_SCRUB = -1L++ /**+ * How far one D-pad press moves the preview.+ *+ * Smaller than a skip on purpose: this is a *scrub*, and the user is aiming. Holding the key+ * repeats it, so a long press still crosses a long video quickly.+ */+ const val SCRUB_STEP_MS = 5_000L++ /** Matches YouPipe's own `CONTROLS_AUTO_HIDE_DELAY_MS`, doubled for a remote's slower aim. */+ const val OVERLAY_AUTO_HIDE_MS = 4_000L+ } }
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 49980111ac..e07c65c2ee 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@@ -18,6 +18,9 @@ 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.PlaybackAction+import com.vayunmathur.cast.protocol.PlaybackCommand+import com.vayunmathur.cast.protocol.PlaybackState import com.vayunmathur.cast.protocol.ProtocolBase64 import com.vayunmathur.cast.protocol.SealedSecret import com.vayunmathur.cast.protocol.SecretSealing@@ -141,6 +144,34 @@ object ReceiverController { private val pairingGate = PairingGate() + /**+ * The live control channel, for sending back up it.+ *+ * The handshake reads and writes this channel from one coroutine, which is why it was never a+ * field before. A remote press is the first thing that originates on *this* end at an arbitrary+ * moment, so it needs a way in - [ControlChannel.send] is synchronised for the same reason.+ * Volatile because the UI thread reads it while the session coroutine writes it.+ */+ @Volatile+ private var channel: ControlChannel? = null++ /**+ * Ask the phone to do something. Dropped silently with no session, which is the honest answer:+ * the remote was pressed at a screen with nothing playing on it.+ */+ fun send(command: PlaybackCommand) {+ val live = channel ?: return+ scope.launch {+ runCatching { live.send(command) }+ .onFailure { Log.w(TAG, "could not send ${command.action}", it) }+ }+ }++ /** Skip forward or back by the phone's own interval, which is the phone's to decide. */+ fun skip(forward: Boolean) {+ send(PlaybackCommand(if (forward) PlaybackAction.SkipForward else PlaybackAction.SkipBack))+ }+ fun start(context: Context) { if (acceptJob != null) return val appContext = context.applicationContext@@ -158,7 +189,7 @@ object ReceiverController { advertiser = null runCatching { serverSocket?.close() } serverSocket = null- _state.update { it.copy(phase = ReceiverPhase.Starting) }+ _state.update { it.copy(phase = ReceiverPhase.Starting, playback = null) } } /** Called by `MirrorActivity` once its `SurfaceView` has a surface to draw into. */@@ -221,10 +252,16 @@ object ReceiverController { } val channel = ControlChannel(socket) // A failure from the previous session has been on screen long enough; the phone connecting- // now is what the user cares about.+ // now is what the user cares about. The previous session's playback goes with it, or the+ // next phone would inherit a seek bar describing something that is no longer playing. _state.update {- if (it.phase is ReceiverPhase.Failed) it.copy(phase = ReceiverPhase.Advertising) else it+ if (it.phase is ReceiverPhase.Failed) {+ it.copy(phase = ReceiverPhase.Advertising, playback = null)+ } else {+ it.copy(playback = null)+ } }+ [email protected] = channel sessionJob = scope.launch { try { runSession(channel, store, identity, deviceId, name, limits)@@ -232,6 +269,7 @@ object ReceiverController { Log.w(TAG, "session ended", e) } finally { channel.close()+ [email protected] = null endMedia() // A failure the user has to read is *not* overwritten with "ready" - it stays until // the next phone tries, which is when it stops being the useful thing to show.@@ -243,6 +281,9 @@ object ReceiverController { it.copy( phase = ReceiverPhase.Advertising, localNetworkBlocked = nsd.localNetworkBlocked,+ // The overlay is gated on this being non-null, so clearing it is+ // what takes the transport controls away with the session.+ playback = null, ) } }@@ -314,7 +355,8 @@ object ReceiverController { // The session now lives in the UDP loop; this coroutine stays here so a BYE or a dropped // socket tears everything down through the same path. It is also where the codec configuration // arrives, which for AV1 is what the media loop is waiting on before it can start a decoder at- // all - it is repeated on every key-frame request, so this handles it more than once.+ // all - it is repeated on every key-frame request, so this handles it more than once. And it is+ // where playback snapshots arrive, twice a second, for as long as an app is casting content. while (true) { val next = channel.receive() ?: break when (val message = next.message) {@@ -323,11 +365,33 @@ object ReceiverController { return } is VideoCodecConfig -> onVideoCodecConfig(message, config)+ is PlaybackState -> onPlaybackState(message) else -> Unit } } } + /**+ * Take a playback snapshot, and stamp it with the moment it arrived.+ *+ * The timestamp is taken here rather than in the UI because this is the closest thing to "when the+ * phone said so" that exists on this side - anything later would fold recomposition delay into the+ * seek bar's anchor.+ *+ * Not logged. Two of these a second would drown the once-a-second throughput line that everything+ * else about a session is diagnosed from.+ */+ private fun onPlaybackState(message: PlaybackState) {+ _state.update {+ it.copy(+ playback = PlaybackSnapshot(+ state = message,+ receivedAtMs = System.currentTimeMillis(),+ ),+ )+ }+ }+ /** * Take the codec configuration the phone sent, and say enough about it to diagnose it from a log. *
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 773ff0434f..01324c57ba 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@@ -1,5 +1,7 @@ package com.vayunmathur.cast.tv.platform +import com.vayunmathur.cast.protocol.PlaybackState+ /** Where the receiver is, from the point of view of a screen. */ sealed interface ReceiverPhase { @@ -90,4 +92,36 @@ data class ReceiverUiState( * the fix is a permission rather than opening the app on the phone. */ val localNetworkBlocked: Boolean = false,+ /**+ * The last thing the phone said about its playback, or null if it has never said anything.+ *+ * **Beside [phase] rather than inside [ReceiverPhase.Mirroring], deliberately.** A phase change+ * replaces the whole object, and playback outlives several of them - the display mode settling,+ * a surface being handed back after a resize. Nesting it would throw the seek bar's anchor away+ * every time something unrelated happened.+ *+ * Null is also the gate on the whole feature: screen mirroring never sends a snapshot, so an+ * overlay that only exists when this is non-null cannot appear over a mirrored phone screen.+ */+ val playback: PlaybackSnapshot? = null, )++/**+ * One playback snapshot, with the moment it landed.+ *+ * **The wall clock is the missing half of the message.** The phone reports twice a second and the+ * panel redraws sixty times a second, so a bar plotted at the reported position would step visibly.+ * What makes it smooth is knowing *when* the number was true, and the interpolation itself lives in+ * `:cast:protocol` beside the message - a pure function of a snapshot and an elapsed time, which is+ * the one part of this feature provable without a television.+ *+ * The TV never computes position authoritatively and cannot: what it holds is a 150 ms RTP jitter+ * buffer, which is a smoothing device and not a content clock. Every fresh snapshot re-anchors, so+ * error is bounded by one reporting interval rather than accumulating.+ */+data class PlaybackSnapshot(+ val state: PlaybackState,+ val receivedAtMs: Long,+) {+ fun positionAt(nowMs: Long): Long = state.interpolated(nowMs - receivedAtMs)+}
cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/TransportOverlay.kt
diff --git a/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/TransportOverlay.kt b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/TransportOverlay.ktnew file mode 100644index 0000000000..ba2ca2cd61--- /dev/null+++ b/cast/tv/src/main/java/com/vayunmathur/cast/tv/ui/TransportOverlay.kt@@ -0,0 +1,203 @@+package com.vayunmathur.cast.tv.ui++import android.text.format.DateUtils+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.withFrameMillis+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.vayunmathur.cast.tv.R+import com.vayunmathur.cast.tv.platform.PlaybackSnapshot++/**+ * The transport controls, over the picture.+ *+ * **Nothing here is focusable, and that is deliberate rather than an omission.** A media overlay is+ * driven by the remote's dedicated keys and its D-pad as *gestures* - left seeks, up is volume - not by+ * moving a focus ring between buttons. `MirrorActivity.dispatchKeyEvent` is therefore the whole input+ * path, and this file is a read-only view of state. It is the one shape of TV UI where `androidx.tv`'s+ * focus machinery has nothing to contribute, which is also why it is safe to draw over a decoder+ * surface: no focus means no chance of the compositor being asked to redraw the video layer.+ *+ * Only mounted while the phone is reporting playback, so it cannot appear over a mirrored phone screen+ * - there would be no transport to control.+ */+@Composable+fun TransportOverlay(+ snapshot: PlaybackSnapshot,+ sourceName: String,+ /** A scrub in progress, which has not been committed to the phone yet. Null when not scrubbing. */+ scrubPreviewMs: Long?,+ modifier: Modifier = Modifier,+) {+ val state = snapshot.state++ // Redrawn with the panel rather than with the phone's reports. A bar plotted only when a snapshot+ // landed would step twice a second; anchoring on the snapshot and advancing with the frame clock is+ // what makes it move like a seek bar. Keyed on the snapshot so every fresh one re-anchors.+ var frameNowMs by remember { mutableLongStateOf(System.currentTimeMillis()) }+ LaunchedEffect(snapshot) {+ frameNowMs = System.currentTimeMillis()+ // Nothing to advance while paused, and a frame callback per frame for a still bar would keep+ // the panel awake for no reason.+ if (!state.playing) return@LaunchedEffect+ while (true) {+ withFrameMillis { frameNowMs = System.currentTimeMillis() }+ }+ }+ val positionMs = scrubPreviewMs ?: snapshot.positionAt(frameNowMs)++ Box(modifier = modifier.fillMaxSize()) {+ Column(+ modifier = Modifier+ .align(Alignment.BottomCenter)+ .fillMaxWidth()+ // A scrim rather than a panel: the picture stays visible behind the controls, which is+ // what makes scrubbing usable at all.+ .background(+ Brush.verticalGradient(+ listOf(Color.Transparent, Color.Black.copy(alpha = 0.85f)),+ ),+ )+ .padding(horizontal = 48.dp, vertical = 32.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(+ text = sourceName,+ style = MaterialTheme.typography.titleLarge,+ color = Color.White,+ )+ if (state.speed != 1f) {+ Text(+ text = stringResource(R.string.tv_transport_speed, formatSpeed(state.speed)),+ style = MaterialTheme.typography.titleMedium,+ color = Color.White.copy(alpha = 0.8f),+ )+ }+ }++ SeekBar(+ positionMs = positionMs,+ durationMs = state.durationMs,+ scrubbing = scrubPreviewMs != null,+ )++ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ ) {+ Text(+ text = elapsed(positionMs),+ style = MaterialTheme.typography.bodyLarge,+ color = Color.White,+ )+ // The one place the paused/buffering distinction is drawn: a stall and a pause look+ // identical on a frozen picture, and only one of them is the user's own doing.+ Text(+ text = when {+ state.buffering -> "…"+ !state.playing -> "❚❚"+ else -> "▶"+ },+ style = MaterialTheme.typography.bodyLarge,+ color = Color.White,+ )+ Text(+ text = if (state.durationMs > 0) elapsed(state.durationMs) else "",+ style = MaterialTheme.typography.bodyLarge,+ color = Color.White,+ )+ }++ Text(+ text = stringResource(R.string.tv_transport_hint),+ style = MaterialTheme.typography.bodySmall,+ color = Color.White.copy(alpha = 0.6f),+ )+ }+ }+}++/**+ * The bar, drawn as nested boxes rather than as a `Slider`.+ *+ * A `Slider` is a touch control: it wants a drag gesture and a focusable thumb, and on a television it+ * would offer both to a device that has neither. What is actually needed is a progress indicator that+ * happens to be movable by the remote, and the remote handling lives in the Activity.+ *+ * A stream with no known duration gets no bar at all, rather than an empty one that looks broken.+ */+@Composable+private fun SeekBar(positionMs: Long, durationMs: Long, scrubbing: Boolean) {+ if (durationMs <= 0) return+ val progress = (positionMs.toFloat() / durationMs).coerceIn(0f, 1f)+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .height(if (scrubbing) 10.dp else 6.dp)+ .clip(RoundedCornerShape(50))+ .background(Color.White.copy(alpha = 0.25f)),+ contentAlignment = Alignment.CenterStart,+ ) {+ Box(+ modifier = Modifier+ .fillMaxHeight()+ .fillMaxWidth(progress)+ .background(MaterialTheme.colorScheme.primary),+ )+ // The thumb rides the end of the filled track, which needs no measured width to place.+ Box(+ modifier = Modifier.fillMaxWidth(progress),+ contentAlignment = Alignment.CenterEnd,+ ) {+ Box(+ modifier = Modifier+ .size(if (scrubbing) 20.dp else 14.dp)+ .clip(RoundedCornerShape(50))+ .background(MaterialTheme.colorScheme.primary),+ )+ }+ }+}++/** `H:MM:SS` past an hour, `M:SS` below it - which is what every other player on the panel does. */+private fun elapsed(positionMs: Long): String =+ DateUtils.formatElapsedTime((positionMs / 1_000).coerceAtLeast(0))++/** "2" rather than "2.0", "1.5" rather than "1.50". Matches YouPipe's own speed readout. */+private fun formatSpeed(speed: Float): String {+ val rounded = Math.round(speed * 100f) / 100f+ return if (rounded % 1f == 0f) {+ rounded.toInt().toString()+ } else {+ rounded.toString().trimEnd('0').trimEnd('.')+ }+}
cast/tv/src/main/res/values/strings.xml
diff --git a/cast/tv/src/main/res/values/strings.xml b/cast/tv/src/main/res/values/strings.xmlindex 7899968c6b..38d169bcd0 100644--- a/cast/tv/src/main/res/values/strings.xml+++ b/cast/tv/src/main/res/values/strings.xml@@ -27,6 +27,10 @@ <string name="tv_no_decoder">This TV has no usable H.265 or AV1 decoder</string> <string name="tv_missing_codec_config">Your phone did not send the video settings this TV needed. Try mirroring again.</string> <string name="tv_stream_failed">The stream stopped</string>+ <!-- Transport overlay, driven from the TV remote -->+ <string name="tv_transport_speed">%1$s×</string>+ <string name="tv_transport_hint">OK to play or pause · ◀ ▶ to seek · ▲ ▼ for volume</string>+ <string name="tv_transport_volume">Volume %1$d%%</string> <!-- Foreground service --> <string name="tv_notification_channel_name">Receiving</string>