Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
54a45b7
Android: rebuild the Carlink audio stream after a reconnect, and stop…
hellowalker Nov 2, 2026
f512e6b
Android: keep local-playback stop on flag flip, widen the audio re-an…
hellowalker Nov 2, 2026
cdabde6
Android: reuse the Wi-Fi link the platform already joined
hellowalker Nov 2, 2026
a34c975
Android: prime the scan cache once, and skip the request when MIUI ca…
hellowalker Nov 2, 2026
143a517
Android: forward Carlink steering-wheel media keys to CarPlay
hellowalker Nov 2, 2026
9d8c6f0
Android: assert the advertised KeyCode set, not an empty one
hellowalker Nov 3, 2026
3f89630
Android: keep the stored subscription choice when the GATT link fails
hellowalker Nov 3, 2026
b062183
Android: report what the Carlink link is doing while it looks stuck
hellowalker Nov 3, 2026
c627509
Android: keep waiting for Carlink instead of failing the start
hellowalker Nov 3, 2026
f44a75f
Android: keep the display awake while a Carlink link is coming up
hellowalker Nov 3, 2026
f89389c
Android: retry the Wi-Fi join without repeating the BLE exchange
hellowalker Nov 3, 2026
27b9edb
Android: join the head-unit access point without the Wi-Fi dialog
hellowalker Nov 3, 2026
e0c142a
Merge pull request #108 from hellowalker
riko2chen Nov 5, 2026
1e81074
Merge pull request #109 from hellowalker
riko2chen Nov 5, 2026
f016e66
Merge pull request #104 from hellowalker
riko2chen Nov 5, 2026
3c9eb10
Merge pull request #110 from hellowalker
riko2chen Nov 5, 2026
eeceec7
Merge pull request #111 from hellowalker
riko2chen Nov 5, 2026
2cfe193
Merge pull request #105 from hellowalker
riko2chen Nov 5, 2026
c7c6af7
Merge pull request #107 from hellowalker
riko2chen Nov 5, 2026
2f6c2c3
Merge pull request #103 from hellowalker
riko2chen Nov 5, 2026
ab6329d
Carlink Wi-Fi recovery: adopt the head-unit network the phone joined …
riko2chen Nov 5, 2026
e64ba73
Media keys: advertise only the keys CarPlay accepts
riko2chen Nov 5, 2026
5411dfe
Audio: a stream DiPlay stopped stays stopped
riko2chen Nov 5, 2026
bc0b010
Relay phone: CarPlay page follows the rotation lock; Back on Home leaves
riko2chen Nov 5, 2026
8c0a84f
Merge remote-tracking branch 'origin/main' into feature/carlink-commu…
riko2chen Nov 5, 2026
cf87a69
Pin OpenXPlay-DiPlay 341d0e0d8aba: a turn of the relay phone no longe…
riko2chen Nov 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,12 @@
<intent-filter tools:node="removeAll" />
</activity>

<!-- DiPlay's host turns with the sensor on head units; on the relay phone it follows the rotation lock. -->
<activity android:name="com.shilapi.xcertplay.CarPlayHostActivity"
android:screenOrientation="fullUser" tools:replace="android:screenOrientation" />
<activity android:name="com.shilapi.xcertplay.SameTaskCarPlayHostActivity"
android:screenOrientation="fullUser" tools:replace="android:screenOrientation" />


<activity
android:name=".RelayActivity"
Expand Down
37 changes: 37 additions & 0 deletions android/app/src/main/java/org/openxplay/direlay/HomeBack.kt
Original file line number Diff line number Diff line change
@@ -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<String?>): Boolean = baseActivities.any { it in hosts }
}
}
28 changes: 28 additions & 0 deletions android/app/src/main/java/org/openxplay/direlay/RelayActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ class StreamBridgeSink(
private val session = input.begin(control)
private val audio = mutableMapOf<Int, Pair<AudioStreamId, RelayAudioStream>>()
private val audioTails = mutableMapOf<Int, RelayAudioStream>()
/** Streams DiPlay stopped; their late packets must not start them again. */
private val stoppedAudio = mutableSetOf<AudioStreamId>()
private val microphoneIds = mutableMapOf<Int, AudioStreamId>()
private val microphoneTails = mutableMapOf<Int, DelegatedMicrophone>()
private val localMicrophones = mutableMapOf<Int, Pair<AudioStreamId, DelegatedMicrophone>>()
Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading