From 54a45b76b5324af59e4cfd2d64f06f9528828b3b Mon Sep 17 00:00:00 2001 From: iwalker <1043309958@qq.com> Date: Mon, 2 Nov 2026 22:18:31 +0800 Subject: [PATCH 01/17] Android: rebuild the Carlink audio stream after a reconnect, and stop 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. --- android/app/src/main/AndroidManifest.xml | 14 ++++ .../openxplay/direlay/bridge/AudioPolicy.kt | 14 +++- .../direlay/bridge/RelayAudioStream.kt | 5 +- .../direlay/bridge/StreamBridgeSink.kt | 68 +++++++++++++------ 4 files changed, 77 insertions(+), 24 deletions(-) diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 0da34872..406b2665 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -106,6 +106,18 @@ + + + diff --git a/android/app/src/main/java/org/openxplay/direlay/bridge/AudioPolicy.kt b/android/app/src/main/java/org/openxplay/direlay/bridge/AudioPolicy.kt index d7399b75..c9f7bf50 100644 --- a/android/app/src/main/java/org/openxplay/direlay/bridge/AudioPolicy.kt +++ b/android/app/src/main/java/org/openxplay/direlay/bridge/AudioPolicy.kt @@ -3,6 +3,7 @@ // Created by riko chen on 2026-10-14 package org.openxplay.direlay.bridge +import android.util.Log import com.shilapi.xcertplay.airplay.AudioCodecKind import com.shilapi.xcertplay.airplay.AudioStreamId import com.shilapi.xcertplay.airplay.AudioFormat as CarPlayAudioFormat @@ -41,14 +42,25 @@ internal class AudioClock(private val rate: Int) { private var sample: Int? = null private var anchorUs = 0L private var elapsed = 0L + private var resets = 0L + private var reportedAt = 0L fun pts(sample: Int, arrivalUs: Long): Long { val previous = this.sample if (previous == null) { anchorUs = arrivalUs; elapsed = 0 } else elapsed += (sample - previous).toLong() this.sample = sample var pts = anchorUs + elapsed * 1_000_000L / rate - if (kotlin.math.abs(pts - arrivalUs) > 100_000) { + // Re-anchor only on a sustained drift. Network bursts make arrivalUs jump by >100 ms while + // the sample-derived PTS stays smooth, so the old 100 ms threshold re-anchored on jitter and + // stepped the PTS (measured: 26 jumps per 10 s, up to 355 ms each — audible dropouts). + if (kotlin.math.abs(pts - arrivalUs) > 500_000) { anchorUs = arrivalUs; elapsed = 0; pts = arrivalUs + resets++ + val now = System.currentTimeMillis() + if (now - reportedAt >= 1_000) { + reportedAt = now + Log.i("OXP-Audio", "clock_reanchor total=$resets") + } } return pts } diff --git a/android/app/src/main/java/org/openxplay/direlay/bridge/RelayAudioStream.kt b/android/app/src/main/java/org/openxplay/direlay/bridge/RelayAudioStream.kt index c9bdbbe4..0ebc20f9 100644 --- a/android/app/src/main/java/org/openxplay/direlay/bridge/RelayAudioStream.kt +++ b/android/app/src/main/java/org/openxplay/direlay/bridge/RelayAudioStream.kt @@ -34,6 +34,8 @@ internal class RelayAudioStream( private val media = AudioPolicy.role(id.audioType) == AudioRole.MEDIA private val worker = Thread({ run() }, "direlay-audio-${id.type}").apply { isDaemon = true } fun start() = worker.start() + /** False once the worker stopped: offer() drops packets, so callers must rebuild instead. */ + fun isRunning() = running.get() fun offer(rtp: ByteArray, sample: Int, arrivalUs: Long) { if (!running.get() || rtp.size <= 12) return val packet = Packet(rtp.copyOf(), sample, clock.pts(sample, arrivalUs)) @@ -88,7 +90,8 @@ internal class RelayAudioStream( } while (running.get()) { val packet = queue.poll(5, TimeUnit.MILLISECONDS) - if (!playLocally() && localStarted) { delegate.onAudioStopped(id); localStarted = false } + // Local playback only. The forwarding path below (output) and the stream's + // registration (StreamBridgeSink.onAudioStarted) are independent of this flag. if (packet != null && playLocally()) { if (!localStarted) { delegate.onAudioStarted(id, source, packet.sample); localStarted = true } delegate.onAudioRtp(id, source, packet.rtp, packet.sample) diff --git a/android/app/src/main/java/org/openxplay/direlay/bridge/StreamBridgeSink.kt b/android/app/src/main/java/org/openxplay/direlay/bridge/StreamBridgeSink.kt index 0072eb58..5ebdae86 100644 --- a/android/app/src/main/java/org/openxplay/direlay/bridge/StreamBridgeSink.kt +++ b/android/app/src/main/java/org/openxplay/direlay/bridge/StreamBridgeSink.kt @@ -43,38 +43,62 @@ class StreamBridgeSink( override fun onAudioStarted(id: AudioStreamId, format: CarPlayAudioFormat, firstSample: Int) { val stream = AudioPolicy.stream(id) ?: return - input.deliver(session) { sink -> - audio.remove(stream)?.second?.close() - if (session.audio.remove(stream)) sink.audioFormat(stream, null) - lateinit var run: RelayAudioStream - run = RelayAudioStream(id, format, { bytes, pts -> - input.deliver(session) { target -> - if (audio[stream]?.second === run) target.audioPacket(AudioPacket(stream, session.id, bytes, pts)) - } - }, { - input.deliver(session) { target -> - if (audio[stream]?.second === run) { - audio.remove(stream) - if (session.audio.remove(stream)) target.audioFormat(stream, null) - } + Log.i("OXP-Audio", "stream_start stream=$stream type=${id.type} codec=${format.codec} " + + "rate=${format.sampleRate} ch=${format.channels} firstSample=$firstSample") + input.deliver(session) { sink -> startAudioStream(id, stream, format, firstSample, sink) } + } + + /** + * Creates the forwarding stream. Called from onAudioStarted, and again from onAudioRtp when the + * map is empty: a reconnect builds a fresh StreamBridgeSink whose audio map starts empty, while + * DiPlay keeps the same audio stream and never re-fires onAudioStarted. Without the lazy path + * every packet after a reconnect was dropped silently (audio[stream] == null). + */ + private fun startAudioStream(id: AudioStreamId, stream: Int, format: CarPlayAudioFormat, + firstSample: Int, sink: InputSink) { + audio.remove(stream)?.second?.close() + if (session.audio.remove(stream)) sink.audioFormat(stream, null) + lateinit var run: RelayAudioStream + run = RelayAudioStream(id, format, { bytes, pts -> + input.deliver(session) { target -> + if (audio[stream]?.second === run) target.audioPacket(AudioPacket(stream, session.id, bytes, pts)) + } + }, { + input.deliver(session) { target -> + if (audio[stream]?.second === run) { + audio.remove(stream) + if (session.audio.remove(stream)) target.audioFormat(stream, null) } - }, delegate, playAudioLocally, firstSample, audioTails[stream]) - audioTails[stream] = run - audio[stream] = id to run - session.audio.add(stream) - sink.audioFormat(stream, AudioPolicy.format(id, format)) - run.start() - } + } + }, delegate, playAudioLocally, firstSample, audioTails[stream]) + audioTails[stream] = run + audio[stream] = id to run + session.audio.add(stream) + sink.audioFormat(stream, AudioPolicy.format(id, format)) + run.start() } override fun onAudioRtp(id: AudioStreamId, format: CarPlayAudioFormat, rtp: ByteArray, sample: Int) { val arrival = System.nanoTime() / 1000 val stream = AudioPolicy.stream(id) ?: return - input.deliver(session) { audio[stream]?.takeIf { it.first == id }?.second?.offer(rtp, sample, arrival) } + input.deliver(session) { sink -> + // A reconnect can leave a *closed* stream in the map: its ended-callback ran while the + // session had already moved on, so the entry was never removed. Checking only for null + // missed it and every packet was dropped by offer() (measured: 1026 packets lost + // between arrival and the queue). Rebuild whenever the stream is missing or stopped. + val existing = audio[stream]?.takeIf { it.first == id } + if (existing == null || !existing.second.isRunning()) { + Log.i("OXP-Audio", "stream_lazy_start stream=$stream type=${id.type} sample=$sample " + + "reason=${if (existing == null) "absent" else "stopped"}") + startAudioStream(id, stream, format, sample, sink) + } + audio[stream]?.takeIf { it.first == id }?.second?.offer(rtp, sample, arrival) + } } override fun onAudioStopped(id: AudioStreamId) { val stream = AudioPolicy.stream(id) ?: return + Log.i("OXP-Audio", "stream_stop stream=$stream type=${id.type}") input.deliver(session) { sink -> if (audio[stream]?.first == id) { audio.remove(stream)?.second?.close() From f512e6bc74371aa5be4d2136966e81de4504e136 Mon Sep 17 00:00:00 2001 From: iwalker <1043309958@qq.com> Date: Mon, 2 Nov 2026 22:39:55 +0800 Subject: [PATCH 02/17] Android: keep local-playback stop on flag flip, widen the audio re-anchor 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. --- .../org/openxplay/direlay/bridge/RelayAudioStream.kt | 3 +-- .../java/org/openxplay/direlay/bridge/AudioPolicyTest.kt | 9 ++++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/android/app/src/main/java/org/openxplay/direlay/bridge/RelayAudioStream.kt b/android/app/src/main/java/org/openxplay/direlay/bridge/RelayAudioStream.kt index 0ebc20f9..15ada4c2 100644 --- a/android/app/src/main/java/org/openxplay/direlay/bridge/RelayAudioStream.kt +++ b/android/app/src/main/java/org/openxplay/direlay/bridge/RelayAudioStream.kt @@ -90,8 +90,7 @@ internal class RelayAudioStream( } while (running.get()) { val packet = queue.poll(5, TimeUnit.MILLISECONDS) - // Local playback only. The forwarding path below (output) and the stream's - // registration (StreamBridgeSink.onAudioStarted) are independent of this flag. + if (!playLocally() && localStarted) { delegate.onAudioStopped(id); localStarted = false } if (packet != null && playLocally()) { if (!localStarted) { delegate.onAudioStarted(id, source, packet.sample); localStarted = true } delegate.onAudioRtp(id, source, packet.rtp, packet.sample) diff --git a/android/app/src/test/java/org/openxplay/direlay/bridge/AudioPolicyTest.kt b/android/app/src/test/java/org/openxplay/direlay/bridge/AudioPolicyTest.kt index 43f13d2d..4747b678 100644 --- a/android/app/src/test/java/org/openxplay/direlay/bridge/AudioPolicyTest.kt +++ b/android/app/src/test/java/org/openxplay/direlay/bridge/AudioPolicyTest.kt @@ -43,13 +43,16 @@ class AudioPolicyTest { assertArrayEquals(hex("12 34 fe dc 80 00 7f ff"), pcm) assertThrows(IllegalArgumentException::class.java) { AudioPolicy.swap(byteArrayOf(1)) } } - @Test fun timestampsAnchorAtArrivalAdvanceBySamplesAndReanchorOnlyBeyond100ms() { + @Test fun timestampsAnchorAtArrivalAdvanceBySamplesAndReanchorOnlyBeyond500ms() { val clock = AudioClock(48000) assertEquals(1_000_000L, clock.pts(900, 1_000_000)) assertEquals(1_020_000L, clock.pts(1860, 1_080_000)) assertEquals(1_040_000L, clock.pts(2820, 1_140_000)) - assertEquals(1_200_001L, clock.pts(3780, 1_200_001)) - assertEquals(1_220_001L, clock.pts(4740, 1_220_000)) + // 140 ms of arrival jitter is inside the 500 ms re-anchor window, so the sample-derived + // PTS keeps advancing instead of snapping to the arrival time. + assertEquals(1_060_000L, clock.pts(3780, 1_200_001)) + assertEquals(1_080_000L, clock.pts(4740, 1_220_000)) + // A first packet has no history: it anchors at its arrival time. assertEquals(2_000_000L, AudioClock(48000).pts(4740, 2_000_000)) val opus = AudioClock(24000) assertEquals(5_000_000L, opus.pts(0, 5_000_000)) From cdabde6882a39b31eed358da6f18803eb8ca4955 Mon Sep 17 00:00:00 2001 From: hellowalker Date: Tue, 3 Nov 2026 00:50:13 +0800 Subject: [PATCH 03/17] Android: reuse the Wi-Fi link the platform already joined 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. --- .../direlay/clink/AndroidClinkLink.kt | 148 ++++++++++++++++-- 1 file changed, 139 insertions(+), 9 deletions(-) diff --git a/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt index e027da79..a6d36224 100644 --- a/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt +++ b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt @@ -11,6 +11,7 @@ import android.net.* import android.net.wifi.WifiNetworkSpecifier import android.net.wifi.p2p.* import android.os.* +import android.util.Log import org.openxplay.stream.clink.* import org.openxplay.stream.clink.ble.* import org.openxplay.direlay.network.readWifiEnabled @@ -38,6 +39,14 @@ class AndroidClinkLink(context: Context, private val deviceId: String, private val reconnect = LinkReconnect() internal val retryBackoff = LinkBackoff() private val scanStartBudget = BleScanStartBudget() + /** WifiNetworkSpecifier request window; the platform gives up on its own after this. */ + private const val REQUEST_TIMEOUT_MS = 12_000L + /** Never hand the request less than this, even if priming ate most of the stage budget. */ + private const val MIN_REQUEST_TIMEOUT_MS = 5_000L + /** How often a link the platform brought up on its own is checked for adoption. */ + private const val ADOPT_POLL_MS = 100L + /** How long a freshly started scan is given to deliver results before the request goes out. */ + private const val PRIME_BUDGET_MS = 3_000L } private val peerStore = object : BlePeerPolicy.Store, BlePeerPolicy.SubscriptionStore { private val preferences = this@AndroidClinkLink.context.getSharedPreferences("clinkPeers", Context.MODE_PRIVATE) @@ -102,6 +111,8 @@ class AndroidClinkLink(context: Context, private val deviceId: String, var expectedSsid: String? = null var receiver: BroadcastReceiver? = null var networkCallback: ConnectivityManager.NetworkCallback? = null + var linkWatcher: Runnable? = null + var adoptedCallback: ConnectivityManager.NetworkCallback? = null var monitor: Runnable? = null var bound: Network? = null var previousBinding: Network? = null @@ -597,7 +608,17 @@ class AndroidClinkLink(context: Context, private val deviceId: String, return await(run, result, 7) } private fun joinSpecifier(run: Run, reply: HeadUnitReply): Pair { + // The car network is a saved network, so the platform joins it on its own as soon as the AP + // shows up — around the moment this stage starts. A WifiNetworkSpecifier request issued into + // that window never attaches: the link completes under the system's uid, the request matches + // nothing, and it expires unfulfilled after 12 s. That is the measured "first attempt after + // getting in the car always fails, the retry succeeds", so adopt the platform's link whenever + // it exists and keep watching for it while the request is pending. + adoptHeadUnitLink(run, reply.ssid)?.let { return it } + // A fresh scan is what makes the platform start its own join, so ask for one before asking + // for a network of our own — then look again in case it already built the link. primeScanCache(run, reply.ssid) + adoptHeadUnitLink(run, reply.ssid)?.let { return it } val result = CompletableFuture>() main { check(!run.cancelled) @@ -624,13 +645,7 @@ class AndroidClinkLink(context: Context, private val deviceId: String, if (expected != null && endpoints != expected) { lost(run); return } if (endpoints == null) return if (!result.isDone) { - if (!isolateNetwork) { - run.previousBinding = manager.boundNetworkForProcess - if (!manager.bindProcessToNetwork(network)) { - result.completeExceptionally(ClinkFailure(ClinkFailureReason.WIFI_BIND)); return - } - run.bound = network - } + bindNetwork(manager, network, run) run.selectedNetwork = network expected = endpoints result.complete(endpoints) @@ -648,9 +663,120 @@ class AndroidClinkLink(context: Context, private val deviceId: String, val specifier = WifiNetworkSpecifier.Builder().setSsid(reply.ssid).setWpa2Passphrase(reply.psk).build() val request = NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).setNetworkSpecifier(specifier).build() - manager.requestNetwork(request, callback, handler, 12000) + manager.requestNetwork(request, callback, handler, + REQUEST_TIMEOUT_MS.toInt()) + // The system's own join of this saved AP is invisible to the request, so adopt it the + // moment it gets an IPv4 lease instead of waiting out the request timeout. + val watcher = object : Runnable { + override fun run() { + if (result.isDone || run.cancelled) return + val endpoints = runCatching { adoptHeadUnitLink(run, reply.ssid) }.getOrNull() + if (endpoints != null) { + Log.i("DiRelayCarlink", "join_adopted local=${endpoints.second} peer=${endpoints.first}") + runCatching { manager.unregisterNetworkCallback(callback) } + result.complete(endpoints) + return + } + handler.postDelayed(this, ADOPT_POLL_MS) + } + } + run.linkWatcher = watcher + handler.postDelayed(watcher, ADOPT_POLL_MS) + } + try { + return await(run, result, 15) + } finally { + main { run.linkWatcher?.let { handler.removeCallbacks(it) }; run.linkWatcher = null } } - return await(run, result, 13) + } + + /** + * Take over a Wi-Fi link the platform already brought up for the head unit's SSID. The relay only + * needs the gateway address on that L2, so reusing the link is equivalent to owning a request on + * it — and it is the only way to reach a connection the system created for itself. + */ + private fun adoptHeadUnitLink(run: Run, ssid: String): Pair? { + val manager = connectivity ?: return null + val network = headUnitNetwork(manager, ssid) ?: return null + val endpoints = endpointsOf(manager, network) ?: return null + bindNetwork(manager, network, run) + run.selectedNetwork = network + return endpoints + } + + private fun bindNetwork(manager: ConnectivityManager, network: Network, run: Run) { + if (isolateNetwork || run.bound === network) return + run.previousBinding = manager.boundNetworkForProcess + if (!manager.bindProcessToNetwork(network)) throw ClinkFailure(ClinkFailureReason.WIFI_BIND) + run.bound = network + watchAdoptedLink(manager, network, run) + } + + /** + * A link we adopted carries no request callback, so nothing would report its loss: the session + * would sit there until TCP noticed. Listen for that network disappearing and report it exactly + * as the request path does. + */ + private fun watchAdoptedLink(manager: ConnectivityManager, network: Network, run: Run) { + if (run.adoptedCallback != null) return + val callback = object : ConnectivityManager.NetworkCallback() { + override fun onLost(gone: Network) { + if (gone != network) return + run.adoptedCallback?.let { runCatching { manager.unregisterNetworkCallback(it) } } + run.adoptedCallback = null + run.bound = null + lost(run) + } + } + val request = NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build() + runCatching { manager.registerNetworkCallback(request, callback) } + .onSuccess { run.adoptedCallback = callback } + } + + /** + * The Wi-Fi network that currently carries [ssid] with an IPv4 lease, if any. + * + * Stock Android answers this through the default network's transport info. MIUI 10 attaches no + * transport info to these agents, so fall back to WifiManager for the SSID and match the lease by + * address — that keeps the choice correct on devices running two concurrent STA links. + */ + @Suppress("DEPRECATION") + private fun headUnitNetwork(manager: ConnectivityManager, ssid: String): Network? { + fun wifiWithIpv4(network: Network): Boolean = + manager.getNetworkCapabilities(network)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true && + manager.getLinkProperties(network)?.linkAddresses?.any { it.address is Inet4Address } == true + + manager.activeNetwork?.takeIf(::wifiWithIpv4)?.let { active -> + val activeInfo = manager.getNetworkCapabilities(active)?.transportInfo as? android.net.wifi.WifiInfo + if (activeInfo?.ssid?.trim('"') == ssid) return active + } + val wifi = context.getSystemService(android.net.wifi.WifiManager::class.java) ?: return null + val info = runCatching { wifi.connectionInfo }.getOrNull() ?: return null + if (info.ssid?.trim('"') != ssid) return null + val currentIp = info.ipAddress.takeIf { it != 0 }?.let { address -> + (0..3).joinToString(".") { ((address ushr (it * 8)) and 255).toString() } + } + return manager.allNetworks.firstOrNull { network -> + wifiWithIpv4(network) && (currentIp == null || + manager.getLinkProperties(network)?.linkAddresses + ?.any { it.address.hostAddress == currentIp } == true) + } + } + + private fun endpointsOf(manager: ConnectivityManager, network: Network): Pair? { + val properties = manager.getLinkProperties(network) ?: return null + val local = properties.linkAddresses.firstOrNull { it.address is Inet4Address }?.address?.hostAddress + val peer = (properties.routes.firstOrNull { it.isDefaultRoute && it.gateway is Inet4Address }?.gateway + as? Inet4Address)?.hostAddress ?: dhcpServer() + return WifiJoinPolicy.endpoints(peer, local) + } + + /** API 29 has no LinkProperties.dhcpServerAddress; the lease carries the same gateway. */ + @Suppress("DEPRECATION") + private fun dhcpServer(): String? { + val lease = context.getSystemService(android.net.wifi.WifiManager::class.java)?.dhcpInfo ?: return null + if (lease.serverAddress == 0) return null + return (0..3).joinToString(".") { ((lease.serverAddress ushr (it * 8)) and 255).toString() } } /** @@ -661,6 +787,8 @@ class AndroidClinkLink(context: Context, private val deviceId: String, * * Gated to the combination observed failing: other vendors match silently on their own, and * HyperOS ships Android 14+, where the framework handles the match itself. + * + * Returns how long the wait took, so the caller can keep the whole stage inside its budget. */ @Suppress("DEPRECATION") private fun primeScanCache(run: Run, ssid: String) { @@ -723,6 +851,8 @@ class AndroidClinkLink(context: Context, private val deviceId: String, } } private fun releaseNetwork(run: Run) { + run.adoptedCallback?.let { runCatching { connectivity?.unregisterNetworkCallback(it) } } + run.adoptedCallback = null run.networkCallback?.let { // unregisterNetworkCallback releases the request synchronously. Android does not send // onLost for an unregistered callback, so waiting for it would stall every reconnect. From a34c975c713028e3eb3c8bbfce4519896b73a3ca Mon Sep 17 00:00:00 2001 From: hellowalker Date: Tue, 3 Nov 2026 00:52:27 +0800 Subject: [PATCH 04/17] Android: prime the scan cache once, and skip the request when MIUI can match MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .../direlay/clink/AndroidClinkLink.kt | 82 ++++++++++++++----- 1 file changed, 60 insertions(+), 22 deletions(-) diff --git a/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt index a6d36224..9b3ae44b 100644 --- a/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt +++ b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt @@ -43,6 +43,8 @@ class AndroidClinkLink(context: Context, private val deviceId: String, private const val REQUEST_TIMEOUT_MS = 12_000L /** Never hand the request less than this, even if priming ate most of the stage budget. */ private const val MIN_REQUEST_TIMEOUT_MS = 5_000L + /** Quiet window granted to the platform's own join before asking for a network. */ + private const val QUIET_JOIN_MS = 2_500L /** How often a link the platform brought up on its own is checked for adoption. */ private const val ADOPT_POLL_MS = 100L /** How long a freshly started scan is given to deliver results before the request goes out. */ @@ -128,6 +130,14 @@ class AndroidClinkLink(context: Context, private val deviceId: String, * dialog. One priming per throttle window keeps the remaining requests for the dialog. */ @Volatile private var lastPrimeAt = 0L + /** Whether the last priming actually saw the head unit's SSID in the scan results. */ + @Volatile private var lastPrimeSawTarget = false + /** + * The confirmation dialog, and the scan-cache workaround for it, are MIUI/Android 10-11 specific. + * Everything else here is generic AOSP behaviour and must not be slowed down for other vendors. + */ + private val miuiRequestsNeedCache = Build.MANUFACTURER.equals("Xiaomi", ignoreCase = true) && + Build.VERSION.SDK_INT <= 30 internal fun redactFailureMessage(text: String): String = failurePassphrase.let { if (it.isEmpty()) text else text.replace(it, "[redacted]") } @@ -615,10 +625,27 @@ class AndroidClinkLink(context: Context, private val deviceId: String, // getting in the car always fails, the retry succeeds", so adopt the platform's link whenever // it exists and keep watching for it while the request is pending. adoptHeadUnitLink(run, reply.ssid)?.let { return it } - // A fresh scan is what makes the platform start its own join, so ask for one before asking - // for a network of our own — then look again in case it already built the link. - primeScanCache(run, reply.ssid) + // Let the platform see the AP first: a scan result is what makes it start its own join — and + // what makes MIUI match the request silently when there is nothing to adopt. + val primed = primeScanCache(run, reply.ssid) adoptHeadUnitLink(run, reply.ssid)?.let { return it } + // When the scan did show the AP the platform joins it within a second. Adopting that link is + // both faster and silent: requestNetwork is what raises MIUI's unanswerable dialog, so give + // the platform a quiet window before asking for a network of our own. + var quiet = 0L + if (lastPrimeSawTarget && miuiRequestsNeedCache) { + val started = SystemClock.elapsedRealtime() + while (!run.cancelled) { + adoptHeadUnitLink(run, reply.ssid)?.let { + Log.i("DiRelayCarlink", "join_adopted waited=${SystemClock.elapsedRealtime() - started}ms") + return it + } + if (SystemClock.elapsedRealtime() - started >= QUIET_JOIN_MS) break + try { Thread.sleep(100) } catch (_: InterruptedException) { break } + } + quiet = SystemClock.elapsedRealtime() - started + } + val consumed = primed + quiet val result = CompletableFuture>() main { check(!run.cancelled) @@ -664,7 +691,7 @@ class AndroidClinkLink(context: Context, private val deviceId: String, val request = NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).setNetworkSpecifier(specifier).build() manager.requestNetwork(request, callback, handler, - REQUEST_TIMEOUT_MS.toInt()) + (REQUEST_TIMEOUT_MS - consumed).coerceAtLeast(MIN_REQUEST_TIMEOUT_MS).toInt()) // The system's own join of this saved AP is invisible to the request, so adopt it the // moment it gets an IPv4 lease instead of waiting out the request timeout. val watcher = object : Runnable { @@ -791,28 +818,39 @@ class AndroidClinkLink(context: Context, private val deviceId: String, * Returns how long the wait took, so the caller can keep the whole stage inside its budget. */ @Suppress("DEPRECATION") - private fun primeScanCache(run: Run, ssid: String) { - if (!Build.MANUFACTURER.equals("Xiaomi", ignoreCase = true) || Build.VERSION.SDK_INT > 30) return + private fun primeScanCache(run: Run, ssid: String): Long { + if (!miuiRequestsNeedCache) return 0 // One priming per throttle window: the relay retries with a fresh connect() each attempt, so - // priming on every attempt would spend the whole shared scan budget and leave the system - // dialog with nothing to list. + // priming on every attempt would spend the whole shared scan budget. val now = SystemClock.elapsedRealtime() - if (now - lastPrimeAt < 120_000) return + if (now - lastPrimeAt < 120_000) return 0 lastPrimeAt = now - val wifi = context.getSystemService(android.net.wifi.WifiManager::class.java) ?: return - if (!wifi.isWifiEnabled) return - val deadline = System.currentTimeMillis() + 2_500 - while (!run.cancelled) { - // A null list means the location permission is missing; waiting would only add delay. - val results = wifi.scanResults ?: return - if (results.any { it.SSID == ssid }) return - // A refused startScan means the scan throttle is exhausted: retrying cannot succeed and - // only burns the budget of the next attempt. Stop here and let the framework dialog (or - // the next attempt) take over. - if (!wifi.startScan()) return - if (System.currentTimeMillis() >= deadline) return - try { Thread.sleep(350) } catch (_: InterruptedException) { return } + val wifi = context.getSystemService(android.net.wifi.WifiManager::class.java) ?: return 0 + if (!wifi.isWifiEnabled) return 0 + // A null list means the location permission is missing; waiting would only add delay. + lastPrimeSawTarget = false + val cached = wifi.scanResults ?: return 0 + if (cached.any { it.SSID == ssid }) { + lastPrimeSawTarget = true + Log.i("DiRelayCarlink", "scan_primed hit=cached waited=0") + return 0 + } + // Exactly one scan, then wait for *its* results. Asking again before those arrive is coalesced + // or refused by the platform, and a refused re-scan says nothing about the scan already in + // flight: treating it as failure is what left the cache cold and forced the dialog above. + // Spending one scan instead of four also keeps the next attempt's budget intact. + val started = SystemClock.elapsedRealtime() + val issued = wifi.startScan() + var hit = false + while (issued && !run.cancelled) { + if (SystemClock.elapsedRealtime() - started >= PRIME_BUDGET_MS) break + val results = wifi.scanResults ?: break + if (results.any { it.SSID == ssid }) { hit = true; lastPrimeSawTarget = true; break } + try { Thread.sleep(100) } catch (_: InterruptedException) { break } } + val waited = SystemClock.elapsedRealtime() - started + Log.i("DiRelayCarlink", "scan_primed hit=$hit issued=$issued waited=${waited}ms") + return waited } private fun lost(run: Run, radioOff: Boolean = false) { if (run.cancelled) return From 143a517db5635775f2e4f29d7d7709b92704fd8d Mon Sep 17 00:00:00 2001 From: hellowalker Date: Tue, 3 Nov 2026 06:35:06 +0800 Subject: [PATCH 05/17] Android: forward Carlink steering-wheel media keys to CarPlay 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. --- .../openxplay/direlay/bridge/DiPlayInput.kt | 27 +++++++++++++++++-- .../openxplay/direlay/relay/RelayRuntime.kt | 3 +++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/android/app/src/main/java/org/openxplay/direlay/bridge/DiPlayInput.kt b/android/app/src/main/java/org/openxplay/direlay/bridge/DiPlayInput.kt index b18bfb80..706761ed 100644 --- a/android/app/src/main/java/org/openxplay/direlay/bridge/DiPlayInput.kt +++ b/android/app/src/main/java/org/openxplay/direlay/bridge/DiPlayInput.kt @@ -6,6 +6,7 @@ package org.openxplay.direlay.bridge import android.util.Log import kotlinx.coroutines.flow.asStateFlow import com.shilapi.xcertplay.airplay.AirPlayContact +import com.shilapi.xcertplay.airplay.CarPlayMediaButton import com.shilapi.xcertplay.airplay.SessionControl import org.openxplay.stream.core.* import java.util.concurrent.RejectedExecutionException @@ -18,10 +19,11 @@ import java.util.concurrent.TimeUnit class DiPlayInput(private val applyFrameRate: (Double) -> Unit = {}, private val restartCarPlay: () -> Unit = {}, private val automaticHevc: () -> Boolean = { false }, private val nowMs: () -> Long = { System.nanoTime() / 1_000_000 }, private val remotePlaybackProof: () -> Boolean = { false }, - private val startupStatus: () -> Boolean = { false }) : ProjectionInput, AutoCloseable { + private val startupStatus: () -> Boolean = { false }, + private val mediaKeysForwarding: () -> Boolean = { false }) : ProjectionInput, AutoCloseable { @Volatile override var capabilities = InputCapabilities( setOf(VideoCodec.H264, VideoCodec.H265), setOf(ScreenId.MAIN), - touch = true, keys = emptySet(), microphone = false, + touch = true, keys = KeyCode.entries.toSet(), microphone = false, keyFrameRequests = true, reconfigure = ReconfigureCost.RESTART_SESSION, ) private set @@ -264,6 +266,27 @@ class DiPlayInput(private val applyFrameRate: (Double) -> Unit = {}, private val ) } } + is ControlEvent.Key -> { + // Steering-wheel media keys arrive as down/up pairs; trigger once on down so a + // single press does not skip two tracks. Forwarding follows the audio route: the + // caller enables it only when CarPlay carries the audio, because when the phone + // keeps car Bluetooth audio it already receives the keys over AVRCP and forwarding + // here would skip tracks twice. + if (!event.down) return false + if (!mediaKeysForwarding()) return false + val index = when (event.code) { + KeyCode.NEXT -> CarPlayMediaButton.NEXT + KeyCode.PREVIOUS -> CarPlayMediaButton.PREVIOUS + KeyCode.PLAY_PAUSE -> CarPlayMediaButton.PLAY_PAUSE + else -> return false + } + synchronized(gate) { + if (current !== session || sink == null) false + else session.control.sendMediaButton(index) + }.also { sent -> + Log.i(TAG, "media key code=${event.code.name} index=$index sent=$sent") + } + } is ControlEvent.KeyFrameRequest -> { val accepted = synchronized(gate) { if (sink == null || current !== session || event.screen !in session.handlers) false diff --git a/android/app/src/main/java/org/openxplay/direlay/relay/RelayRuntime.kt b/android/app/src/main/java/org/openxplay/direlay/relay/RelayRuntime.kt index f13b4e01..8cb7086f 100644 --- a/android/app/src/main/java/org/openxplay/direlay/relay/RelayRuntime.kt +++ b/android/app/src/main/java/org/openxplay/direlay/relay/RelayRuntime.kt @@ -127,6 +127,9 @@ class RelayRuntime(private val context: Context, remotePlaybackProof = { settingsStore.snapshot.value?.experimental?.effective()?.remotePlaybackProof == true }, startupStatus = { settingsStore.snapshot.value?.experimental?.effective()?.startupStatus == true }, automaticHevc = { settingsStore.snapshot.value?.videoCodec == VideoCodecSetting.AUTO && appliedVideoDecision.codec == VideoCodec.H265 }, + // Media keys follow the audio route: CarPlay audio → forward Carlink method=12 to the iPhone; + // car Bluetooth audio → the phone already gets them over AVRCP, so do not double-forward. + mediaKeysForwarding = { settingsStore.snapshot.value?.carBluetoothAudio == false }, ) private val bundledPlugins = org.openxplay.direlay.plugins.BundledPlugins(context.applicationContext) fun installedPlugins() = runCatching { From 9d8c6f078f33d772cc54d1140cc7127763079979 Mon Sep 17 00:00:00 2001 From: hellowalker Date: Tue, 3 Nov 2026 08:59:35 +0800 Subject: [PATCH 06/17] Android: assert the advertised KeyCode set, not an empty one 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. --- .../test/java/org/openxplay/direlay/bridge/DiPlayInputTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/app/src/test/java/org/openxplay/direlay/bridge/DiPlayInputTest.kt b/android/app/src/test/java/org/openxplay/direlay/bridge/DiPlayInputTest.kt index 1789de6b..2a4bb909 100644 --- a/android/app/src/test/java/org/openxplay/direlay/bridge/DiPlayInputTest.kt +++ b/android/app/src/test/java/org/openxplay/direlay/bridge/DiPlayInputTest.kt @@ -245,7 +245,7 @@ class DiPlayInputTest { assertEquals(setOf(ScreenId.MAIN), input.capabilities.screens) assertTrue(input.capabilities.touch) assertTrue(input.capabilities.keyFrameRequests) - assertTrue(input.capabilities.keys.isEmpty()) + assertEquals(KeyCode.entries.toSet(), input.capabilities.keys) assertFalse(input.capabilities.microphone) assertEquals(ReconfigureCost.RESTART_SESSION, input.capabilities.reconfigure) assertEquals(ReconfigureResult.RESTART_SESSION, input.reconfigure(configuration)) From 3f89630c011a5e17408795f09d7bf730e31da3e2 Mon Sep 17 00:00:00 2001 From: hellowalker Date: Tue, 3 Nov 2026 14:37:58 +0800 Subject: [PATCH 07/17] Android: keep the stored subscription choice when the GATT link fails MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .../org/openxplay/direlay/clink/AndroidClinkLink.kt | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt index e027da79..37a90355 100644 --- a/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt +++ b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt @@ -38,6 +38,14 @@ class AndroidClinkLink(context: Context, private val deviceId: String, private val reconnect = LinkReconnect() internal val retryBackoff = LinkBackoff() private val scanStartBudget = BleScanStartBudget() + /** + * Failures that happen before the subscription is ever exercised. They carry no signal about + * whether the head unit wants CCCD or a local subscription, so they must not clear that choice. + */ + private val CONNECT_SIDE_FAILURES = setOf(ClinkFailureReason.GATT_CONNECT, + ClinkFailureReason.GATT_SERVICES, ClinkFailureReason.BLE_SCAN, + ClinkFailureReason.BLE_TIMEOUT, ClinkFailureReason.BLE_DISCOVERY, + ClinkFailureReason.BLE_SERVICE_MISSING) } private val peerStore = object : BlePeerPolicy.Store, BlePeerPolicy.SubscriptionStore { private val preferences = this@AndroidClinkLink.context.getSharedPreferences("clinkPeers", Context.MODE_PRIVATE) @@ -282,7 +290,9 @@ class AndroidClinkLink(context: Context, private val deviceId: String, try { return exchange(run, device, key, choice) } catch (failure: Exception) { - if (!run.cancelled) peers.exchangeFailed(key) + // A failure that never reached the subscription says nothing about which subscription works. + // Forgetting the persisted choice there makes every later connection pay the CCCD timeout again. + if (!run.cancelled && (failure as? ClinkFailure)?.reason !in CONNECT_SIDE_FAILURES) peers.exchangeFailed(key) throw failure } } From b0621836e56b72d5d04dffdf52b579d0c6b72331 Mon Sep 17 00:00:00 2001 From: hellowalker Date: Tue, 3 Nov 2026 14:40:31 +0800 Subject: [PATCH 08/17] Android: report what the Carlink link is doing while it looks stuck MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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). --- .../direlay/clink/AndroidClinkLink.kt | 94 ++++++++++++++++++- .../openxplay/direlay/clink/BlePeerPolicy.kt | 23 ++++- .../openxplay/direlay/logs/NetworkTimeline.kt | 70 ++++++++++++-- 3 files changed, 174 insertions(+), 13 deletions(-) diff --git a/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt index e027da79..f7997527 100644 --- a/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt +++ b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt @@ -11,6 +11,7 @@ import android.net.* import android.net.wifi.WifiNetworkSpecifier import android.net.wifi.p2p.* import android.os.* +import android.util.Log import org.openxplay.stream.clink.* import org.openxplay.stream.clink.ble.* import org.openxplay.direlay.network.readWifiEnabled @@ -20,6 +21,7 @@ import java.net.NetworkInterface import java.util.UUID import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger /** Blocking lifecycle API; Android callbacks and owned resource cleanup run on the main handler. */ @SuppressLint("MissingPermission") @@ -38,6 +40,11 @@ class AndroidClinkLink(context: Context, private val deviceId: String, private val reconnect = LinkReconnect() internal val retryBackoff = LinkBackoff() private val scanStartBudget = BleScanStartBudget() + /** + * How often a running scan reports how much it has heard. A scan that finds nothing produces no + * log lines at all, which is why "no progress" and "no such device" looked the same in the field. + */ + private const val SCAN_PROGRESS_MS = 10_000L } private val peerStore = object : BlePeerPolicy.Store, BlePeerPolicy.SubscriptionStore { private val preferences = this@AndroidClinkLink.context.getSharedPreferences("clinkPeers", Context.MODE_PRIVATE) @@ -53,7 +60,9 @@ class AndroidClinkLink(context: Context, private val deviceId: String, if (!preferences.edit().remove("$key.legacy").commit()) cleanupFailure(IllegalStateException("peer_store_failed")) } } - private val peers = BlePeerPolicy(peerStore, if (experimental.rememberSubscription) peerStore else null) + private val peers = BlePeerPolicy(peerStore, if (experimental.rememberSubscription) peerStore else null) { message -> + Log.i("DiRelayCarlink", message) + } private val scanPolicy = BleScanPolicy.forAttempt(experimental.keepScanning) private val phoneAddress: () -> String = if (experimental.sendBluetoothAddress) ({ experimental.bluetoothAddress }) else ::phoneMac private val experimentNames = experimental.names() @@ -89,6 +98,8 @@ class AndroidClinkLink(context: Context, private val deviceId: String, var scan: ScanCallback? = null var scanner: BluetoothLeScanner? = null var scanRenewal: Runnable? = null + var scanCounter: ScanCallback? = null + var scanProgress: Runnable? = null var rawScan: ScanCallback? = null var rawCapture: BleRawCapture? = null var gatt: BluetoothGatt? = null @@ -155,6 +166,9 @@ class AndroidClinkLink(context: Context, private val deviceId: String, diagnostics.handoff(reply.ssid, reply.psk.length) // No PIN/UI pause here; return immediately after DHCP so clink can start AUTH. val endpoints = diagnosed(ClinkStage.WIFI_JOIN, ClinkFailureReason.WIFI_TIMEOUT) { join(run, reply) } + logLinkReady(run, "join") + // A second sample: if the route was missing at join time, this shows when it arrived. + handler.postDelayed({ logLinkReady(run, "join+2s") }, 2_000) diagnostics.emit(ClinkDiagnostic.Joined(endpoints.first, endpoints.second)) main { check(!run.cancelled) { "Link cancelled" } @@ -193,17 +207,27 @@ class AndroidClinkLink(context: Context, private val deviceId: String, } private fun scan(run: Run): Pair { val result = CompletableFuture>() + // Counters behind ble_scan_progress. Without them a scan that heard nothing at all is + // indistinguishable from a scanner whose results never arrive: raw counts every advertisement + // the radio delivered, matched every result that passed the service filter, peer the ones that + // decoded as ours. raw stays -1 when the counting scan could not be started. + val rawSeen = AtomicInteger(-1) + val matched = AtomicInteger() + val peer = AtomicInteger() + val startedAt = SystemClock.elapsedRealtime() main { check(!run.cancelled) val scanner = bluetooth?.adapter?.bluetoothLeScanner ?: throw ClinkFailure(ClinkFailureReason.BLE_UNAVAILABLE) val callback = object : ScanCallback() { override fun onScanResult(type: Int, scan: ScanResult) { if (run.cancelled || result.isDone) return + matched.incrementAndGet() val record = scan.scanRecord ?: return try { val identity = record.getServiceData(ParcelUuid(UUID.fromString(BleCodec.IDENTITY_SERVICE))) ?: return val name = record.getServiceData(ParcelUuid(UUID.fromString(BleCodec.NAME_SERVICE))) ?: byteArrayOf() val advertisement = BleCodec.advertisement(identity, name) + peer.incrementAndGet() advertisements?.selected(advertisement) diagnostics.traceLink("ble_advertisement", mapOf( "major" to advertisement.major.toString(), "minor" to advertisement.minor.toString(), @@ -216,6 +240,7 @@ class AndroidClinkLink(context: Context, private val deviceId: String, } catch (_: IllegalArgumentException) { /* Ignore malformed advertisements. */ } } override fun onScanFailed(errorCode: Int) { + Log.w("DiRelayCarlink", "ble_scan_failed code=$errorCode elapsed=${(SystemClock.elapsedRealtime() - startedAt) / 1000}s") result.completeExceptionally(ClinkFailure(ClinkFailureReason.BLE_SCAN)) } } @@ -225,6 +250,39 @@ class AndroidClinkLink(context: Context, private val deviceId: String, val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build() if (advertisements != null) scanStartBudget.recordStart(SystemClock.elapsedRealtime()) scanner.startScan(filters, settings, callback) + // One unfiltered scan whose only job is counting. The filtered callback never sees a device + // that does not advertise our service UUID, so on its own it cannot answer the question that + // matters when nothing is found: is the radio hearing anything at all, or is the scanner dead? + if (advertisements == null) { + val now = SystemClock.elapsedRealtime() + if (scanStartBudget.tryStart(now, reserve = 2)) { + val counter = object : ScanCallback() { + override fun onScanResult(type: Int, scan: ScanResult) { rawSeen.incrementAndGet() } + override fun onBatchScanResults(results: MutableList) { rawSeen.addAndGet(results.size) } + override fun onScanFailed(errorCode: Int) { + Log.w("DiRelayCarlink", "ble_scan_counter_failed code=$errorCode") + rawSeen.set(-1); run.scanCounter = null + } + } + run.scanCounter = counter + runCatching { scanner.startScan(emptyList(), settings, counter) } + .onFailure { rawSeen.set(-1); run.scanCounter = null } + } else { + diagnostics.traceLink("ble_scan_counter_skipped", mapOf( + "reason" to "scan_budget", "count" to scanStartBudget.count(now).toString())) + } + } + val progress = object : Runnable { + override fun run() { + if (run.cancelled || result.isDone) return + Log.i("DiRelayCarlink", "ble_scan_progress elapsed=${(SystemClock.elapsedRealtime() - startedAt) / 1000}s" + + " raw=${if (rawSeen.get() >= 0) rawSeen.get().toString() else if (advertisements != null) "capture" else "off"}" + + " matched=${matched.get()} peer=${peer.get()}") + handler.postDelayed(this, SCAN_PROGRESS_MS) + } + } + run.scanProgress = progress + handler.postDelayed(progress, SCAN_PROGRESS_MS) fun startRawScan(raw: ScanCallback) { val now = SystemClock.elapsedRealtime() if (scanStartBudget.tryStart(now, reserve = 2)) { @@ -274,7 +332,20 @@ class AndroidClinkLink(context: Context, private val deviceId: String, diagnostics.emit(ClinkStage.BLE_SCAN) } try { return await(run, result, scanPolicy.timeoutSeconds) } - finally { main { stopScan(run) } } + finally { + main { + stopScan(run) + val outcome = when { + run.cancelled -> "cancelled" + result.isDone && !result.isCompletedExceptionally -> "found" + result.isDone -> "failed" + else -> "timeout" + } + Log.i("DiRelayCarlink", "ble_scan_end elapsed=${(SystemClock.elapsedRealtime() - startedAt) / 1000}s" + + " raw=${if (rawSeen.get() >= 0) rawSeen.get().toString() else if (advertisements != null) "capture" else "off"}" + + " matched=${matched.get()} peer=${peer.get()} outcome=$outcome") + } + } } private fun exchange(run: Run, device: BluetoothDevice, carId: String): HeadUnitReply { val key = peers.key(carId, device.address) @@ -686,6 +757,21 @@ class AndroidClinkLink(context: Context, private val deviceId: String, try { Thread.sleep(350) } catch (_: InterruptedException) { return } } } + private fun logLinkReady(run: Run, stage: String) { + val manager = connectivity ?: return + runCatching { + val network = run.selectedNetwork + val properties = network?.let { manager.getLinkProperties(it) } + val routes = properties?.routes?.joinToString(",") { + it.destination.toString().substringBefore("/") + if (it.isDefaultRoute) "*" else "" + } ?: "-" + val addresses = properties?.linkAddresses?.joinToString(",") { it.address.hostAddress ?: "-" } ?: "-" + val dns = properties?.dnsServers?.joinToString(",") { it.hostAddress ?: "-" } ?: "-" + Log.i("DiRelayCarlink", "link_ready stage=$stage iface=${properties?.interfaceName ?: "-"} " + + "addrs=$addresses defaultRoute=${properties?.routes?.any { it.isDefaultRoute } ?: false} " + + "routes=$routes dns=$dns processBound=${manager.boundNetworkForProcess != null}") + }.onFailure { Log.w("DiRelayCarlink", "link_ready stage=$stage failed=${it.javaClass.simpleName}") } + } private fun lost(run: Run, radioOff: Boolean = false) { if (run.cancelled) return val failure = ClinkFailure(ClinkFailureReason.LINK_LOST) @@ -782,6 +868,10 @@ class AndroidClinkLink(context: Context, private val deviceId: String, } private fun stopScan(run: Run) { run.scanRenewal?.let(handler::removeCallbacks); run.scanRenewal = null + run.scanProgress?.let(handler::removeCallbacks); run.scanProgress = null + val counter = run.scanCounter + run.scanCounter = null + counter?.let { callback -> runCatching { run.scanner?.stopScan(callback) }.onFailure(::cleanupFailure) } val raw = run.rawScan run.rawScan = null raw?.let { callback -> runCatching { run.scanner?.stopScan(callback) }.onFailure(::cleanupFailure) } diff --git a/android/app/src/main/java/org/openxplay/direlay/clink/BlePeerPolicy.kt b/android/app/src/main/java/org/openxplay/direlay/clink/BlePeerPolicy.kt index b8aa12cc..25469a16 100644 --- a/android/app/src/main/java/org/openxplay/direlay/clink/BlePeerPolicy.kt +++ b/android/app/src/main/java/org/openxplay/direlay/clink/BlePeerPolicy.kt @@ -7,7 +7,12 @@ package org.openxplay.direlay.clink internal class BlePeerPolicy(private val store: Store = object : Store { override fun read(key: String): Int? = null override fun write(key: String, type: Int) {} -}, private val subscriptions: SubscriptionStore? = null) { +}, private val subscriptions: SubscriptionStore? = null, + /** + * Persistence trace for post-hoc analysis of each connection. Injected instead of calling + * android.util.Log so the JVM unit tests stay pure and can assert on the same lines. + */ + private val log: (String) -> Unit = {}) { interface Store { fun read(key: String): Int? fun write(key: String, type: Int) @@ -24,30 +29,44 @@ internal class BlePeerPolicy(private val store: Store = object : Store { java.security.MessageDigest.getInstance("SHA-256") .digest((if (carId.isNotBlank()) "car:$carId" else "address:$address").toByteArray(Charsets.UTF_8)) .joinToString("") { "%02x".format(it.toInt() and 255) } + /** Short key keeps one connection's lines greppable; the full hash is the storage key. */ + private fun trace(key: String, message: String) = log("peer_$message key=${key.take(8)}") @Synchronized fun choice(key: String): Choice { peers[key]?.let { return it } val type = store.read(key)?.takeIf { it == 1001 || it == 1002 } ?: 1002 val legacy = subscriptions?.readLegacy(key) == true if (legacy) persistedLegacy.add(key) + trace(key, "choice legacy=$legacy type=$type source=${if (legacy) "persisted" else "default"}") return Choice(type, legacy) } @Synchronized fun cccdTimedOut(key: String, choice: Choice) { peers[key] = choice.copy(legacy = true) + trace(key, "cccd_timeout legacy=true type=${choice.requestType} where=memory") } @Synchronized fun rejected(key: String, choice: Choice) { peers[key] = choice.copy(requestType = if (choice.requestType == 1002) 1001 else 1002) + trace(key, "rejected type=${peers[key]?.requestType} legacy=${choice.legacy} where=memory") } @Synchronized fun succeeded(key: String, choice: Choice) { peers[key] = choice store.write(key, choice.requestType) + trace(key, "succeeded type=${choice.requestType} legacy=${choice.legacy} persisted=type") } @Synchronized fun exchanged(key: String, choice: Choice) { - if (choice.legacy) subscriptions?.writeLegacy(key) + if (choice.legacy) { + subscriptions?.writeLegacy(key) + trace(key, "exchanged legacy=true persisted=legacy") + } else { + trace(key, "exchanged legacy=false persisted=none") + } } @Synchronized fun exchangeFailed(key: String) { if (persistedLegacy.remove(key)) { subscriptions?.removeLegacy(key) peers[key]?.let { peers[key] = it.copy(legacy = false) } + trace(key, "exchange_failed legacy=false forgot=persisted") + } else { + trace(key, "exchange_failed legacy=false forgot=none") } } } diff --git a/android/app/src/main/java/org/openxplay/direlay/logs/NetworkTimeline.kt b/android/app/src/main/java/org/openxplay/direlay/logs/NetworkTimeline.kt index 8da26941..371467f2 100644 --- a/android/app/src/main/java/org/openxplay/direlay/logs/NetworkTimeline.kt +++ b/android/app/src/main/java/org/openxplay/direlay/logs/NetworkTimeline.kt @@ -12,7 +12,9 @@ import android.content.IntentFilter import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities +import android.net.NetworkInfo import android.net.NetworkRequest +import android.net.wifi.SupplicantState import android.net.wifi.WifiInfo import android.net.wifi.WifiManager import android.net.wifi.p2p.WifiP2pManager @@ -34,6 +36,8 @@ class NetworkTimeline(context: Context, private val log: ConnectionLog) : AutoCl private val started = java.util.concurrent.atomic.AtomicBoolean() private val closed = java.util.concurrent.atomic.AtomicBoolean() private val networks = linkedMapOf() + private var hadWifi = false + private var lastSnapshotAt = 0L private val callback = object : ConnectivityManager.NetworkCallback() { override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) = safely { if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) return@safely @@ -47,7 +51,8 @@ class NetworkTimeline(context: Context, private val log: ConnectionLog) : AutoCl override fun onReceive(context: Context, intent: Intent) = safely { when (intent.action) { WifiManager.WIFI_STATE_CHANGED_ACTION -> wifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)) - WifiManager.NETWORK_STATE_CHANGED_ACTION -> wifiConnection() + WifiManager.NETWORK_STATE_CHANGED_ACTION -> wifiConnection(intent) + WifiManager.SUPPLICANT_STATE_CHANGED_ACTION -> supplicant(intent) TETHER -> hotspot(intent) BluetoothAdapter.ACTION_STATE_CHANGED -> bluetooth(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION -> p2p() @@ -60,6 +65,7 @@ class NetworkTimeline(context: Context, private val log: ConnectionLog) : AutoCl if (closed.get()) return@safely val filter = IntentFilter().apply { addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION) + addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION) addAction(TETHER); addAction(BluetoothAdapter.ACTION_STATE_CHANGED) addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION) } @@ -75,7 +81,7 @@ class NetworkTimeline(context: Context, private val log: ConnectionLog) : AutoCl callbackRegistered = true }.onFailure { unavailable("wifi_connection") } runCatching { wifiState(wifi.wifiState) }.onFailure { unavailable("wifi") } - wifiConnection(); hotspot(); p2p() + wifiConnection(null); hotspot(); p2p() runCatching { bluetooth(context.getSystemService(BluetoothManager::class.java)?.adapter?.state ?: BluetoothAdapter.ERROR) } .onFailure { unavailable("bluetooth") } } } @@ -98,26 +104,72 @@ class NetworkTimeline(context: Context, private val log: ConnectionLog) : AutoCl @Suppress("DEPRECATION") private fun currentWifi(): WifiInfo? = runCatching { wifi.connectionInfo }.getOrNull() private fun wifiDetail(info: WifiInfo?): String { val frequency = info?.frequency ?: -1 - if (info == null || info.ssid == WifiManager.UNKNOWN_SSID || frequency <= 0) unavailable("wifi_identity") + if (info == null || info.ssid == WifiManager.UNKNOWN_SSID || frequency <= 0) { + unavailable("wifi_identity") + wifiSnapshot("wifi_identity_lost") + } val band = when (frequency) { in 2400..2500 -> "2.4GHz"; in 4900..5900 -> "5GHz"; in 5925..7125 -> "6GHz"; else -> "unavailable" } return "frequency=$frequency band=$band" } - @Suppress("DEPRECATION") private fun wifiConnection() { + /** + * Facts a disconnect report needs: the platform tells us only that the network went away, so the + * supplicant state and the last known identity are what separate a deauth from an interface reset. + */ + @Suppress("DEPRECATION") private fun wifiFacts(): String { + val enabled = runCatching { wifi.isWifiEnabled }.getOrDefault(false) + val info = currentWifi() ?: return "supplicant=unknown ssid=- frequency=-1 rssi=0 linkMbps=-1 networkId=-1 ip=- enabled=$enabled" + val raw = info.ipAddress + val ip = if (raw == 0) "-" + else "${raw and 0xff}.${(raw shr 8) and 0xff}.${(raw shr 16) and 0xff}.${(raw shr 24) and 0xff}" + return "supplicant=${info.supplicantState?.name ?: "unknown"} ssid=${info.ssid} frequency=${info.frequency} " + + "rssi=${info.rssi} linkMbps=${info.linkSpeed} networkId=${info.networkId} ip=$ip enabled=$enabled" + } + /** Once per flap window: a burst of callbacks must not bury the snapshot that explains it. */ + private fun wifiSnapshot(event: String, suffix: String = "") { + val now = android.os.SystemClock.elapsedRealtime() + if (now - lastSnapshotAt < 2_000) return + lastSnapshotAt = now + log.event("network", event, (wifiFacts() + suffix).trim()) + } + @Suppress("DEPRECATION") private fun networkDetail(info: NetworkInfo): String { + val reason = info.reason?.takeIf { it.isNotBlank() } ?: "-" + return "detailed=${info.detailedState} state=${info.state} reason=$reason" + } + @Suppress("DEPRECATION") private fun wifiConnection(intent: Intent?) { + val network = intent?.let { runCatching { it.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO) }.getOrNull() } + if (network != null) state("wifi/link", "wifi_link", networkDetail(network)) runCatching { val active = connectivity.allNetworks.filter { connectivity.getNetworkCapabilities(it) ?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true } networks.keys.retainAll(active.toSet()) - for (network in active) remember(network, wifiDetail(currentWifi())) - connected() + for (n in active) remember(n, wifiDetail(currentWifi())) + connected(network) }.onFailure { unavailable("wifi_connection") } } + @Suppress("DEPRECATION") private fun supplicant(intent: Intent?) { + if (intent == null) return + val supplicantState = if (Build.VERSION.SDK_INT >= 33) + intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE, SupplicantState::class.java) + else intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE) + val error = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1) + val name = supplicantState?.name ?: "unknown" + state("wifi/supplicant", "supplicant_state", "supplicant=$name error=$error") + if (error != -1 || supplicantState == SupplicantState.DISCONNECTED) + wifiSnapshot("supplicant_lost", " supplicant=$name error=$error") + } private fun remember(network: Network, detail: String) { networks[network] = detail } - private fun connected() { + @Suppress("DEPRECATION") private fun connected(network: NetworkInfo? = null) { val detail = networks.values.sorted().joinToString("; ") - if (networks.isEmpty()) state("wifi_connection", "wifi_disconnected", "by=os cause=network_lost") - else state("wifi_connection", "wifi_connected", detail) + val wasConnected = hadWifi + hadWifi = networks.isNotEmpty() + if (networks.isEmpty()) { + val reason = network?.reason?.takeIf { it.isNotBlank() } + val extra = if (network != null && reason != null) " detailed=${network.detailedState} reason=$reason" else "" + state("wifi_connection", "wifi_disconnected", "by=os cause=network_lost$extra") + if (wasConnected) wifiSnapshot("wifi_lost", if (reason == null) "" else " reason=$reason") + } else state("wifi_connection", "wifi_connected", detail) } private fun hotspot(intent: Intent? = null) { val key = listOf("tetherArray", "activeArray").firstOrNull { intent?.hasExtra(it) == true } From c627509a2a464b293a45c9852972375559abf80a Mon Sep 17 00:00:00 2001 From: hellowalker Date: Tue, 3 Nov 2026 14:41:18 +0800 Subject: [PATCH 09/17] Android: keep waiting for Carlink instead of failing the start MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .../direlay/relay/CarlinkStartGate.kt | 5 ++- .../openxplay/direlay/relay/RelayRuntime.kt | 2 + .../direlay/relay/RelaySessionActions.kt | 44 +++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/android/app/src/main/java/org/openxplay/direlay/relay/CarlinkStartGate.kt b/android/app/src/main/java/org/openxplay/direlay/relay/CarlinkStartGate.kt index 5522f83e..b2b310f4 100644 --- a/android/app/src/main/java/org/openxplay/direlay/relay/CarlinkStartGate.kt +++ b/android/app/src/main/java/org/openxplay/direlay/relay/CarlinkStartGate.kt @@ -4,6 +4,9 @@ package org.openxplay.direlay.relay import java.io.IOException +/** The gate ran out of time while the Carlink link was still starting. */ +class CarlinkStartTimeout : IOException("Carlink output did not become ready before CarPlay startup") + /** One explicit start owns a bounded wait; a saved screen never releases it. */ class CarlinkStartGate { @Volatile var untilMillis: Long? = null @@ -17,7 +20,7 @@ class CarlinkStartGate { val until = untilMillis ?: return true if (!outputEnabled) throw IOException("Carlink output was disabled while waiting to start CarPlay") if (outputReady) { cancel(); return true } - if (nowMillis >= until) throw IOException("Carlink output did not become ready before CarPlay startup") + if (nowMillis >= until) throw CarlinkStartTimeout() return false } diff --git a/android/app/src/main/java/org/openxplay/direlay/relay/RelayRuntime.kt b/android/app/src/main/java/org/openxplay/direlay/relay/RelayRuntime.kt index f13b4e01..7e31c595 100644 --- a/android/app/src/main/java/org/openxplay/direlay/relay/RelayRuntime.kt +++ b/android/app/src/main/java/org/openxplay/direlay/relay/RelayRuntime.kt @@ -728,6 +728,7 @@ class RelayRuntime(private val context: Context, } val networkStart get() = sessionController.networkStart fun recheckNetworkStart() = sessionController.recheckNetworkStart() + fun recheckCarlinkReady() = sessionController.recheckCarlinkReady() fun startAnyway() = sessionController.startAnyway() fun cancelNetworkStart() = sessionController.cancelNetworkStart() val adminService = org.openxplay.direlay.admin.RelayAdminService(context.applicationContext, this, @@ -818,6 +819,7 @@ class RelayRuntime(private val context: Context, status.session?.phase == org.openxplay.stream.core.SessionPhase.ACTIVE) sessionController.recoverRadio(networkReadings) sessionController.recheckNetworkStart() + sessionController.recheckCarlinkReady() // A session start or stop can block or release Carlink without a settings change. if (carlinkBlock.sessionChanged(autoStartSessions.tracker.running)) enqueueCarlink() }, 0, 500, TimeUnit.MILLISECONDS) diff --git a/android/app/src/main/java/org/openxplay/direlay/relay/RelaySessionActions.kt b/android/app/src/main/java/org/openxplay/direlay/relay/RelaySessionActions.kt index b75bda1c..ebf31058 100644 --- a/android/app/src/main/java/org/openxplay/direlay/relay/RelaySessionActions.kt +++ b/android/app/src/main/java/org/openxplay/direlay/relay/RelaySessionActions.kt @@ -18,6 +18,8 @@ import org.openxplay.direlay.settings.StartupPermissions import org.openxplay.direlay.settings.CarlinkConnectionPolicy import org.openxplay.direlay.network.ManualNetworkStart import org.openxplay.direlay.storage.MaterialStatus +import org.openxplay.stream.clink.ClinkState +import org.openxplay.stream.core.SessionPhase import java.util.concurrent.Executors import java.util.concurrent.TimeUnit @@ -42,6 +44,9 @@ class RelaySessionActions(private val context: Context, private val runtime: Rel val carlinkFirst = CarlinkStartGate() private val recovery = RecoverOncePolicy() private var userStopped = false + private var carlinkGateRetries = 0 + /** Set when a start gave up waiting for Carlink; cleared by the next start, stop, or late start. */ + private var restartWhenCarlinkReady = false private var pendingManual = true private var carWaitSatisfied = false @Volatile override var bootStart = false @@ -95,6 +100,7 @@ class RelaySessionActions(private val context: Context, private val runtime: Rel else -> "error.invalid" } private fun stop(source: String) { + restartWhenCarlinkReady = false runtime.carPlayStage.reset() runtime.iphoneLink.reset() runtime.connectionLog.event("relay", "carplay_stop", "source=$source") @@ -188,6 +194,22 @@ class RelaySessionActions(private val context: Context, private val runtime: Rel return startAfterNetworkAccepted() } + /** + * A start that stopped waiting for Carlink is not a stop. The link keeps scanning on its own and + * can come up a minute later — that is exactly what happened in the field, where the only thing + * that ever restarted CarPlay was the phone reconnecting by itself. Restart it here instead, and + * stand down when a session is already on its way. + */ + @Synchronized fun recheckCarlinkReady(): String? { + if (!restartWhenCarlinkReady || closed) return null + if (runtime.startRequest.pending || restarting) return null + if (runtime.carlinkState != ClinkState.PLAYING.name) return null + if (runtime.status.session?.phase in SESSION_STARTING) return null + restartWhenCarlinkReady = false + runtime.connectionLog.event("relay", "carplay_late_start", "reason=carlink_ready carlink=${runtime.carlinkState}") + return start(manual = false) + } + @Synchronized fun recoverRadio(readings: org.openxplay.direlay.network.NetworkReadings) { val code = recovery.observe(runtime.iphoneLink.snapshot.failure, readings, userStopped) ?: return runtime.connectionLog.event("relay", "carplay_radio_recover", "code=$code") @@ -255,6 +277,7 @@ class RelaySessionActions(private val context: Context, private val runtime: Rel runtime.carPlayDiagnostics.clear() carlinkFirst.request(System.currentTimeMillis(), wireless && CarlinkConnectionPolicy.enabled(settings) && settings.experimental.effective().waitForCarlink) + carlinkGateRetries = 0 if (carlinkFirst.untilMillis != null) waits.begin("carlink", "max=${CarlinkStartGate.MAX_WAIT_MILLIS} carlink=${runtime.carlinkState}") if (!carWaitSatisfied && carFirst.request(System.currentTimeMillis(), settings.displayMode == org.openxplay.direlay.settings.DisplayMode.AUTOMATIC, settings.browserOutput || settings.carlifeOutput, settings.carlinkOutput, @@ -275,6 +298,17 @@ class RelaySessionActions(private val context: Context, private val runtime: Rel return } waits.end("carlink", "ready") + } catch (timeout: CarlinkStartTimeout) { + waits.end("carlink", "timeout carlink=${runtime.carlinkState}") + // Expiring here says nothing about the link: it is still scanning, and the head unit is + // known to stop advertising for minutes. Buy another window instead of tearing the start + // down, but keep a bound so a link that never comes up still fails visibly. + if (carlinkGateRetries >= CARLINK_GATE_RETRIES) { restartWhenCarlinkReady = true; startFailed(timeout); return } + carlinkGateRetries++ + carlinkFirst.request(System.currentTimeMillis(), true) + waits.begin("carlink", "retry=$carlinkGateRetries max=${CarlinkStartGate.MAX_WAIT_MILLIS} carlink=${runtime.carlinkState}") + worker.schedule({ continueStart(launchGeneration, source, networkAccepted) }, 100, TimeUnit.MILLISECONDS) + return } catch (failure: Exception) { waits.end("carlink", "failed carlink=${runtime.carlinkState}"); startFailed(failure); return } if (!carFirst.ready(System.currentTimeMillis(), runtime.carScreenReported)) { waits.tick("car_screen") @@ -332,4 +366,14 @@ class RelaySessionActions(private val context: Context, private val runtime: Rel } private fun endWaits(outcome: String) { listOf("network", "carlink", "car_screen", "restart").forEach { waits.end(it, outcome) } } @Synchronized override fun close() { closed = true; generation++; restarting = false; networkStart.cancel(); carFirst.cancel(); carlinkFirst.cancel(); runtime.startRequest.finish(); worker.shutdownNow() } + private companion object { + /** + * How many extra Carlink gate windows an expired wait buys. The link is still scanning when the + * gate expires and the head unit stops advertising for minutes at a time, so failing the whole + * start there throws away work that is about to succeed; four windows bound the cost instead. + */ + const val CARLINK_GATE_RETRIES = 3 + /** Session phases that already mean "CarPlay is being brought up"; a late start stands down. */ + val SESSION_STARTING = setOf(SessionPhase.CONNECTING, SessionPhase.ACTIVE, SessionPhase.RECONNECTING) + } } From f44a75f26d6e40052d30008526c7a79a13a90022 Mon Sep 17 00:00:00 2001 From: hellowalker Date: Tue, 3 Nov 2026 14:41:26 +0800 Subject: [PATCH 10/17] Android: keep the display awake while a Carlink link is coming up MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .../org/openxplay/direlay/RelayActivity.kt | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/android/app/src/main/java/org/openxplay/direlay/RelayActivity.kt b/android/app/src/main/java/org/openxplay/direlay/RelayActivity.kt index 674e0dc7..7e653b93 100644 --- a/android/app/src/main/java/org/openxplay/direlay/RelayActivity.kt +++ b/android/app/src/main/java/org/openxplay/direlay/RelayActivity.kt @@ -56,6 +56,12 @@ import org.openxplay.stream.core.SessionPhase class RelayActivity : androidx.activity.ComponentActivity() { private val handler = Handler(Looper.getMainLooper()) + /** + * Keeps the display awake while a Carlink link is being brought up. The Bluetooth stack stops + * scanning the moment the screen goes to sleep, so a connection attempt that is still looking for + * the head unit dies with it — and the wait that follows then has nothing left to find it with. + */ + private var keepAwakeForLink = false private val identityImport by lazy { androidx.lifecycle.ViewModelProvider(this)[IdentityImportState::class.java] } private var identityDialog: AlertDialog? = null private var dialogVisible by androidx.compose.runtime.mutableStateOf(false) @@ -134,6 +140,23 @@ class RelayActivity : androidx.activity.ComponentActivity() { launch { presentation.readiness.collect { sample -> if (sample != null && sample.flags == hostFlags() && shouldAutoStart(sample.automatic, hostFlags())) startCarPlay() } } + launch { + var connectingSince = 0L + while (true) { + val connecting = runtime.carlinkState == org.openxplay.stream.clink.ClinkState.CONNECTING.name + // Bounded: an abandoned start leaves the link reporting CONNECTING forever, and + // holding the screen on there would never end. Five minutes covers every gate window. + if (!connecting) connectingSince = 0L + else if (connectingSince == 0L) connectingSince = android.os.SystemClock.elapsedRealtime() + val awake = connecting && android.os.SystemClock.elapsedRealtime() - connectingSince < LINK_AWAKE_LIMIT_MS + if (awake != keepAwakeForLink) { + keepAwakeForLink = awake + if (awake) window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + else window.clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } + kotlinx.coroutines.delay(1000) + } + } } } setContent { @@ -729,6 +752,8 @@ class RelayActivity : androidx.activity.ComponentActivity() { } companion object { + /** Longest a pending link may hold the display awake: every Carlink gate window in a row. */ + private const val LINK_AWAKE_LIMIT_MS = 300_000L /** A separate singleton task keeps bringing up Relay from clearing the CarPlay host. */ fun intent(context: Context, destination: String? = null, stepAction: StepAction? = null): Intent = Intent(context, RelayActivity::class.java) From f89389cf4c342a6333ec1dccd7c6642f2220e4a0 Mon Sep 17 00:00:00 2001 From: hellowalker Date: Tue, 3 Nov 2026 15:14:15 +0800 Subject: [PATCH 11/17] Android: retry the Wi-Fi join without repeating the BLE exchange 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. --- .../direlay/clink/AndroidClinkLink.kt | 84 +++++++++++++++---- 1 file changed, 69 insertions(+), 15 deletions(-) diff --git a/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt index 9b3ae44b..525399fd 100644 --- a/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt +++ b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt @@ -43,12 +43,26 @@ class AndroidClinkLink(context: Context, private val deviceId: String, private const val REQUEST_TIMEOUT_MS = 12_000L /** Never hand the request less than this, even if priming ate most of the stage budget. */ private const val MIN_REQUEST_TIMEOUT_MS = 5_000L + /** + * Window for a join retry. The first attempt gets the full [REQUEST_TIMEOUT_MS] because a slow + * access point can still come up inside it; a retry only has to catch an AP that is coming + * back, and waiting another full window there costs more than restarting the link. + */ + private const val JOIN_RETRY_BUDGET_MS = 5_000L + /** + * Pause before a join retry. Short on purpose: every retry polls for the platform's own link, + * so the moment the access point returns it is adopted without waiting out the rest. + */ + private const val JOIN_RETRY_FIRST_MS = 500L + private const val JOIN_RETRY_NEXT_MS = 1_500L /** Quiet window granted to the platform's own join before asking for a network. */ private const val QUIET_JOIN_MS = 2_500L /** How often a link the platform brought up on its own is checked for adoption. */ private const val ADOPT_POLL_MS = 100L /** How long a freshly started scan is given to deliver results before the request goes out. */ private const val PRIME_BUDGET_MS = 3_000L + /** How long a scan result counts as evidence that the head unit's AP is up right now. */ + private const val PRIME_FRESH_MS = 15_000L } private val peerStore = object : BlePeerPolicy.Store, BlePeerPolicy.SubscriptionStore { private val preferences = this@AndroidClinkLink.context.getSharedPreferences("clinkPeers", Context.MODE_PRIVATE) @@ -87,6 +101,20 @@ class AndroidClinkLink(context: Context, private val deviceId: String, handler.postDelayed({ done.complete(Unit) }, delay) await(run, done, 16) } + /** + * Pause between join attempts. Deliberately separate from [retry]: that backoff belongs to the BLE + * exchange, and letting a Wi-Fi retry push it to 4 s would slow the next full link start. + */ + private fun joinRetry(run: Run, delayMs: Long) { + // Distinct from the BLE backoff on purpose: seeing this line means the link was kept alive + // through a Wi-Fi failure instead of being rebuilt from a fresh scan. + Log.i("DiRelayCarlink", "join_retry delay=${delayMs}ms") + diagnostics.emit(ClinkDiagnostic.Retry(delayMs)) + val done = CompletableFuture() + handler.postDelayed({ done.complete(Unit) }, delayMs) + await(run, done, 5) + } + private fun awaitCleanup() { reconnect.awaitReleased(diagnostics) } @@ -130,8 +158,14 @@ class AndroidClinkLink(context: Context, private val deviceId: String, * dialog. One priming per throttle window keeps the remaining requests for the dialog. */ @Volatile private var lastPrimeAt = 0L - /** Whether the last priming actually saw the head unit's SSID in the scan results. */ - @Volatile private var lastPrimeSawTarget = false + /** + * When the head unit's SSID was last actually seen in scan results. A timestamp, not a flag: the + * 2-minute throttle means a retry can reuse a scan from long ago, and treating that as "the AP is + * there right now" spends the quiet window waiting for a network that has moved or restarted. + */ + @Volatile private var lastPrimeSawAt = 0L + private fun primeSawTarget(): Boolean = + lastPrimeSawAt != 0L && android.os.SystemClock.elapsedRealtime() - lastPrimeSawAt < PRIME_FRESH_MS /** * The confirmation dialog, and the scan-cache workaround for it, are MIUI/Android 10-11 specific. * Everything else here is generic AOSP behaviour and must not be slowed down for other vendors. @@ -175,15 +209,34 @@ class AndroidClinkLink(context: Context, private val deviceId: String, onSecret(reply.psk) diagnostics.handoff(reply.ssid, reply.psk.length) // No PIN/UI pause here; return immediately after DHCP so clink can start AUTH. - val endpoints = diagnosed(ClinkStage.WIFI_JOIN, ClinkFailureReason.WIFI_TIMEOUT) { join(run, reply) } - diagnostics.emit(ClinkDiagnostic.Joined(endpoints.first, endpoints.second)) + // A join failure says nothing about the BLE exchange: the head unit keeps the same soft AP + // for the session, so redoing a scan plus exchange only adds seconds to a Wi-Fi problem it + // cannot fix. Retry the join with the reply already in hand; a rotated passphrase still + // surfaces as a failure here and the next link attempt redoes BLE anyway. + var endpoints: Pair? = null + for (joinAttempt in 0..2) { + try { + endpoints = diagnosed(ClinkStage.WIFI_JOIN, ClinkFailureReason.WIFI_TIMEOUT) { + join(run, reply, if (joinAttempt == 0) REQUEST_TIMEOUT_MS else JOIN_RETRY_BUDGET_MS) + } + break + } catch (failure: Exception) { + // Drop the request and any P2P channel before asking again, or the next attempt + // stacks a second request on the first one and MIUI pays for both. + main { leaveP2p(run); releaseNetwork(run) } + if (run.cancelled || joinAttempt == 2) throw failure + joinRetry(run, if (joinAttempt == 0) JOIN_RETRY_FIRST_MS else JOIN_RETRY_NEXT_MS) + } + } + val joined = checkNotNull(endpoints) + diagnostics.emit(ClinkDiagnostic.Joined(joined.first, joined.second)) main { check(!run.cancelled) { "Link cancelled" } run.failure?.let { throw it } run.ready = true run.peerKey?.let { peers.succeeded(it, checkNotNull(run.peerChoice)) } } - return ClinkAddresses(endpoints.first, endpoints.second, + return ClinkAddresses(joined.first, joined.second, reply.port.takeIf { it != 0 } ?: 57209, carId, socketBinding = if (!isolateNetwork) ClinkSocketBinding.SYSTEM else ClinkSocketBinding { socket -> synchronized(this) { @@ -540,10 +593,11 @@ class AndroidClinkLink(context: Context, private val deviceId: String, awaitCleanup() } } - private fun join(run: Run, reply: HeadUnitReply): Pair = - WifiJoinPolicy.withWifi(readWifiEnabled(context)) { joinWithWifi(run, reply) } + private fun join(run: Run, reply: HeadUnitReply, budgetMs: Long = REQUEST_TIMEOUT_MS): Pair = + WifiJoinPolicy.withWifi(readWifiEnabled(context)) { joinWithWifi(run, reply, budgetMs) } + - private fun joinWithWifi(run: Run, reply: HeadUnitReply): Pair { + private fun joinWithWifi(run: Run, reply: HeadUnitReply, budgetMs: Long): Pair { val reserved = p2pReservation.reservedByCarPlay() var method = WifiJoinPolicy.first(Build.VERSION.SDK_INT, p2p != null && !reserved, reply.type) diagnostics.emit(ClinkDiagnostic.JoinChoice(method, when { @@ -564,7 +618,7 @@ class AndroidClinkLink(context: Context, private val deviceId: String, } } if (method != WifiJoinPolicy.Method.NETWORK_SPECIFIER) throw ClinkFailure(ClinkFailureReason.WIFI_UNAVAILABLE) - return joinSpecifier(run, reply) + return joinSpecifier(run, reply, budgetMs) } private fun joinP2p(run: Run, reply: HeadUnitReply): Pair { val result = CompletableFuture>() @@ -617,7 +671,7 @@ class AndroidClinkLink(context: Context, private val deviceId: String, } return await(run, result, 7) } - private fun joinSpecifier(run: Run, reply: HeadUnitReply): Pair { + private fun joinSpecifier(run: Run, reply: HeadUnitReply, budgetMs: Long): Pair { // The car network is a saved network, so the platform joins it on its own as soon as the AP // shows up — around the moment this stage starts. A WifiNetworkSpecifier request issued into // that window never attaches: the link completes under the system's uid, the request matches @@ -633,7 +687,7 @@ class AndroidClinkLink(context: Context, private val deviceId: String, // both faster and silent: requestNetwork is what raises MIUI's unanswerable dialog, so give // the platform a quiet window before asking for a network of our own. var quiet = 0L - if (lastPrimeSawTarget && miuiRequestsNeedCache) { + if (primeSawTarget() && miuiRequestsNeedCache) { val started = SystemClock.elapsedRealtime() while (!run.cancelled) { adoptHeadUnitLink(run, reply.ssid)?.let { @@ -691,7 +745,7 @@ class AndroidClinkLink(context: Context, private val deviceId: String, val request = NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).setNetworkSpecifier(specifier).build() manager.requestNetwork(request, callback, handler, - (REQUEST_TIMEOUT_MS - consumed).coerceAtLeast(MIN_REQUEST_TIMEOUT_MS).toInt()) + (budgetMs - consumed).coerceAtLeast(MIN_REQUEST_TIMEOUT_MS).toInt()) // The system's own join of this saved AP is invisible to the request, so adopt it the // moment it gets an IPv4 lease instead of waiting out the request timeout. val watcher = object : Runnable { @@ -828,10 +882,10 @@ class AndroidClinkLink(context: Context, private val deviceId: String, val wifi = context.getSystemService(android.net.wifi.WifiManager::class.java) ?: return 0 if (!wifi.isWifiEnabled) return 0 // A null list means the location permission is missing; waiting would only add delay. - lastPrimeSawTarget = false + lastPrimeSawAt = 0L val cached = wifi.scanResults ?: return 0 if (cached.any { it.SSID == ssid }) { - lastPrimeSawTarget = true + lastPrimeSawAt = SystemClock.elapsedRealtime() Log.i("DiRelayCarlink", "scan_primed hit=cached waited=0") return 0 } @@ -845,7 +899,7 @@ class AndroidClinkLink(context: Context, private val deviceId: String, while (issued && !run.cancelled) { if (SystemClock.elapsedRealtime() - started >= PRIME_BUDGET_MS) break val results = wifi.scanResults ?: break - if (results.any { it.SSID == ssid }) { hit = true; lastPrimeSawTarget = true; break } + if (results.any { it.SSID == ssid }) { hit = true; lastPrimeSawAt = SystemClock.elapsedRealtime(); break } try { Thread.sleep(100) } catch (_: InterruptedException) { break } } val waited = SystemClock.elapsedRealtime() - started From 27b9edb4197b020b2339a8e9619681dcfeb03471 Mon Sep 17 00:00:00 2001 From: hellowalker Date: Tue, 3 Nov 2026 15:16:12 +0800 Subject: [PATCH 12/17] Android: join the head-unit access point without the Wi-Fi dialog 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. --- .../direlay/clink/AndroidClinkLink.kt | 43 +++++++++++++++++++ .../direlay/config/UserConfigCodec.kt | 2 + .../direlay/settings/ExperimentalOptions.kt | 8 +++- .../direlay/settings/RelaySettings.kt | 2 + .../direlay/ui/ExperimentalScreen.kt | 5 +++ .../direlay/ui/ExperimentalSections.kt | 3 ++ .../direlay/ui/SettingsDraftSaver.kt | 2 + .../src/main/res/values-zh-rCN/strings.xml | 2 + android/app/src/main/res/values/strings.xml | 2 + .../direlay/config/UserConfigCodecTest.kt | 2 +- .../settings/ExperimentalOptionsTest.kt | 8 ++-- .../direlay/settings/RelaySettingsTest.kt | 2 +- .../direlay/ui/ExperimentalSectionsTest.kt | 3 +- 13 files changed, 75 insertions(+), 9 deletions(-) diff --git a/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt index 9b3ae44b..1add8f23 100644 --- a/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt +++ b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt @@ -47,6 +47,14 @@ class AndroidClinkLink(context: Context, private val deviceId: String, private const val QUIET_JOIN_MS = 2_500L /** How often a link the platform brought up on its own is checked for adoption. */ private const val ADOPT_POLL_MS = 100L + /** + * How long the platform gets to join the saved head-unit network after one scan. Measured: + * when the scan does show the AP the link is up in 350-430 ms, so this only has to cover a + * slow association, not a whole request window. + */ + private const val PLATFORM_JOIN_MS = 3_000L + /** Shorter listen when the scan was refused: the platform may already be joining on its own. */ + private const val PLATFORM_JOIN_REFUSED_MS = 800L /** How long a freshly started scan is given to deliver results before the request goes out. */ private const val PRIME_BUDGET_MS = 3_000L } @@ -87,6 +95,35 @@ class AndroidClinkLink(context: Context, private val deviceId: String, handler.postDelayed({ done.complete(Unit) }, delay) await(run, done, 16) } + /** MIUI only, and only while the experiment is on: see the comment at the call site. */ + private val scanAdoptJoinEnabled = experimental.scanAdoptJoin + private val scanAdoptJoin: Boolean get() = scanAdoptJoinEnabled && miuiRequestsNeedCache + /** + * Nudges the platform with one scan and adopts whatever link it brings up, without asking for a + * network of our own. Returns null when the phone does not join by itself, so the caller falls + * back to the request path exactly as before. + */ + @Suppress("DEPRECATION") + private fun platformScanJoin(run: Run, ssid: String): Pair? { + adoptHeadUnitLink(run, ssid)?.let { return it } + val wifi = context.getSystemService(android.net.wifi.WifiManager::class.java) ?: return null + if (!runCatching { wifi.isWifiEnabled }.getOrDefault(false)) return null + val started = SystemClock.elapsedRealtime() + val issued = runCatching { wifi.startScan() }.getOrDefault(false) + // A refused scan means MIUI's budget is spent. The platform may still be joining, so listen + // briefly, but not long enough to delay the request path this is meant to avoid. + val deadline = started + if (issued) PLATFORM_JOIN_MS else PLATFORM_JOIN_REFUSED_MS + while (!run.cancelled && SystemClock.elapsedRealtime() < deadline) { + adoptHeadUnitLink(run, ssid)?.let { + Log.i("DiRelayCarlink", "join_scan_adopted issued=$issued waited=${SystemClock.elapsedRealtime() - started}ms") + return it + } + try { Thread.sleep(ADOPT_POLL_MS) } catch (_: InterruptedException) { break } + } + Log.i("DiRelayCarlink", "join_scan_miss issued=$issued waited=${SystemClock.elapsedRealtime() - started}ms") + return null + } + private fun awaitCleanup() { reconnect.awaitReleased(diagnostics) } @@ -625,6 +662,12 @@ class AndroidClinkLink(context: Context, private val deviceId: String, // getting in the car always fails, the retry succeeds", so adopt the platform's link whenever // it exists and keep watching for it while the request is pending. adoptHeadUnitLink(run, reply.ssid)?.let { return it } + // MIUI raises its Wi-Fi picker for every WifiNetworkSpecifier request, and on this build 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 us — ask for the scan and take it. Everything + // below stays as the fallback, so non-MIUI devices never enter this branch. + if (scanAdoptJoin) platformScanJoin(run, reply.ssid)?.let { return it } // Let the platform see the AP first: a scan result is what makes it start its own join — and // what makes MIUI match the request silently when there is nothing to adopt. val primed = primeScanCache(run, reply.ssid) diff --git a/android/app/src/main/java/org/openxplay/direlay/config/UserConfigCodec.kt b/android/app/src/main/java/org/openxplay/direlay/config/UserConfigCodec.kt index 1107ac8c..9602aab0 100644 --- a/android/app/src/main/java/org/openxplay/direlay/config/UserConfigCodec.kt +++ b/android/app/src/main/java/org/openxplay/direlay/config/UserConfigCodec.kt @@ -188,6 +188,7 @@ object UserConfigCodec { .put("releaseBluetoothOnRequest", e.releaseBluetoothOnRequest) .put("awaitIphoneReconnect", e.awaitIphoneReconnect) .put("radioConflictPrompt", e.radioConflictPrompt) + .put("scanAdoptJoin", e.scanAdoptJoin) .put("stallWatchdog", e.stallWatchdog) .put("sendBluetoothAddress", e.sendBluetoothAddress) .put("bluetoothAddress", e.bluetoothAddress) @@ -334,6 +335,7 @@ object UserConfigCodec { "releaseBluetoothOnRequest" -> e.copy(releaseBluetoothOnRequest = objectValue.bool(field)) "awaitIphoneReconnect" -> e.copy(awaitIphoneReconnect = objectValue.bool(field)) "radioConflictPrompt" -> e.copy(radioConflictPrompt = objectValue.bool(field)) + "scanAdoptJoin" -> e.copy(scanAdoptJoin = objectValue.bool(field)) "stallWatchdog" -> e.copy(stallWatchdog = objectValue.bool(field)) "rememberSubscription" -> { objectValue.bool(field); e } "keepScanning" -> { objectValue.bool(field); e } diff --git a/android/app/src/main/java/org/openxplay/direlay/settings/ExperimentalOptions.kt b/android/app/src/main/java/org/openxplay/direlay/settings/ExperimentalOptions.kt index f67ac3de..992be689 100644 --- a/android/app/src/main/java/org/openxplay/direlay/settings/ExperimentalOptions.kt +++ b/android/app/src/main/java/org/openxplay/direlay/settings/ExperimentalOptions.kt @@ -11,6 +11,7 @@ data class ExperimentalOptions( val active: Boolean = true, val rememberSubscription: Boolean = true, val keepScanning: Boolean = true, + val scanAdoptJoin: Boolean = true, val recordAdvertisements: Boolean = true, val sendBluetoothAddress: Boolean = false, val bluetoothAddress: String = "", @@ -49,6 +50,7 @@ data class ExperimentalOptions( releaseBluetoothOnRequest = active && releaseBluetoothOnRequest, awaitIphoneReconnect = active && awaitIphoneReconnect, radioConflictPrompt = active && radioConflictPrompt, + scanAdoptJoin = active && scanAdoptJoin, stallWatchdog = active && stallWatchdog) } @@ -56,10 +58,11 @@ data class ExperimentalOptions( val optionCount: Int get() = listOf(remotePlaybackProof, cancelRecoveredRetries, startupStatus, startupDiagnostics, networkObservationBackoff, screenSessionIsolation, screenReconnectReset, screenDeliverySerialization, iapChannelWhenOffered, releaseBluetoothOnRequest, awaitIphoneReconnect, radioConflictPrompt, stallWatchdog, - sendBluetoothAddress).count { it } + scanAdoptJoin, sendBluetoothAddress).count { it } fun names(): List = listOf(rememberSubscription to "remember_subscription", keepScanning to "keep_scanning", recordAdvertisements to "record_advertisements", sendBluetoothAddress to "send_bluetooth_address", + scanAdoptJoin to "scan_adopt_join", isolateCarlinkNetwork to "isolate_carlink_network", waitForCarlink to "wait_for_carlink", recoverWirelessNetwork to "recover_wireless_network", remotePlaybackProof to "remote_playback_proof", @@ -91,7 +94,8 @@ data class ExperimentalOptions( releaseBluetoothOnRequest = false, awaitIphoneReconnect = false, radioConflictPrompt = false, - stallWatchdog = false) + stallWatchdog = false, + scanAdoptJoin = false) fun normalizedBluetoothAddress(value: String): String? { val octets = value.split(':') diff --git a/android/app/src/main/java/org/openxplay/direlay/settings/RelaySettings.kt b/android/app/src/main/java/org/openxplay/direlay/settings/RelaySettings.kt index 703d42b6..d02f9329 100644 --- a/android/app/src/main/java/org/openxplay/direlay/settings/RelaySettings.kt +++ b/android/app/src/main/java/org/openxplay/direlay/settings/RelaySettings.kt @@ -446,6 +446,7 @@ class RelaySettingsStore(private val context: Context) : AutoCloseable, org.open releaseBluetoothOnRequest = relay.getBoolean("experimental.releaseBluetoothOnRequest", true), awaitIphoneReconnect = relay.getBoolean("experimental.awaitIphoneReconnect", true), radioConflictPrompt = relay.getBoolean("experimental.radioConflictPrompt", true), + scanAdoptJoin = relay.getBoolean("experimental.scanAdoptJoin", true), stallWatchdog = relay.getBoolean("experimental.stallWatchdog", true), ) if (legacy) relay.edit().also { writeExperimentalOptions(it, value) }.apply() @@ -469,6 +470,7 @@ class RelaySettingsStore(private val context: Context) : AutoCloseable, org.open .putBoolean("experimental.releaseBluetoothOnRequest", value.releaseBluetoothOnRequest) .putBoolean("experimental.awaitIphoneReconnect", value.awaitIphoneReconnect) .putBoolean("experimental.radioConflictPrompt", value.radioConflictPrompt) + .putBoolean("experimental.scanAdoptJoin", value.scanAdoptJoin) .putBoolean("experimental.stallWatchdog", value.stallWatchdog) .remove("experimental.rememberSubscription") .remove("experimental.keepScanning") diff --git a/android/app/src/main/java/org/openxplay/direlay/ui/ExperimentalScreen.kt b/android/app/src/main/java/org/openxplay/direlay/ui/ExperimentalScreen.kt index 1dac711b..244b7a5d 100644 --- a/android/app/src/main/java/org/openxplay/direlay/ui/ExperimentalScreen.kt +++ b/android/app/src/main/java/org/openxplay/direlay/ui/ExperimentalScreen.kt @@ -58,6 +58,11 @@ fun ExperimentalScreen(state: SettingsEditorState, back: () -> Unit, wireless: ( footer = stringResource(R.string.experimental_stall_watchdog_hint), enabled = options.active, header = header) { enabled -> state.changeExperimental { it.copy(stallWatchdog = enabled) } } + ExperimentalOption.SCAN_ADOPT_JOIN -> SettingsToggleGroup(stringResource(R.string.experimental_scan_adopt_join), options.scanAdoptJoin, + R.drawable.symbol_wifi, IconHue.NETWORK, + footer = stringResource(R.string.experimental_scan_adopt_join_hint), enabled = options.active, header = header) { enabled -> + state.changeExperimental { it.copy(scanAdoptJoin = enabled) } + } ExperimentalOption.SCREEN_SESSION_ISOLATION -> SettingsToggleGroup(stringResource(R.string.experimental_screen_session_isolation), options.screenSessionIsolation, R.drawable.symbol_activity, IconHue.DEVELOPER, footer = stringResource(R.string.experimental_screen_session_isolation_hint), enabled = options.active, header = header) { enabled -> diff --git a/android/app/src/main/java/org/openxplay/direlay/ui/ExperimentalSections.kt b/android/app/src/main/java/org/openxplay/direlay/ui/ExperimentalSections.kt index c9cec5fc..a573b3f3 100644 --- a/android/app/src/main/java/org/openxplay/direlay/ui/ExperimentalSections.kt +++ b/android/app/src/main/java/org/openxplay/direlay/ui/ExperimentalSections.kt @@ -9,6 +9,7 @@ internal enum class ExperimentalOption { AWAIT_IPHONE_RECONNECT, RADIO_CONFLICT_PROMPT, STALL_WATCHDOG, + SCAN_ADOPT_JOIN, SCREEN_SESSION_ISOLATION, SCREEN_RECONNECT_RESET, SCREEN_DELIVERY_SERIALIZATION, @@ -23,6 +24,8 @@ internal enum class ExperimentalOption { internal data class ExperimentalSection(val version: String, val options: List) internal val experimentalSections = listOf( + ExperimentalSection("0.2.5", listOf( + ExperimentalOption.SCAN_ADOPT_JOIN)), ExperimentalSection("0.2.3", listOf( ExperimentalOption.IAP_CHANNEL_WHEN_OFFERED, ExperimentalOption.RELEASE_BLUETOOTH_ON_REQUEST, diff --git a/android/app/src/main/java/org/openxplay/direlay/ui/SettingsDraftSaver.kt b/android/app/src/main/java/org/openxplay/direlay/ui/SettingsDraftSaver.kt index 1f11bc63..6d60c140 100644 --- a/android/app/src/main/java/org/openxplay/direlay/ui/SettingsDraftSaver.kt +++ b/android/app/src/main/java/org/openxplay/direlay/ui/SettingsDraftSaver.kt @@ -92,6 +92,7 @@ fun relaySettingsSaver(base: RelaySettings) = Saver(save putBoolean("experimental.releaseBluetoothOnRequest", value.experimental.releaseBluetoothOnRequest) putBoolean("experimental.awaitIphoneReconnect", value.experimental.awaitIphoneReconnect) putBoolean("experimental.radioConflictPrompt", value.experimental.radioConflictPrompt) + putBoolean("experimental.scanAdoptJoin", value.experimental.scanAdoptJoin) putBoolean("experimental.stallWatchdog", value.experimental.stallWatchdog) putBoolean("experimental.rememberSubscription", value.experimental.rememberSubscription) putBoolean("experimental.keepScanning", value.experimental.keepScanning) @@ -140,6 +141,7 @@ fun relaySettingsSaver(base: RelaySettings) = Saver(save releaseBluetoothOnRequest = bundle.getBoolean("experimental.releaseBluetoothOnRequest", base.experimental.releaseBluetoothOnRequest), awaitIphoneReconnect = bundle.getBoolean("experimental.awaitIphoneReconnect", base.experimental.awaitIphoneReconnect), radioConflictPrompt = bundle.getBoolean("experimental.radioConflictPrompt", base.experimental.radioConflictPrompt), + scanAdoptJoin = bundle.getBoolean("experimental.scanAdoptJoin", base.experimental.scanAdoptJoin), stallWatchdog = bundle.getBoolean("experimental.stallWatchdog", base.experimental.stallWatchdog), rememberSubscription = bundle.getBoolean("experimental.rememberSubscription", base.experimental.rememberSubscription), keepScanning = bundle.getBoolean("experimental.keepScanning", base.experimental.keepScanning), diff --git a/android/app/src/main/res/values-zh-rCN/strings.xml b/android/app/src/main/res/values-zh-rCN/strings.xml index e2cce676..c9b7c128 100644 --- a/android/app/src/main/res/values-zh-rCN/strings.xml +++ b/android/app/src/main/res/values-zh-rCN/strings.xml @@ -822,6 +822,8 @@ 手机打开热点会关闭 Wi-Fi 时,如果当前方式无法启动 CarPlay,弹窗建议改用可用的方式。关闭后只写入日志。 卡顿监测 每秒检查一次,记录暂停、线程卡住和长时间不动的连接步骤;为下次启动保留心跳,并重启停止输出的日志记录。会多耗一点电。 + 免弹窗加入 + 在 MIUI 上只发起一次扫描,让手机自己连上已保存的车机热点,再接管这条链路。可避开本系统中无法应答的 Wi-Fi 选择弹窗,并快约 3 秒。若手机没有自己去连,仍会回退到原来的网络请求方式。 复制到系统(推荐) 将下面的名称和密码分别复制到这台手机的热点设置,再开启热点。设置一项后,返回这里复制另一项。 填写已有热点 diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 81518b7f..3b0344ca 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -831,6 +831,8 @@ On a phone that turns Wi-Fi off while its hotspot is on, ask to switch when the current mode cannot start CarPlay. Off: the conflict is only written to the log. Watch for stalls Checks the relay every second and logs pauses, blocked threads and connection steps that stop moving; keeps a heartbeat for the next start and restarts a silent log recorder. Uses a little more battery. + Join without the Wi-Fi dialog + On MIUI, ask for one scan and let the phone join the head-unit saved network, then take that link over. Avoids the Wi-Fi picker dialog that can never be answered on this build, and is about three seconds faster. Falls back to the network request when the phone does not join. Copy to settings (recommended) Copy each value below into this phone\'s hotspot settings, then turn on the hotspot. Return here to copy the other value. Use my existing hotspot diff --git a/android/app/src/test/java/org/openxplay/direlay/config/UserConfigCodecTest.kt b/android/app/src/test/java/org/openxplay/direlay/config/UserConfigCodecTest.kt index e6a04bb6..b9b63128 100644 --- a/android/app/src/test/java/org/openxplay/direlay/config/UserConfigCodecTest.kt +++ b/android/app/src/test/java/org/openxplay/direlay/config/UserConfigCodecTest.kt @@ -471,7 +471,7 @@ class UserConfigCodecTest { val text = UserConfigCodec.encode(chosen, DeveloperOverrides(), meta) val json = JSONObject(text).getJSONObject("settings").getJSONObject("experimental") assertEquals(setOf("version", "active", "remotePlaybackProof", "cancelRecoveredRetries", "startupStatus", "startupDiagnostics", "networkObservationBackoff", "screenSessionIsolation", "screenReconnectReset", "screenDeliverySerialization", - "iapChannelWhenOffered", "releaseBluetoothOnRequest", "awaitIphoneReconnect", "radioConflictPrompt", "stallWatchdog", + "iapChannelWhenOffered", "releaseBluetoothOnRequest", "awaitIphoneReconnect", "radioConflictPrompt", "scanAdoptJoin", "stallWatchdog", "sendBluetoothAddress", "bluetoothAddress"), json.keys().asSequence().toSet()) val result = UserConfigCodec.decode(text, base.copy(experimental = ExperimentalOptions.OFF)) diff --git a/android/app/src/test/java/org/openxplay/direlay/settings/ExperimentalOptionsTest.kt b/android/app/src/test/java/org/openxplay/direlay/settings/ExperimentalOptionsTest.kt index a5919b17..2871708a 100644 --- a/android/app/src/test/java/org/openxplay/direlay/settings/ExperimentalOptionsTest.kt +++ b/android/app/src/test/java/org/openxplay/direlay/settings/ExperimentalOptionsTest.kt @@ -14,7 +14,7 @@ class ExperimentalOptionsTest { @Test fun newLaboratoryOptionsDefaultOnAndPromotedFeaturesSurviveMasterOff() { val defaults = ExperimentalOptions() assertTrue(defaults.active); assertFalse(defaults.sendBluetoothAddress) - assertEquals(13, defaults.optionCount) + assertEquals(14, defaults.optionCount) assertEquals(ExperimentalOptions.OFF, defaults.copy(active = false).effective()) val disabled = selected.copy(active = false).effective() assertEquals(ExperimentalOptions.OFF, disabled) @@ -39,7 +39,7 @@ class ExperimentalOptionsTest { assertTrue(invalid.effective().recordAdvertisements) assertFalse(invalid.copy(active = false).invalidAddress) assertFalse(invalid.copy(sendBluetoothAddress = false).invalidAddress) - assertEquals(20, selected.effective().names().size) + assertEquals(21, selected.effective().names().size) } @Test fun addressRequiresSixHexUnicastOctetsAndRejectsHiddenAndZeroAddresses() { @@ -87,7 +87,7 @@ class ExperimentalOptionsTest { releaseBluetoothOnRequest = bits and 2 != 0, awaitIphoneReconnect = bits and 4 != 0) val enabled = selected.effective() assertEquals(selected, enabled) - assertEquals(10 + Integer.bitCount(bits), enabled.optionCount) + assertEquals(11 + Integer.bitCount(bits), enabled.optionCount) assertEquals(names.filterIndexed { index, _ -> bits and (1 shl index) != 0 }, enabled.names().filter { it in names }) val disabled = selected.copy(active = false).effective() assertEquals(ExperimentalOptions.OFF, disabled) @@ -106,7 +106,7 @@ class ExperimentalOptionsTest { val selected = defaults.copy(radioConflictPrompt = bits and 1 != 0, stallWatchdog = bits and 2 != 0) val enabled = selected.effective() assertEquals(selected, enabled) - assertEquals(11 + Integer.bitCount(bits), enabled.optionCount) + assertEquals(12 + Integer.bitCount(bits), enabled.optionCount) assertEquals(names.filterIndexed { index, _ -> bits and (1 shl index) != 0 }, enabled.names().filter { it in names }) val disabled = selected.copy(active = false).effective() assertFalse(disabled.radioConflictPrompt || disabled.stallWatchdog) diff --git a/android/app/src/test/java/org/openxplay/direlay/settings/RelaySettingsTest.kt b/android/app/src/test/java/org/openxplay/direlay/settings/RelaySettingsTest.kt index c28a411c..03eb0cf1 100644 --- a/android/app/src/test/java/org/openxplay/direlay/settings/RelaySettingsTest.kt +++ b/android/app/src/test/java/org/openxplay/direlay/settings/RelaySettingsTest.kt @@ -807,7 +807,7 @@ class RelaySettingsTest { RelaySettingsStore(context).use { migrated -> val value = migrated.load() assertTrue(value.experimental.active) - assertEquals(13, value.experimental.optionCount) + assertEquals(14, value.experimental.optionCount) assertTrue(value.experimental.effective().keepScanning) assertFalse(value.experimental.sendBluetoothAddress) migrated.save(value.copy(experimental = value.experimental.copy(active = false, startupDiagnostics = false))) diff --git a/android/app/src/test/java/org/openxplay/direlay/ui/ExperimentalSectionsTest.kt b/android/app/src/test/java/org/openxplay/direlay/ui/ExperimentalSectionsTest.kt index b7fa44be..13734f2f 100644 --- a/android/app/src/test/java/org/openxplay/direlay/ui/ExperimentalSectionsTest.kt +++ b/android/app/src/test/java/org/openxplay/direlay/ui/ExperimentalSectionsTest.kt @@ -10,8 +10,9 @@ import java.util.Locale class ExperimentalSectionsTest { @Test fun sectionsAreNewestFirstAndTheirOptionsFollowReleaseOrder() { - assertEquals(listOf("0.2.3", "0.2.2", "0.2.1", "0.2.0"), experimentalSections.map { it.version }) + assertEquals(listOf("0.2.5", "0.2.3", "0.2.2", "0.2.1", "0.2.0"), experimentalSections.map { it.version }) assertEquals(listOf( + listOf(ExperimentalOption.SCAN_ADOPT_JOIN), listOf(ExperimentalOption.IAP_CHANNEL_WHEN_OFFERED, ExperimentalOption.RELEASE_BLUETOOTH_ON_REQUEST, ExperimentalOption.AWAIT_IPHONE_RECONNECT, ExperimentalOption.RADIO_CONFLICT_PROMPT, ExperimentalOption.STALL_WATCHDOG), listOf(ExperimentalOption.SCREEN_SESSION_ISOLATION, ExperimentalOption.SCREEN_RECONNECT_RESET, From ab6329d931318f762b349e096a90b9e8952040d0 Mon Sep 17 00:00:00 2001 From: Riko Date: Wed, 4 Nov 2026 21:30:29 -0800 Subject: [PATCH 13/17] Carlink Wi-Fi recovery: adopt the head-unit network the phone joined 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. --- .../direlay/clink/AndroidCarlinkWifi.kt | 17 +++++ .../direlay/clink/CarlinkWifiFlow.kt | 72 ++++++++++++++++++- .../direlay/clink/AndroidCarlinkWifiTest.kt | 6 ++ .../direlay/clink/CarlinkWifiFlowTest.kt | 62 +++++++++++++++- 4 files changed, 152 insertions(+), 5 deletions(-) diff --git a/android/app/src/main/java/org/openxplay/direlay/clink/AndroidCarlinkWifi.kt b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidCarlinkWifi.kt index 548af309..f2f46e57 100644 --- a/android/app/src/main/java/org/openxplay/direlay/clink/AndroidCarlinkWifi.kt +++ b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidCarlinkWifi.kt @@ -47,6 +47,18 @@ internal class AndroidCarlinkWifi(context: Context, private val handler: Handler handler.postDelayed(runnable, millis) return AutoCloseable { handler.removeCallbacks(runnable) } } + /** + * MIUI on Android 10/11 raises a Wi-Fi picker for every specifier request that can never be + * answered. One scan makes the phone join the saved head-unit network by itself within about + * half a second; a refused scan (spent throttle) still leaves a join in progress to wait for. + */ + @Suppress("DEPRECATION") + override fun nudgePlatformJoin(): Long { + if (!miuiConfirmationDialog() || wifi == null || !runCatching { wifi.isWifiEnabled }.getOrDefault(false)) return 0 + val issued = runCatching { wifi.startScan() }.getOrDefault(false) + diagnostics.emit(ClinkDiagnostic.WifiRecovery(if (issued) "platform_join_scan" else "platform_join_scan_refused")) + return if (issued) PLATFORM_JOIN_MILLIS else PLATFORM_JOIN_REFUSED_MILLIS + } } private val flow = CarlinkWifiFlow(reply.ssid, driver, { phase -> when (phase) { @@ -166,6 +178,11 @@ internal class AndroidCarlinkWifi(context: Context, private val handler: Handler } else common } companion object { + /** Measured on a MI 8 SE: a scan that shows the AP has it joined in 350-430 ms. */ + const val PLATFORM_JOIN_MILLIS = 3_000L + const val PLATFORM_JOIN_REFUSED_MILLIS = 800L + internal fun miuiConfirmationDialog(manufacturer: String = Build.MANUFACTURER, sdk: Int = Build.VERSION.SDK_INT) = + manufacturer.equals("Xiaomi", ignoreCase = true) && sdk <= 30 // UNKNOWN_SSID is an inlined string, including on Android 10. @SuppressLint("InlinedApi") internal fun normalizeSsid(value: String?): String? = value?.let { diff --git a/android/app/src/main/java/org/openxplay/direlay/clink/CarlinkWifiFlow.kt b/android/app/src/main/java/org/openxplay/direlay/clink/CarlinkWifiFlow.kt index b6174058..953f1c8c 100644 --- a/android/app/src/main/java/org/openxplay/direlay/clink/CarlinkWifiFlow.kt +++ b/android/app/src/main/java/org/openxplay/direlay/clink/CarlinkWifiFlow.kt @@ -29,6 +29,11 @@ internal class CarlinkWifiFlow(private val ssid: String, private val driver: fun observe(observer: Observer): AutoCloseable fun request(observer: Observer, unavailable: () -> Unit, timeoutMillis: Int): AutoCloseable fun later(millis: Long, action: () -> Unit): AutoCloseable + /** + * Asks the platform to join a saved network by itself and returns how long to wait for it + * before requesting one; 0 when the platform needs no nudge. + */ + fun nudgePlatformJoin(): Long = 0 } val result = CompletableFuture>() var phase = Phase.IDENTIFYING @@ -36,6 +41,8 @@ internal class CarlinkWifiFlow(private val ssid: String, private val driver: private var observer: AutoCloseable? = null private var request: AutoCloseable? = null private var timer: AutoCloseable? = null + private var claim: AutoCloseable? = null + private var platformJoin = false private var generation = 0 private var observationGeneration = 0 private var selected: CarlinkWifiCandidate? = null @@ -48,9 +55,20 @@ internal class CarlinkWifiFlow(private val ssid: String, private val driver: fun start() { check(observer == null && phase == Phase.IDENTIFYING) observe() - if (phase == Phase.IDENTIFYING) timer = driver.later(IDENTIFY_MILLIS) { + if (phase != Phase.IDENTIFYING) return + val nudge = driver.nudgePlatformJoin() + timer = driver.later(IDENTIFY_MILLIS) { val matching = matching() - if (matching.size == 1) select(matching.single()) else automatic() + when { + matching.size == 1 -> select(matching.single()) + matching.isEmpty() && nudge > IDENTIFY_MILLIS -> { + // The platform joins the saved network within a second of the scan; adopting that + // link avoids the request, which is what raises MIUI's unanswerable dialog. + platformJoin = true + timer = driver.later(nudge - IDENTIFY_MILLIS) { platformJoin = false; automatic() } + } + else -> automatic() + } } } /** Re-read identities after returning from system settings or changing location permission. */ @@ -94,7 +112,15 @@ internal class CarlinkWifiFlow(private val ssid: String, private val driver: } // A network announced during request setup may be owned by that request. Its own callback // must select it, otherwise cancelling the pending request could destroy a borrowed link. - if (phase == Phase.AUTOMATIC) { automaticNetworks.add(candidate.network); return } + if (phase == Phase.AUTOMATIC) { + automaticNetworks.add(candidate.network) + if (match == WifiTargetMatch.SAME && candidate.endpoints != null) awaitClaim() + return + } + if (phase == Phase.IDENTIFYING && platformJoin && match == WifiTargetMatch.SAME && candidate.endpoints != null) { + if (matching().size == 1) select(candidate) + return + } if (phase == Phase.IDENTIFYING || candidate.endpoints == null || candidate.network in automaticNetworks) return if (match == WifiTargetMatch.SAME && matching().size == 1) select(candidate) else if (phase == Phase.MANUAL && match == WifiTargetMatch.UNKNOWN && unknownRetried.add(candidate.network)) { @@ -106,6 +132,29 @@ internal class CarlinkWifiFlow(private val ssid: String, private val driver: private fun matching() = candidates.values.filter { it.network !in automaticNetworks && it.match(ssid) == WifiTargetMatch.SAME && it.endpoints != null } + private fun unclaimed() = candidates.values.filter { + it.network in automaticNetworks && it.match(ssid) == WifiTargetMatch.SAME && it.endpoints != null + } + /** + * The request's own network reaches its callback in the same dispatch as the observer, so a target + * network the request has not claimed after [CLAIM_MILLIS] was joined by the platform itself (a saved + * network). Such a request never attaches; borrow the platform's link instead of waiting it out. + */ + private fun awaitClaim() { + if (claim != null) return + val token = generation + claim = driver.later(CLAIM_MILLIS) { + claim = null + if (generation != token || phase != Phase.AUTOMATIC) return@later + val unclaimed = unclaimed() + if (unclaimed.size != 1) return@later + ++generation + timer?.close(); timer = null + request?.close(); request = null + automaticNetworks.remove(unclaimed.single().network) + select(unclaimed.single()) + } + } private fun automatic() { if (phase !in setOf(Phase.IDENTIFYING, Phase.MANUAL)) return timer?.close(); timer = null @@ -131,13 +180,28 @@ internal class CarlinkWifiFlow(private val ssid: String, private val driver: if (generation != token || phase != Phase.AUTOMATIC) return ++generation timer?.close(); timer = null + claim?.close(); claim = null request?.close(); request = null transition(Phase.MANUAL) + // Once the request is gone its own network goes with it. What remains of the target was joined + // by the platform during the request; adopt it instead of waiting for a return to the app. + val token = generation + timer = driver.later(CLAIM_MILLIS) { + timer = null + if (generation != token || phase != Phase.MANUAL) return@later + val unclaimed = unclaimed() + if (unclaimed.size == 1 && matching().isEmpty()) { + automaticNetworks.remove(unclaimed.single().network) + select(unclaimed.single()) + } + } } private fun select(candidate: CarlinkWifiCandidate) { if (phase == Phase.CLOSED || phase == Phase.READY) return check(candidate.endpoints != null) timer?.close(); timer = null + claim?.close(); claim = null + platformJoin = false selected = candidate transition(Phase.READY) result.complete(candidate) @@ -153,12 +217,14 @@ internal class CarlinkWifiFlow(private val ssid: String, private val driver: ++observationGeneration transition(Phase.CLOSED) timer?.close(); timer = null + claim?.close(); claim = null request?.close(); request = null observer?.close(); observer = null result.cancel(false) } companion object { const val IDENTIFY_MILLIS = 250L + const val CLAIM_MILLIS = 2_000L const val AUTOMATIC_MILLIS = 45_000 } } diff --git a/android/app/src/test/java/org/openxplay/direlay/clink/AndroidCarlinkWifiTest.kt b/android/app/src/test/java/org/openxplay/direlay/clink/AndroidCarlinkWifiTest.kt index f96fdc03..a04dd686 100644 --- a/android/app/src/test/java/org/openxplay/direlay/clink/AndroidCarlinkWifiTest.kt +++ b/android/app/src/test/java/org/openxplay/direlay/clink/AndroidCarlinkWifiTest.kt @@ -70,6 +70,12 @@ class AndroidCarlinkWifiTest { callback.onLinkPropertiesChanged(network, links) callback.onCapabilitiesChanged(network, capabilities) } + @Test fun onlyMiuiOnAndroid10And11IsNudgedToJoinByItself() { + assertTrue(AndroidCarlinkWifi.miuiConfirmationDialog("Xiaomi", 29)) + assertTrue(AndroidCarlinkWifi.miuiConfirmationDialog("xiaomi", 30)) + assertFalse(AndroidCarlinkWifi.miuiConfirmationDialog("Xiaomi", 31)) + assertFalse(AndroidCarlinkWifi.miuiConfirmationDialog("OnePlus", 29)) + } @Test fun reusesAnIdentifiedSystemNetworkAndUnregistersWithoutReplacingIt() { flow().use { flow -> flow.start() diff --git a/android/app/src/test/java/org/openxplay/direlay/clink/CarlinkWifiFlowTest.kt b/android/app/src/test/java/org/openxplay/direlay/clink/CarlinkWifiFlowTest.kt index 84333513..21a6c682 100644 --- a/android/app/src/test/java/org/openxplay/direlay/clink/CarlinkWifiFlowTest.kt +++ b/android/app/src/test/java/org/openxplay/direlay/clink/CarlinkWifiFlowTest.kt @@ -17,6 +17,9 @@ class CarlinkWifiFlowTest { var requests = 0 var releases = 0 var unobserved = 0 + var nudge = 0L + var nudges = 0 + override fun nudgePlatformJoin(): Long { nudges++; return nudge } override fun observe(observer: CarlinkWifiFlow.Observer): AutoCloseable { this.observer = observer return AutoCloseable { unobserved++ } @@ -43,8 +46,8 @@ class CarlinkWifiFlowTest { private fun candidate(id: Int = 1, ssid: String? = "car", encrypted: Boolean? = true, peer: String? = "192.168.49.1", local: String? = "192.168.49.2") = CarlinkWifiCandidate(id, ssid, encrypted, peer, local) - private class Fixture { - val driver = Driver() + private class Fixture(nudge: Long = 0) { + val driver = Driver().also { it.nudge = nudge } val phases = mutableListOf() var losses = 0 val flow = CarlinkWifiFlow("car", driver, phases::add, { _, _ -> }, { losses++ }) @@ -171,4 +174,59 @@ class CarlinkWifiFlowTest { assertEquals(CarlinkWifiFlow.Phase.CLOSED, f.flow.phase) assertEquals(1, f.driver.releases); assertEquals(1, f.driver.unobserved) } + @Test fun thePlatformsOwnJoinAfterTheNudgeIsAdoptedWithoutARequest() { + val f = Fixture(nudge = 3_000); f.automatic() + assertEquals(1, f.driver.nudges) + assertEquals(0, f.driver.requests) + f.driver.advance(400) + f.driver.observer.changed(candidate()) + assertEquals(1, f.flow.result.get().network) + assertEquals(0, f.driver.requests) + f.driver.advance(10_000) + assertEquals(0, f.driver.requests) + assertFalse(CarlinkWifiFlow.Phase.AUTOMATIC in f.phases) + } + @Test fun withoutAJoinTheNudgeWindowEndsInTheExactTargetRequest() { + val f = Fixture(nudge = 3_000) + f.driver.advance(2_999); assertEquals(0, f.driver.requests) + f.driver.advance(1); assertEquals(1, f.driver.requests) + f.driver.observer.changed(candidate(ssid = "other")) + assertFalse(f.flow.result.isDone) + } + @Test fun aTargetTheRequestNeverClaimsIsBorrowedFromThePlatform() { + val f = Fixture(); f.automatic() + f.driver.observer.changed(candidate()) + f.driver.advance(CarlinkWifiFlow.CLAIM_MILLIS - 1) + assertFalse(f.flow.result.isDone) + f.driver.advance(1) + assertEquals(1, f.flow.result.get().network) + assertEquals(1, f.driver.releases) + assertFalse(CarlinkWifiFlow.Phase.MANUAL in f.phases) + f.driver.requested.changed(candidate(2)) + assertEquals(1, f.flow.result.get().network) + } + @Test fun twoUnclaimedTargetsAreNeverBorrowed() { + val f = Fixture(); f.automatic() + f.driver.observer.changed(candidate(1)); f.driver.observer.changed(candidate(2)) + f.driver.advance(CarlinkWifiFlow.CLAIM_MILLIS) + assertFalse(f.flow.result.isDone) + assertEquals(0, f.driver.releases) + } + @Test fun afterTheRequestEndsTheTargetThePlatformJoinedIsAdopted() { + val f = Fixture(); f.automatic() + f.driver.observer.changed(candidate(2)) + f.driver.unavailable() + assertEquals(CarlinkWifiFlow.Phase.MANUAL, f.flow.phase) + f.driver.advance(CarlinkWifiFlow.CLAIM_MILLIS) + assertEquals(2, f.flow.result.get().network) + } + @Test fun theRequestsOwnNetworkGoingAwayIsNotAdoptedAfterTheRequestEnds() { + val f = Fixture(); f.automatic() + f.driver.observer.changed(candidate(2)) + f.driver.unavailable() + f.driver.observer.lost(2) + f.driver.advance(CarlinkWifiFlow.CLAIM_MILLIS) + assertFalse(f.flow.result.isDone) + assertEquals(CarlinkWifiFlow.Phase.MANUAL, f.flow.phase) + } } From e64ba734d73586d1926ee9b786d87bf81171c749 Mon Sep 17 00:00:00 2001 From: Riko Date: Wed, 4 Nov 2026 21:32:22 -0800 Subject: [PATCH 14/17] Media keys: advertise only the keys CarPlay accepts 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). --- .../openxplay/direlay/bridge/DiPlayInput.kt | 4 +++- .../direlay/bridge/DiPlayInputTest.kt | 24 ++++++++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/android/app/src/main/java/org/openxplay/direlay/bridge/DiPlayInput.kt b/android/app/src/main/java/org/openxplay/direlay/bridge/DiPlayInput.kt index 706761ed..19152363 100644 --- a/android/app/src/main/java/org/openxplay/direlay/bridge/DiPlayInput.kt +++ b/android/app/src/main/java/org/openxplay/direlay/bridge/DiPlayInput.kt @@ -23,7 +23,7 @@ class DiPlayInput(private val applyFrameRate: (Double) -> Unit = {}, private val private val mediaKeysForwarding: () -> Boolean = { false }) : ProjectionInput, AutoCloseable { @Volatile override var capabilities = InputCapabilities( setOf(VideoCodec.H264, VideoCodec.H265), setOf(ScreenId.MAIN), - touch = true, keys = KeyCode.entries.toSet(), microphone = false, + touch = true, keys = MEDIA_KEYS, microphone = false, keyFrameRequests = true, reconfigure = ReconfigureCost.RESTART_SESSION, ) private set @@ -320,3 +320,5 @@ class DiPlayInput(private val applyFrameRate: (Double) -> Unit = {}, private val } private const val TAG = "OpenXPlay Relay" +/** The steering-wheel keys CarPlay accepts as media HID presses; the rest stay with the head unit. */ +private val MEDIA_KEYS = setOf(KeyCode.PLAY_PAUSE, KeyCode.NEXT, KeyCode.PREVIOUS) diff --git a/android/app/src/test/java/org/openxplay/direlay/bridge/DiPlayInputTest.kt b/android/app/src/test/java/org/openxplay/direlay/bridge/DiPlayInputTest.kt index 2a4bb909..f60fa8c8 100644 --- a/android/app/src/test/java/org/openxplay/direlay/bridge/DiPlayInputTest.kt +++ b/android/app/src/test/java/org/openxplay/direlay/bridge/DiPlayInputTest.kt @@ -5,6 +5,7 @@ package org.openxplay.direlay.bridge import com.shilapi.xcertplay.airplay.AirPlayContact import com.shilapi.xcertplay.airplay.MediaSink +import com.shilapi.xcertplay.airplay.CarPlayMediaButton import com.shilapi.xcertplay.airplay.SessionControl import com.shilapi.xcertplay.orchestration.CarPlayHostUiHandler import com.shilapi.xcertplay.orchestration.CarPlayStatus @@ -202,6 +203,27 @@ class DiPlayInputTest { } } + @Test fun mediaKeysReachTheCurrentSessionOncePerPressOnlyWhileCarPlayCarriesTheAudio() { + var forwarding = false + val pressed = mutableListOf() + val control = object : SessionControl { + override fun sendTouch(contacts: List) = false + override fun sendMediaButton(index: Int): Boolean { pressed.add(index); return true } + } + DiPlayInput(mediaKeysForwarding = { forwarding }).use { input -> + fun key(code: KeyCode, down: Boolean = true) = input.control(ControlEvent.Key(code, down, origin)) + input.start(configuration, CapturingInputSink()) + input.begin(control) + assertFalse(key(KeyCode.NEXT)) + forwarding = true + assertTrue(key(KeyCode.NEXT)); assertFalse(key(KeyCode.NEXT, down = false)) + assertTrue(key(KeyCode.PREVIOUS)); assertTrue(key(KeyCode.PLAY_PAUSE)) + assertFalse(key(KeyCode.HOME)) + input.stop(); assertFalse(key(KeyCode.NEXT)) + assertEquals(listOf(CarPlayMediaButton.NEXT, CarPlayMediaButton.PREVIOUS, CarPlayMediaButton.PLAY_PAUSE), pressed) + } + } + @Test fun viewAreaCommandsUseOnlyTheCurrentDecoratedSession() { DiPlayInput().use { input -> val calls = mutableListOf() @@ -245,7 +267,7 @@ class DiPlayInputTest { assertEquals(setOf(ScreenId.MAIN), input.capabilities.screens) assertTrue(input.capabilities.touch) assertTrue(input.capabilities.keyFrameRequests) - assertEquals(KeyCode.entries.toSet(), input.capabilities.keys) + assertEquals(setOf(KeyCode.PLAY_PAUSE, KeyCode.NEXT, KeyCode.PREVIOUS), input.capabilities.keys) assertFalse(input.capabilities.microphone) assertEquals(ReconfigureCost.RESTART_SESSION, input.capabilities.reconfigure) assertEquals(ReconfigureResult.RESTART_SESSION, input.reconfigure(configuration)) From 5411dfefe175d26872b8d23160b3dae35e5edb21 Mon Sep 17 00:00:00 2001 From: Riko Date: Wed, 4 Nov 2026 21:33:31 -0800 Subject: [PATCH 15/17] Audio: a stream DiPlay stopped stays stopped 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. --- .../direlay/bridge/StreamBridgeSink.kt | 7 +++++-- .../direlay/bridge/AudioBridgeTest.kt | 20 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/android/app/src/main/java/org/openxplay/direlay/bridge/StreamBridgeSink.kt b/android/app/src/main/java/org/openxplay/direlay/bridge/StreamBridgeSink.kt index 5ebdae86..4a630eda 100644 --- a/android/app/src/main/java/org/openxplay/direlay/bridge/StreamBridgeSink.kt +++ b/android/app/src/main/java/org/openxplay/direlay/bridge/StreamBridgeSink.kt @@ -30,6 +30,8 @@ class StreamBridgeSink( private val session = input.begin(control) private val audio = mutableMapOf>() private val audioTails = mutableMapOf() + /** Streams DiPlay stopped; their late packets must not start them again. */ + private val stoppedAudio = mutableSetOf() private val microphoneIds = mutableMapOf() private val microphoneTails = mutableMapOf() private val localMicrophones = mutableMapOf>() @@ -45,7 +47,7 @@ class StreamBridgeSink( val stream = AudioPolicy.stream(id) ?: return Log.i("OXP-Audio", "stream_start stream=$stream type=${id.type} codec=${format.codec} " + "rate=${format.sampleRate} ch=${format.channels} firstSample=$firstSample") - input.deliver(session) { sink -> startAudioStream(id, stream, format, firstSample, sink) } + input.deliver(session) { sink -> stoppedAudio.remove(id); startAudioStream(id, stream, format, firstSample, sink) } } /** @@ -87,7 +89,7 @@ class StreamBridgeSink( // missed it and every packet was dropped by offer() (measured: 1026 packets lost // between arrival and the queue). Rebuild whenever the stream is missing or stopped. val existing = audio[stream]?.takeIf { it.first == id } - if (existing == null || !existing.second.isRunning()) { + if (id !in stoppedAudio && (existing == null || !existing.second.isRunning())) { Log.i("OXP-Audio", "stream_lazy_start stream=$stream type=${id.type} sample=$sample " + "reason=${if (existing == null) "absent" else "stopped"}") startAudioStream(id, stream, format, sample, sink) @@ -100,6 +102,7 @@ class StreamBridgeSink( val stream = AudioPolicy.stream(id) ?: return Log.i("OXP-Audio", "stream_stop stream=$stream type=${id.type}") input.deliver(session) { sink -> + stoppedAudio.add(id) if (audio[stream]?.first == id) { audio.remove(stream)?.second?.close() if (session.audio.remove(stream)) sink.audioFormat(stream, null) diff --git a/android/app/src/test/java/org/openxplay/direlay/bridge/AudioBridgeTest.kt b/android/app/src/test/java/org/openxplay/direlay/bridge/AudioBridgeTest.kt index d7f6ca75..6a308c86 100644 --- a/android/app/src/test/java/org/openxplay/direlay/bridge/AudioBridgeTest.kt +++ b/android/app/src/test/java/org/openxplay/direlay/bridge/AudioBridgeTest.kt @@ -58,6 +58,26 @@ class AudioBridgeTest { assertEquals(2, capture.audio.size) } } + @Test fun aStreamDiPlayKeptAcrossAReconnectStartsOnItsFirstPacketButAStoppedOneStaysStopped() { + DiPlayInput().use { input -> + val capture = Capture(); input.start(configuration, capture) + val id = AudioStreamId(102, "media") + val format = CarPlayAudioFormat(AudioCodecKind.AAC_LC, 48000, 2, 102) + // A reconnect builds a new bridge while DiPlay keeps the stream: no onAudioStarted. + val bridge = StreamBridgeSink(input, object : MediaSink {}, SessionControl { true }) + bridge.onAudioRtp(id, format, ByteArray(12) + hex("21 43 65"), 0) + assertTrue(capture.packetReady.await(2, TimeUnit.SECONDS)) + assertEquals(1, capture.audio.size) + bridge.onAudioStopped(id) + assertEquals(2, capture.audio.size) + bridge.onAudioRtp(id, format, ByteArray(12) + hex("21 43 65"), 1024) + bridge.onAudioStopped(AudioStreamId(999, "media")) + assertEquals(2, capture.audio.size) + assertEquals(1, capture.packets.size) + bridge.onAudioStarted(id, format, 2048) + assertEquals(3, capture.audio.size) + } + } @Test fun voiceLpcmIsSwappedOnTheWorkerAndStoppedExplicitly() { DiPlayInput().use { input -> val capture = Capture(); input.start(configuration, capture) From bc0b010ea5b86bb62bc1ed01acaa3725cd54476d Mon Sep 17 00:00:00 2001 From: Riko Date: Wed, 4 Nov 2026 21:34:05 -0800 Subject: [PATCH 16/17] Relay phone: CarPlay page follows the rotation lock; Back on Home leaves - 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). --- android/app/src/main/AndroidManifest.xml | 18 ++------ .../java/org/openxplay/direlay/HomeBack.kt | 37 +++++++++++++++ .../org/openxplay/direlay/RelayActivity.kt | 3 ++ .../org/openxplay/direlay/HomeBackTest.kt | 46 +++++++++++++++++++ 4 files changed, 91 insertions(+), 13 deletions(-) create mode 100644 android/app/src/main/java/org/openxplay/direlay/HomeBack.kt create mode 100644 android/app/src/test/java/org/openxplay/direlay/HomeBackTest.kt diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 406b2665..ea698221 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -106,17 +106,11 @@ - - + + + diff --git a/android/app/src/main/java/org/openxplay/direlay/HomeBack.kt b/android/app/src/main/java/org/openxplay/direlay/HomeBack.kt new file mode 100644 index 00000000..3d3ce792 --- /dev/null +++ b/android/app/src/main/java/org/openxplay/direlay/HomeBack.kt @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: 2026 OpenXPlay.org +// SPDX-License-Identifier: AGPL-3.0-only +// Created by riko chen on 2026-11-04 +package org.openxplay.direlay + +import android.app.ActivityManager +import android.content.Intent +import androidx.activity.ComponentActivity +import androidx.activity.OnBackPressedCallback +import com.shilapi.xcertplay.CarPlayHostActivity +import com.shilapi.xcertplay.SameTaskCarPlayHostActivity + +/** + * The running page (DiPlay's CarPlay host) is a page above Home, but it lives in its own task under Relay's + * when Home was opened from it. Back on Home would move Relay's task back and show the running page again, + * so while that task exists Back on Home leaves for the launcher. Pages and the drawer handle Back first. + */ +internal class HomeBack(private val activity: ComponentActivity) : OnBackPressedCallback(false) { + /** Call when Home comes to the front; the running page's task cannot appear while Home is in front. */ + fun refresh() { + isEnabled = runningPageBehind(runCatching { + activity.getSystemService(ActivityManager::class.java)?.appTasks.orEmpty() + .map { task -> runCatching { task.taskInfo?.baseActivity?.className }.getOrNull() } + }.getOrDefault(emptyList())) + } + + override fun handleOnBackPressed() { + val launcher = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + if (runCatching { activity.startActivity(launcher) }.isFailure) activity.moveTaskToBack(true) + } + + companion object { + private val hosts = setOf(CarPlayHostActivity::class.java.name, SameTaskCarPlayHostActivity::class.java.name) + + fun runningPageBehind(baseActivities: List): Boolean = baseActivities.any { it in hosts } + } +} diff --git a/android/app/src/main/java/org/openxplay/direlay/RelayActivity.kt b/android/app/src/main/java/org/openxplay/direlay/RelayActivity.kt index d8d5ae54..ede15a1c 100644 --- a/android/app/src/main/java/org/openxplay/direlay/RelayActivity.kt +++ b/android/app/src/main/java/org/openxplay/direlay/RelayActivity.kt @@ -62,6 +62,7 @@ class RelayActivity : androidx.activity.ComponentActivity() { * the head unit dies with it — and the wait that follows then has nothing left to find it with. */ private var keepAwakeForLink = false + private val homeBack = HomeBack(this) private val identityImport by lazy { androidx.lifecycle.ViewModelProvider(this)[IdentityImportState::class.java] } private var identityDialog: AlertDialog? = null private var dialogVisible by androidx.compose.runtime.mutableStateOf(false) @@ -114,6 +115,7 @@ class RelayActivity : androidx.activity.ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) animateSplashExit() + onBackPressedDispatcher.addCallback(this, homeBack) if (identityImport.uri == null) { identityImport.uri = savedInstanceState?.getString("identityUri")?.let(Uri::parse) identityImport.kind = savedInstanceState?.getString("identityKind")?.let(IdentityKind::valueOf) ?: IdentityKind.UNKNOWN @@ -783,6 +785,7 @@ class RelayActivity : androidx.activity.ComponentActivity() { override fun onResume() { super.onResume() + homeBack.refresh() presentation.action { runtime.keepAlive.uiVisible() } resumed = true dialogs.active = !requestingPermissions && !pairingInFlight diff --git a/android/app/src/test/java/org/openxplay/direlay/HomeBackTest.kt b/android/app/src/test/java/org/openxplay/direlay/HomeBackTest.kt new file mode 100644 index 00000000..fdf809e7 --- /dev/null +++ b/android/app/src/test/java/org/openxplay/direlay/HomeBackTest.kt @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: 2026 OpenXPlay.org +// SPDX-License-Identifier: AGPL-3.0-only +// Created by riko chen on 2026-11-04 +package org.openxplay.direlay + +import android.app.Application +import android.content.Intent +import androidx.activity.ComponentActivity +import com.shilapi.xcertplay.CarPlayHostActivity +import com.shilapi.xcertplay.SameTaskCarPlayHostActivity +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], application = Application::class) +class HomeBackTest { + @Test fun eitherCarPlayHostBehindHomeIsTheRunningPage() { + assertTrue(HomeBack.runningPageBehind(listOf(RelayActivity::class.java.name, CarPlayHostActivity::class.java.name))) + assertTrue(HomeBack.runningPageBehind(listOf(null, SameTaskCarPlayHostActivity::class.java.name))) + assertFalse(HomeBack.runningPageBehind(listOf(RelayActivity::class.java.name, null))) + assertFalse(HomeBack.runningPageBehind(emptyList())) + } + + @Test fun withoutTheRunningPageHomeKeepsTheSystemBack() { + val activity = Robolectric.buildActivity(ComponentActivity::class.java).setup().get() + val back = HomeBack(activity).also { activity.onBackPressedDispatcher.addCallback(activity, it) } + back.refresh() + assertFalse(back.isEnabled) + } + + @Test fun backWithTheRunningPageBehindOpensTheLauncher() { + val activity = Robolectric.buildActivity(ComponentActivity::class.java).setup().get() + val back = HomeBack(activity).also { activity.onBackPressedDispatcher.addCallback(activity, it) } + back.isEnabled = true + activity.onBackPressedDispatcher.onBackPressed() + val started = shadowOf(activity).nextStartedActivity + assertEquals(Intent.ACTION_MAIN, started.action) + assertTrue(started.hasCategory(Intent.CATEGORY_HOME)) + assertFalse(activity.isFinishing) + } +} From cf87a69d32a9aeae0fe8bbf93217effacbcbace4 Mon Sep 17 00:00:00 2001 From: Riko Date: Wed, 4 Nov 2026 21:46:42 -0800 Subject: [PATCH 17/17] Pin OpenXPlay-DiPlay 341d0e0d8aba: a turn of the relay phone no longer rebuilds CarPlay --- diplay.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/diplay.lock b/diplay.lock index 9e722a32..7acd6947 100644 --- a/diplay.lock +++ b/diplay.lock @@ -1 +1 @@ -35a7d07d44acce9c04fcd0fa8045a9f20e547f93 +341d0e0d8aba933f2550267e951107e6816f080f