Modern Apps git

← Modern-Apps.git

maauto: now-playing card into ch2 plus phone row

Commit
81a71e0c9feb01c4bc27e9fb061b5ec75a7f2057
Author
vayun-mathur <[email protected]>
When
2026-09-12 20:43 UTC (2 months ago)
Parents
3d7d48c

Diff

auto/build.gradle.kts
diff --git a/auto/build.gradle.kts b/auto/build.gradle.ktsindex 257556cf55..efd1ab5813 100644--- a/auto/build.gradle.kts+++ b/auto/build.gradle.kts@@ -14,4 +14,6 @@ dependencies {     // The GAL wire format. Nothing in the app re-implements it, and keeping it out of here is     // what lets the handshake be tested on the JVM.     implementation(project(":auto:protocol"))+    // Media3 controller for the Phase 4 now-playing feed from the on-device media session.+    implementation(libs.androidx.media3.session) }
auto/src/main/AndroidManifest.xml
diff --git a/auto/src/main/AndroidManifest.xml b/auto/src/main/AndroidManifest.xmlindex 710d20ffed..a2e50488d9 100644--- a/auto/src/main/AndroidManifest.xml+++ b/auto/src/main/AndroidManifest.xml@@ -17,7 +17,9 @@     <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />      <!-- The car launcher resolves Maps / Music / dialer through PackageManager. Android 11+-         hides other apps by default, so these queries keep those lookups visible. -->+         hides other apps by default, so these queries keep those lookups visible. The media+         monitor also resolves the music browser service through getServiceInfo, which needs+         no query entry, but the explicit package row keeps the intent clear. -->     <queries>         <package android:name="com.vayunmathur.maps" />         <package android:name="com.vayunmathur.music" />
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 8ba4224fde..042c092283 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/AutoSessionState.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AutoSessionState.kt@@ -129,6 +129,10 @@ object AutoSessionState {     private val _surfaceValid = MutableStateFlow(false)     val surfaceValid: StateFlow<Boolean> = _surfaceValid.asStateFlow() +    /** Latest now-playing snapshot from the on-device media session; null until one reports. */+    private val _nowPlaying = MutableStateFlow<NowPlayingInfo?>(null)+    val nowPlaying: StateFlow<NowPlayingInfo?> = _nowPlaying.asStateFlow()+     /**      * Send/ack timestamps backing the fps windows. Mutated only on the      * `ma-auto-projection` worker thread (every entry point above runs there),@@ -167,6 +171,7 @@ object AutoSessionState {     fun onSocketAccepted() {         _video.value = null         _focusMode.value = null+        _nowPlaying.value = null         _framesSent.value = 0         _acksSeen.value = 0         _ackMismatches.value = 0@@ -191,6 +196,7 @@ object AutoSessionState {         _connection.value = AutoConnectionState.Disconnected         _video.value = null         _focusMode.value = null+        _nowPlaying.value = null         _sessionStartedAt.value = null         resetTelemetry()     }@@ -256,6 +262,13 @@ object AutoSessionState {         }     } +    /** Records a media snapshot. Thread-safe like every other flow write here. */+    fun onMediaEvent(event: MediaEvent) {+        when (event) {+            is MediaEvent.NowPlayingChanged -> _nowPlaying.value = event.info+        }+    }+     /** Shares the ack timestamp/rate bookkeeping between matching and mismatched acks. */     private fun recordAck(ackSeq: Long?) {         val nowWall = System.currentTimeMillis()
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 704c28e3e8..1a2c360e21 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt@@ -63,6 +63,10 @@ class AutoViewModel : ViewModel() {     val surfaceValid: StateFlow<Boolean> = AutoSessionState.surfaceValid         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), false) +    /** Latest now-playing snapshot; null until the media session reports. */+    val nowPlaying: StateFlow<NowPlayingInfo?> = AutoSessionState.nowPlaying+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), null)+     /** Whole days until the shipped GAL leaf expires; null until the service seeds it. */     val credentialDaysLeft: StateFlow<Long?> = AutoSessionState.credentialDaysLeft         .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 1ec914ea25..ce330a6dc1 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt@@ -40,9 +40,25 @@ class CarDisplay(     private val densityDpi: Int, ) {     private var virtualDisplay: VirtualDisplay? = null-    private var presentation: Presentation? = null+    private var presentation: CarPresentation? = null     private val mainHandler = Handler(Looper.getMainLooper()) +    /**+     * Fires when the now-playing card is tapped, locally or from the head unit+     * via [handleCarTap]. Wired to the media monitor's transport toggle.+     */+    var onMediaTap: (() -> Unit)? = null++    /**+     * Latest now-playing snapshot: applied to the card when set, and to any+     * presentation created afterwards. Written on the projection worker thread+     * and handed to the main thread by reference through the posted update.+     */+    @Volatile private var nowPlaying: NowPlayingInfo? = null++    /** Last-known now-playing card bounds in display pixels; null until laid out. */+    @Volatile private var mediaCardBounds: TapBounds? = null+     private val isMainThread get() = Looper.myLooper() == Looper.getMainLooper()      /**@@ -66,10 +82,42 @@ class CarDisplay(         ) ?: error("could not create the car virtual display")         virtualDisplay = display -        presentation = showPresentation(display.display)+        presentation = showPresentation(+            display.display,+            initialNowPlaying = nowPlaying,+            onMediaTap = { onMediaTap?.invoke() },+            onCardBounds = { left, top, right, bottom ->+                mediaCardBounds = TapBounds(left, top, right, bottom)+            },+        )         dumpVirtualDisplay(display.display, surface)     } +    /**+     * Refreshes the car now-playing card. Safe from any thread: the snapshot is+     * cached for presentations created later, and the view update hops to main.+     */+    fun setNowPlaying(info: NowPlayingInfo) {+        nowPlaying = info+        mainHandler.post { presentation?.updateNowPlaying(info) }+    }++    /**+     * Routes a head-unit tap at the now-playing card.+     *+     * [x] and [y] are display pixels (what ch8 scales to), compared against the+     * card's on-screen bounds on the virtual display. Returns whether the tap+     * hit the card; a hit posts the toggle to the main thread because views may+     * only be touched there. The ch8 owner calls this after scaling -- see the+     * Phase 4 handoff to input-dev.+     */+    fun handleCarTap(x: Float, y: Float): Boolean {+        val bounds = mediaCardBounds ?: return false+        if (!bounds.contains(x, y)) return false+        mainHandler.post { onMediaTap?.invoke() }+        return true+    }+     /**      * Dismisses the car UI and releases the virtual display. The dismiss hops to the      * main thread to match [show]; it is fire-and-forget since nothing after it@@ -85,11 +133,20 @@ class CarDisplay(         virtualDisplay = null     } -    /** Creates and shows the [Presentation] for [display] on the main thread. */-    private fun showPresentation(display: android.view.Display): Presentation {-        if (isMainThread) return CarPresentation(context, display).also { it.show() }+    /** Creates and shows the [CarPresentation] for [display] on the main thread. */+    private fun showPresentation(+        display: android.view.Display,+        initialNowPlaying: NowPlayingInfo?,+        onMediaTap: () -> Unit,+        onCardBounds: (Int, Int, Int, Int) -> Unit,+    ): CarPresentation {+        if (isMainThread) {+            return CarPresentation(context, display, initialNowPlaying, onMediaTap, onCardBounds)+                .also { it.show() }+        }         val show = FutureTask<CarPresentation> {-            CarPresentation(context, display).also { it.show() }+            CarPresentation(context, display, initialNowPlaying, onMediaTap, onCardBounds)+                .also { it.show() }         }         mainHandler.post(show)         try {@@ -114,11 +171,28 @@ class CarDisplay(      * extra plumbing. Large tiles, high contrast, and nothing that needs reading at      * a glance beyond a label.      */-    private class CarPresentation(context: Context, display: android.view.Display) :-        Presentation(context, display) {+    private class CarPresentation(+        context: Context,+        display: android.view.Display,+        initialNowPlaying: NowPlayingInfo?,+        private val onMediaTap: () -> Unit,+        private val onCardBounds: (Int, Int, Int, Int) -> Unit,+    ) : Presentation(context, display) {++        /**+         * Snapshot that arrived before `onCreate` built the card views.+         * Consumed once in `onCreate`; after that the card exists and updates+         * apply directly.+         */+        private var pendingNowPlaying: NowPlayingInfo? = initialNowPlaying          private var clockView: TextView? = null         private val timeFormat: DateFormat = DateFormat.getTimeInstance(DateFormat.SHORT)+        private var mediaTitle: TextView? = null+        private var mediaSubtitle: TextView? = null+        private var mediaState: TextView? = null+        private var mediaProgress: View? = null+        private var mediaCard: LinearLayout? = null          // Real wall-clock time, ticking every second. The old placeholder showed a         // session counter here; a driver needs to know what time it is instead, and the@@ -140,10 +214,14 @@ class CarDisplay(             }             root.addView(statusBar())             root.addView(divider())+            root.addView(nowPlayingCard())             val apps = CarApps.query(context)             root.addView(if (apps.isEmpty()) emptyState() else appGrid(apps))             setContentView(root) +            pendingNowPlaying?.let { updateNowPlaying(it) }+            pendingNowPlaying = null+             clockView?.let {                 it.text = timeFormat.format(Date())                 it.post(ticker)@@ -153,9 +231,117 @@ class CarDisplay(         override fun onStop() {             clockView?.removeCallbacks(ticker)             clockView = null+            mediaTitle = null+            mediaSubtitle = null+            mediaState = null+            mediaProgress = null+            mediaCard = null             super.onStop()         } +        /**+         * Applies a snapshot to the now-playing card. Main thread only: called+         * from the posted update in [setNowPlaying], or from `onCreate` above+         * for a snapshot that arrived before the views existed.+         */+        fun updateNowPlaying(info: NowPlayingInfo) {+            val title = mediaTitle ?: return+            val subtitle = mediaSubtitle ?: return+            val state = mediaState ?: return+            title.text = info.title ?: context.getString(R.string.car_now_playing_unknown)+            subtitle.text = info.artist ?: context.getString(R.string.car_now_playing_unknown_artist)+            state.text = context.getString(+                if (info.playing) R.string.car_now_playing_playing+                else R.string.car_now_playing_paused,+            )+            val progress = mediaProgress ?: return+            val fraction = progressFraction(info.positionMs, info.durationMs)+            val bar = mediaCard ?: return+            // Resize the fill once laid out: the bar width is only known after+            // the layout pass, and the encoder surface picks the re-layout up on+            // the next frame.+            progress.post {+                val total = bar.width+                if (total > 0) {+                    progress.layoutParams = progress.layoutParams.apply {+                        width = (total * fraction).toInt().coerceIn(0, total)+                    }+                    progress.requestLayout()+                }+            }+        }++        /**+         * The single now-playing layout (Phase 4 time-box): card, title, artist,+         * state, progress bar. Tapping anywhere on the card toggles playback.+         */+        private fun nowPlayingCard(): LinearLayout {+            val card = LinearLayout(context).apply {+                orientation = LinearLayout.VERTICAL+                setBackgroundColor(Color.parseColor("#1B2430"))+                setPadding(dp(24), dp(16), dp(24), dp(16))+                layoutParams = LinearLayout.LayoutParams(MATCH, WRAP)+                isClickable = true+                isFocusable = true+            }+            card.addView(+                TextView(context).apply {+                    text = context.getString(R.string.car_now_playing)+                    setTextColor(Color.parseColor("#8AB4F8"))+                    textSize = 14f+                },+            )+            card.addView(+                TextView(context).apply {+                    textSize = 24f+                    setTextColor(Color.WHITE)+                    mediaTitle = this+                },+            )+            card.addView(+                TextView(context).apply {+                    textSize = 16f+                    setTextColor(Color.parseColor("#C7CFD9"))+                    mediaSubtitle = this+                },+            )+            card.addView(+                TextView(context).apply {+                    textSize = 14f+                    setTextColor(Color.parseColor("#8AB4F8"))+                    mediaState = this+                },+            )+            val track = View(context).apply {+                setBackgroundColor(Color.parseColor("#2A3138"))+                layoutParams = LinearLayout.LayoutParams(MATCH, dp(4)).apply {+                    topMargin = dp(12)+                }+            }+            card.addView(track)+            val fill = View(context).apply {+                setBackgroundColor(Color.parseColor("#8AB4F8"))+                layoutParams = LinearLayout.LayoutParams(0, dp(4)).apply {+                    topMargin = dp(-4)+                }+                mediaProgress = this+            }+            card.addView(fill)+            card.setOnClickListener { onMediaTap() }+            // Report layout bounds for ch8 tap routing once the view is placed.+            card.viewTreeObserver.addOnGlobalLayoutListener(+                object : android.view.ViewTreeObserver.OnGlobalLayoutListener {+                    override fun onGlobalLayout() {+                        val loc = IntArray(2)+                        card.getLocationOnScreen(loc)+                        onCardBounds(loc[0], loc[1], loc[0] + card.width, loc[1] + card.height)+                    }+                },+            )+            mediaCard = card+            return card+        }+         private fun statusBar(): LinearLayout {             val bar = LinearLayout(context).apply {                 orientation = LinearLayout.HORIZONTAL@@ -260,9 +446,25 @@ class CarDisplay(             const val COLUMNS = 3             const val UNDEFINED_COLUMN = GridLayout.UNDEFINED             val FILL: GridLayout.Alignment = GridLayout.FILL++            /** Progress fraction in [0,1]; half (indeterminate-ish) with no duration. */+            fun progressFraction(positionMs: Long, durationMs: Long?): Float {+                val duration = durationMs?.takeIf { it > 0 } ?: return 0.5f+                return (positionMs.coerceAtLeast(0).toFloat() / duration).coerceIn(0f, 1f)+            }         }     } +    /**+     * Now-playing card bounds in display pixels, for ch8 tap routing.+     * Compared in presentation root-view coordinates, which are 1:1 with+     * display pixels on a virtual display.+     */+    private data class TapBounds(val left: Int, val top: Int, val right: Int, val bottom: Int) {+        fun contains(x: Float, y: Float): Boolean =+            x >= left && x <= right && y >= top && y <= bottom+    }+     private companion object {         const val DISPLAY_NAME = "MA Auto"         const val TAG = "MaAuto.Display"
auto/src/main/java/com/vayunmathur/auto/platform/MediaNowPlaying.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/MediaNowPlaying.kt b/auto/src/main/java/com/vayunmathur/auto/platform/MediaNowPlaying.ktnew file mode 100644index 0000000000..db466c4bfa--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/MediaNowPlaying.kt@@ -0,0 +1,34 @@+package com.vayunmathur.auto.platform++/**+ * Whatever the on-device media session is playing right now.+ *+ * Sourced from the phone's media browser service (MA Music's `PlaybackService`+ * or any declared `MediaBrowserService`) and shown in two places: the+ * now-playing card rendered into the ch2 video stream, and the phone status+ * screen. A snapshot, not a live player handle: the position is where playback+ * was when the session last reported, so progress may lag the music by a beat.+ */+data class NowPlayingInfo(+    /** Track title, or null when the session reports none. */+    val title: String?,+    /** Track artist, or null when the session reports none. */+    val artist: String?,+    /** True while audio is actually coming out. */+    val playing: Boolean,+    /** Position in millis at snapshot time, clamped at zero. */+    val positionMs: Long,+    /** Track length in millis, or null when the session does not know it. */+    val durationMs: Long?,+)++/**+ * Something the media monitor observed, forwarded to [AutoSessionState] for the phone UI.+ *+ * Streaming never waits on these: they are fire-and-forget observations, mirroring+ * [VideoEvent].+ */+sealed interface MediaEvent {+    /** The media session reported a new snapshot. */+    data class NowPlayingChanged(val info: NowPlayingInfo) : MediaEvent+}
auto/src/main/java/com/vayunmathur/auto/platform/MediaPlaybackMonitor.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/MediaPlaybackMonitor.kt b/auto/src/main/java/com/vayunmathur/auto/platform/MediaPlaybackMonitor.ktnew file mode 100644index 0000000000..e9f11f55b4--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/MediaPlaybackMonitor.kt@@ -0,0 +1,130 @@+package com.vayunmathur.auto.platform++import android.content.ComponentName+import android.content.Context+import android.content.Intent+import android.os.Handler+import android.os.Looper+import android.util.Log+import androidx.media3.common.MediaMetadata+import androidx.media3.common.Player+import androidx.media3.common.Timeline+import androidx.media3.session.MediaController+import androidx.media3.session.SessionToken++/**+ * Watches the on-device media session and publishes snapshots.+ *+ * Binds a [MediaController] to MA Music's `PlaybackService` (or, if that is+ * not installed, the first declared `MediaBrowserService`) and forwards every+ * metadata / playback-state change as a [NowPlayingInfo] snapshot. The+ * controller is read-only here except for [toggle]: playback itself stays in+ * the music app, and the GAL 11/12 media channels stay unspoken -- this is the+ * Phase 4 replacement for them.+ *+ * All session work hops to the main thread; [onUpdate] may be invoked from any+ * thread, so sinks must be thread-safe (a `StateFlow` set, a main-posted view+ * update) rather than doing work inline.+ */+class MediaPlaybackMonitor(+    private val context: Context,+    private val onUpdate: (NowPlayingInfo) -> Unit,+) {+    private val mainHandler = Handler(Looper.getMainLooper())+    private var controller: MediaController? = null++    private val listener = object : Player.Listener {+        override fun onMediaMetadataChanged(metadata: MediaMetadata) = publish()+        override fun onIsPlayingChanged(isPlaying: Boolean) = publish()+        override fun onPlaybackStateChanged(playbackState: Int) = publish()+        override fun onTimelineChanged(timeline: Timeline, reason: Int) = publish()+    }++    /**+     * Binds to the media session. Safe from any thread; the bind hops to the+     * main thread because session binding is a lifecycle operation. With no+     * browser service on the phone this logs and leaves now-playing empty.+     */+    fun start() {+        mainHandler.post {+            val component = resolveMediaSession() ?: run {+                Log.w(TAG, "no media browser service; now-playing stays empty")+                return@post+            }+            val future =+                MediaController.Builder(context, SessionToken(context, component)).buildAsync()+            future.addListener(+                {+                    val connected = runCatching { future.get() }.getOrNull()+                    mainHandler.post { onConnected(connected) }+                },+                { it.run() },+            )+        }+    }++    /** Toggles phone playback from the car card's tap target. Safe from any thread. */+    fun toggle() {+        mainHandler.post {+            val active = controller ?: return@post+            if (active.isPlaying) active.pause() else active.play()+        }+    }++    /** Drops the controller. Safe from any thread. */+    fun stop() {+        mainHandler.post {+            controller?.removeListener(listener)+            runCatching { controller?.release() }+            controller = null+        }+    }++    private fun onConnected(connected: MediaController?) {+        if (connected == null) {+            Log.w(TAG, "media controller connect failed; now-playing stays empty")+            return+        }+        connected.addListener(listener)+        controller = connected+        publish()+    }++    private fun publish() {+        val active = controller ?: return+        val metadata = active.mediaMetadata+        onUpdate(+            NowPlayingInfo(+                title = metadata.title?.toString(),+                artist = metadata.artist?.toString(),+                playing = active.isPlaying,+                positionMs = active.currentPosition.coerceAtLeast(0),+                durationMs = active.duration.takeIf { it >= 0 },+            ),+        )+    }++    /**+     * Resolves the session to watch, preferring MA Music.+     *+     * The class name is a string on purpose: the auto module must not take a+     * compile dependency on the music app module, and the manifest already+     * queries this exact package plus the generic browse action, so both+     * lookups below stay visible to PackageManager.+     */+    private fun resolveMediaSession(): ComponentName? {+        val pm = context.packageManager+        val direct = ComponentName(MUSIC_PACKAGE, MUSIC_SERVICE_CLASS)+        if (runCatching { pm.getServiceInfo(direct, 0) }.isSuccess) return direct+        // Fallback: anything declaring a browsable media surface.+        val browse = Intent("android.media.browse.MediaBrowserService")+        val info = pm.queryIntentServices(browse, 0).firstOrNull()?.serviceInfo ?: return null+        return ComponentName(info.packageName, info.name)+    }++    private companion object {+        const val TAG = "MaAuto.Media"+        const val MUSIC_PACKAGE = "com.vayunmathur.music"+        const val MUSIC_SERVICE_CLASS = "com.vayunmathur.music.service.PlaybackService"+    }+}
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 9a24f19cbe..77ef0d615f 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.kt@@ -47,6 +47,14 @@ class VideoSinkChannel(     private var configurationIndex = 0     private var firstFrameSent = false +    /**+     * Where the car card's now-playing comes from and where its taps go.+     * [get] is read when the render pair comes up (plus every snapshot pushed+     * via [setNowPlaying]); [onTap] toggles phone playback. `null` until the+     * service wires the media monitor -- unset means the card shows empty.+     */+    private var nowPlayingSource: NowPlayingSource? = null+     /**      * Frames emitted since the last [pumpEncoder] call. `drain()` invokes      * [sendFrame] synchronously, so snapshotting after it returns counts exactly@@ -60,6 +68,21 @@ class VideoSinkChannel(      val channelId: Int get() = service.id +    /** Wires the now-playing feed from the media monitor; see [nowPlayingSource]. */+    fun setNowPlayingSource(get: () -> NowPlayingInfo?, onTap: () -> Unit) {+        nowPlayingSource = NowPlayingSource(get, onTap)+        nowPlayingSource?.get()?.let { display?.setNowPlaying(it) }+    }++    /**+     * Pushes one snapshot to the car card, if the render pair is up. The+     * service calls this on every media-monitor update so the card tracks+     * playback without waiting for the encoder pump.+     */+    fun setNowPlaying(info: NowPlayingInfo) {+        display?.setNowPlaying(info)+    }+     /** Step 1. Called once the channel is open. */     fun requestSetup() {         connection.send(@@ -152,6 +175,9 @@ class VideoSinkChannel(          val surface = checkNotNull(encoder.surface) { "encoder produced no input surface" }         display = CarDisplay(context, width, height, density).also {+            val source = nowPlayingSource+            it.onMediaTap = source?.onTap+            source?.get()?.let(it::setNowPlaying)             it.show(surface)         }         // The render pair is up: a private virtual display compositing straight into@@ -259,3 +285,13 @@ class VideoSinkChannel(         const val DEFAULT_DENSITY = 160     } }++/**+ * Where a video channel's car now-playing card reads from and writes to.+ * [get] returns the latest snapshot (or null before the session reports);+ * [onTap] toggles phone playback when the card is tapped, locally or via ch8.+ */+data class NowPlayingSource(+    val get: () -> NowPlayingInfo?,+    val onTap: () -> Unit,+)
auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt b/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.ktindex 3f1058b186..64df0f373b 100644--- a/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt+++ b/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt@@ -12,12 +12,15 @@ import android.util.Log import com.vayunmathur.auto.R import com.vayunmathur.auto.network.HeadUnitServer import com.vayunmathur.auto.platform.AutoSessionState+import com.vayunmathur.auto.platform.MediaEvent+import com.vayunmathur.auto.platform.MediaPlaybackMonitor import com.vayunmathur.auto.platform.VideoSinkChannel import com.vayunmathur.auto.protocol.GalConnection import com.vayunmathur.auto.protocol.GalCredential import com.vayunmathur.auto.protocol.GalService import com.vayunmathur.auto.protocol.SessionState import com.vayunmathur.auto.protocol.StreamTransport+import com.vayunmathur.auto.protocol.isMediaBrowserChannel import kotlin.concurrent.thread  /**@@ -39,6 +42,12 @@ class ProjectionService : Service() {         running = true         startForeground(NOTIFICATION_ID, notification())         publishCredentialExpiry()+        // The now-playing feed outlives any one session: the phone card shows it+        // between connections, and the car card picks the latest up on bring-up.+        mediaMonitor = MediaPlaybackMonitor(this) { info ->+            AutoSessionState.onMediaEvent(MediaEvent.NowPlayingChanged(info))+            video?.setNowPlaying(info)+        }.also { it.start() }         worker = thread(name = "ma-auto-projection") { serve() }         return START_STICKY     }@@ -46,6 +55,8 @@ class ProjectionService : Service() {     override fun onDestroy() {         running = false         worker?.interrupt()+        mediaMonitor?.stop()+        mediaMonitor = null         super.onDestroy()     } @@ -68,7 +79,14 @@ class ProjectionService : Service() {                 deviceModel = Build.MODEL,                 deviceManufacturer = Build.MANUFACTURER,                 onChannelMessage = { message ->-                    video?.onMessage(message.channelId, message.type, message.payload)+                    if (isMediaBrowserChannel(message.channelId)) {+                        // GAL 11/12 gap: the channel message IDs are unmapped, so+                        // these are observed and ignored, never answered. Now-playing+                        // rides the ch2 video stream instead.+                        Log.d(TAG, "ignoring media-browser message on ch${message.channelId}")+                    } else {+                        video?.onMessage(message.channelId, message.type, message.payload)+                    }                 },                 trace = { Log.d(TAG, it) },             )@@ -104,6 +122,9 @@ class ProjectionService : Service() {      private var video: VideoSinkChannel? = null +    /** Outlives sessions; owned by the service, not the pump thread. */+    private var mediaMonitor: MediaPlaybackMonitor? = null+     /**      * Seeds the credential-expiry flow once per service start, off the pump thread.      *@@ -146,6 +167,12 @@ class ProjectionService : Service() {         Log.i(TAG, "requesting channel open for service ${next.id}")         if (next.id == GalService.VIDEO_SINK.id && next.hasMediaSink()) {             video = VideoSinkChannel(this, next, connection, AutoSessionState::onVideoEvent)+                .also { sink ->+                    sink.setNowPlayingSource(+                        get = { AutoSessionState.nowPlaying.value },+                        onTap = { mediaMonitor?.toggle() },+                    )+                }         }     } 
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 609fb7e3b3..d5784e9fae 100644--- a/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt+++ b/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt@@ -14,6 +14,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.auto.R import com.vayunmathur.auto.platform.AutoConnectionState import com.vayunmathur.auto.platform.AutoViewModel+import com.vayunmathur.auto.platform.NowPlayingInfo import com.vayunmathur.auto.platform.VideoInfo import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Card@@ -41,6 +42,7 @@ fun AutoScreen(viewModel: AutoViewModel) {         surfaceValid = viewModel.surfaceValid.collectAsStateWithLifecycle().value,         credentialDaysLeft = viewModel.credentialDaysLeft.collectAsStateWithLifecycle().value,         sessionStartedAt = viewModel.sessionStartedAt.collectAsStateWithLifecycle().value,+        nowPlaying = viewModel.nowPlaying.collectAsStateWithLifecycle().value,     )     val scrollBehavior = appBarScrollBehavior()     AppScaffold(@@ -93,6 +95,8 @@ data class SessionSnapshot(     /** Whole days until the shipped GAL leaf expires; null until the service seeds it. */     val credentialDaysLeft: Long?,     val sessionStartedAt: Long?,+    /** Latest now-playing snapshot; null until the media session reports. */+    val nowPlaying: NowPlayingInfo?, )  @Composable
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 66e0a943dc..17b0c6e271 100644--- a/auto/src/main/java/com/vayunmathur/auto/ui/SessionCard.kt+++ b/auto/src/main/java/com/vayunmathur/auto/ui/SessionCard.kt@@ -11,6 +11,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import com.vayunmathur.auto.R+import com.vayunmathur.auto.platform.NowPlayingInfo import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.Text@@ -107,11 +108,40 @@ fun SessionCard(session: SessionSnapshot, modifier: Modifier = Modifier) {                 },             )             SessionElapsedRow(sessionStartedAt = session.sessionStartedAt)+            NowPlayingRow(nowPlaying = session.nowPlaying)             CredentialRow(daysLeft = session.credentialDaysLeft)         }     } } +/**+ * What the on-device media session is playing: track, artist, playback state.+ * Null until the session reports; kept after disconnect like the video line so+ * the last-known state stays visible between sessions.+ */+@Composable+private fun NowPlayingRow(nowPlaying: NowPlayingInfo?) {+    if (nowPlaying == null) {+        ListItem(+            headlineContent = { Text(stringResource(R.string.session_now_playing)) },+            supportingContent = { Text(stringResource(R.string.session_now_playing_none)) },+        )+        return+    }+    val title = nowPlaying.title ?: stringResource(R.string.session_now_playing_unknown)+    val artist = nowPlaying.artist ?: stringResource(R.string.session_now_playing_unknown_artist)+    val state = stringResource(+        if (nowPlaying.playing) R.string.session_now_playing_playing+        else R.string.session_now_playing_paused,+    )+    ListItem(+        headlineContent = { Text(stringResource(R.string.session_now_playing)) },+        supportingContent = {+            Text(stringResource(R.string.session_now_playing_value, title, artist, state))+        },+    )+}+ /**  * GAL leaf expiry: quiet count while far out, escalating warnings at 90/30/7 days,  * expired notice at zero. Thresholds live here next to the rows they drive so a
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 a25bab70fd..ad4e9e1a6c 100644--- a/auto/src/main/res/values/strings.xml+++ b/auto/src/main/res/values/strings.xml@@ -116,6 +116,22 @@     <!-- Shown when there is no active session to time. -->     <string name="session_elapsed_none">โ€”</string> +    <!-- Heading of the row showing what the on-device media session is playing. -->+    <string name="session_now_playing">Now playing</string>+    <!-- Shown on the session card before the media session has reported. -->+    <string name="session_now_playing_none">No media yet</string>+    <!-- Track and artist with playback state. %1$s is the track title, %2$s the+         artist, %3$s the state ("Playing" or "Paused" below). -->+    <string name="session_now_playing_value"><xliff:g example="Midnight City" id="title">%1$s</xliff:g> โ€” <xliff:g example="M83" id="artist">%2$s</xliff:g> (<xliff:g example="Playing" id="state">%3$s</xliff:g>)</string>+    <!-- Playback state shown in the now-playing row and on the car now-playing card. -->+    <string name="session_now_playing_playing">Playing</string>+    <!-- Playback state shown in the now-playing row and on the car now-playing card. -->+    <string name="session_now_playing_paused">Paused</string>+    <!-- Shown when the media session reports no title. -->+    <string name="session_now_playing_unknown">Unknown track</string>+    <!-- Shown when the media session reports no artist. -->+    <string name="session_now_playing_unknown_artist">Unknown artist</string>+     <!-- Notification channel name for the ongoing projection session. -->     <string name="projection_channel">Projection</string>     <!-- Ongoing notification shown while a car is connected. -->@@ -123,6 +139,16 @@      <!-- Second line of the car status bar, under the product name. -->     <string name="car_connected">Connected</string>+    <!-- Heading of the single now-playing card on the car display (Phase 4 time-box). -->+    <string name="car_now_playing">Now playing</string>+    <!-- Shown on the car card while audio is playing. -->+    <string name="car_now_playing_playing">Playing</string>+    <!-- Shown on the car card while playback is paused. -->+    <string name="car_now_playing_paused">Paused</string>+    <!-- Shown on the car card when the media session reports no title. -->+    <string name="car_now_playing_unknown">Unknown track</string>+    <!-- Shown on the car card when the media session reports no artist. -->+    <string name="car_now_playing_unknown_artist">Unknown artist</string>     <!-- Shown on the car display when no launchable apps were found on the phone. -->     <string name="car_no_apps">No apps available โ€” install Maps or Music to get started</string> </resources>