Modern Apps git

← Modern-Apps.git

various fixes

Commit
5ac87e2326e8a23f5fdf3f489e836b929ff5f635
Author
vayun-mathur <[email protected]>
When
2026-09-11 23:28 UTC (2 months ago)
Parents
974dbb0

Diff

.github/ISSUE_TEMPLATE/bug_report.yml
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 5a94b5589f..82e79e16b2 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -12,6 +12,7 @@ body:         - alchemist         - appstore         - astronomy+        - auto         - calculator         - calendar         - camera@@ -36,7 +37,6 @@ body:         - music         - musicbrainz         - notes-        - nowplaying         - office         - openassistant         - passwords
.github/ISSUE_TEMPLATE/feature_request.yml
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlindex 557fd4a34c..87ee27a069 100644--- a/.github/ISSUE_TEMPLATE/feature_request.yml+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -12,6 +12,7 @@ body:         - alchemist         - appstore         - astronomy+        - auto         - calculator         - calendar         - camera@@ -36,7 +37,6 @@ body:         - music         - musicbrainz         - notes-        - nowplaying         - office         - openassistant         - passwords
.github/workflows/issue_labeler.yml
diff --git a/.github/workflows/issue_labeler.yml b/.github/workflows/issue_labeler.ymlindex 6e98eaa9a1..6620f7efaf 100644--- a/.github/workflows/issue_labeler.yml+++ b/.github/workflows/issue_labeler.yml@@ -21,7 +21,7 @@ jobs:              if (match && match[1]) {               const selectedApp = match[1].trim().toLowerCase();-              const validApps = ['alchemist', 'appstore', 'astronomy', 'calculator', 'calendar', 'camera', 'chess', 'clock', 'code', 'contacts', 'education', 'email', 'everysync', 'files', 'findfamily', 'fooddelivery', 'health', 'hub', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'messages', 'music', 'musicbrainz', 'notes', 'nowplaying', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'solitaire', 'speech', 'things', 'translate', 'travel', 'tuner', 'unblockjam', 'vpn', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];+              const validApps = ['alchemist', 'appstore', 'astronomy', 'auto', 'calculator', 'calendar', 'camera', 'chess', 'clock', 'code', 'contacts', 'education', 'email', 'everysync', 'files', 'findfamily', 'fooddelivery', 'health', 'hub', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'messages', 'music', 'musicbrainz', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'solitaire', 'speech', 'things', 'translate', 'travel', 'tuner', 'unblockjam', 'vpn', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];                if (validApps.includes(selectedApp)) {                 await github.rest.issues.addLabels({
.gitignore
diff --git a/.gitignore b/.gitignoreindex 310a78ff6f..9d8359fa7f 100644--- a/.gitignore+++ b/.gitignore@@ -56,6 +56,14 @@ health/src/main/assets/food.bin.br health/src/main/assets/food.bin.meta.json health/src/main/assets/staging.db +# Medical catalogue asset — large binary, regenerate with scripts/generate_med_db.py.+# Holds both the RxNorm medication and ICD-10-CM condition terminologies. The vaccine half of+# that script writes health/src/main/assets/cvx.json, which is small enough to commit and is+# deliberately not ignored.+health/src/main/assets/catalog.db+health/src/main/assets/catalog.db.br+health/src/main/assets/catalog.db.meta.json+ # Compose preview screenshot rendering (common-conventions-preview-metadata). These PNGs # are an intermediate: the `metadata` task copies them into metadata_data/photos/<module>, # which is what is committed and what release.sh reads. Committing them too would store
README.md
diff --git a/README.md b/README.mdindex ca46e8aa65..2c971209cc 100644--- a/README.md+++ b/README.md@@ -42,6 +42,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | :--- | :---: | :---: | :---: | | **App Store** | [Homepage](https://ma.vayunmathur.com/apps/appstore) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.appstore/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=App%20Store&packageName=com.vayunmathur.appstore&apk=appstore-release.apk) | | **Astronomy** | [Homepage](https://ma.vayunmathur.com/apps/astronomy) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.astronomy/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Astronomy&packageName=com.vayunmathur.astronomy&apk=astronomy-release.apk) |+| **Auto** | [Homepage](https://ma.vayunmathur.com/apps/auto) | In Progress | In Progress | | **Calculator** | [Homepage](https://ma.vayunmathur.com/apps/calculator) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.calculator/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Calculator&packageName=com.vayunmathur.calculator&apk=calculator-release.apk) | | **Calendar** | [Homepage](https://ma.vayunmathur.com/apps/calendar) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.calendar/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Calendar&packageName=com.vayunmathur.calendar&apk=calendar-release.apk) | | **Camera** | [Homepage](https://ma.vayunmathur.com/apps/camera) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.camera/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Camera&packageName=com.vayunmathur.camera&apk=camera-release.apk) |@@ -66,7 +67,6 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **Music** | [Homepage](https://ma.vayunmathur.com/apps/music) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.music/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Music&packageName=com.vayunmathur.music&apk=music-release.apk) | | **MusicBrainz** | [Homepage](https://ma.vayunmathur.com/apps/musicbrainz) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.musicbrainz/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=MusicBrainz&packageName=com.vayunmathur.musicbrainz&apk=musicbrainz-release.apk) | | **Notes** | [Homepage](https://ma.vayunmathur.com/apps/notes) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.notes/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Notes&packageName=com.vayunmathur.notes&apk=notes-release.apk) |-| **Now Playing** | [Homepage](https://ma.vayunmathur.com/apps/nowplaying) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.nowplaying/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Now%20Playing&packageName=com.vayunmathur.nowplaying&apk=nowplaying-release.apk) | | **Office** | [Homepage](https://ma.vayunmathur.com/apps/office) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.office) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Office&packageName=com.vayunmathur.office&apk=office-release.apk) | | **Open Assistant** | [Homepage](https://ma.vayunmathur.com/apps/openassistant) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.openassistant) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=OpenAssistant&packageName=com.vayunmathur.openassistant&apk=openassistant-release.apk) | | **Passwords** | [Homepage](https://ma.vayunmathur.com/apps/passwords) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.passwords/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Passwords&packageName=com.vayunmathur.passwords&apk=passwords-release.apk) |
SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdindex 9dc4ecfbbf..cd2ec39dbf 100644--- a/SUPPLY_CHAIN_RISKS.md+++ b/SUPPLY_CHAIN_RISKS.md@@ -557,7 +557,7 @@ Mitigation: record the upstream commit for both, in the form `third_party/betoco  --- -## 10. Release signing key+## 10. Committed key material  ### 10.1 `release_keystore.jks` is committed to the repository — High, pending confirmation @@ -574,6 +574,42 @@ key, treat it as disclosed — rotate it and follow key-compromise procedure. Ei from version control and have CI supply the keystore entirely from secrets, so no file at that path is ever tracked. +### 10.2 Google's Android Auto client key is committed and shipped — Medium, with a hard expiry++`auto/protocol/src/main/assets/gal/` holds three PEMs that are packaged into the MA Auto APK:++| File | What it is |+|---|---|+| `client-cert.pem` | `O=CarService` leaf, issued by `O=Google Automotive Link` |+| `client-key.pem` | the leaf's unencrypted PKCS#8 RSA-2048 private key |+| `root.pem` | the Google Automotive Link root, used as the sole TLS trust anchor |++Provenance: extracted from `com.google.android.projection.gearhead` 17.5.663214 by+`analysis/maauto/extract_key.py`, which reproduces the app's own key derivation. Gearhead stores the+key AES-encrypted, but the KDF's entire input — the two certificate PEMs and a static salt — ships in+the same APK, so this is obfuscation rather than protection. Full write-up in+`analysis/maauto/FINDINGS.md`.++**This is not a secret being disclosed.** The same bytes are recoverable from every Android Auto+installation, and the aasdk/openauto projects have shipped this credential publicly for years.+Committing it reveals nothing that was not already public. Three real risks remain:++- **It expires 2026-12-09 and cannot be renewed by us.** We do not hold the GAL root key, so no+  replacement can be minted. When it lapses, head units will reject the handshake and projection+  stops. Treat this as a scheduled outage, not a hypothetical.+- **It is Google's key material, not ours.** Using it to authenticate to third-party hardware is a+  licensing and terms question that this document does not attempt to answer.+- **Google is moving to remote provisioning.** `rvg` prefers a certificate delivered through six+  phenotype flags (cert, encrypted key, salt, each with a SHA-1 check) and only falls back to the+  hardcoded one. If head units begin requiring the rotated certificate, the embedded credential+  stops working before its notAfter date.++Mitigation: keep `extract_key.py` working so the credential can be re-extracted from a newer+gearhead; watch whether the phenotype path becomes mandatory; and treat the expiry as a dated+dependency rather than something to discover in production. `GalCredentialTest` fails loudly if the+shipped assets stop chaining or stop completing a handshake, but nothing currently fails on+approaching expiry.+ ---  ## 11. Runtime servers the apps depend on@@ -800,7 +836,6 @@ fallbacks, MTU 1280, and port 51820. - `:share` — LAN TCP plus mDNS/BLE. - `:photos` — holds `INTERNET` but has no host of its own; models ship in the APK. - `:music` — **no `INTERNET` permission**; no radio, lyrics or artwork APIs.-- `:nowplaying` — `SongMatcher` is a stub; no AcoustID, no Shazam. - `:speech` — models bundled. - Fully offline: astronomy, clock, code, contacts, calendar, health, keyboard, launcher, logviewer,   measure, things, tuner, setupwizard, camera (which *removes* `INTERNET`), and every game except
auto/build.gradle.kts
diff --git a/auto/build.gradle.kts b/auto/build.gradle.ktsnew file mode 100644index 0000000000..861d01a988--- /dev/null+++ b/auto/build.gradle.kts@@ -0,0 +1,28 @@+plugins {+    id("common-conventions-app")+    id("common-conventions-preview-metadata")+}+launcherIcon {+    symbol = "directions_car"+}+android {+    defaultConfig {+        applicationId = "com.vayunmathur.auto"+    }+    packaging {+        resources {+            // protoc copies every .proto it sees into the jar's resources, so without this+            // the APK carries our two schemas plus protobuf's well-known types - about+            // 125 KB of source that nothing reads. protobuf-lite never looks at a .proto at+            // runtime; only full-protobuf descriptor reflection would, and we do not use it.+            // Note :appstore has the same leak (22 files) and is left alone here: fixing it+            // repo-wide belongs in common-conventions-app, not in this app's build file.+            excludes += setOf("**/*.proto", "*.proto")+        }+    }+}+dependencies {+    // The GAL wire format. Nothing in the app re-implements it, and keeping it out of here is+    // what lets the handshake be tested on the JVM.+    implementation(project(":auto:protocol"))+}
auto/protocol/build.gradle.kts
diff --git a/auto/protocol/build.gradle.kts b/auto/protocol/build.gradle.ktsnew file mode 100644index 0000000000..838a450393--- /dev/null+++ b/auto/protocol/build.gradle.kts@@ -0,0 +1,34 @@+plugins {+    id("common-conventions-library")+    alias(libs.plugins.protobuf)+}+// The Google Automotive Link (GAL) wire protocol: framing, TLS, channel multiplexing and the+// generated protobuf. Deliberately free of Android framework calls so the whole handshake and+// every codec round-trip is host-runnable, the same split :cast:protocol uses.+//+// An Android library rather than common-conventions-jvm because the credential loader reads the+// PEMs from this module's assets.+//+// No `defaultConfig {` block: release.sh sed-injects versionCode/versionName after that+// literal in every build.gradle.kts it finds, and a library has no such properties.+dependencies {+    implementation(project(":library"))+    implementation(libs.protobuf.javalite)+}++protobuf {+    protoc {+        artifact = libs.protobuf.protoc.get().toString()+    }+    generateProtoTasks {+        all().forEach { task ->+            task.builtins {+                // `create`, not `named` as in :youpipe:extractor: the Android path does not+                // pre-register the java builtin, so it has to be added here.+                create("java") {+                    option("lite")+                }+            }+        }+    }+}
auto/protocol/src/main/assets/gal/client-cert.pem
diff --git a/auto/protocol/src/main/assets/gal/client-cert.pem b/auto/protocol/src/main/assets/gal/client-cert.pemnew file mode 100644index 0000000000..29c6b63571--- /dev/null+++ b/auto/protocol/src/main/assets/gal/client-cert.pem@@ -0,0 +1,21 @@+-----BEGIN CERTIFICATE-----+MIIDbjCCAlagAwIBAgIIAJLDKgIL/IcwDQYJKoZIhvcNAQELBQAwWzELMAkGA1UE+BhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZp+ZXcxHzAdBgNVBAoMFkdvb2dsZSBBdXRvbW90aXZlIExpbmswHhcNMTQwNzA0MDAw+MDAwWhcNMjYxMjA5MTgzOTAzWjBPMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2Fs+aWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzETMBEGA1UECgwKQ2FyU2Vy+dmljZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALfRDCzkWykDVbBq++A0QJoQ9fRioKWDv3IqOj/dAXGMV8nWM2CY31kLrlmp937U1RP+QaKJI6XFQsuM4+ODj1SzyUcoGm2VER2CbyQrPbmbyCySGSx6Hp61nX/cLArHvBTU9N/5zw+4X/kHlb+bA74MhrxIjVNS84rWz4nin8WidFMFLGFSoVgPkHW0ZM1y2aJnnRXYc1SZ/yJEpnh+sfoZtvfZWebgyWkmh2KxZbmhGVY03QWjWYOk6IvKzOQ+Itoq4suyqHDk/aFRVus6+8AMW6jER8dird9qhCfCeeNS+KdS9QbQZbfie9ezxQ2WrQ4AcAV991aPgiZRFyrs6++KyPDFMCAwEAAaNCMEAwHQYDVR0OBBYEFCsXkgAKX9/zeT8UuTkBrzeeePrIMB8G+A1UdIwQYMBaAFLl2q+/wM9CLCsx+CfzEpH3WTvCCMA0GCSqGSIb3DQEBCwUAA4IB+AQAXmxI1shXK0V2TnMacNnyv45r6qE5ClM9KbfJsc1ZhQreNl+qh86zMhjZhigkJ+pferNv2axF2+8f9r8ZIWZ/7gb8g5kKd7V8t+IIFJ99VDtzVPkADIvUrUPsUpUYOm+TUTJ3mIJN7oqpFoF5Fn0ATspVlglIVuvlltnkmSN+F2xhrqyqByWkVzOoAhtRmQ5+mqVy+55ED5GPC/PHlOEUkA/a8aQdG4+bSpfUDK+V5CuggQu6Olh1JGvJ67EV8+K8+e6typKqw4GLDn1calWMp+MM3mY+GUbQhSNcq2CLtrl+AUAQ+E4iwYkIWKsXyjxpC+vfSGfsEFDq5ZjQdn1gKWppHD+-----END CERTIFICATE-----
auto/protocol/src/main/assets/gal/client-key.pem
diff --git a/auto/protocol/src/main/assets/gal/client-key.pem b/auto/protocol/src/main/assets/gal/client-key.pemnew file mode 100644index 0000000000..0245816e8a--- /dev/null+++ b/auto/protocol/src/main/assets/gal/client-key.pem@@ -0,0 +1,28 @@+-----BEGIN PRIVATE KEY-----+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC30Qws5FspA1Ww+avgNECaEPX0YqClg79yKjo/3QFxjFfJ1jNgmN9ZC65Zqfd+1NUT/kGiiSOlxULLj+ODg49Us8lHKBptlREdgm8kKz25m8gskhkseh6etZ1/3CwKx7wU1PTf+c8PuF/5B5+W2wO+DIa8SI1TUvOK1s+J4p/FonRTBSxhUqFYD5B1tGTNctmiZ50V2HNUmf8iRKZ+4bH6Gbb32Vnm4MlpJodisWW5oRlWNN0Fo1mDpOiLyszkPiLaKuLLsqhw5P2hUVbr+OvADFuoxEfHYq3faoQnwnnjUvinUvUG0GW34nvXs8UNlq0OAHAFffdWj4ImURcq7+OvisjwxTAgMBAAECggEAEjXDA4WB5G/AovAN79lcP3iJ9pHeO4y3qABUkdWN8YEA+mpWf6jVY5BtLtPQQX/bNhZXsT7tyaPfqKOluZHIkiHVaXK7HU6k1ZTJV2lSUh+Db+BRjx7v/qAWYM7SjCTaZKPuOGwaj7+fvl96fPbjI3YITn8yjbrCqOaPto1ItKjvHU+FQJWB6p/cj/ItKbNU+qGSEgYExerI84Lu6hnxBoZXnJL1W5yzH6j81zDJ40cypGx+BiyA9+YSwqTh7cYFSTE5m1my07tLfKf0RUCZGl6BNGPFXXPveN8r9DD4PXUPaFEX+T4krZ3yzPzhg8Ja1/6Wjo1WGbQntavAHQZRFcaqZjQKBgQDbtaTnFtXHaxrvDBJf+NgCCr7tIOM/WTWRsEo4q8nN9ACqoei9phRQ8xfJg2EXWNNKBD19K3Sd+pi0AT6+F+lz2MLgVZZvdlxea1B6KM1DyKPuCU7HjuICqgjfQpOL++vYXHIj6ovt/pfLawKCYE++vJJR7jrSkX1PBeNkBL7ye59dwKBgQDWLa4S9HHGyxfMWdpCx4Tw1hUJqaeawQ6M+ZexrtFvIlZz6V3LZW4wNxYItgCujCXh0xNHDcPY9r+06bSscLbaY+UzvPv8IS0Mq+bWifoXPQbLQBLf6SczTnyLaithCj7x3I+LVzwbyTMaX07gDz538I3dH57CHEb076+Xqad4YBvBQKBgQCN5VRpAvByaJPuiydaYnAV9xTHYhmo2DbhLWKwDgHUW0Uxpif0+yEP3tAgDz+nanCbPv3PVz9rwCrbJmq1LZBAV9qrxwHRLQHLtu86ZkYC/8DfvNoIr+mI6vPr7P2JzNvW0m3NEG/q9yBl+eiW90i/Xqqe2d2EwyQ+saPFBmWVYzpQKBgDRv+mJehax2daWUpdms1B9Iix6HG/HbB3zr2VSyFSpdQMc+Ei2S1qhNREK7tG0HeNrR3+31c3F8JAiRbt1Ukf0/2dw30rciroqjf/80Zps74KbwN+7D2UoRZCKJyrcGWCTEuA+wIPnobBzzkqp3mfYfFyCWj8S1a2PBsn7VFWA+P21AoGACjol1Njoka+zz928x7hr+cJ7BmD4sMErz/sRYIXsaGy7T/LloR7yyx6HBDwKt+iMxQZEhpoHS8nkey3kFV/4g+2qTDf4EyRWoMNucpGtrXoqehRr/HvDIi4piZ12DgwCsmk0KsfvUEpHTHDNAQCpqY+DOiSKVqkc1Gh6+hxb6VTuzI=+-----END PRIVATE KEY-----
auto/protocol/src/main/assets/gal/root.pem
diff --git a/auto/protocol/src/main/assets/gal/root.pem b/auto/protocol/src/main/assets/gal/root.pemnew file mode 100644index 0000000000..22e8043d54--- /dev/null+++ b/auto/protocol/src/main/assets/gal/root.pem@@ -0,0 +1,21 @@+-----BEGIN CERTIFICATE-----+MIIDiTCCAnGgAwIBAgIJAMFO56WkVE1CMA0GCSqGSIb3DQEBBQUAMFsxCzAJBgNV+BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBW+aWV3MR8wHQYDVQQKDBZHb29nbGUgQXV0b21vdGl2ZSBMaW5rMB4XDTE0MDYwNjE4+MjgxOVoXDTQ0MDYwNTE4MjgxOVowWzELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNh+bGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxHzAdBgNVBAoMFkdvb2ds+ZSBBdXRvbW90aXZlIExpbmswggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB+AQDUH+iIbwwVb74NdI5eBv/ACFmh4ml/NOW7gUVWdYX50n8uQQsHHLCNIhk5VV2H+hanvAZ/XXHPuVAPadE2HpnNqePKF/RDo4eJo/+rOief8gBYq/Z+OQTZeLdNm+GoI+HBrEjU4Ms8IdLuFW0jF8LlIRgekjLHpc7duUl3QpwBlmAWQK40T/SZjprlmhyqfJ+g1rxFdnGbrSibmCsTmb3m6WZyZUyrcwmd7t6q3pHbMABO+o02asPG/YPj/SJo4+i+fb5/Nk56f3hH9pBiPKQXJnVUdVLKMXSRgydDBsGSBol4C0JL77MNDrMR5jdafJ4j+mWmsa2+mnzoAv9AxEL9T0LiNAgMBAAGjUDBOMB0GA1UdDgQWBBS5dqvv8DPQiwrM+fgn8xKR91k7wgjAfBgNVHSMEGDAWgBS5dqvv8DPQiwrMfgn8xKR91k7wgjAMBgNV+HRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQDKcnBsrbB0Jbz2VGJKP2lwYB6P+dCTCCpQu7dVp61UQOX+zWfd2hnNMnLs/r1xPO+eyN0vmw7sD05phaIhbXVauKWZi+9WqWHTaR+9s6CTyBOc1Mye0DMj+4vHt+WLmf0lYjkYUVYvR1EImX8ktXzkVmOqn++e30siqlZ8pQpsOgegIKfJ+pNQM8c3eXVv3KFMUgjZW33SziZL8IMsLvSO+1LtH37+KqbTEMP6XUwVuZopgGvaHU74eT/WSRGlL7vX4OL5/UXXP4qsGH2Zp7uQlErv4H9j+kMs37UL1vGb4M8RM7Eyu9/RulepSmqZUF+3i+3eby8iGq/3OWk9wgJf7AXnx+-----END CERTIFICATE-----
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/Fragmenter.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/Fragmenter.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/Fragmenter.ktnew file mode 100644index 0000000000..414020d50f--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/Fragmenter.kt@@ -0,0 +1,69 @@+package com.vayunmathur.auto.protocol++/** One slice of a message payload, with the frame flags that describe its position. */+data class Fragment(+    val offset: Int,+    val length: Int,+    val isFirst: Boolean,+    val isLast: Boolean,+) {+    /** Frame flags for this slice, before [FrameFlags.CONTROL]/[FrameFlags.ENCRYPTED]. */+    val positionFlags: Int+        get() = (if (isFirst) FrameFlags.FIRST else 0) or (if (isLast) FrameFlags.LAST else 0)+}++/**+ * Splits a message payload across frames.+ *+ * The usable payload differs between frames because the first fragment of a *fragmented*+ * message carries an 8-byte header (it has the 4-byte total length) while every other+ * frame carries 4. A message that fits in one frame is `FIRST or LAST` and so uses the+ * short header.+ *+ * Sizes here are plaintext. When the payload is subsequently TLS-wrapped the record grows,+ * so [FrameHeader.DEFAULT_MAX_FRAME_SIZE] (16128) is deliberately below gearhead's 16384+ * receive staging buffer, leaving 256 bytes of headroom for the record overhead.+ */+object Fragmenter {++    /**+     * @throws IllegalArgumentException if [isControl] and the payload needs more than one+     *   frame. Gearhead refuses to fragment control messages (`rtt.i()`), so a control+     *   message that does not fit is a programming error rather than something to split.+     */+    fun split(+        payloadSize: Int,+        maxFrameSize: Int = FrameHeader.DEFAULT_MAX_FRAME_SIZE,+        isControl: Boolean = false,+    ): List<Fragment> {+        require(payloadSize >= 0) { "payload size $payloadSize is negative" }+        require(maxFrameSize > FrameHeader.LONG_HEADER_SIZE) {+            "max frame size $maxFrameSize leaves no room for a payload"+        }++        val single = maxFrameSize - FrameHeader.SHORT_HEADER_SIZE+        if (payloadSize <= single) {+            return listOf(Fragment(0, payloadSize, isFirst = true, isLast = true))+        }+        require(!isControl) {+            "control message of $payloadSize bytes exceeds the $single-byte frame payload " ++                "and control messages cannot be fragmented"+        }++        val fragments = mutableListOf<Fragment>()+        // The first fragment pays for the 4-byte total length; the rest do not.+        var offset = minOf(payloadSize, maxFrameSize - FrameHeader.LONG_HEADER_SIZE)+        fragments += Fragment(0, offset, isFirst = true, isLast = false)+        while (offset < payloadSize) {+            val length = minOf(payloadSize - offset, single)+            offset += length+            fragments += Fragment(+                offset = offset - length,+                length = length,+                isFirst = false,+                isLast = offset == payloadSize,+            )+        }+        return fragments+    }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FrameHeader.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FrameHeader.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FrameHeader.ktnew file mode 100644index 0000000000..da15636e10--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/FrameHeader.kt@@ -0,0 +1,104 @@+package com.vayunmathur.auto.protocol++import java.nio.ByteBuffer++/**+ * Flags in byte 1 of a GAL frame header.+ *+ * A message that fits in one frame carries `FIRST or LAST`. Anything else is a fragment,+ * and only the first fragment of a fragmented message carries the 4-byte total length.+ */+object FrameFlags {+    const val FIRST = 0x01+    const val LAST = 0x02++    /** The message belongs to the control channel rather than a service channel. */+    const val CONTROL = 0x04++    /** The payload is TLS-wrapped. Set on everything after the handshake completes. */+    const val ENCRYPTED = 0x08+}++/**+ * The header of one GAL frame.+ *+ * ```+ * byte 0      channel id+ * byte 1      flags+ * bytes 2-3   payload length, big-endian uint16, excluding this header+ * bytes 4-7   total message length, big-endian int32, only when FIRST && !LAST+ * ```+ *+ * [payloadLength] is the on-wire length, so for an encrypted frame it is the size of the+ * TLS record and not of the plaintext inside it.+ */+data class FrameHeader(+    val channelId: Int,+    val flags: Int,+    val payloadLength: Int,+    val totalLength: Int? = null,+) {+    val isFirst: Boolean get() = flags and FrameFlags.FIRST != 0+    val isLast: Boolean get() = flags and FrameFlags.LAST != 0+    val isControl: Boolean get() = flags and FrameFlags.CONTROL != 0+    val isEncrypted: Boolean get() = flags and FrameFlags.ENCRYPTED != 0++    /** 8 bytes on the first fragment of a fragmented message, otherwise 4. */+    val size: Int get() = if (isFirst && !isLast) LONG_HEADER_SIZE else SHORT_HEADER_SIZE++    init {+        require(channelId in 0..0xFF) { "channel id $channelId does not fit in a byte" }+        require(flags in 0..0xFF) { "flags $flags do not fit in a byte" }+        require(payloadLength in 0..0xFFFF) {+            "payload length $payloadLength does not fit in a uint16"+        }+        require((totalLength != null) == (isFirst && !isLast)) {+            "totalLength is present exactly on the first fragment of a fragmented message"+        }+    }++    /** Writes this header at the buffer's current position. */+    fun writeTo(buffer: ByteBuffer) {+        buffer.put(channelId.toByte())+        buffer.put(flags.toByte())+        buffer.putShort(payloadLength.toShort())+        if (totalLength != null) buffer.putInt(totalLength)+    }++    companion object {+        const val SHORT_HEADER_SIZE = 4+        const val LONG_HEADER_SIZE = 8++        /**+         * The default maximum frame size, header included (`rto.a()` in gearhead).+         * Head units may negotiate something smaller.+         */+        const val DEFAULT_MAX_FRAME_SIZE = 16128++        /**+         * Reads a header from the buffer's current position, advancing it past the header.+         *+         * The caller must already have enough bytes: [SHORT_HEADER_SIZE] to learn the+         * flags, and [LONG_HEADER_SIZE] if those flags turn out to mean a long header.+         */+        fun readFrom(buffer: ByteBuffer): FrameHeader {+            require(buffer.remaining() >= SHORT_HEADER_SIZE) {+                "need at least $SHORT_HEADER_SIZE bytes for a frame header, " ++                    "have ${buffer.remaining()}"+            }+            val channelId = buffer.get().toInt() and 0xFF+            val flags = buffer.get().toInt() and 0xFF+            val payloadLength = buffer.short.toInt() and 0xFFFF+            val long = flags and FrameFlags.FIRST != 0 && flags and FrameFlags.LAST == 0+            val totalLength = if (long) {+                require(buffer.remaining() >= 4) {+                    "first fragment of a fragmented message needs a 4-byte total length"+                }+                buffer.int+            } else {+                null+            }+            return FrameHeader(channelId, flags, payloadLength, totalLength)+        }+    }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalCredential.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalCredential.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalCredential.ktnew file mode 100644index 0000000000..9595a39d16--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalCredential.kt@@ -0,0 +1,111 @@+package com.vayunmathur.auto.protocol++import android.content.res.AssetManager+import java.io.ByteArrayInputStream+import java.security.KeyFactory+import java.security.KeyStore+import java.security.PrivateKey+import java.security.cert.CertificateFactory+import java.security.cert.X509Certificate+import java.security.spec.PKCS8EncodedKeySpec+import java.util.Base64+import javax.net.ssl.KeyManagerFactory+import javax.net.ssl.SSLContext+import javax.net.ssl.SSLEngine+import javax.net.ssl.TrustManagerFactory++/**+ * The Google Automotive Link credential and the TLS context built from it.+ *+ * Head units authenticate the phone against a private `Google Automotive Link` root, so a+ * projection sender has to present a leaf signed by that root. The one we use is Google's+ * own, lifted out of the Android Auto APK; see `analysis/maauto/FINDINGS.md` and the entry+ * in `SUPPLY_CHAIN_RISKS.md`. **It expires 2026-12-09 and cannot be renewed by us.**+ *+ * Two details are load-bearing and easy to get backwards:+ *+ *  1. **The phone is the TLS server.** Gearhead calls `setUseClientMode(false)` and+ *     `setNeedClientAuth(true)`; the head unit connects as the client and must present its+ *     own GAL-signed certificate.+ *  2. **The GAL root is the only trust anchor.** The system trust store is not consulted,+ *     so the trust manager is built from a keystore holding just that one certificate under+ *     the alias `GAL`.+ */+object GalCredential {++    private const val ASSET_DIR = "gal"+    const val CERT_ASSET = "$ASSET_DIR/client-cert.pem"+    const val KEY_ASSET = "$ASSET_DIR/client-key.pem"+    const val ROOT_ASSET = "$ASSET_DIR/root.pem"++    /** Keystore alias for the GAL root, matching gearhead's. */+    private const val ROOT_ALIAS = "GAL"++    /**+     * Builds the TLS context from PEM text.+     *+     * Kept free of Android so the handshake can be exercised on the JVM; [fromAssets] is+     * the thin wrapper that reads the shipped files.+     */+    fun create(certPem: String, keyPem: String, rootPem: String): SSLContext {+        val certificates = CertificateFactory.getInstance("X.509")+        val leaf = certificates.generateCertificate(+            ByteArrayInputStream(certPem.toByteArray()),+        ) as X509Certificate+        val root = certificates.generateCertificate(+            ByteArrayInputStream(rootPem.toByteArray()),+        ) as X509Certificate++        // An empty password rather than null: KeyStore.setKeyEntry rejects null, and the+        // store never leaves memory.+        val empty = CharArray(0)++        val identity = KeyStore.getInstance(KeyStore.getDefaultType()).apply {+            load(null, null)+            setKeyEntry("client", parsePrivateKey(keyPem), empty, arrayOf(leaf))+        }+        val keyManagers = KeyManagerFactory+            .getInstance(KeyManagerFactory.getDefaultAlgorithm())+            .apply { init(identity, empty) }+            .keyManagers++        val anchors = KeyStore.getInstance(KeyStore.getDefaultType()).apply {+            load(null, null)+            setCertificateEntry(ROOT_ALIAS, root)+        }+        val trustManagers = TrustManagerFactory+            .getInstance(TrustManagerFactory.getDefaultAlgorithm())+            .apply { init(anchors) }+            .trustManagers++        return SSLContext.getInstance("TLSv1.2").apply {+            init(keyManagers, trustManagers, null)+        }+    }++    /** Reads the credential shipped in this module's assets. */+    fun fromAssets(assets: AssetManager): SSLContext = create(+        certPem = assets.open(CERT_ASSET).use { it.readBytes().decodeToString() },+        keyPem = assets.open(KEY_ASSET).use { it.readBytes().decodeToString() },+        rootPem = assets.open(ROOT_ASSET).use { it.readBytes().decodeToString() },+    )++    /**+     * An engine configured the way gearhead configures its own: server side, client+     * certificate required.+     */+    fun serverEngine(context: SSLContext): SSLEngine = context.createSSLEngine().apply {+        useClientMode = false+        needClientAuth = true+    }++    private fun parsePrivateKey(pem: String): PrivateKey {+        val body = pem+            .substringAfter("-----BEGIN PRIVATE KEY-----")+            .substringBefore("-----END PRIVATE KEY-----")+            .filterNot(Char::isWhitespace)+        require(body.isNotEmpty()) { "no PKCS#8 PRIVATE KEY block in the credential" }+        val der = Base64.getDecoder().decode(body)+        return KeyFactory.getInstance("RSA").generatePrivate(PKCS8EncodedKeySpec(der))+    }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalMessage.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalMessage.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalMessage.ktnew file mode 100644index 0000000000..bbb8f0ac77--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalMessage.kt@@ -0,0 +1,134 @@+package com.vayunmathur.auto.protocol++/**+ * GAL message types. Every channel payload is `[2-byte big-endian type][protobuf]`.+ *+ * The control channel uses small integers; every service channel uses 0x8000-based ones,+ * with 0x0000/0x0001 reserved for bulk media data.+ *+ * These are **wire** values. Reading them out of gearhead is error-prone in one specific+ * way: `jdk` and `jdi` dispatch on `wub.o(id)`, which maps a wire id to a 1-based enum+ * index and so is `id + 1` over this range, while the `k(id, …)` send calls are already+ * raw. Taking those comparisons at face value yields every received media type one too+ * high. The values below are the raw wire ids, and they agree with the public+ * aasdk/openauto tables.+ */+object GalMessage {++    /** Control channel, channel id 0. */+    object Control {+        const val VERSION_REQUEST = 1+        const val VERSION_RESPONSE = 2++        /** Raw TLS handshake bytes, wrapped and unwrapped by the SSL engine. */+        const val SSL_HANDSHAKE = 3+        const val AUTH_COMPLETE = 4++        /** The phone asks; the head unit answers with its service list. */+        const val SERVICE_DISCOVERY_REQUEST = 5+        const val SERVICE_DISCOVERY_RESPONSE = 6++        const val CHANNEL_OPEN_REQUEST = 7+        const val CHANNEL_OPEN_RESPONSE = 8++        const val PING_REQUEST = 11+        const val PING_RESPONSE = 12++        const val NAVIGATION_FOCUS_NOTIFICATION = 14++        const val BYEBYE_REQUEST = 15+        const val BYEBYE_RESPONSE = 16++        const val AUDIO_FOCUS_REQUEST = 18+        const val AUDIO_FOCUS_NOTIFICATION = 19++        const val CALL_AVAILABILITY_STATUS = 24++        /** Hot-add or replace a single service after the initial discovery. */+        const val SERVICE_DISCOVERY_UPDATE = 26++        const val MESSAGE_ERROR = 255+        const val FRAMING_ERROR = 0xFFFF+    }++    /** Shared by the video sink, the three audio sinks and the microphone source. */+    object Media {+        /** Bulk payload prefixed with an 8-byte timestamp. */+        const val DATA_WITH_TIMESTAMP = 0x0000++        /** Bulk payload with no timestamp. */+        const val DATA = 0x0001++        const val SETUP_REQUEST = 0x8000+        const val START_REQUEST = 0x8001+        const val STOP_REQUEST = 0x8002+        const val CONFIG = 0x8003+        const val ACK = 0x8004+    }++    /** Video sink, on top of [Media]. */+    object Video {+        const val FOCUS_REQUEST = 0x8007+        const val FOCUS_INDICATION = 0x8008+        const val UPDATE_UI_CONFIG_REQUEST = 0x800A+    }++    /** Microphone source. The car owns the microphone, so the phone receives and acks. */+    object Microphone {+        const val REQUEST = 0x8006+    }++    /** Input source: touch, keys and rotary, all reported by the head unit. */+    object Input {+        const val REPORT = 0x8001+        const val KEY_BINDING_REQUEST = 0x8002+        const val KEY_BINDING_RESPONSE = 0x8003+    }++    /** Sensor source. [SENSOR_REQUEST] is synchronous with a 2 s timeout. */+    object Sensor {+        const val SENSOR_REQUEST = 0x8001+        const val SENSOR_RESPONSE = 0x8002+        const val SENSOR_BATCH = 0x8003+        const val SENSOR_ERROR = 0x8004++        /** A [SENSOR_REQUEST] with this update period unsubscribes instead. */+        const val UNSUBSCRIBE_PERIOD = -1L+    }+}++/**+ * Service ids as advertised in the head unit's discovery response, which double as the+ * channel ids. Mirrors gearhead's internal `rro` enum.+ */+enum class GalService(val id: Int) {+    CONTROL(1),+    VIDEO_SINK(2),+    AUDIO_SINK_GUIDANCE(3),+    AUDIO_SINK_SYSTEM(4),+    AUDIO_SINK_MEDIA(5),+    AUDIO_SOURCE(6),+    SENSOR_SOURCE(7),+    INPUT_SOURCE(8),+    BLUETOOTH(9),+    NAVIGATION_STATUS(10),+    MEDIA_PLAYBACK_STATUS(11),+    MEDIA_BROWSER(12),+    PHONE_STATUS(13),+    NOTIFICATION(14),+    RADIO(15),+    VENDOR_EXTENSION(16),+    WIFI_PROJECTION(17),+    WIFI_DISCOVERY(18),+    CAR_CONTROL(19),+    CAR_LOCAL_MEDIA(20),+    BUFFERED_MEDIA_SINK(21),+    CAR_INTENT(22),+    ;++    companion object {+        private val byId = entries.associateBy(GalService::id)++        fun fromId(id: Int): GalService? = byId[id]+    }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MessageCodec.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MessageCodec.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MessageCodec.ktnew file mode 100644index 0000000000..e55f97da99--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/MessageCodec.kt@@ -0,0 +1,54 @@+package com.vayunmathur.auto.protocol++import java.nio.ByteBuffer++/**+ * One message on a channel: a 2-byte big-endian type followed by a protobuf payload.+ *+ * This sits above [FrameHeader]. A frame carries a slice of one of these; a fragmented+ * message is reassembled before it gets here, so [payload] is always complete.+ */+class ChannelMessage(+    val channelId: Int,+    val type: Int,+    val payload: ByteArray,+) {+    override fun toString(): String =+        "ChannelMessage(channel=$channelId, type=0x${type.toString(16)}, ${payload.size} bytes)"+}++/**+ * Encodes and decodes the message-type prefix.+ *+ * The type is read as an **unsigned** 16-bit value. Gearhead does the same+ * (`(char) byteBuffer.getShort()`), and it matters: the framing-error type is `0xFFFF`,+ * which a signed read turns into `-1` and no dispatch table will match.+ */+object MessageCodec {++    const val TYPE_PREFIX_SIZE = 2++    fun encode(type: Int, payload: ByteArray): ByteArray {+        require(type in 0..0xFFFF) { "message type $type does not fit in a uint16" }+        return ByteBuffer.allocate(TYPE_PREFIX_SIZE + payload.size)+            .putShort(type.toShort())+            .put(payload)+            .array()+    }++    /** Encodes a message with no payload, e.g. a framing error. */+    fun encode(type: Int): ByteArray = encode(type, EMPTY)++    fun decode(channelId: Int, bytes: ByteArray): ChannelMessage {+        require(bytes.size >= TYPE_PREFIX_SIZE) {+            "message of ${bytes.size} bytes is too short to carry a type"+        }+        val buffer = ByteBuffer.wrap(bytes)+        val type = buffer.short.toInt() and 0xFFFF+        val payload = ByteArray(buffer.remaining())+        buffer.get(payload)+        return ChannelMessage(channelId, type, payload)+    }++    private val EMPTY = ByteArray(0)+}
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.protonew file mode 100644index 0000000000..2b060a8639--- /dev/null+++ b/auto/protocol/src/main/proto/gal/control.proto@@ -0,0 +1,207 @@+// Google Automotive Link control channel.+//+// 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, which uses the same field numbers.+//+// proto2 throughout, because the originals are proto2: `required` and explicit presence are+// load-bearing here, and a head unit will reject a message missing a required field.++syntax = "proto2";++package gal;++import "gal/services.proto";++option java_package = "com.vayunmathur.auto.protocol.gal";+option java_multiple_files = true;++// ---- enums ----++// Recovered verbatim from the APK's Java enums, values included.+enum MessageStatus {+  STATUS_SUCCESS = 0;+  STATUS_UNSOLICITED_MESSAGE = 1;+  STATUS_NO_COMPATIBLE_VERSION = -1;+  STATUS_CERTIFICATE_ERROR = -2;+  STATUS_AUTHENTICATION_FAILURE = -3;+  STATUS_INVALID_SERVICE = -4;+  STATUS_INVALID_CHANNEL = -5;+  STATUS_INVALID_PRIORITY = -6;+  STATUS_INTERNAL_ERROR = -7;+  STATUS_MEDIA_CONFIG_MISMATCH = -8;+  STATUS_INVALID_SENSOR = -9;+  STATUS_BLUETOOTH_PAIRING_DELAYED = -10;+  STATUS_BLUETOOTH_UNAVAILABLE = -11;+  STATUS_BLUETOOTH_INVALID_ADDRESS = -12;+  STATUS_BLUETOOTH_INVALID_PAIRING_METHOD = -13;+  STATUS_BLUETOOTH_INVALID_AUTH_DATA = -14;+  STATUS_BLUETOOTH_AUTH_DATA_MISMATCH = -15;+  STATUS_BLUETOOTH_HFP_ANOTHER_CONNECTION = -16;+  STATUS_BLUETOOTH_HFP_CONNECTION_FAILURE = -17;+  STATUS_KEYCODE_NOT_BOUND = -18;+  STATUS_RADIO_INVALID_STATION = -19;+  STATUS_INVALID_INPUT = -20;+  STATUS_RADIO_STATION_PRESETS_NOT_SUPPORTED = -21;+  STATUS_RADIO_COMM_ERROR = -22;+  STATUS_AUTHENTICATION_FAILURE_CERT_NOT_YET_VALID = -23;+  STATUS_AUTHENTICATION_FAILURE_CERT_EXPIRED = -24;+  STATUS_PING_TIMEOUT = -25;+  STATUS_CAR_PROPERTY_SET_REQUEST_FAILED = -26;+  STATUS_CAR_PROPERTY_LISTENER_REGISTRATION_FAILED = -27;+  STATUS_COMMAND_NOT_SUPPORTED = -250;+  STATUS_FRAMING_ERROR = -251;+  STATUS_UNEXPECTED_MESSAGE = -253;+  STATUS_BUSY = -254;+  STATUS_OUT_OF_MEMORY = -255;+}++enum ByeByeReason {+  USER_SELECTION = 1;+  DEVICE_SWITCH = 2;+  NOT_SUPPORTED = 3;+  NOT_CURRENTLY_SUPPORTED = 4;+  PROBE_SUPPORTED = 5;+  WIRELESS_PROJECTION_DISABLED = 6;+  POWER_DOWN = 7;+  USER_PROFILE_SWITCH = 8;+}++enum AudioFocusRequestType {+  AUDIO_FOCUS_GAIN = 1;+  AUDIO_FOCUS_GAIN_TRANSIENT = 2;+  AUDIO_FOCUS_GAIN_TRANSIENT_MAY_DUCK = 3;+  AUDIO_FOCUS_RELEASE = 4;+}++enum AudioFocusState {+  AUDIO_FOCUS_STATE_INVALID = 0;+  AUDIO_FOCUS_STATE_GAIN = 1;+  AUDIO_FOCUS_STATE_GAIN_TRANSIENT = 2;+  AUDIO_FOCUS_STATE_LOSS = 3;+  AUDIO_FOCUS_STATE_LOSS_TRANSIENT_CAN_DUCK = 4;+  AUDIO_FOCUS_STATE_LOSS_TRANSIENT = 5;+  AUDIO_FOCUS_STATE_GAIN_MEDIA_ONLY = 6;+  AUDIO_FOCUS_STATE_GAIN_TRANSIENT_GUIDANCE_ONLY = 7;+}++enum NavigationFocusType {+  NAV_FOCUS_NATIVE = 1;+  NAV_FOCUS_PROJECTED = 2;+}++// ---- messages ----++// Control message 5. Sent by the PHONE. Only sent once version negotiation reaches >= 1.6.+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 bytes field6 = 6;+}++// Control message 6. Sent by the HEAD UNIT: it advertises, we consume.+message ServiceDiscoveryResponse {+  repeated Service services = 1;+  optional string head_unit_name = 2;+  optional string car_model = 3;+  optional string car_year = 4;+  optional string car_serial = 5;+  optional int32 driver_position = 6;+  optional string headunit_make = 7;+  optional string headunit_model = 8;+  optional string headunit_software_build = 9;+  optional string headunit_software_version = 10;+  optional bool can_play_native_media_during_vr = 11;+  optional int32 field13 = 13;+  optional string field14 = 14;+  optional bool hide_clock = 15;+  optional bytes field17 = 17;+  // Fields 12 and 16 are absent from this build.+}++// The service id doubles as the channel id. Exactly one of the payload fields is set;+// which one tells you what the service is.+message Service {+  required int32 id = 1;+  optional SensorSourceService sensor_source = 2;+  optional MediaSinkService media_sink = 3;+  optional InputSourceService input_source = 4;+  optional MediaSourceService media_source = 5;+  optional BluetoothService bluetooth = 6;+  optional bytes radio = 7;+  optional NavigationStatusService navigation_status = 8;+  optional bytes media_playback_status = 9;+  optional bytes phone_status = 10;+  optional bytes media_browser = 11;+  optional VendorExtensionService vendor_extension = 12;+  optional bytes notification = 13;+  optional WifiProjectionService wifi_projection = 14;+  optional bytes field15 = 15;+  optional bytes field16 = 16;+  optional bytes field17 = 17;+  optional bytes field18 = 18;+}++// Control message 26: hot-add or replace one service after the initial discovery.+message ServiceDiscoveryUpdate {+  optional Service service = 1;+}++// Control message 7. Note the order: priority first, then the service id. `priority` is+// sint32 because the control channel opens itself at -128.+message ChannelOpenRequest {+  required sint32 priority = 1;+  required int32 service_id = 2;+}++// Control message 4.+message AuthComplete {+  required int32 status = 1;+}++// Control message 11.+message PingRequest {+  required int64 timestamp = 1;+  optional bool bug_report = 2;+  optional bytes field3 = 3;+}++// Control message 12.+message PingResponse {+  required int64 timestamp = 1;+  optional bytes field2 = 2;+}++// Control message 15.+message ByeByeRequest {+  required ByeByeReason reason = 1;+}++// Control message 16. Genuinely empty.+message ByeByeResponse {}++// Control message 18.+message AudioFocusRequestMessage {+  required AudioFocusRequestType request = 1;+}++// Control message 19.+message AudioFocusNotification {+  required AudioFocusState state = 1;+  optional bool unsolicited = 2;+}++// Control message 14.+message NavigationFocusNotification {+  required NavigationFocusType focus = 1;+}++// Control message 24.+message CallAvailabilityStatus {+  optional bool call_available = 1;+}
auto/protocol/src/main/proto/gal/services.proto
diff --git a/auto/protocol/src/main/proto/gal/services.proto b/auto/protocol/src/main/proto/gal/services.protonew file mode 100644index 0000000000..a46a9acfb7--- /dev/null+++ b/auto/protocol/src/main/proto/gal/services.proto@@ -0,0 +1,121 @@+// Google Automotive Link service descriptors -- the payloads a head unit puts inside each+// Service entry of its discovery response.+//+// 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 MediaCodecType {+  MEDIA_CODEC_AUDIO_PCM = 1;+  MEDIA_CODEC_AUDIO_AAC_LC = 2;+  MEDIA_CODEC_VIDEO_H264_BP = 3;+  MEDIA_CODEC_AUDIO_AAC_LC_ADTS = 4;+  MEDIA_CODEC_VIDEO_VP9 = 5;+  MEDIA_CODEC_VIDEO_AV1 = 6;+  MEDIA_CODEC_VIDEO_H265 = 7;+}++enum VideoResolution {+  VIDEO_800x480 = 1;+  VIDEO_1280x720 = 2;+  VIDEO_1920x1080 = 3;+  VIDEO_2560x1440 = 4;+  VIDEO_3840x2160 = 5;+  VIDEO_720x1280 = 6;+  VIDEO_1080x1920 = 7;+  VIDEO_1440x2560 = 8;+  VIDEO_2160x3840 = 9;+}++// All three are `required`: a head unit that omits one is malformed, and protobuf-lite will+// refuse to build it, which is the behaviour we want.+message AudioConfiguration {+  required uint32 sampling_rate = 1;+  required uint32 number_of_bits = 2;+  required uint32 number_of_channels = 3;+}++message VideoConfiguration {+  optional VideoResolution codec_resolution = 1;+  optional int32 frame_rate = 2;+  optional uint32 width_margin = 3;+  optional uint32 height_margin = 4;+  optional uint32 density = 5;+  optional uint32 field6 = 6;+  optional uint32 field8 = 8;+  optional uint32 field9 = 9;+  optional int32 field10 = 10;+  optional bytes field11 = 11;+  // Field 7 is absent from this build.+}++// Carries both audio and video sinks; which one it is depends on the codec type.+message MediaSinkService {+  optional MediaCodecType available_type = 1;+  optional int32 audio_type = 2;+  repeated AudioConfiguration audio_configs = 3;+  repeated VideoConfiguration video_configs = 4;+  optional uint32 available_while_in_call = 6;+  optional int32 field7 = 7;+  optional int32 field8 = 8;+  optional int32 field9 = 9;+  // Field 5 is absent from this build.+}++// The car's microphone. The phone receives this audio and acks it.+message MediaSourceService {+  optional MediaCodecType available_type = 1;+  optional AudioConfiguration audio_config = 2;+}++message TouchConfig {+  required int32 width = 1;+  required int32 height = 2;+  optional int32 type = 3;+}++message InputSourceService {+  repeated int32 keycodes_supported = 1 [packed = true];+  repeated TouchConfig touchscreen = 2;+  repeated TouchConfig touchpad = 3;+  repeated int32 feedback_events_supported = 4;+  optional uint32 field5 = 5;+}++message Sensor {+  required int32 type = 1;+}++message SensorSourceService {+  repeated Sensor sensors = 1;+  optional uint32 location_characterization = 2;+  repeated int32 fuel_types = 3;+  repeated int32 ev_connector_types = 4;+}++message BluetoothService {+  required string car_address = 1;+  repeated int32 supported_pairing_methods = 2 [packed = true];+}++message NavigationStatusService {+  required int32 minimum_interval_ms = 1;+  required int32 type = 2;+  optional bytes image_options = 3;+}++message VendorExtensionService {+  required string name = 1;+  repeated string package_allowlist = 2;+  optional bytes data = 3;+}++message WifiProjectionService {+  optional string car_wifi_bssid = 1;+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FragmenterTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FragmenterTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FragmenterTest.ktnew file mode 100644index 0000000000..689366ad96--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FragmenterTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.auto.protocol++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++class FragmenterTest {++    private val max = FrameHeader.DEFAULT_MAX_FRAME_SIZE+    private val singleMax = max - FrameHeader.SHORT_HEADER_SIZE++    @Test+    fun `a message that fits is one frame flagged first and last`() {+        val fragments = Fragmenter.split(payloadSize = 10)+        assertEquals(1, fragments.size)+        assertEquals(Fragment(0, 10, isFirst = true, isLast = true), fragments.single())+        assertEquals(FrameFlags.FIRST or FrameFlags.LAST, fragments.single().positionFlags)+    }++    @Test+    fun `an empty message is still one frame`() {+        assertEquals(1, Fragmenter.split(payloadSize = 0).size)+    }++    @Test+    fun `the largest single-frame payload does not fragment`() {+        assertEquals(1, Fragmenter.split(singleMax).size)+        assertEquals(2, Fragmenter.split(singleMax + 1).size)+    }++    @Test+    fun `the first fragment is shorter because it carries the total length`() {+        val fragments = Fragmenter.split(50_000)+        assertEquals(max - FrameHeader.LONG_HEADER_SIZE, fragments.first().length)+        assertEquals(singleMax, fragments[1].length)+    }++    @Test+    fun `fragments are contiguous and cover the payload exactly`() {+        for (size in listOf(singleMax + 1, 20_000, 50_000, 1_000_000)) {+            val fragments = Fragmenter.split(size)+            var expectedOffset = 0+            for (fragment in fragments) {+                assertEquals(expectedOffset, fragment.offset, "gap at size $size")+                expectedOffset += fragment.length+            }+            assertEquals(size, expectedOffset, "coverage at size $size")+        }+    }++    @Test+    fun `exactly one first and one last across a fragmented message`() {+        val fragments = Fragmenter.split(50_000)+        assertTrue(fragments.size > 1)+        assertEquals(1, fragments.count { it.isFirst })+        assertEquals(1, fragments.count { it.isLast })+        assertTrue(fragments.first().isFirst)+        assertTrue(fragments.last().isLast)+        // A fragmented message never has a frame that is both, which is what selects the+        // long header on the first frame.+        assertTrue(fragments.none { it.isFirst && it.isLast })+    }++    @Test+    fun `no fragment exceeds what its own header leaves room for`() {+        for (fragment in Fragmenter.split(50_000)) {+            val headerSize = if (fragment.isFirst && !fragment.isLast) {+                FrameHeader.LONG_HEADER_SIZE+            } else {+                FrameHeader.SHORT_HEADER_SIZE+            }+            assertTrue(fragment.length + headerSize <= max, "fragment $fragment overflows")+        }+    }++    @Test+    fun `a payload landing exactly on a boundary does not emit an empty final fragment`() {+        // First fragment takes max-8, then whole max-4 frames after it.+        val size = (max - FrameHeader.LONG_HEADER_SIZE) + singleMax * 2+        val fragments = Fragmenter.split(size)+        assertEquals(3, fragments.size)+        assertTrue(fragments.none { it.length == 0 })+        assertTrue(fragments.last().isLast)+    }++    @Test+    fun `control messages refuse to fragment`() {+        Fragmenter.split(singleMax, isControl = true)+        assertFailsWith<IllegalArgumentException> {+            Fragmenter.split(singleMax + 1, isControl = true)+        }+    }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FrameHeaderTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FrameHeaderTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FrameHeaderTest.ktnew file mode 100644index 0000000000..38bfc8e056--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/FrameHeaderTest.kt@@ -0,0 +1,92 @@+package com.vayunmathur.auto.protocol++import java.nio.ByteBuffer+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNull++class FrameHeaderTest {++    @Test+    fun `unfragmented message uses the short header`() {+        val header = FrameHeader(+            channelId = 2,+            flags = FrameFlags.FIRST or FrameFlags.LAST or FrameFlags.ENCRYPTED,+            payloadLength = 100,+        )+        assertEquals(FrameHeader.SHORT_HEADER_SIZE, header.size)++        val buffer = ByteBuffer.allocate(header.size)+        header.writeTo(buffer)+        assertContentEquals(byteArrayOf(2, 0x0B, 0, 100), buffer.array())+    }++    @Test+    fun `first fragment of a fragmented message carries the total length`() {+        val header = FrameHeader(+            channelId = 5,+            flags = FrameFlags.FIRST,+            payloadLength = 16120,+            totalLength = 40000,+        )+        assertEquals(FrameHeader.LONG_HEADER_SIZE, header.size)++        val buffer = ByteBuffer.allocate(header.size)+        header.writeTo(buffer)+        buffer.flip()+        assertEquals(header, FrameHeader.readFrom(buffer))+    }++    @Test+    fun `payload length is unsigned`() {+        // 40000 exceeds Short.MAX_VALUE; a signed read would come back negative.+        val header = FrameHeader(0, FrameFlags.FIRST or FrameFlags.LAST, 40000)+        val buffer = ByteBuffer.allocate(header.size)+        header.writeTo(buffer)+        buffer.flip()+        assertEquals(40000, FrameHeader.readFrom(buffer).payloadLength)+    }++    @Test+    fun `channel id is unsigned`() {+        val header = FrameHeader(200, FrameFlags.FIRST or FrameFlags.LAST, 1)+        val buffer = ByteBuffer.allocate(header.size)+        header.writeTo(buffer)+        buffer.flip()+        assertEquals(200, FrameHeader.readFrom(buffer).channelId)+    }++    @Test+    fun `middle and last fragments use the short header and carry no total`() {+        for (flags in listOf(0, FrameFlags.LAST)) {+            val header = FrameHeader(3, flags, 8)+            assertEquals(FrameHeader.SHORT_HEADER_SIZE, header.size)+            assertNull(header.totalLength)+        }+    }++    @Test+    fun `total length is rejected when the flags do not call for one`() {+        assertFailsWith<IllegalArgumentException> {+            FrameHeader(1, FrameFlags.FIRST or FrameFlags.LAST, 4, totalLength = 4)+        }+        assertFailsWith<IllegalArgumentException> {+            FrameHeader(1, FrameFlags.FIRST, 4, totalLength = null)+        }+    }++    @Test+    fun `flag accessors read the right bits`() {+        val header = FrameHeader(+            channelId = 0,+            flags = FrameFlags.LAST or FrameFlags.CONTROL,+            payloadLength = 0,+        )+        assertEquals(false, header.isFirst)+        assertEquals(true, header.isLast)+        assertEquals(true, header.isControl)+        assertEquals(false, header.isEncrypted)+    }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalCredentialTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalCredentialTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalCredentialTest.ktnew file mode 100644index 0000000000..01a3128dd9--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalCredentialTest.kt@@ -0,0 +1,142 @@+package com.vayunmathur.auto.protocol++import java.io.File+import java.nio.ByteBuffer+import java.security.KeyStore+import java.security.cert.CertificateFactory+import java.security.cert.X509Certificate+import javax.net.ssl.SSLEngine+import javax.net.ssl.SSLEngineResult.HandshakeStatus+import javax.net.ssl.SSLEngineResult.Status+import javax.net.ssl.TrustManagerFactory+import javax.net.ssl.X509TrustManager+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlin.test.fail++/**+ * Exercises the shipped GAL credential without a device.+ *+ * The PEMs are read straight out of `src/main/assets` rather than duplicated into test+ * resources, so this fails if the shipped files are wrong rather than passing against a+ * private copy.+ */+class GalCredentialTest {++    private val assetDir = File("src/main/assets/gal")++    private fun asset(name: String): String {+        val file = File(assetDir, name)+        assertTrue(file.exists(), "missing shipped asset ${file.absolutePath}")+        return file.readText()+    }++    private fun context() = GalCredential.create(+        certPem = asset("client-cert.pem"),+        keyPem = asset("client-key.pem"),+        rootPem = asset("root.pem"),+    )++    @Test+    fun `the shipped leaf chains to the shipped GAL root`() {+        val factory = CertificateFactory.getInstance("X.509")+        val leaf = factory.generateCertificate(+            asset("client-cert.pem").byteInputStream(),+        ) as X509Certificate+        val root = factory.generateCertificate(+            asset("root.pem").byteInputStream(),+        ) as X509Certificate++        val anchors = KeyStore.getInstance(KeyStore.getDefaultType()).apply {+            load(null, null)+            setCertificateEntry("GAL", root)+        }+        val trust = TrustManagerFactory+            .getInstance(TrustManagerFactory.getDefaultAlgorithm())+            .apply { init(anchors) }+            .trustManagers+            .filterIsInstance<X509TrustManager>()+            .first()++        // Throws if the chain does not validate.+        trust.checkClientTrusted(arrayOf(leaf, root), "RSA")+        assertEquals("CarService", leaf.subjectX500Principal.name.substringAfter("O=")+            .substringBefore(","))+    }++    @Test+    fun `the engine is a server that demands a client certificate`() {+        val engine = GalCredential.serverEngine(context())+        assertEquals(false, engine.useClientMode, "the phone is the TLS server, not the client")+        assertTrue(engine.needClientAuth, "the head unit must present a GAL-signed cert")+    }++    @Test+    fun `a mutually authenticated handshake completes`() {+        val context = context()+        val server = GalCredential.serverEngine(context)+        // A head unit presents its own GAL-signed certificate; we only have the one, which+        // is exactly what openauto does on the head-unit side.+        val client = context.createSSLEngine().apply { useClientMode = true }++        handshake(server, client)++        assertEquals("TLSv1.2", server.session.protocol)+        val peer = server.session.peerCertificates.first() as X509Certificate+        assertTrue(+            peer.subjectX500Principal.name.contains("CarService"),+            "server should have authenticated the client, saw ${peer.subjectX500Principal}",+        )+    }++    /** Drives two engines against each other in memory until both report FINISHED. */+    private fun handshake(server: SSLEngine, client: SSLEngine) {+        server.beginHandshake()+        client.beginHandshake()++        val packetSize = maxOf(server.session.packetBufferSize, client.session.packetBufferSize)+        val appSize =+            maxOf(server.session.applicationBufferSize, client.session.applicationBufferSize)+        val empty = ByteBuffer.allocate(0)++        repeat(MAX_STEPS) {+            if (settled(server) && settled(client)) return+            var progressed = false+            for ((from, to) in listOf(client to server, server to client)) {+                runTasks(from)+                if (from.handshakeStatus != HandshakeStatus.NEED_WRAP) continue++                val wire = ByteBuffer.allocate(packetSize)+                val wrapped = from.wrap(empty, wire)+                assertEquals(Status.OK, wrapped.status, "wrap failed")+                wire.flip()+                progressed = true++                while (wire.hasRemaining()) {+                    runTasks(to)+                    val plain = ByteBuffer.allocate(appSize)+                    val unwrapped = to.unwrap(wire, plain)+                    assertEquals(Status.OK, unwrapped.status, "unwrap failed")+                    if (to.handshakeStatus == HandshakeStatus.NEED_WRAP) break+                }+            }+            if (!progressed) fail("handshake stalled: ${server.handshakeStatus} / ${client.handshakeStatus}")+        }+        fail("handshake did not settle within $MAX_STEPS steps")+    }++    private fun runTasks(engine: SSLEngine) {+        while (engine.handshakeStatus == HandshakeStatus.NEED_TASK) {+            engine.delegatedTask?.run() ?: break+        }+    }++    private fun settled(engine: SSLEngine) =+        engine.handshakeStatus == HandshakeStatus.NOT_HANDSHAKING ||+            engine.handshakeStatus == HandshakeStatus.FINISHED++    private companion object {+        const val MAX_STEPS = 50+    }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalProtoTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalProtoTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalProtoTest.ktnew file mode 100644index 0000000000..d3e028364b--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalProtoTest.kt@@ -0,0 +1,145 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.AudioConfiguration+import com.vayunmathur.auto.protocol.gal.AuthComplete+import com.vayunmathur.auto.protocol.gal.ByeByeReason+import com.vayunmathur.auto.protocol.gal.ByeByeRequest+import com.vayunmathur.auto.protocol.gal.ChannelOpenRequest+import com.vayunmathur.auto.protocol.gal.MediaCodecType+import com.vayunmathur.auto.protocol.gal.MediaSinkService+import com.vayunmathur.auto.protocol.gal.PingRequest+import com.vayunmathur.auto.protocol.gal.Service+import com.vayunmathur.auto.protocol.gal.ServiceDiscoveryResponse+import com.vayunmathur.auto.protocol.gal.VideoConfiguration+import com.vayunmathur.auto.protocol.gal.VideoResolution+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++/**+ * Pins the GAL wire format.+ *+ * These assert exact bytes rather than round-tripping, because a round-trip passes happily+ * with a wrong field number: the failure only shows up as a head unit that ignores us. The+ * expected bytes below are derived from the field numbers recovered from the Android Auto+ * APK, so if someone renumbers a field the test says so immediately.+ */+class GalProtoTest {++    @Test+    fun `ChannelOpenRequest puts priority first and zigzags it`() {+        // The control channel opens itself at priority -128, which is why field 1 is sint32+        // rather than int32 -- as int32 a negative would cost ten bytes of varint.+        val bytes = ChannelOpenRequest.newBuilder()+            .setPriority(-128)+            .setServiceId(2)+            .build()+            .toByteArray()++        assertContentEquals(+            byteArrayOf(+                0x08, 0xFF.toByte(), 0x01, // field 1, varint, zigzag(-128) = 255+                0x10, 0x02, //               field 2, varint, 2+            ),+            bytes,+        )+    }++    @Test+    fun `ChannelOpenRequest refuses to build without both required fields`() {+        assertFailsWith<Exception> {+            ChannelOpenRequest.newBuilder().setServiceId(2).build()+        }+        assertFailsWith<Exception> {+            ChannelOpenRequest.newBuilder().setPriority(0).build()+        }+    }++    @Test+    fun `PingRequest carries its timestamp in field 1`() {+        // Read off the APK as field 1, not field 2 -- a hand-read of the decompiled Java+        // suggested 2 because `b` there is the hasbit word, not the first field.+        val bytes = PingRequest.newBuilder().setTimestamp(1).build().toByteArray()+        assertContentEquals(byteArrayOf(0x08, 0x01), bytes)+    }++    @Test+    fun `AuthComplete status is a plain int32 in field 1`() {+        assertContentEquals(+            byteArrayOf(0x08, 0x00),+            AuthComplete.newBuilder().setStatus(0).build().toByteArray(),+        )+    }++    @Test+    fun `ByeByeRequest encodes the reason enum by value`() {+        val bytes = ByeByeRequest.newBuilder()+            .setReason(ByeByeReason.DEVICE_SWITCH)+            .build()+            .toByteArray()+        assertContentEquals(byteArrayOf(0x08, 0x02), bytes)+    }++    @Test+    fun `AudioConfiguration needs all three fields`() {+        assertFailsWith<Exception> {+            AudioConfiguration.newBuilder().setSamplingRate(48000).build()+        }+        val config = AudioConfiguration.newBuilder()+            .setSamplingRate(48000)+            .setNumberOfBits(16)+            .setNumberOfChannels(2)+            .build()+        assertEquals(48000, config.samplingRate)+    }++    @Test+    fun `a discovery response parses back into its services`() {+        val response = ServiceDiscoveryResponse.newBuilder()+            .setHeadUnitName("Pioneer")+            .addServices(+                Service.newBuilder()+                    .setId(GalService.VIDEO_SINK.id)+                    .setMediaSink(+                        MediaSinkService.newBuilder()+                            .setAvailableType(MediaCodecType.MEDIA_CODEC_VIDEO_H264_BP)+                            .addVideoConfigs(+                                VideoConfiguration.newBuilder()+                                    .setCodecResolution(VideoResolution.VIDEO_1920x1080)+                                    .setFrameRate(60)+                                    .setDensity(160),+                            ),+                    ),+            )+            .build()++        val parsed = ServiceDiscoveryResponse.parseFrom(response.toByteArray())+        assertEquals("Pioneer", parsed.headUnitName)+        val service = parsed.servicesList.single()+        assertEquals(GalService.VIDEO_SINK, GalService.fromId(service.id))+        assertTrue(service.hasMediaSink())+        assertEquals(+            VideoResolution.VIDEO_1920x1080,+            service.mediaSink.getVideoConfigs(0).codecResolution,+        )+    }++    @Test+    fun `resolution enum values match the head unit's numbering`() {+        // Off-by-one here would negotiate the wrong screen size.+        assertEquals(1, VideoResolution.VIDEO_800x480.number)+        assertEquals(2, VideoResolution.VIDEO_1280x720.number)+        assertEquals(3, VideoResolution.VIDEO_1920x1080.number)+        assertEquals(5, VideoResolution.VIDEO_3840x2160.number)+        assertEquals(9, VideoResolution.VIDEO_2160x3840.number)+    }++    @Test+    fun `codec enum values match the head unit's numbering`() {+        assertEquals(1, MediaCodecType.MEDIA_CODEC_AUDIO_PCM.number)+        assertEquals(3, MediaCodecType.MEDIA_CODEC_VIDEO_H264_BP.number)+        assertEquals(7, MediaCodecType.MEDIA_CODEC_VIDEO_H265.number)+    }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/MessageCodecTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/MessageCodecTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/MessageCodecTest.ktnew file mode 100644index 0000000000..90e3973cab--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/MessageCodecTest.kt@@ -0,0 +1,74 @@+package com.vayunmathur.auto.protocol++import com.vayunmathur.auto.protocol.gal.ChannelOpenRequest+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith++class MessageCodecTest {++    @Test+    fun `the type is a big-endian prefix ahead of the payload`() {+        val encoded = MessageCodec.encode(+            GalMessage.Control.CHANNEL_OPEN_REQUEST,+            byteArrayOf(0x0A, 0x0B),+        )+        assertContentEquals(byteArrayOf(0x00, 0x07, 0x0A, 0x0B), encoded)+    }++    @Test+    fun `the type is unsigned so the framing error round-trips`() {+        // 0xFFFF read as a signed short is -1 and matches nothing.+        val encoded = MessageCodec.encode(GalMessage.Control.FRAMING_ERROR)+        assertContentEquals(byteArrayOf(0xFF.toByte(), 0xFF.toByte()), encoded)++        val decoded = MessageCodec.decode(channelId = 0, bytes = encoded)+        assertEquals(GalMessage.Control.FRAMING_ERROR, decoded.type)+        assertEquals(0, decoded.payload.size)+    }++    @Test+    fun `0x8000-based service types survive the round trip`() {+        for (type in listOf(+            GalMessage.Media.SETUP_REQUEST,+            GalMessage.Media.ACK,+            GalMessage.Video.FOCUS_INDICATION,+            GalMessage.Sensor.SENSOR_BATCH,+        )) {+            val decoded = MessageCodec.decode(2, MessageCodec.encode(type, byteArrayOf(1)))+            assertEquals(type, decoded.type, "type 0x${type.toString(16)} did not round-trip")+        }+    }++    @Test+    fun `a real protobuf survives the round trip intact`() {+        val request = ChannelOpenRequest.newBuilder()+            .setPriority(-128)+            .setServiceId(GalService.VIDEO_SINK.id)+            .build()++        val decoded = MessageCodec.decode(+            channelId = 0,+            bytes = MessageCodec.encode(+                GalMessage.Control.CHANNEL_OPEN_REQUEST,+                request.toByteArray(),+            ),+        )++        assertEquals(GalMessage.Control.CHANNEL_OPEN_REQUEST, decoded.type)+        val parsed = ChannelOpenRequest.parseFrom(decoded.payload)+        assertEquals(-128, parsed.priority)+        assertEquals(GalService.VIDEO_SINK.id, parsed.serviceId)+    }++    @Test+    fun `a message too short to hold a type is rejected`() {+        assertFailsWith<IllegalArgumentException> { MessageCodec.decode(0, byteArrayOf(0x01)) }+    }++    @Test+    fun `a type outside uint16 is rejected`() {+        assertFailsWith<IllegalArgumentException> { MessageCodec.encode(0x10000) }+    }+}
auto/src/main/AndroidManifest.xml
diff --git a/nowplaying/src/main/AndroidManifest.xml b/auto/src/main/AndroidManifest.xmlsimilarity index 81%rename from nowplaying/src/main/AndroidManifest.xmlrename to auto/src/main/AndroidManifest.xmlindex 7488ef2d25..6730544a79 100644--- a/nowplaying/src/main/AndroidManifest.xml+++ b/auto/src/main/AndroidManifest.xml@@ -1,22 +1,25 @@ <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> -    <uses-permission android:name="android.permission.RECORD_AUDIO" />-    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <!-- The projection session outlives any activity: it is bound to the cable or the wireless+         link, not to a screen the user is looking at. -->     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />-    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />+    <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" />      <application-        android:allowBackup="true"+        android:allowBackup="false"         android:dataExtractionRules="@xml/data_extraction_rules"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"         android:roundIcon="@mipmap/ic_launcher"         android:supportsRtl="true"         android:theme="@style/Theme.General">+         <activity-            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"             android:name=".MainActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"             android:exported="true"             android:launchMode="singleTop"             android:theme="@style/Theme.General">@@ -25,10 +28,5 @@                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>--        <service-            android:name=".service.ListenerService"-            android:foregroundServiceType="microphone"-            android:exported="false" />     </application> </manifest>
auto/src/main/java/com/vayunmathur/auto/MainActivity.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/MainActivity.kt b/auto/src/main/java/com/vayunmathur/auto/MainActivity.ktsimilarity index 62%rename from euicc/src/main/java/com/vayunmathur/euicc/MainActivity.ktrename to auto/src/main/java/com/vayunmathur/auto/MainActivity.ktindex a02da5b099..b990281caa 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/MainActivity.kt+++ b/auto/src/main/java/com/vayunmathur/auto/MainActivity.kt@@ -1,18 +1,23 @@-package com.vayunmathur.euicc+package com.vayunmathur.auto  import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels-import com.vayunmathur.euicc.platform.EuiccViewModel+import com.vayunmathur.auto.platform.AutoViewModel import com.vayunmathur.library.ui.DynamicTheme  class MainActivity : ComponentActivity() {-    private val viewModel: EuiccViewModel by viewModels()+    private val viewModel: AutoViewModel by viewModels()+     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         enableEdgeToEdge()-        setContent { DynamicTheme { Navigation(viewModel) } }+        setContent {+            DynamicTheme {+                Navigation(viewModel)+            }+        }     } }
auto/src/main/java/com/vayunmathur/auto/Navigation.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/Navigation.kt b/auto/src/main/java/com/vayunmathur/auto/Navigation.ktnew file mode 100644index 0000000000..d637260735--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/Navigation.kt@@ -0,0 +1,17 @@+package com.vayunmathur.auto++import androidx.compose.runtime.Composable+import com.vayunmathur.auto.platform.AutoViewModel+import com.vayunmathur.auto.ui.AutoScreen+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack++@Composable+fun Navigation(viewModel: AutoViewModel) {+    val backStack = rememberNavBackStack<Route>(Route.Home)+    MainNavigation(backStack) {+        entry<Route.Home> {+            AutoScreen(state = viewModel.state)+        }+    }+}
auto/src/main/java/com/vayunmathur/auto/Route.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/Route.kt b/auto/src/main/java/com/vayunmathur/auto/Route.ktnew file mode 100644index 0000000000..b445e8cc34--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/Route.kt@@ -0,0 +1,15 @@+package com.vayunmathur.auto++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++/**+ * Auto has one phone-side screen. The interesting interface lives on the car's display, not+ * here; this is only somewhere to see whether a car is attached.+ */+@Serializable+sealed interface Route : NavKey {+    /** Connection state and how to attach a car. */+    @Serializable+    data object Home : Route+}
auto/src/main/java/com/vayunmathur/auto/platform/AutoConnectionState.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/AutoConnectionState.kt b/auto/src/main/java/com/vayunmathur/auto/platform/AutoConnectionState.ktnew file mode 100644index 0000000000..e3451167ce--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AutoConnectionState.kt@@ -0,0 +1,16 @@+package com.vayunmathur.auto.platform++/** What the phone is currently doing about a car, as the status screen needs to render it. */+sealed interface AutoConnectionState {+    /** No head unit attached, over either transport. */+    data object Disconnected : AutoConnectionState++    /** A transport is up; version negotiation and the TLS handshake are in progress. */+    data object Connecting : AutoConnectionState++    /** Authenticated and projecting. [carName] is whatever the head unit reported. */+    data class Projecting(val carName: String) : AutoConnectionState++    /** The head unit refused our certificate, or auth otherwise failed. */+    data object Rejected : AutoConnectionState+}
auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.ktnew file mode 100644index 0000000000..6b9fe1b586--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AutoViewModel.kt@@ -0,0 +1,12 @@+package com.vayunmathur.auto.platform++import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.lifecycle.ViewModel++/** Holds what the status screen shows. The projection session will drive this. */+class AutoViewModel : ViewModel() {+    var state: AutoConnectionState by mutableStateOf(AutoConnectionState.Disconnected)+        private set+}
auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt b/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.ktnew file mode 100644index 0000000000..c0b1d68b4d--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/ui/AutoScreen.kt@@ -0,0 +1,56 @@+package com.vayunmathur.auto.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.auto.R+import com.vayunmathur.auto.platform.AutoConnectionState+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior++/** Whether a car is attached, and what to do if one is not. */+@Composable+fun AutoScreen(state: AutoConnectionState) {+    val scrollBehavior = appBarScrollBehavior()+    AppScaffold(+        title = stringResource(R.string.app_name),+        scrollBehavior = scrollBehavior,+    ) { padding ->+        Column(+            Modifier+                .padding(padding)+                .verticalScroll(rememberScrollState())+                .padding(horizontal = 16.dp),+        ) {+            Card(Modifier.fillMaxWidth()) {+                ListItem(+                    headlineContent = { Text(stringResource(R.string.connection)) },+                    supportingContent = { Text(state.describe()) },+                )+            }+            Text(+                text = stringResource(R.string.connect_hint),+                style = MaterialTheme.typography.bodyMedium,+                modifier = Modifier.padding(vertical = 16.dp),+            )+        }+    }+}++@Composable+private fun AutoConnectionState.describe(): String = when (this) {+    AutoConnectionState.Disconnected -> stringResource(R.string.state_disconnected)+    AutoConnectionState.Connecting -> stringResource(R.string.state_connecting)+    is AutoConnectionState.Projecting -> stringResource(R.string.state_projecting, carName)+    AutoConnectionState.Rejected -> stringResource(R.string.state_rejected)+}
auto/src/main/res/values/strings.xml
diff --git a/auto/src/main/res/values/strings.xml b/auto/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..63979797d8--- /dev/null+++ b/auto/src/main/res/values/strings.xml@@ -0,0 +1,21 @@+<?xml version="1.0" encoding="utf-8"?>+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">+    <!-- Launcher and title. The product is a projection sender: it puts a driving-safe+         interface on the car's screen. -->+    <string name="app_name">Auto</string>++    <!-- Heading of the card showing whether a head unit is connected. -->+    <string name="connection">Connection</string>+    <!-- Shown when no head unit is attached, over USB or wirelessly. -->+    <string name="state_disconnected">Not connected to a car</string>+    <!-- Shown while the USB or wireless link is being brought up and authenticated. -->+    <string name="state_connecting">Connecting…</string>+    <!-- Shown once the car has authenticated and projection is running. %1$s is the car's+         name as it reported it, for example "Pioneer" or "Volkswagen". -->+    <string name="state_projecting">Projecting to <xliff:g example="Pioneer" id="car">%1$s</xliff:g></string>+    <!-- Shown when the link came up but the car refused to authenticate us. -->+    <string name="state_rejected">The car would not accept this phone</string>++    <!-- 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>+</resources>
auto/src/main/res/xml/data_extraction_rules.xml
diff --git a/nowplaying/src/main/res/xml/data_extraction_rules.xml b/auto/src/main/res/xml/data_extraction_rules.xmlsimilarity index 100%rename from nowplaying/src/main/res/xml/data_extraction_rules.xmlrename to auto/src/main/res/xml/data_extraction_rules.xml
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.ktindex 8c2f6538ff..294cd08013 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -232,6 +232,7 @@ fun CameraScreen(     }     val highSpeedActive by viewModel.highSpeedActive.collectAsState()     val photoSessionActive by viewModel.photoSessionActive.collectAsState()+    val analysisStreamActive by viewModel.analysisStreamActive.collectAsState()     // Whether to offer the NIGHT extension. Reactive: the ViewModel recomputes it on lens/mode     // change (off-main; support probe + weekly failure cache) AND flips it false immediately if a     // night bind fails, so a broken extender (GrapheneOS/Pixel) stops engaging night after one try.@@ -330,8 +331,9 @@ fun CameraScreen(     }      // Analyzer selection for the photo modes. Keyed on photoSessionActive so the analyzer is-    // re-applied to the freshly-bound ImageAnalysis after every (re)bind (mode switch / flip).-    LaunchedEffect(cameraMode, photoSessionActive) {+    // re-applied to the freshly-bound ImageAnalysis after every (re)bind (mode switch / flip), and+    // on lensFacing to match the DisposableEffect below, which detaches on a flip.+    LaunchedEffect(cameraMode, photoSessionActive, lensFacing) {         when {             cameraMode == CameraMode.SLOW_MO -> {                 maskBitmap = null@@ -354,7 +356,7 @@ fun CameraScreen(                     }                     else -> {                         maskBitmap = null-                        viewModel.setImageAnalyzer(+                        viewModel.setPhotoAnalyzer(                             PhotoAnalyzer(                                 onLuminance = { viewModel.onLuminance(it) },                                 onQrDetected = { viewModel.setQrResult(it) },@@ -403,8 +405,13 @@ fun CameraScreen(             }         } else null         onDispose {-            viewModel.setImageAnalyzer(null)-            analyzer?.close()+            // Only detach what this effect attached. It also keys on lensFacing, which the+            // analyzer-selection effect above does not, so an unconditional clear stripped+            // PhotoAnalyzer off the photo stream on every camera flip.+            if (analyzer != null) {+                viewModel.setImageAnalyzer(null)+                analyzer.close()+            }             // Post recycle to avoid racing with graphicsLayer reading maskBitmap             mainHandler.post {                 maskBitmap?.let { bmp ->@@ -742,6 +749,22 @@ fun CameraScreen(                         )                     } +                    // Some vendor NIGHT extensions can't host a concurrent ImageAnalysis stream, so+                    // the session binds without one and QR codes stop being read. Say so rather than+                    // letting the scanner look broken.+                    if (isPhotoType && photoSessionActive && !analysisStreamActive) {+                        Text(+                            text = stringResource(R.string.qr_scanning_paused),+                            color = Color.White,+                            fontSize = 12.sp,+                            modifier = Modifier+                                .align(Alignment.TopCenter)+                                .padding(top = 84.dp)+                                .background(Color(0x66000000), RoundedCornerShape(12.dp))+                                .padding(horizontal = 10.dp, vertical = 4.dp)+                        )+                    }+                     Column(                         modifier = Modifier                             .align(Alignment.BottomCenter)
camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.ktindex 5a946bdd15..ebbd2ede6f 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -299,6 +299,10 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {     private val sensorManager by lazy { app.getSystemService(Context.SENSOR_SERVICE) as SensorManager }     // Dedicated single thread for portrait segmentation so main thread stays free for preview rendering.     private val bokehExecutor: ExecutorService = Executors.newSingleThreadExecutor()+    // Same for the photo stream. [PhotoAnalyzer] copies the Y plane, runs a ZXing decode and (in+    // PHOTO) a toBitmap() per frame; on the main executor that only ran between UI frames, so+    // KEEP_ONLY_LATEST dropped most of them and QR codes decoded only when main happened to be idle.+    private val analysisExecutor: ExecutorService = Executors.newSingleThreadExecutor()     // Bakes the same bokeh into the saved still. Separate from the preview's BokehAnalyzer, which is     // owned by the composable and torn down with it; this one loads its model on the first capture.     private val stillBokeh = StillBokehRenderer(app)@@ -475,8 +479,9 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {     }      // Consecutive-frame counters backing the hysteresis + debounce in onLuminance().-    private var lowLumaFrames = 0-    private var highLumaFrames = 0+    // Bumped on the analysis thread, zeroed from main by resetNightModeDetection().+    @Volatile private var lowLumaFrames = 0+    @Volatile private var highLumaFrames = 0      private val _longExposureProgress = MutableStateFlow(0f)     val longExposureProgress = _longExposureProgress.asStateFlow()@@ -516,14 +521,25 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {     private var imageCapture: ImageCapture? = null     private var imageAnalysis: ImageAnalysis? = null -    // The analyzer currently attached to imageAnalysis, so the night burst can swap in a temporary-    // frame collector and restore the previous analyzer (PhotoAnalyzer) when it finishes.-    private var currentAnalyzer: ImageAnalysis.Analyzer? = null+    // The analyzer the UI wants running, kept across teardown/rebind. Every session bind re-attaches+    // it via [attachDesiredAnalyzer], so a new ImageAnalysis is never left bare: the UI's attach+    // effect is keyed on photoSessionActive, and that StateFlow conflates, so a false->true rebind+    // inside one frame used to leave the analyzer detached until the next mode switch.+    private var desiredAnalyzer: ImageAnalysis.Analyzer? = null+    private var desiredAnalyzerExecutor: Executor? = null      /** True once the photo session's use cases (incl. ImageAnalysis) are bound. */     private val _photoSessionActive = MutableStateFlow(false)     val photoSessionActive = _photoSessionActive.asStateFlow() +    /**+     * Whether the bound session actually carries an ImageAnalysis stream. False when the vendor+     * NIGHT extension can't host concurrent analysis, which silently stops QR scanning, luminance+     * sampling and Motion Photo; the viewfinder shows a notice so it isn't a mystery.+     */+    private val _analysisStreamActive = MutableStateFlow(false)+    val analysisStreamActive = _analysisStreamActive.asStateFlow()+     /**      * True while the live preview is bound with the CameraX NIGHT extension (plain      * PHOTO mode, low light). When set, capture goes straight through the already@@ -1402,6 +1418,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {             readManualControlRanges()             applyManualControls()             boundCamera?.cameraInfo?.let { observeNightModeIndicator(it) }+            onSessionBound()             _photoSessionActive.value = true             Log.d("NightPreview", "setupPhotoSession() SUCCESS photoActive=true surface=${_surfaceRequest.value?.resolution} nightIndicatorSupported=$nightIndicatorSupported")             true@@ -1492,6 +1509,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {                     imageAnalysis = analysis                     bindSession(provider, owner, nightSelector, preview, capture, analysis)                 } else {+                    Log.w("NightPreview", "setupNightPreviewSession() binding NIGHT without ImageAnalysis – QR scanning, luminance sampling and Motion Photo are off for this session")                     imageAnalysis = null                     bindSession(provider, owner, nightSelector, preview, capture)                 }@@ -1524,6 +1542,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {                 observeExtensionStrength(it)                 observeExtensionCameraState(it)             }+            onSessionBound()             _nightPreviewActive.value = true             _photoSessionActive.value = true             Log.d("NightPreview", "setupNightPreviewSession() SUCCESS – nightPreviewActive=true photoSessionActive=true surfaceRequest=${_surfaceRequest.value?.resolution}")@@ -1627,6 +1646,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {                 restoreZoom(it.minZoomRatio, it.maxZoomRatio)                 Log.d("NightPreview", "setupPortraitSession() after update levels=${_availableZoomLevels.value} ratio=${_zoomRatio.value}")             }+            onSessionBound()             _photoSessionActive.value = true             Log.d("NightPreview", "setupPanoramaSession() SUCCESS photoActive=true surface=${_surfaceRequest.value?.resolution}")             true@@ -1786,6 +1806,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {             _sloMoSupported.value = true             readManualControlRanges()             applyManualControls()+            onSessionBound()             _photoSessionActive.value = true             Log.d("NightPreview", "setupPortraitSession() SUCCESS photoActive=true surface=${_surfaceRequest.value?.resolution}")             true@@ -2080,11 +2101,12 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {         highSpeedRecording = null         try {             imageAnalysis?.clearAnalyzer()-            Log.d("NightPreview", "teardownSession() cleared analyzer previous=${currentAnalyzer?.javaClass?.simpleName}")+            Log.d("NightPreview", "teardownSession() cleared analyzer previous=${desiredAnalyzer?.javaClass?.simpleName}")         } catch (e: Exception) {             Log.e("NightPreview", "teardownSession() clearAnalyzer failed (swallowed before)", e)         }-        currentAnalyzer = null+        // desiredAnalyzer is deliberately kept: teardown runs on every rebind and the next bind+        // re-attaches it. Only the UI clears it, when the effect that owns the analyzer disposes.         sessionLifecycleOwner?.destroy()         sessionLifecycleOwner = null         try {@@ -2100,6 +2122,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {         highSpeedVideoCapture = null         cameraProvider = null         _photoSessionActive.value = false+        _analysisStreamActive.value = false         _nightPreviewActive.value = false         _highSpeedActive.value = false         _videoSessionActive.value = false@@ -2154,17 +2177,13 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {      /** Swaps the analyzer on the bound ImageAnalysis without rebinding. */     fun setImageAnalyzer(analyzer: ImageAnalysis.Analyzer?) {-        val analysis = imageAnalysis ?: return-        currentAnalyzer = analyzer-        if (analyzer == null) analysis.clearAnalyzer()-        else analysis.setAnalyzer(ContextCompat.getMainExecutor(app), analyzer)+        setImageAnalyzer(analyzer, ContextCompat.getMainExecutor(app))     }      fun setImageAnalyzer(analyzer: ImageAnalysis.Analyzer?, executor: Executor) {-        val analysis = imageAnalysis ?: return-        currentAnalyzer = analyzer-        if (analyzer == null) analysis.clearAnalyzer()-        else analysis.setAnalyzer(executor, analyzer)+        desiredAnalyzer = analyzer+        desiredAnalyzerExecutor = executor+        attachDesiredAnalyzer()     }      /** Convenience for portrait bokeh – always runs off the dedicated bokeh thread. */@@ -2172,6 +2191,30 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {         setImageAnalyzer(analyzer, bokehExecutor)     } +    /** Convenience for the photo stream – always runs off the dedicated analysis thread. */+    fun setPhotoAnalyzer(analyzer: ImageAnalysis.Analyzer?) {+        setImageAnalyzer(analyzer, analysisExecutor)+    }++    /**+     * Pushes [desiredAnalyzer] onto whatever ImageAnalysis is currently bound. A no-op while none+     * is, which is why the desired analyzer survives teardown: the next successful bind calls this+     * again and picks it back up.+     */+    private fun attachDesiredAnalyzer() {+        val analysis = imageAnalysis ?: return+        val analyzer = desiredAnalyzer+        val executor = desiredAnalyzerExecutor+        if (analyzer == null || executor == null) analysis.clearAnalyzer()+        else analysis.setAnalyzer(executor, analyzer)+    }++    /** Publishes whether the session just bound has an analysis stream, and re-arms the analyzer. */+    private fun onSessionBound() {+        _analysisStreamActive.value = imageAnalysis != null+        attachDesiredAnalyzer()+    }+     private fun startRecordingTimer() {         _isRecording.value = true         _recordingPaused.value = false@@ -2709,7 +2752,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {             }             provider.unbindAll()             imageAnalysis = null-            currentAnalyzer = null+            _analysisStreamActive.value = false              val baseSelector = CameraSelector.Builder()                 .requireLensFacing(_lensFacing.value)@@ -3438,6 +3481,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {     override fun onCleared() {         unregisterLevelSensor()         try { bokehExecutor.shutdown() } catch (_: Exception) {}+        try { analysisExecutor.shutdown() } catch (_: Exception) {}         try { stillBokeh.close() } catch (_: Exception) {}     } }
camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.ktindex ba6b089cbb..911fe3e93a 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/PhotoAnalyzer.kt@@ -17,7 +17,11 @@ import com.google.zxing.common.HybridBinarizer /**  * Combined PHOTO-stream analyzer. The ImageAnalysis use case can only host one analyzer, so this  * reads the Y (luminance) plane once and both (1) samples average brightness for night-mode- * detection and (2) runs the ZXing QR decode. Replaces the standalone [QrAnalyzer] in PHOTO mode.+ * detection and (2) runs the ZXing QR decode.+ *+ * Runs on the ViewModel's dedicated analysis thread, not the main one: the decode plus the+ * Motion-Photo frame copy cost tens of ms per frame, and under STRATEGY_KEEP_ONLY_LATEST that+ * starved the analyzer of frames when it shared the main thread with preview rendering.  *  * When [onMotionFrame] is supplied it also emits a copy of each frame (bitmap + timestamp +  * rotation) so the ViewModel can maintain a Motion-Photo ring buffer off this same stream.
camera/src/main/java/com/vayunmathur/camera/util/QrAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/QrAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/util/QrAnalyzer.ktdeleted file mode 100644index 06f1a7aa82..0000000000--- a/camera/src/main/java/com/vayunmathur/camera/util/QrAnalyzer.kt+++ /dev/null@@ -1,46 +0,0 @@-package com.vayunmathur.camera.util--import androidx.annotation.OptIn-import androidx.camera.core.ExperimentalGetImage-import androidx.camera.core.ImageAnalysis-import androidx.camera.core.ImageProxy-import com.google.zxing.BinaryBitmap-import com.google.zxing.MultiFormatReader-import com.google.zxing.NotFoundException-import com.google.zxing.PlanarYUVLuminanceSource-import com.google.zxing.common.HybridBinarizer--class QrAnalyzer(private val onQrDetected: (String) -> Unit) : ImageAnalysis.Analyzer {-    private val reader = MultiFormatReader()--    @OptIn(ExperimentalGetImage::class)-    override fun analyze(imageProxy: ImageProxy) {-        val plane = imageProxy.planes[0]-        val buffer = plane.buffer-        val bytes = ByteArray(buffer.remaining())-        buffer.get(bytes)--        // dataWidth (arg 2) is the backing array's row stride, not the image width; HALs pad-        // Y rows to an alignment boundary, and using width there shears the frame so no code-        // ever decodes. See the same fix in [PhotoAnalyzer].-        val source = PlanarYUVLuminanceSource(-            bytes,-            plane.rowStride,-            imageProxy.height,-            0, 0,-            imageProxy.width,-            imageProxy.height,-            false-        )-        val bitmap = BinaryBitmap(HybridBinarizer(source))--        try {-            val result = reader.decodeWithState(bitmap)-            onQrDetected(result.text)-        } catch (_: NotFoundException) {-        } finally {-            reader.reset()-            imageProxy.close()-        }-    }-}
camera/src/main/res/values/strings.xml
diff --git a/camera/src/main/res/values/strings.xml b/camera/src/main/res/values/strings.xmlindex 3903cff800..13033b6dca 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -84,6 +84,9 @@     <string name="no_app_to_open_url">No app can open this link</string>     <!-- QrResultOverlay: button to copy QR text to clipboard. Verb. -->     <string name="copy_text">Copy</string>+    <!-- CameraScreen overlay pill: the bound camera session has no analysis stream (some vendor+         night extensions cannot host one), so the viewfinder cannot look for QR codes -->+    <string name="qr_scanning_paused">QR scanning paused</string>      <!-- Pro / manual controls -->     <!-- CameraScreen: slider label for portrait blur/bokeh strength -->
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/CodecNegotiation.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/CodecNegotiation.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/CodecNegotiation.ktindex 8d2f231dc2..c04381751a 100644--- a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/CodecNegotiation.kt+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/CodecNegotiation.kt@@ -84,7 +84,7 @@ object CodecNegotiation {         receiver: DecoderLimits,         width: Int,         height: Int,-        frameRate: Int,+        frameRate: Float,         demoted: Set<VideoCodec> = emptySet(),     ): CodecSelection {         for (codec in PREFERENCE) {
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.ktindex 2932612c52..bd573a4a2e 100644--- a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/HandshakeMessages.kt@@ -58,8 +58,15 @@ import kotlinx.serialization.json.Json  * still parses - but the version moves anyway, because a receiver that advertises nothing is  * indistinguishable from a panel that enumerated no modes, and silently falling back to phone  * geometry is the failure this exists to remove.+ *+ * 9 makes a frame rate a real number. [StreamConfig.frameRate] was an `Int`, which cannot tell+ * 59.94 from 60 or 23.976 from 24 - and a television advertises those as *separate panel modes*,+ * so rounding collapsed pairs of genuine choices into one. Version 8 only ever offered the fastest+ * mode per resolution, so the distinction had nowhere to show; now that every native mode is+ * offered and the receiver switches its panel to match the stream, the rate has to survive the+ * trip exactly or the mode it names cannot be found again on the other side.  */-const val PROTOCOL_VERSION = 8+const val PROTOCOL_VERSION = 9  /** The mDNS service type the TV registers and the phone browses for. */ const val MACAST_SERVICE_TYPE = "_macast._tcp"@@ -157,6 +164,12 @@ data class TvIdentity(      * surface the screen then has to scale back down. Empty when the receiver enumerated nothing,      * which the sender treats as "fall back to the phone's geometry" rather than as a failure -      * mirroring is unaffected either way, because it deliberately sends the phone's own shape.+     *+     * **Every native mode, not one per resolution.** This used to be collapsed by size with the+     * fastest rate kept, on the reasoning that two modes differing only in refresh rate are one+     * choice as far as a desktop is concerned. They are not: the panel presents them differently,+     * and a phone whose encoder cannot hold 60 at 4K can still hold 50 there. Collapsing hid every+     * rate the user might actually have wanted.      */     val displayModes: List<DisplayMode> = emptyList(), ) : ControlMessage@@ -164,9 +177,10 @@ data class TvIdentity( /**  * One mode the television's panel can display.  *- * [refreshRate] is carried because two modes can share a resolution and differ only in rate, and- * dropping it would make them collide when the sender picks. It is not currently used to drive the- * encoder's frame rate, which stays negotiated through [CodecLimits.maxFrameRate].+ * [refreshRate] is what distinguishes two modes that share a resolution, and is carried exactly -+ * a panel really does list 59.94 and 60 separately, and rounding them together would offer one+ * choice where the screen has two. It is also what the sender sets its encoder to and what the+ * receiver switches the panel to, so the same number has to mean the same thing at both ends.  */ @Serializable data class DisplayMode(@@ -296,7 +310,7 @@ data class CodecLimits(     }      /** Whether this envelope takes exactly [width] x [height] at [frameRate]. */-    fun admits(width: Int, height: Int, frameRate: Int): Boolean =+    fun admits(width: Int, height: Int, frameRate: Float): Boolean =         width in 1..maxWidth && height in 1..maxHeight && frameRate <= maxFrameRate } @@ -366,7 +380,15 @@ data class PairFailed( data class StreamConfig(     val width: Int,     val height: Int,-    val frameRate: Int,+    /**+     * Frames per second, and the reason this protocol is at version 9.+     *+     * A `Float` because it names one of the receiver's own panel modes, which are 23.976, 29.97+     * and 59.94 as often as they are whole numbers. The receiver looks its panel mode up by this+     * value and switches the screen to it, so an `Int` here would not merely lose precision - it+     * would name a mode that does not exist.+     */+    val frameRate: Float,     val bitRate: Int,     val audio: Boolean,     val video: Boolean,
cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Streams.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Streams.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Streams.ktindex a36a471493..b6c91ac560 100644--- a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Streams.kt+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/Streams.kt@@ -25,7 +25,21 @@ object StreamConstants {     const val AUDIO_CHANNELS = 2     const val AUDIO_BITRATE = 128_000 -    const val VIDEO_MAX_FRAME_RATE = 30+    /**+     * The rate a session aims for, and the rate a codec has to be able to hold to be chosen at all.+     *+     * **These are two different questions and used to be one number.** The floor is what+     * `CodecNegotiation.choose` enforces against the sender's own encoder, because an encoder that+     * silently under-delivers is worse than one that is refused. The ceiling is only an aspiration:+     * each geometry settles at the highest rate the panel, the decoder and this phone's encoder all+     * manage at that size, which is why 4K commonly lands at the floor while 1080p reaches the+     * ceiling.+     *+     * Raising the ceiling to 60 raises the bitrate ask with it - the target is linear in frame rate+     * - so a 4K session roughly doubles from ~15 to ~30 Mbit/s. That is the trade being made.+     */+    const val VIDEO_MAX_FRAME_RATE = 60f+    const val VIDEO_MIN_FRAME_RATE = 30f      /**      * How long the receiver buffers before playing, in ms.
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/AudioNegotiationTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/AudioNegotiationTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/AudioNegotiationTest.ktindex afa22ef42a..74c10c21d9 100644--- a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/AudioNegotiationTest.kt+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/AudioNegotiationTest.kt@@ -167,7 +167,7 @@ class AudioNegotiationTest {     private fun audioOnlyConfig() = StreamConfig(         width = 0,         height = 0,-        frameRate = 0,+        frameRate = 0f,         bitRate = 0,         audio = true,         video = false,
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/CodecNegotiationTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/CodecNegotiationTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/CodecNegotiationTest.ktindex cb96d32759..86657dd715 100644--- a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/CodecNegotiationTest.kt+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/CodecNegotiationTest.kt@@ -30,7 +30,7 @@ class CodecNegotiationTest {         receiver: List<CodecLimits>,         width: Int = 1344,         height: Int = 2992,-        frameRate: Int = 30,+        frameRate: Float = 30f,         demoted: Set<VideoCodec> = emptySet(),     ) = CodecNegotiation.choose(         senderCodecs = sender,@@ -132,7 +132,7 @@ class CodecNegotiationTest {             choose(                 sender = listOf(limits(VideoCodec.Av1, maxFrameRate = 24), limits(VideoCodec.Hevc)),                 receiver = bothCodecs,-                frameRate = 30,+                frameRate = 30f,             ),         )         assertEquals(VideoCodec.Hevc, chosen.codec)@@ -147,7 +147,7 @@ class CodecNegotiationTest {             choose(                 sender = bothCodecs,                 receiver = listOf(limits(VideoCodec.Av1, maxFrameRate = 24)),-                frameRate = 30,+                frameRate = 30f,             ),         )         assertEquals(VideoCodec.Av1, chosen.codec)
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.ktindex fae8e277dc..b92ed8d1f3 100644--- a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/HandshakeTest.kt@@ -83,7 +83,9 @@ class HandshakeTest {             StreamConfig(                 width = 1440,                 height = 3120,-                frameRate = 30,+                // Fractional on purpose: it is the case an `Int` used to eat, and the reason the+                // protocol moved to 9.+                frameRate = 29.97f,                 bitRate = 12_000_000,                 audio = true,                 video = true,@@ -96,7 +98,7 @@ class HandshakeTest {             StreamConfig(                 width = 1920,                 height = 1080,-                frameRate = 60,+                frameRate = 59.94f,                 bitRate = 12_000_000,                 audio = true,                 video = true,@@ -142,7 +144,7 @@ class HandshakeTest {                 StreamConfig(                     width = 1920,                     height = 1080,-                    frameRate = 30,+                    frameRate = 30f,                     bitRate = 6_000_000,                     audio = false,                     video = true,@@ -406,7 +408,7 @@ class HandshakeTest {         val config = StreamConfig(             width = 1440,             height = 3120,-            frameRate = 30,+            frameRate = 30f,             bitRate = 12_000_000,             audio = true,             video = true,
cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.ktindex a168768d1b..f73dc43f51 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/CastController.kt@@ -1,9 +1,11 @@ package com.vayunmathur.cast.platform  import android.content.Context+import android.hardware.display.DisplayManager import android.media.projection.MediaProjection import android.os.ParcelFileDescriptor import android.util.Log+import android.view.Display import android.view.Surface import com.vayunmathur.cast.R import com.vayunmathur.cast.domain.CastDevice@@ -12,6 +14,7 @@ import com.vayunmathur.cast.domain.ClientPhase import com.vayunmathur.cast.domain.ClientState import com.vayunmathur.cast.network.ControlSocket import com.vayunmathur.cast.platform.discovery.CastDiscoveryManager+import com.vayunmathur.cast.platform.mirror.CaptureGeometry import com.vayunmathur.cast.platform.mirror.EncoderSupport import com.vayunmathur.cast.platform.mirror.MirrorConsentActivity import com.vayunmathur.cast.platform.mirror.MirrorDegradation@@ -52,9 +55,20 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext+import kotlin.math.abs+import kotlin.math.roundToInt  private const val TAG = "CastController" +/**+ * How far apart two frame rates may be and still be the same mode.+ *+ * The framework reports a declared mode's rate back as the float it was given, and the panel's own+ * numbers are 59.94006 and 23.976025, so exact equality is not something to compare on. Small+ * enough that 59.94 and 60 stay distinct.+ */+private const val MODE_RATE_TOLERANCE = 0.2f+ /** What [CastController.startContentSession] managed. */ sealed interface ContentSessionResult { @@ -162,6 +176,36 @@ object CastController {      */     private var activeCodec: VideoCodec? = null +    /**+     * The desktop session's source, kept because its display outlives every [engine] built for it.+     *+     * Null for a mirroring or content session, which have no display of their own to preserve.+     */+    private var desktopSource: MirrorSource.SystemDisplay? = null++    /**+     * Watches the desktop display for the user choosing a different mode in Settings.+     *+     * There is no callback for "the user picked 1080p": the framework simply resizes the display+     * and the owner is expected to notice. Nothing did, which is why the stream used to carry on+     * at whatever geometry the session started with no matter what was selected.+     */+    private var displayListener: DisplayManager.DisplayListener? = null++    /** Held alongside [displayListener], because unregistering needs the same service instance. */+    private var displayManager: DisplayManager? = null++    /**+     * The geometry the running engine was built for, so a display change can be told from an echo.+     *+     * Our own re-negotiation resizes the display, which fires the very listener that started it.+     * Without something to compare against, that is a loop.+     */+    private var activeGeometry: CaptureGeometry? = null++    /** Serialises re-negotiations so two mode changes in quick succession cannot interleave. */+    private var renegotiateJob: Job? = null+     private val _mirrorPhase = MutableStateFlow(MirrorPhase.Idle)     val mirrorPhase: StateFlow<MirrorPhase> = _mirrorPhase.asStateFlow() @@ -460,15 +504,38 @@ object CastController {             // the H.264 reference. There is no H.264 fallback behind this - a phone or a TV without one             // of the two hardware codecs is told which were missing and mirroring stops here.             val (screenWidth, screenHeight) = MirrorGeometry.screenSize(appContext)+            // Mirroring encodes the phone's screen, so the codec is chosen for that size. A desktop+            // is composed at the TV's panel resolution, so choose the codec for the TV's largest+            // mode instead: at 4K that excludes this phone's AV1 encoder (capped well below 4K) and+            // selects H.265 (which reaches it), which is what lets the real panel resolutions reach+            // the picker rather than an encoder-clamped one. Falls back to the screen size if+            // nothing can encode the TV's largest, so a lower real mode still works.+            val desktopMax = (source as? MirrorSource.SystemDisplay)?.let {+                activeClient.displayModes.maxByOrNull { m -> m.width.toLong() * m.height }+            }             val codec = when (-                val choice = chooseCodec(appContext, device, activeClient, screenWidth, screenHeight)+                val choice = chooseCodec(+                    appContext, device, activeClient,+                    desktopMax?.width ?: screenWidth,+                    desktopMax?.height ?: screenHeight,+                )             ) {+                is CodecOutcome.Chosen -> choice                 is CodecOutcome.Refused -> {-                    Log.w(TAG, "refusing to mirror: ${choice.message}")-                    abandonMirroring(appContext, projection, choice.message)-                    return@launch+                    val retry = if (desktopMax != null) {+                        chooseCodec(appContext, device, activeClient, screenWidth, screenHeight)+                    } else {+                        choice+                    }+                    when (retry) {+                        is CodecOutcome.Chosen -> retry+                        is CodecOutcome.Refused -> {+                            Log.w(TAG, "refusing to mirror: ${retry.message}")+                            abandonMirroring(appContext, projection, retry.message)+                            return@launch+                        }+                    }                 }-                is CodecOutcome.Chosen -> choice             }              if (source is MirrorSource.SystemDisplay) {@@ -489,7 +556,7 @@ object CastController {             } else {                 MirrorGeometry.forDisplay(appContext, codec.selection)             }-            val frameRate = MirrorGeometry.frameRateFor(codec.selection.receiverLimits)+            val frameRate = geometry.frameRate             val outcome = mutex.withLock {                 activeClient.configureStream(                     width = geometry.width,@@ -526,10 +593,15 @@ object CastController {             ).apply { hexDump = verboseStreamLogging }             engine = newEngine             activeCodec = codec.codec+            activeGeometry = geometry             if (newEngine.start()) {                 // The framework never discovers this display on its own - MediaRouterService                 // only reads back an id the provider published. See CastSystemDisplay.-                if (source is MirrorSource.SystemDisplay) onDisplayId(source.displayId)+                if (source is MirrorSource.SystemDisplay) {+                    desktopSource = source+                    onDisplayId(source.displayId)+                    watchDisplay(appContext, source)+                }                 _mirrorPhase.value = MirrorPhase.Mirroring                 _sessionState.update {                     it.copy(phase = ClientPhase.Streaming, negotiation = ready.negotiation)@@ -605,7 +677,7 @@ object CastController {             is CodecOutcome.Chosen -> choice         }         val geometry = MirrorGeometry.forContent(width, height, codec.selection)-        val frameRate = MirrorGeometry.frameRateFor(codec.selection.receiverLimits)+        val frameRate = geometry.frameRate         val outcome = mutex.withLock {             activeClient.configureStream(                 width = geometry.width,@@ -660,7 +732,10 @@ object CastController {             audioWriteEnd = newEngine.audioWriteEnd,             width = geometry.width,             height = geometry.height,-            frameRate = frameRate,+            // Rounded, because `CastContract.KEY_GRANTED_FRAME_RATE` is an `Int` in a Bundle read+            // by third-party SDK callers. The wire rate is a float so it can name one of the TV's+            // panel modes exactly; an app drawing into a surface only needs the whole number.+            frameRate = frameRate.roundToInt(),             receiverName = activeClient.receiverName ?: device.friendlyName,         )     }@@ -987,8 +1062,10 @@ object CastController {             width = width,             height = height,             // The rate is a floor, not a target: a codec that cannot hold it is excluded rather than-            // accepted at whatever it manages. Resolution is what yields.-            frameRate = StreamConstants.VIDEO_MAX_FRAME_RATE,+            // accepted at whatever it manages. Resolution is what yields. Deliberately the floor and+            // not the ceiling - selecting against 60 would refuse H.265 at 4K on a phone whose+            // encoder tops out below that, leaving no codec at all rather than a 30fps session.+            frameRate = StreamConstants.VIDEO_MIN_FRAME_RATE,             demoted = demoted,         )         return when (selection) {@@ -1054,10 +1131,142 @@ object CastController {         scope.launch { mutex.withLock { activeClient.sendPlaybackState(state) } }     } +    /**+     * Follow the desktop display's mode, because the user changes it from Settings and not here.+     *+     * Android's external-display resolution picker calls straight into the framework: the display+     * is resized and its mode replaced, and the app that owns it is told only through the ordinary+     * `DisplayListener`. Nothing was listening, so the encoder and the TV kept running the+     * geometry the session started at while the framework composed the desktop at the new one -+     * the picker appeared to work and changed nothing that could be seen.+     */+    private fun watchDisplay(context: Context, source: MirrorSource.SystemDisplay) {+        stopWatchingDisplay()+        val displays = context.getSystemService(DisplayManager::class.java) ?: return+        val listener = object : DisplayManager.DisplayListener {+            override fun onDisplayAdded(displayId: Int) = Unit+            override fun onDisplayRemoved(displayId: Int) = Unit+            override fun onDisplayChanged(displayId: Int) {+                if (displayId != source.displayId) return+                val mode = displays.getDisplay(displayId)?.mode ?: return+                onDesktopModeChanged(context, source, mode)+            }+        }+        displays.registerDisplayListener(listener, null)+        displayListener = listener+        displayManager = displays+    }++    private fun stopWatchingDisplay() {+        renegotiateJob?.cancel()+        renegotiateJob = null+        val listener = displayListener ?: return+        displayListener = null+        runCatching { displayManager?.unregisterDisplayListener(listener) }+        displayManager = null+    }++    /**+     * Re-negotiate the stream around a mode the user picked.+     *+     * **Everything except the display is rebuilt.** A `MediaCodec` cannot be resized, so the+     * encoder and the RTP session have to go; the display cannot be, because it is the desktop -+     * recreating it would destroy every window on it and hand out a new `displayId` that the+     * Settings page the user is standing on no longer refers to. So the new encoder's surface is+     * attached to the display that is already there.+     *+     * Ignores anything that is not actually a change, which is not an optimisation: our own resize+     * fires this same listener, and without the guard each change would trigger the next.+     */+    private fun onDesktopModeChanged(+        context: Context,+        source: MirrorSource.SystemDisplay,+        mode: Display.Mode,+    ) {+        val running = activeGeometry ?: return+        val target = source.supportedModes.firstOrNull {+            it.width == mode.physicalWidth &&+                it.height == mode.physicalHeight &&+                abs(it.frameRate - mode.refreshRate) <= MODE_RATE_TOLERANCE+        } ?: return+        if (target.width == running.width &&+            target.height == running.height &&+            abs(target.frameRate - running.frameRate) <= MODE_RATE_TOLERANCE+        ) {+            return+        }+        if (renegotiateJob?.isActive == true) return+        renegotiateJob = scope.launch {+            val activeClient = client ?: return@launch+            val device = _device.value ?: return@launch+            val codec = activeCodec ?: return@launch+            Log.i(+                TAG,+                "the user chose ${target.width}x${target.height}@${target.frameRate}; " ++                    "re-negotiating from ${running.width}x${running.height}@${running.frameRate}",+            )+            // Only the engine, so the display - and the desktop on it - stays exactly where it is.+            engine?.stop()+            engine = null+            // `reconfigureStream`, not `configureStream`: the watch job is parked in a blocking+            // read on this socket and would swallow the reply. See MirrorClient for the hand-off.+            val outcome = mutex.withLock {+                activeClient.reconfigureStream(+                    width = target.width,+                    height = target.height,+                    frameRate = target.frameRate,+                    bitRate = target.bitRate,+                    videoCodec = codec,+                    audio = true,+                    video = true,+                )+            }+            val ready = outcome as? HandshakeOutcome.Ready+            if (ready == null) {+                Log.w(TAG, "the TV would not agree the new mode: $outcome")+                abandonMirroring(+                    context,+                    null,+                    context.getString(R.string.cast_mirror_negotiation_failed),+                )+                return@launch+            }+            val newEngine = MirrorEngine(+                context = context,+                source = source,+                receiverHost = device.host,+                negotiation = ready.negotiation,+                geometry = target,+                videoCodec = codec,+                frameRate = target.frameRate,+                onDegraded = { _degradation.value = it },+                onStopped = { reason -> onEngineStopped(context, reason) },+                onCodecConfig = { csd -> sendCodecConfig(activeClient, csd) },+            ).apply { hexDump = verboseStreamLogging }+            engine = newEngine+            activeGeometry = target+            if (!newEngine.start()) {+                engine = null+                activeGeometry = null+                return@launch+            }+            _sessionState.update {+                it.copy(phase = ClientPhase.Streaming, negotiation = ready.negotiation)+            }+        }+    }+     private fun stopEngine() {+        stopWatchingDisplay()+        desktopSource?.let {+            it.display?.release()+            it.display = null+        }+        desktopSource = null         engine?.stop()         engine = null         activeCodec = null+        activeGeometry = null         // The served session's other half. An open HTTPS port outliving the session it belonged to         // would serve a token that is no longer anybody's.         proxy?.stop()
cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.ktindex 7c61bf966a..883b4803c9 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/MirrorClient.kt@@ -36,9 +36,20 @@ import com.vayunmathur.cast.protocol.TvIdentity import com.vayunmathur.cast.protocol.VideoCodec import com.vayunmathur.cast.protocol.VideoCodecConfig import java.security.SecureRandom+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.withTimeoutOrNull  private const val TAG = "MirrorClient" +/**+ * How long a mid-session `STREAM_CONFIG` waits for its answer.+ *+ * Far shorter than the socket's own read deadline on purpose. This is a resolution change with a+ * user watching a blank screen, so failing fast and saying so beats holding the session open for a+ * minute on the chance that a television is merely slow.+ */+private const val RECONFIGURE_TIMEOUT_MS = 5_000L+ /** Whether the TV took a content session, and why not if it did not. */ sealed interface ContentOutcome { @@ -103,6 +114,16 @@ class MirrorClient(      private var keys: SessionKeys? = null +    /**+     * A re-negotiation waiting for its `STREAM_READY`, or null when none is.+     *+     * Written from the coroutine calling [reconfigureStream] and read from the thread parked in+     * [awaitEnd], hence `@Volatile`. It is the hand-off between the two: the reader cannot know a+     * reply is wanted, and the requester cannot read it.+     */+    @Volatile+    private var pendingStreamReady: CompletableDeferred<StreamReady>? = null+     /**      * The transcript, frozen after `SEALED_SECRET`.      *@@ -264,7 +285,7 @@ class MirrorClient(     fun configureStream(         width: Int,         height: Int,-        frameRate: Int,+        frame

Diff truncated.