maauto: session bridge, phone status card, car launcher
- Commit
601e1d1a6a84a47bfddf960abfe0e56400cd9ca8- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-12 17:08 UTC (2 months ago)
- Parents
8d2e8db
Diff
auto/src/main/AndroidManifest.xml
diff --git a/auto/src/main/AndroidManifest.xml b/auto/src/main/AndroidManifest.xmlindex 631c4ab629..710d20ffed 100644--- a/auto/src/main/AndroidManifest.xml+++ b/auto/src/main/AndroidManifest.xml@@ -16,6 +16,20 @@ filter below does not satisfy it on its own. --> <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. -->+ <queries>+ <package android:name="com.vayunmathur.maps" />+ <package android:name="com.vayunmathur.music" />+ <intent>+ <action android:name="android.media.browse.MediaBrowserService" />+ </intent>+ <intent>+ <action android:name="android.intent.action.DIAL" />+ <data android:scheme="tel" />+ </intent>+ </queries>+ <application android:allowBackup="false" android:dataExtractionRules="@xml/data_extraction_rules"
auto/src/main/java/com/vayunmathur/auto/Navigation.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/Navigation.kt b/auto/src/main/java/com/vayunmathur/auto/Navigation.ktindex d637260735..ed862ab043 100644--- a/auto/src/main/java/com/vayunmathur/auto/Navigation.kt+++ b/auto/src/main/java/com/vayunmathur/auto/Navigation.kt@@ -11,7 +11,7 @@ fun Navigation(viewModel: AutoViewModel) { val backStack = rememberNavBackStack<Route>(Route.Home) MainNavigation(backStack) { entry<Route.Home> {- AutoScreen(state = viewModel.state)+ AutoScreen(viewModel = viewModel) } } }
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.ktnew file mode 100644index 0000000000..6c83dae78a--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AutoSessionState.kt@@ -0,0 +1,121 @@+package com.vayunmathur.auto.platform++import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/** The video stream the head unit accepted, for the phone status screen. */+data class VideoInfo(+ val width: Int,+ val height: Int,+ val frameRate: Int,+ val configIndex: Int,+)++/**+ * Something the video channel observed, forwarded to [AutoSessionState] for the phone UI.+ *+ * Streaming never waits on these: they are fire-and-forget observations, and the service+ * forwards them without gating any protocol step on the UI.+ */+sealed interface VideoEvent {+ /** The head unit accepted video; these are the parameters it chose. */+ data class Setup(val info: VideoInfo) : VideoEvent++ /** Video focus moved, e.g. to `VIDEO_FOCUS_NATIVE` when the car takes the screen back. */+ data class FocusChanged(val mode: String) : VideoEvent++ /** The first encoded frame went out. */+ data object FirstFrame : VideoEvent++ /** One encoded frame went out. */+ data object FrameSent : VideoEvent++ /** The head unit acknowledged frames. */+ data object AckReceived : 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+}++/**+ * The bridge between the projection session and the phone UI.+ *+ * The session runs on the single `ma-auto-projection` worker thread and the ViewModel lives+ * on the main thread, so they share nothing but these flows. Setting a [MutableStateFlow]+ * value is thread-safe, which is what makes worker-thread emission safe here; the encoder+ * pump itself stays single-threaded exactly as before.+ */+object AutoSessionState {+ private val _connection =+ MutableStateFlow<AutoConnectionState>(AutoConnectionState.Disconnected)+ val connection: StateFlow<AutoConnectionState> = _connection.asStateFlow()++ private val _video = MutableStateFlow<VideoInfo?>(null)+ val video: StateFlow<VideoInfo?> = _video.asStateFlow()++ private val _focusMode = MutableStateFlow<String?>(null)+ val focusMode: StateFlow<String?> = _focusMode.asStateFlow()++ private val _framesSent = MutableStateFlow(0L)+ val framesSent: StateFlow<Long> = _framesSent.asStateFlow()++ private val _acksSeen = MutableStateFlow(0L)+ val acksSeen: StateFlow<Long> = _acksSeen.asStateFlow()++ private val _ackMismatches = MutableStateFlow(0L)+ val ackMismatches: StateFlow<Long> = _ackMismatches.asStateFlow()++ /** 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()++ /** A socket was accepted; version negotiation and the TLS handshake are next. */+ fun onSocketAccepted() {+ _video.value = null+ _focusMode.value = null+ _framesSent.value = 0+ _acksSeen.value = 0+ _ackMismatches.value = 0+ _sessionStartedAt.value = null+ _connection.value = AutoConnectionState.Connecting+ }++ /** Discovery completed and the bring-up is running against [carName]. */+ fun onActive(carName: String) {+ _sessionStartedAt.value = System.currentTimeMillis()+ _connection.value = AutoConnectionState.Projecting(carName)+ }++ /** The link came up but authentication failed, or the session otherwise refused us. */+ fun onRejected() {+ _connection.value = AutoConnectionState.Rejected+ }++ /** The head unit went away cleanly. */+ fun onDisconnected() {+ _connection.value = AutoConnectionState.Disconnected+ _video.value = null+ _focusMode.value = null+ _sessionStartedAt.value = null+ }++ /** End of a session: a recorded failure means refusal, anything else a clean parting. */+ fun onSessionEnd(failure: String?) {+ if (failure != null) onRejected() else onDisconnected()+ }++ fun onVideoEvent(event: VideoEvent) {+ when (event) {+ 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.AckMismatch -> {+ _acksSeen.value+++ _ackMismatches.value+++ }+ }+ }+}
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 6b9fe1b586..3ab6e7f1eb 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt@@ -1,12 +1,40 @@ package com.vayunmathur.auto.platform -import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.stateIn -/** Holds what the status screen shows. The projection session will drive this. */+/**+ * What the phone status screen shows, driven by the projection session.+ *+ * The session runs on its own worker thread and publishes to [AutoSessionState]; this+ * ViewModel only re-exposes those flows on a scope the UI can collect. It never writes.+ */ class AutoViewModel : ViewModel() {- var state: AutoConnectionState by mutableStateOf(AutoConnectionState.Disconnected)- private set+ val connection: StateFlow<AutoConnectionState> = AutoSessionState.connection+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), AutoConnectionState.Disconnected)++ val video: StateFlow<VideoInfo?> = AutoSessionState.video+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), null)++ val focusMode: StateFlow<String?> = AutoSessionState.focusMode+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), null)++ val framesSent: StateFlow<Long> = AutoSessionState.framesSent+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), 0L)++ val acksSeen: StateFlow<Long> = AutoSessionState.acksSeen+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), 0L)++ val ackMismatches: StateFlow<Long> = AutoSessionState.ackMismatches+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), 0L)++ val sessionStartedAt: StateFlow<Long?> = AutoSessionState.sessionStartedAt+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), null)++ private companion object {+ const val STOP_TIMEOUT_MS = 5_000L+ } }
auto/src/main/java/com/vayunmathur/auto/platform/CarApps.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarApps.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarApps.ktnew file mode 100644index 0000000000..4c16fd8455--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarApps.kt@@ -0,0 +1,99 @@+package com.vayunmathur.auto.platform++import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.graphics.drawable.Drawable+import android.util.Log++/** One tile on the car launcher: an icon, a label, and how to open it. */+data class CarApp(+ val label: CharSequence,+ val icon: Drawable?,+ val launch: Intent,+)++/**+ * Which apps the car launcher shows.+ *+ * The app-inventory pass (Task 10) found no third-party Android Auto targets on the phone,+ * so the launcher resolves Modern Apps siblings plus the platform's own media surfaces:+ * navigation goes to MA Maps, audio to MA Music's media browser service or any declared+ * `MediaBrowserService`, and telephony to the system dialer. Whatever is not installed+ * is skipped rather than shown dead, and an empty grid gets an explicit empty state.+ */+object CarApps {+ fun query(context: Context): List<CarApp> {+ val pm = context.packageManager+ val found = mutableListOf<CarApp>()+ for (slot in SLOTS) {+ runCatching { slot.resolve(context, pm) }+ .onSuccess { app -> if (app != null) found += app }+ .onFailure { Log.w(TAG, "could not resolve car slot ${slot.label}", it) }+ }+ return found+ }++ private interface Slot {+ val label: String+ fun resolve(context: Context, pm: PackageManager): CarApp?+ }++ private fun launcherApp(+ context: Context,+ pm: PackageManager,+ packageName: String,+ ): CarApp? {+ val intent = pm.getLaunchIntentForPackage(packageName) ?: return null+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ val info = pm.getApplicationInfo(packageName, 0)+ return CarApp(+ label = pm.getApplicationLabel(info),+ icon = pm.getApplicationIcon(info),+ launch = intent,+ )+ }++ private val SLOTS: List<Slot> = listOf(+ object : Slot {+ override val label = "maps"+ override fun resolve(context: Context, pm: PackageManager): CarApp? =+ launcherApp(context, pm, "com.vayunmathur.maps")+ },+ object : Slot {+ override val label = "music"+ override fun resolve(context: Context, pm: PackageManager): CarApp? {+ val direct = runCatching {+ launcherApp(context, pm, "com.vayunmathur.music")+ }.getOrNull()+ if (direct != null) return direct+ // Fallback: anything declaring a browsable media surface.+ val browse = Intent("android.media.browse.MediaBrowserService")+ val services = pm.queryIntentServices(browse, 0)+ val service = services.firstOrNull() ?: return null+ val info = service.serviceInfo+ return CarApp(+ label = info.loadLabel(pm),+ icon = info.loadIcon(pm),+ launch = pm.getLaunchIntentForPackage(info.packageName)+ ?: Intent(Intent.ACTION_VIEW).setPackage(info.packageName),+ )+ }+ },+ object : Slot {+ override val label = "phone"+ override fun resolve(context: Context, pm: PackageManager): CarApp? {+ val dial = Intent(Intent.ACTION_DIAL).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ val activity = dial.resolveActivity(pm) ?: return null+ val info = pm.getActivityInfo(activity, 0)+ return CarApp(+ label = info.loadLabel(pm),+ icon = info.loadIcon(pm),+ launch = dial,+ )+ }+ },+ )++ private const val TAG = "MaAuto.CarApps"+}
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 9e7d8466bb..8164472d66 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt@@ -10,9 +10,15 @@ import android.os.Handler import android.os.Looper import android.view.Gravity import android.view.Surface+import android.view.View import android.view.ViewGroup+import android.widget.GridLayout+import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView+import com.vayunmathur.auto.R+import java.text.DateFormat+import java.util.Date import java.util.concurrent.ExecutionException import java.util.concurrent.FutureTask @@ -98,52 +104,159 @@ class CarDisplay( } /**- * A placeholder car UI.+ * The car launcher: a driving-safe home screen with a status bar and big app tiles. *- * Something unmistakably ours and unmistakably live, so a successful projection is- * obvious at a glance and a frozen one is obvious too. The real driving-safe interface- * replaces this.+ * Deliberately Views, not Compose: a `Presentation` on a private virtual display has+ * no Compose lifecycle owner, and Views render into the encoder surface with no+ * 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 var clockView: TextView? = null+ private val timeFormat: DateFormat = DateFormat.getTimeInstance(DateFormat.SHORT)++ // 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+ // moving digits still prove frames are flowing rather than one stale image.+ private val ticker = object : Runnable {+ override fun run() {+ val view = clockView ?: return+ view.text = timeFormat.format(Date())+ view.postDelayed(this, 1000)+ }+ }+ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val root = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL- gravity = Gravity.CENTER setBackgroundColor(Color.parseColor("#101418")) layoutParams = ViewGroup.LayoutParams(MATCH, MATCH) }- root.addView(+ root.addView(statusBar())+ root.addView(divider())+ val apps = CarApps.query(context)+ root.addView(if (apps.isEmpty()) emptyState() else appGrid(apps))+ setContentView(root)++ clockView?.let {+ it.text = timeFormat.format(Date())+ it.post(ticker)+ }+ }++ override fun onStop() {+ clockView?.removeCallbacks(ticker)+ clockView = null+ super.onStop()+ }++ private fun statusBar(): LinearLayout {+ val bar = LinearLayout(context).apply {+ orientation = LinearLayout.HORIZONTAL+ gravity = Gravity.CENTER_VERTICAL+ setPadding(dp(24), dp(16), dp(24), dp(16))+ }+ val titles = LinearLayout(context).apply {+ orientation = LinearLayout.VERTICAL+ layoutParams = LinearLayout.LayoutParams(0, WRAP, 1f)+ }+ titles.addView( TextView(context).apply {- text = "MA Auto"+ text = context.getString(R.string.app_name) setTextColor(Color.WHITE)- textSize = 40f- gravity = Gravity.CENTER+ textSize = 28f }, )+ titles.addView(+ TextView(context).apply {+ text = context.getString(R.string.car_connected)+ setTextColor(Color.parseColor("#8AB4F8"))+ textSize = 16f+ },+ )+ bar.addView(titles) val clock = TextView(context).apply {- setTextColor(Color.parseColor("#8AB4F8"))- textSize = 20f- gravity = Gravity.CENTER+ setTextColor(Color.WHITE)+ textSize = 24f+ gravity = Gravity.END }- root.addView(clock)- setContentView(root)+ clockView = clock+ bar.addView(clock)+ return bar+ } - // A moving element proves frames are still flowing rather than one stale image.- val ticker = object : Runnable {- private var seconds = 0- override fun run() {- clock.text = "projecting — ${seconds++}s"- clock.postDelayed(this, 1000)+ private fun divider(): View = View(context).apply {+ setBackgroundColor(Color.parseColor("#2A3138"))+ layoutParams = LinearLayout.LayoutParams(MATCH, dp(1))+ }++ private fun appGrid(apps: List<CarApp>): GridLayout {+ return GridLayout(context).apply {+ columnCount = COLUMNS+ setPadding(dp(16), dp(8), dp(16), dp(16))+ layoutParams = LinearLayout.LayoutParams(MATCH, 0, 1f)+ apps.forEach { app ->+ addView(+ appCell(app).apply {+ layoutParams = GridLayout.LayoutParams().apply {+ width = 0+ columnSpec = GridLayout.spec(UNDEFINED_COLUMN, 1, FILL, 1f)+ }+ },+ ) } }- clock.post(ticker) } + private fun appCell(app: CarApp): LinearLayout {+ return LinearLayout(context).apply {+ orientation = LinearLayout.VERTICAL+ gravity = Gravity.CENTER+ setPadding(dp(8), dp(16), dp(8), dp(16))+ isClickable = true+ isFocusable = true+ addView(+ ImageView(context).apply {+ setImageDrawable(app.icon)+ contentDescription = app.label.toString()+ layoutParams = LinearLayout.LayoutParams(dp(72), dp(72))+ },+ )+ addView(+ TextView(context).apply {+ text = app.label.toString()+ setTextColor(Color.WHITE)+ textSize = 16f+ gravity = Gravity.CENTER+ setPadding(0, dp(8), 0, 0)+ },+ )+ setOnClickListener { context.startActivity(app.launch) }+ }+ }++ private fun emptyState(): TextView {+ return TextView(context).apply {+ text = context.getString(R.string.car_no_apps)+ setTextColor(Color.parseColor("#8AB4F8"))+ textSize = 20f+ gravity = Gravity.CENTER+ layoutParams = LinearLayout.LayoutParams(MATCH, 0, 1f)+ }+ }++ private fun dp(value: Int): Int =+ (value * context.resources.displayMetrics.density).toInt()+ private companion object { const val MATCH = ViewGroup.LayoutParams.MATCH_PARENT+ const val WRAP = ViewGroup.LayoutParams.WRAP_CONTENT+ const val COLUMNS = 3+ const val UNDEFINED_COLUMN = GridLayout.UNDEFINED+ val FILL: GridLayout.Alignment = GridLayout.FILL } }
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 100a0f8533..7a3afe44d7 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.kt@@ -32,11 +32,17 @@ class VideoSinkChannel( private val context: Context, private val service: Service, private val connection: GalConnection,+ /**+ * Fire-and-forget observations for the phone status screen. Never blocks and never+ * gates streaming: the service forwards these to the session state without waiting.+ */+ private val onEvent: (VideoEvent) -> Unit = {}, ) { private var display: CarDisplay? = null private var encoder: VideoEncoder? = null private var sessionId = -1 private var configurationIndex = 0+ private var firstFrameSent = false /** Chosen from what the head unit advertised in discovery. */ private val configuration: VideoConfiguration? =@@ -82,6 +88,7 @@ class VideoSinkChannel( private fun onFocus(payload: ByteArray) { val mode = VideoFocusIndication.parseFrom(payload).mode Log.i(TAG, "video focus is now $mode")+ onEvent(VideoEvent.FocusChanged(mode.name)) // Regaining the screen needs a fresh keyframe; the head unit has nothing to decode // against otherwise and would show garbage until the next scheduled one. if (mode == VideoFocusMode.VIDEO_FOCUS_PROJECTED) encoder?.requestKeyFrame()@@ -93,6 +100,9 @@ class VideoSinkChannel( 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) } } @@ -103,8 +113,10 @@ class VideoSinkChannel( val density = config?.density?.takeIf { it > 0 } ?: DEFAULT_DENSITY Log.i(TAG, "starting video ${width}x$height @${frameRate} dpi $density")+ onEvent(VideoEvent.Setup(VideoInfo(width, height, frameRate, configurationIndex))) sessionId = 0+ firstFrameSent = false val encoder = VideoEncoder(width, height, frameRate, onFrame = ::sendFrame) this.encoder = encoder encoder.start()@@ -126,6 +138,11 @@ class VideoSinkChannel( } private fun sendFrame(buffer: ByteBuffer, info: MediaCodec.BufferInfo) {+ if (!firstFrameSent) {+ firstFrameSent = true+ onEvent(VideoEvent.FirstFrame)+ }+ onEvent(VideoEvent.FrameSent) val bytes = ByteArray(info.size) buffer.get(bytes) // Timestamped form: an 8-byte microsecond timestamp then the access unit. Codec
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 89eab5eb0c..10dbab02dc 100644--- a/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt+++ b/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt@@ -11,6 +11,7 @@ import android.os.IBinder 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.VideoSinkChannel import com.vayunmathur.auto.protocol.GalConnection import com.vayunmathur.auto.protocol.GalCredential@@ -58,6 +59,8 @@ class ProjectionService : Service() { private fun session(server: HeadUnitServer) { server.accept().use { socket ->+ // A head unit is on the wire; the phone status screen leaves Disconnected.+ AutoSessionState.onSocketAccepted() val connection = GalConnection( transport = StreamTransport(socket.getInputStream(), socket.getOutputStream()), sslContext = GalCredential.fromAssets(assets),@@ -68,6 +71,7 @@ class ProjectionService : Service() { ) var setupVideo = false+ var reportedActive = false while (running && connection.pump()) { // Open every advertised service in HU-discovery wire order, one at a // time: the next 0x7 goes out only once the previous channel is@@ -76,6 +80,10 @@ class ProjectionService : Service() { // this same order (`jbp.i[]` follows the `xob.c` wire order). // Video setup additionally waits for its own channel grant. if (connection.session.state == SessionState.ACTIVE) {+ if (!reportedActive) {+ reportedActive = true+ AutoSessionState.onActive(CAR_NAME)+ } openNext(connection) } if (!setupVideo && GalService.VIDEO_SINK.id in connection.session.openChannels) {@@ -85,6 +93,7 @@ class ProjectionService : Service() { video?.pumpEncoder() } Log.i(TAG, "head unit disconnected: ${connection.session.failure ?: "cleanly"}")+ AutoSessionState.onSessionEnd(connection.session.failure) video?.release() video = null }@@ -116,7 +125,7 @@ class ProjectionService : Service() { connection.send(session.openChannel(next)) Log.i(TAG, "requesting channel open for service ${next.id}") if (next.id == GalService.VIDEO_SINK.id && next.hasMediaSink()) {- video = VideoSinkChannel(this, next, connection)+ video = VideoSinkChannel(this, next, connection, AutoSessionState::onVideoEvent) } } @@ -141,6 +150,13 @@ class ProjectionService : Service() { private const val CHANNEL_ID = "projection" private const val NOTIFICATION_ID = 1 + /**+ * Interim car name until the head unit reports its own. The GAL services the DHU+ * advertises carry no human-readable name, so the status screen says where the+ * pixels are going rather than guessing a make.+ */+ private const val CAR_NAME = "Desktop Head Unit"+ fun start(context: Context) { context.startForegroundService(Intent(context, ProjectionService::class.java)) }
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 c0b1d68b4d..191fa2ef25 100644--- a/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt+++ b/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt@@ -6,11 +6,15 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp+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.VideoInfo import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.ListItem@@ -18,9 +22,18 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior -/** Whether a car is attached, and what to do if one is not. */+/** Whether a car is attached, and what is running on it. */ @Composable-fun AutoScreen(state: AutoConnectionState) {+fun AutoScreen(viewModel: AutoViewModel) {+ val state by viewModel.connection.collectAsStateWithLifecycle()+ val session = SessionSnapshot(+ video = viewModel.video.collectAsStateWithLifecycle().value,+ focusMode = viewModel.focusMode.collectAsStateWithLifecycle().value,+ framesSent = viewModel.framesSent.collectAsStateWithLifecycle().value,+ acksSeen = viewModel.acksSeen.collectAsStateWithLifecycle().value,+ ackMismatches = viewModel.ackMismatches.collectAsStateWithLifecycle().value,+ sessionStartedAt = viewModel.sessionStartedAt.collectAsStateWithLifecycle().value,+ ) val scrollBehavior = appBarScrollBehavior() AppScaffold( title = stringResource(R.string.app_name),@@ -38,6 +51,7 @@ fun AutoScreen(state: AutoConnectionState) { supportingContent = { Text(state.describe()) }, ) }+ SessionCard(session = session, modifier = Modifier.padding(top = 16.dp)) Text( text = stringResource(R.string.connect_hint), style = MaterialTheme.typography.bodyMedium,@@ -47,6 +61,16 @@ fun AutoScreen(state: AutoConnectionState) { } } +/** Whatever the session card needs that is not the connection state itself. */+data class SessionSnapshot(+ val video: VideoInfo?,+ val focusMode: String?,+ val framesSent: Long,+ val acksSeen: Long,+ val ackMismatches: Long,+ val sessionStartedAt: Long?,+)+ @Composable private fun AutoConnectionState.describe(): String = when (this) { AutoConnectionState.Disconnected -> stringResource(R.string.state_disconnected)
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.ktnew file mode 100644index 0000000000..285bcc2f28--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/ui/SessionCard.kt@@ -0,0 +1,82 @@+package com.vayunmathur.auto.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import com.vayunmathur.auto.R+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.rememberClock+import kotlin.time.Duration.Companion.seconds++/** What the projection session is doing right now: video, focus, counts, elapsed time. */+@Composable+fun SessionCard(session: SessionSnapshot, modifier: Modifier = Modifier) {+ val videoLine = session.video?.let {+ stringResource(R.string.session_video, it.width, it.height, it.frameRate, it.configIndex)+ } ?: stringResource(R.string.session_video_none)+ val focusLine = session.focusMode ?: stringResource(R.string.session_focus_none)+ Card(modifier.fillMaxWidth()) {+ Column {+ ListItem(+ headlineContent = { Text(stringResource(R.string.session_headline)) },+ supportingContent = { Text(videoLine) },+ )+ ListItem(+ headlineContent = { Text(stringResource(R.string.session_focus)) },+ supportingContent = { Text(focusLine) },+ )+ ListItem(+ headlineContent = { Text(stringResource(R.string.session_frames)) },+ supportingContent = {+ Text(+ stringResource(+ R.string.session_frames_value,+ session.framesSent,+ session.acksSeen,+ ),+ )+ },+ )+ if (session.ackMismatches > 0) {+ ListItem(+ headlineContent = { Text(stringResource(R.string.session_ack_mismatch)) },+ supportingContent = {+ Text(+ stringResource(R.string.session_ack_mismatch_value, session.ackMismatches),+ )+ },+ )+ }+ SessionElapsedRow(sessionStartedAt = session.sessionStartedAt)+ }+ }+}++/** Live mm:ss counter since the session became active; a dash when there is no session. */+@Composable+private fun SessionElapsedRow(sessionStartedAt: Long?) {+ val now = rememberClock(1.seconds)+ var tick by remember { mutableLongStateOf(System.currentTimeMillis()) }+ // Invoke the clock getter inside the row that displays it, so only this row+ // recomposes each second rather than the whole screen.+ tick = now()+ val elapsed = sessionStartedAt?.let { formatElapsed(tick - it) }+ ?: stringResource(R.string.session_elapsed_none)+ ListItem(+ headlineContent = { Text(stringResource(R.string.session_elapsed)) },+ supportingContent = { Text(elapsed) },+ )+}++private fun formatElapsed(millis: Long): String {+ val totalSeconds = (millis.coerceAtLeast(0) / 1000).toInt()+ return "%d:%02d".format(totalSeconds / 60, totalSeconds % 60)+}
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 a1782b66cc..4edc525cae 100644--- a/auto/src/main/res/values/strings.xml+++ b/auto/src/main/res/values/strings.xml@@ -19,8 +19,37 @@ <!-- Explains that plugging in is all that is needed; there is nothing to configure. --> <string name="connect_hint">Plug the phone into the car with a USB cable, or start Android Auto from the car\'s screen if it supports a wireless connection.</string> + <!-- Heading of the card showing what the projection session is doing. -->+ <string name="session_headline">Session</string>+ <!-- The video stream the head unit accepted. %1$d and %2$d are the width and height in+ pixels, %3$d the frame rate, %4$d the configuration index it chose. -->+ <string name="session_video">Video <xliff:g example="800" id="width">%1$d</xliff:g>×<xliff:g example="480" id="height">%2$d</xliff:g> @ <xliff:g example="30" id="fps">%3$d</xliff:g> fps, config <xliff:g example="0" id="config">%4$d</xliff:g></string>+ <!-- Shown when no video configuration has been accepted yet. -->+ <string name="session_video_none">No video yet</string>+ <!-- Heading of the row showing which side currently holds video focus. -->+ <string name="session_focus">Focus</string>+ <!-- Shown when no focus indication has arrived yet. -->+ <string name="session_focus_none">Unknown</string>+ <!-- Heading of the row showing encoded frames sent and head-unit acks seen. -->+ <string name="session_frames">Frames / acks</string>+ <!-- %1$d is frames sent, %2$d is acks seen. -->+ <string name="session_frames_value"><xliff:g example="120" id="frames">%1$d</xliff:g> / <xliff:g example="118" id="acks">%2$d</xliff:g></string>+ <!-- Heading of the row counting acks that named the wrong session. -->+ <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 how long the session has been active. -->+ <string name="session_elapsed">Session time</string>+ <!-- Shown when there is no active session to time. -->+ <string name="session_elapsed_none">—</string>+ <!-- Notification channel name for the ongoing projection session. --> <string name="projection_channel">Projection</string> <!-- Ongoing notification shown while a car is connected. --> <string name="projection_running">Connected to a car</string>++ <!-- Second line of the car status bar, under the product name. -->+ <string name="car_connected">Connected</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>