Skip to content

Android: merge community Carlink, audio and media-key fixes (#103–#111); rotation lock and Back on Home - #117

Merged
riko2chen merged 26 commits into
mainfrom
feature/carlink-community-fixes
Nov 5, 2026
Merged

riko2chen merged 26 commits into
mainfrom
feature/carlink-community-fixes

Conversation

@riko2chen

Copy link
Copy Markdown
Contributor

Merges the eight open community pull requests from hellowalker onto main (after #116, Carlink Wi-Fi recovery), with the fixes they needed to fit together. Each pull request's own commits are kept unchanged; adjustments are separate commits.

Merged

PR Problem it solves How it landed
#108 A GATT/scan failure forgot the remembered subscription choice as is
#109 A Carlink scan that finds nothing logged nothing as is
#104 The phone joins the saved head-unit network itself; the specifier request never attaches and the first attempt fails as is for the legacy join; also built into Carlink Wi-Fi recovery (below)
#110 A Wi-Fi join failure redid the whole BLE exchange as is; wraps both join paths
#111 MIUI (Android 10/11) raises an unanswerable Wi-Fi picker for every request no new Experimental switch: runs wherever that dialog does; also built into Carlink Wi-Fi recovery
#105 Steering-wheel media keys never reached CarPlay advertises only PLAY_PAUSE / NEXT / PREVIOUS; test added
#107 The start gave up after one 60 s Carlink window; the screen slept while scanning as is; combined with #116's Wi-Fi wait
#103 Audio stayed silent after a reconnect; PTS jitter re-anchored the clock a stream DiPlay stopped is no longer restarted by a late packet; test added. Its portrait pin is replaced (below)

Fixes on top

Not in this pull request

Validation

:app:testDebugUnitTest: 213 suites, 1479 tests, 0 failures (local, with the integrated DiPlay fix). Not run on a car or phone.

hellowalker and others added 26 commits November 2, 2026 22:18
… rotation from rebuilding it

Two ways the car lost iPhone audio after playing fine.

Reconnect: DiPlayInput.begin() ends the previous session, which clears the
audio map, but DiPlay keeps the same audio stream and never re-fires
onAudioStarted - every packet then hits audio[stream] == null. Separately,
a closed stream can stay in the map because its ended-callback runs after
the session moved on, and offer() drops packets silently. Measured: 1026
packets lost between arrival and the queue, with no rejection log.

Rotation: CarPlayHostActivity ships with screenOrientation=fullSensor, so
rotating the relay re-lays-out the host, tears down the CarPlay session and
audio does not come back (stream_stop/stream_start every ~20 s).

Also: flipping playLocally to false called onAudioStopped, which removes the
whole stream - forwarding included - even though output() never depended on
that flag. And AudioClock re-anchored on network jitter (100 ms threshold
inside normal Wi-Fi bursts), stepping the PTS 26 times per 10 s.

Rebuild the stream when it is missing or stopped (startAudioStream is the
old onAudioStarted body, shared by both entry points), drop the
onAudioStopped call on flag flips, widen the re-anchor threshold to 500 ms,
and pin CarPlayHostActivity and RelayActivity to portrait.

After: arrival = worker = emitted (2683 packets, queued=0), no stream_stop
on rotation, audio keeps reporting n=468 with step=21333.

The Stream half of this fix is in OpenXPlay-Stream; this branch does not
bump stream.lock yet - it must point at a commit on Stream's main, so the
bump happens once that PR lands.

Measured on MI 8 SE (Android 10) with an XPeng G9.
…chor test

Two unit tests pinned behaviour this branch changed.

AudioBridgeTest asserts that turning local playback off calls
onAudioStopped. That is correct: AndroidMediaSink.onAudioStopped only
closes the local renderer and updates the media-audio flag, it does not
touch forwarding. Dropping the call would have leaked renderers, so the
call is restored and the test passes unchanged.

AudioPolicyTest pinned the 100 ms re-anchor threshold. The threshold is
now 500 ms so Wi-Fi burst jitter no longer steps the PTS (measured: 26
jumps per 10 s, up to 355 ms each). The test now expects the
sample-derived PTS to keep advancing through 140 ms of jitter, and a
first packet to still anchor at its arrival time.
The first Carlink attempt after getting in the car fails almost every time, and
the retry right after succeeds. Logs from a Xiaomi Mi 8 SE (Android 10) show
why: the request goes out 20-60 ms before the platform finishes a join it
started on its own for the same saved AP.

  CMD_START_CONNECT                      -32 ms
  requestNetwork(WifiNetworkSpecifier)     0
  CTRL-EVENT-CONNECTED                   +29 ms
  DHCP lease                             +300 ms
  NetworkMonitor: PROBE_DNS ... OK              <- ordinary default network
  12 s later: onUnavailable

When the platform's join wins, the link is created under the system uid and
validated as a normal network, so the specifier request never matches it. When
the request wins, NetworkMonitor logs "Network would not satisfy default
request, not validating" and the callback fires in 0.4 s. Same timings, same
supplicant events, different owner.

Adopt the link instead of racing it: if a Wi-Fi network already carries the
head unit's SSID with an IPv4 lease, bind to it and use its default-route
gateway as the peer. While a request is pending, poll for that link every
100 ms and take it as soon as it gets the lease, releasing the request. An
adopted link has no request callback, so listen for its loss and report it
through the same lost() path the request uses.

A link we adopted is the one the phone is really using, so the SSID check reads
the default network's transport info first; the WifiManager fallback covers
ROMs (MIUI 10) that attach no transport info to these agents, and matches the
lease by address so two concurrent STA links cannot be confused.

Measured on the Mi 8 SE, first attempt after Wi-Fi off/on: before,
wifi_join_unavailable at 12 s and a second attempt (26 s to PLAYING); after,
join_adopted in 0.43-0.47 s and PLAYING in 8 s. After a reboot: first attempt
succeeds in 6-11 s instead of failing once and retrying.
…n match

MIUI 10/11 answers a WifiNetworkSpecifier request with a confirmation dialog
whose window has no input channel, so an unconfirmed request always expires.
The existing priming workaround spends up to four startScan calls per window:
the platform coalesces or refuses the later ones, and a refusal is read as
"nothing to prime", which is how the cache ended up cold while the dialog was
already up.

Issue one scan and wait for its results instead of asking again, and remember
whether the target SSID was actually seen. When it was, give the platform a
2.5 s quiet window to finish the join it just started: adopting that link is
faster and silent, because no request means no dialog. Only when the window
passes without a link does the request go out, with its timeout reduced by the
time already spent.

Measured on MIUI 10: the dialog used to flash on every screen-on connect. With
this, cold start and daily restart show 0 dialogs and adopt in ~0.44 s. The
boot case still requests — a background app gets no scan results — and keeps
its old, faster timing.

Gated to MANUFACTURER == Xiaomi && SDK <= 30, the same combination the priming
workaround already targets; no other device reaches this code.
Steering-wheel media keys arrive on the Carlink control channel (method=12)
and are decoded into ControlEvent.Key by UibcDecoder. The relay dropped them:
DiPlayInput advertised keys = emptySet(), so ProjectionHub's gate rejected
every key, and control() had no ControlEvent.Key branch.

Advertise all KeyCode entries and forward NEXT/PREVIOUS/PLAY_PAUSE to
CarPlayMediaButton, triggering once on key-down (the head unit sends down/up
pairs). Forwarding follows the audio route: enabled only when CarPlay carries
the audio, because with car Bluetooth audio the phone already receives the
keys over AVRCP and forwarding again would skip tracks twice.
The capability test still asserted an empty keys set after DiPlayInput began
advertising KeyCode.entries to let the steering-wheel media keys through
ProjectionHub's gate.
exchange() treats every failure as evidence that the remembered subscription
choice is wrong: any exception calls peers.exchangeFailed(), which drops the
persisted "this head unit needs a local subscription instead of CCCD" flag and
falls back to the CCCD path on the next connection.

Most of those failures never reach the subscription. A GATT connection that
does not complete, a missing service, a scan that timed out — none of them say
anything about whether the head unit answers a CCCD descriptor write. Clearing
the flag there costs a full CCCD timeout on the next attempt, and the attempt
after that re-learns the same answer.

Measured on a Xiaomi Mi 8 SE with a G9 head unit: one transient
gatt_connect_failed turned the next connection into

  peer_choice legacy=false source=default
  ble_cccd result=timeout                  (3.1 s)
  peer_cccd_timeout legacy=true where=memory
  ble_request subscription=legacy          (third attempt)

— 3.1 s of CCCD timeout plus one extra scan and GATT round, 5.3 s of the 20.1 s
that connection took.

Only clear the stored choice for failures that actually exercised the
subscription. Connect-side failures (GATT connect/services, scan, timeout,
discovery, missing service) leave it alone.
A connection that finds nothing produces no log lines at all between
ble_scan_started and the failure, so "the scan sees nothing", "the scanner is
not delivering" and "the app is wedged" were indistinguishable in the field.
Two of those need opposite responses — one is a phone-side fault worth fixing,
the other is the head unit not advertising and there is nothing to do but wait.

Add a counting scan next to the filtered one. It asks for no service UUID and
its only job is to count what the radio delivered, so ble_scan_progress can
report, every 10 s:

  raw       every advertisement the radio heard
  matched   the ones that passed the service filter
  peer      the ones that decoded as an OpenXPlay head unit

raw climbing while peer stays 0 means the head unit is silent; raw frozen
means the scanner stopped. ble_scan_end closes the attempt with the same
numbers and an outcome, and ble_scan_failed reports the platform error code
instead of failing silently. The counting scan is budgeted through the
existing scan-start allowance and reports raw=off when it cannot start.

The same blind spot exists in the persistence layer and after the join: add
the peer_ trace (choice/cccd_timeout/exchanged/succeeded/exchange_failed, with
an eight-character key) and a link_ready sample taken at the join and again
two seconds later, which separates "route never installed" from "head unit not
listening" when the TCP connect straddles several SYN retransmits.

Measured on a Xiaomi Mi 8 SE: the first sample caught the head unit going
quiet for 50 s (raw 1177 -> 4774, peer 0) right after a deauth; the second
caught the Bluetooth stack stopping the scan when the display slept (raw
frozen at 1859 for 4.5 min, recovered 0.36 s after the screen came back).
CarlinkStartGate gives the link 60 s to become ready and then throws, and the
throw tears the whole start down: the wait ends, the gates are cancelled, the
status is set to failed and nothing tries again. That deadline says nothing
about the link, which is still scanning — and the head unit is known to stop
advertising for tens of seconds at a time, so the throw lands exactly in the
window a retry would have covered.

Give the timeout its own type and re-arm the window instead of failing, up to
three more times. Four windows bound the cost at four minutes, which still ends
in a visible failure when the link really is not coming up.

A start that has already given up is also not a stop. When the link finishes
after the last window, nothing restarted CarPlay — in the field the only thing
that ever did was the phone reconnecting on its own. Remember that the start
was abandoned and let the runtime tick start CarPlay once Carlink reports
PLAYING, unless a session is already on its way. A user stop or a new start
clears the flag.

Seen on a Xiaomi Mi 8 SE: after a deauth the link took 91 s to come back while
the gate had already failed at 60 s, so the recovery only happened when the
phone was rebooted by hand.
The Bluetooth stack stops the LE scan when the display sleeps: on a Xiaomi
Mi 8 SE the platform logs stopScan() at the moment the screen times out, and a
scan that was delivering about 100 advertisements per second stops dead — raw
froze at 1859 for four and a half minutes and resumed 0.36 s after the screen
came back. A connection attempt that is still looking for the head unit dies
with it, and the wait that follows has nothing left to find it with.

Hold FLAG_KEEP_SCREEN_ON only while a link is actually being brought up, so
the common case — open the app, wait for CarPlay — cannot lose the scan to the
screen timeout. Bound it to five minutes, one full set of start windows: an
abandoned link keeps reporting CONNECTING forever, and holding the display on
there would never end.

Measured: the flag appears and disappears with the state, including a transient
ENDED between two attempts, and is gone before the session reaches PLAYING.
A Wi-Fi join failure says nothing about the BLE exchange: the head unit keeps
the same soft AP for the session, so failing the join tears the whole link
down and redoes a scan plus exchange that cannot fix the Wi-Fi problem.

Retry the join with the reply already in hand, three attempts with a short
fixed backoff that stays separate from the BLE backoff. A rotated passphrase
still surfaces as a failure and the next link attempt redoes BLE anyway.

While there, treat "the AP was seen" as a timestamp instead of a flag: the
2-minute prime throttle reuses an old scan, and acting on a stale "seen" waits
out the quiet window for a network that has already moved or restarted.
MIUI raises its Wi-Fi picker for every WifiNetworkSpecifier request, and on
the Android 10/11 builds the picker has no input channel: it can never be
answered, so the request expires with the dialog still on screen. The phone
joins the saved head-unit network by itself once a scan shows the AP, and that
link is equivalent for the relay.

Add scanAdoptJoin: after adopting any link the platform already brought up,
issue one scan and adopt whatever the platform joins within a short window
instead of asking for a network of our own. When the phone does not join, fall
back to the existing prime/quiet-window/request path unchanged, so non-MIUI
devices never enter this branch.

Measured on a Xiaomi Mi 8 SE: the handoff-to-join window dropped from a median
5071 ms to 2176 ms, and the Mi UI dialog stopped appearing. The option is a
lab switch (default on), gated to the MIUI/Android-10-11 confirmation-dialog
case.
# Conflicts:
#	android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt
# Conflicts:
#	android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt
# Conflicts:
#	android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt
The scan-and-adopt join runs wherever MIUI's unanswerable dialog does
(Xiaomi, Android 10/11) instead of behind a new Experimental switch; the
Carlink Wi-Fi recovery switch remains the way back to the old flow.
# Conflicts:
#	android/app/src/main/java/org/openxplay/direlay/relay/CarlinkStartGate.kt
…by itself

The car network is a saved network, so the platform often joins it while a
specifier request is pending; that request never attaches (#104).

- MIUI on Android 10/11: one scan at the start, then up to 3 s (0.8 s when
  the scan is refused) for the platform's own join before any request, which
  is what raises MIUI's unanswerable picker (#111).
- A target network the request has not claimed within 2 s was joined by the
  platform: release the request and borrow that link.
- After the request ends, a remaining target joined by the platform is
  adopted without waiting for a return to the app.
DiPlayInput forwards PLAY_PAUSE, NEXT and PREVIOUS; advertising every key
let the hub route HOME, BACK and the knob here only to be refused. Test the
forwarding gate, down-only presses and the end of the session (#105).
The lazy start that rebuilds a stream after a reconnect (#103) also restarted
a stream from a packet that arrived after onAudioStopped, announcing it to the
head unit again. Remember stopped streams until DiPlay starts them again.
- Both DiPlay hosts use fullUser on the relay phone instead of fullSensor, so
  the system rotation lock holds (replaces the portrait pin from #103; DiPlay
  stops rebuilding the session on a turn when the app supplies the canvas).
- Back on the running page opens Home in front of the CarPlay task; Back on
  Home then revealed the running page again. While a CarPlay host task
  exists, Back on Home leaves for the launcher (OpenXPlay-t64j).
@riko2chen
riko2chen enabled auto-merge November 5, 2026 05:46
@riko2chen
riko2chen merged commit d699c40 into main Nov 5, 2026
7 checks passed
@riko2chen
riko2chen deleted the feature/carlink-community-fixes branch November 5, 2026 05:52
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 5, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants