Music starts on every cable connection without flipping the audio setting

- The music asks the car for its speakers only once the car shows
  Gearslip's screen. A head unit answered LOSS within 2 ms to every ask
  made before that, and Gearslip took it as final: a cable plugged back
  in quickly played nothing. A car keeping its own screen is asked when
  the wait for the screen runs out, as before.
- Capture is asked for whenever the car opens its music channel with
  music through Gearslip. The only ask was the car screen's, once per
  screen, so a reconnect to a screen kept from the drive before played
  nothing until the driver flipped the audio setting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jim HavrillaandClaude Opus 5.5 committed 2026-11-22 16:46:27 -05:00
1 parent 095141ad07
commit 5055e39ed2
3 files changed
+140

No files matched your search

@@ -87,6 +87,8 @@ class GearslipRunner(
private var selectedConfigIndex: Int? = null private var selectedConfigIndex: Int? = null
private var vehicleProfile: VehicleProfile? = null private var vehicleProfile: VehicleProfile? = null
@Volatile private var videoStarted = false @Volatile private var videoStarted = false
/** The car shows Gearslip's screen: the music asks for its speakers only from here on. */
@Volatile private var screenShown = false
/** The car's screen has been asked for once, so asking again is in order. */ /** The car's screen has been asked for once, so asking again is in order. */
@Volatile private var focusAsked = false @Volatile private var focusAsked = false
private var videoSource: VideoSource? = null private var videoSource: VideoSource? = null
@@ -636,6 +638,7 @@ class GearslipRunner(
media, media,
sendOnChannel = { id, body -> send(id, body, encrypted = true, channel = media.serviceId) }, sendOnChannel = { id, body -> send(id, body, encrypted = true, channel = media.serviceId) },
sendControl = { id, body -> send(id, body, encrypted = true) }, sendControl = { id, body -> send(id, body, encrypted = true) },
screenUp = { screenShown },
// The driver picked the radio or another source on the car: pause the phone's music // The driver picked the radio or another source on the car: pause the phone's music
// as Android Auto does, instead of letting it play on to no one. // as Android Auto does, instead of letting it play on to no one.
onTakenBack = { CarServices.pausePhoneMedia("the car switched to another source") }, onTakenBack = { CarServices.pausePhoneMedia("the car switched to another source") },
@@ -647,6 +650,10 @@ class GearslipRunner(
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)
// Asked for here, on every connection. The car screen's own ask runs once per screen,
// and a screen kept from the drive before never asked again: a reconnect played
// nothing for minutes, until the driver flipped the audio setting.
CarAudio.request()
} else { } else {
// Many cars switch their source to Android Auto the moment this channel opens, which // Many cars switch their source to Android Auto the moment this channel opens, which
// cut off music the driver chose to play over Bluetooth. Open it only if they switch. // cut off music the driver chose to play over Bluetooth. Open it only if they switch.
@@ -1269,6 +1276,8 @@ class GearslipRunner(
projection.onSurfaceReady(surface, width, height, config.density) projection.onSurfaceReady(surface, width, height, config.density)
} }
SessionStatus.projecting() SessionStatus.projecting()
screenShown = true
audioLink?.mayAskForSpeakers()
BluetoothAudioCheck.onProjecting() BluetoothAudioCheck.onProjecting()
LocationCheck.onProjecting() LocationCheck.onProjecting()
} }
@@ -1422,6 +1431,8 @@ class GearslipRunner(
// Give the car the channels' open responses before it hears the request again. // Give the car the channels' open responses before it hears the request again.
if (open != null || toldBluetooth) Thread.sleep(1_000) if (open != null || toldBluetooth) Thread.sleep(1_000)
if (running && !videoStarted) requestProjectedFocus(withDisplay = true) if (running && !videoStarted) requestProjectedFocus(withDisplay = true)
// A car keeping its own screen may still play the music: stop holding it back.
if (running && !screenShown) audioLink?.mayAskForSpeakers(screenOrNot = true)
}, "gearslip-focus-fallback").apply { isDaemon = true }.start() }, "gearslip-focus-fallback").apply { isDaemon = true }.start()
} }
@@ -32,6 +32,11 @@ class AudioLink(
* through [askForSpeakers], and only when the music isn't already ours. * through [askForSpeakers], and only when the music isn't already ours.
*/ */
private val asksFocus: Boolean = true, private val asksFocus: Boolean = true,
/**
* Whether the car shows Gearslip's screen. A head unit answered LOSS within 2 ms to every ask
* that came before it did, and GAIN to every one after, so the ask waits; see [mayAskForSpeakers].
*/
private val screenUp: () -> Boolean = { true },
private val onReady: (AudioLink) -> Unit = { CarAudio.attach(it) }, private val onReady: (AudioLink) -> Unit = { CarAudio.attach(it) },
private val onClose: (AudioLink) -> Unit = { CarAudio.detach(it) }, private val onClose: (AudioLink) -> Unit = { CarAudio.detach(it) },
/** The car took the sound back after giving it, as when the driver switches to the radio. */ /** The car took the sound back after giving it, as when the driver switches to the radio. */
@@ -352,7 +357,33 @@ class AudioLink(
/** Silence for [ms], whole frames of this sink's format. */ /** Silence for [ms], whole frames of this sink's format. */
private fun silence(ms: Int): ByteArray = ByteArray(sampleRate * ms / 1000 * channels * 2) private fun silence(ms: Int): ByteArray = ByteArray(sampleRate * ms / 1000 * channels * 2)
/** The capture wants to play, but the car isn't showing Gearslip yet; the ask waits for it. */
@Volatile private var waitingForScreen = false
/**
* The car shows Gearslip's screen now ([screenOrNot] false), or has kept its own for so long
* that the music shouldn't wait any more (true): a music start that was held goes ahead.
*/
fun mayAskForSpeakers(screenOrNot: Boolean = false) {
if (!waitingForScreen) return
if (!screenOrNot && !screenUp()) return
waitingForScreen = false
GearslipLog.i("$tag: ${if (screenOrNot) "the car is keeping its own screen" else "the car shows Gearslip"} - asking for the speakers now")
askAndStart()
}
override fun start() { override fun start() {
if (!ready || started) return
if (asksFocus && !focusRequested && !screenUp()) {
// Asked now, the car says LOSS at once and the music never plays: wait for the screen.
if (!waitingForScreen) GearslipLog.i("$tag: the car isn't showing Gearslip yet - holding the music until it does")
waitingForScreen = true
return
}
askAndStart()
}
private fun askAndStart() {
if (!ready || started) return if (!ready || started) return
if (asksFocus && !focusRequested) { if (asksFocus && !focusRequested) {
focusRequested = true focusRequested = true
@@ -407,6 +438,8 @@ class AudioLink(
} }
override fun stop() { override fun stop() {
// A held start is dropped too: the capture stopped before the screen came.
waitingForScreen = false
synchronized(startLock) { stopLocked() } synchronized(startLock) { stopLocked() }
} }
@@ -0,0 +1,96 @@
package app.seb3thehacker.gearslip.audio
import app.seb3thehacker.gearslip.Protobuf
import app.seb3thehacker.gearslip.ServiceDiscovery
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Collections
/**
* A head unit answered LOSS within 2 ms whenever the music asked for its speakers before it showed
* Gearslip's screen, and GAIN every time the ask came after. Gearslip took the LOSS as final, so a
* cable plugged back in quickly, with the capture still running, played nothing until the driver
* flipped the audio setting. The music should hold its ask until the screen is up.
*/
class AudioLinkFocusTest {
private val sink = ServiceDiscovery.AudioService(
serviceId = 4,
streamType = 3,
codecType = ServiceDiscovery.CODEC_PCM,
configs = listOf(ServiceDiscovery.AudioConfig(48_000, 16, 2)),
)
/** A media link whose car has set the sink up, and the control and channel messages it sent. */
private fun readyLink(screenUp: () -> Boolean): Triple<AudioLink, MutableList<Int>, MutableList<Int>> {
val control = Collections.synchronizedList(mutableListOf<Int>())
val channel = Collections.synchronizedList(mutableListOf<Int>())
val link = AudioLink(
sink,
sendOnChannel = { id, _ -> channel += id },
sendControl = { id, _ -> control += id },
screenUp = screenUp,
onReady = {},
onClose = {},
)
link.onMessage(
MSG_CONFIG,
Protobuf.varintField(1, 2) + Protobuf.varintField(2, 4) + Protobuf.varintField(3, 0),
)
return Triple(link, control, channel)
}
@Test
fun beforeTheScreenIsUpTheMusicDoesNotAskForTheSpeakers() {
val (link, control, channel) = readyLink(screenUp = { false })
link.start()
assertTrue("no focus request yet: $control", AudioLink.MSG_FOCUS_REQUEST !in control)
assertTrue("no Start yet: $channel", MSG_START !in channel)
assertEquals(false, link.streaming)
}
@Test
fun onceTheScreenIsUpTheHeldAskGoesOut() {
var up = false
val (link, control, channel) = readyLink(screenUp = { up })
link.start()
up = true
link.mayAskForSpeakers()
assertEquals(listOf(AudioLink.MSG_FOCUS_REQUEST), control)
assertTrue("Start sent: $channel", MSG_START in channel)
assertTrue(link.streaming)
link.stop()
}
@Test
fun aCarKeepingItsScreenStillGetsAskedWhenTheWaitIsOver() {
// A car that keeps its own screen never shows Gearslip's; the runner gives up waiting
// and lets the music ask anyway, as it always did.
val (link, control, _) = readyLink(screenUp = { false })
link.start()
link.mayAskForSpeakers(screenOrNot = true)
assertEquals(listOf(AudioLink.MSG_FOCUS_REQUEST), control)
link.stop()
}
@Test
fun withTheScreenAlreadyUpTheMusicAsksAtOnce() {
val (link, control, _) = readyLink(screenUp = { true })
link.start()
assertEquals(listOf(AudioLink.MSG_FOCUS_REQUEST), control)
link.stop()
}
@Test
fun nothingHeldMeansNothingToSend() {
val (link, control, _) = readyLink(screenUp = { true })
link.mayAskForSpeakers()
assertTrue("never started, so nothing asked: $control", control.isEmpty())
}
private companion object {
const val MSG_START = 32769
const val MSG_CONFIG = 32771
}
}