Car fixes from user logs: a Mazda that hangs up after the reverse camera, a Peugeot's black bar, a Sony stuck on discovery, a Ford Transit's blank screen, and a Citroen's Bluetooth music

This commit is contained in:
Seb3thehacker committed 2026-11-24 00:13:04 -08:00
1 parent 10db44f681
commit 91bb654b74
4 files changed
+128 -9

No files matched your search

@@ -178,7 +178,7 @@ class GearslipRunner(
} finally { } finally {
// The car hung up between our service discovery request and its answer: try the // The car hung up between our service discovery request and its answer: try the
// other kind of request with this car next time (see [ServiceDiscoveryQuirks]). // other kind of request with this car next time (see [ServiceDiscoveryQuirks]).
if (!stopped && state == State.WAIT_SDR) ServiceDiscoveryQuirks.droppedAfter(tls.headUnitKey, plainDiscovery) if (!stopped && state == State.WAIT_SDR) switchDiscovery("hung up")
running = false running = false
// The car is gone, but nothing calls stop() when a wireless session drops: it waits // The car is gone, but nothing calls stop() when a wireless session drops: it waits
// for the next one. Close the music channel now, so the audio capture behind it, // for the next one. Close the music channel now, so the audio capture behind it,
@@ -349,6 +349,7 @@ class GearslipRunner(
} }
log.w("<- ByeByeRequest: reason=$reason ($name) in state $state") log.w("<- ByeByeRequest: reason=$reason ($name) in state $state")
log.hex(" byebye raw", body) log.hex(" byebye raw", body)
if (System.currentTimeMillis() - restartSentAt < RESTART_HANGUP_MS) VideoRestartQuirks.hungUpAfterRestart(tls.headUnitKey)
SessionReport.fail(SessionReport.Category.BYEBYE, "ByeByeRequest reason=$reason ($name)", state.name, "bye $reason") SessionReport.fail(SessionReport.Category.BYEBYE, "ByeByeRequest reason=$reason ($name)", state.name, "bye $reason")
send(MSG_BYEBYE_RESPONSE, ByteArray(0), encrypted = state == State.WAIT_SDR || state == State.DONE) send(MSG_BYEBYE_RESPONSE, ByteArray(0), encrypted = state == State.WAIT_SDR || state == State.DONE)
log.i("-> ByeByeResponse") log.i("-> ByeByeResponse")
@@ -511,9 +512,26 @@ class GearslipRunner(
Protobuf.stringField(5, Build.MODEL) // device_name Protobuf.stringField(5, Build.MODEL) // device_name
if (!plainDiscovery) body += Protobuf.bytesField(6, Protobuf.stringField(1, java.util.UUID.randomUUID().toString())) // session ID if (!plainDiscovery) body += Protobuf.bytesField(6, Protobuf.stringField(1, java.util.UUID.randomUUID().toString())) // session ID
send(MSG_SERVICE_DISCOVERY_REQUEST, body, encrypted = true) send(MSG_SERVICE_DISCOVERY_REQUEST, body, encrypted = true)
discoverySentAt = System.currentTimeMillis()
log.i("-> ServiceDiscoveryRequest (encrypted, ${if (plainDiscovery) "short, as this car asked" else "${icons.size} icons"}, ${body.size} bytes)") log.i("-> ServiceDiscoveryRequest (encrypted, ${if (plainDiscovery) "short, as this car asked" else "${icons.size} icons"}, ${body.size} bytes)")
} }
@Volatile private var discoverySentAt = 0L
@Volatile private var discoverySwitched = false
/**
* The car didn't answer this session's service discovery request: next time it gets the other
* kind. Once a session at most, so a car that goes quiet and then hangs up isn't switched twice,
* back to the request it ignored. A Sony XAV-AX6000 kept up its pings for over a minute
* without ever answering (issue #107).
*/
private fun switchDiscovery(why: String) {
if (discoverySwitched) return
discoverySwitched = true
log.i("service discovery: the car $why without answering")
ServiceDiscoveryQuirks.droppedAfter(tls.headUnitKey, plainDiscovery)
}
private fun onServiceDiscoveryResponse(body: ByteArray) { private fun onServiceDiscoveryResponse(body: ByteArray) {
if (state != State.WAIT_SDR) return if (state != State.WAIT_SDR) return
log.i("<- ServiceDiscoveryResponse (${body.size} bytes, decrypted successfully)") log.i("<- ServiceDiscoveryResponse (${body.size} bytes, decrypted successfully)")
@@ -644,6 +662,7 @@ class GearslipRunner(
) )
// A car known to switch Bluetooth music off gets it through Gearslip, whatever the setting. // A car known to switch Bluetooth music off gets it through Gearslip, whatever the setting.
CarSettings.carConnected(ServiceDiscovery.findBluetoothService(serviceDiscoveryResponse)?.carAddress) CarSettings.carConnected(ServiceDiscovery.findBluetoothService(serviceDiscoveryResponse)?.carAddress)
BluetoothAudioCheck.onCarFound()
if (CarSettings.pipesNow) { if (CarSettings.pipesNow) {
if (!CarSettings.pipeAudio.value) log.i("this car turns Bluetooth music off, so music goes through Gearslip") if (!CarSettings.pipeAudio.value) log.i("this car turns Bluetooth music off, so music goes through Gearslip")
openChannel(media.serviceId) openChannel(media.serviceId)
@@ -1149,7 +1168,7 @@ class GearslipRunner(
* (touchscreen 0x0) blurred 800x480 across a 1080p screen. * (touchscreen 0x0) blurred 800x480 across a 1080p screen.
*/ */
private fun fitToScreen(offered: List<Int>): Int? { private fun fitToScreen(offered: List<Int>): Int? {
val known = offered.filter { videoConfigs.getOrNull(it)?.pixelSize() != null } val known = sameShape(offered.filter { videoConfigs.getOrNull(it)?.pixelSize() != null })
fun pixels(idx: Int) = videoConfigs[idx].pixelCount() fun pixels(idx: Int) = videoConfigs[idx].pixelCount()
if (touchWidth <= 0) { if (touchWidth <= 0) {
return known.filter { pixels(it) <= 1920 * 1080 }.maxByOrNull(::pixels) return known.filter { pixels(it) <= 1920 * 1080 }.maxByOrNull(::pixels)
@@ -1159,6 +1178,23 @@ class GearslipRunner(
return wide.minByOrNull(::pixels) ?: known.maxByOrNull(::pixels) return wide.minByOrNull(::pixels) ?: known.maxByOrNull(::pixels)
} }
/**
* The offered sizes whose visible part has the same shape as the largest one's. A Peugeot's
* Marelli unit shows 3:1 at 1920x1080 and 1280x720, but its 800x480 leaves an 800x320 strip,
* 2.5:1, which it stretched to full height with a black bar beside it (issue #127). All of
* them, when none match.
*/
private fun sameShape(known: List<Int>): List<Int> {
fun shape(idx: Int): Double? = videoConfigs[idx].visibleSize()
?.takeIf { it.first > 0 && it.second > 0 }
?.let { it.first.toDouble() / it.second }
val largest = known.maxByOrNull { videoConfigs[it].pixelCount() } ?: return known
val want = shape(largest) ?: return known
val alike = known.filter { idx -> shape(idx)?.let { kotlin.math.abs(it / want - 1) < 0.05 } ?: false }
if (alike.size < known.size) log.i("video: leaving out sizes whose visible part isn't shaped like the largest one's")
return alike.ifEmpty { known }
}
/** /**
* The part of a [frameWidth] x [frameHeight] frame shaped like the screen size set in * The part of a [frameWidth] x [frameHeight] frame shaped like the screen size set in
* Settings, centred and in even pixels; null when none is set or it is the frame's own shape. * Settings, centred and in even pixels; null when none is set or it is the frame's own shape.
@@ -1332,6 +1368,9 @@ class GearslipRunner(
/** Whether the car is showing Gearslip; false while it shows its own interface. */ /** Whether the car is showing Gearslip; false while it shows its own interface. */
@Volatile private var videoProjected = true @Volatile private var videoProjected = true
/** When the stream was last restarted after the car handed its screen back; 0 for never. */
@Volatile private var restartSentAt = 0L
/** The encoder's SPS/PPS, resent when the car hands its screen back. */ /** The encoder's SPS/PPS, resent when the car hands its screen back. */
@Volatile private var lastCodecConfig: ByteArray? = null @Volatile private var lastCodecConfig: ByteArray? = null
@@ -1362,12 +1401,19 @@ class GearslipRunner(
inFlight = 0 inFlight = 0
ackLock.notifyAll() ackLock.notifyAll()
} }
val start = Protobuf.varintField(1, SESSION_ID.toLong()) + if (VideoRestartQuirks.pausesOnly(tls.headUnitKey)) {
Protobuf.varintField(2, (selectedConfigIndex ?: 0).toLong()) log.i(" resuming without a new Start, as this car asked")
send(MSG_MEDIA_START, start, encrypted = true, channel = videoChannelId) } else {
log.i("-> Start(session_id=$SESSION_ID)") val index = selectedConfigIndex ?: 0
val start = Protobuf.varintField(1, SESSION_ID.toLong()) + Protobuf.varintField(2, index.toLong())
send(MSG_MEDIA_START, start, encrypted = true, channel = videoChannelId)
restartSentAt = System.currentTimeMillis()
log.i("-> Start(session_id=$SESSION_ID, configuration_index=$index)")
}
lastCodecConfig?.let { send(MSG_MEDIA_CODEC_CONFIG, it, encrypted = true, channel = videoChannelId) } lastCodecConfig?.let { send(MSG_MEDIA_CODEC_CONFIG, it, encrypted = true, channel = videoChannelId) }
videoSource?.requestSyncFrame() videoSource?.requestSyncFrame()
} else if (VideoRestartQuirks.pausesOnly(tls.headUnitKey)) {
log.i("the car is showing its own screen - video paused, audio carries on")
} else { } else {
// A phone ends the stream when the car takes its screen. LIVI switches on the focus // A phone ends the stream when the car takes its screen. LIVI switches on the focus
// answer alone, but the 2018 Uconnect kept showing our last frame until it got Stop. // answer alone, but the 2018 Uconnect kept showing our last frame until it got Stop.
@@ -1596,6 +1642,11 @@ class GearslipRunner(
val idle = System.currentTimeMillis() - lastProgress val idle = System.currentTimeMillis() - lastProgress
if (idle > 10_000) log.w("stalled in state $state for ${idle / 1000}s") if (idle > 10_000) log.w("stalled in state $state for ${idle / 1000}s")
} }
if (state == State.WAIT_SDR && discoverySentAt > 0 &&
System.currentTimeMillis() - discoverySentAt > DISCOVERY_STALL_MS
) {
switchDiscovery("went ${DISCOVERY_STALL_MS / 1000}s")
}
if (!videoStarted && !toldStuck && System.currentTimeMillis() - startedAt > STUCK_MS) { if (!videoStarted && !toldStuck && System.currentTimeMillis() - startedAt > STUCK_MS) {
toldStuck = true toldStuck = true
log.w("still not on the car's screen after ${STUCK_MS / 1000}s, in state $state") log.w("still not on the car's screen after ${STUCK_MS / 1000}s, in state $state")
@@ -1696,6 +1747,12 @@ class GearslipRunner(
/** A car shows its screen within seconds; this long without one, Home says what to try. */ /** A car shows its screen within seconds; this long without one, Home says what to try. */
const val STUCK_MS = 45_000L const val STUCK_MS = 45_000L
/** A car answers service discovery within a second; this long silent means it never will. */
const val DISCOVERY_STALL_MS = 10_000L
/** A goodbye this soon after a restarted stream is the car refusing it (issue #115). */
const val RESTART_HANGUP_MS = 2_000L
// protobuf/aap_protobuf/service/control/ControlMessageType.proto:7-17 // protobuf/aap_protobuf/service/control/ControlMessageType.proto:7-17
const val MSG_VERSION_REQUEST = 1 const val MSG_VERSION_REQUEST = 1
const val MSG_VERSION_RESPONSE = 2 const val MSG_VERSION_RESPONSE = 2
@@ -54,9 +54,24 @@ object VehicleProfiles {
if (!file.isFile) runCatching { file.writeText(DEFAULT_JSON) } if (!file.isFile) runCatching { file.writeText(DEFAULT_JSON) }
return runCatching { parse(file.readText()) } return runCatching { parse(file.readText()) }
.onFailure { GearslipLog.e("could not read $FILE - ignoring vehicle profiles", it) } .onFailure { GearslipLog.e("could not read $FILE - ignoring vehicle profiles", it) }
.getOrDefault(emptyList()) .getOrDefault(emptyList()) + BUILT_IN
} }
/**
* Profiles every install gets, after the file's own, so the file can still override them.
* The file is only written once, so a profile added to [DEFAULT_JSON] later would never reach
* anyone who already has one.
*/
private val BUILT_IN = listOf(
// Took every 1080p frame and showed none, while the Mach-E's SYNC 4 shows 1080p fine (issue #112).
VehicleProfile(
name = "Ford Transit (SYNC 4)",
match = mapOf("carModel" to "Ford Transit", "headUnitModel" to "SYNC 4.0"),
resolution = "1280x720",
insets = Insets.NONE,
),
)
/** Writes [insets] into the profile called [name] in the file, leaving everything else as it was. */ /** Writes [insets] into the profile called [name] in the file, leaving everything else as it was. */
fun saveInsets(context: Context, name: String, insets: Insets): Boolean { fun saveInsets(context: Context, name: String, insets: Insets): Boolean {
val file = context.getExternalFilesDir(null)?.let { File(it, FILE) } ?: return false val file = context.getExternalFilesDir(null)?.let { File(it, FILE) } ?: return false
@@ -0,0 +1,33 @@
package app.seb3thehacker.gearslip
import app.seb3thehacker.gearslip.car.CarEnvironment
/**
* Which cars hang up when the video restarts. When a car takes its screen (the reverse camera,
* its own menus) Gearslip sends Stop, and when the screen comes back it sends Start again with a
* fresh keyframe. A 2018 Uconnect needs that Stop, or it keeps showing the last frame. A 2021
* Mazda 3 hangs up a few milliseconds after the new Start instead (issue #115). A car that hangs
* up right after a restart is remembered by its head unit's certificate, and from then on its
* stream just pauses and resumes, with no Stop or Start.
*/
object VideoRestartQuirks {
private const val KEY = "video_no_restart_cars"
fun pausesOnly(car: String?): Boolean = car != null && car in cars()
/** The car hung up right after a restarted stream: pause and resume it from now on. */
fun hungUpAfterRestart(car: String?) {
val context = CarEnvironment.appContext ?: return
car ?: return
val now = cars()
if (car in now) return
AppSettings.putString(context, KEY, (now + car).joinToString(","))
GearslipLog.i("video: the car hung up right after the stream restarted, so next time it only pauses and resumes", "PROTO")
}
private fun cars(): Set<String> {
val context = CarEnvironment.appContext ?: return emptySet()
return AppSettings.getString(context, KEY, "").split(",").filter { it.isNotEmpty() }.toSet()
}
}
@@ -54,18 +54,32 @@ object BluetoothAudioCheck {
appContext = context.applicationContext appContext = context.applicationContext
} }
/** Whether Bluetooth audio to the car was up when the car first answered, before its screen. */
private var connectedEarly: Boolean? = null
/**
* The car answered, a moment before it shows Gearslip. A Citroen drops Bluetooth music 0.4s
* after it hands over its screen, before the check in [onProjecting] gets an answer, so the
* drop went unseen and its music stayed silent (issue #108). Looking here as well catches it.
*/
fun onCarFound() = main.post {
if (armed) return@post
audioToCar { connectedEarly = it }
}
/** The car shows Gearslip. Called again whenever the video restarts, so it arms once per drive. */ /** The car shows Gearslip. Called again whenever the video restarts, so it arms once per drive. */
fun onProjecting() = main.post { fun onProjecting() = main.post {
if (armed) return@post if (armed) return@post
armed = true armed = true
connectedAtStart = null connectedAtStart = connectedEarly
audioToCar { connectedAtStart = it } audioToCar { if (it != null) connectedAtStart = it || connectedEarly == true }
main.postDelayed(::start, WAIT_MS) main.postDelayed(::start, WAIT_MS)
} }
fun onCarDisconnected() = main.post { fun onCarDisconnected() = main.post {
armed = false armed = false
connectedAtStart = null connectedAtStart = null
connectedEarly = null
main.removeCallbacksAndMessages(null) main.removeCallbacksAndMessages(null)
stopWatching() stopWatching()
_missing.value = false _missing.value = false