maauto: maps mirror path plus host-vs-mirror decision
- Commit
78d0d4c656f507a0b3ae1931d06475ba9f88638e- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-12 22:12 UTC (2 months ago)
- Parents
e21897b
Diff
auto/build.gradle.kts
diff --git a/auto/build.gradle.kts b/auto/build.gradle.ktsindex efd1ab5813..181348bd7b 100644--- a/auto/build.gradle.kts+++ b/auto/build.gradle.kts@@ -16,4 +16,9 @@ dependencies { implementation(project(":auto:protocol")) // Media3 controller for the Phase 4 now-playing feed from the on-device media session. implementation(libs.androidx.media3.session)+ // Phase 6 maps mirror: CarMapsMirror draws the :library:map basemap+ // (SurfaceMapRenderer) into the car video path. No maps-app dependency --+ // the mirror reads the renderer only, and guidance arrives as plain+ // NavSnapshot data through NavGuidanceMonitor.+ implementation(project(":library:map")) }
auto/docs/HANDOFF.md
diff --git a/auto/docs/HANDOFF.md b/auto/docs/HANDOFF.mdindex f514579152..51d31d6463 100644--- a/auto/docs/HANDOFF.md+++ b/auto/docs/HANDOFF.md@@ -61,6 +61,90 @@ protocol — nothing to do with the OS or with privileges. --- +## 10. Phase 6 — Maps mirror + host-vs-mirror decision (maps-dev, task 9)++**Decision: MIRROR. The host stays a prototype.**++The head unit only ever sees our ch2 H.264, so the host path adds a second+renderer, a service bind and a template round-trip without changing a single+wire byte. `HostVsMirror.recommend` (pure, JVM-tested in+`HostVsMirrorTest`) says MIRROR whenever the `:library:map` renderer loads --+which is every arm64 build -- and only says HOST when the host is fully+ready (maps car-app service present, projection role held, `app-projected`+on the classpath) AND the mirror cannot draw at all (no renderer, no+location). `GearheadHostProbe.probe` gathers those facts on device without+hard-linking the host stack (`Class.forName`, never an import); its+one-line verdict feeds this report and the phone debug row, not a live+switch. Mirror is the session default regardless.++Side-by-side (prototype comparison, no DHU run in this environment):++| | Mirror (`CarMapsMirror`) | Host (`MapsCarAppService`) |+|---|---|---|+| Renderer | own `SurfaceMapRenderer`, same archive/tiles as the phone map | car-app host surface via `app-projected` |+| Wire cost | zero new bytes: pixels ride existing ch2 H.264 | same ch2 H.264 plus service bind + template round-trip |+| Latency | one Choreographer loop, on-demand frames | host surface callback + our encode on top |+| Fidelity | full basemap, puck, route, POI; heading-up flat (renderer has no tilt) | `NavigationTemplate` maneuvers + ETA for free |+| Needs role? | no (offscreen surface, no trusted display) | yes (`SYSTEM_AUTOMOTIVE_PROJECTION` for host bind) |+| Needs Maps app? | no (renderer only, `:library:map` dep) | yes (`com.vayunmathur.maps` installed with car service) |+| Fallback | is the fallback | mirror stays fallback even if host prototypes |++What landed (all new files; no other agent's in-flight file touched):++- `auto/protocol/.../MapsGuidance.kt` -- pure `NavSnapshot` shaping:+ `snapshotFromFix` (decimal degrees to e7), `toSensorEvents` (LOCATION /+ SPEED / DRIVING_STATUS always, NIGHT only when known so unknown keeps+ last-known), `toNavStatus` + `encodeNavStatus` (ch10 args + wire render+ through `NavStatusCodec`). Android-free, JVM-tested in+ `MapsGuidanceTest` (6 tests).+- `auto/protocol/.../HostVsMirror.kt` -- pure `HostFacts` / `MirrorFacts`+ / `recommend` (JVM-tested in `HostVsMirrorTest`, 6 tests).+- `platform/NavGuidanceMonitor.kt` -- GPS + network fixes into+ `NavSnapshot`s (last-known seed, motion-heuristic parked, GPS-course+ bearing above 1 m/s else null cone-off, phone-night read); route+ guidance overlays through the `RouteProvider` seam (null = idle map).+ Same "monitor owns its source" shape as `MediaPlaybackMonitor`.+- `platform/CarMapsMirror.kt` -- `SurfaceMapRenderer` into a caller-owned+ surface (own renderer beside the encoder's; composition is the+ bring-up owner's work). Route pushes gated by reference identity, like+ `NavMapScreen.pushedRoute`. Main-thread marshalled; `setDark` follows+ the system theme.+- `platform/GearheadHostProbe.kt` -- on-device fact gathering + one-line+ verdict (`describe()` / `log()`), no host hard-link.+- `auto/build.gradle.kts` -- `implementation(project(":library:map"))`+ for the mirror only.++Guidance hooks for sensors-dev (their channels, their files -- seams only):++- ch7 live values: fold `MapsGuidance.toSensorEvents(snapshot)` through+ `SensorChannel`'s `onValues` seam into `SensorSnapshot.withEvents`.+ The monitor's night read duplicates `ProjectionService.isNightNow`+ deliberately (that file is in-flight); pass the monitor's read in as+ the `NightSource` so the two agree, and dedup when the tree settles.+- ch10 turn updates: forward `MapsGuidance.toNavStatus(snapshot)` to+ `NavStatusChannel.postStatus` as the route advances; the grant-time+ inactive stub stays the no-guidance state.+- ch3 TTS: `GuidanceChannel.startStream` / `stopStream` stay audio-dev's;+ the monitor produces no audio, only the timing (guidanceActive flips)+ a TTS owner could cue on.+- ch8 map touches: route through `VideoSinkChannel` /+ `CarDisplay.injectTouch` like the media card tap -- the mirror draws+ into its own surface, so pan/zoom needs the service to forward scaled+ ch8 frames to the mirror's gesture path (not yet wired; the mirror+ exposes no gesture entry point on purpose until the service owns the+ composition).++Verdict status: Maps visible + pannable and the guidance stub stable are+**not yet shown** -- no DHU/ADB in this environment by hygiene rule. The+JVM leg is green (`:auto:protocol:testDebugUnitTest`); the live leg (DHU+shows the mirror, ch8 pans it, ch10 posts live turns) needs a DHU + Pixel+run and belongs to the task 4 (DHU live-verification) owner via the+`ma-auto-parity` team channel.++---++## 9. Decompiler traps+ ## 3. The blocker, precisely — RESOLVED (Tasks 3+6) DHU *used to* answer our ServiceDiscoveryRequest (control message 5) with
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/HostVsMirror.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/HostVsMirror.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/HostVsMirror.ktnew file mode 100644index 0000000000..5771e54f77--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/HostVsMirror.kt@@ -0,0 +1,67 @@+package com.vayunmathur.auto.protocol++/**+ * Facts the host-vs-mirror prototype compares (Phase 6, maps-dev).+ *+ * The two paths render the same drive two different ways:+ *+ * - MIRROR: MA Auto draws the `:library:map` basemap itself (own+ * `SurfaceMapRenderer`, camera, puck and route) into the ch2 video stream.+ * The pixels are ours end to end; the head unit only ever sees H.264.+ * - HOST: the `:maps` car app (`MapsCarAppService`, a Car App Library+ * `NAVIGATION` service) renders through a car-app host, and MA Auto would+ * carry the host's surface into ch2 instead of drawing its own map.+ *+ * All fields are plain data gathered on the Android side by+ * `GearheadHostProbe`; the recommendation itself is pure so it stays+ * host-testable here.+ */+data class HostFacts(+ /** The `:maps` car-app service resolves through PackageManager. */+ val mapsServicePresent: Boolean,+ /** Our package holds `SYSTEM_AUTOMOTIVE_PROJECTION` (trusted display + injection). */+ val holdsProjectionRole: Boolean,+ /** The car-app host connection (`app-projected`) is on the classpath. */+ val hostLibraryPresent: Boolean,+)++data class MirrorFacts(+ /** `:library:map`'s renderer class loads (native Vulkan still gates first frame). */+ val rendererPresent: Boolean,+ /** Phone GPS is available for the puck and camera. */+ val locationAvailable: Boolean,+ /** An active route is overlaid (guidance), or null when idle map only. */+ val routeActive: Boolean,+)++//** Which path the session should render maps through. */+enum class MapsPath {+ /** Draw our own basemap into ch2; host stays a prototype. */+ MIRROR,++ /** Carry the car-app host's surface into ch2 instead. */+ HOST,+}++/**+ * Pure host-vs-mirror recommendation (Phase 6 prototype comparison).+ *+ * Mirror wins by default and host needs a measured win, per the plan:+ * the head unit only ever sees our ch2 H.264, so the host path adds a+ * second renderer, a service bind and a template round-trip without+ * changing a single wire byte. Host is recommended only when every host+ * fact holds AND the mirror cannot draw (no renderer, no location): a+ * host surface with no position is still a map, while no renderer at all+ * is a black card.+ */+object HostVsMirror {++ fun recommend(host: HostFacts, mirror: MirrorFacts): MapsPath {+ if (mirror.rendererPresent) return MapsPath.MIRROR+ val hostReady = host.mapsServicePresent &&+ host.holdsProjectionRole &&+ host.hostLibraryPresent+ if (hostReady && !mirror.locationAvailable) return MapsPath.HOST+ return MapsPath.MIRROR+ }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MapsGuidance.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MapsGuidance.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MapsGuidance.ktnew file mode 100644index 0000000000..d192292338--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MapsGuidance.kt@@ -0,0 +1,176 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.DrivingStatusReading+import com.vayunmathur.auto.protocol.gal.LocationReading+import com.vayunmathur.auto.protocol.gal.NightReading+import com.vayunmathur.auto.protocol.gal.SensorEvent+import com.vayunmathur.auto.protocol.gal.SensorType+import com.vayunmathur.auto.protocol.gal.SpeedReading+import kotlin.math.roundToLong++/**+ * One point of the active route polyline, in degrees.+ *+ * Own data class rather than `:library:map`'s `GeoPoint`: `auto/protocol`+ * stays Android-free and must not take a renderer dependency. The car mirror+ * (`CarMapsMirror`) maps these onto `GeoPoint` one for one.+ */+data class MapRoutePoint(+ val longitude: Double,+ val latitude: Double,+)++/**+ * The phone-side navigation picture, in one snapshot.+ *+ * Produced on the Android side by `NavGuidanceMonitor` (GPS fix plus the+ * maps-module route provider) and consumed three ways: folded into+ * [SensorSnapshot] through [MapsGuidance.toSensorEvents] for the ch7 live+ * values, posted onto ch10 through [NavStatusUpdate] for the cluster, and+ * rendered by `CarMapsMirror` into the ch2 video stream.+ *+ * Plain data, no Android types, so the whole mapping is host-testable. A+ * snapshot with [guidanceActive] false and a null [route] is the idle map:+ * position and puck only, which is what the monitor produces before the+ * maps provider binds or when no route is active.+ */+data class NavSnapshot(+ /** Fix latitude x10^7, matching `LocationReading.latitude_e7`. */+ val latitudeE7: Long,+ /** Fix longitude x10^7, matching `LocationReading.longitude_e7`. */+ val longitudeE7: Long,+ /** Fix accuracy in metres, or null when the provider does not know it. */+ val accuracyM: Int? = null,+ /** Fix wall-clock millis, or null when the provider does not know it. */+ val fixTimestampMs: Long? = null,+ /** GPS ground speed in metres/second; 0 when unknown or stationary. */+ val speedMps: Double = 0.0,+ /** Whether the vehicle is parked; true until motion says otherwise. */+ val parked: Boolean = true,+ /** Phone night state, or null when unknown (keeps last-known downstream). */+ val isNight: Boolean? = null,+ /** Whether turn-by-turn guidance is actively navigating. */+ val guidanceActive: Boolean = false,+ /** Next road name, or null when idle or unnamed. */+ val nextRoad: String? = null,+ /** Metres to the next maneuver, or null when idle. */+ val nextTurnDistanceM: Int? = null,+ /** Maneuver token for the upcoming turn, or null when idle. */+ val maneuver: String? = null,+ /** Course over ground, degrees clockwise from north, or null with no heading. */+ val bearingDeg: Float? = null,+ /** Active route polyline, or null when idle or unknown. */+ val route: List<MapRoutePoint>? = null,+)++/**+ * Turn-guidance arguments for `NavStatusChannel.postStatus`, as data.+ *+ * Mirrors that signature one for one so the service can forward without+ * reshaping; [MapsGuidance.encodeNavStatus] renders the same update to the+ * wire for tests and head-unit stand-ins.+ */+data class NavStatusUpdate(+ val guidanceActive: Boolean,+ val nextRoad: String? = null,+ val nextTurnDistanceM: Int? = null,+ val maneuver: String? = null,+)++/**+ * Pure guidance producers (Phase 6, maps-dev): navigation snapshot shaping+ * plus the hooks sensors-dev consumes.+ *+ * Android-free like everything else in this module. The service-side wiring+ * (which owns the channels) is documented in `auto/docs/HANDOFF.md` §10;+ * this file only builds the payloads:+ *+ * - ch7 live values: [toSensorEvents] builds the `gal.SensorEvent` list a+ * `SensorChannel` folds through `SensorSnapshot.withEvents`. Night is+ * omitted (not posted empty) when [NavSnapshot.isNight] is null, so an+ * unknown phone state keeps last-known instead of clobbering it -- the+ * same payload-less rule `withEvents` already enforces.+ * - ch10 turn updates: [toNavStatus] selects the post arguments;+ * [encodeNavStatus] renders them through [NavStatusCodec].+ */+object MapsGuidance {++ /**+ * Builds a snapshot from a decimal-degrees fix.+ *+ * Guidance and route fields stay at their idle defaults: the caller+ * overlays the maps provider's route state (or leaves idle) afterwards.+ */+ fun snapshotFromFix(+ latitude: Double,+ longitude: Double,+ accuracyM: Int? = null,+ fixTimestampMs: Long? = null,+ speedMps: Double = 0.0,+ parked: Boolean = true,+ isNight: Boolean? = null,+ ): NavSnapshot = NavSnapshot(+ latitudeE7 = (latitude * E7).roundToLong(),+ longitudeE7 = (longitude * E7).roundToLong(),+ accuracyM = accuracyM,+ fixTimestampMs = fixTimestampMs,+ speedMps = speedMps,+ parked = parked,+ isNight = isNight,+ )++ /**+ * Renders [snapshot] as the ch7 event list.+ *+ * Always LOCATION, SPEED and DRIVING_STATUS (stub parity: the stub set+ * subscribes to exactly these plus NIGHT_MODE), with NIGHT appended only+ * when the snapshot knows the phone state. Deterministic order so tests+ * and stand-ins can pin it.+ */+ fun toSensorEvents(snapshot: NavSnapshot): List<SensorEvent> {+ val events = ArrayList<SensorEvent>(4)+ val fix = LocationReading.newBuilder()+ .setLatitudeE7(snapshot.latitudeE7)+ .setLongitudeE7(snapshot.longitudeE7)+ if (snapshot.accuracyM != null) fix.accuracyM = snapshot.accuracyM+ if (snapshot.fixTimestampMs != null) fix.timestampMs = snapshot.fixTimestampMs+ events += SensorEvent.newBuilder()+ .setSensorType(SensorType.LOCATION)+ .setLocation(fix)+ .build()+ events += SensorEvent.newBuilder()+ .setSensorType(SensorType.SPEED)+ .setSpeed(SpeedReading.newBuilder().setSpeedMps(snapshot.speedMps))+ .build()+ events += SensorEvent.newBuilder()+ .setSensorType(SensorType.DRIVING_STATUS_DATA)+ .setDrivingStatus(DrivingStatusReading.newBuilder().setParked(snapshot.parked))+ .build()+ if (snapshot.isNight != null) {+ events += SensorEvent.newBuilder()+ .setSensorType(SensorType.NIGHT_MODE)+ .setNight(NightReading.newBuilder().setIsNight(snapshot.isNight))+ .build()+ }+ return events+ }++ /** Selects the ch10 post arguments for [snapshot]. */+ fun toNavStatus(snapshot: NavSnapshot): NavStatusUpdate = NavStatusUpdate(+ guidanceActive = snapshot.guidanceActive,+ nextRoad = snapshot.nextRoad,+ nextTurnDistanceM = snapshot.nextTurnDistanceM,+ maneuver = snapshot.maneuver,+ )++ /** Renders [update] to the ch10 wire type plus payload. */+ fun encodeNavStatus(update: NavStatusUpdate): Pair<Int, ByteArray> =+ NavStatusCodec.encodeStatus(+ update.guidanceActive,+ update.nextRoad,+ update.nextTurnDistanceM,+ update.maneuver,+ )++ private const val E7 = 10_000_000.0+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/HostVsMirrorTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/HostVsMirrorTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/HostVsMirrorTest.ktnew file mode 100644index 0000000000..db5e38a2ca--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/HostVsMirrorTest.kt@@ -0,0 +1,83 @@+package com.vayunmathur.auto.protocol++import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Pins the host-vs-mirror default (Phase 6, maps-dev): mirror wins unless+ * the host is fully ready AND the mirror cannot draw at all.+ */+class HostVsMirrorTest {++ private val readyHost = HostFacts(+ mapsServicePresent = true,+ holdsProjectionRole = true,+ hostLibraryPresent = true,+ )+ private val fullMirror = MirrorFacts(+ rendererPresent = true,+ locationAvailable = true,+ routeActive = true,+ )++ @Test+ fun `mirror wins when it can draw, even with a ready host`() {+ assertEquals(MapsPath.MIRROR, HostVsMirror.recommend(readyHost, fullMirror))+ }++ @Test+ fun `mirror wins with no host at all`() {+ val noHost = HostFacts(+ mapsServicePresent = false,+ holdsProjectionRole = false,+ hostLibraryPresent = false,+ )+ assertEquals(MapsPath.MIRROR, HostVsMirror.recommend(noHost, fullMirror))+ }++ @Test+ fun `host wins only when ready and the mirror has no renderer and no location`() {+ val deadMirror = MirrorFacts(+ rendererPresent = false,+ locationAvailable = false,+ routeActive = false,+ )+ assertEquals(MapsPath.HOST, HostVsMirror.recommend(readyHost, deadMirror))+ }++ @Test+ fun `missing any one host fact keeps the mirror`() {+ val deadMirror = MirrorFacts(+ rendererPresent = false,+ locationAvailable = false,+ routeActive = false,+ )+ for (missing in listOf(+ readyHost.copy(mapsServicePresent = false),+ readyHost.copy(holdsProjectionRole = false),+ readyHost.copy(hostLibraryPresent = false),+ )) {+ assertEquals(MapsPath.MIRROR, HostVsMirror.recommend(missing, deadMirror))+ }+ }++ @Test+ fun `location alone keeps the mirror: last-known still draws a map`() {+ val noRendererButLocated = MirrorFacts(+ rendererPresent = false,+ locationAvailable = true,+ routeActive = false,+ )+ assertEquals(MapsPath.MIRROR, HostVsMirror.recommend(readyHost, noRendererButLocated))+ }++ @Test+ fun `route state never flips the decision`() {+ val idle = MirrorFacts(+ rendererPresent = true,+ locationAvailable = true,+ routeActive = false,+ )+ assertEquals(MapsPath.MIRROR, HostVsMirror.recommend(readyHost, idle))+ }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/MapsGuidanceTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/MapsGuidanceTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/MapsGuidanceTest.ktnew file mode 100644index 0000000000..34e32511bf--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/MapsGuidanceTest.kt@@ -0,0 +1,130 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.SensorType+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pins the Phase 6 maps-dev guidance producers.+ *+ * Coordinate math and event shaping live here (host-testable); the channel+ * owners stay thin. Exact bytes only for the integer fields the teardown or+ * our own protos pin -- e7 scaling is asserted by value, not by byte.+ */+class MapsGuidanceTest {++ @Test+ fun `fix scales decimal degrees to e7`() {+ val snapshot = MapsGuidance.snapshotFromFix(+ latitude = 37.422,+ longitude = -122.084,+ speedMps = 13.9,+ parked = false,+ isNight = true,+ )+ assertEquals(374_220_000L, snapshot.latitudeE7)+ assertEquals(-1_220_840_000L, snapshot.longitudeE7)+ assertEquals(13.9, snapshot.speedMps, 1e-9)+ assertEquals(false, snapshot.parked)+ assertEquals(true, snapshot.isNight)+ // Guidance and route stay idle until the provider overlays them.+ assertEquals(false, snapshot.guidanceActive)+ assertNull(snapshot.route)+ }++ @Test+ fun `sensor events carry stub parity without night when unknown`() {+ val snapshot = MapsGuidance.snapshotFromFix(+ latitude = 37.0,+ longitude = -122.0,+ accuracyM = 8,+ fixTimestampMs = 42L,+ )+ val events = MapsGuidance.toSensorEvents(snapshot)+ assertEquals(+ listOf(+ SensorType.LOCATION,+ SensorType.SPEED,+ SensorType.DRIVING_STATUS_DATA,+ ),+ events.map { it.sensorType },+ )+ val folded = SensorSnapshot().withEvents(events)+ assertEquals(370_000_000L, folded.location?.latitudeE7)+ assertEquals(-1_220_000_000L, folded.location?.longitudeE7)+ assertEquals(8, folded.location?.accuracyM)+ assertEquals(42L, folded.location?.timestampMs)+ assertEquals(0.0, folded.speedMps, 1e-9)+ assertTrue(folded.parked)+ // Unknown night keeps last-known: the event is omitted, not posted empty.+ assertNull(folded.isNight)+ }++ @Test+ fun `sensor events append night when the phone state is known`() {+ val day = MapsGuidance.toSensorEvents(+ MapsGuidance.snapshotFromFix(0.0, 0.0, isNight = false),+ )+ assertEquals(+ listOf(+ SensorType.LOCATION,+ SensorType.SPEED,+ SensorType.DRIVING_STATUS_DATA,+ SensorType.NIGHT_MODE,+ ),+ day.map { it.sensorType },+ )+ assertEquals(false, SensorSnapshot().withEvents(day).isNight)+ }++ @Test+ fun `nav status selects the post arguments and encodes them`() {+ val snapshot = MapsGuidance.snapshotFromFix(37.0, -122.0).copy(+ guidanceActive = true,+ nextRoad = "Amphitheatre Pkwy",+ nextTurnDistanceM = 250,+ maneuver = "turn-right",+ )+ val update = MapsGuidance.toNavStatus(snapshot)+ assertEquals(+ NavStatusUpdate(+ guidanceActive = true,+ nextRoad = "Amphitheatre Pkwy",+ nextTurnDistanceM = 250,+ maneuver = "turn-right",+ ),+ update,+ )+ val (type, payload) = MapsGuidance.encodeNavStatus(update)+ assertEquals(GalMessage.NavigationStatus.STATUS, type)+ val (directType, directPayload) = NavStatusCodec.encodeStatus(+ true,+ "Amphitheatre Pkwy",+ 250,+ "turn-right",+ )+ assertEquals(directType, type)+ assertContentEquals(directPayload, payload)+ }++ @Test+ fun `idle nav status is guidance off with no turn fields`() {+ val (type, payload) = MapsGuidance.encodeNavStatus(+ MapsGuidance.toNavStatus(MapsGuidance.snapshotFromFix(0.0, 0.0)),+ )+ val (inactiveType, inactivePayload) = NavStatusCodec.encodeInactive()+ assertEquals(inactiveType, type)+ assertContentEquals(inactivePayload, payload)+ }++ @Test+ fun `ch10 status sits in the service range`() {+ val (type, _) = MapsGuidance.encodeNavStatus(+ NavStatusUpdate(guidanceActive = false),+ )+ assertTrue(type in 0x8000..0xFFFF)+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/CarMapsMirror.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarMapsMirror.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarMapsMirror.ktnew file mode 100644index 0000000000..7d5a8b08fb--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarMapsMirror.kt@@ -0,0 +1,185 @@+package com.vayunmathur.auto.platform++import android.content.Context+import android.os.Handler+import android.os.Looper+import android.util.Log+import android.view.Surface+import com.vayunmathur.auto.protocol.NavSnapshot+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.LayerOptions+import com.vayunmathur.library.map.MapRenderState+import com.vayunmathur.library.map.SurfaceMapRenderer+import com.vayunmathur.library.map.UserPuck++/**+ * Draws the phone map into the car video stream (Phase 6 mirror path).+ *+ * This is the short-term Maps answer from the plan: with no gearhead host+ * binding, MA Auto renders the `:library:map` basemap itself -- same+ * renderer, archive and tile cache the phone map uses -- onto an offscreen+ * [Surface] whose frames join the ch2 path, while Phase 2 touch pans it.+ *+ * Two surfaces, two renderers, one map state: the encoder keeps its own+ * input surface (the `CarDisplay` virtual display composites into it), and+ * this mirror draws into [mirrorSurface] with its own `SurfaceMapRenderer`.+ * The service composites or switches between them per the session's+ * [com.vayunmathur.auto.protocol.MapsPath] -- that composition is the+ * bring-up owner's work (see the Phase 6 handoff to the service owner in+ * `auto/docs/HANDOFF.md` §10), not this file's: this file only draws a map+ * into a surface it is handed.+ *+ * Threading follows `SurfaceMapRenderer`'s own rule: every call on the main+ * thread. [render] and [setSurface] marshal onto [mainHandler] so the+ * guidance monitor's worker-thread snapshots stay safe; destruction is+ * synchronous on main like `CarMapRenderer.teardown`.+ *+ * Route identity (not equality) gates the route push, matching+ * `NavMapScreen.pushedRoute`: the native side tessellates on every `set`+ * call, so pushing an equal-but-new list per GPS fix would re-tessellate a+ * cross-city route a few times a second.+ */+class CarMapsMirror(+ context: Context,+ private val density: Float = 1f,+) {+ private val appContext = context.applicationContext+ private val mainHandler = Handler(Looper.getMainLooper())++ private var renderer: SurfaceMapRenderer? = null+ private var mirrorSurface: Surface? = null+ private var mirrorWidth = 0+ private var mirrorHeight = 0++ /** The route polyline already on the GPU, by identity. */+ private var pushedRoute: List<GeoPoint>? = null++ private val isMainThread get() = Looper.myLooper() == Looper.getMainLooper()++ /**+ * Attaches the mirror to [surface] at [widthPx] x [heightPx] pixels.+ *+ * The caller owns [surface] (encoder input or an offscreen target) and+ * must not release it before [release]. Re-attaching tears the previous+ * renderer down first, replaying camera/puck/route on the new one like+ * `CarMapRenderer.onSurfaceAvailable`.+ */+ fun setSurface(surface: Surface, widthPx: Int, heightPx: Int) {+ if (isMainThread) attach(surface, widthPx, heightPx)+ else mainHandler.post { attach(surface, widthPx, heightPx) }+ }++ /**+ * Renders one guidance snapshot into the mirror. Safe from any thread;+ * the push marshals onto main.+ *+ * No-op until [setSurface]: a fix before the surface exists is dropped,+ * and the next fix repaints -- positions arrive at ~1 Hz, so nothing+ * worth queuing is lost. Map follows the system theme through+ * [setDark]; idle (no route) draws north-up with the puck, navigating+ * draws heading-up with the route.+ */+ fun render(snapshot: NavSnapshot) {+ if (isMainThread) push(snapshot)+ else mainHandler.post { push(snapshot) }+ }++ /** Switches the basemap palette; free (push constant, no re-tessellation). */+ fun setDark(dark: Boolean) {+ if (isMainThread) renderer?.setPalette(dark = dark, muted = false)+ else mainHandler.post { renderer?.setPalette(dark = dark, muted = false) }+ }++ /** Tears the renderer down; the caller still owns and releases the surface. */+ fun release() {+ if (isMainThread) teardown()+ else mainHandler.post { teardown() }+ }++ /** Whether the last attach produced a drawing renderer. */+ fun isRendering(): Boolean = renderer?.renderState is MapRenderState.Rendering++ private fun attach(surface: Surface, widthPx: Int, heightPx: Int) {+ if (widthPx <= 0 || heightPx <= 0) return+ teardown()+ mirrorSurface = surface+ mirrorWidth = widthPx+ mirrorHeight = heightPx+ val created = runCatching {+ SurfaceMapRenderer(appContext, density).apply {+ setPalette(dark = false, muted = false)+ setLayers(CAR_LAYERS)+ attachSurface(surface, widthPx, heightPx)+ }+ }.getOrNull() ?: run {+ Log.e(TAG, "car map mirror will not draw: renderer creation failed")+ return+ }+ val state = created.renderState+ if (state is MapRenderState.Unavailable) {+ Log.e(TAG, "car map mirror will not draw: ${state.reason}")+ created.destroy()+ return+ }+ // The route outlives a surface recreation (host rebind, backgrounding):+ // replay the tessellated mesh so the first frame already has it.+ pushedRoute?.let { created.setRoute(it) }+ created.start()+ renderer = created+ }++ private fun push(snapshot: NavSnapshot) {+ val active = renderer ?: return+ val position = GeoPoint(+ longitude = snapshot.longitudeE7 / E7,+ latitude = snapshot.latitudeE7 / E7,+ )+ active.setUserPuck(+ UserPuck(position = position, bearing = snapshot.bearingDeg),+ )+ val navigating = snapshot.guidanceActive && snapshot.route != null+ if (navigating) {+ val points = snapshot.route.map { GeoPoint(it.longitude, it.latitude) }+ // Identity gate: the monitor forwards the provider's list+ // untouched, so an unchanged route skips the tessellation.+ if (points !== pushedRoute) {+ pushedRoute = points+ active.setRoute(points)+ }+ active.camera = com.vayunmathur.library.map.CameraPosition(+ target = position,+ zoom = NAVIGATING_ZOOM,+ bearing = snapshot.bearingDeg?.toDouble() ?: 0.0,+ )+ } else {+ if (pushedRoute != null) {+ pushedRoute = null+ active.setRoute(points = null)+ }+ active.camera = com.vayunmathur.library.map.CameraPosition(+ target = position,+ zoom = IDLE_ZOOM,+ )+ }+ }++ private fun teardown() {+ renderer?.destroy()+ renderer = null+ mirrorSurface = null+ pushedRoute = null+ }++ private companion object {+ const val TAG = "MaAuto.Maps"++ /** Same layers as the car-app host path (`CarMapRenderer.CAR_LAYERS`). */+ val CAR_LAYERS = LayerOptions(poi = true, transit = false)++ /** Matches `NavMapScreen`: navigating zooms in, idle shows context. */+ const val NAVIGATING_ZOOM = 17.0+ const val IDLE_ZOOM = 15.0++ const val E7 = 10_000_000.0+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/GearheadHostProbe.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/GearheadHostProbe.kt b/auto/src/main/java/com/vayunmathur/auto/platform/GearheadHostProbe.ktnew file mode 100644index 0000000000..093d50bd0c--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/GearheadHostProbe.kt@@ -0,0 +1,116 @@+package com.vayunmathur.auto.platform++import android.content.ComponentName+import android.content.Context+import android.location.LocationManager+import android.util.Log+import com.vayunmathur.auto.protocol.HostFacts+import com.vayunmathur.auto.protocol.HostVsMirror+import com.vayunmathur.auto.protocol.MapsPath+import com.vayunmathur.auto.protocol.MirrorFacts++/**+ * Gathers the host-vs-mirror facts and renders the pure recommendation.+ *+ * Each lookup mirrors an existing seam in this module: the maps-service+ * lookup follows `CarApps.launcherApp` (which already resolves the+ * `com.vayunmathur.maps` tile, so this re-checks the car-app service inside+ * it), the role read follows `MaosRoleStatus`, and the host-library probe+ * is a `Class.forName` that never hard-links the car-app host -- the auto+ * module must not take that dependency until the host path is chosen.+ *+ * Runs on demand (one report per call), never watched: the recommendation+ * feeds the Phase 6 side-by-side report in `auto/docs/HANDOFF.md` §10 and+ * the phone debug row, not a live switch. Mirror is the session default+ * regardless; a HOST recommendation here is "prototype the host next", not+ * "reroute this session".+ */+object GearheadHostProbe {++ /**+ * Probes the device and recommends a maps path.+ *+ * @param routeActive whether a route is currently overlaid; from the+ * guidance monitor's latest snapshot, never read from the maps module+ * (no cross-module dependency, no shared process).+ */+ fun probe(context: Context, routeActive: Boolean = false): HostReport {+ val host = HostFacts(+ mapsServicePresent = hasMapsCarService(context),+ holdsProjectionRole = MaosRoleStatus.isProjectionRoleHeld(context),+ hostLibraryPresent = hasHostLibrary(),+ )+ val mirror = MirrorFacts(+ rendererPresent = hasMapRenderer(),+ locationAvailable = hasLocation(context),+ routeActive = routeActive,+ )+ return HostReport(host, mirror, HostVsMirror.recommend(host, mirror))+ }++ /**+ * The `:maps` car-app service (`MapsCarAppService`) is declared and+ * enabled. Package-qualified on purpose, like the music service string+ * in `MediaPlaybackMonitor`: no compile dependency on the maps module.+ */+ private fun hasMapsCarService(context: Context): Boolean = runCatching {+ val component = ComponentName(MAPS_PACKAGE, MAPS_CAR_SERVICE_CLASS)+ val info = context.packageManager.getServiceInfo(component, 0)+ info.enabled+ }.getOrDefault(false)++ /**+ * The car-app projected host is on the classpath.+ *+ * `Class.forName`, never an import: linking `androidx.car.app.projected`+ * from this module would drag the whole host stack into every auto+ * build for a path that is still a prototype. A missing class is a+ * fact (host not ready), not an error.+ */+ private fun hasHostLibrary(): Boolean = runCatching {+ Class.forName(HOST_CONNECTION_CLASS)+ true+ }.getOrDefault(false)++ /** `:library:map`'s renderer class loads. Native Vulkan still gates the first frame. */+ private fun hasMapRenderer(): Boolean = runCatching {+ Class.forName(MAP_RENDERER_CLASS)+ true+ }.getOrDefault(false)++ /** A location provider exists (enabled or not); permission still gates fixes. */+ private fun hasLocation(context: Context): Boolean = runCatching {+ val manager = context.getSystemService(LocationManager::class.java) ?: return false+ manager.getProviders(true).isNotEmpty() ||+ manager.allProviders.isNotEmpty()+ }.getOrDefault(false)++ /** One probe: the facts plus the pure recommendation. */+ data class HostReport(+ val host: HostFacts,+ val mirror: MirrorFacts,+ val path: MapsPath,+ ) {+ /** One-line verdict for logcat and the side-by-side report. */+ fun describe(): String =+ "maps path=$path " ++ "(host: service=${host.mapsServicePresent} " ++ "role=${host.holdsProjectionRole} lib=${host.hostLibraryPresent}; " ++ "mirror: renderer=${mirror.rendererPresent} " ++ "location=${mirror.locationAvailable} route=${mirror.routeActive})"++ /** Logs the verdict; call from the service bring-up on DEV builds only. */+ fun log() {+ Log.i(TAG, describe())+ }+ }++ private const val TAG = "MaAuto.Maps"++ private const val MAPS_PACKAGE = "com.vayunmathur.maps"+ private const val MAPS_CAR_SERVICE_CLASS = "com.vayunmathur.maps.car.MapsCarAppService"++ private const val HOST_CONNECTION_CLASS = "androidx.car.app.projected.CarAppProjectedService"++ private const val MAP_RENDERER_CLASS = "com.vayunmathur.library.map.SurfaceMapRenderer"+}
auto/src/main/java/com/vayunmathur/auto/platform/NavGuidanceMonitor.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/NavGuidanceMonitor.kt b/auto/src/main/java/com/vayunmathur/auto/platform/NavGuidanceMonitor.ktnew file mode 100644index 0000000000..becc43f698--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/NavGuidanceMonitor.kt@@ -0,0 +1,204 @@+package com.vayunmathur.auto.platform++import android.app.UiModeManager+import android.content.Context+import android.content.res.Configuration+import android.location.Location+import android.location.LocationListener+import android.location.LocationManager+import android.os.Bundle+import android.os.Handler+import android.os.Looper+import android.util.Log+import com.vayunmathur.auto.protocol.MapsGuidance+import com.vayunmathur.auto.protocol.MapRoutePoint+import com.vayunmathur.auto.protocol.NavSnapshot+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlin.math.roundToInt++/**+ * One active route overlaid on the mirror, from whoever owns routing.+ *+ * Own data class rather than the maps module's `RouteService.Route`: the+ * auto module must not take a compile dependency on the maps app module+ * (same rule as `MediaPlaybackMonitor`'s string class name for music), and+ * the two APKs do not share a process singleton anyway. Points are+ * [MapRoutePoint] so the monitor can forward them without reshaping.+ *+ * The provider must return a stable list instance while the route is+ * unchanged: the monitor forwards the reference untouched, and+ * `CarMapsMirror` skips the (expensive, tessellating) route push when the+ * reference is identical. A provider that rebuilds the list per read would+ * re-tessellate a cross-city route on every GPS fix.+ */+data class ActiveRoute(+ val points: List<MapRoutePoint>,+ val nextRoad: String? = null,+ val nextTurnDistanceM: Int? = null,+ val maneuver: String? = null,+)++/** Supplies the active route, or null when idle or unknown. */+fun interface RouteProvider {+ fun current(): ActiveRoute?+}++/**+ * Binds phone GPS (plus night state) into [NavSnapshot]s for the Phase 6+ * mirror and the ch7/ch10 live values.+ *+ * Owns location collection the way `MediaPlaybackMonitor` owns its+ * controller: `start()` subscribes on the main thread, fixes arrive on the+ * location listener, and every fix republishes through [snapshots] with the+ * latest route overlay. Sinks must be thread-safe (a `StateFlow` set, a+ * main-posted view update), never work inline.+ *+ * Without `ACCESS_FINE_LOCATION` the monitor seeds from the last-known fix+ * and stays there: a `SecurityException` degrades to last-known rather than+ * failing anything downstream. Route guidance stays idle until a+ * [RouteProvider] is set -- position and puck are live from the first fix,+ * turn fields join when routing does.+ *+ * Seams, all future wiring, none of it here:+ * - ch7: fold `MapsGuidance.toSensorEvents(snapshot)` through+ * `SensorChannel`'s `onValues` seam (sensors-dev owns the channel).+ * - ch10: forward `MapsGuidance.toNavStatus(snapshot)` to+ * `NavStatusChannel.postStatus` (sensors-dev owns the channel).+ * - `CarMapsMirror.render(snapshot)` drives the ch2 map picture.+ */+class NavGuidanceMonitor(+ private val context: Context,+ private val onUpdate: (NavSnapshot) -> Unit = {},+) {+ private val mainHandler = Handler(Looper.getMainLooper())++ private val _snapshots = MutableStateFlow<NavSnapshot?>(null)+ /** Latest snapshot; null until the first fix or last-known seed. */+ val snapshots: StateFlow<NavSnapshot?> = _snapshots.asStateFlow()++ /** Overlays route guidance onto each fix; null means idle map. */+ @Volatile var routeProvider: RouteProvider? = null++ private var locationManager: LocationManager? = null+ private var listener: LocationListener? = null++ /**+ * Subscribes to GPS + network fixes. Safe from any thread; the subscribe+ * hops to main. Seeds from the last-known fix so observers have a+ * position before the next GPS tick.+ */+ fun start() {+ mainHandler.post {+ val manager = context.getSystemService(LocationManager::class.java) ?: run {+ Log.w(TAG, "no location manager; guidance stays empty")+ return@post+ }+ locationManager = manager+ val active = object : LocationListener {+ override fun onLocationChanged(location: Location) = publish(location)++ @Deprecated("Required by old LocationListener interface; status callbacks are no longer delivered on API 29+.")+ override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}+ }+ listener = active+ runCatching {+ if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {+ manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, FIX_MIN_MS, 0f, active)+ }+ if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {+ manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, FIX_MIN_MS, 0f, active)+ }+ val last = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER)+ ?: manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)+ last?.let { publish(it) }+ }.onFailure {+ // No permission (or no provider): last-known stays, live fixes+ // wait for the permission UX in MainActivity/Navigation/Route.+ Log.w(TAG, "location unavailable; guidance holds last-known", it)+ }+ }+ }++ /** Drops the subscription. Safe from any thread. */+ fun stop() {+ mainHandler.post {+ listener?.let { runCatching { locationManager?.removeUpdates(it) } }+ listener = null+ locationManager = null+ }+ }++ /**+ * Folds one fix plus the current route overlay into a snapshot.+ *+ * Parked is a motion heuristic (no speed, or below walking pace), not a+ * gear reading: the head unit's DRIVING_STATUS stream wins downstream+ * wherever the snapshot is folded into one. Bearing trusts GPS course+ * only above [GPS_COURSE_MIN_SPEED_MPS], matching the maps stack's own+ * rule (`NavigationSessionManager`), and is null otherwise -- null draws+ * the dot without a cone, which is different from pointing it north.+ */+ private fun publish(location: Location) {+ val speed = if (location.hasSpeed()) location.speed.toDouble() else 0.0+ val course = if (location.hasBearing() && location.hasSpeed() &&+ location.speed >= GPS_COURSE_MIN_SPEED_MPS+ ) {+ location.bearing+ } else {+ null+ }+ val route = runCatching { routeProvider?.current() }.getOrNull()+ val snapshot = MapsGuidance.snapshotFromFix(+ latitude = location.latitude,+ longitude = location.longitude,+ accuracyM = if (location.hasAccuracy()) location.accuracy.roundToInt() else null,+ fixTimestampMs = location.time,+ speedMps = speed,+ parked = speed < PARKED_MAX_SPEED_MPS,+ isNight = isNightNow(),+ ).copy(+ guidanceActive = route != null,+ nextRoad = route?.nextRoad,+ nextTurnDistanceM = route?.nextTurnDistanceM,+ maneuver = route?.maneuver,+ bearingDeg = course,+ route = route?.points,+ )+ _snapshots.value = snapshot+ onUpdate(snapshot)+ }++ /**+ * The phone's own night state.+ *+ * Duplicates the `ProjectionService.isNightNow` read on purpose: that+ * file is another agent's in-flight work and this must not touch it.+ * Whoever wires the monitor passes this in as the `SensorChannel`+ * `NightSource` so the two agree; dedup when the tree settles.+ */+ private fun isNightNow(): Boolean? = runCatching {+ // Car-dock UiMode first (a phone in a car holder at night reports car+ // mode), then the system night flag. Null only when both are unknown.+ val uiMode = context.getSystemService(UiModeManager::class.java)?.nightMode+ ?: (context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK)+ when (uiMode) {+ UiModeManager.MODE_NIGHT_YES -> true+ UiModeManager.MODE_NIGHT_NO -> false+ else -> (context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) ==+ Configuration.UI_MODE_NIGHT_YES+ }+ }.getOrNull()++ private companion object {+ const val TAG = "MaAuto.Guidance"+ const val FIX_MIN_MS = 1_000L++ /** Below a slow walk the vehicle counts as parked (heuristic, see [publish]). */+ const val PARKED_MAX_SPEED_MPS = 0.5++ /** GPS course is trusted for bearing only above this (maps-stack rule). */+ const val GPS_COURSE_MIN_SPEED_MPS = 1.0f+ }+}