diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 0da3487..ea69822 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -106,6 +106,12 @@ + + + + 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 330c82d..ede15a1 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,13 @@ 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 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) @@ -108,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 @@ -134,6 +142,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 { @@ -731,6 +756,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) @@ -758,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/main/java/org/openxplay/direlay/bridge/AudioPolicy.kt b/android/app/src/main/java/org/openxplay/direlay/bridge/AudioPolicy.kt index d7399b7..c9f7bf5 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/DiPlayInput.kt b/android/app/src/main/java/org/openxplay/direlay/bridge/DiPlayInput.kt index b18bfb8..1915236 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 = MEDIA_KEYS, 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 @@ -297,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/main/java/org/openxplay/direlay/bridge/RelayAudioStream.kt b/android/app/src/main/java/org/openxplay/direlay/bridge/RelayAudioStream.kt index c9bdbbe..15ada4c 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)) 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 0072eb5..4a630ed 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>() @@ -43,39 +45,64 @@ 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 -> stoppedAudio.remove(id); 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 (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) + } + 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 -> + 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/main/java/org/openxplay/direlay/clink/AndroidCarlinkWifi.kt b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidCarlinkWifi.kt index 548af30..f2f46e5 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/AndroidClinkLink.kt b/android/app/src/main/java/org/openxplay/direlay/clink/AndroidClinkLink.kt index 8759a76..0d2ceec 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,51 @@ 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) + /** + * 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 + /** 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 + /** + * 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 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 + /** 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) @@ -53,7 +100,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() @@ -78,6 +127,47 @@ 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) + } + /** MIUI's unanswerable confirmation dialog only: see the comment at the call site. */ + private val scanAdoptJoin: Boolean get() = 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) } @@ -91,6 +181,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 @@ -105,6 +197,8 @@ class AndroidClinkLink(context: Context, private val deviceId: String, var receiver: BroadcastReceiver? = null var wifiFlow: AndroidCarlinkWifi? = 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 @@ -120,6 +214,20 @@ 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 + /** + * 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. + */ + 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]") } @@ -157,15 +265,37 @@ 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) + 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(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) { @@ -196,17 +326,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(), @@ -219,6 +359,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)) } } @@ -228,6 +369,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)) { @@ -277,7 +451,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) @@ -285,7 +472,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 } } @@ -522,10 +711,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 { @@ -546,7 +736,7 @@ class AndroidClinkLink(context: Context, private val deviceId: String, } } if (method != WifiJoinPolicy.Method.NETWORK_SPECIFIER) throw ClinkFailure(ClinkFailureReason.WIFI_UNAVAILABLE) - return if (wifiRecovery) joinRecoverableWifi(run, reply) else joinSpecifier(run, reply) + return if (wifiRecovery) joinRecoverableWifi(run, reply) else joinSpecifier(run, reply, budgetMs) } private fun joinRecoverableWifi(run: Run, reply: HeadUnitReply): Pair { val flow = AndroidCarlinkWifi(context, handler, reply, diagnostics) { lost(run) } @@ -615,8 +805,41 @@ class AndroidClinkLink(context: Context, private val deviceId: String, } return await(run, result, 7) } - private fun joinSpecifier(run: Run, reply: HeadUnitReply): Pair { - primeScanCache(run, reply.ssid) + 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 + // 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 } + // 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) + 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 (primeSawTarget() && 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) @@ -643,13 +866,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) @@ -667,9 +884,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, + (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 { + 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 } + } + } + + /** + * 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 } - return await(run, result, 13) + 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() } } /** @@ -680,30 +1008,58 @@ 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) { - 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. + lastPrimeSawAt = 0L + val cached = wifi.scanResults ?: return 0 + if (cached.any { it.SSID == ssid }) { + lastPrimeSawAt = SystemClock.elapsedRealtime() + 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; lastPrimeSawAt = SystemClock.elapsedRealtime(); 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 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 @@ -743,6 +1099,8 @@ class AndroidClinkLink(context: Context, private val deviceId: String, } private fun releaseNetwork(run: Run) { run.wifiFlow?.close(); run.wifiFlow = null + 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. @@ -802,6 +1160,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 b8aa12c..25469a1 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/clink/CarlinkWifiFlow.kt b/android/app/src/main/java/org/openxplay/direlay/clink/CarlinkWifiFlow.kt index b617405..953f1c8 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/main/java/org/openxplay/direlay/logs/NetworkTimeline.kt b/android/app/src/main/java/org/openxplay/direlay/logs/NetworkTimeline.kt index 8da2694..371467f 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 } 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 17ff7ee..aac600b 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 @@ -5,6 +5,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 @@ -19,7 +22,7 @@ class CarlinkStartGate { if (!outputEnabled) throw IOException("Carlink output was disabled while waiting to start CarPlay") if (outputReady) { cancel(); return true } if (waitingForWifi) { untilMillis = nowMillis + MAX_WAIT_MILLIS; return false } - 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 dc1b17d..445aa14 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 { @@ -746,6 +749,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, @@ -836,6 +840,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 ee0bdec..f2ec612 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, @@ -276,6 +299,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") @@ -333,4 +367,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) + } } 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 0000000..fdf809e --- /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) + } +} 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 d7f6ca7..6a308c8 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) 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 43f13d2..4747b67 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)) 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 1789de6..f60fa8c 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) - assertTrue(input.capabilities.keys.isEmpty()) + 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)) 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 f96fdc0..a04dd68 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 8433351..21a6c68 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) + } } diff --git a/diplay.lock b/diplay.lock index 9e722a3..7acd694 100644 --- a/diplay.lock +++ b/diplay.lock @@ -1 +1 @@ -35a7d07d44acce9c04fcd0fa8045a9f20e547f93 +341d0e0d8aba933f2550267e951107e6816f080f