Modern Apps git

← Modern-Apps.git

maauto: input channel 8 codec, routing and injection

Commit
3798785609c5b92d7eaf6bf3cd009f318c81fceb
Author
vayun-mathur <[email protected]>
When
2026-09-12 22:20 UTC (2 months ago)
Parents
78d0d4c

Diff

auto/protocol/src/main/java/com/vayunmathur/auto/protocol/InputCodec.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/InputCodec.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/InputCodec.ktnew file mode 100644index 0000000000..57ca0d52af--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/InputCodec.kt@@ -0,0 +1,244 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.AbsoluteEvent+import com.vayunmathur.auto.protocol.gal.AbsoluteEvents+import com.vayunmathur.auto.protocol.gal.InputReport+import com.vayunmathur.auto.protocol.gal.KeyBindingRequest+import com.vayunmathur.auto.protocol.gal.KeyBindingResponse+import com.vayunmathur.auto.protocol.gal.KeyEvent+import com.vayunmathur.auto.protocol.gal.KeyEvents+import com.vayunmathur.auto.protocol.gal.RelativeEvent+import com.vayunmathur.auto.protocol.gal.RelativeEvents+import com.vayunmathur.auto.protocol.gal.TouchAction+import com.vayunmathur.auto.protocol.gal.TouchEvent+import com.vayunmathur.auto.protocol.gal.TouchPointer++/**+ * One decoded finger: display-agnostic head-unit pixels plus the pointer id the+ * head unit assigned. Coordinates are in the head-unit touchscreen space from+ * discovery (`TouchConfig` width/height, DHU default 800x480); the receiver+ * scales them to car-display pixels with [scaleCoordinate].+ */+data class InputPointer(val x: Int, val y: Int, val pointerId: Int)++/** A decoded touch frame: the action plus whichever pointer it acts on. */+data class InputTouch(val action: TouchAction, val pointers: List<InputPointer>, val actionIndex: Int)++/** A decoded key press or release: the Android keycode and the direction. */+data class InputKey(val keycode: Int, val down: Boolean)++/**+ * A decoded head-unit input report, already classified.+ *+ * Every section is optional on the wire (`xjt` fields 3-7) and the phone handles+ * whichever are present, so each list may be empty independently. The head unit+ * is the only sender: the phone never builds or receives its own reports.+ */+data class InputEvents(+    val timestamp: Long,+    val touches: List<InputTouch>,+    val keys: List<InputKey>,+    /** Scroll ticks: (keycode 65536, delta) pairs; a zero delta is dropped upstream. */+    val scrolls: List<Pair<Int, Int>>,+    /** Absolute values (e.g. tap-as-select keycode 65541) the owner may act on. */+    val absolutes: List<Pair<Int, Int>>,+)++/**+ * Pure input-channel (INPUT_SOURCE, service 8) codecs: touch, keys and scroll.+ *+ * Android-free like everything else in this module, so decoding, keybinding and+ * coordinate scaling are all host-testable. The head unit owns the input+ * hardware and sends [GalMessage.Input.REPORT]; the phone answers with+ * [GalMessage.Input.KEY_BINDING_REQUEST] on channel open (the keycode list the+ * head unit advertised in discovery) and observes+ * [GalMessage.Input.KEY_BINDING_RESPONSE]. Sends go out with+ * `GalConnection.send(channelId, type, payload)` -- always encrypted, never+ * CONTROL-flagged, like all service-channel traffic.+ *+ * Wire values, from the APK bytecode and descriptors rather than the decompiler+ * (HANDOFF.md section 9): `jar.a()` compares the raw ids, so 0x8001 is the+ * report and 0x8003 the binding response -- no `wub.o` off-by-one here.+ */+object InputCodec {++    /**+     * Head-unit keycode for a scroll tick. A relative event with this keycode+     * and a non-zero delta becomes a scroll of that many detents; a zero delta+     * is ignored (`jar.java`: "Ignoring zero delta relative event").+     */+    const val SCROLL_KEYCODE = 65536++    /**+     * Head-unit keycode for the touchpad tap-as-select behind absolute event+     * 65541: value 1 presses KEYCODE_DPAD_CENTER, 0 releases it.+     */+    const val TAP_SELECT_KEYCODE = 65541++    /** Android `KEYCODE_DPAD_CENTER`, the key tap-as-select synthesizes. */+    const val KEYCODE_DPAD_CENTER = 23++    /**+     * DHU default touchscreen: `config/default.ini` is 800x480, which is+     * `VIDEO_800x480`. These are the fallback head-unit dimensions when+     * discovery advertised no touchscreen config.+     */+    const val DEFAULT_HU_WIDTH = 800+    const val DEFAULT_HU_HEIGHT = 480++    /** Phone -> HU: echo the discovery-advertised keycodes back on channel open. */+    fun encodeKeyBinding(keycodes: List<Int>): Pair<Int, ByteArray> =+        GalMessage.Input.KEY_BINDING_REQUEST to KeyBindingRequest.newBuilder()+            .addAllKeycodes(keycodes)+            .build()+            .toByteArray()++    /** Parses a HU -> phone binding response, throwing on malformed bytes. */+    fun decodeKeyBindingResponse(payload: ByteArray): KeyBindingResponse =+        KeyBindingResponse.parseFrom(payload)++    /**+     * Classifies one inbound ch8 message, or null when it is not an input+     * report we handle: a type other than REPORT, malformed bytes, or a+     * report missing its required timestamp. Null means "observed and+     * ignored", never an error -- the pump must survive whatever a head+     * unit sends. Route by channel id before calling: the 0x04 CONTROL+     * frame flag does NOT mean "control channel" (HANDOFF.md section 9),+     * and 0x8001 is aliased across services (media start, sensor request,+     * messaging threads), so only ch8 traffic belongs here.+     */+    fun decodeInbound(type: Int, payload: ByteArray): InputEvents? {+        if (type != GalMessage.Input.REPORT) return null+        val report = runCatching { InputReport.parseFrom(payload) }.getOrNull()+            ?: return null+        if (!report.isInitialized) return null+        return InputEvents(+            timestamp = report.timestamp,+            touches = listOfNotNull(+                report.takeIf { it.hasTouchscreen() }?.touchscreen?.toTouch(),+                report.takeIf { it.hasTouchpad() }?.touchpad?.toTouch(),+            ),+            keys = if (report.hasKeyEvents()) report.keyEvents.eventsList.map { it.toKey() }+            else emptyList(),+            scrolls = if (report.hasRelativeEvents()) {+                report.relativeEvents.eventList+                    .filter { it.keycode == SCROLL_KEYCODE && it.delta != 0 }+                    .map { it.keycode to it.delta }+            } else emptyList(),+            absolutes = if (report.hasAbsEvents()) {+                report.absEvents.eventList.map { it.keycode to it.value }+            } else emptyList(),+        )+    }++    private fun TouchEvent.toTouch(): InputTouch? {+        // An empty frame carries no pointers; `jar.java` guards on the count+        // before touching the index, so an empty frame is observed, not an error.+        if (pointersCount == 0) return null+        // The action enum is already the MotionEvent action (`wox.A` minus one),+        // so it passes through verbatim; absent means DOWN (0 arrives as default).+        val index = if (hasActionIndex()) actionIndex else 0+        return InputTouch(+            action = action,+            pointers = pointersList.map { InputPointer(x = it.x, y = it.y, pointerId = it.pointerId) },+            actionIndex = index.coerceIn(0, pointersCount - 1),+        )+    }++    private fun KeyEvent.toKey(): InputKey = InputKey(keycode = keycode, down = keyDown)++    /**+     * Scales one head-unit touchscreen pixel to a car-display pixel.+     *+     * The head unit reports in its own touchscreen space (`TouchConfig`+     * width/height from discovery) while the car UI renders at its own size,+     * so each axis scales independently and rounds to the nearest pixel.+     * A zero or negative head-unit dimension cannot divide, so it falls back+     * to the DHU default for that axis rather than producing garbage.+     */+    fun scaleCoordinate(value: Int, huSize: Int, displaySize: Int, defaultHuSize: Int): Int {+        val source = if (huSize > 0) huSize else defaultHuSize+        return ((value.toLong() * displaySize + source / 2) / source).toInt()+    }++    /** Scales both axes of one pointer into car-display pixels. */+    fun scalePointer(+        pointer: InputPointer,+        huWidth: Int,+        huHeight: Int,+        displayWidth: Int,+        displayHeight: Int,+    ): InputPointer = pointer.copy(+        x = scaleCoordinate(pointer.x, huWidth, displayWidth, DEFAULT_HU_WIDTH),+        y = scaleCoordinate(pointer.y, huHeight, displayHeight, DEFAULT_HU_HEIGHT),+    )++    /**+     * Builds a touchscreen report carrying one touch frame, for tests and for+     * head-unit stand-ins. The phone never sends these on the wire.+     */+    fun buildReport(+        timestamp: Long = 0,+        action: TouchAction = TouchAction.TOUCH_DOWN,+        pointers: List<InputPointer> = listOf(InputPointer(0, 0, 0)),+        actionIndex: Int = 0,+    ): ByteArray = InputReport.newBuilder()+        .setTimestamp(timestamp)+        .setTouchscreen(+            TouchEvent.newBuilder()+                .setAction(action)+                .setActionIndex(actionIndex)+                .addAllPointers(+                    pointers.map {+                        TouchPointer.newBuilder()+                            .setX(it.x)+                            .setY(it.y)+                            .setPointerId(it.pointerId)+                            .build()+                    },+                ),+        )+        .build()+        .toByteArray()++    /** Builds a report carrying key events only. */+    fun buildKeyReport(timestamp: Long = 0, vararg keys: Pair<Int, Boolean>): ByteArray =+        InputReport.newBuilder()+            .setTimestamp(timestamp)+            .setKeyEvents(+                KeyEvents.newBuilder().addAllEvents(+                    keys.map { (keycode, down) ->+                        KeyEvent.newBuilder()+                            .setKeycode(keycode)+                            .setKeyDown(down)+                            .setMetaState(0)+                            .build()+                    },+                ),+            )+            .build()+            .toByteArray()++    /** Builds a report carrying one scroll tick (keycode 65536, non-zero delta). */+    fun buildScrollReport(timestamp: Long = 0, delta: Int): ByteArray = InputReport.newBuilder()+        .setTimestamp(timestamp)+        .setRelativeEvents(+            RelativeEvents.newBuilder().addEvent(+                RelativeEvent.newBuilder().setKeycode(SCROLL_KEYCODE).setDelta(delta),+            ),+        )+        .build()+        .toByteArray()++    /** Builds a report carrying one absolute value (e.g. tap-as-select). */+    fun buildAbsoluteReport(timestamp: Long = 0, keycode: Int, value: Int): ByteArray =+        InputReport.newBuilder()+            .setTimestamp(timestamp)+            .setAbsEvents(+                AbsoluteEvents.newBuilder().addEvent(+                    AbsoluteEvent.newBuilder().setKeycode(keycode).setValue(value),+                ),+            )+            .build()+            .toByteArray()+}
auto/protocol/src/main/proto/gal/input.proto
diff --git a/auto/protocol/src/main/proto/gal/input.proto b/auto/protocol/src/main/proto/gal/input.protonew file mode 100644index 0000000000..644ca2a38e--- /dev/null+++ b/auto/protocol/src/main/proto/gal/input.proto@@ -0,0 +1,130 @@+// Google Automotive Link input channel (service 8): touch, keys and scroll.+//+// Field numbers, wire types and cardinality were recovered from the protobuf-lite+// RawMessageInfo descriptors in the Android Auto APK (analysis/maauto/dump_protos.py) and are+// exact. Message and field NAMES are not in the APK -- they follow the public aasdk/openauto+// naming where it matches, and are plain descriptions elsewhere. See gal/control.proto for+// the provenance note and auto/docs/FINDINGS.md for the endpoint teardown.+//+// Direction: the head unit OWNS the input hardware, so it SENDS InputReport (0x8001) and+// the phone only answers with KeyBindingRequest (0x8002, supported keycodes echoed back+// on channel open) and InputFeedback (0x8004). The phone never builds an InputReport.+// The dispatch compares raw wire ids (`jar.a()` overrides the base and never calls+// `wub.o`, so there is no off-by-one here): 0x8001 report, 0x8003 binding response.+//+// Touch mapping, from `ikb.i` + `iye.a` + `wox.A`:+// - TouchPointer is (x, y, pointer_id): `iyd` prints "ProjectionPointer(x,y,id)" and+//   `iye.a` assigns `props.id = pointer_id`, `coords.x/y = x/y` (+ a zero offset).+// - The action enum IS the MotionEvent action: `wox.A` maps 0->1, 1->2, 2->3, 5->6,+//   6->7 and `ikb.i` subtracts one, so 0/1/2/5/6 become DOWN/UP/MOVE/POINTER_DOWN/+//   POINTER_UP. Anything else maps to 0 and then defaults back to DOWN -- mirrored+//   in InputCodec.motionAction rather than fixed, because the head unit decides.+// - `action_index` indexes the pointers list for the POINTER_DOWN/UP actions.+// - Coordinates arrive in head-unit touchscreen pixels (discovery `TouchConfig`+//   width/height, DHU default 800x480) and are scaled to car-display pixels by+//   the receiver; see InputCodec.scaleCoordinate.+//+// Key mapping, from `ikb.h`: KeyEvent(code=field1, down=field2, meta=field3) --+// field3 sits in the KeyEvent metaState position. Field4 is observed but its exact+// HU intent is undecoded: a key-UP carrying it makes gearhead synthesize a full+// down+up pair (`jar.java` fallback branch), so it is kept as `field4` rather+// than given a confident wrong name.+//+// Scroll, from `jar.java` relative handling: RelativeEvent{keycode=65536, delta}+// with a non-zero delta becomes an ACTION_SCROLL MotionEvent with AXIS_VSCROLL set+// to the delta and SOURCE_MOUSE. AbsoluteEvent{keycode=65541, value} is the+// touchpad tap-as-select: value 1 presses KEYCODE_DPAD_CENTER, 0 releases it.++syntax = "proto2";++package gal;++option java_package = "com.vayunmathur.auto.protocol.gal";+option java_multiple_files = true;++// `xom.e` via `wox.A`, minus one: these already ARE the MotionEvent actions.+enum TouchAction {+  TOUCH_DOWN = 0;+  TOUCH_UP = 1;+  TOUCH_MOVE = 2;+  TOUCH_POINTER_DOWN = 5;+  TOUCH_POINTER_UP = 6;+}++// One finger: `xol` (`iyd`), fields in order x, y, pointer id.+message TouchPointer {+  required uint32 x = 1;+  required uint32 y = 2;+  required uint32 pointer_id = 3;+}++// One touch frame: `xom`. Field 3 is the touchscreen, field 7 the touchpad.+message TouchEvent {+  repeated TouchPointer pointers = 1;+  optional uint32 action_index = 2;+  optional TouchAction action = 3;+}++// One key press or release: `xke`.+message KeyEvent {+  required uint32 keycode = 1;+  required bool key_down = 2;+  required uint32 meta_state = 3;+  optional bool field4 = 4;+}++// One rotary/scroll tick: `xno`. Scroll is keycode 65536 with a non-zero delta.+message RelativeEvent {+  required uint32 keycode = 1;+  required int32 delta = 2;+}++message RelativeEvents {+  repeated RelativeEvent event = 1;+}++// One absolute input value: `xgw`. Keycode 65541 is tap-as-select.+message AbsoluteEvent {+  required uint32 keycode = 1;+  required int32 value = 2;+}++message AbsoluteEvents {+  repeated AbsoluteEvent event = 1;+}++// The key-event list inside a report: `xkf`.+message KeyEvents {+  repeated KeyEvent events = 1;+}++// The head-unit-to-phone report: `xjt`. Field 1 is the report timestamp;+// every section is optional and the phone handles whichever are present.+message InputReport {+  required uint64 timestamp = 1;+  optional TouchEvent touchscreen = 3;+  optional KeyEvents key_events = 4;+  optional AbsoluteEvents abs_events = 5;+  optional RelativeEvents relative_events = 6;+  optional TouchEvent touchpad = 7;+  // Field 2 is absent from this build.+}++// Phone-to-head-unit, sent on channel open: `xkb`. The phone echoes the keycode+// list the head unit advertised in discovery (`ikb.r` sends `this.c`, which came+// from `xjw` field 1 via `wub.ay`).+message KeyBindingRequest {+  repeated int32 keycodes = 1 [packed = true];+}++// Head-unit-to-phone answer: `xkc`, a single status (field 1).+message KeyBindingResponse {+  required int32 status = 1;+}++// Phone-to-head-unit feedback event: `xjs` (`ikb.n` sends one per `xji` event+// from the discovery-advertised set). The field carries the feedback event id;+// like `xjw` field 4 it is enum-typed on the wire and int32 here.+message InputFeedback {+  optional int32 feedback_event = 1;+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/InputCodecTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/InputCodecTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/InputCodecTest.ktnew file mode 100644index 0000000000..719bc44891--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/InputCodecTest.kt@@ -0,0 +1,219 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.InputReport+import com.vayunmathur.auto.protocol.gal.KeyBindingRequest+import com.vayunmathur.auto.protocol.gal.TouchAction+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pins the input-channel (service 8) wire format and the codec around it.+ *+ * Exact bytes where the head unit cares (the keybinding echo), round-trips+ * everywhere else: a round-trip passes happily with a wrong field number and+ * the failure only shows up as a head unit that ignores us.+ */+class InputCodecTest {++    @Test+    fun `KeyBindingRequest packs the keycodes into field 1`() {+        val (type, payload) = InputCodec.encodeKeyBinding(listOf(19, 20, 21))+        assertEquals(GalMessage.Input.KEY_BINDING_REQUEST, type)+        assertContentEquals(+            byteArrayOf(+                0x0A, 0x03, // field 1, length-delimited, 3 bytes+                0x13, 0x14, 0x15, // 19, 20, 21+            ),+            payload,+        )+        // And it parses back through the generated class the head unit reads.+        val parsed = KeyBindingRequest.parseFrom(payload)+        assertEquals(listOf(19, 0x14, 0x15), parsed.keycodesList)+    }++    @Test+    fun `key binding response pins status in field 1`() {+        // `xkc`: single int32 field 1. STATUS_SUCCESS = 0 encodes as 08 00.+        val parsed = InputCodec.decodeKeyBindingResponse(byteArrayOf(0x08, 0x00))+        assertEquals(0, parsed.status)+    }++    @Test+    fun `a touch down round-trips with its pointer and index`() {+        val payload = InputCodec.buildReport(+            timestamp = 7,+            action = TouchAction.TOUCH_DOWN,+            pointers = listOf(InputPointer(x = 400, y = 240, pointerId = 0)),+            actionIndex = 0,+        )+        val events = InputCodec.decodeInbound(GalMessage.Input.REPORT, payload)+            ?: error("expected a decoded report")+        assertEquals(7L, events.timestamp)+        val touch = events.touches.single()+        assertEquals(TouchAction.TOUCH_DOWN, touch.action)+        assertEquals(InputPointer(400, 240, 0), touch.pointers.single())+        assertEquals(0, touch.actionIndex)+        assertTrue(events.keys.isEmpty())+        assertTrue(events.scrolls.isEmpty())+        assertTrue(events.absolutes.isEmpty())+    }++    @Test+    fun `a multitouch frame keeps every pointer and the action index`() {+        val payload = InputCodec.buildReport(+            action = TouchAction.TOUCH_POINTER_DOWN,+            pointers = listOf(+                InputPointer(x = 100, y = 100, pointerId = 0),+                InputPointer(x = 700, y = 380, pointerId = 1),+            ),+            actionIndex = 1,+        )+        val touch = InputCodec.decodeInbound(GalMessage.Input.REPORT, payload)!!+            .touches.single()+        assertEquals(TouchAction.TOUCH_POINTER_DOWN, touch.action)+        assertEquals(2, touch.pointers.size)+        assertEquals(1, touch.actionIndex)+        assertEquals(1, touch.pointers[1].pointerId)+    }++    @Test+    fun `an out-of-range action index clamps to the last pointer`() {+        // `jar.java` logs "Bad InputReport" when the index exceeds the count;+        // the codec clamps instead so one bad index cannot kill the frame.+        val payload = InputCodec.buildReport(+            pointers = listOf(InputPointer(x = 10, y = 10, pointerId = 0)),+            actionIndex = 9,+        )+        val touch = InputCodec.decodeInbound(GalMessage.Input.REPORT, payload)!!+            .touches.single()+        assertEquals(0, touch.actionIndex)+    }++    @Test+    fun `key down and up decode with their keycodes`() {+        val payload = InputCodec.buildKeyReport(+            timestamp = 3,+            19 to true,+            19 to false,+        )+        val events = InputCodec.decodeInbound(GalMessage.Input.REPORT, payload)!!+        assertEquals(3L, events.timestamp)+        assertEquals(listOf(InputKey(19, true), InputKey(19, false)), events.keys)+        assertTrue(events.touches.isEmpty())+    }++    @Test+    fun `a scroll tick decodes to its delta`() {+        val payload = InputCodec.buildScrollReport(delta = -1)+        val events = InputCodec.decodeInbound(GalMessage.Input.REPORT, payload)!!+        assertEquals(listOf(InputCodec.SCROLL_KEYCODE to -1), events.scrolls)+    }++    @Test+    fun `a zero scroll delta is dropped`() {+        // `jar.java` ignores zero-delta relative events outright.+        val payload = InputCodec.buildScrollReport(delta = 0)+        val events = InputCodec.decodeInbound(GalMessage.Input.REPORT, payload)!!+        assertTrue(events.scrolls.isEmpty())+    }++    @Test+    fun `an absolute value passes through with its keycode`() {+        val payload = InputCodec.buildAbsoluteReport(+            keycode = InputCodec.TAP_SELECT_KEYCODE,+            value = 1,+        )+        val events = InputCodec.decodeInbound(GalMessage.Input.REPORT, payload)!!+        assertEquals(listOf(InputCodec.TAP_SELECT_KEYCODE to 1), events.absolutes)+    }++    @Test+    fun `anything but a report decodes to null`() {+        // A type that is not a report on ch8 is not ours. Note 0x8001 IS the+        // report here: it aliases media start, sensor request and messaging+        // threads on other services, so that aliasing is defeated one layer+        // up by channel-id routing (InputChannel.onMessage), never by type.+        assertNull(+            InputCodec.decodeInbound(+                GalMessage.Input.KEY_BINDING_REQUEST,+                InputCodec.buildReport(),+            ),+        )+        assertNull(+            InputCodec.decodeInbound(+                GalMessage.Input.KEY_BINDING_RESPONSE,+                byteArrayOf(0x08, 0x00),+            ),+        )+    }++    @Test+    fun `malformed bytes decode to null, never throw`() {+        assertNull(InputCodec.decodeInbound(GalMessage.Input.REPORT, byteArrayOf(0xFF.toByte())))+        assertNull(InputCodec.decodeInbound(GalMessage.Input.REPORT, ByteArray(0)))+    }++    @Test+    fun `a report without its required timestamp decodes to null`() {+        // Field 1 is required (`xjt` checkInit): an uninitialized report is+        // corrupt traffic, not an empty one. `buildPartial` skips the+        // builder-side required check so the payload reaches the codec.+        val payload = InputReport.newBuilder().buildPartial().toByteArray()+        assertNull(InputCodec.decodeInbound(GalMessage.Input.REPORT, payload))+    }++    @Test+    fun `identity scaling keeps DHU pixels on a DHU-sized display`() {+        // DHU default is 800x480 with a matching display: nothing moves.+        val pointer = InputPointer(x = 400, y = 240, pointerId = 0)+        assertEquals(+            pointer,+            InputCodec.scalePointer(pointer, 800, 480, 800, 480),+        )+    }++    @Test+    fun `scaling maps the DHU touchscreen onto a tall car display`() {+        // 800x480 head-unit pixels onto the 1440x2560 car grid: each axis+        // scales independently, rounding to the nearest pixel.+        val scaled = InputCodec.scalePointer(+            InputPointer(x = 400, y = 240, pointerId = 0),+            huWidth = InputCodec.DEFAULT_HU_WIDTH,+            huHeight = InputCodec.DEFAULT_HU_HEIGHT,+            displayWidth = 1440,+            displayHeight = 2560,+        )+        assertEquals(InputPointer(x = 720, y = 1280, pointerId = 0), scaled)+    }++    @Test+    fun `corners map to corners`() {+        // Nearest-pixel rounding of a through-origin scale: the extreme+        // head-unit pixel lands one short of the extreme display pixel+        // (799/800 across is 1438.2, 479/480 down is 2554.7), immaterial+        // for injection; the tall-display test pins the exact factor.+        assertEquals(0, InputCodec.scaleCoordinate(0, 800, 1440, 800))+        assertEquals(1438, InputCodec.scaleCoordinate(799, 800, 1440, 800))+        assertEquals(2555, InputCodec.scaleCoordinate(479, 480, 2560, 480))+    }++    @Test+    fun `a missing head-unit size falls back to the DHU default`() {+        // No touchscreen config in discovery: divide by the 800x480 default+        // rather than by zero.+        assertEquals(400, InputCodec.scaleCoordinate(400, 0, 800, 800))+        assertEquals(240, InputCodec.scaleCoordinate(240, -1, 480, 480))+    }++    @Test+    fun `input message ids are the raw wire values`() {+        // `jar.a()` compares raw ids (no `wub.o` shift): the report the head+        // unit sends is 0x8001 and the binding answer is 0x8003.+        assertEquals(0x8001, GalMessage.Input.REPORT)+        assertEquals(0x8002, GalMessage.Input.KEY_BINDING_REQUEST)+        assertEquals(0x8003, GalMessage.Input.KEY_BINDING_RESPONSE)+    }+}
auto/src/main/java/com/vayunmathur/auto/platform/InputChannel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/InputChannel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/InputChannel.ktnew file mode 100644index 0000000000..b91207bdb7--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/InputChannel.kt@@ -0,0 +1,147 @@+package com.vayunmathur.auto.platform++import android.util.Log+import com.vayunmathur.auto.protocol.GalConnection+import com.vayunmathur.auto.protocol.GalMessage+import com.vayunmathur.auto.protocol.InputCodec+import com.vayunmathur.auto.protocol.InputKey+import com.vayunmathur.auto.protocol.InputPointer+import com.vayunmathur.auto.protocol.gal.Service++/**+ * A touch frame scaled to car-display pixels, ready to inject.+ *+ * [action] already IS the `MotionEvent` action: the head unit numbers touch+ * actions exactly as `MotionEvent` does (DOWN 0, UP 1, MOVE 2, POINTER_DOWN 5,+ * POINTER_UP 6), so it passes through verbatim and only the POINTER_DOWN/UP+ * variants need the index shifted in at injection time.+ */+data class ScaledTouch(+    val action: Int,+    val pointers: List<InputPointer>,+    val actionIndex: Int,+)++/**+ * The input source channel: turns head-unit touch, keys and scroll into car+ * UI events once the head unit grants the channel.+ *+ * Bring-up needs nothing beyond the generic open: ch8 opens in the wire-order+ * pass like every other service, and the binding request goes out on the+ * grant -- sending on a channel the head unit has not opened earns a bare+ * MessageError (0xff). Injection itself gates on the arbitrated input flag+ * (projected video WITH input focus): a `PROJECTED_NO_INPUT_FOCUS` head unit+ * still streams video but its input must be dropped, as must everything while+ * the car shows its own UI.+ *+ * Route by channel id: 0x8001 is aliased across services (media start, sensor+ * request, messaging threads), so only ch8 traffic belongs to [InputCodec].+ * The 0x04 CONTROL frame flag does NOT mean "control channel" (HANDOFF.md+ * section 9) and never enters this decision.+ */+class InputChannel(+    private val service: Service,+    private val connection: GalConnection,+    /** Arbitrated input flag; the service reads it off the session's focus state. */+    private val isInputAllowed: () -> Boolean = { false },+    /** Current car-display size in pixels, or null before video streaming starts. */+    private val displaySize: () -> Pair<Int, Int>? = { null },+    /** Fire-and-forget observations for the phone status screen; never gates. */+    private val onEvent: (InputEvent) -> Unit = {},+    /** Injects one scaled touch frame; returns whether it was consumed. */+    private val touchSink: (ScaledTouch) -> Boolean = { false },+    /** Injects one key press or release; returns whether it was consumed. */+    private val keySink: (InputKey) -> Boolean = { false },+    /** Injects one scroll tick; returns whether it was consumed. */+    private val scrollSink: (delta: Int) -> Boolean = { false },+) {+    val channelId: Int get() = service.id++    /** Head-unit touchscreen size, or the DHU default when undiscovered. */+    private val huSize: Pair<Int, Int> =+        service.inputSource.touchscreenList.firstOrNull()?.let { it.width to it.height }+            ?: (InputCodec.DEFAULT_HU_WIDTH to InputCodec.DEFAULT_HU_HEIGHT)++    /**+     * The grant arrived: echo the discovery-advertised keycodes back so the+     * head unit knows which keys we handle. Called once per channel open.+     */+    fun requestBinding() {+        val keycodes = service.inputSource.keycodesSupportedList+        val (type, payload) = InputCodec.encodeKeyBinding(keycodes)+        connection.send(channelId, type, payload)+        Log.i(TAG, "input channel open; bound ${keycodes.size} keycodes")+        onEvent(InputEvent.BindingRequested(keycodes.size))+    }++    /** One message for this channel; anything else is ignored, never misparsed. */+    fun onMessage(channelId: Int, type: Int, payload: ByteArray) {+        if (channelId != this.channelId) {+            Log.w(TAG, "ignoring 0x${type.toString(16)} for channel $channelId")+            return+        }+        if (type == GalMessage.Input.KEY_BINDING_RESPONSE) {+            val status = runCatching { InputCodec.decodeKeyBindingResponse(payload) }.getOrNull()+            Log.i(TAG, "key binding response: ${status?.status}")+            onEvent(InputEvent.BindingAnswered(status?.status ?: -1))+            return+        }+        val events = InputCodec.decodeInbound(type, payload)+        if (events == null) {+            Log.d(TAG, "unhandled input message 0x${type.toString(16)}")+            return+        }+        if (!isInputAllowed()) {+            Log.d(TAG, "dropping ${events.describe()} without input focus")+            onEvent(InputEvent.DroppedNoFocus)+            return+        }+        val display = displaySize()+        if (display == null) {+            Log.d(TAG, "dropping ${events.describe()} with no car display yet")+            onEvent(InputEvent.DroppedNoFocus)+            return+        }+        val (displayWidth, displayHeight) = display+        events.touches.forEach { touch ->+            val scaled = ScaledTouch(+                action = touch.action.number,+                pointers = touch.pointers.map {+                    InputCodec.scalePointer(+                        it,+                        huWidth = huSize.first,+                        huHeight = huSize.second,+                        displayWidth = displayWidth,+                        displayHeight = displayHeight,+                    )+                },+                actionIndex = touch.actionIndex,+            )+            if (touchSink(scaled)) onEvent(InputEvent.Touch(scaled.action, scaled.pointers.size))+        }+        events.keys.forEach { key ->+            if (keySink(key)) onEvent(InputEvent.Key(key.keycode, key.down))+        }+        // Tap-as-select rides the absolute section: keycode 65541, value 1+        // presses DPAD_CENTER and anything else releases it (`jar.java`).+        events.absolutes.forEach { (keycode, value) ->+            if (keycode == InputCodec.TAP_SELECT_KEYCODE) {+                val key = InputKey(InputCodec.KEYCODE_DPAD_CENTER, value == 1)+                if (keySink(key)) onEvent(InputEvent.Key(key.keycode, key.down))+            } else {+                Log.d(TAG, "ignoring absolute event keycode=$keycode value=$value")+            }+        }+        events.scrolls.forEach { (_, delta) ->+            if (scrollSink(delta)) onEvent(InputEvent.Scroll(delta))+        }+    }++    private companion object {+        const val TAG = "MaAuto.Input"++        private fun com.vayunmathur.auto.protocol.InputEvents.describe(): String =+            "input report (${touches.size} touch, ${keys.size} keys, " ++                "${scrolls.size} scroll, ${absolutes.size} abs)"+    }+}
auto/src/main/java/com/vayunmathur/auto/platform/InputEvent.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/InputEvent.kt b/auto/src/main/java/com/vayunmathur/auto/platform/InputEvent.ktnew file mode 100644index 0000000000..91c11580af--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/InputEvent.kt@@ -0,0 +1,29 @@+package com.vayunmathur.auto.platform++/**+ * Something the input channel observed, forwarded to [AutoSessionState] for the phone UI.+ *+ * Injection never waits on these: they are fire-and-forget observations, mirroring+ * [VideoEvent] and [MessagingEvent]. The phone status screen counts touches, keys+ * and drops so the operator can tell "head unit sends, phone injects" from+ * "gated on focus" without a live run.+ */+sealed interface InputEvent {+    /** The binding request went out on the ch8 grant; [count] is keycodes echoed. */+    data class BindingRequested(val count: Int) : InputEvent++    /** The head unit answered the binding request with [status] (0 is success). */+    data class BindingAnswered(val status: Int) : InputEvent++    /** One touch frame was injected: [action] is the MotionEvent action verbatim. */+    data class Touch(val action: Int, val pointerCount: Int) : InputEvent++    /** One key press or release was injected. */+    data class Key(val keycode: Int, val down: Boolean) : InputEvent++    /** One scroll tick was injected. */+    data class Scroll(val delta: Int) : InputEvent++    /** A report arrived but the arbitrated input flag was off, so it was dropped. */+    data object DroppedNoFocus : InputEvent+}