Video quality setting (Light, Standard, High): the car gets the largest size it offers up to 1080p by default instead of the smallest that fits, and Light caps it at 720p, 30 fps and a lower bitrate for phones that run hot; taps are scaled when a car reports them in its touch panel's size, found automatically or set in Settings; only the small live speech model loads when the car connects; your own speech and AI servers (OpenAI-style, such as whisper.cpp and Ollama) for voice without on-device models; other apps can send the assistant commands through a gearslip:// link or a broadcast, never calls; and music can be recorded through Shizuku with no screen sharing prompt

This commit is contained in:
Seb3thehacker committed 2026-11-25 12:27:19 -08:00
1 parent 924df40413
commit aad5c449e8
23 files changed
+1084 -30

No files matched your search

+32
View File
@@ -250,6 +250,38 @@
android:resource="@xml/accessory_filter" />
</activity-alias>
<!--
Commands from other apps, run as if the driver said them (see AssistantLink). Off until
the driver allows it in Settings, and never a phone call. The broadcast is for automation
apps such as Tasker; the gearslip:// link is for assistants that open links.
-->
<receiver
android:name=".car.AssistantLinkReceiver"
android:exported="true">
<intent-filter>
<action android:name="app.seb3thehacker.gearslip.action.COMMAND" />
</intent-filter>
</receiver>
<activity
android:name=".car.AssistantLinkActivity"
android:exported="true"
android:excludeFromRecents="true"
android:noHistory="true"
android:taskAffinity=""
android:theme="@android:style/Theme.Translucent.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="gearslip" android:host="command" />
</intent-filter>
<intent-filter>
<action android:name="app.seb3thehacker.gearslip.action.COMMAND" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<!-- Dev builds' test message: its Reply and Mark as read actions land here. -->
<receiver
android:name=".notify.TestMessageReceiver"
@@ -1,5 +1,6 @@
package app.seb3thehacker.gearslip.shizuku;
import android.os.ParcelFileDescriptor;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
@@ -26,4 +27,10 @@ interface IShellService {
oneway void injectKey(in KeyEvent event, int displayId) = 6;
void releaseDisplay(int displayId) = 7;
// Records everything the phone plays, as adb can, and hands back the read end of a pipe of
// 16-bit PCM. Null when the recording can't start.
ParcelFileDescriptor startAudio(int sampleRate, int channels) = 8;
void stopAudio() = 9;
}
@@ -208,6 +208,7 @@ class GearslipActivity : ComponentActivity(), Projection {
PhoneMirror.onStartRequested = { runOnUiThread { requestCapture() } }
PhoneMirror.onTokenReady = { token -> runOnUiThread { showMirror(token) } }
PhoneMirror.onEnded = { runOnUiThread { showCarUi() } }
CarAudio.appContext = applicationContext
CarAudio.onConsentRequested = { runOnUiThread { requestAudioCapture() } }
registerReceiver(detachReceiver, IntentFilter(UsbManager.ACTION_USB_ACCESSORY_DETACHED), RECEIVER_NOT_EXPORTED)
@@ -14,6 +14,8 @@ import app.seb3thehacker.gearslip.car.CarAssistant
import app.seb3thehacker.gearslip.car.CarEnvironment
import app.seb3thehacker.gearslip.car.CarKeys
import app.seb3thehacker.gearslip.car.ScreenFit
import app.seb3thehacker.gearslip.car.TouchScale
import app.seb3thehacker.gearslip.car.VideoQuality
import app.seb3thehacker.gearslip.car.CarSensors
import app.seb3thehacker.gearslip.car.CarServices
import app.seb3thehacker.gearslip.car.CarSettings
@@ -617,6 +619,7 @@ class GearslipRunner(
inputChannelId = input.serviceId
inputKeycodes = input.keycodesSupported
touchWidth = input.touchWidth
touchPanelCoordinates = false
touchHeight = input.touchHeight
log.i(
"input service: channel=${input.serviceId} touchscreen=" +
@@ -1000,8 +1003,10 @@ class GearslipRunner(
// A stretched frame (see [screenShape]): the car's tap is on the frame, the UI is drawn smaller.
val drawn = drawSize
val stretched = drawn != null && size != null
val (scaleX, scaleY) = touchScaleFor(config, touch)
val (action, actionIndex, raw) =
(if (stretched) InputProtocol.touch(touch, size) else InputProtocol.touch(touch, size, shift.left, shift.top)) ?: return
(if (stretched) InputProtocol.touch(touch, size, scaleX = scaleX, scaleY = scaleY)
else InputProtocol.touch(touch, size, shift.left, shift.top, scaleX, scaleY)) ?: return
val points = if (drawn != null && size != null) {
raw.map { TouchPoint(it.id, it.x * drawn.first / size.first, it.y * drawn.second / size.second) }
} else {
@@ -1021,6 +1026,39 @@ class GearslipRunner(
projection?.onTouch(action, actionIndex, points)
}
/** This drive's taps came in past the edge of the picture, so the car reports in its panel's size. */
@Volatile private var touchPanelCoordinates = false
/**
* How much to scale the car's taps by. Most cars map their panel onto our picture before
* reporting (the 2018 Uconnect does, and scaling broke it), but some report in the panel's own
* size; on those a 1920-wide panel over a 1280-wide picture put every tap on the right third
* against the edge. In Auto, the first tap past the picture's edge gives that away, and the
* rest of the drive is scaled. Only a panel bigger than the picture can be told apart this way;
* Scaled in Settings covers the other kind.
*/
private fun touchScaleFor(config: ServiceDiscovery.VideoConfig?, touch: ByteArray): Pair<Float, Float> {
val visible = config?.visibleSize() ?: return 1f to 1f
if (touchWidth <= 0 || touchHeight <= 0 || visible.first <= 0 || visible.second <= 0) return 1f to 1f
val scale = visible.first.toFloat() / touchWidth to visible.second.toFloat() / touchHeight
when (CarSettings.touchScale.value) {
TouchScale.AS_SENT -> return 1f to 1f
TouchScale.SCALED -> return scale
TouchScale.AUTO -> Unit
}
if (!touchPanelCoordinates && (touchWidth > visible.first || touchHeight > visible.second)) {
val (x, y) = InputProtocol.extent(touch) ?: return 1f to 1f
if (x >= visible.first || y >= visible.second) {
touchPanelCoordinates = true
log.i(
"touch: a tap at $x,$y is past the ${visible.first}x${visible.second} picture, so the car " +
"reports in its ${touchWidth}x$touchHeight panel's size - scaling taps from now on",
)
}
}
return if (touchPanelCoordinates) scale else 1f to 1f
}
/**
* Asks the head unit to forward its buttons. Many units send nothing from the steering wheel
* until the phone names the keys it wants. What the unit offered is asked for; a unit that
@@ -1162,21 +1200,25 @@ class GearslipRunner(
// <- Ack { session_id, ack } - at most max_unacked frames may be outstanding
/**
* The offered config that best fills the car's screen: the smallest whose visible width
* reaches most of the touchscreen's, else the largest there is. Always taking the smallest
* put 800x480 on a 1540x720 Audi screen and stretched it. A car that gives no touchscreen
* size gets the largest up to 1080p: a car only offers sizes it can show, and the 2024 VW
* (touchscreen 0x0) blurred 800x480 across a 1080p screen.
* The largest offered size within the driver's video quality (up to 1080p by default), of the
* screen's own shape. A car only offers sizes it can show, so the biggest one is the sharpest.
* An earlier choice, the smallest whose width reached most of the touch panel's, could send
* 720p where the car offered 1080p, and a driver found the picture softer than another app's
* on the same car.
* A car that offers nothing small enough gets its smallest.
*/
private fun fitToScreen(offered: List<Int>): Int? {
val known = sameShape(offered.filter { videoConfigs.getOrNull(it)?.pixelSize() != null })
fun pixels(idx: Int) = videoConfigs[idx].pixelCount()
if (touchWidth <= 0) {
return known.filter { pixels(it) <= 1920 * 1080 }.maxByOrNull(::pixels)
?: known.minByOrNull(::pixels)
}
val wide = known.filter { (videoConfigs[it].visibleSize()?.first ?: 0) >= touchWidth * 8 / 10 }
return wide.minByOrNull(::pixels) ?: known.maxByOrNull(::pixels)
fun shortSide(idx: Int) = videoConfigs[idx].pixelSize()?.let { minOf(it.first, it.second) } ?: Int.MAX_VALUE
val quality = CarSettings.videoQuality.value
val fits = known.filter { shortSide(it) <= quality.maxShortSide }
// Of two the same size, the 60 fps one when it'd be used.
fun fps60(idx: Int) = videoConfigs[idx].frameRate == 1
val wants60 = quality == VideoQuality.HIGH || (quality == VideoQuality.STANDARD && !wireless)
val best = fits.maxWithOrNull(compareBy<Int>(::pixels).thenBy { if (fps60(it) == wants60) 1 else 0 })
if (best != null) log.i("video: ${quality.name.lowercase()} quality takes ${videoConfigs[best].resolutionName}")
return best ?: known.minByOrNull(::pixels)
}
/**
@@ -1267,8 +1309,15 @@ class GearslipRunner(
}
val useProjection = projection != null
// 60fps only over a cable: over Wi-Fi it doubles the data for little the driver sees.
videoFrameRate = if (config.frameRate == 1 && !wireless) 60 else 30
// 60fps only over a cable: over Wi-Fi it doubles the data for little the driver sees. Light
// quality never, High always when the car offers it.
val quality = CarSettings.videoQuality.value
videoFrameRate = when {
config.frameRate != 1 || quality == VideoQuality.LIGHT -> 30
quality == VideoQuality.HIGH -> 60
wireless -> 30
else -> 60
}
smoothWindows = 0
lastCut = null
decoderBound = false
@@ -1280,6 +1329,7 @@ class GearslipRunner(
frameRate = videoFrameRate,
mode = if (useProjection) VideoSource.Mode.SURFACE else VideoSource.Mode.TEST_CARD,
wireless = wireless,
bitRateShare = if (quality == VideoQuality.LIGHT) LIGHT_BIT_RATE_SHARE else 1f,
onCodecConfig = { csd ->
lastCodecConfig = csd
send(MSG_MEDIA_CODEC_CONFIG, csd, encrypted = true, channel = videoChannelId)
@@ -1742,6 +1792,9 @@ class GearslipRunner(
}
internal companion object {
/** Light video quality's share of the usual bitrate: still sharp for text, far less work. */
const val LIGHT_BIT_RATE_SHARE = 0.6f
/** The stats window adaptive bitrate reads, matching the watchdog's sleep. */
const val ADAPT_WINDOW_MS = 5_000L
@@ -0,0 +1,74 @@
package app.seb3thehacker.gearslip
import app.seb3thehacker.gearslip.car.CarSettings
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
/**
* Talks to a server the driver runs themselves, for speech and the assistant, so the phone needn't
* hold a model in memory while it also streams video, plays music and runs a map. Both use the
* OpenAI-style calls that whisper.cpp, faster-whisper, LocalAI, llama.cpp and Ollama all answer.
*
* Only the driver's own address is ever called, and nothing said is written to the log.
*/
object OwnServer {
/** Something went wrong in a way worth saying on the car screen. */
class Failed(message: String) : IOException(message)
const val UNREACHABLE = "Couldn't reach your server. Check its address in Gearslip's settings."
private const val CONNECT_MS = 5_000
private const val READ_MS = 30_000
/**
* Where to send a call: the address as typed when it already names a path for it (whisper.cpp's
* server answers on /inference, say), otherwise [path] under it. "http://" is added when the
* driver left it off.
*/
fun endpoint(address: String, path: String, alreadyThere: List<String>): URL {
var base = address.trim().trimEnd('/')
if (!base.startsWith("http://") && !base.startsWith("https://")) base = "http://$base"
if (alreadyThere.any { base.endsWith(it) }) return URL(base)
// "http://host:8080/v1" and "http://host:8080" both mean the same server.
val tail = if (base.endsWith("/v1")) path.removePrefix("/v1") else path
return URL(base + tail)
}
/** POSTs [body] and returns the reply's text; [Failed] for a refusal or no answer. */
fun post(server: CarSettings.Server, url: URL, contentType: String, body: ByteArray): String {
val connection = try {
url.openConnection() as HttpURLConnection
} catch (e: Exception) {
throw Failed(UNREACHABLE)
}
try {
connection.requestMethod = "POST"
connection.connectTimeout = CONNECT_MS
connection.readTimeout = READ_MS
connection.doOutput = true
connection.setRequestProperty("Content-Type", contentType)
if (server.key.isNotBlank()) connection.setRequestProperty("Authorization", "Bearer ${server.key}")
connection.setFixedLengthStreamingMode(body.size)
connection.outputStream.use { it.write(body) }
val code = connection.responseCode
if (code == 401 || code == 403) throw Failed("Your server refused the key. Check it in Gearslip's settings.")
if (code == 404) throw Failed("Your server doesn't answer at that address. Check it in Gearslip's settings.")
if (code !in 200..299) {
GearslipLog.w("own server: $url answered HTTP $code")
throw Failed("Your server had a problem (HTTP $code).")
}
return connection.inputStream.bufferedReader().use { it.readText() }
} catch (e: Failed) {
throw e
} catch (e: java.net.SocketTimeoutException) {
throw Failed("Your server took too long to answer.")
} catch (e: IOException) {
GearslipLog.w("own server: $url failed: ${e.javaClass.simpleName}")
throw Failed(UNREACHABLE)
} finally {
connection.disconnect()
}
}
}
@@ -25,6 +25,8 @@ class VideoSource(
private val mode: Mode = Mode.TEST_CARD,
/** Over Wi-Fi: a fraction of the cable bitrate, so the link keeps up and sound isn't starved. */
private val wireless: Boolean = false,
/** A fraction of the usual bitrate, for the driver's Light video quality. */
private val bitRateShare: Float = 1f,
private val onCodecConfig: (ByteArray) -> Unit,
private val onFrame: (data: ByteArray, presentationTimeUs: Long, keyFrame: Boolean) -> Unit,
/**
@@ -64,7 +66,7 @@ class VideoSource(
val level = levelFor(width, height, frameRate)
val bitRate = defaultBitRate(width, height, frameRate, level).let {
if (wireless) (it * WIRELESS_SHARE).toInt().coerceAtMost(WIRELESS_MAX_BIT_RATE) else it
}
}.let { (it * bitRateShare).toInt() }
fullBitRate = bitRate
this.bitRate = bitRate
fun format(tuned: Boolean) = MediaFormat.createVideoFormat(MIME, width, height).apply {
@@ -113,7 +113,21 @@ object CarAudio {
}
}
/** Set by the activity, like [onConsentRequested]: what [ShellAudio] needs to start. */
var appContext: android.content.Context? = null
private fun ask() {
_capture.value = Capture.ASKING
// Shizuku, when the driver chose it, records without a dialog.
val context = appContext
if (context != null && ShellAudio.available(context)) {
ShellAudio.start(context, onFailed = ::askForConsent)
return
}
askForConsent()
}
private fun askForConsent() {
_capture.value = Capture.ASKING
val request = onConsentRequested
if (request == null) {
@@ -148,6 +162,7 @@ object CarAudio {
main.removeCallbacks(releaseWhenGone)
wanted = false
toldBlocked = false
ShellAudio.stop()
AudioCaptureService.stop()
_capture.value = Capture.OFF
}
@@ -0,0 +1,111 @@
package app.seb3thehacker.gearslip.audio
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.ParcelFileDescriptor
import android.os.Process
import app.seb3thehacker.gearslip.GearslipLog
import app.seb3thehacker.gearslip.car.CarSettings
import app.seb3thehacker.gearslip.shizuku.ShellBridge
import app.seb3thehacker.gearslip.shizuku.ShizukuSetup
import kotlin.math.abs
/**
* Music for the car recorded through Shizuku, as adb records it, instead of through
* [AudioCaptureService]. The shell may record the phone's whole output: there's no consent
* dialog, apps that refuse playback capture (Spotify) are heard anyway, and the phone goes quiet
* by itself while it runs. Optional, and only with Shizuku running and allowed; anything that
* goes wrong falls back to the usual capture.
*/
internal object ShellAudio {
private val log = GearslipLog.tagged("audio")
private val main = Handler(Looper.getMainLooper())
@Volatile private var reading = false
@Volatile private var acquired = false
/** The driver wants it and Shizuku can do it now. */
fun available(context: Context): Boolean {
if (!CarSettings.shizukuAudio.value) return false
ShizukuSetup.init(context)
ShizukuSetup.refresh()
return ShizukuSetup.state.value == ShizukuSetup.State.READY
}
/** Starts recording; [onFailed] runs on the main thread if the shell can't. */
fun start(context: Context, onFailed: () -> Unit) {
if (reading) return
reading = true
acquired = true
ShellBridge.acquire(context)
val rate = CarAudio.sampleRate
val channels = CarAudio.channels
ShellBridge.call { shell ->
val pipe = runCatching { shell.startAudio(rate, channels) }.getOrNull()
if (pipe == null || !reading) {
pipe?.close()
if (reading) {
log.w("Shizuku couldn't record the phone's sound - asking for the usual capture instead")
stop()
main.post(onFailed)
}
return@call
}
pump(pipe, rate, channels)
}
}
private fun pump(pipe: ParcelFileDescriptor, rate: Int, channels: Int) {
Thread({
Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO)
val buffer = ByteArray(CHUNK_BYTES)
var peak = 0
var loggedAt = System.currentTimeMillis()
try {
ParcelFileDescriptor.AutoCloseInputStream(pipe).use { input ->
log.i("recording the phone's sound through Shizuku at ${rate}Hz x$channels")
CarAudio.captureStarted()
while (reading) {
val n = input.read(buffer)
if (n < 0) break
if (n == 0) continue
var i = 0
while (i + 1 < n) {
val sample = (buffer[i].toInt() and 0xFF) or (buffer[i + 1].toInt() shl 8)
peak = maxOf(peak, abs(sample.toShort().toInt()))
i += 2
}
CarAudio.deliver(buffer, n, peak / 32768f)
val now = System.currentTimeMillis()
if (now - loggedAt >= LEVEL_LOG_MS) {
log.i("peak %.3f".format(peak / 32768f))
loggedAt = now
peak = 0
}
}
}
} catch (t: Throwable) {
log.e("the Shizuku recording ended", t)
} finally {
CarAudio.captureStopped()
if (reading) {
log.w("the Shizuku recording stopped by itself")
stop()
}
}
}, "gearslip-shell-audio").apply { isDaemon = true; start() }
}
fun stop() {
reading = false
if (!acquired) return
acquired = false
ShellBridge.call { runCatching { it.stopAudio() } }
ShellBridge.release()
}
private const val CHUNK_BYTES = 4096
private const val LEVEL_LOG_MS = 3_000L
}
@@ -20,7 +20,26 @@ import kotlinx.coroutines.withTimeoutOrNull
*/
object AssistantCommands {
suspend fun handle(context: Context, navigator: CarNavigator, frame: CarEnvironment.Frame, heardRaw: String): String {
/**
* [fromApp] is a command another app sent ([AssistantLink]): those never place a call, since
* that would let any app on the phone dial out without the phone permission.
*/
suspend fun handle(
context: Context,
navigator: CarNavigator,
frame: CarEnvironment.Frame,
heardRaw: String,
fromApp: Boolean = false,
): String = handle(context, navigator, frame, heardRaw, fromApp, askServer = true)
private suspend fun handle(
context: Context,
navigator: CarNavigator,
frame: CarEnvironment.Frame,
heardRaw: String,
fromApp: Boolean,
askServer: Boolean,
): String {
val heard = natural(heardRaw)
VoiceHelp.hide()
if (heard in HELP_WORDS || heard.startsWith("what can i say") || heard.startsWith("what can you do")) {
@@ -34,9 +53,24 @@ object AssistantCommands {
mediaCommand(heard)?.let { return it }
navCommand(navigator, heard)?.let { return it }
infoCommand(heard)?.let { return it }
if (fromApp && (after(heard, CALL_TRIGGERS) != null || GIVE_A_CALL.matches(heard))) {
return "Calls can't be started from another app."
}
callCommand(context, heard)?.let { return it }
openAppCommand(context, navigator, frame, heard)?.let { return it }
// Not one of ours: the driver's own AI server, when there is one, gets a go. A command it
// hands back runs once, and isn't sent back to it, so the two can't bounce forever.
if (askServer && ServerAssistant.enabled) {
return try {
when (val answer = ServerAssistant.ask(heardRaw)) {
is ServerAssistant.Answer.Say -> answer.text
is ServerAssistant.Answer.Run -> handle(context, navigator, frame, answer.command, fromApp, askServer = false)
}
} catch (e: app.seb3thehacker.gearslip.OwnServer.Failed) {
e.message ?: app.seb3thehacker.gearslip.OwnServer.UNREACHABLE
}
}
return "I don't know how to do that yet."
}
@@ -317,7 +351,7 @@ object AssistantCommands {
private suspend fun callCommand(context: Context, heard: String): String? {
val name = (
after(heard, CALL_TRIGGERS)
?: Regex("^give (.+) a (?:call|ring)$").find(heard)?.groupValues?.get(1)
?: GIVE_A_CALL.find(heard)?.groupValues?.get(1)
?: return null
).replace(Regex(" (?:on|at) (?:their |his |her )?(?:mobile|cell|phone|home|work)$"), "").trim()
if (name.isBlank()) return "Who should I call?"
@@ -377,6 +411,8 @@ object AssistantCommands {
private val PLAY_TRIGGERS = listOf("play me ", "play ", "put on ", "listen to ", "i want to hear ", "shuffle ")
private val GIVE_A_CALL = Regex("^give (.+) a (?:call|ring)$")
private val CALL_TRIGGERS = listOf("call ", "phone ", "dial ", "ring ", "make a call to ", "place a call to ", "start a call with ")
private val OPEN_TRIGGERS = listOf("open ", "launch ", "start ", "go to ", "switch to ", "show me ", "bring up ", "pull up ")
@@ -0,0 +1,75 @@
package app.seb3thehacker.gearslip.car
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import app.seb3thehacker.gearslip.GearslipLog
import app.seb3thehacker.gearslip.R
/**
* Lets another app drive Gearslip's assistant, so a different voice assistant, a home automation
* app or Tasker can do what the driver could say: "navigate to work", "play Daft Punk", "open
* Spotify". The command runs exactly as if spoken, and the answer is said on the car.
*
* Two ways in, for the two kinds of caller:
*
* gearslip://command?text=navigate%20to%20work (a link, for assistants)
* am broadcast -a app.seb3thehacker.gearslip.action.COMMAND -e text "play jazz" (Tasker)
*
* Off until the driver turns on "Commands from other apps", only while a car is connected, and
* never a phone call: that would let any app dial out without the phone permission.
*/
object AssistantLink {
const val ACTION = "app.seb3thehacker.gearslip.action.COMMAND"
const val EXTRA_TEXT = "text"
/** Longest command taken: a spoken one is a sentence, not a page. */
private const val MAX_LENGTH = 300
enum class Result { RAN, OFF, NO_CAR, EMPTY }
fun run(intent: Intent?): Result {
val text = (intent?.getStringExtra(EXTRA_TEXT) ?: intent?.data?.getQueryParameter(EXTRA_TEXT))
?.trim()?.take(MAX_LENGTH).orEmpty()
val result = when {
!CarSettings.appCommands.value -> Result.OFF
text.isEmpty() -> Result.EMPTY
!CarAssistant.runCommand(text) -> Result.NO_CAR
else -> Result.RAN
}
// What was asked stays out of the log, as with spoken commands.
GearslipLog.i("assistant: a command from another app: ${result.name.lowercase().replace('_', ' ')}")
return result
}
fun explain(context: Context, result: Result) {
val message = when (result) {
Result.RAN -> return
Result.OFF -> R.string.app_commands_off
Result.NO_CAR -> R.string.app_commands_no_car
Result.EMPTY -> R.string.app_commands_empty
}
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}
/** The broadcast way in, for automation apps that run in the background. */
class AssistantLinkReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != AssistantLink.ACTION) return
AssistantLink.run(intent)
}
}
/** The link way in. Shows nothing: it hands the command on and closes. */
class AssistantLinkActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AssistantLink.explain(this, AssistantLink.run(intent))
finish()
}
}
@@ -45,9 +45,29 @@ object CarAssistant {
private val _state = MutableStateFlow(State())
val state: StateFlow<State> = _state
/** A command to act on; [fromApp] when another app sent it rather than the driver saying it. */
data class Pending(val text: String, val fromApp: Boolean = false)
/** Set once a recognition result comes in; [reply] clears it once handled. */
private val _pendingCommand = MutableStateFlow<String?>(null)
val pendingCommand: StateFlow<String?> = _pendingCommand
private val _pendingCommand = MutableStateFlow<Pending?>(null)
val pendingCommand: StateFlow<Pending?> = _pendingCommand
/** How many car screens are acting on [pendingCommand]: none means no car to do anything on. */
@Volatile var carScreens = 0
/**
* A command another app sent ([AssistantLink]), run as if the driver had said it, answer and
* all. False when there's no car screen up to act on it.
*/
fun runCommand(text: String): Boolean {
if (carScreens <= 0 || text.isBlank()) return false
mainHandler.post {
tts?.stop()
_state.value = State(Phase.THINKING, heard = text.trim(), ready = true)
_pendingCommand.value = Pending(text.trim(), fromApp = true)
}
return true
}
private var appContext: Context? = null
private var recognizer: SpeechRecognizer? = null
@@ -96,7 +116,7 @@ object CarAssistant {
onHeard = { _state.value = _state.value.copy(phase = Phase.THINKING) },
onResult = { text ->
_state.value = _state.value.copy(phase = Phase.THINKING, heard = text)
_pendingCommand.value = text
_pendingCommand.value = Pending(text)
},
onError = { message -> _state.value = State(Phase.ERROR, reply = message) },
)
@@ -84,14 +84,21 @@ object CarServices {
app.seb3thehacker.gearslip.notify.CarMotion.start(appContext)
app.seb3thehacker.gearslip.call.CarCalls.start(appContext)
CarAssistant.init(appContext)
// Lets music start through Shizuku with no phone screen up to ask for consent.
app.seb3thehacker.gearslip.audio.CarAudio.appContext = appContext
DirectionsVoice.init(appContext)
CarBluetooth.init(appContext)
BluetoothAudioCheck.init(appContext)
LocationCheck.init(appContext)
CarKeys.init(appContext)
VoiceReply.init(appContext)
// Loaded now, while nothing's waiting on it, so the first reply isn't slower than the rest.
app.seb3thehacker.gearslip.speech.SpeechEngine.warm(appContext)
// Only the small live model, so the first command still starts at once. The big one that
// rereads each phrase took hundreds of megabytes from the moment the car connected, on
// drives where nobody spoke; it loads when the driver first does. Nothing at all when
// listening goes to the driver's own server or the phone's speech service.
if (!CarSettings.speechServer.value.on && !CarSettings.systemSpeech.value) {
app.seb3thehacker.gearslip.speech.SpeechEngine.warm(appContext, final = false)
}
}
// --- map -----------------------------------------------------------------------------
@@ -43,6 +43,20 @@ enum class ScreenFit { CROP, SQUASH }
/** What size the phone's car preview draws: the last car's, this device's whole screen, or one typed in. */
enum class PreviewSize { LAST_CAR, FILL, CUSTOM }
/**
* How much the phone puts into the car's video. [LIGHT] caps it at 720p, 30 fps and a lower
* bitrate, for a phone that runs hot or kills apps; [STANDARD] takes up to 1080p; [HIGH] takes
* the biggest size the car offers and 60 fps over Wi-Fi too.
*/
enum class VideoQuality(val maxShortSide: Int) { LIGHT(720), STANDARD(1080), HIGH(2160) }
/**
* How the car's taps map onto the screen. [AUTO] sends them as the car reports them, the way the
* 2018 Uconnect needs, until one lands outside the picture, which shows the car is reporting in
* its touch panel's own size; from then on they're scaled. [AS_SENT] and [SCALED] fix the choice.
*/
enum class TouchScale { AUTO, AS_SENT, SCALED }
/** When the nav bar gets out of the way: never, during a route, or whenever the map is up. */
enum class NavBarMode { SHOW, HIDE_NAVIGATING, HIDE }
@@ -89,6 +103,16 @@ private const val KEY_CLUSTER_VIDEO = "cluster_video_enabled"
private const val KEY_SCREEN_FIT = "car_screen_fit"
private const val KEY_PREVIEW_SIZE = "preview_size"
private const val KEY_PREVIEW_CUSTOM = "preview_custom_size"
private const val KEY_VIDEO_QUALITY = "car_video_quality"
private const val KEY_TOUCH_SCALE = "car_touch_scale"
private const val KEY_SPEECH_SERVER = "speech_server_url"
private const val KEY_SPEECH_SERVER_MODEL = "speech_server_model"
private const val KEY_SPEECH_SERVER_KEY = "speech_server_key"
private const val KEY_AI_SERVER = "ai_server_url"
private const val KEY_AI_SERVER_MODEL = "ai_server_model"
private const val KEY_AI_SERVER_KEY = "ai_server_key"
private const val KEY_SHIZUKU_AUDIO = "car_shizuku_audio"
private const val KEY_APP_COMMANDS = "car_app_commands"
private const val KEY_WHATS_NEW = "car_whats_new_after_updates"
private const val KEY_WHATS_NEW_SEEN = "car_whats_new_seen_code"
@@ -169,6 +193,81 @@ private const val KEY_CLUSTER_VIDEO = "cluster_video_enabled"
AppSettings.putString(app, KEY_PREVIEW_CUSTOM, custom?.toString().orEmpty())
}
private val videoQualityFlow = MutableStateFlow(VideoQuality.STANDARD)
private val touchScaleFlow = MutableStateFlow(TouchScale.AUTO)
/** Takes effect the next time the car connects: the video size is agreed at the start. */
val videoQuality: StateFlow<VideoQuality> = videoQualityFlow
val touchScale: StateFlow<TouchScale> = touchScaleFlow
fun setVideoQuality(quality: VideoQuality) {
videoQualityFlow.value = quality
AppSettings.putString(app, KEY_VIDEO_QUALITY, quality.name)
}
fun setTouchScale(scale: TouchScale) {
touchScaleFlow.value = scale
AppSettings.putString(app, KEY_TOUCH_SCALE, scale.name)
}
/**
* A speech-to-text server the driver runs themselves (whisper.cpp, faster-whisper, LocalAI and
* the like all answer OpenAI's transcription call). Set, it replaces the on-device models, so
* the phone loads none of them. Empty means off.
*/
data class Server(val url: String, val model: String, val key: String) {
val on: Boolean get() = url.isNotBlank()
}
private val speechServerFlow = MutableStateFlow(Server("", "", ""))
private val aiServerFlow = MutableStateFlow(Server("", "", ""))
val speechServer: StateFlow<Server> = speechServerFlow
/**
* A chat model the driver runs themselves (Ollama, llama.cpp, LocalAI, or any OpenAI-style
* server). Asked only when a command isn't one Gearslip knows: it may answer, or turn what
* was said into a command. Empty means off.
*/
val aiServer: StateFlow<Server> = aiServerFlow
fun setSpeechServer(server: Server) {
speechServerFlow.value = server
AppSettings.putString(app, KEY_SPEECH_SERVER, server.url.trim())
AppSettings.putString(app, KEY_SPEECH_SERVER_MODEL, server.model.trim())
AppSettings.putString(app, KEY_SPEECH_SERVER_KEY, server.key.trim())
}
fun setAiServer(server: Server) {
aiServerFlow.value = server
AppSettings.putString(app, KEY_AI_SERVER, server.url.trim())
AppSettings.putString(app, KEY_AI_SERVER_MODEL, server.model.trim())
AppSettings.putString(app, KEY_AI_SERVER_KEY, server.key.trim())
}
private val appCommandsFlow = MutableStateFlow(false)
/** Other apps may send the assistant commands (see [AssistantLink]). Off until the driver allows it. */
val appCommands: StateFlow<Boolean> = appCommandsFlow
fun setAppCommands(on: Boolean) {
appCommandsFlow.value = on
AppSettings.putString(app, KEY_APP_COMMANDS, on.toString())
}
private val shizukuAudioFlow = MutableStateFlow(false)
/**
* With Shizuku running, music is recorded the way adb would (the phone's whole output), not
* through Android's playback capture: no consent dialog, and apps that block capture, such as
* Spotify, still reach the car.
*/
val shizukuAudio: StateFlow<Boolean> = shizukuAudioFlow
fun setShizukuAudio(on: Boolean) {
shizukuAudioFlow.value = on
AppSettings.putString(app, KEY_SHIZUKU_AUDIO, on.toString())
}
private val navBarFlow = MutableStateFlow(NavBarMode.SHOW)
val navBarMode: StateFlow<NavBarMode> = navBarFlow
@@ -441,6 +540,24 @@ private const val KEY_CLUSTER_VIDEO = "cluster_video_enabled"
navBarFlow.value = runCatching {
NavBarMode.valueOf(AppSettings.getString(app, KEY_NAV_BAR, NavBarMode.SHOW.name))
}.getOrDefault(NavBarMode.SHOW)
videoQualityFlow.value = runCatching {
VideoQuality.valueOf(AppSettings.getString(app, KEY_VIDEO_QUALITY, VideoQuality.STANDARD.name))
}.getOrDefault(VideoQuality.STANDARD)
touchScaleFlow.value = runCatching {
TouchScale.valueOf(AppSettings.getString(app, KEY_TOUCH_SCALE, TouchScale.AUTO.name))
}.getOrDefault(TouchScale.AUTO)
speechServerFlow.value = Server(
AppSettings.getString(app, KEY_SPEECH_SERVER, ""),
AppSettings.getString(app, KEY_SPEECH_SERVER_MODEL, ""),
AppSettings.getString(app, KEY_SPEECH_SERVER_KEY, ""),
)
aiServerFlow.value = Server(
AppSettings.getString(app, KEY_AI_SERVER, ""),
AppSettings.getString(app, KEY_AI_SERVER_MODEL, ""),
AppSettings.getString(app, KEY_AI_SERVER_KEY, ""),
)
shizukuAudioFlow.value = AppSettings.getString(app, KEY_SHIZUKU_AUDIO, "false") == "true"
appCommandsFlow.value = AppSettings.getString(app, KEY_APP_COMMANDS, "false") == "true"
whatsNewFlow.value = AppSettings.getString(app, KEY_WHATS_NEW, "true") == "true"
whatsNewSeenFlow.value = AppSettings.getString(app, KEY_WHATS_NEW_SEEN, "0").toIntOrNull() ?: 0
}
@@ -156,12 +156,17 @@ fun CarUi() {
// only knows how to listen and speak, not what "open Spotify" means.
val frameForAssistant by CarEnvironment.frame.collectAsState()
LaunchedEffect(navigator) {
CarAssistant.pendingCommand.collect { heard ->
if (heard != null) {
val reply = AssistantCommands.handle(appContext, navigator, frameForAssistant, heard)
CarAssistant.carScreens++
try {
CarAssistant.pendingCommand.collect { pending ->
if (pending != null) {
val reply = AssistantCommands.handle(appContext, navigator, frameForAssistant, pending.text, pending.fromApp)
CarAssistant.reply(reply)
}
}
} finally {
CarAssistant.carScreens--
}
}
// The car's own back, home, map, media and phone keys.
@@ -0,0 +1,77 @@
package app.seb3thehacker.gearslip.car
import app.seb3thehacker.gearslip.OwnServer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
/**
* The driver's own chat model (Ollama, llama.cpp's server, LocalAI, or anything with OpenAI's chat
* call), asked only about what [AssistantCommands] doesn't already understand. It either answers
* in a sentence or two, or rewrites what was said as one of Gearslip's own commands, which then
* runs like any other. Only this one exchange is sent: no history, nothing about the drive.
*/
object ServerAssistant {
/** What came back: words to say, or a command to run. */
sealed interface Answer {
data class Say(val text: String) : Answer
data class Run(val command: String) : Answer
}
private const val DEFAULT_MODEL = "llama3.2"
private const val COMMAND_PREFIX = "DO:"
private val PROMPT = """
You are the voice assistant in a car's dashboard, heard over the car's speakers while the
driver is driving. Keep every answer to one or two short spoken sentences, with no lists,
markdown or emoji.
If the driver wants something the car can do, reply with only one line, "$COMMAND_PREFIX "
followed by the command, in one of these forms:
navigate to <place>
play <song, artist, album or playlist>
pause / resume / next / previous
call <contact name>
open <app name>
go home
what time is it
what's the weather
Otherwise, answer the question yourself.
""".trimIndent()
val enabled: Boolean get() = CarSettings.aiServer.value.on
suspend fun ask(heard: String): Answer = withContext(Dispatchers.IO) {
val server = CarSettings.aiServer.value
val url = OwnServer.endpoint(server.url, "/v1/chat/completions", listOf("/chat/completions"))
val request = JSONObject()
.put("model", server.model.ifBlank { DEFAULT_MODEL })
.put("stream", false)
.put("temperature", 0.2)
.put("max_tokens", 120)
.put(
"messages",
JSONArray()
.put(JSONObject().put("role", "system").put("content", PROMPT))
.put(JSONObject().put("role", "user").put("content", heard)),
)
val reply = OwnServer.post(server, url, "application/json", request.toString().toByteArray())
val text = runCatching {
JSONObject(reply).getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content")
}.getOrElse { throw OwnServer.Failed("Your AI server sent back something Gearslip can't read.") }
parse(text)
}
/** A "DO:" line anywhere in the reply is a command; anything else is said as it is. */
internal fun parse(text: String): Answer {
// Reasoning models put their thinking in <think> tags first.
val clean = text.replace(Regex("(?s)<think>.*?</think>"), "").trim()
clean.lineSequence().map { it.trim() }.firstOrNull { it.startsWith(COMMAND_PREFIX, ignoreCase = true) }?.let {
return Answer.Run(it.substring(COMMAND_PREFIX.length).trim().trimEnd('.'))
}
return Answer.Say(clean.replace(Regex("[*_#`]"), "").ifBlank { "I don't know how to do that yet." })
}
}
@@ -8,7 +8,18 @@ internal object InputProtocol {
data class Touch(val action: Int, val actionIndex: Int, val points: List<TouchPoint>)
/** [shiftX] and [shiftY] move each point by the margin the car crops off before measuring. */
fun touch(body: ByteArray, size: Pair<Int, Int>?, shiftX: Int = 0, shiftY: Int = 0): Touch? {
/**
* The touch's points, each scaled by [scaleX] and [scaleY] (for a car that reports in its touch
* panel's size), shifted, and clamped to [size].
*/
fun touch(
body: ByteArray,
size: Pair<Int, Int>?,
shiftX: Int = 0,
shiftY: Int = 0,
scaleX: Float = 1f,
scaleY: Float = 1f,
): Touch? {
val fields = Wire.fields(body)
val action = Wire.varint(fields, 3)?.toInt() ?: 0
if (action !in setOf(0, 1, 2, 5, 6)) return null
@@ -22,12 +33,30 @@ internal object InputProtocol {
val y = Wire.varint(values, 2)?.toInt() ?: return null
val id = Wire.varint(values, 3) ?: return null
if (id !in 0L..31L) return null
TouchPoint(id.toInt(), clamp(x + shiftX, size?.first), clamp(y + shiftY, size?.second))
TouchPoint(
id.toInt(),
clamp(Math.round(x * scaleX) + shiftX, size?.first),
clamp(Math.round(y * scaleY) + shiftY, size?.second),
)
}
if (points.map { it.id }.toSet().size != points.size) return null
return Touch(action, actionIndex, points)
}
/** The furthest right and down any point of the touch reaches, as the car sent it; null if unreadable. */
fun extent(body: ByteArray): Pair<Int, Int>? {
val pointers = Wire.allBytes(Wire.fields(body), 1)
if (pointers.isEmpty()) return null
var maxX = 0
var maxY = 0
for (pointer in pointers) {
val values = Wire.fields(pointer)
maxX = maxOf(maxX, Wire.varint(values, 1)?.toInt() ?: continue)
maxY = maxOf(maxY, Wire.varint(values, 2)?.toInt() ?: continue)
}
return maxX to maxY
}
private fun clamp(value: Int, limit: Int?): Float = when {
limit == null -> value.toFloat()
limit <= 0 -> 0f
@@ -4,6 +4,9 @@ import android.annotation.SuppressLint
import android.content.AttributionSource
import android.content.Context
import android.content.ContextWrapper
import android.media.AudioFormat
import android.media.AudioRecord
import android.os.ParcelFileDescriptor
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.view.InputEvent
@@ -36,7 +39,10 @@ class ShellService() : IShellService.Stub() {
private val displays = mutableMapOf<Int, VirtualDisplay>()
@Volatile private var record: AudioRecord? = null
override fun destroy() {
stopAudio()
displays.values.forEach { runCatching { it.release() } }
exitProcess(0)
}
@@ -93,6 +99,65 @@ class ShellService() : IShellService.Stub() {
synchronized(displays) { displays.remove(displayId) }?.let { runCatching { it.release() } }
}
/**
* The phone's whole output, through the "remote submix" source that only the shell and the
* system may record, the way scrcpy captures sound. Android stops playing it on the phone
* while it's recorded, as it does for Android Auto. Unlike playback capture, no app can opt
* out of it, so music from Spotify reaches the car too.
*/
@SuppressLint("MissingPermission", "WrongConstant")
override fun startAudio(sampleRate: Int, channels: Int): ParcelFileDescriptor? {
stopAudio()
val base = context ?: return null
return runCatching {
val mask = if (channels == 1) AudioFormat.CHANNEL_IN_MONO else AudioFormat.CHANNEL_IN_STEREO
val format = AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setSampleRate(sampleRate)
.setChannelMask(mask)
.build()
val chunk = sampleRate / 50 * channels * 2
val minimum = AudioRecord.getMinBufferSize(sampleRate, mask, AudioFormat.ENCODING_PCM_16BIT)
val r = AudioRecord.Builder()
// Recorded as the shell, whose uid holds the right to record the phone's output.
.setContext(ShellContext(base))
.setAudioSource(REMOTE_SUBMIX)
.setAudioFormat(format)
.setBufferSizeInBytes(maxOf(minimum, chunk * 8))
.build()
check(r.state == AudioRecord.STATE_INITIALIZED) { "AudioRecord didn't initialize" }
r.startRecording()
record = r
val (read, write) = ParcelFileDescriptor.createPipe()
Thread({
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO)
val buffer = ByteArray(chunk)
ParcelFileDescriptor.AutoCloseOutputStream(write).use { out ->
runCatching {
while (record === r) {
val n = r.read(buffer, 0, buffer.size)
if (n < 0) break
if (n > 0) out.write(buffer, 0, n)
}
}
}
if (record === r) stopAudio()
}, "gearslip-shell-audio").apply { isDaemon = true; start() }
read
}.getOrElse {
System.err.println("gearslip shell: startAudio failed: $it")
stopAudio()
null
}
}
override fun stopAudio() {
val r = record ?: return
record = null
runCatching { r.stop() }
r.release()
}
private fun inject(event: InputEvent, displayId: Int) {
runCatching {
InputEvent::class.java.getMethod("setDisplayId", Int::class.javaPrimitiveType).invoke(event, displayId)
@@ -130,6 +195,9 @@ class ShellService() : IShellService.Stub() {
const val SHELL_UID = 2000
const val INJECT_ASYNC = 0
/** MediaRecorder.AudioSource.REMOTE_SUBMIX, a system-only source. */
const val REMOTE_SUBMIX = 8
// DisplayManager's flags, several of them hidden: public, own content only, supports
// touch, rotates with content, destroys its apps when released, trusted, its own display
// group, always unlocked, and no touch feedback.
@@ -0,0 +1,58 @@
package app.seb3thehacker.gearslip.speech
import app.seb3thehacker.gearslip.OwnServer
import app.seb3thehacker.gearslip.car.CarSettings
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
import org.json.JSONObject
/**
* Speech-to-text on the driver's own server: the phrase goes out as a WAV file to OpenAI's
* transcription call, which whisper.cpp's server, faster-whisper-server, Speaches and LocalAI all
* answer, and the words come back. The recording is held in memory only for the request.
*/
internal object ServerSpeech {
typealias Failed = OwnServer.Failed
const val UNREACHABLE = OwnServer.UNREACHABLE
/** The model name most of these servers accept when the driver leaves it blank. */
private const val DEFAULT_MODEL = "whisper-1"
fun transcribe(server: CarSettings.Server, wav: ByteArray): String {
val url = OwnServer.endpoint(server.url, "/v1/audio/transcriptions", listOf("/transcriptions", "/inference"))
val boundary = "gearslip" + System.nanoTime()
val body = ByteArrayOutputStream().apply {
fun field(name: String, value: String) {
write("--$boundary\r\nContent-Disposition: form-data; name=\"$name\"\r\n\r\n$value\r\n".toByteArray())
}
field("model", server.model.ifBlank { DEFAULT_MODEL })
field("response_format", "json")
// Commands are matched in English, so a guessed language would only lose words.
field("language", "en")
write(
("--$boundary\r\nContent-Disposition: form-data; name=\"file\"; filename=\"phrase.wav\"\r\n" +
"Content-Type: audio/wav\r\n\r\n").toByteArray(),
)
write(wav)
write("\r\n--$boundary--\r\n".toByteArray())
}.toByteArray()
val reply = OwnServer.post(server, url, "multipart/form-data; boundary=$boundary", body)
return runCatching { JSONObject(reply).optString("text") }
.getOrElse { reply.takeIf { !it.trimStart().startsWith("{") } ?: "" }
.trim()
}
/** 16-bit mono little-endian [pcm] with a WAV header. */
fun wav(pcm: ByteArray, rate: Int): ByteArray {
val header = ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply {
put("RIFF".toByteArray()); putInt(36 + pcm.size); put("WAVE".toByteArray())
put("fmt ".toByteArray()); putInt(16); putShort(1); putShort(1)
putInt(rate); putInt(rate * 2); putShort(2); putShort(16)
put("data".toByteArray()); putInt(pcm.size)
}.array()
return header + pcm
}
}
@@ -14,6 +14,7 @@ import android.os.Looper
import android.os.SystemClock
import app.seb3thehacker.gearslip.GearslipLog
import app.seb3thehacker.gearslip.audio.CarMic
import app.seb3thehacker.gearslip.car.CarSettings
import com.k2fsa.sherpa.onnx.EndpointConfig
import com.k2fsa.sherpa.onnx.EndpointRule
import com.k2fsa.sherpa.onnx.FeatureConfig
@@ -86,14 +87,17 @@ object SpeechEngine {
private val idleUnload = Runnable { unloadFinal("after ${IDLE_UNLOAD_MS / 60_000} minutes without use") }
@Volatile private var run = 0
/** Loads the model ahead of time, so the first command doesn't wait for it. */
fun warm(context: Context) {
/**
* Loads the live model ahead of time, so the first command doesn't wait for it, and the final
* one too when [final] is set.
*/
fun warm(context: Context, final: Boolean = true) {
val app = context.applicationContext
SpeechModels.init(app)
// Kroko first, alone: loading both at once slowed it from a fraction of a second to six.
worker.execute {
ensureLoaded(app)
finalWorker.execute { ensureFinalLoaded(app) }
if (final) finalWorker.execute { ensureFinalLoaded(app) }
}
}
@@ -150,6 +154,31 @@ object SpeechEngine {
}
val id = ++run
fun post(block: () -> Unit) { main.post { if (id == run) block() } }
val server = CarSettings.speechServer.value
if (server.on) {
worker.execute {
if (id != run) return@execute
VoiceFocus.acquire(app)
try {
if (cue) cue()
if (id != run) return@execute
post(onListening)
val wav = record(id, onSpeaking = { post(onSpeaking) }) ?: return@execute post { onError("Didn't catch that.") }
if (id != run) return@execute
post(onHeard)
val text = ServerSpeech.transcribe(server, wav).let(::clean)
post { if (text.isEmpty()) onError("Didn't catch that.") else onResult(text) }
} catch (e: ServerSpeech.Failed) {
post { onError(e.message ?: ServerSpeech.UNREACHABLE) }
} catch (t: Throwable) {
GearslipLog.e("speech: listening failed", t)
post { onError("The microphone isn't available right now.") }
} finally {
VoiceFocus.release()
}
}
return
}
// Brings Parakeet back if it was unloaded, while the driver talks.
main.removeCallbacks(idleUnload)
finalWorker.execute { ensureFinalLoaded(app) }
@@ -271,6 +300,58 @@ object SpeechEngine {
return reread
}
/**
* One phrase for the driver's own server, as 16 kHz mono WAV. With no model on the phone to
* say when the driver has finished, loudness does: speech is anything well above the first
* moments' background noise, and a second under it ends the phrase. Null when nobody spoke.
*/
private fun record(id: Int, onSpeaking: () -> Unit): ByteArray? {
val mic = carMic() ?: phoneMic()
val frame = ShortArray(CHUNK)
val pcm = java.io.ByteArrayOutputStream()
var floor = -1.0
var spoke = false
var quietMs = 0L
var heardMs = 0L
try {
while (id == run) {
val n = mic.read(frame)
if (n < 0) break
if (n == 0) continue
var sum = 0.0
for (i in 0 until n) {
sum += frame[i].toDouble() * frame[i]
pcm.write(frame[i].toInt() and 0xFF)
pcm.write(frame[i].toInt() shr 8 and 0xFF)
}
val rms = Math.sqrt(sum / n)
val ms = n * 1000L / RATE
heardMs += ms
// The quietest moment so far is the car's own hum.
floor = if (floor < 0) rms else minOf(floor, rms)
val loud = rms > maxOf(floor * SPEECH_OVER_NOISE, MIN_SPEECH_RMS)
if (loud) {
quietMs = 0
if (!spoke) { spoke = true; onSpeaking() }
} else {
quietMs += ms
}
if (spoke && quietMs >= (END_SILENCE_S * 1000).toLong()) break
if (!spoke && heardMs >= (NO_SPEECH_S * 1000).toLong()) break
if (heardMs >= (MAX_S * 1000).toLong()) break
}
} finally {
mic.close()
}
if (!spoke || id != run) return null
return ServerSpeech.wav(pcm.toByteArray(), RATE)
}
/** Loudness, as RMS of 16-bit samples, that counts as speech: this many times the background... */
private const val SPEECH_OVER_NOISE = 2.5
/** ...and never less than this, so a silent car doesn't make every breath a word. */
private const val MIN_SPEECH_RMS = 400.0
/** The model that rereads the phrase, when one is chosen and downloaded; null otherwise. */
private fun ensureFinalLoaded(context: Context): OfflineRecognizer? = synchronized(finalLock) {
val model = SpeechModels.final.value ?: return null
@@ -61,6 +61,8 @@ import app.seb3thehacker.gearslip.car.LauncherCache
import app.seb3thehacker.gearslip.car.NavBarMode
import app.seb3thehacker.gearslip.car.NightMode
import app.seb3thehacker.gearslip.car.Units
import app.seb3thehacker.gearslip.car.TouchScale
import app.seb3thehacker.gearslip.car.VideoQuality
import app.seb3thehacker.gearslip.car.theme.GsThemes
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@@ -117,6 +119,88 @@ private fun CustomDensityDialog(current: Int, onDismiss: () -> Unit, onSave: (In
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
)
}
@Composable
private fun videoQualityChoices() = listOf(
VideoQuality.LIGHT to stringResource(R.string.choice_video_light),
VideoQuality.STANDARD to stringResource(R.string.choice_video_standard),
VideoQuality.HIGH to stringResource(R.string.choice_video_high),
)
@Composable
private fun touchChoices() = listOf(
TouchScale.AUTO to stringResource(R.string.choice_touch_auto),
TouchScale.AS_SENT to stringResource(R.string.choice_touch_as_sent),
TouchScale.SCALED to stringResource(R.string.choice_touch_scaled),
)
/** A server the driver runs: its address, or Off, with a dialog to change it. */
@Composable
private fun ServerRow(
title: String,
note: String,
hint: String,
example: String,
server: CarSettings.Server,
onSave: (CarSettings.Server) -> Unit,
) {
var editing by remember { mutableStateOf(false) }
SettingsRow(
title,
Modifier.clickable { editing = true },
subtitle = note,
trailing = {
Text(
if (server.on) server.url.removePrefix("http://").removePrefix("https://") else stringResource(R.string.server_off),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.primary,
maxLines = 1,
)
},
)
if (!editing) return
var url by remember { mutableStateOf(server.url) }
var model by remember { mutableStateOf(server.model) }
var key by remember { mutableStateOf(server.key) }
AlertDialog(
onDismissRequest = { editing = false },
title = { Text(title) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(hint, style = MaterialTheme.typography.bodyMedium)
OutlinedTextField(
url, { url = it.trim() },
label = { Text(stringResource(R.string.server_address)) },
placeholder = { Text(example) },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
)
OutlinedTextField(model, { model = it }, label = { Text(stringResource(R.string.server_model)) }, singleLine = true)
OutlinedTextField(
key, { key = it.trim() },
label = { Text(stringResource(R.string.server_key)) },
singleLine = true,
visualTransformation = androidx.compose.ui.text.input.PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
)
}
},
confirmButton = {
TextButton({
onSave(CarSettings.Server(url, model, key))
editing = false
}) { Text(stringResource(R.string.save)) }
},
dismissButton = {
Row {
if (server.on) TextButton({
onSave(CarSettings.Server("", "", ""))
editing = false
}) { Text(stringResource(R.string.server_clear)) }
TextButton({ editing = false }) { Text(stringResource(R.string.cancel)) }
}
},
)
}
@Composable
private fun themeChoices() = listOf(AppTheme.PHONE to stringResource(R.string.choice_theme_phone), AppTheme.LIGHT to stringResource(R.string.choice_theme_light), AppTheme.DARK to stringResource(R.string.choice_theme_dark))
@Composable
@@ -291,6 +375,13 @@ private fun GroupRows(group: CarGroup) {
val carSensors by CarSettings.carSensorsEnabled.collectAsState()
val adaptiveVideo by CarSettings.adaptiveVideoEnabled.collectAsState()
val clusterVideo by CarSettings.clusterVideoEnabled.collectAsState()
val videoQuality by CarSettings.videoQuality.collectAsState()
val touchScale by CarSettings.touchScale.collectAsState()
val speechServer by CarSettings.speechServer.collectAsState()
val aiServer by CarSettings.aiServer.collectAsState()
val appCommands by CarSettings.appCommands.collectAsState()
val shizukuAudio by CarSettings.shizukuAudio.collectAsState()
val shizuku by app.seb3thehacker.gearslip.shizuku.ShizukuSetup.state.collectAsState()
when (group) {
CarGroup.APPS -> AppRows()
@@ -324,6 +415,10 @@ private fun GroupRows(group: CarGroup) {
SettingsDivider()
Choice(stringResource(R.string.car_units), unitChoices(), units, CarSettings::setUnits)
SettingsDivider()
Choice(stringResource(R.string.car_video_quality), videoQualityChoices(), videoQuality, CarSettings::setVideoQuality, note = stringResource(R.string.car_video_quality_note))
SettingsDivider()
Choice(stringResource(R.string.car_touch_scale), touchChoices(), touchScale, CarSettings::setTouchScale, note = stringResource(R.string.car_touch_scale_note))
SettingsDivider()
WallpaperRows()
}
CarGroup.NAV_BAR -> {
@@ -360,6 +455,16 @@ private fun GroupRows(group: CarGroup) {
CarSettings::setSystemSpeech,
note = stringResource(R.string.car_phone_speech_note),
)
SettingsDivider()
ServerRow(stringResource(R.string.car_speech_server), stringResource(R.string.car_speech_server_note), stringResource(R.string.speech_server_hint), "http://192.168.1.20:8080", speechServer, CarSettings::setSpeechServer)
SettingsDivider()
ServerRow(stringResource(R.string.car_ai_server), stringResource(R.string.car_ai_server_note), stringResource(R.string.ai_server_hint), "http://192.168.1.20:11434", aiServer, CarSettings::setAiServer)
SettingsDivider()
Toggle(stringResource(R.string.car_app_commands), appCommands, CarSettings::setAppCommands, note = stringResource(R.string.car_app_commands_note))
if (shizuku != app.seb3thehacker.gearslip.shizuku.ShizukuSetup.State.MISSING) {
SettingsDivider()
Toggle(stringResource(R.string.car_shizuku_audio), shizukuAudio, CarSettings::setShizukuAudio, note = stringResource(R.string.car_shizuku_audio_note))
}
}
CarGroup.PLACES -> Unit
CarGroup.WARNINGS -> {
+28
View File
@@ -225,6 +225,34 @@
<string name="car_spoken_directions_note">Turn it off if your map app\'s own voice already plays in the car.</string>
<string name="car_phone_speech">Use the phone\'s speech recognition</string>
<string name="car_phone_speech_note">On most phones that\'s Google\'s, which may send your voice to Google.</string>
<string name="car_video_quality">Video quality</string>
<string name="car_video_quality_note">Light is easier on a phone that runs hot or closes apps. Applies on the next connection.</string>
<string name="choice_video_light">Light (720p)</string>
<string name="choice_video_standard">Standard (up to 1080p)</string>
<string name="choice_video_high">High (largest, 60 fps)</string>
<string name="car_touch_scale">Touch</string>
<string name="car_touch_scale_note">Change this if taps land in the wrong place, or only reach part of the screen.</string>
<string name="choice_touch_auto">Automatic</string>
<string name="choice_touch_as_sent">As the car sends them</string>
<string name="choice_touch_scaled">Scaled to the screen</string>
<string name="car_shizuku_audio">Record music through Shizuku</string>
<string name="car_shizuku_audio_note">Sends everything the phone plays, with no screen sharing prompt, Spotify included. Your map app\'s own voice comes through too, so you may want Spoken directions off.</string>
<string name="car_speech_server">Your own speech server</string>
<string name="car_speech_server_note">Hears your voice on a server you run, such as whisper.cpp or faster-whisper, so the phone loads no speech model.</string>
<string name="car_ai_server">Your own AI server</string>
<string name="car_ai_server_note">Answers questions and works out commands Gearslip doesn\'t know, on a server you run, such as Ollama.</string>
<string name="server_off">Off</string>
<string name="server_address">Address</string>
<string name="server_model">Model (optional)</string>
<string name="server_key">API key (optional)</string>
<string name="server_clear">Turn off</string>
<string name="speech_server_hint">Gearslip sends each phrase as a WAV file to the address\'s /v1/audio/transcriptions, the call most speech servers answer.</string>
<string name="ai_server_hint">Gearslip sends only what you said, to the address\'s /v1/chat/completions. Ollama answers it on port 11434.</string>
<string name="car_app_commands">Commands from other apps</string>
<string name="car_app_commands_note">Lets another assistant or Tasker tell Gearslip what to do, with a gearslip://command?text= link or a broadcast. Never phone calls.</string>
<string name="app_commands_off">Turn on Commands from other apps in Gearslip\'s settings first.</string>
<string name="app_commands_no_car">Gearslip isn\'t connected to a car.</string>
<string name="app_commands_empty">That command was empty.</string>
<string name="car_warn_bluetooth">Warn when Bluetooth isn\'t connected</string>
<string name="car_warn_location">Warn when location is off</string>
<string name="car_experimental">Experimental features</string>
@@ -0,0 +1,39 @@
package app.seb3thehacker.gearslip
import app.seb3thehacker.gearslip.car.ServerAssistant
import org.junit.Assert.assertEquals
import org.junit.Test
class OwnServerTest {
private val speech = listOf("/transcriptions", "/inference")
@Test fun `a bare address gets the call's path and http`() {
assertEquals(
"http://192.168.1.20:8080/v1/audio/transcriptions",
OwnServer.endpoint("192.168.1.20:8080/", "/v1/audio/transcriptions", speech).toString(),
)
}
@Test fun `an address ending in v1 doesn't get a second one`() {
assertEquals(
"https://ai.example.org/v1/chat/completions",
OwnServer.endpoint("https://ai.example.org/v1", "/v1/chat/completions", listOf("/chat/completions")).toString(),
)
}
@Test fun `a full path the driver typed is kept`() {
assertEquals(
"http://pc:8080/inference",
OwnServer.endpoint("http://pc:8080/inference", "/v1/audio/transcriptions", speech).toString(),
)
}
@Test fun `a DO line is a command and anything else is said`() {
assertEquals(ServerAssistant.Answer.Run("navigate to the beach"), ServerAssistant.parse("DO: navigate to the beach."))
assertEquals(
ServerAssistant.Answer.Run("play jazz"),
ServerAssistant.parse("<think>they want music</think>\nSure.\ndo: play jazz"),
)
assertEquals(ServerAssistant.Answer.Say("Paris is the capital."), ServerAssistant.parse("**Paris** is the capital."))
}
}
@@ -49,4 +49,18 @@ class InputProtocolTest {
assertEquals(49f, touch.points.single().x)
assertEquals(59f, touch.points.single().y)
}
@Test fun `a tap in touch panel size is scaled onto the picture before the margin shift`() {
// 1920x1080 panel over a 1280x720 picture: the panel's 100,200 is the picture's 67,133.
val touch = requireNotNull(InputProtocol.touch(pointer(0), 1280 to 720, shiftX = 10, scaleX = 2f / 3, scaleY = 2f / 3))
assertEquals(77f, touch.points.single().x)
assertEquals(133f, touch.points.single().y)
}
@Test fun `extent is the furthest point the car sent, before any clamping`() {
val far = Protobuf.bytesField(1,
Protobuf.varintField(1, 1900) + Protobuf.varintField(2, 50) + Protobuf.varintField(3, 1))
assertEquals(1900 to 200, InputProtocol.extent(pointer(0) + far))
assertNull(InputProtocol.extent(Protobuf.varintField(3, 0)))
}
}