Modern Apps git

← Modern-Apps.git

auto: video pipeline, head unit server and DHU-verified GAL handshake

Commit
3e52b3114254f57a527afd4fcf13edf31fb55798
Author
vayun-mathur <[email protected]>
When
2026-09-12 02:59 UTC (2 months ago)
Parents
f9912f7

Diff

auto/protocol/build.gradle.kts
diff --git a/auto/protocol/build.gradle.kts b/auto/protocol/build.gradle.ktsindex 838a450393..2ac5ccea21 100644--- a/auto/protocol/build.gradle.kts+++ b/auto/protocol/build.gradle.kts@@ -13,7 +13,10 @@ plugins { // literal in every build.gradle.kts it finds, and a library has no such properties. dependencies {     implementation(project(":library"))-    implementation(libs.protobuf.javalite)+    // `api`, not `implementation`: the generated message classes are part of this module's+    // public surface, so a consumer that touches one needs GeneratedMessageLite and+    // Internal.EnumLite on its compile classpath too.+    api(libs.protobuf.javalite) }  protobuf {
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.ktindex 2d5e843ad7..8ba00183ac 100644--- a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt@@ -8,6 +8,22 @@ fun interface ChannelMessageHandler {     fun onMessage(message: ChannelMessage) } +/**+ * Whether a service-channel message type carries protobuf rather than bulk media.+ *+ * The [FrameFlags.CONTROL] bit does *not* mean "control channel" -- channel 0 is what+ * identifies that, and a head unit never sets the bit there. Observed against a Desktop Head+ * Unit: its VersionRequest, its SslHandshake frames, its AuthComplete and even its encrypted+ * control replies all arrive as `FIRST|LAST` or `FIRST|LAST|ENC`, with the bit clear.+ *+ * What it distinguishes is a channel's own protobuf messages (the 0x8000 range) from the+ * bulk media that shares the channel with them.+ */+fun isChannelControlMessage(type: Int): Boolean = when (type) {+    GalMessage.Media.DATA, GalMessage.Media.DATA_WITH_TIMESTAMP -> false+    else -> true+}+ /**  * Ties a [GalTransport] to the control session.  *@@ -24,7 +40,14 @@ class GalConnection(     private val transport: GalTransport,     sslContext: SSLContext,     deviceName: String,+    deviceBrand: String = deviceName,     private val onChannelMessage: ChannelMessageHandler = ChannelMessageHandler { },+    /**+     * Traces every message and state change. A live session is otherwise opaque, and this+     * module stays free of `android.util.Log` so its tests run on the host, so the app+     * supplies the sink.+     */+    private val trace: (String) -> Unit = {}, ) : Closeable {      private val engine = GalCredential.serverEngine(sslContext)@@ -32,7 +55,7 @@ class GalConnection(     private val reader = FrameReader(decrypt = tls::unwrap)     private val writer = FrameWriter(encrypt = tls::wrap) -    val session: GalControlSession = GalControlSession(engine, deviceName)+    val session: GalControlSession = GalControlSession(engine, deviceName, deviceBrand)      private val buffer = ByteArray(READ_BUFFER_SIZE) @@ -47,9 +70,22 @@ class GalConnection(          for (message in reader.offer(buffer, 0, count)) {             val decoded = MessageCodec.decode(message.channelId, message.payload)-            if (message.isControl) {-                session.onMessage(decoded.type, decoded.payload).forEach(::send)+            // Routed by channel id, not by the frame's control bit: a head unit leaves that+            // bit clear on the version request, which is a control-channel message.+            if (message.channelId == CONTROL_CHANNEL) {+                val before = session.state+                val replies = session.onMessage(decoded.type, decoded.payload)+                trace(+                    "ctrl in 0x${decoded.type.toString(16)} (${decoded.payload.size}B) " ++                        "$before -> ${session.state}, ${replies.size} reply",+                )+                session.failure?.let { trace("session failed: $it") }+                replies.forEach(::send)             } else {+                trace(+                    "ch${message.channelId} in 0x${decoded.type.toString(16)} " ++                        "(${decoded.payload.size}B)",+                )                 onChannelMessage.onMessage(decoded)             }         }@@ -58,16 +94,33 @@ class GalConnection(      /** Frames a control message and writes it. */     fun send(message: OutboundMessage) {-        write(CONTROL_CHANNEL, MessageCodec.encode(message.type, message.payload),-            isControl = true, encrypted = message.encrypted)+        write(+            channelId = CONTROL_CHANNEL,+            payload = MessageCodec.encode(message.type, message.payload),+            // Never set on channel 0; see isChannelControlMessage.+            isControl = false,+            encrypted = message.encrypted,+        )     }      /** Frames a service-channel message and writes it. Always encrypted. */     fun send(channelId: Int, type: Int, payload: ByteArray) {-        write(channelId, MessageCodec.encode(type, payload), isControl = false, encrypted = true)+        write(+            channelId = channelId,+            payload = MessageCodec.encode(type, payload),+            isControl = isChannelControlMessage(type),+            encrypted = true,+        )     }      private fun write(channelId: Int, payload: ByteArray, isControl: Boolean, encrypted: Boolean) {+        trace(+            "out ch$channelId 0x${+                ((payload[0].toInt() and 0xFF shl 8) or (payload[1].toInt() and 0xFF)).toString(16)+            } ctrl=$isControl enc=$encrypted ${payload.take(48).joinToString("") {+                "%02x".format(it)+            }}",+        )         for (frame in writer.frame(channelId, payload, isControl, encrypted)) {             transport.write(frame, 0, frame.size)         }
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalControlSession.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalControlSession.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalControlSession.ktindex b219cc2e58..111d2e06e8 100644--- a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalControlSession.kt+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalControlSession.kt@@ -55,6 +55,7 @@ enum class SessionState { class GalControlSession(     private val engine: SSLEngine,     private val deviceName: String,+    private val deviceBrand: String = deviceName,     private val supportedVersion: GalVersion = VersionNegotiation.SUPPORTED, ) {     var state: SessionState = SessionState.AWAITING_VERSION@@ -169,8 +170,11 @@ class GalControlSession(         return listOf(             OutboundMessage(                 type = GalMessage.Control.SERVICE_DISCOVERY_REQUEST,+                // Both name and brand: a head unit rejects the request outright when only+                // one is set, which shows up as a bare MessageError with no explanation.                 payload = ServiceDiscoveryRequest.newBuilder()                     .setDeviceName(deviceName)+                    .setDeviceBrand(deviceBrand)                     .build()                     .toByteArray(),                 encrypted = true,
auto/protocol/src/main/proto/gal/control.proto
diff --git a/auto/protocol/src/main/proto/gal/control.proto b/auto/protocol/src/main/proto/gal/control.protoindex 2b060a8639..d0b56a7979 100644--- a/auto/protocol/src/main/proto/gal/control.proto+++ b/auto/protocol/src/main/proto/gal/control.proto@@ -94,13 +94,15 @@ enum NavigationFocusType { // ---- messages ----  // Control message 5. Sent by the PHONE. Only sent once version negotiation reaches >= 1.6.+//+// Fields 4 and 5 are optional in this build's descriptor but aasdk has both as required, and+// a Desktop Head Unit answers MessageError when only one is set, so both are always populated. message ServiceDiscoveryRequest {   optional bytes field1 = 1;   optional bytes field2 = 2;   optional bytes field3 = 3;-  optional string field4 = 4;-  // Build.MODEL, prefixed with Build.MANUFACTURER when not already prefixed.-  optional string device_name = 5;+  optional string device_name = 4;+  optional string device_brand = 5;   optional bytes field6 = 6; } 
auto/protocol/src/main/proto/gal/media.proto
diff --git a/auto/protocol/src/main/proto/gal/media.proto b/auto/protocol/src/main/proto/gal/media.protonew file mode 100644index 0000000000..63f05179a5--- /dev/null+++ b/auto/protocol/src/main/proto/gal/media.proto@@ -0,0 +1,69 @@+// Google Automotive Link media channels: the shared setup/start/ack sequence used by the+// video sink and the three audio sinks, plus video focus.+//+// Field numbers recovered from the APK's protobuf-lite descriptors and exact; names follow+// aasdk/openauto. See gal/control.proto for the provenance note.++syntax = "proto2";++package gal;++option java_package = "com.vayunmathur.auto.protocol.gal";+option java_multiple_files = true;++enum VideoFocusMode {+  VIDEO_FOCUS_PROJECTED = 1;+  VIDEO_FOCUS_NATIVE = 2;+  VIDEO_FOCUS_NATIVE_TRANSIENT = 3;+  VIDEO_FOCUS_PROJECTED_NO_INPUT_FOCUS = 4;+}++enum VideoFocusReason {+  UNKNOWN = 0;+  PHONE_SCREEN_OFF = 1;+  PHONE_SCREEN_ON = 2;+  LAUNCH_NATIVE = 3;+}++// 0x8000. Claims the channel for a media type before anything is streamed.+message MediaSetupRequest {+  required int32 media_type = 1;+}++// 0x8003, from the head unit. `configuration_indices` selects which of the configurations+// advertised in discovery the head unit will actually accept.+message MediaSetupResponse {+  required int32 media_status = 1;+  optional uint32 max_unacked = 2;+  repeated uint32 configuration_indices = 3;+}++// 0x8001. `configuration_index` indexes the config list from the discovery response.+message MediaStartRequest {+  required int32 session_id = 1;+  required uint32 configuration_index = 2;+  optional int32 field3 = 3;+  optional bytes field4 = 4;+}++// 0x8002. Genuinely empty.+message MediaStopRequest {}++// 0x8004, from the head unit: it has consumed frames and we may send more.+message MediaAck {+  required int32 session_id = 1;+  optional uint32 ack = 2;+  repeated uint64 field3 = 3;+}++// 0x8007. Note this starts at field 2 -- there is no field 1.+message VideoFocusRequest {+  optional VideoFocusMode mode = 2;+  optional VideoFocusReason reason = 3;+}++// 0x8008, from the head unit.+message VideoFocusIndication {+  optional VideoFocusMode mode = 1;+  optional bool unsolicited = 2;+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionTest.ktindex ddd539dd55..adce86545b 100644--- a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionTest.kt+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionTest.kt@@ -50,12 +50,12 @@ class GalConnectionTest {     private fun connection(transport: FakeTransport) =         GalConnection(transport, TestTls.context(), deviceName = "Pixel 8") -    /** A control frame as a head unit would put it on the wire: plaintext, channel 0. */+    /** A control frame exactly as the Desktop Head Unit puts it on the wire. */     private fun headUnitFrame(type: Int, payload: ByteArray): ByteArray =         FrameWriter().frame(             channelId = 0,             payload = MessageCodec.encode(type, payload),-            isControl = true,+            isControl = false,             encrypted = false,         ).single() @@ -72,11 +72,11 @@ class GalConnectionTest {          assertTrue(connection.pump()) -        // The full frame: 4-byte header, then type 2, major, minor, status. Flags are 0x07,-        // FIRST|LAST|CONTROL -- the control bit is what puts this on the control channel.+        // Flags 0x03, FIRST|LAST with the control bit CLEAR: version negotiation is raw+        // shorts rather than protobuf. A real DHU sends its request the same way.         assertContentEquals(             byteArrayOf(-                0x00, 0x07, 0x00, 0x08, // channel 0, FIRST|LAST|CONTROL, 8-byte payload+                0x00, 0x03, 0x00, 0x08, // channel 0, FIRST|LAST, 8-byte payload                 0x00, 0x02, //             VersionResponse                 0x00, 0x01, 0x00, 0x06, // 1.6                 0x00, 0x00, //             STATUS_SUCCESS@@ -87,6 +87,26 @@ class GalConnectionTest {         assertEquals(SessionState.HANDSHAKING, connection.session.state)     } +    @Test+    fun `the exact bytes a Desktop Head Unit sends are understood`() {+        // Captured from desktop-head-unit.exe 2.0 on connect. Kept verbatim because it is+        // the only ground truth we have for what a head unit actually puts on the wire.+        val fromDhu = byteArrayOf(+            0x00, 0x03, 0x00, 0x06, // channel 0, FIRST|LAST, 6-byte payload+            0x00, 0x01, //             VersionRequest+            0x00, 0x01, 0x00, 0x07, // 1.7+        )+        val transport = FakeTransport()+        val connection = connection(transport)+        transport.queue(fromDhu)++        assertTrue(connection.pump())++        assertEquals(GalVersion(1, 7), connection.session.negotiatedVersion)+        assertEquals(SessionState.HANDSHAKING, connection.session.state)+        assertTrue(transport.written.size() > 0, "the head unit should have been answered")+    }+     @Test     fun `pump reports end of stream when the head unit goes away`() {         val transport = FakeTransport()@@ -120,15 +140,18 @@ class GalConnectionTest {             transport,             TestTls.context(),             deviceName = "Pixel 8",-        ) { received += it }+            // Named: `trace` is also a trailing lambda, so positional binding here would+            // silently attach this to the wrong parameter.+            onChannelMessage = { received += it },+        ) -        // A plaintext service-channel frame. Real ones are encrypted, but the routing-        // decision is the control flag, which is what this is checking.+        // A service-channel frame. Routing is by channel id, so this must reach the handler+        // rather than the session regardless of how the control bit is set.         transport.queue(             FrameWriter().frame(                 channelId = GalService.VIDEO_SINK.id,                 payload = MessageCodec.encode(GalMessage.Video.FOCUS_INDICATION, byteArrayOf(1)),-                isControl = false,+                isControl = true,                 encrypted = false,             ).single(),         )
auto/src/main/AndroidManifest.xml
diff --git a/auto/src/main/AndroidManifest.xml b/auto/src/main/AndroidManifest.xmlindex 6730544a79..631c4ab629 100644--- a/auto/src/main/AndroidManifest.xml+++ b/auto/src/main/AndroidManifest.xml@@ -7,6 +7,14 @@     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />     <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />     <uses-permission android:name="android.permission.WAKE_LOCK" />+    <!-- The head unit connects in over TCP. For the Desktop Head Unit that is an adb forward+         to loopback; for a real car it is the wireless link. -->+    <uses-permission android:name="android.permission.INTERNET" />+    <!-- Bringing up the WiFi link to a wireless head unit. This is also what qualifies+         ProjectionService for the connectedDevice foreground type: that check accepts a USB+         accessory only when one is physically attached and permission-granted, so the USB+         filter below does not satisfy it on its own. -->+    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />      <application         android:allowBackup="false"@@ -27,6 +35,20 @@                 <action android:name="android.intent.action.MAIN" />                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>+            <!-- Plugging into a head unit puts the phone into AOAP accessory mode and+                 Android hands the connection to whoever matches, which is also how the app+                 gets launched on plug-in. -->+            <intent-filter>+                <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />+            </intent-filter>+            <meta-data+                android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"+                android:resource="@xml/usb_accessory_filter" />         </activity>++        <service+            android:name=".service.ProjectionService"+            android:exported="false"+            android:foregroundServiceType="connectedDevice" />     </application> </manifest>
auto/src/main/java/com/vayunmathur/auto/MainActivity.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/MainActivity.kt b/auto/src/main/java/com/vayunmathur/auto/MainActivity.ktindex b990281caa..feb60b19ef 100644--- a/auto/src/main/java/com/vayunmathur/auto/MainActivity.kt+++ b/auto/src/main/java/com/vayunmathur/auto/MainActivity.kt@@ -6,6 +6,7 @@ import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels import com.vayunmathur.auto.platform.AutoViewModel+import com.vayunmathur.auto.service.ProjectionService import com.vayunmathur.library.ui.DynamicTheme  class MainActivity : ComponentActivity() {@@ -13,6 +14,9 @@ class MainActivity : ComponentActivity() {      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)+        // Start listening as soon as the app is opened. A head unit can attach at any time+        // and the service is what holds the socket.+        ProjectionService.start(this)         enableEdgeToEdge()         setContent {             DynamicTheme {
auto/src/main/java/com/vayunmathur/auto/network/HeadUnitServer.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/network/HeadUnitServer.kt b/auto/src/main/java/com/vayunmathur/auto/network/HeadUnitServer.ktnew file mode 100644index 0000000000..4100b25950--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/network/HeadUnitServer.kt@@ -0,0 +1,51 @@+package com.vayunmathur.auto.network++import android.util.Log+import java.io.Closeable+import java.net.InetAddress+import java.net.ServerSocket+import java.net.Socket++/**+ * Listens for a head unit on the port the Desktop Head Unit uses.+ *+ * The DHU runs on a workstation and reaches the phone through+ * `adb forward tcp:5277 tcp:5277`, so the phone is the one listening. That is the same+ * direction as the rest of GAL, where the phone is the TLS server and the head unit+ * connects to it.+ *+ * Bound to loopback: the only thing that should reach this is an adb forward, and binding+ * the wildcard address would expose the projection socket to the local network.+ */+class HeadUnitServer(private val port: Int = DHU_PORT) : Closeable {++    private var server: ServerSocket? = null++    /** Blocks until a head unit connects. */+    fun accept(): Socket {+        val socket = server ?: ServerSocket(port, BACKLOG, InetAddress.getLoopbackAddress())+            .also {+                server = it+                Log.i(TAG, "listening for a head unit on ${it.inetAddress.hostAddress}:$port")+            }+        return socket.accept().apply {+            // Projection is latency-sensitive and its writes are small and frequent; Nagle+            // would coalesce frames and add a visible stutter.+            tcpNoDelay = true+            Log.i(TAG, "head unit connected from $remoteSocketAddress")+        }+    }++    override fun close() {+        server?.close()+        server = null+    }++    companion object {+        /** The port the Desktop Head Unit expects to be forwarded to. */+        const val DHU_PORT = 5277++        private const val TAG = "MaAuto.Server"+        private const val BACKLOG = 1+    }+}
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.ktnew file mode 100644index 0000000000..b595f8e339--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt@@ -0,0 +1,109 @@+package com.vayunmathur.auto.platform++import android.app.Presentation+import android.content.Context+import android.graphics.Color+import android.hardware.display.DisplayManager+import android.hardware.display.VirtualDisplay+import android.os.Bundle+import android.view.Gravity+import android.view.Surface+import android.view.ViewGroup+import android.widget.LinearLayout+import android.widget.TextView++/**+ * The car's screen, as a virtual display rendered into the encoder's input surface.+ *+ * Deliberately a *private* virtual display for now: a trusted one needs+ * `ADD_TRUSTED_DISPLAY`, which arrives with the role work, and is only required to launch+ * other apps' activities onto the display. A [Presentation] owned by this app renders onto a+ * private display perfectly well, which is enough to get pixels onto a head unit and prove+ * the video path end to end.+ */+class CarDisplay(+    private val context: Context,+    private val width: Int,+    private val height: Int,+    private val densityDpi: Int,+) {+    private var virtualDisplay: VirtualDisplay? = null+    private var presentation: Presentation? = null++    /** Creates the display against [surface] and shows the car UI on it. */+    fun show(surface: Surface) {+        val displayManager = context.getSystemService(DisplayManager::class.java)+        val display = displayManager.createVirtualDisplay(+            DISPLAY_NAME,+            width,+            height,+            densityDpi,+            surface,+            DisplayManager.VIRTUAL_DISPLAY_FLAG_PRESENTATION,+        ) ?: error("could not create the car virtual display")+        virtualDisplay = display++        presentation = CarPresentation(context, display.display).also { it.show() }+    }++    fun release() {+        presentation?.dismiss()+        presentation = null+        virtualDisplay?.release()+        virtualDisplay = null+    }++    /**+     * A placeholder car UI.+     *+     * 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.+     */+    private class CarPresentation(context: Context, display: android.view.Display) :+        Presentation(context, display) {++        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(+                TextView(context).apply {+                    text = "MA Auto"+                    setTextColor(Color.WHITE)+                    textSize = 40f+                    gravity = Gravity.CENTER+                },+            )+            val clock = TextView(context).apply {+                setTextColor(Color.parseColor("#8AB4F8"))+                textSize = 20f+                gravity = Gravity.CENTER+            }+            root.addView(clock)+            setContentView(root)++            // 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)+                }+            }+            clock.post(ticker)+        }++        private companion object {+            const val MATCH = ViewGroup.LayoutParams.MATCH_PARENT+        }+    }++    private companion object {+        const val DISPLAY_NAME = "MA Auto"+    }+}
auto/src/main/java/com/vayunmathur/auto/platform/VideoEncoder.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/VideoEncoder.kt b/auto/src/main/java/com/vayunmathur/auto/platform/VideoEncoder.ktnew file mode 100644index 0000000000..2f00cd32fa--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/VideoEncoder.kt@@ -0,0 +1,107 @@+package com.vayunmathur.auto.platform++import android.media.MediaCodec+import android.media.MediaCodecInfo+import android.media.MediaFormat+import android.view.Surface+import java.nio.ByteBuffer++/**+ * H.264 encoder feeding the video sink channel.+ *+ * The encoder's input [surface] is what the car display renders into, so frames never touch+ * the CPU: the virtual display composites straight into the encoder.+ *+ * Head units want Baseline profile H.264 ([gal codec][com.vayunmathur.auto.protocol.gal.MediaCodecType.MEDIA_CODEC_VIDEO_H264_BP]),+ * and they want the codec-specific data (SPS/PPS) ahead of the first frame. MediaCodec+ * delivers that either as a `BUFFER_FLAG_CODEC_CONFIG` buffer or via the output format, and+ * we forward it as an ordinary frame because that is how GAL carries it.+ */+class VideoEncoder(+    private val width: Int,+    private val height: Int,+    private val frameRate: Int,+    private val bitRate: Int = DEFAULT_BIT_RATE,+    private val onFrame: (ByteBuffer, MediaCodec.BufferInfo) -> Unit,+) {+    private var codec: MediaCodec? = null++    /** The surface to render the car UI into. Valid between [start] and [stop]. */+    var surface: Surface? = null+        private set++    fun start() {+        val format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, width, height)+            .apply {+                setInteger(+                    MediaFormat.KEY_COLOR_FORMAT,+                    MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface,+                )+                setInteger(MediaFormat.KEY_BIT_RATE, bitRate)+                setInteger(MediaFormat.KEY_FRAME_RATE, frameRate)+                // A keyframe every second: a head unit that joins late, or drops a frame,+                // recovers within a second rather than showing garbage until the next one.+                setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1)+                setInteger(+                    MediaFormat.KEY_PROFILE,+                    MediaCodecInfo.CodecProfileLevel.AVCProfileBaseline,+                )+            }++        codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC).apply {+            configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)+            surface = createInputSurface()+            start()+        }+    }++    /**+     * Drains whatever the encoder has ready.+     *+     * @return false once the encoder has signalled end of stream.+     */+    fun drain(timeoutUs: Long = 0): Boolean {+        val codec = codec ?: return false+        val info = MediaCodec.BufferInfo()+        while (true) {+            val index = codec.dequeueOutputBuffer(info, timeoutUs)+            when {+                index == MediaCodec.INFO_TRY_AGAIN_LATER -> return true+                index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> Unit+                index < 0 -> Unit+                else -> {+                    val buffer = codec.getOutputBuffer(index)+                    if (buffer != null && info.size > 0) {+                        buffer.position(info.offset)+                        buffer.limit(info.offset + info.size)+                        onFrame(buffer, info)+                    }+                    codec.releaseOutputBuffer(index, false)+                    if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) return false+                }+            }+        }+    }++    /** Asks for a keyframe, which a head unit needs when it (re)gains video focus. */+    fun requestKeyFrame() {+        codec?.setParameters(+            android.os.Bundle().apply { putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0) },+        )+    }++    fun stop() {+        surface?.release()+        surface = null+        codec?.run {+            runCatching { stop() }+            release()+        }+        codec = null+    }++    private companion object {+        /** Enough for 800x480 and 720p without obvious blocking. */+        const val DEFAULT_BIT_RATE = 4_000_000+    }+}
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.ktnew file mode 100644index 0000000000..100a0f8533--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.kt@@ -0,0 +1,173 @@+package com.vayunmathur.auto.platform++import android.content.Context+import android.media.MediaCodec+import android.util.Log+import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalMessage+import com.vayunmathur.auto.protocol.gal.MediaAck+import com.vayunmathur.auto.protocol.gal.MediaSetupRequest+import com.vayunmathur.auto.protocol.gal.MediaSetupResponse+import com.vayunmathur.auto.protocol.gal.MediaStartRequest+import com.vayunmathur.auto.protocol.gal.Service+import com.vayunmathur.auto.protocol.gal.VideoConfiguration+import com.vayunmathur.auto.protocol.gal.VideoFocusIndication+import com.vayunmathur.auto.protocol.gal.VideoFocusMode+import com.vayunmathur.auto.protocol.gal.VideoFocusRequest+import com.vayunmathur.auto.protocol.gal.VideoResolution+import java.nio.ByteBuffer++/**+ * The video sink channel: brings the display and encoder up once the head unit agrees.+ *+ * The bring-up is a four-step conversation and the order matters — a head unit that gets+ * frames before it has acknowledged the start request drops them silently:+ *+ *  1. → `MediaSetupRequest`      claim the channel for video+ *  2. ← `MediaSetupResponse`     the head unit says which configuration it will accept+ *  3. → `VideoFocusRequest`      ask for the screen+ *  4. → `MediaStartRequest`      then, and only then, start streaming+ */+class VideoSinkChannel(+    private val context: Context,+    private val service: Service,+    private val connection: GalConnection,+) {+    private var display: CarDisplay? = null+    private var encoder: VideoEncoder? = null+    private var sessionId = -1+    private var configurationIndex = 0++    /** Chosen from what the head unit advertised in discovery. */+    private val configuration: VideoConfiguration? =+        service.mediaSink.videoConfigsList.firstOrNull()++    val channelId: Int get() = service.id++    /** Step 1. Called once the channel is open. */+    fun requestSetup() {+        connection.send(+            channelId,+            GalMessage.Media.SETUP_REQUEST,+            MediaSetupRequest.newBuilder().setMediaType(MEDIA_TYPE_VIDEO).build().toByteArray(),+        )+    }++    fun onMessage(type: Int, payload: ByteArray) {+        when (type) {+            GalMessage.Media.CONFIG -> onSetupResponse(payload)+            GalMessage.Video.FOCUS_INDICATION -> onFocus(payload)+            GalMessage.Media.ACK -> onAck(payload)+            else -> Log.d(TAG, "unhandled video message 0x${type.toString(16)}")+        }+    }++    private fun onSetupResponse(payload: ByteArray) {+        val response = MediaSetupResponse.parseFrom(payload)+        configurationIndex = response.configurationIndicesList.firstOrNull() ?: 0+        Log.i(TAG, "head unit accepted video, config index $configurationIndex")++        // Step 3: ask for the screen before starting the stream.+        connection.send(+            channelId,+            GalMessage.Video.FOCUS_REQUEST,+            VideoFocusRequest.newBuilder()+                .setMode(VideoFocusMode.VIDEO_FOCUS_PROJECTED)+                .build()+                .toByteArray(),+        )+        startStreaming()+    }++    private fun onFocus(payload: ByteArray) {+        val mode = VideoFocusIndication.parseFrom(payload).mode+        Log.i(TAG, "video focus is now $mode")+        // 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()+    }++    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.+        val ack = MediaAck.parseFrom(payload)+        if (ack.sessionId != sessionId) {+            Log.w(TAG, "ack for session ${ack.sessionId}, expected $sessionId")+        }+    }++    private fun startStreaming() {+        val config = configuration+        val (width, height) = config?.codecResolution.dimensions()+        val frameRate = config?.frameRate?.takeIf { it > 0 } ?: DEFAULT_FRAME_RATE+        val density = config?.density?.takeIf { it > 0 } ?: DEFAULT_DENSITY++        Log.i(TAG, "starting video ${width}x$height @${frameRate} dpi $density")++        sessionId = 0+        val encoder = VideoEncoder(width, height, frameRate, onFrame = ::sendFrame)+        this.encoder = encoder+        encoder.start()++        display = CarDisplay(context, width, height, density).also {+            it.show(checkNotNull(encoder.surface) { "encoder produced no input surface" })+        }++        // Step 4.+        connection.send(+            channelId,+            GalMessage.Media.START_REQUEST,+            MediaStartRequest.newBuilder()+                .setSessionId(sessionId)+                .setConfigurationIndex(configurationIndex)+                .build()+                .toByteArray(),+        )+    }++    private fun sendFrame(buffer: ByteBuffer, info: MediaCodec.BufferInfo) {+        val bytes = ByteArray(info.size)+        buffer.get(bytes)+        // Timestamped form: an 8-byte microsecond timestamp then the access unit. Codec+        // config (SPS/PPS) rides the same way, which is what a head unit expects first.+        val payload = ByteBuffer.allocate(Long.SIZE_BYTES + bytes.size)+            .putLong(info.presentationTimeUs)+            .put(bytes)+            .array()+        connection.send(channelId, GalMessage.Media.DATA_WITH_TIMESTAMP, payload)+    }++    /** Pushes any encoded frames out. Called from the connection's loop. */+    fun pumpEncoder() {+        encoder?.drain()+    }++    fun release() {+        display?.release()+        display = null+        encoder?.stop()+        encoder = null+    }++    private fun VideoResolution?.dimensions(): Pair<Int, Int> = when (this) {+        VideoResolution.VIDEO_1280x720 -> 1280 to 720+        VideoResolution.VIDEO_1920x1080 -> 1920 to 1080+        VideoResolution.VIDEO_2560x1440 -> 2560 to 1440+        VideoResolution.VIDEO_3840x2160 -> 3840 to 2160+        VideoResolution.VIDEO_720x1280 -> 720 to 1280+        VideoResolution.VIDEO_1080x1920 -> 1080 to 1920+        VideoResolution.VIDEO_1440x2560 -> 1440 to 2560+        VideoResolution.VIDEO_2160x3840 -> 2160 to 3840+        // 800x480 is the DHU default and a sane fallback for anything unrecognised.+        else -> 800 to 480+    }++    private companion object {+        const val TAG = "MaAuto.Video"++        /** `MediaSetupRequest.media_type`: 1 audio, 3 video. */+        const val MEDIA_TYPE_VIDEO = 3+        const val DEFAULT_FRAME_RATE = 30+        const val DEFAULT_DENSITY = 160+    }+}
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.ktnew file mode 100644index 0000000000..f31df3c38b--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt@@ -0,0 +1,124 @@+package com.vayunmathur.auto.service++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.Service+import android.content.Context+import android.content.Intent+import android.os.Build+import android.os.IBinder+import android.util.Log+import com.vayunmathur.auto.R+import com.vayunmathur.auto.network.HeadUnitServer+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 kotlin.concurrent.thread++/**+ * Runs a projection session for as long as a head unit is attached.+ *+ * Single-threaded by design: one [javax.net.ssl.SSLEngine] backs the connection and an+ * engine is not thread-safe, so reads, writes and encoder draining all happen on this+ * thread.+ */+class ProjectionService : Service() {++    private var worker: Thread? = null+    @Volatile private var running = false++    override fun onBind(intent: Intent?): IBinder? = null++    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+        if (running) return START_STICKY+        running = true+        startForeground(NOTIFICATION_ID, notification())+        worker = thread(name = "ma-auto-projection") { serve() }+        return START_STICKY+    }++    override fun onDestroy() {+        running = false+        worker?.interrupt()+        super.onDestroy()+    }++    private fun serve() {+        HeadUnitServer().use { server ->+            while (running) {+                runCatching { session(server) }+                    .onFailure { if (running) Log.e(TAG, "projection session ended", it) }+            }+        }+    }++    private fun session(server: HeadUnitServer) {+        server.accept().use { socket ->+            val connection = GalConnection(+                transport = StreamTransport(socket.getInputStream(), socket.getOutputStream()),+                sslContext = GalCredential.fromAssets(assets),+                deviceName = Build.MODEL,+                deviceBrand = Build.MANUFACTURER,+                onChannelMessage = { message -> video?.onMessage(message.type, message.payload) },+                trace = { Log.d(TAG, it) },+            )++            var openedVideo = false+            while (running && connection.pump()) {+                // Opening the video channel is the first thing to do once discovery lands.+                if (!openedVideo && connection.session.state == SessionState.ACTIVE) {+                    openedVideo = openVideo(connection)+                }+                video?.pumpEncoder()+            }+            Log.i(TAG, "head unit disconnected: ${connection.session.failure ?: "cleanly"}")+            video?.release()+            video = null+        }+    }++    private var video: VideoSinkChannel? = null++    /** @return true once the request is away, so it is only sent once. */+    private fun openVideo(connection: GalConnection): Boolean {+        val service = connection.session.services+            .firstOrNull { it.id == GalService.VIDEO_SINK.id && it.hasMediaSink() }+        if (service == null) {+            Log.w(TAG, "head unit advertised no video sink; nothing to project onto")+            return true+        }+        connection.send(connection.session.openChannel(service))+        video = VideoSinkChannel(this, service, connection).also { it.requestSetup() }+        return true+    }++    private fun notification(): Notification {+        val manager = getSystemService(NotificationManager::class.java)+        manager.createNotificationChannel(+            NotificationChannel(+                CHANNEL_ID,+                getString(R.string.projection_channel),+                NotificationManager.IMPORTANCE_LOW,+            ),+        )+        return Notification.Builder(this, CHANNEL_ID)+            .setContentTitle(getString(R.string.projection_running))+            .setSmallIcon(android.R.drawable.stat_sys_data_bluetooth)+            .setOngoing(true)+            .build()+    }++    companion object {+        private const val TAG = "MaAuto.Service"+        private const val CHANNEL_ID = "projection"+        private const val NOTIFICATION_ID = 1++        fun start(context: Context) {+            context.startForegroundService(Intent(context, ProjectionService::class.java))+        }+    }+}
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 63979797d8..a1782b66cc 100644--- a/auto/src/main/res/values/strings.xml+++ b/auto/src/main/res/values/strings.xml@@ -18,4 +18,9 @@      <!-- 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>++    <!-- 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> </resources>
auto/src/main/res/xml/usb_accessory_filter.xml
diff --git a/auto/src/main/res/xml/usb_accessory_filter.xml b/auto/src/main/res/xml/usb_accessory_filter.xmlnew file mode 100644index 0000000000..2359c6c252--- /dev/null+++ b/auto/src/main/res/xml/usb_accessory_filter.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- The AOAP identity a head unit announces when it puts the phone into accessory mode.+     Matching it is what lets Android hand us the connection, and it is also what qualifies+     the projection service for the connectedDevice foreground type. -->+<resources>+    <usb-accessory manufacturer="Android" model="Android Auto" />+    <usb-accessory manufacturer="Android" model="Android Auto Wireless" />+</resources>