Modern Apps git

← Modern-Apps.git

maauto: sender-side render-confirmation telemetry + session card

Commit
695082fa12c026158acd48e07ab968b1ed73dfd0
Author
vayun-mathur <[email protected]>
When
2026-09-12 18:43 UTC (2 months ago)
Parents
601e1d1

Diff

auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalProtoTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalProtoTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalProtoTest.ktindex 44e6a72eb3..32e6ecfefd 100644--- a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalProtoTest.kt+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalProtoTest.kt@@ -6,6 +6,7 @@ import com.vayunmathur.auto.protocol.gal.ByeByeReason import com.vayunmathur.auto.protocol.gal.ByeByeRequest import com.vayunmathur.auto.protocol.gal.ChannelOpenResponse import com.vayunmathur.auto.protocol.gal.ChannelOpenRequest+import com.vayunmathur.auto.protocol.gal.MediaAck import com.vayunmathur.auto.protocol.gal.MediaCodecType import com.vayunmathur.auto.protocol.gal.MediaSinkService import com.vayunmathur.auto.protocol.gal.PingRequest@@ -152,4 +153,43 @@ class GalProtoTest {         assertEquals(3, MediaCodecType.MEDIA_CODEC_VIDEO_H264_BP.number)         assertEquals(7, MediaCodecType.MEDIA_CODEC_VIDEO_H265.number)     }++    @Test+    fun `MediaAck carries session id, ack counter and field3 entries`() {+        // 0x8004 from the head unit. The video channel reads the optional ack+        // counter (field 2) for its sequence track and counts field3 entries,+        // so pin both the exact bytes and the accessors here.+        val bytes = MediaAck.newBuilder()+            .setSessionId(0)+            .setAck(118)+            .addField3(1L)+            .addField3(2L)+            .build()+            .toByteArray()+        assertContentEquals(+            byteArrayOf(+                0x08, 0x00, // field 1, varint, session 0+                0x10, 0x76, // field 2, varint, 118+                0x18, 0x01, // field 3, varint, 1+                0x18, 0x02, // field 3, varint, 2+            ),+            bytes,+        )+        val parsed = MediaAck.parseFrom(bytes)+        assertEquals(0, parsed.sessionId)+        assertTrue(parsed.hasAck())+        assertEquals(118, parsed.ack)+        assertEquals(2, parsed.field3Count)+    }++    @Test+    fun `MediaAck without ack leaves the counter absent`() {+        // The head unit may omit the optional counter; the channel then reports+        // a null sequence rather than a bogus zero.+        val parsed = MediaAck.parseFrom(+            MediaAck.newBuilder().setSessionId(0).build().toByteArray(),+        )+        assertTrue(!parsed.hasAck())+        assertEquals(0, parsed.field3Count)+    } }
auto/src/main/java/com/vayunmathur/auto/platform/AutoSessionState.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/AutoSessionState.kt b/auto/src/main/java/com/vayunmathur/auto/platform/AutoSessionState.ktindex 6c83dae78a..d7ec21dc6f 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/AutoSessionState.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AutoSessionState.kt@@ -1,5 +1,6 @@ package com.vayunmathur.auto.platform +import android.os.SystemClock import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow@@ -28,14 +29,34 @@ sealed interface VideoEvent {     /** The first encoded frame went out. */     data object FirstFrame : VideoEvent -    /** One encoded frame went out. */-    data object FrameSent : VideoEvent+    /**+     * One encoded frame went out.+     *+     * [presentationTimeUs] is the codec timestamp; [latencyUs] is monotonic+     * queue + encode time for this frame (send time minus its timestamp).+     * Sender-side only: this counts frames handed to the socket, never frames+     * decoded or shown by the head unit.+     */+    data class FrameSent(val presentationTimeUs: Long, val latencyUs: Long) : VideoEvent -    /** The head unit acknowledged frames. */-    data object AckReceived : VideoEvent+    /**+     * The head unit acknowledged frames (0x8004).+     *+     * [ackSeq] is the `ack` counter from the `MediaAck`, unsigned-extended; null+     * when the head unit omits the field. [extraCount] is how many `field3`+     * entries rode along. An ack confirms receipt, not visibility — the+     * sender-side proxy for "visible" is acks advancing in step with frames.+     */+    data class AckReceived(val ackSeq: Long?, val extraCount: Int) : VideoEvent      /** An ack named a session that is not ours; the session id lines up otherwise. */     data class AckMismatch(val expected: Int, val actual: Int) : VideoEvent++    /** One encoder drain produced [framesOut] frames (0 when it had nothing ready). */+    data class EncoderDrained(val framesOut: Int) : VideoEvent++    /** The virtual-display + encoder-input-surface pair became valid or went away. */+    data class SurfaceChanged(val valid: Boolean) : VideoEvent }  /**@@ -66,6 +87,53 @@ object AutoSessionState {     private val _ackMismatches = MutableStateFlow(0L)     val ackMismatches: StateFlow<Long> = _ackMismatches.asStateFlow() +    /**+     * Encode-side frames per second over a sliding window of send timestamps.+     * Sender-side: frames handed to the socket per second, not frames displayed.+     */+    private val _encodedFps = MutableStateFlow(0.0)+    val encodedFps: StateFlow<Double> = _encodedFps.asStateFlow()++    /**+     * Head-unit acks per second over a sliding window of ack timestamps.+     * The sender-side proxy for "visible" is this advancing in step with+     * [encodedFps], not the total in [acksSeen].+     */+    private val _ackFps = MutableStateFlow(0.0)+    val ackFps: StateFlow<Double> = _ackFps.asStateFlow()++    /** Millis since the last 0x8004 ack; null when none has arrived this session. */+    private val _lastAckAgeMs = MutableStateFlow<Long?>(null)+    val lastAckAgeMs: StateFlow<Long?> = _lastAckAgeMs.asStateFlow()++    /** Wall-clock millis of the last 0x8004 ack; the UI derives a live age from this. */+    private val _lastAckAt = MutableStateFlow<Long?>(null)+    val lastAckAt: StateFlow<Long?> = _lastAckAt.asStateFlow()++    /** Highest 0x8004 `ack` counter seen; null until an ack carries the field. */+    private val _lastAckSeq = MutableStateFlow<Long?>(null)+    val lastAckSeq: StateFlow<Long?> = _lastAckSeq.asStateFlow()++    /** Rolling mean encode-to-send latency in microseconds over recent frames. */+    private val _avgEncodeLatencyUs = MutableStateFlow<Long?>(null)+    val avgEncodeLatencyUs: StateFlow<Long?> = _avgEncodeLatencyUs.asStateFlow()++    /** Encoder drains so far; frames ride out via [framesSent]. */+    private val _encoderDrains = MutableStateFlow(0L)+    val encoderDrains: StateFlow<Long> = _encoderDrains.asStateFlow()++    /** Whether the virtual display + encoder input surface pair is currently up. */+    private val _surfaceValid = MutableStateFlow(false)+    val surfaceValid: StateFlow<Boolean> = _surfaceValid.asStateFlow()++    /**+     * Send/ack timestamps backing the fps windows. Mutated only on the+     * `ma-auto-projection` worker thread (every entry point above runs there),+     * so no extra locking beyond the flows' own thread-safety.+     */+    private val frameTimes = ArrayDeque<Long>()+    private val ackTimes = ArrayDeque<Long>()+     /** Wall-clock millis when the session became active, for the phone's elapsed counter. */     private val _sessionStartedAt = MutableStateFlow<Long?>(null)     val sessionStartedAt: StateFlow<Long?> = _sessionStartedAt.asStateFlow()@@ -77,6 +145,7 @@ object AutoSessionState {         _framesSent.value = 0         _acksSeen.value = 0         _ackMismatches.value = 0+        resetTelemetry()         _sessionStartedAt.value = null         _connection.value = AutoConnectionState.Connecting     }@@ -98,6 +167,25 @@ object AutoSessionState {         _video.value = null         _focusMode.value = null         _sessionStartedAt.value = null+        resetTelemetry()+    }++    /**+     * Clears every Phase 0 telemetry counter. Called from [onSocketAccepted] and+     * [onDisconnected] alongside the existing counters — a new socket means a+     * new session, so stale fps/age/seq values must not leak across.+     */+    private fun resetTelemetry() {+        frameTimes.clear()+        ackTimes.clear()+        _encodedFps.value = 0.0+        _ackFps.value = 0.0+        _lastAckAgeMs.value = null+        _lastAckAt.value = null+        _lastAckSeq.value = null+        _avgEncodeLatencyUs.value = null+        _encoderDrains.value = 0+        _surfaceValid.value = false     }      /** End of a session: a recorded failure means refusal, anything else a clean parting. */@@ -110,12 +198,63 @@ object AutoSessionState {             is VideoEvent.Setup -> _video.value = event.info             is VideoEvent.FocusChanged -> _focusMode.value = event.mode             VideoEvent.FirstFrame -> Unit-            VideoEvent.FrameSent -> _framesSent.value++-            VideoEvent.AckReceived -> _acksSeen.value+++            is VideoEvent.FrameSent -> {+                _framesSent.value+++                val now = SystemClock.uptimeMillis()+                frameTimes.addLast(now)+                while (frameTimes.isNotEmpty() && now - frameTimes.first() > FPS_WINDOW_MS) {+                    frameTimes.removeFirst()+                }+                _encodedFps.value = frameTimes.size * 1_000.0 / FPS_WINDOW_MS+                // Blend this frame's encode-to-send latency into the rolling mean.+                val previous = _avgEncodeLatencyUs.value+                _avgEncodeLatencyUs.value =+                    if (previous == null) event.latencyUs else (previous + event.latencyUs) / 2+                // Keep the ack age live while frames flow: it is the gap since the+                // last ack, recomputed on every frame, not just when an ack lands.+                refreshAckAge(System.currentTimeMillis())+            }+            is VideoEvent.AckReceived -> {+                _acksSeen.value+++                recordAck(event.ackSeq)+            }             is VideoEvent.AckMismatch -> {                 _acksSeen.value++                 _ackMismatches.value+++                // A mismatched ack still proves the head unit is alive and consuming.+                _lastAckAt.value = System.currentTimeMillis()+                _lastAckAgeMs.value = 0             }+            is VideoEvent.EncoderDrained -> _encoderDrains.value+++            is VideoEvent.SurfaceChanged -> _surfaceValid.value = event.valid+        }+    }++    /** Shares the ack timestamp/rate bookkeeping between matching and mismatched acks. */+    private fun recordAck(ackSeq: Long?) {+        val nowWall = System.currentTimeMillis()+        val nowUptime = SystemClock.uptimeMillis()+        _lastAckAt.value = nowWall+        _lastAckAgeMs.value = 0+        ackTimes.addLast(nowUptime)+        while (ackTimes.isNotEmpty() && nowUptime - ackTimes.first() > FPS_WINDOW_MS) {+            ackTimes.removeFirst()+        }+        _ackFps.value = ackTimes.size * 1_000.0 / FPS_WINDOW_MS+        if (ackSeq != null) {+            val previous = _lastAckSeq.value+            if (previous == null || ackSeq > previous) _lastAckSeq.value = ackSeq         }     }++    /** Recomputes the last-ack age against [nowWall]; a no-op until the first ack. */+    private fun refreshAckAge(nowWall: Long) {+        val at = _lastAckAt.value ?: return+        _lastAckAgeMs.value = (nowWall - at).coerceAtLeast(0)+    }++    private companion object {+        /** Sliding window the fps rates are computed over. */+        const val FPS_WINDOW_MS = 5_000L+    } }
auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.ktindex 3ab6e7f1eb..4929384f18 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt@@ -31,6 +31,38 @@ class AutoViewModel : ViewModel() {     val ackMismatches: StateFlow<Long> = AutoSessionState.ackMismatches         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), 0L) +    /** Encode-side frames per second over a sliding window; never decoded/rendered. */+    val encodedFps: StateFlow<Double> = AutoSessionState.encodedFps+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), 0.0)++    /** Head-unit acks per second over a sliding window; receipt, not visibility. */+    val ackFps: StateFlow<Double> = AutoSessionState.ackFps+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), 0.0)++    /** Millis since the last 0x8004 ack; null before the first. */+    val lastAckAgeMs: StateFlow<Long?> = AutoSessionState.lastAckAgeMs+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), null)++    /** Wall-clock millis of the last ack; the UI derives a live age from this. */+    val lastAckAt: StateFlow<Long?> = AutoSessionState.lastAckAt+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), null)++    /** Highest 0x8004 ack counter seen; null until an ack carries the field. */+    val lastAckSeq: StateFlow<Long?> = AutoSessionState.lastAckSeq+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), null)++    /** Rolling mean encode-to-send latency in microseconds, or null with no frames. */+    val avgEncodeLatencyUs: StateFlow<Long?> = AutoSessionState.avgEncodeLatencyUs+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), null)++    /** Encoder drains so far; frames ride out via [framesSent]. */+    val encoderDrains: StateFlow<Long> = AutoSessionState.encoderDrains+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), 0L)++    /** Whether the virtual display + encoder input surface pair is currently up. */+    val surfaceValid: StateFlow<Boolean> = AutoSessionState.surfaceValid+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), false)+     val sessionStartedAt: StateFlow<Long?> = AutoSessionState.sessionStartedAt         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), null) 
auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.ktindex 8164472d66..1ec914ea25 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt@@ -8,6 +8,7 @@ import android.hardware.display.VirtualDisplay import android.os.Bundle import android.os.Handler import android.os.Looper+import android.util.Log import android.view.Gravity import android.view.Surface import android.view.View@@ -16,6 +17,7 @@ import android.widget.GridLayout import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView+import com.vayunmathur.auto.BuildConfig import com.vayunmathur.auto.R import java.text.DateFormat import java.util.Date@@ -65,6 +67,7 @@ class CarDisplay(         virtualDisplay = display          presentation = showPresentation(display.display)+        dumpVirtualDisplay(display.display, surface)     }      /**@@ -262,5 +265,21 @@ class CarDisplay(      private companion object {         const val DISPLAY_NAME = "MA Auto"+        const val TAG = "MaAuto.Display"++        /**+         * Dev-build validity dump of the virtual display for the Phase 0 probe:+         * display id, real size, and whether the encoder input surface is live.+         * Gated on [BuildConfig.DEV_BUILD] so release logcat stays quiet.+         */+        fun dumpVirtualDisplay(display: android.view.Display, surface: Surface) {+            if (!BuildConfig.DEV_BUILD) return+            val size = android.graphics.Point().also { display.getRealSize(it) }+            Log.i(+                TAG,+                "virtual display up: id=${display.displayId} real=${size.x}x${size.y} " ++                    "surface valid=${surface.isValid}",+            )+        }     } }
auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.ktindex 7a3afe44d7..756b3011dc 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.kt@@ -2,7 +2,10 @@ package com.vayunmathur.auto.platform  import android.content.Context import android.media.MediaCodec+import android.os.SystemClock import android.util.Log+import android.view.Surface+import com.vayunmathur.auto.BuildConfig import com.vayunmathur.auto.protocol.GalConnection import com.vayunmathur.auto.protocol.GalMessage import com.vayunmathur.auto.protocol.gal.MediaAck@@ -44,6 +47,13 @@ class VideoSinkChannel(     private var configurationIndex = 0     private var firstFrameSent = false +    /**+     * Frames emitted since the last [pumpEncoder] call. `drain()` invokes+     * [sendFrame] synchronously, so snapshotting after it returns counts exactly+     * this pump's yield — which is what tells "encoder idle" from "flowing".+     */+    private var framesOutSinceDrain = 0+     /** Chosen from what the head unit advertised in discovery. */     private val configuration: VideoConfiguration? =         service.mediaSink.videoConfigsList.firstOrNull()@@ -96,13 +106,19 @@ class VideoSinkChannel(      private fun onAck(payload: ByteArray) {         // Flow control: the head unit has consumed frames. Nothing to do while we send-        // unthrottled, but parsing it confirms the session id lines up.+        // unthrottled, but parsing it confirms the session id lines up — and the ack+        // counter plus field3 entries are the sender-side sequence track of the stream.         val ack = MediaAck.parseFrom(payload)         if (ack.sessionId != sessionId) {             Log.w(TAG, "ack for session ${ack.sessionId}, expected $sessionId")             onEvent(VideoEvent.AckMismatch(expected = sessionId, actual = ack.sessionId))         } else {-            onEvent(VideoEvent.AckReceived)+            onEvent(+                VideoEvent.AckReceived(+                    ackSeq = if (ack.hasAck()) Integer.toUnsignedLong(ack.ack) else null,+                    extraCount = ack.field3Count,+                ),+            )         }     } @@ -121,9 +137,14 @@ class VideoSinkChannel(         this.encoder = encoder         encoder.start() +        val surface = checkNotNull(encoder.surface) { "encoder produced no input surface" }         display = CarDisplay(context, width, height, density).also {-            it.show(checkNotNull(encoder.surface) { "encoder produced no input surface" })+            it.show(surface)         }+        // The render pair is up: a private virtual display compositing straight into+        // the encoder's input surface. Validity dump for the Phase 0 probe.+        dumpSurfaces(width, height, density, surface)+        onEvent(VideoEvent.SurfaceChanged(valid = true))          // Step 4.         connection.send(@@ -137,12 +158,38 @@ class VideoSinkChannel(         )     } +    /**+     * Dev-build validity dump of the render pair for the Phase 0 probe: virtual-display+     * geometry plus whether the encoder input surface is still live. R8 strips the+     * whole call from release builds via [BuildConfig.DEV_BUILD]; production logcat+     * stays quiet.+     */+    private fun dumpSurfaces(width: Int, height: Int, density: Int, surface: Surface) {+        if (!BuildConfig.DEV_BUILD) return+        Log.i(+            TAG,+            "render pair up: virtual display ${width}x$height dpi $density, " ++                "encoder input surface valid=${surface.isValid}",+        )+    }+     private fun sendFrame(buffer: ByteBuffer, info: MediaCodec.BufferInfo) {         if (!firstFrameSent) {             firstFrameSent = true             onEvent(VideoEvent.FirstFrame)         }-        onEvent(VideoEvent.FrameSent)+        framesOutSinceDrain+++        // Encode-to-send latency: codec timestamp (queue time, monotonic) vs now.+        // Clamped at zero — a late pump can drain a frame whose timestamp predates+        // the send by more than the stream age only on clock weirdness.+        val latencyUs = (SystemClock.elapsedRealtimeNanos() / 1_000 - info.presentationTimeUs)+            .coerceAtLeast(0)+        onEvent(+            VideoEvent.FrameSent(+                presentationTimeUs = info.presentationTimeUs,+                latencyUs = latencyUs,+            ),+        )         val bytes = ByteArray(info.size)         buffer.get(bytes)         // Timestamped form: an 8-byte microsecond timestamp then the access unit. Codec@@ -154,9 +201,19 @@ class VideoSinkChannel(         connection.send(channelId, GalMessage.Media.DATA_WITH_TIMESTAMP, payload)     } -    /** Pushes any encoded frames out. Called from the connection's loop. */+    /**+     * Pushes any encoded frames out. Called from the connection's loop.+     *+     * Emits a drain observation per pump so the phone UI can tell "encoder idle"+     * (drains with nothing ready) from "frames flowing" ([VideoEvent.FrameSent]).+     */     fun pumpEncoder() {+        // No encoder yet (channel open but setup/start still in flight): nothing to+        // drain and nothing to count — drains are scoped to the streaming session.+        if (encoder == null) return+        framesOutSinceDrain = 0         encoder?.drain()+        onEvent(VideoEvent.EncoderDrained(framesOut = framesOutSinceDrain))     }      fun release() {@@ -164,6 +221,7 @@ class VideoSinkChannel(         display = null         encoder?.stop()         encoder = null+        onEvent(VideoEvent.SurfaceChanged(valid = false))     }      private fun VideoResolution?.dimensions(): Pair<Int, Int> = when (this) {
auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt b/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.ktindex 191fa2ef25..1b2b269a5d 100644--- a/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt+++ b/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt@@ -32,6 +32,13 @@ fun AutoScreen(viewModel: AutoViewModel) {         framesSent = viewModel.framesSent.collectAsStateWithLifecycle().value,         acksSeen = viewModel.acksSeen.collectAsStateWithLifecycle().value,         ackMismatches = viewModel.ackMismatches.collectAsStateWithLifecycle().value,+        encodedFps = viewModel.encodedFps.collectAsStateWithLifecycle().value,+        ackFps = viewModel.ackFps.collectAsStateWithLifecycle().value,+        lastAckAt = viewModel.lastAckAt.collectAsStateWithLifecycle().value,+        lastAckSeq = viewModel.lastAckSeq.collectAsStateWithLifecycle().value,+        avgEncodeLatencyUs = viewModel.avgEncodeLatencyUs.collectAsStateWithLifecycle().value,+        encoderDrains = viewModel.encoderDrains.collectAsStateWithLifecycle().value,+        surfaceValid = viewModel.surfaceValid.collectAsStateWithLifecycle().value,         sessionStartedAt = viewModel.sessionStartedAt.collectAsStateWithLifecycle().value,     )     val scrollBehavior = appBarScrollBehavior()@@ -68,6 +75,20 @@ data class SessionSnapshot(     val framesSent: Long,     val acksSeen: Long,     val ackMismatches: Long,+    /** Encode-side frames per second; sent, never decoded or shown. */+    val encodedFps: Double,+    /** Head-unit acks per second; receipt, not visibility. */+    val ackFps: Double,+    /** Wall-clock millis of the last ack; null before the first. Drives the live age. */+    val lastAckAt: Long?,+    /** Highest 0x8004 ack counter seen; null until an ack carries the field. */+    val lastAckSeq: Long?,+    /** Rolling mean encode-to-send latency in microseconds, or null with no frames. */+    val avgEncodeLatencyUs: Long?,+    /** Encoder drains so far. */+    val encoderDrains: Long,+    /** Whether the virtual display + encoder input surface pair is up. */+    val surfaceValid: Boolean,     val sessionStartedAt: Long?, ) 
auto/src/main/java/com/vayunmathur/auto/ui/SessionCard.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/ui/SessionCard.kt b/auto/src/main/java/com/vayunmathur/auto/ui/SessionCard.ktindex 285bcc2f28..61d986e523 100644--- a/auto/src/main/java/com/vayunmathur/auto/ui/SessionCard.kt+++ b/auto/src/main/java/com/vayunmathur/auto/ui/SessionCard.kt@@ -55,11 +55,92 @@ fun SessionCard(session: SessionSnapshot, modifier: Modifier = Modifier) {                     },                 )             }+            ListItem(+                headlineContent = { Text(stringResource(R.string.session_rates)) },+                supportingContent = {+                    Text(+                        stringResource(+                            R.string.session_rates_value,+                            session.encodedFps,+                            session.ackFps,+                        ),+                    )+                },+            )+            AckAgeRow(lastAckAt = session.lastAckAt)+            ListItem(+                headlineContent = { Text(stringResource(R.string.session_ack_seq)) },+                supportingContent = {+                    Text(+                        session.lastAckSeq?.let {+                            stringResource(R.string.session_ack_seq_value, it)+                        } ?: stringResource(R.string.session_ack_seq_none),+                    )+                },+            )+            ListItem(+                headlineContent = { Text(stringResource(R.string.session_latency)) },+                supportingContent = {+                    Text(+                        session.avgEncodeLatencyUs?.let {+                            stringResource(R.string.session_latency_value, it)+                        } ?: stringResource(R.string.session_latency_none),+                    )+                },+            )+            ListItem(+                headlineContent = { Text(stringResource(R.string.session_drains)) },+                supportingContent = {+                    Text(stringResource(R.string.session_drains_value, session.encoderDrains))+                },+            )+            ListItem(+                headlineContent = { Text(stringResource(R.string.session_surface)) },+                supportingContent = {+                    Text(+                        stringResource(+                            if (session.surfaceValid) R.string.session_surface_valid+                            else R.string.session_surface_invalid,+                        ),+                    )+                },+            )             SessionElapsedRow(sessionStartedAt = session.sessionStartedAt)         }     } } +/**+ * Live age of the last head-unit ack, recomposing each second from the wall-clock+ * timestamp; a dash while no ack has arrived. Reuses the session clock pattern so+ * only this row recomposes, not the whole card.+ */+@Composable+private fun AckAgeRow(lastAckAt: Long?) {+    val now = rememberClock(1.seconds)+    var tick by remember { mutableLongStateOf(System.currentTimeMillis()) }+    tick = now()+    if (lastAckAt == null) {+        ListItem(+            headlineContent = { Text(stringResource(R.string.session_ack_age)) },+            supportingContent = { Text(stringResource(R.string.session_ack_age_none)) },+        )+        return+    }+    val age = formatAge(tick - lastAckAt)+    ListItem(+        headlineContent = { Text(stringResource(R.string.session_ack_age)) },+        supportingContent = { Text(stringResource(R.string.session_ack_age_value, age)) },+    )+}++@Composable+private fun formatAge(millis: Long): String {+    val clamped = millis.coerceAtLeast(0)+    return if (clamped < 10_000) stringResource(R.string.session_ack_age_secs, clamped / 1_000.0)+    else stringResource(R.string.session_ack_age_secs_whole, (clamped / 1_000).toInt())+}+ /** Live mm:ss counter since the session became active; a dash when there is no session. */ @Composable private fun SessionElapsedRow(sessionStartedAt: Long?) {
auto/src/main/res/values/strings.xml
diff --git a/auto/src/main/res/values/strings.xml b/auto/src/main/res/values/strings.xmlindex 4edc525cae..2e7eeca1c2 100644--- a/auto/src/main/res/values/strings.xml+++ b/auto/src/main/res/values/strings.xml@@ -38,6 +38,47 @@     <string name="session_ack_mismatch">Ack mismatches</string>     <!-- %1$d is the count of mismatched acks. -->     <string name="session_ack_mismatch_value"><xliff:g example="1" id="count">%1$d</xliff:g></string>+    <!-- Heading of the row showing the encode-side and ack rates over a sliding window.+         Sender-side only: sent frames per second and head-unit acks per second. -->+    <string name="session_rates">Rates sent / acked</string>+    <!-- %1$.1f is frames sent per second, %2$.1f is acks per second. -->+    <string name="session_rates_value"><xliff:g example="30.0" id="sent_fps">%1$.1f</xliff:g> / <xliff:g example="29.5" id="ack_fps">%2$.1f</xliff:g> fps</string>+    <!-- Heading of the row showing how old the last head-unit ack is. -->+    <string name="session_ack_age">Last ack</string>+    <!-- Shown once an ack has arrived. %1$s is an age like "0.4 s" or "12 s". -->+    <string name="session_ack_age_value"><xliff:g example="0.4 s" id="age">%1$s</xliff:g> ago</string>+    <!-- Age of the last head-unit ack under ten seconds, one decimal. %1$.1f is+         seconds; translators own the unit so it can be spaced or abbreviated per locale. -->+    <string name="session_ack_age_secs"><xliff:g example="0.4" id="secs">%1$.1f</xliff:g> s</string>+    <!-- Age of the last head-unit ack at ten seconds or more, whole seconds.+         %1$d is seconds; translators own the unit. -->+    <string name="session_ack_age_secs_whole"><xliff:g example="12" id="secs">%1$d</xliff:g> s</string>+    <!-- Shown on the session card before the first head-unit ack arrives. -->+    <string name="session_ack_age_none">No acks yet</string>+    <!-- Heading of the row showing the highest head-unit ack counter seen. -->+    <string name="session_ack_seq">Ack sequence</string>+    <!-- %1$d is the highest 0x8004 ack counter seen so far. -->+    <string name="session_ack_seq_value"><xliff:g example="118" id="seq">%1$d</xliff:g></string>+    <!-- Shown when no ack has carried a sequence counter yet. -->+    <string name="session_ack_seq_none">—</string>+    <!-- Heading of the row showing the mean encode-to-send latency. -->+    <string name="session_latency">Encode latency</string>+    <!-- %1$d is the rolling mean encode-to-send latency in microseconds. -->+    <string name="session_latency_value"><xliff:g example="8300" id="latency_us">%1$d</xliff:g> µs</string>+    <!-- Shown when no frame has been sent yet to measure latency from. -->+    <string name="session_latency_none">—</string>+    <!-- Heading of the row counting encoder drains. -->+    <string name="session_drains">Encoder drains</string>+    <!-- %1$d is the count of encoder drains so far. -->+    <string name="session_drains_value"><xliff:g example="240" id="count">%1$d</xliff:g></string>+    <!-- Heading of the row showing whether the virtual display plus encoder input+         surface pair is currently up. -->+    <string name="session_surface">Surface</string>+    <!-- Shown on the session card while the virtual-display and encoder-input-surface+         pair is up and compositing. -->+    <string name="session_surface_valid">Valid</string>+    <!-- Shown on the session card when the render pair is down or not yet up. -->+    <string name="session_surface_invalid">Down</string>     <!-- Heading of the row showing how long the session has been active. -->     <string name="session_elapsed">Session time</string>     <!-- Shown when there is no active session to time. -->